]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/ssh-keygen.c
ssh: Update to OpenSSH 9.3p1
[FreeBSD/FreeBSD.git] / crypto / openssh / ssh-keygen.c
1 /* $OpenBSD: ssh-keygen.c,v 1.466 2023/03/08 00:05:37 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Identity and host key generation and maintenance.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14
15 #include "includes.h"
16
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20
21 #ifdef WITH_OPENSSL
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
25 #endif
26
27 #ifdef HAVE_STDINT_H
28 # include <stdint.h>
29 #endif
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <netdb.h>
33 #ifdef HAVE_PATHS_H
34 # include <paths.h>
35 #endif
36 #include <pwd.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <limits.h>
43 #include <locale.h>
44 #include <time.h>
45
46 #include "xmalloc.h"
47 #include "sshkey.h"
48 #include "authfile.h"
49 #include "sshbuf.h"
50 #include "pathnames.h"
51 #include "log.h"
52 #include "misc.h"
53 #include "match.h"
54 #include "hostfile.h"
55 #include "dns.h"
56 #include "ssh.h"
57 #include "ssh2.h"
58 #include "ssherr.h"
59 #include "ssh-pkcs11.h"
60 #include "atomicio.h"
61 #include "krl.h"
62 #include "digest.h"
63 #include "utf8.h"
64 #include "authfd.h"
65 #include "sshsig.h"
66 #include "ssh-sk.h"
67 #include "sk-api.h" /* XXX for SSH_SK_USER_PRESENCE_REQD; remove */
68 #include "cipher.h"
69
70 #ifdef WITH_OPENSSL
71 # define DEFAULT_KEY_TYPE_NAME "rsa"
72 #else
73 # define DEFAULT_KEY_TYPE_NAME "ed25519"
74 #endif
75
76 /*
77  * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
78  * overridden on the command line.
79  *
80  * These values, with the exception of DSA, provide security equivalent to at
81  * least 128 bits of security according to NIST Special Publication 800-57:
82  * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
83  * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
84  * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
85  * SHA1 we limit the DSA key size 1k bits.
86  */
87 #define DEFAULT_BITS            3072
88 #define DEFAULT_BITS_DSA        1024
89 #define DEFAULT_BITS_ECDSA      256
90
91 static int quiet = 0;
92
93 /* Flag indicating that we just want to see the key fingerprint */
94 static int print_fingerprint = 0;
95 static int print_bubblebabble = 0;
96
97 /* Hash algorithm to use for fingerprints. */
98 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
99
100 /* The identity file name, given on the command line or entered by the user. */
101 static char identity_file[PATH_MAX];
102 static int have_identity = 0;
103
104 /* This is set to the passphrase if given on the command line. */
105 static char *identity_passphrase = NULL;
106
107 /* This is set to the new passphrase if given on the command line. */
108 static char *identity_new_passphrase = NULL;
109
110 /* Key type when certifying */
111 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
112
113 /* "key ID" of signed key */
114 static char *cert_key_id = NULL;
115
116 /* Comma-separated list of principal names for certifying keys */
117 static char *cert_principals = NULL;
118
119 /* Validity period for certificates */
120 static u_int64_t cert_valid_from = 0;
121 static u_int64_t cert_valid_to = ~0ULL;
122
123 /* Certificate options */
124 #define CERTOPT_X_FWD                           (1)
125 #define CERTOPT_AGENT_FWD                       (1<<1)
126 #define CERTOPT_PORT_FWD                        (1<<2)
127 #define CERTOPT_PTY                             (1<<3)
128 #define CERTOPT_USER_RC                         (1<<4)
129 #define CERTOPT_NO_REQUIRE_USER_PRESENCE        (1<<5)
130 #define CERTOPT_REQUIRE_VERIFY                  (1<<6)
131 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
132                          CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
133 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
134 static char *certflags_command = NULL;
135 static char *certflags_src_addr = NULL;
136
137 /* Arbitrary extensions specified by user */
138 struct cert_ext {
139         char *key;
140         char *val;
141         int crit;
142 };
143 static struct cert_ext *cert_ext;
144 static size_t ncert_ext;
145
146 /* Conversion to/from various formats */
147 enum {
148         FMT_RFC4716,
149         FMT_PKCS8,
150         FMT_PEM
151 } convert_format = FMT_RFC4716;
152
153 static char *key_type_name = NULL;
154
155 /* Load key from this PKCS#11 provider */
156 static char *pkcs11provider = NULL;
157
158 /* FIDO/U2F provider to use */
159 static char *sk_provider = NULL;
160
161 /* Format for writing private keys */
162 static int private_key_format = SSHKEY_PRIVATE_OPENSSH;
163
164 /* Cipher for new-format private keys */
165 static char *openssh_format_cipher = NULL;
166
167 /* Number of KDF rounds to derive new format keys. */
168 static int rounds = 0;
169
170 /* argv0 */
171 extern char *__progname;
172
173 static char hostname[NI_MAXHOST];
174
175 #ifdef WITH_OPENSSL
176 /* moduli.c */
177 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
178 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
179     unsigned long);
180 #endif
181
182 static void
183 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
184 {
185         if (type == KEY_UNSPEC)
186                 fatal("unknown key type %s", key_type_name);
187         if (*bitsp == 0) {
188 #ifdef WITH_OPENSSL
189                 int nid;
190
191                 switch(type) {
192                 case KEY_DSA:
193                         *bitsp = DEFAULT_BITS_DSA;
194                         break;
195                 case KEY_ECDSA:
196                         if (name != NULL &&
197                             (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
198                                 *bitsp = sshkey_curve_nid_to_bits(nid);
199                         if (*bitsp == 0)
200                                 *bitsp = DEFAULT_BITS_ECDSA;
201                         break;
202                 case KEY_RSA:
203                         *bitsp = DEFAULT_BITS;
204                         break;
205                 }
206 #endif
207         }
208 #ifdef WITH_OPENSSL
209         switch (type) {
210         case KEY_DSA:
211                 if (*bitsp != 1024)
212                         fatal("Invalid DSA key length: must be 1024 bits");
213                 break;
214         case KEY_RSA:
215                 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
216                         fatal("Invalid RSA key length: minimum is %d bits",
217                             SSH_RSA_MINIMUM_MODULUS_SIZE);
218                 else if (*bitsp > OPENSSL_RSA_MAX_MODULUS_BITS)
219                         fatal("Invalid RSA key length: maximum is %d bits",
220                             OPENSSL_RSA_MAX_MODULUS_BITS);
221                 break;
222         case KEY_ECDSA:
223                 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
224 #ifdef OPENSSL_HAS_NISTP521
225                         fatal("Invalid ECDSA key length: valid lengths are "
226                             "256, 384 or 521 bits");
227 #else
228                         fatal("Invalid ECDSA key length: valid lengths are "
229                             "256 or 384 bits");
230 #endif
231         }
232 #endif
233 }
234
235 /*
236  * Checks whether a file exists and, if so, asks the user whether they wish
237  * to overwrite it.
238  * Returns nonzero if the file does not already exist or if the user agrees to
239  * overwrite, or zero otherwise.
240  */
241 static int
242 confirm_overwrite(const char *filename)
243 {
244         char yesno[3];
245         struct stat st;
246
247         if (stat(filename, &st) != 0)
248                 return 1;
249         printf("%s already exists.\n", filename);
250         printf("Overwrite (y/n)? ");
251         fflush(stdout);
252         if (fgets(yesno, sizeof(yesno), stdin) == NULL)
253                 return 0;
254         if (yesno[0] != 'y' && yesno[0] != 'Y')
255                 return 0;
256         return 1;
257 }
258
259 static void
260 ask_filename(struct passwd *pw, const char *prompt)
261 {
262         char buf[1024];
263         char *name = NULL;
264
265         if (key_type_name == NULL)
266                 name = _PATH_SSH_CLIENT_ID_RSA;
267         else {
268                 switch (sshkey_type_from_name(key_type_name)) {
269                 case KEY_DSA_CERT:
270                 case KEY_DSA:
271                         name = _PATH_SSH_CLIENT_ID_DSA;
272                         break;
273 #ifdef OPENSSL_HAS_ECC
274                 case KEY_ECDSA_CERT:
275                 case KEY_ECDSA:
276                         name = _PATH_SSH_CLIENT_ID_ECDSA;
277                         break;
278                 case KEY_ECDSA_SK_CERT:
279                 case KEY_ECDSA_SK:
280                         name = _PATH_SSH_CLIENT_ID_ECDSA_SK;
281                         break;
282 #endif
283                 case KEY_RSA_CERT:
284                 case KEY_RSA:
285                         name = _PATH_SSH_CLIENT_ID_RSA;
286                         break;
287                 case KEY_ED25519:
288                 case KEY_ED25519_CERT:
289                         name = _PATH_SSH_CLIENT_ID_ED25519;
290                         break;
291                 case KEY_ED25519_SK:
292                 case KEY_ED25519_SK_CERT:
293                         name = _PATH_SSH_CLIENT_ID_ED25519_SK;
294                         break;
295                 case KEY_XMSS:
296                 case KEY_XMSS_CERT:
297                         name = _PATH_SSH_CLIENT_ID_XMSS;
298                         break;
299                 default:
300                         fatal("bad key type");
301                 }
302         }
303         snprintf(identity_file, sizeof(identity_file),
304             "%s/%s", pw->pw_dir, name);
305         printf("%s (%s): ", prompt, identity_file);
306         fflush(stdout);
307         if (fgets(buf, sizeof(buf), stdin) == NULL)
308                 exit(1);
309         buf[strcspn(buf, "\n")] = '\0';
310         if (strcmp(buf, "") != 0)
311                 strlcpy(identity_file, buf, sizeof(identity_file));
312         have_identity = 1;
313 }
314
315 static struct sshkey *
316 load_identity(const char *filename, char **commentp)
317 {
318         char *pass;
319         struct sshkey *prv;
320         int r;
321
322         if (commentp != NULL)
323                 *commentp = NULL;
324         if ((r = sshkey_load_private(filename, "", &prv, commentp)) == 0)
325                 return prv;
326         if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
327                 fatal_r(r, "Load key \"%s\"", filename);
328         if (identity_passphrase)
329                 pass = xstrdup(identity_passphrase);
330         else
331                 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
332         r = sshkey_load_private(filename, pass, &prv, commentp);
333         freezero(pass, strlen(pass));
334         if (r != 0)
335                 fatal_r(r, "Load key \"%s\"", filename);
336         return prv;
337 }
338
339 #define SSH_COM_PUBLIC_BEGIN            "---- BEGIN SSH2 PUBLIC KEY ----"
340 #define SSH_COM_PUBLIC_END              "---- END SSH2 PUBLIC KEY ----"
341 #define SSH_COM_PRIVATE_BEGIN           "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
342 #define SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
343
344 #ifdef WITH_OPENSSL
345 static void
346 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
347 {
348         struct sshbuf *b;
349         char comment[61], *b64;
350         int r;
351
352         if ((b = sshbuf_new()) == NULL)
353                 fatal_f("sshbuf_new failed");
354         if ((r = sshkey_putb(k, b)) != 0)
355                 fatal_fr(r, "put key");
356         if ((b64 = sshbuf_dtob64_string(b, 1)) == NULL)
357                 fatal_f("sshbuf_dtob64_string failed");
358
359         /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
360         snprintf(comment, sizeof(comment),
361             "%u-bit %s, converted by %s@%s from OpenSSH",
362             sshkey_size(k), sshkey_type(k),
363             pw->pw_name, hostname);
364
365         sshkey_free(k);
366         sshbuf_free(b);
367
368         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
369         fprintf(stdout, "Comment: \"%s\"\n%s", comment, b64);
370         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
371         free(b64);
372         exit(0);
373 }
374
375 static void
376 do_convert_to_pkcs8(struct sshkey *k)
377 {
378         switch (sshkey_type_plain(k->type)) {
379         case KEY_RSA:
380                 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
381                         fatal("PEM_write_RSA_PUBKEY failed");
382                 break;
383         case KEY_DSA:
384                 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
385                         fatal("PEM_write_DSA_PUBKEY failed");
386                 break;
387 #ifdef OPENSSL_HAS_ECC
388         case KEY_ECDSA:
389                 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
390                         fatal("PEM_write_EC_PUBKEY failed");
391                 break;
392 #endif
393         default:
394                 fatal_f("unsupported key type %s", sshkey_type(k));
395         }
396         exit(0);
397 }
398
399 static void
400 do_convert_to_pem(struct sshkey *k)
401 {
402         switch (sshkey_type_plain(k->type)) {
403         case KEY_RSA:
404                 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
405                         fatal("PEM_write_RSAPublicKey failed");
406                 break;
407         case KEY_DSA:
408                 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
409                         fatal("PEM_write_DSA_PUBKEY failed");
410                 break;
411 #ifdef OPENSSL_HAS_ECC
412         case KEY_ECDSA:
413                 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
414                         fatal("PEM_write_EC_PUBKEY failed");
415                 break;
416 #endif
417         default:
418                 fatal_f("unsupported key type %s", sshkey_type(k));
419         }
420         exit(0);
421 }
422
423 static void
424 do_convert_to(struct passwd *pw)
425 {
426         struct sshkey *k;
427         struct stat st;
428         int r;
429
430         if (!have_identity)
431                 ask_filename(pw, "Enter file in which the key is");
432         if (stat(identity_file, &st) == -1)
433                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
434         if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
435                 k = load_identity(identity_file, NULL);
436         switch (convert_format) {
437         case FMT_RFC4716:
438                 do_convert_to_ssh2(pw, k);
439                 break;
440         case FMT_PKCS8:
441                 do_convert_to_pkcs8(k);
442                 break;
443         case FMT_PEM:
444                 do_convert_to_pem(k);
445                 break;
446         default:
447                 fatal_f("unknown key format %d", convert_format);
448         }
449         exit(0);
450 }
451
452 /*
453  * This is almost exactly the bignum1 encoding, but with 32 bit for length
454  * instead of 16.
455  */
456 static void
457 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
458 {
459         u_int bytes, bignum_bits;
460         int r;
461
462         if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
463                 fatal_fr(r, "parse");
464         bytes = (bignum_bits + 7) / 8;
465         if (sshbuf_len(b) < bytes)
466                 fatal_f("input buffer too small: need %d have %zu",
467                     bytes, sshbuf_len(b));
468         if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
469                 fatal_f("BN_bin2bn failed");
470         if ((r = sshbuf_consume(b, bytes)) != 0)
471                 fatal_fr(r, "consume");
472 }
473
474 static struct sshkey *
475 do_convert_private_ssh2(struct sshbuf *b)
476 {
477         struct sshkey *key = NULL;
478         char *type, *cipher;
479         const char *alg = NULL;
480         u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
481         int r, rlen, ktype;
482         u_int magic, i1, i2, i3, i4;
483         size_t slen;
484         u_long e;
485         BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
486         BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
487         BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
488         BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
489
490         if ((r = sshbuf_get_u32(b, &magic)) != 0)
491                 fatal_fr(r, "parse magic");
492
493         if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
494                 error("bad magic 0x%x != 0x%x", magic,
495                     SSH_COM_PRIVATE_KEY_MAGIC);
496                 return NULL;
497         }
498         if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
499             (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
500             (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
501             (r = sshbuf_get_u32(b, &i2)) != 0 ||
502             (r = sshbuf_get_u32(b, &i3)) != 0 ||
503             (r = sshbuf_get_u32(b, &i4)) != 0)
504                 fatal_fr(r, "parse");
505         debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
506         if (strcmp(cipher, "none") != 0) {
507                 error("unsupported cipher %s", cipher);
508                 free(cipher);
509                 free(type);
510                 return NULL;
511         }
512         free(cipher);
513
514         if (strstr(type, "dsa")) {
515                 ktype = KEY_DSA;
516         } else if (strstr(type, "rsa")) {
517                 ktype = KEY_RSA;
518         } else {
519                 free(type);
520                 return NULL;
521         }
522         if ((key = sshkey_new(ktype)) == NULL)
523                 fatal("sshkey_new failed");
524         free(type);
525
526         switch (key->type) {
527         case KEY_DSA:
528                 if ((dsa_p = BN_new()) == NULL ||
529                     (dsa_q = BN_new()) == NULL ||
530                     (dsa_g = BN_new()) == NULL ||
531                     (dsa_pub_key = BN_new()) == NULL ||
532                     (dsa_priv_key = BN_new()) == NULL)
533                         fatal_f("BN_new");
534                 buffer_get_bignum_bits(b, dsa_p);
535                 buffer_get_bignum_bits(b, dsa_g);
536                 buffer_get_bignum_bits(b, dsa_q);
537                 buffer_get_bignum_bits(b, dsa_pub_key);
538                 buffer_get_bignum_bits(b, dsa_priv_key);
539                 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
540                         fatal_f("DSA_set0_pqg failed");
541                 dsa_p = dsa_q = dsa_g = NULL; /* transferred */
542                 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
543                         fatal_f("DSA_set0_key failed");
544                 dsa_pub_key = dsa_priv_key = NULL; /* transferred */
545                 break;
546         case KEY_RSA:
547                 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
548                     (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
549                     (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
550                         fatal_fr(r, "parse RSA");
551                 e = e1;
552                 debug("e %lx", e);
553                 if (e < 30) {
554                         e <<= 8;
555                         e += e2;
556                         debug("e %lx", e);
557                         e <<= 8;
558                         e += e3;
559                         debug("e %lx", e);
560                 }
561                 if ((rsa_e = BN_new()) == NULL)
562                         fatal_f("BN_new");
563                 if (!BN_set_word(rsa_e, e)) {
564                         BN_clear_free(rsa_e);
565                         sshkey_free(key);
566                         return NULL;
567                 }
568                 if ((rsa_n = BN_new()) == NULL ||
569                     (rsa_d = BN_new()) == NULL ||
570                     (rsa_p = BN_new()) == NULL ||
571                     (rsa_q = BN_new()) == NULL ||
572                     (rsa_iqmp = BN_new()) == NULL)
573                         fatal_f("BN_new");
574                 buffer_get_bignum_bits(b, rsa_d);
575                 buffer_get_bignum_bits(b, rsa_n);
576                 buffer_get_bignum_bits(b, rsa_iqmp);
577                 buffer_get_bignum_bits(b, rsa_q);
578                 buffer_get_bignum_bits(b, rsa_p);
579                 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
580                         fatal_f("RSA_set0_key failed");
581                 rsa_n = rsa_e = rsa_d = NULL; /* transferred */
582                 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
583                         fatal_f("RSA_set0_factors failed");
584                 rsa_p = rsa_q = NULL; /* transferred */
585                 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
586                         fatal_fr(r, "generate RSA parameters");
587                 BN_clear_free(rsa_iqmp);
588                 alg = "rsa-sha2-256";
589                 break;
590         }
591         rlen = sshbuf_len(b);
592         if (rlen != 0)
593                 error_f("remaining bytes in key blob %d", rlen);
594
595         /* try the key */
596         if ((r = sshkey_sign(key, &sig, &slen, data, sizeof(data),
597             alg, NULL, NULL, 0)) != 0)
598                 error_fr(r, "signing with converted key failed");
599         else if ((r = sshkey_verify(key, sig, slen, data, sizeof(data),
600             alg, 0, NULL)) != 0)
601                 error_fr(r, "verification with converted key failed");
602         if (r != 0) {
603                 sshkey_free(key);
604                 free(sig);
605                 return NULL;
606         }
607         free(sig);
608         return key;
609 }
610
611 static int
612 get_line(FILE *fp, char *line, size_t len)
613 {
614         int c;
615         size_t pos = 0;
616
617         line[0] = '\0';
618         while ((c = fgetc(fp)) != EOF) {
619                 if (pos >= len - 1)
620                         fatal("input line too long.");
621                 switch (c) {
622                 case '\r':
623                         c = fgetc(fp);
624                         if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
625                                 fatal("unget: %s", strerror(errno));
626                         return pos;
627                 case '\n':
628                         return pos;
629                 }
630                 line[pos++] = c;
631                 line[pos] = '\0';
632         }
633         /* We reached EOF */
634         return -1;
635 }
636
637 static void
638 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
639 {
640         int r, blen, escaped = 0;
641         u_int len;
642         char line[1024];
643         struct sshbuf *buf;
644         char encoded[8096];
645         FILE *fp;
646
647         if ((buf = sshbuf_new()) == NULL)
648                 fatal("sshbuf_new failed");
649         if ((fp = fopen(identity_file, "r")) == NULL)
650                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
651         encoded[0] = '\0';
652         while ((blen = get_line(fp, line, sizeof(line))) != -1) {
653                 if (blen > 0 && line[blen - 1] == '\\')
654                         escaped++;
655                 if (strncmp(line, "----", 4) == 0 ||
656                     strstr(line, ": ") != NULL) {
657                         if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
658                                 *private = 1;
659                         if (strstr(line, " END ") != NULL) {
660                                 break;
661                         }
662                         /* fprintf(stderr, "ignore: %s", line); */
663                         continue;
664                 }
665                 if (escaped) {
666                         escaped--;
667                         /* fprintf(stderr, "escaped: %s", line); */
668                         continue;
669                 }
670                 strlcat(encoded, line, sizeof(encoded));
671         }
672         len = strlen(encoded);
673         if (((len % 4) == 3) &&
674             (encoded[len-1] == '=') &&
675             (encoded[len-2] == '=') &&
676             (encoded[len-3] == '='))
677                 encoded[len-3] = '\0';
678         if ((r = sshbuf_b64tod(buf, encoded)) != 0)
679                 fatal_fr(r, "base64 decode");
680         if (*private) {
681                 if ((*k = do_convert_private_ssh2(buf)) == NULL)
682                         fatal_f("private key conversion failed");
683         } else if ((r = sshkey_fromb(buf, k)) != 0)
684                 fatal_fr(r, "parse key");
685         sshbuf_free(buf);
686         fclose(fp);
687 }
688
689 static void
690 do_convert_from_pkcs8(struct sshkey **k, int *private)
691 {
692         EVP_PKEY *pubkey;
693         FILE *fp;
694
695         if ((fp = fopen(identity_file, "r")) == NULL)
696                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
697         if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
698                 fatal_f("%s is not a recognised public key format",
699                     identity_file);
700         }
701         fclose(fp);
702         switch (EVP_PKEY_base_id(pubkey)) {
703         case EVP_PKEY_RSA:
704                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
705                         fatal("sshkey_new failed");
706                 (*k)->type = KEY_RSA;
707                 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
708                 break;
709         case EVP_PKEY_DSA:
710                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
711                         fatal("sshkey_new failed");
712                 (*k)->type = KEY_DSA;
713                 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
714                 break;
715 #ifdef OPENSSL_HAS_ECC
716         case EVP_PKEY_EC:
717                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
718                         fatal("sshkey_new failed");
719                 (*k)->type = KEY_ECDSA;
720                 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
721                 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
722                 break;
723 #endif
724         default:
725                 fatal_f("unsupported pubkey type %d",
726                     EVP_PKEY_base_id(pubkey));
727         }
728         EVP_PKEY_free(pubkey);
729         return;
730 }
731
732 static void
733 do_convert_from_pem(struct sshkey **k, int *private)
734 {
735         FILE *fp;
736         RSA *rsa;
737
738         if ((fp = fopen(identity_file, "r")) == NULL)
739                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
740         if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
741                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
742                         fatal("sshkey_new failed");
743                 (*k)->type = KEY_RSA;
744                 (*k)->rsa = rsa;
745                 fclose(fp);
746                 return;
747         }
748         fatal_f("unrecognised raw private key format");
749 }
750
751 static void
752 do_convert_from(struct passwd *pw)
753 {
754         struct sshkey *k = NULL;
755         int r, private = 0, ok = 0;
756         struct stat st;
757
758         if (!have_identity)
759                 ask_filename(pw, "Enter file in which the key is");
760         if (stat(identity_file, &st) == -1)
761                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
762
763         switch (convert_format) {
764         case FMT_RFC4716:
765                 do_convert_from_ssh2(pw, &k, &private);
766                 break;
767         case FMT_PKCS8:
768                 do_convert_from_pkcs8(&k, &private);
769                 break;
770         case FMT_PEM:
771                 do_convert_from_pem(&k, &private);
772                 break;
773         default:
774                 fatal_f("unknown key format %d", convert_format);
775         }
776
777         if (!private) {
778                 if ((r = sshkey_write(k, stdout)) == 0)
779                         ok = 1;
780                 if (ok)
781                         fprintf(stdout, "\n");
782         } else {
783                 switch (k->type) {
784                 case KEY_DSA:
785                         ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
786                             NULL, 0, NULL, NULL);
787                         break;
788 #ifdef OPENSSL_HAS_ECC
789                 case KEY_ECDSA:
790                         ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
791                             NULL, 0, NULL, NULL);
792                         break;
793 #endif
794                 case KEY_RSA:
795                         ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
796                             NULL, 0, NULL, NULL);
797                         break;
798                 default:
799                         fatal_f("unsupported key type %s", sshkey_type(k));
800                 }
801         }
802
803         if (!ok)
804                 fatal("key write failed");
805         sshkey_free(k);
806         exit(0);
807 }
808 #endif
809
810 static void
811 do_print_public(struct passwd *pw)
812 {
813         struct sshkey *prv;
814         struct stat st;
815         int r;
816         char *comment = NULL;
817
818         if (!have_identity)
819                 ask_filename(pw, "Enter file in which the key is");
820         if (stat(identity_file, &st) == -1)
821                 fatal("%s: %s", identity_file, strerror(errno));
822         prv = load_identity(identity_file, &comment);
823         if ((r = sshkey_write(prv, stdout)) != 0)
824                 fatal_fr(r, "write key");
825         if (comment != NULL && *comment != '\0')
826                 fprintf(stdout, " %s", comment);
827         fprintf(stdout, "\n");
828         if (sshkey_is_sk(prv)) {
829                 debug("sk_application: \"%s\", sk_flags 0x%02x",
830                         prv->sk_application, prv->sk_flags);
831         }
832         sshkey_free(prv);
833         free(comment);
834         exit(0);
835 }
836
837 static void
838 do_download(struct passwd *pw)
839 {
840 #ifdef ENABLE_PKCS11
841         struct sshkey **keys = NULL;
842         int i, nkeys;
843         enum sshkey_fp_rep rep;
844         int fptype;
845         char *fp, *ra, **comments = NULL;
846
847         fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
848         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
849
850         pkcs11_init(1);
851         nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys, &comments);
852         if (nkeys <= 0)
853                 fatal("cannot read public key from pkcs11");
854         for (i = 0; i < nkeys; i++) {
855                 if (print_fingerprint) {
856                         fp = sshkey_fingerprint(keys[i], fptype, rep);
857                         ra = sshkey_fingerprint(keys[i], fingerprint_hash,
858                             SSH_FP_RANDOMART);
859                         if (fp == NULL || ra == NULL)
860                                 fatal_f("sshkey_fingerprint fail");
861                         printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
862                             fp, sshkey_type(keys[i]));
863                         if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
864                                 printf("%s\n", ra);
865                         free(ra);
866                         free(fp);
867                 } else {
868                         (void) sshkey_write(keys[i], stdout); /* XXX check */
869                         fprintf(stdout, "%s%s\n",
870                             *(comments[i]) == '\0' ? "" : " ", comments[i]);
871                 }
872                 free(comments[i]);
873                 sshkey_free(keys[i]);
874         }
875         free(comments);
876         free(keys);
877         pkcs11_terminate();
878         exit(0);
879 #else
880         fatal("no pkcs11 support");
881 #endif /* ENABLE_PKCS11 */
882 }
883
884 static struct sshkey *
885 try_read_key(char **cpp)
886 {
887         struct sshkey *ret;
888         int r;
889
890         if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
891                 fatal("sshkey_new failed");
892         if ((r = sshkey_read(ret, cpp)) == 0)
893                 return ret;
894         /* Not a key */
895         sshkey_free(ret);
896         return NULL;
897 }
898
899 static void
900 fingerprint_one_key(const struct sshkey *public, const char *comment)
901 {
902         char *fp = NULL, *ra = NULL;
903         enum sshkey_fp_rep rep;
904         int fptype;
905
906         fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
907         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
908         fp = sshkey_fingerprint(public, fptype, rep);
909         ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
910         if (fp == NULL || ra == NULL)
911                 fatal_f("sshkey_fingerprint failed");
912         mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
913             comment ? comment : "no comment", sshkey_type(public));
914         if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
915                 printf("%s\n", ra);
916         free(ra);
917         free(fp);
918 }
919
920 static void
921 fingerprint_private(const char *path)
922 {
923         struct stat st;
924         char *comment = NULL;
925         struct sshkey *privkey = NULL, *pubkey = NULL;
926         int r;
927
928         if (stat(identity_file, &st) == -1)
929                 fatal("%s: %s", path, strerror(errno));
930         if ((r = sshkey_load_public(path, &pubkey, &comment)) != 0)
931                 debug_r(r, "load public \"%s\"", path);
932         if (pubkey == NULL || comment == NULL || *comment == '\0') {
933                 free(comment);
934                 if ((r = sshkey_load_private(path, NULL,
935                     &privkey, &comment)) != 0)
936                         debug_r(r, "load private \"%s\"", path);
937         }
938         if (pubkey == NULL && privkey == NULL)
939                 fatal("%s is not a key file.", path);
940
941         fingerprint_one_key(pubkey == NULL ? privkey : pubkey, comment);
942         sshkey_free(pubkey);
943         sshkey_free(privkey);
944         free(comment);
945 }
946
947 static void
948 do_fingerprint(struct passwd *pw)
949 {
950         FILE *f;
951         struct sshkey *public = NULL;
952         char *comment = NULL, *cp, *ep, *line = NULL;
953         size_t linesize = 0;
954         int i, invalid = 1;
955         const char *path;
956         u_long lnum = 0;
957
958         if (!have_identity)
959                 ask_filename(pw, "Enter file in which the key is");
960         path = identity_file;
961
962         if (strcmp(identity_file, "-") == 0) {
963                 f = stdin;
964                 path = "(stdin)";
965         } else if ((f = fopen(path, "r")) == NULL)
966                 fatal("%s: %s: %s", __progname, path, strerror(errno));
967
968         while (getline(&line, &linesize, f) != -1) {
969                 lnum++;
970                 cp = line;
971                 cp[strcspn(cp, "\n")] = '\0';
972                 /* Trim leading space and comments */
973                 cp = line + strspn(line, " \t");
974                 if (*cp == '#' || *cp == '\0')
975                         continue;
976
977                 /*
978                  * Input may be plain keys, private keys, authorized_keys
979                  * or known_hosts.
980                  */
981
982                 /*
983                  * Try private keys first. Assume a key is private if
984                  * "SSH PRIVATE KEY" appears on the first line and we're
985                  * not reading from stdin (XXX support private keys on stdin).
986                  */
987                 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
988                     strstr(cp, "PRIVATE KEY") != NULL) {
989                         free(line);
990                         fclose(f);
991                         fingerprint_private(path);
992                         exit(0);
993                 }
994
995                 /*
996                  * If it's not a private key, then this must be prepared to
997                  * accept a public key prefixed with a hostname or options.
998                  * Try a bare key first, otherwise skip the leading stuff.
999                  */
1000                 if ((public = try_read_key(&cp)) == NULL) {
1001                         i = strtol(cp, &ep, 10);
1002                         if (i == 0 || ep == NULL ||
1003                             (*ep != ' ' && *ep != '\t')) {
1004                                 int quoted = 0;
1005
1006                                 comment = cp;
1007                                 for (; *cp && (quoted || (*cp != ' ' &&
1008                                     *cp != '\t')); cp++) {
1009                                         if (*cp == '\\' && cp[1] == '"')
1010                                                 cp++;   /* Skip both */
1011                                         else if (*cp == '"')
1012                                                 quoted = !quoted;
1013                                 }
1014                                 if (!*cp)
1015                                         continue;
1016                                 *cp++ = '\0';
1017                         }
1018                 }
1019                 /* Retry after parsing leading hostname/key options */
1020                 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
1021                         debug("%s:%lu: not a public key", path, lnum);
1022                         continue;
1023                 }
1024
1025                 /* Find trailing comment, if any */
1026                 for (; *cp == ' ' || *cp == '\t'; cp++)
1027                         ;
1028                 if (*cp != '\0' && *cp != '#')
1029                         comment = cp;
1030
1031                 fingerprint_one_key(public, comment);
1032                 sshkey_free(public);
1033                 invalid = 0; /* One good key in the file is sufficient */
1034         }
1035         fclose(f);
1036         free(line);
1037
1038         if (invalid)
1039                 fatal("%s is not a public key file.", path);
1040         exit(0);
1041 }
1042
1043 static void
1044 do_gen_all_hostkeys(struct passwd *pw)
1045 {
1046         struct {
1047                 char *key_type;
1048                 char *key_type_display;
1049                 char *path;
1050         } key_types[] = {
1051 #ifdef WITH_OPENSSL
1052                 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
1053 #ifdef OPENSSL_HAS_ECC
1054                 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
1055 #endif /* OPENSSL_HAS_ECC */
1056 #endif /* WITH_OPENSSL */
1057                 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
1058 #ifdef WITH_XMSS
1059                 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
1060 #endif /* WITH_XMSS */
1061                 { NULL, NULL, NULL }
1062         };
1063
1064         u_int32_t bits = 0;
1065         int first = 0;
1066         struct stat st;
1067         struct sshkey *private, *public;
1068         char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
1069         int i, type, fd, r;
1070
1071         for (i = 0; key_types[i].key_type; i++) {
1072                 public = private = NULL;
1073                 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1074
1075                 xasprintf(&prv_file, "%s%s",
1076                     identity_file, key_types[i].path);
1077
1078                 /* Check whether private key exists and is not zero-length */
1079                 if (stat(prv_file, &st) == 0) {
1080                         if (st.st_size != 0)
1081                                 goto next;
1082                 } else if (errno != ENOENT) {
1083                         error("Could not stat %s: %s", key_types[i].path,
1084                             strerror(errno));
1085                         goto failnext;
1086                 }
1087
1088                 /*
1089                  * Private key doesn't exist or is invalid; proceed with
1090                  * key generation.
1091                  */
1092                 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1093                     identity_file, key_types[i].path);
1094                 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1095                     identity_file, key_types[i].path);
1096                 xasprintf(&pub_file, "%s%s.pub",
1097                     identity_file, key_types[i].path);
1098
1099                 if (first == 0) {
1100                         first = 1;
1101                         printf("%s: generating new host keys: ", __progname);
1102                 }
1103                 printf("%s ", key_types[i].key_type_display);
1104                 fflush(stdout);
1105                 type = sshkey_type_from_name(key_types[i].key_type);
1106                 if ((fd = mkstemp(prv_tmp)) == -1) {
1107                         error("Could not save your private key in %s: %s",
1108                             prv_tmp, strerror(errno));
1109                         goto failnext;
1110                 }
1111                 (void)close(fd); /* just using mkstemp() to reserve a name */
1112                 bits = 0;
1113                 type_bits_valid(type, NULL, &bits);
1114                 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1115                         error_r(r, "sshkey_generate failed");
1116                         goto failnext;
1117                 }
1118                 if ((r = sshkey_from_private(private, &public)) != 0)
1119                         fatal_fr(r, "sshkey_from_private");
1120                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1121                     hostname);
1122                 if ((r = sshkey_save_private(private, prv_tmp, "",
1123                     comment, private_key_format, openssh_format_cipher,
1124                     rounds)) != 0) {
1125                         error_r(r, "Saving key \"%s\" failed", prv_tmp);
1126                         goto failnext;
1127                 }
1128                 if ((fd = mkstemp(pub_tmp)) == -1) {
1129                         error("Could not save your public key in %s: %s",
1130                             pub_tmp, strerror(errno));
1131                         goto failnext;
1132                 }
1133                 (void)fchmod(fd, 0644);
1134                 (void)close(fd);
1135                 if ((r = sshkey_save_public(public, pub_tmp, comment)) != 0) {
1136                         error_r(r, "Unable to save public key to %s",
1137                             identity_file);
1138                         goto failnext;
1139                 }
1140
1141                 /* Rename temporary files to their permanent locations. */
1142                 if (rename(pub_tmp, pub_file) != 0) {
1143                         error("Unable to move %s into position: %s",
1144                             pub_file, strerror(errno));
1145                         goto failnext;
1146                 }
1147                 if (rename(prv_tmp, prv_file) != 0) {
1148                         error("Unable to move %s into position: %s",
1149                             key_types[i].path, strerror(errno));
1150  failnext:
1151                         first = 0;
1152                         goto next;
1153                 }
1154  next:
1155                 sshkey_free(private);
1156                 sshkey_free(public);
1157                 free(prv_tmp);
1158                 free(pub_tmp);
1159                 free(prv_file);
1160                 free(pub_file);
1161         }
1162         if (first != 0)
1163                 printf("\n");
1164 }
1165
1166 struct known_hosts_ctx {
1167         const char *host;       /* Hostname searched for in find/delete case */
1168         FILE *out;              /* Output file, stdout for find_hosts case */
1169         int has_unhashed;       /* When hashing, original had unhashed hosts */
1170         int found_key;          /* For find/delete, host was found */
1171         int invalid;            /* File contained invalid items; don't delete */
1172         int hash_hosts;         /* Hash hostnames as we go */
1173         int find_host;          /* Search for specific hostname */
1174         int delete_host;        /* Delete host from known_hosts */
1175 };
1176
1177 static int
1178 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1179 {
1180         struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1181         char *hashed, *cp, *hosts, *ohosts;
1182         int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1183         int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1184
1185         switch (l->status) {
1186         case HKF_STATUS_OK:
1187         case HKF_STATUS_MATCHED:
1188                 /*
1189                  * Don't hash hosts already already hashed, with wildcard
1190                  * characters or a CA/revocation marker.
1191                  */
1192                 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1193                         fprintf(ctx->out, "%s\n", l->line);
1194                         if (has_wild && !ctx->find_host) {
1195                                 logit("%s:%lu: ignoring host name "
1196                                     "with wildcard: %.64s", l->path,
1197                                     l->linenum, l->hosts);
1198                         }
1199                         return 0;
1200                 }
1201                 /*
1202                  * Split any comma-separated hostnames from the host list,
1203                  * hash and store separately.
1204                  */
1205                 ohosts = hosts = xstrdup(l->hosts);
1206                 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1207                         lowercase(cp);
1208                         if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1209                                 fatal("hash_host failed");
1210                         fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1211                         free(hashed);
1212                         ctx->has_unhashed = 1;
1213                 }
1214                 free(ohosts);
1215                 return 0;
1216         case HKF_STATUS_INVALID:
1217                 /* Retain invalid lines, but mark file as invalid. */
1218                 ctx->invalid = 1;
1219                 logit("%s:%lu: invalid line", l->path, l->linenum);
1220                 /* FALLTHROUGH */
1221         default:
1222                 fprintf(ctx->out, "%s\n", l->line);
1223                 return 0;
1224         }
1225         /* NOTREACHED */
1226         return -1;
1227 }
1228
1229 static int
1230 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1231 {
1232         struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1233         enum sshkey_fp_rep rep;
1234         int fptype;
1235         char *fp = NULL, *ra = NULL;
1236
1237         fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1238         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1239
1240         if (l->status == HKF_STATUS_MATCHED) {
1241                 if (ctx->delete_host) {
1242                         if (l->marker != MRK_NONE) {
1243                                 /* Don't remove CA and revocation lines */
1244                                 fprintf(ctx->out, "%s\n", l->line);
1245                         } else {
1246                                 /*
1247                                  * Hostname matches and has no CA/revoke
1248                                  * marker, delete it by *not* writing the
1249                                  * line to ctx->out.
1250                                  */
1251                                 ctx->found_key = 1;
1252                                 if (!quiet)
1253                                         printf("# Host %s found: line %lu\n",
1254                                             ctx->host, l->linenum);
1255                         }
1256                         return 0;
1257                 } else if (ctx->find_host) {
1258                         ctx->found_key = 1;
1259                         if (!quiet) {
1260                                 printf("# Host %s found: line %lu %s\n",
1261                                     ctx->host,
1262                                     l->linenum, l->marker == MRK_CA ? "CA" :
1263                                     (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1264                         }
1265                         if (ctx->hash_hosts)
1266                                 known_hosts_hash(l, ctx);
1267                         else if (print_fingerprint) {
1268                                 fp = sshkey_fingerprint(l->key, fptype, rep);
1269                                 ra = sshkey_fingerprint(l->key,
1270                                     fingerprint_hash, SSH_FP_RANDOMART);
1271                                 if (fp == NULL || ra == NULL)
1272                                         fatal_f("sshkey_fingerprint failed");
1273                                 mprintf("%s %s %s%s%s\n", ctx->host,
1274                                     sshkey_type(l->key), fp,
1275                                     l->comment[0] ? " " : "",
1276                                     l->comment);
1277                                 if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
1278                                         printf("%s\n", ra);
1279                                 free(ra);
1280                                 free(fp);
1281                         } else
1282                                 fprintf(ctx->out, "%s\n", l->line);
1283                         return 0;
1284                 }
1285         } else if (ctx->delete_host) {
1286                 /* Retain non-matching hosts when deleting */
1287                 if (l->status == HKF_STATUS_INVALID) {
1288                         ctx->invalid = 1;
1289                         logit("%s:%lu: invalid line", l->path, l->linenum);
1290                 }
1291                 fprintf(ctx->out, "%s\n", l->line);
1292         }
1293         return 0;
1294 }
1295
1296 static void
1297 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1298     int delete_host, int hash_hosts)
1299 {
1300         char *cp, tmp[PATH_MAX], old[PATH_MAX];
1301         int r, fd, oerrno, inplace = 0;
1302         struct known_hosts_ctx ctx;
1303         u_int foreach_options;
1304         struct stat sb;
1305
1306         if (!have_identity) {
1307                 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1308                 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1309                     sizeof(identity_file))
1310                         fatal("Specified known hosts path too long");
1311                 free(cp);
1312                 have_identity = 1;
1313         }
1314         if (stat(identity_file, &sb) != 0)
1315                 fatal("Cannot stat %s: %s", identity_file, strerror(errno));
1316
1317         memset(&ctx, 0, sizeof(ctx));
1318         ctx.out = stdout;
1319         ctx.host = name;
1320         ctx.hash_hosts = hash_hosts;
1321         ctx.find_host = find_host;
1322         ctx.delete_host = delete_host;
1323
1324         /*
1325          * Find hosts goes to stdout, hash and deletions happen in-place
1326          * A corner case is ssh-keygen -HF foo, which should go to stdout
1327          */
1328         if (!find_host && (hash_hosts || delete_host)) {
1329                 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1330                     strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1331                     strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1332                     strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1333                         fatal("known_hosts path too long");
1334                 umask(077);
1335                 if ((fd = mkstemp(tmp)) == -1)
1336                         fatal("mkstemp: %s", strerror(errno));
1337                 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1338                         oerrno = errno;
1339                         unlink(tmp);
1340                         fatal("fdopen: %s", strerror(oerrno));
1341                 }
1342                 (void)fchmod(fd, sb.st_mode & 0644);
1343                 inplace = 1;
1344         }
1345         /* XXX support identity_file == "-" for stdin */
1346         foreach_options = find_host ? HKF_WANT_MATCH : 0;
1347         foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1348         if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1349             known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1350             foreach_options, 0)) != 0) {
1351                 if (inplace)
1352                         unlink(tmp);
1353                 fatal_fr(r, "hostkeys_foreach");
1354         }
1355
1356         if (inplace)
1357                 fclose(ctx.out);
1358
1359         if (ctx.invalid) {
1360                 error("%s is not a valid known_hosts file.", identity_file);
1361                 if (inplace) {
1362                         error("Not replacing existing known_hosts "
1363                             "file because of errors");
1364                         unlink(tmp);
1365                 }
1366                 exit(1);
1367         } else if (delete_host && !ctx.found_key) {
1368                 logit("Host %s not found in %s", name, identity_file);
1369                 if (inplace)
1370                         unlink(tmp);
1371         } else if (inplace) {
1372                 /* Backup existing file */
1373                 if (unlink(old) == -1 && errno != ENOENT)
1374                         fatal("unlink %.100s: %s", old, strerror(errno));
1375                 if (link(identity_file, old) == -1)
1376                         fatal("link %.100s to %.100s: %s", identity_file, old,
1377                             strerror(errno));
1378                 /* Move new one into place */
1379                 if (rename(tmp, identity_file) == -1) {
1380                         error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1381                             strerror(errno));
1382                         unlink(tmp);
1383                         unlink(old);
1384                         exit(1);
1385                 }
1386
1387                 printf("%s updated.\n", identity_file);
1388                 printf("Original contents retained as %s\n", old);
1389                 if (ctx.has_unhashed) {
1390                         logit("WARNING: %s contains unhashed entries", old);
1391                         logit("Delete this file to ensure privacy "
1392                             "of hostnames");
1393                 }
1394         }
1395
1396         exit (find_host && !ctx.found_key);
1397 }
1398
1399 /*
1400  * Perform changing a passphrase.  The argument is the passwd structure
1401  * for the current user.
1402  */
1403 static void
1404 do_change_passphrase(struct passwd *pw)
1405 {
1406         char *comment;
1407         char *old_passphrase, *passphrase1, *passphrase2;
1408         struct stat st;
1409         struct sshkey *private;
1410         int r;
1411
1412         if (!have_identity)
1413                 ask_filename(pw, "Enter file in which the key is");
1414         if (stat(identity_file, &st) == -1)
1415                 fatal("%s: %s", identity_file, strerror(errno));
1416         /* Try to load the file with empty passphrase. */
1417         r = sshkey_load_private(identity_file, "", &private, &comment);
1418         if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1419                 if (identity_passphrase)
1420                         old_passphrase = xstrdup(identity_passphrase);
1421                 else
1422                         old_passphrase =
1423                             read_passphrase("Enter old passphrase: ",
1424                             RP_ALLOW_STDIN);
1425                 r = sshkey_load_private(identity_file, old_passphrase,
1426                     &private, &comment);
1427                 freezero(old_passphrase, strlen(old_passphrase));
1428                 if (r != 0)
1429                         goto badkey;
1430         } else if (r != 0) {
1431  badkey:
1432                 fatal_r(r, "Failed to load key %s", identity_file);
1433         }
1434         if (comment)
1435                 mprintf("Key has comment '%s'\n", comment);
1436
1437         /* Ask the new passphrase (twice). */
1438         if (identity_new_passphrase) {
1439                 passphrase1 = xstrdup(identity_new_passphrase);
1440                 passphrase2 = NULL;
1441         } else {
1442                 passphrase1 =
1443                         read_passphrase("Enter new passphrase (empty for no "
1444                             "passphrase): ", RP_ALLOW_STDIN);
1445                 passphrase2 = read_passphrase("Enter same passphrase again: ",
1446                     RP_ALLOW_STDIN);
1447
1448                 /* Verify that they are the same. */
1449                 if (strcmp(passphrase1, passphrase2) != 0) {
1450                         explicit_bzero(passphrase1, strlen(passphrase1));
1451                         explicit_bzero(passphrase2, strlen(passphrase2));
1452                         free(passphrase1);
1453                         free(passphrase2);
1454                         printf("Pass phrases do not match.  Try again.\n");
1455                         exit(1);
1456                 }
1457                 /* Destroy the other copy. */
1458                 freezero(passphrase2, strlen(passphrase2));
1459         }
1460
1461         /* Save the file using the new passphrase. */
1462         if ((r = sshkey_save_private(private, identity_file, passphrase1,
1463             comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
1464                 error_r(r, "Saving key \"%s\" failed", identity_file);
1465                 freezero(passphrase1, strlen(passphrase1));
1466                 sshkey_free(private);
1467                 free(comment);
1468                 exit(1);
1469         }
1470         /* Destroy the passphrase and the copy of the key in memory. */
1471         freezero(passphrase1, strlen(passphrase1));
1472         sshkey_free(private);            /* Destroys contents */
1473         free(comment);
1474
1475         printf("Your identification has been saved with the new passphrase.\n");
1476         exit(0);
1477 }
1478
1479 /*
1480  * Print the SSHFP RR.
1481  */
1482 static int
1483 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1484     int print_generic, char * const *opts, size_t nopts)
1485 {
1486         struct sshkey *public;
1487         char *comment = NULL;
1488         struct stat st;
1489         int r, hash = -1;
1490         size_t i;
1491
1492         for (i = 0; i < nopts; i++) {
1493                 if (strncasecmp(opts[i], "hashalg=", 8) == 0) {
1494                         if ((hash = ssh_digest_alg_by_name(opts[i] + 8)) == -1)
1495                                 fatal("Unsupported hash algorithm");
1496                 } else {
1497                         error("Invalid option \"%s\"", opts[i]);
1498                         return SSH_ERR_INVALID_ARGUMENT;
1499                 }
1500         }
1501         if (fname == NULL)
1502                 fatal_f("no filename");
1503         if (stat(fname, &st) == -1) {
1504                 if (errno == ENOENT)
1505                         return 0;
1506                 fatal("%s: %s", fname, strerror(errno));
1507         }
1508         if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1509                 fatal_r(r, "Failed to read v2 public key from \"%s\"", fname);
1510         export_dns_rr(hname, public, stdout, print_generic, hash);
1511         sshkey_free(public);
1512         free(comment);
1513         return 1;
1514 }
1515
1516 /*
1517  * Change the comment of a private key file.
1518  */
1519 static void
1520 do_change_comment(struct passwd *pw, const char *identity_comment)
1521 {
1522         char new_comment[1024], *comment, *passphrase;
1523         struct sshkey *private;
1524         struct sshkey *public;
1525         struct stat st;
1526         int r;
1527
1528         if (!have_identity)
1529                 ask_filename(pw, "Enter file in which the key is");
1530         if (stat(identity_file, &st) == -1)
1531                 fatal("%s: %s", identity_file, strerror(errno));
1532         if ((r = sshkey_load_private(identity_file, "",
1533             &private, &comment)) == 0)
1534                 passphrase = xstrdup("");
1535         else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1536                 fatal_r(r, "Cannot load private key \"%s\"", identity_file);
1537         else {
1538                 if (identity_passphrase)
1539                         passphrase = xstrdup(identity_passphrase);
1540                 else if (identity_new_passphrase)
1541                         passphrase = xstrdup(identity_new_passphrase);
1542                 else
1543                         passphrase = read_passphrase("Enter passphrase: ",
1544                             RP_ALLOW_STDIN);
1545                 /* Try to load using the passphrase. */
1546                 if ((r = sshkey_load_private(identity_file, passphrase,
1547                     &private, &comment)) != 0) {
1548                         freezero(passphrase, strlen(passphrase));
1549                         fatal_r(r, "Cannot load private key \"%s\"",
1550                             identity_file);
1551                 }
1552         }
1553
1554         if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1555             private_key_format != SSHKEY_PRIVATE_OPENSSH) {
1556                 error("Comments are only supported for keys stored in "
1557                     "the new format (-o).");
1558                 explicit_bzero(passphrase, strlen(passphrase));
1559                 sshkey_free(private);
1560                 exit(1);
1561         }
1562         if (comment)
1563                 printf("Old comment: %s\n", comment);
1564         else
1565                 printf("No existing comment\n");
1566
1567         if (identity_comment) {
1568                 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1569         } else {
1570                 printf("New comment: ");
1571                 fflush(stdout);
1572                 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1573                         explicit_bzero(passphrase, strlen(passphrase));
1574                         sshkey_free(private);
1575                         exit(1);
1576                 }
1577                 new_comment[strcspn(new_comment, "\n")] = '\0';
1578         }
1579         if (comment != NULL && strcmp(comment, new_comment) == 0) {
1580                 printf("No change to comment\n");
1581                 free(passphrase);
1582                 sshkey_free(private);
1583                 free(comment);
1584                 exit(0);
1585         }
1586
1587         /* Save the file using the new passphrase. */
1588         if ((r = sshkey_save_private(private, identity_file, passphrase,
1589             new_comment, private_key_format, openssh_format_cipher,
1590             rounds)) != 0) {
1591                 error_r(r, "Saving key \"%s\" failed", identity_file);
1592                 freezero(passphrase, strlen(passphrase));
1593                 sshkey_free(private);
1594                 free(comment);
1595                 exit(1);
1596         }
1597         freezero(passphrase, strlen(passphrase));
1598         if ((r = sshkey_from_private(private, &public)) != 0)
1599                 fatal_fr(r, "sshkey_from_private");
1600         sshkey_free(private);
1601
1602         strlcat(identity_file, ".pub", sizeof(identity_file));
1603         if ((r = sshkey_save_public(public, identity_file, new_comment)) != 0)
1604                 fatal_r(r, "Unable to save public key to %s", identity_file);
1605         sshkey_free(public);
1606         free(comment);
1607
1608         if (strlen(new_comment) > 0)
1609                 printf("Comment '%s' applied\n", new_comment);
1610         else
1611                 printf("Comment removed\n");
1612
1613         exit(0);
1614 }
1615
1616 static void
1617 cert_ext_add(const char *key, const char *value, int iscrit)
1618 {
1619         cert_ext = xreallocarray(cert_ext, ncert_ext + 1, sizeof(*cert_ext));
1620         cert_ext[ncert_ext].key = xstrdup(key);
1621         cert_ext[ncert_ext].val = value == NULL ? NULL : xstrdup(value);
1622         cert_ext[ncert_ext].crit = iscrit;
1623         ncert_ext++;
1624 }
1625
1626 /* qsort(3) comparison function for certificate extensions */
1627 static int
1628 cert_ext_cmp(const void *_a, const void *_b)
1629 {
1630         const struct cert_ext *a = (const struct cert_ext *)_a;
1631         const struct cert_ext *b = (const struct cert_ext *)_b;
1632         int r;
1633
1634         if (a->crit != b->crit)
1635                 return (a->crit < b->crit) ? -1 : 1;
1636         if ((r = strcmp(a->key, b->key)) != 0)
1637                 return r;
1638         if ((a->val == NULL) != (b->val == NULL))
1639                 return (a->val == NULL) ? -1 : 1;
1640         if (a->val != NULL && (r = strcmp(a->val, b->val)) != 0)
1641                 return r;
1642         return 0;
1643 }
1644
1645 #define OPTIONS_CRITICAL        1
1646 #define OPTIONS_EXTENSIONS      2
1647 static void
1648 prepare_options_buf(struct sshbuf *c, int which)
1649 {
1650         struct sshbuf *b;
1651         size_t i;
1652         int r;
1653         const struct cert_ext *ext;
1654
1655         if ((b = sshbuf_new()) == NULL)
1656                 fatal_f("sshbuf_new failed");
1657         sshbuf_reset(c);
1658         for (i = 0; i < ncert_ext; i++) {
1659                 ext = &cert_ext[i];
1660                 if ((ext->crit && (which & OPTIONS_EXTENSIONS)) ||
1661                     (!ext->crit && (which & OPTIONS_CRITICAL)))
1662                         continue;
1663                 if (ext->val == NULL) {
1664                         /* flag option */
1665                         debug3_f("%s", ext->key);
1666                         if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1667                             (r = sshbuf_put_string(c, NULL, 0)) != 0)
1668                                 fatal_fr(r, "prepare flag");
1669                 } else {
1670                         /* key/value option */
1671                         debug3_f("%s=%s", ext->key, ext->val);
1672                         sshbuf_reset(b);
1673                         if ((r = sshbuf_put_cstring(c, ext->key)) != 0 ||
1674                             (r = sshbuf_put_cstring(b, ext->val)) != 0 ||
1675                             (r = sshbuf_put_stringb(c, b)) != 0)
1676                                 fatal_fr(r, "prepare k/v");
1677                 }
1678         }
1679         sshbuf_free(b);
1680 }
1681
1682 static void
1683 finalise_cert_exts(void)
1684 {
1685         /* critical options */
1686         if (certflags_command != NULL)
1687                 cert_ext_add("force-command", certflags_command, 1);
1688         if (certflags_src_addr != NULL)
1689                 cert_ext_add("source-address", certflags_src_addr, 1);
1690         if ((certflags_flags & CERTOPT_REQUIRE_VERIFY) != 0)
1691                 cert_ext_add("verify-required", NULL, 1);
1692         /* extensions */
1693         if ((certflags_flags & CERTOPT_X_FWD) != 0)
1694                 cert_ext_add("permit-X11-forwarding", NULL, 0);
1695         if ((certflags_flags & CERTOPT_AGENT_FWD) != 0)
1696                 cert_ext_add("permit-agent-forwarding", NULL, 0);
1697         if ((certflags_flags & CERTOPT_PORT_FWD) != 0)
1698                 cert_ext_add("permit-port-forwarding", NULL, 0);
1699         if ((certflags_flags & CERTOPT_PTY) != 0)
1700                 cert_ext_add("permit-pty", NULL, 0);
1701         if ((certflags_flags & CERTOPT_USER_RC) != 0)
1702                 cert_ext_add("permit-user-rc", NULL, 0);
1703         if ((certflags_flags & CERTOPT_NO_REQUIRE_USER_PRESENCE) != 0)
1704                 cert_ext_add("no-touch-required", NULL, 0);
1705         /* order lexically by key */
1706         if (ncert_ext > 0)
1707                 qsort(cert_ext, ncert_ext, sizeof(*cert_ext), cert_ext_cmp);
1708 }
1709
1710 static struct sshkey *
1711 load_pkcs11_key(char *path)
1712 {
1713 #ifdef ENABLE_PKCS11
1714         struct sshkey **keys = NULL, *public, *private = NULL;
1715         int r, i, nkeys;
1716
1717         if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1718                 fatal_r(r, "Couldn't load CA public key \"%s\"", path);
1719
1720         nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase,
1721             &keys, NULL);
1722         debug3_f("%d keys", nkeys);
1723         if (nkeys <= 0)
1724                 fatal("cannot read public key from pkcs11");
1725         for (i = 0; i < nkeys; i++) {
1726                 if (sshkey_equal_public(public, keys[i])) {
1727                         private = keys[i];
1728                         continue;
1729                 }
1730                 sshkey_free(keys[i]);
1731         }
1732         free(keys);
1733         sshkey_free(public);
1734         return private;
1735 #else
1736         fatal("no pkcs11 support");
1737 #endif /* ENABLE_PKCS11 */
1738 }
1739
1740 /* Signer for sshkey_certify_custom that uses the agent */
1741 static int
1742 agent_signer(struct sshkey *key, u_char **sigp, size_t *lenp,
1743     const u_char *data, size_t datalen,
1744     const char *alg, const char *provider, const char *pin,
1745     u_int compat, void *ctx)
1746 {
1747         int *agent_fdp = (int *)ctx;
1748
1749         return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1750             data, datalen, alg, compat);
1751 }
1752
1753 static void
1754 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1755     unsigned long long cert_serial, int cert_serial_autoinc,
1756     int argc, char **argv)
1757 {
1758         int r, i, found, agent_fd = -1;
1759         u_int n;
1760         struct sshkey *ca, *public;
1761         char valid[64], *otmp, *tmp, *cp, *out, *comment;
1762         char *ca_fp = NULL, **plist = NULL, *pin = NULL;
1763         struct ssh_identitylist *agent_ids;
1764         size_t j;
1765         struct notifier_ctx *notifier = NULL;
1766
1767 #ifdef ENABLE_PKCS11
1768         pkcs11_init(1);
1769 #endif
1770         tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1771         if (pkcs11provider != NULL) {
1772                 /* If a PKCS#11 token was specified then try to use it */
1773                 if ((ca = load_pkcs11_key(tmp)) == NULL)
1774                         fatal("No PKCS#11 key matching %s found", ca_key_path);
1775         } else if (prefer_agent) {
1776                 /*
1777                  * Agent signature requested. Try to use agent after making
1778                  * sure the public key specified is actually present in the
1779                  * agent.
1780                  */
1781                 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1782                         fatal_r(r, "Cannot load CA public key %s", tmp);
1783                 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1784                         fatal_r(r, "Cannot use public key for CA signature");
1785                 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1786                         fatal_r(r, "Retrieve agent key list");
1787                 found = 0;
1788                 for (j = 0; j < agent_ids->nkeys; j++) {
1789                         if (sshkey_equal(ca, agent_ids->keys[j])) {
1790                                 found = 1;
1791                                 break;
1792                         }
1793                 }
1794                 if (!found)
1795                         fatal("CA key %s not found in agent", tmp);
1796                 ssh_free_identitylist(agent_ids);
1797                 ca->flags |= SSHKEY_FLAG_EXT;
1798         } else {
1799                 /* CA key is assumed to be a private key on the filesystem */
1800                 ca = load_identity(tmp, NULL);
1801                 if (sshkey_is_sk(ca) &&
1802                     (ca->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
1803                         if ((pin = read_passphrase("Enter PIN for CA key: ",
1804                             RP_ALLOW_STDIN)) == NULL)
1805                                 fatal_f("couldn't read PIN");
1806                 }
1807         }
1808         free(tmp);
1809
1810         if (key_type_name != NULL) {
1811                 if (sshkey_type_from_name(key_type_name) != ca->type) {
1812                         fatal("CA key type %s doesn't match specified %s",
1813                             sshkey_ssh_name(ca), key_type_name);
1814                 }
1815         } else if (ca->type == KEY_RSA) {
1816                 /* Default to a good signature algorithm */
1817                 key_type_name = "rsa-sha2-512";
1818         }
1819         ca_fp = sshkey_fingerprint(ca, fingerprint_hash, SSH_FP_DEFAULT);
1820
1821         finalise_cert_exts();
1822         for (i = 0; i < argc; i++) {
1823                 /* Split list of principals */
1824                 n = 0;
1825                 if (cert_principals != NULL) {
1826                         otmp = tmp = xstrdup(cert_principals);
1827                         plist = NULL;
1828                         for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1829                                 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1830                                 if (*(plist[n] = xstrdup(cp)) == '\0')
1831                                         fatal("Empty principal name");
1832                         }
1833                         free(otmp);
1834                 }
1835                 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1836                         fatal("Too many certificate principals specified");
1837
1838                 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1839                 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1840                         fatal_r(r, "load pubkey \"%s\"", tmp);
1841                 if (sshkey_is_cert(public))
1842                         fatal_f("key \"%s\" type %s cannot be certified",
1843                             tmp, sshkey_type(public));
1844
1845                 /* Prepare certificate to sign */
1846                 if ((r = sshkey_to_certified(public)) != 0)
1847                         fatal_r(r, "Could not upgrade key %s to certificate", tmp);
1848                 public->cert->type = cert_key_type;
1849                 public->cert->serial = (u_int64_t)cert_serial;
1850                 public->cert->key_id = xstrdup(cert_key_id);
1851                 public->cert->nprincipals = n;
1852                 public->cert->principals = plist;
1853                 public->cert->valid_after = cert_valid_from;
1854                 public->cert->valid_before = cert_valid_to;
1855                 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1856                 prepare_options_buf(public->cert->extensions,
1857                     OPTIONS_EXTENSIONS);
1858                 if ((r = sshkey_from_private(ca,
1859                     &public->cert->signature_key)) != 0)
1860                         fatal_r(r, "sshkey_from_private (ca key)");
1861
1862                 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1863                         if ((r = sshkey_certify_custom(public, ca,
1864                             key_type_name, sk_provider, NULL, agent_signer,
1865                             &agent_fd)) != 0)
1866                                 fatal_r(r, "Couldn't certify %s via agent", tmp);
1867                 } else {
1868                         if (sshkey_is_sk(ca) &&
1869                             (ca->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
1870                                 notifier = notify_start(0,
1871                                     "Confirm user presence for key %s %s",
1872                                     sshkey_type(ca), ca_fp);
1873                         }
1874                         r = sshkey_certify(public, ca, key_type_name,
1875                             sk_provider, pin);
1876                         notify_complete(notifier, "User presence confirmed");
1877                         if (r != 0)
1878                                 fatal_r(r, "Couldn't certify key %s", tmp);
1879                 }
1880
1881                 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1882                         *cp = '\0';
1883                 xasprintf(&out, "%s-cert.pub", tmp);
1884                 free(tmp);
1885
1886                 if ((r = sshkey_save_public(public, out, comment)) != 0) {
1887                         fatal_r(r, "Unable to save public key to %s",
1888                             identity_file);
1889                 }
1890
1891                 if (!quiet) {
1892                         sshkey_format_cert_validity(public->cert,
1893                             valid, sizeof(valid));
1894                         logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1895                             "valid %s", sshkey_cert_type(public),
1896                             out, public->cert->key_id,
1897                             (unsigned long long)public->cert->serial,
1898                             cert_principals != NULL ? " for " : "",
1899                             cert_principals != NULL ? cert_principals : "",
1900                             valid);
1901                 }
1902
1903                 sshkey_free(public);
1904                 free(out);
1905                 if (cert_serial_autoinc)
1906                         cert_serial++;
1907         }
1908         if (pin != NULL)
1909                 freezero(pin, strlen(pin));
1910         free(ca_fp);
1911 #ifdef ENABLE_PKCS11
1912         pkcs11_terminate();
1913 #endif
1914         exit(0);
1915 }
1916
1917 static u_int64_t
1918 parse_relative_time(const char *s, time_t now)
1919 {
1920         int64_t mul, secs;
1921
1922         mul = *s == '-' ? -1 : 1;
1923
1924         if ((secs = convtime(s + 1)) == -1)
1925                 fatal("Invalid relative certificate time %s", s);
1926         if (mul == -1 && secs > now)
1927                 fatal("Certificate time %s cannot be represented", s);
1928         return now + (u_int64_t)(secs * mul);
1929 }
1930
1931 static void
1932 parse_hex_u64(const char *s, uint64_t *up)
1933 {
1934         char *ep;
1935         unsigned long long ull;
1936
1937         errno = 0;
1938         ull = strtoull(s, &ep, 16);
1939         if (*s == '\0' || *ep != '\0')
1940                 fatal("Invalid certificate time: not a number");
1941         if (errno == ERANGE && ull == ULONG_MAX)
1942                 fatal_fr(SSH_ERR_SYSTEM_ERROR, "Invalid certificate time");
1943         *up = (uint64_t)ull;
1944 }
1945
1946 static void
1947 parse_cert_times(char *timespec)
1948 {
1949         char *from, *to;
1950         time_t now = time(NULL);
1951         int64_t secs;
1952
1953         /* +timespec relative to now */
1954         if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1955                 if ((secs = convtime(timespec + 1)) == -1)
1956                         fatal("Invalid relative certificate life %s", timespec);
1957                 cert_valid_to = now + secs;
1958                 /*
1959                  * Backdate certificate one minute to avoid problems on hosts
1960                  * with poorly-synchronised clocks.
1961                  */
1962                 cert_valid_from = ((now - 59)/ 60) * 60;
1963                 return;
1964         }
1965
1966         /*
1967          * from:to, where
1968          * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "always"
1969          *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | 0x... | "forever"
1970          */
1971         from = xstrdup(timespec);
1972         to = strchr(from, ':');
1973         if (to == NULL || from == to || *(to + 1) == '\0')
1974                 fatal("Invalid certificate life specification %s", timespec);
1975         *to++ = '\0';
1976
1977         if (*from == '-' || *from == '+')
1978                 cert_valid_from = parse_relative_time(from, now);
1979         else if (strcmp(from, "always") == 0)
1980                 cert_valid_from = 0;
1981         else if (strncmp(from, "0x", 2) == 0)
1982                 parse_hex_u64(from, &cert_valid_from);
1983         else if (parse_absolute_time(from, &cert_valid_from) != 0)
1984                 fatal("Invalid from time \"%s\"", from);
1985
1986         if (*to == '-' || *to == '+')
1987                 cert_valid_to = parse_relative_time(to, now);
1988         else if (strcmp(to, "forever") == 0)
1989                 cert_valid_to = ~(u_int64_t)0;
1990         else if (strncmp(to, "0x", 2) == 0)
1991                 parse_hex_u64(to, &cert_valid_to);
1992         else if (parse_absolute_time(to, &cert_valid_to) != 0)
1993                 fatal("Invalid to time \"%s\"", to);
1994
1995         if (cert_valid_to <= cert_valid_from)
1996                 fatal("Empty certificate validity interval");
1997         free(from);
1998 }
1999
2000 static void
2001 add_cert_option(char *opt)
2002 {
2003         char *val, *cp;
2004         int iscrit = 0;
2005
2006         if (strcasecmp(opt, "clear") == 0)
2007                 certflags_flags = 0;
2008         else if (strcasecmp(opt, "no-x11-forwarding") == 0)
2009                 certflags_flags &= ~CERTOPT_X_FWD;
2010         else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
2011                 certflags_flags |= CERTOPT_X_FWD;
2012         else if (strcasecmp(opt, "no-agent-forwarding") == 0)
2013                 certflags_flags &= ~CERTOPT_AGENT_FWD;
2014         else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
2015                 certflags_flags |= CERTOPT_AGENT_FWD;
2016         else if (strcasecmp(opt, "no-port-forwarding") == 0)
2017                 certflags_flags &= ~CERTOPT_PORT_FWD;
2018         else if (strcasecmp(opt, "permit-port-forwarding") == 0)
2019                 certflags_flags |= CERTOPT_PORT_FWD;
2020         else if (strcasecmp(opt, "no-pty") == 0)
2021                 certflags_flags &= ~CERTOPT_PTY;
2022         else if (strcasecmp(opt, "permit-pty") == 0)
2023                 certflags_flags |= CERTOPT_PTY;
2024         else if (strcasecmp(opt, "no-user-rc") == 0)
2025                 certflags_flags &= ~CERTOPT_USER_RC;
2026         else if (strcasecmp(opt, "permit-user-rc") == 0)
2027                 certflags_flags |= CERTOPT_USER_RC;
2028         else if (strcasecmp(opt, "touch-required") == 0)
2029                 certflags_flags &= ~CERTOPT_NO_REQUIRE_USER_PRESENCE;
2030         else if (strcasecmp(opt, "no-touch-required") == 0)
2031                 certflags_flags |= CERTOPT_NO_REQUIRE_USER_PRESENCE;
2032         else if (strcasecmp(opt, "no-verify-required") == 0)
2033                 certflags_flags &= ~CERTOPT_REQUIRE_VERIFY;
2034         else if (strcasecmp(opt, "verify-required") == 0)
2035                 certflags_flags |= CERTOPT_REQUIRE_VERIFY;
2036         else if (strncasecmp(opt, "force-command=", 14) == 0) {
2037                 val = opt + 14;
2038                 if (*val == '\0')
2039                         fatal("Empty force-command option");
2040                 if (certflags_command != NULL)
2041                         fatal("force-command already specified");
2042                 certflags_command = xstrdup(val);
2043         } else if (strncasecmp(opt, "source-address=", 15) == 0) {
2044                 val = opt + 15;
2045                 if (*val == '\0')
2046                         fatal("Empty source-address option");
2047                 if (certflags_src_addr != NULL)
2048                         fatal("source-address already specified");
2049                 if (addr_match_cidr_list(NULL, val) != 0)
2050                         fatal("Invalid source-address list");
2051                 certflags_src_addr = xstrdup(val);
2052         } else if (strncasecmp(opt, "extension:", 10) == 0 ||
2053                     (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
2054                 val = xstrdup(strchr(opt, ':') + 1);
2055                 if ((cp = strchr(val, '=')) != NULL)
2056                         *cp++ = '\0';
2057                 cert_ext_add(val, cp, iscrit);
2058                 free(val);
2059         } else
2060                 fatal("Unsupported certificate option \"%s\"", opt);
2061 }
2062
2063 static void
2064 show_options(struct sshbuf *optbuf, int in_critical)
2065 {
2066         char *name, *arg, *hex;
2067         struct sshbuf *options, *option = NULL;
2068         int r;
2069
2070         if ((options = sshbuf_fromb(optbuf)) == NULL)
2071                 fatal_f("sshbuf_fromb failed");
2072         while (sshbuf_len(options) != 0) {
2073                 sshbuf_free(option);
2074                 option = NULL;
2075                 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
2076                     (r = sshbuf_froms(options, &option)) != 0)
2077                         fatal_fr(r, "parse option");
2078                 printf("                %s", name);
2079                 if (!in_critical &&
2080                     (strcmp(name, "permit-X11-forwarding") == 0 ||
2081                     strcmp(name, "permit-agent-forwarding") == 0 ||
2082                     strcmp(name, "permit-port-forwarding") == 0 ||
2083                     strcmp(name, "permit-pty") == 0 ||
2084                     strcmp(name, "permit-user-rc") == 0 ||
2085                     strcmp(name, "no-touch-required") == 0)) {
2086                         printf("\n");
2087                 } else if (in_critical &&
2088                     (strcmp(name, "force-command") == 0 ||
2089                     strcmp(name, "source-address") == 0)) {
2090                         if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
2091                                 fatal_fr(r, "parse critical");
2092                         printf(" %s\n", arg);
2093                         free(arg);
2094                 } else if (in_critical &&
2095                     strcmp(name, "verify-required") == 0) {
2096                         printf("\n");
2097                 } else if (sshbuf_len(option) > 0) {
2098                         hex = sshbuf_dtob16(option);
2099                         printf(" UNKNOWN OPTION: %s (len %zu)\n",
2100                             hex, sshbuf_len(option));
2101                         sshbuf_reset(option);
2102                         free(hex);
2103                 } else
2104                         printf(" UNKNOWN FLAG OPTION\n");
2105                 free(name);
2106                 if (sshbuf_len(option) != 0)
2107                         fatal("Option corrupt: extra data at end");
2108         }
2109         sshbuf_free(option);
2110         sshbuf_free(options);
2111 }
2112
2113 static void
2114 print_cert(struct sshkey *key)
2115 {
2116         char valid[64], *key_fp, *ca_fp;
2117         u_int i;
2118
2119         key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
2120         ca_fp = sshkey_fingerprint(key->cert->signature_key,
2121             fingerprint_hash, SSH_FP_DEFAULT);
2122         if (key_fp == NULL || ca_fp == NULL)
2123                 fatal_f("sshkey_fingerprint fail");
2124         sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
2125
2126         printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
2127             sshkey_cert_type(key));
2128         printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
2129         printf("        Signing CA: %s %s (using %s)\n",
2130             sshkey_type(key->cert->signature_key), ca_fp,
2131             key->cert->signature_type);
2132         printf("        Key ID: \"%s\"\n", key->cert->key_id);
2133         printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
2134         printf("        Valid: %s\n", valid);
2135         printf("        Principals: ");
2136         if (key->cert->nprincipals == 0)
2137                 printf("(none)\n");
2138         else {
2139                 for (i = 0; i < key->cert->nprincipals; i++)
2140                         printf("\n                %s",
2141                             key->cert->principals[i]);
2142                 printf("\n");
2143         }
2144         printf("        Critical Options: ");
2145         if (sshbuf_len(key->cert->critical) == 0)
2146                 printf("(none)\n");
2147         else {
2148                 printf("\n");
2149                 show_options(key->cert->critical, 1);
2150         }
2151         printf("        Extensions: ");
2152         if (sshbuf_len(key->cert->extensions) == 0)
2153                 printf("(none)\n");
2154         else {
2155                 printf("\n");
2156                 show_options(key->cert->extensions, 0);
2157         }
2158 }
2159
2160 static void
2161 do_show_cert(struct passwd *pw)
2162 {
2163         struct sshkey *key = NULL;
2164         struct stat st;
2165         int r, is_stdin = 0, ok = 0;
2166         FILE *f;
2167         char *cp, *line = NULL;
2168         const char *path;
2169         size_t linesize = 0;
2170         u_long lnum = 0;
2171
2172         if (!have_identity)
2173                 ask_filename(pw, "Enter file in which the key is");
2174         if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) == -1)
2175                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2176
2177         path = identity_file;
2178         if (strcmp(path, "-") == 0) {
2179                 f = stdin;
2180                 path = "(stdin)";
2181                 is_stdin = 1;
2182         } else if ((f = fopen(identity_file, "r")) == NULL)
2183                 fatal("fopen %s: %s", identity_file, strerror(errno));
2184
2185         while (getline(&line, &linesize, f) != -1) {
2186                 lnum++;
2187                 sshkey_free(key);
2188                 key = NULL;
2189                 /* Trim leading space and comments */
2190                 cp = line + strspn(line, " \t");
2191                 if (*cp == '#' || *cp == '\0')
2192                         continue;
2193                 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2194                         fatal("sshkey_new");
2195                 if ((r = sshkey_read(key, &cp)) != 0) {
2196                         error_r(r, "%s:%lu: invalid key", path, lnum);
2197                         continue;
2198                 }
2199                 if (!sshkey_is_cert(key)) {
2200                         error("%s:%lu is not a certificate", path, lnum);
2201                         continue;
2202                 }
2203                 ok = 1;
2204                 if (!is_stdin && lnum == 1)
2205                         printf("%s:\n", path);
2206                 else
2207                         printf("%s:%lu:\n", path, lnum);
2208                 print_cert(key);
2209         }
2210         free(line);
2211         sshkey_free(key);
2212         fclose(f);
2213         exit(ok ? 0 : 1);
2214 }
2215
2216 static void
2217 load_krl(const char *path, struct ssh_krl **krlp)
2218 {
2219         struct sshbuf *krlbuf;
2220         int r;
2221
2222         if ((r = sshbuf_load_file(path, &krlbuf)) != 0)
2223                 fatal_r(r, "Unable to load KRL %s", path);
2224         /* XXX check sigs */
2225         if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2226             *krlp == NULL)
2227                 fatal_r(r, "Invalid KRL file %s", path);
2228         sshbuf_free(krlbuf);
2229 }
2230
2231 static void
2232 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2233     const char *file, u_long lnum)
2234 {
2235         char *tmp;
2236         size_t tlen;
2237         struct sshbuf *b;
2238         int r;
2239
2240         if (strncmp(cp, "SHA256:", 7) != 0)
2241                 fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2242         cp += 7;
2243
2244         /*
2245          * OpenSSH base64 hashes omit trailing '='
2246          * characters; put them back for decode.
2247          */
2248         tlen = strlen(cp);
2249         tmp = xmalloc(tlen + 4 + 1);
2250         strlcpy(tmp, cp, tlen + 1);
2251         while ((tlen % 4) != 0) {
2252                 tmp[tlen++] = '=';
2253                 tmp[tlen] = '\0';
2254         }
2255         if ((b = sshbuf_new()) == NULL)
2256                 fatal_f("sshbuf_new failed");
2257         if ((r = sshbuf_b64tod(b, tmp)) != 0)
2258                 fatal_r(r, "%s:%lu: decode hash failed", file, lnum);
2259         free(tmp);
2260         *lenp = sshbuf_len(b);
2261         *blobp = xmalloc(*lenp);
2262         memcpy(*blobp, sshbuf_ptr(b), *lenp);
2263         sshbuf_free(b);
2264 }
2265
2266 static void
2267 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2268     const struct sshkey *ca, struct ssh_krl *krl)
2269 {
2270         struct sshkey *key = NULL;
2271         u_long lnum = 0;
2272         char *path, *cp, *ep, *line = NULL;
2273         u_char *blob = NULL;
2274         size_t blen = 0, linesize = 0;
2275         unsigned long long serial, serial2;
2276         int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2277         FILE *krl_spec;
2278
2279         path = tilde_expand_filename(file, pw->pw_uid);
2280         if (strcmp(path, "-") == 0) {
2281                 krl_spec = stdin;
2282                 free(path);
2283                 path = xstrdup("(standard input)");
2284         } else if ((krl_spec = fopen(path, "r")) == NULL)
2285                 fatal("fopen %s: %s", path, strerror(errno));
2286
2287         if (!quiet)
2288                 printf("Revoking from %s\n", path);
2289         while (getline(&line, &linesize, krl_spec) != -1) {
2290                 lnum++;
2291                 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2292                 cp = line + strspn(line, " \t");
2293                 /* Trim trailing space, comments and strip \n */
2294                 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2295                         if (cp[i] == '#' || cp[i] == '\n') {
2296                                 cp[i] = '\0';
2297                                 break;
2298                         }
2299                         if (cp[i] == ' ' || cp[i] == '\t') {
2300                                 /* Remember the start of a span of whitespace */
2301                                 if (r == -1)
2302                                         r = i;
2303                         } else
2304                                 r = -1;
2305                 }
2306                 if (r != -1)
2307                         cp[r] = '\0';
2308                 if (*cp == '\0')
2309                         continue;
2310                 if (strncasecmp(cp, "serial:", 7) == 0) {
2311                         if (ca == NULL && !wild_ca) {
2312                                 fatal("revoking certificates by serial number "
2313                                     "requires specification of a CA key");
2314                         }
2315                         cp += 7;
2316                         cp = cp + strspn(cp, " \t");
2317                         errno = 0;
2318                         serial = strtoull(cp, &ep, 0);
2319                         if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2320                                 fatal("%s:%lu: invalid serial \"%s\"",
2321                                     path, lnum, cp);
2322                         if (errno == ERANGE && serial == ULLONG_MAX)
2323                                 fatal("%s:%lu: serial out of range",
2324                                     path, lnum);
2325                         serial2 = serial;
2326                         if (*ep == '-') {
2327                                 cp = ep + 1;
2328                                 errno = 0;
2329                                 serial2 = strtoull(cp, &ep, 0);
2330                                 if (*cp == '\0' || *ep != '\0')
2331                                         fatal("%s:%lu: invalid serial \"%s\"",
2332                                             path, lnum, cp);
2333                                 if (errno == ERANGE && serial2 == ULLONG_MAX)
2334                                         fatal("%s:%lu: serial out of range",
2335                                             path, lnum);
2336                                 if (serial2 <= serial)
2337                                         fatal("%s:%lu: invalid serial range "
2338                                             "%llu:%llu", path, lnum,
2339                                             (unsigned long long)serial,
2340                                             (unsigned long long)serial2);
2341                         }
2342                         if (ssh_krl_revoke_cert_by_serial_range(krl,
2343                             ca, serial, serial2) != 0) {
2344                                 fatal_f("revoke serial failed");
2345                         }
2346                 } else if (strncasecmp(cp, "id:", 3) == 0) {
2347                         if (ca == NULL && !wild_ca) {
2348                                 fatal("revoking certificates by key ID "
2349                                     "requires specification of a CA key");
2350                         }
2351                         cp += 3;
2352                         cp = cp + strspn(cp, " \t");
2353                         if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2354                                 fatal_f("revoke key ID failed");
2355                 } else if (strncasecmp(cp, "hash:", 5) == 0) {
2356                         cp += 5;
2357                         cp = cp + strspn(cp, " \t");
2358                         hash_to_blob(cp, &blob, &blen, file, lnum);
2359                         r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2360                         if (r != 0)
2361                                 fatal_fr(r, "revoke key failed");
2362                 } else {
2363                         if (strncasecmp(cp, "key:", 4) == 0) {
2364                                 cp += 4;
2365                                 cp = cp + strspn(cp, " \t");
2366                                 was_explicit_key = 1;
2367                         } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2368                                 cp += 5;
2369                                 cp = cp + strspn(cp, " \t");
2370                                 was_sha1 = 1;
2371                         } else if (strncasecmp(cp, "sha256:", 7) == 0) {
2372                                 cp += 7;
2373                                 cp = cp + strspn(cp, " \t");
2374                                 was_sha256 = 1;
2375                                 /*
2376                                  * Just try to process the line as a key.
2377                                  * Parsing will fail if it isn't.
2378                                  */
2379                         }
2380                         if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2381                                 fatal("sshkey_new");
2382                         if ((r = sshkey_read(key, &cp)) != 0)
2383                                 fatal_r(r, "%s:%lu: invalid key", path, lnum);
2384                         if (was_explicit_key)
2385                                 r = ssh_krl_revoke_key_explicit(krl, key);
2386                         else if (was_sha1) {
2387                                 if (sshkey_fingerprint_raw(key,
2388                                     SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2389                                         fatal("%s:%lu: fingerprint failed",
2390                                             file, lnum);
2391                                 }
2392                                 r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2393                         } else if (was_sha256) {
2394                                 if (sshkey_fingerprint_raw(key,
2395                                     SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2396                                         fatal("%s:%lu: fingerprint failed",
2397                                             file, lnum);
2398                                 }
2399                                 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2400                         } else
2401                                 r = ssh_krl_revoke_key(krl, key);
2402                         if (r != 0)
2403                                 fatal_fr(r, "revoke key failed");
2404                         freezero(blob, blen);
2405                         blob = NULL;
2406                         blen = 0;
2407                         sshkey_free(key);
2408                 }
2409         }
2410         if (strcmp(path, "-") != 0)
2411                 fclose(krl_spec);
2412         free(line);
2413         free(path);
2414 }
2415
2416 static void
2417 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2418     unsigned long long krl_version, const char *krl_comment,
2419     int argc, char **argv)
2420 {
2421         struct ssh_krl *krl;
2422         struct stat sb;
2423         struct sshkey *ca = NULL;
2424         int i, r, wild_ca = 0;
2425         char *tmp;
2426         struct sshbuf *kbuf;
2427
2428         if (*identity_file == '\0')
2429                 fatal("KRL generation requires an output file");
2430         if (stat(identity_file, &sb) == -1) {
2431                 if (errno != ENOENT)
2432                         fatal("Cannot access KRL \"%s\": %s",
2433                             identity_file, strerror(errno));
2434                 if (updating)
2435                         fatal("KRL \"%s\" does not exist", identity_file);
2436         }
2437         if (ca_key_path != NULL) {
2438                 if (strcasecmp(ca_key_path, "none") == 0)
2439                         wild_ca = 1;
2440                 else {
2441                         tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2442                         if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2443                                 fatal_r(r, "Cannot load CA public key %s", tmp);
2444                         free(tmp);
2445                 }
2446         }
2447
2448         if (updating)
2449                 load_krl(identity_file, &krl);
2450         else if ((krl = ssh_krl_init()) == NULL)
2451                 fatal("couldn't create KRL");
2452
2453         if (krl_version != 0)
2454                 ssh_krl_set_version(krl, krl_version);
2455         if (krl_comment != NULL)
2456                 ssh_krl_set_comment(krl, krl_comment);
2457
2458         for (i = 0; i < argc; i++)
2459                 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2460
2461         if ((kbuf = sshbuf_new()) == NULL)
2462                 fatal("sshbuf_new failed");
2463         if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2464                 fatal("Couldn't generate KRL");
2465         if ((r = sshbuf_write_file(identity_file, kbuf)) != 0)
2466                 fatal("write %s: %s", identity_file, strerror(errno));
2467         sshbuf_free(kbuf);
2468         ssh_krl_free(krl);
2469         sshkey_free(ca);
2470 }
2471
2472 static void
2473 do_check_krl(struct passwd *pw, int print_krl, int argc, char **argv)
2474 {
2475         int i, r, ret = 0;
2476         char *comment;
2477         struct ssh_krl *krl;
2478         struct sshkey *k;
2479
2480         if (*identity_file == '\0')
2481                 fatal("KRL checking requires an input file");
2482         load_krl(identity_file, &krl);
2483         if (print_krl)
2484                 krl_dump(krl, stdout);
2485         for (i = 0; i < argc; i++) {
2486                 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2487                         fatal_r(r, "Cannot load public key %s", argv[i]);
2488                 r = ssh_krl_check_key(krl, k);
2489                 printf("%s%s%s%s: %s\n", argv[i],
2490                     *comment ? " (" : "", comment, *comment ? ")" : "",
2491                     r == 0 ? "ok" : "REVOKED");
2492                 if (r != 0)
2493                         ret = 1;
2494                 sshkey_free(k);
2495                 free(comment);
2496         }
2497         ssh_krl_free(krl);
2498         exit(ret);
2499 }
2500
2501 static struct sshkey *
2502 load_sign_key(const char *keypath, const struct sshkey *pubkey)
2503 {
2504         size_t i, slen, plen = strlen(keypath);
2505         char *privpath = xstrdup(keypath);
2506         static const char * const suffixes[] = { "-cert.pub", ".pub", NULL };
2507         struct sshkey *ret = NULL, *privkey = NULL;
2508         int r, waspub = 0;
2509         struct stat st;
2510
2511         /*
2512          * If passed a public key filename, then try to locate the corresponding
2513          * private key. This lets us specify certificates on the command-line
2514          * and have ssh-keygen find the appropriate private key.
2515          */
2516         for (i = 0; suffixes[i]; i++) {
2517                 slen = strlen(suffixes[i]);
2518                 if (plen <= slen ||
2519                     strcmp(privpath + plen - slen, suffixes[i]) != 0)
2520                         continue;
2521                 privpath[plen - slen] = '\0';
2522                 debug_f("%s looks like a public key, using private key "
2523                     "path %s instead", keypath, privpath);
2524                 waspub = 1;
2525         }
2526         if (waspub && stat(privpath, &st) != 0 && errno == ENOENT)
2527                 fatal("No private key found for public key \"%s\"", keypath);
2528         if ((r = sshkey_load_private(privpath, "", &privkey, NULL)) != 0 &&
2529             (r != SSH_ERR_KEY_WRONG_PASSPHRASE)) {
2530                 debug_fr(r, "load private key \"%s\"", privpath);
2531                 fatal("No private key found for \"%s\"", privpath);
2532         } else if (privkey == NULL)
2533                 privkey = load_identity(privpath, NULL);
2534
2535         if (!sshkey_equal_public(pubkey, privkey)) {
2536                 error("Public key %s doesn't match private %s",
2537                     keypath, privpath);
2538                 goto done;
2539         }
2540         if (sshkey_is_cert(pubkey) && !sshkey_is_cert(privkey)) {
2541                 /*
2542                  * Graft the certificate onto the private key to make
2543                  * it capable of signing.
2544                  */
2545                 if ((r = sshkey_to_certified(privkey)) != 0) {
2546                         error_fr(r, "sshkey_to_certified");
2547                         goto done;
2548                 }
2549                 if ((r = sshkey_cert_copy(pubkey, privkey)) != 0) {
2550                         error_fr(r, "sshkey_cert_copy");
2551                         goto done;
2552                 }
2553         }
2554         /* success */
2555         ret = privkey;
2556         privkey = NULL;
2557  done:
2558         sshkey_free(privkey);
2559         free(privpath);
2560         return ret;
2561 }
2562
2563 static int
2564 sign_one(struct sshkey *signkey, const char *filename, int fd,
2565     const char *sig_namespace, const char *hashalg, sshsig_signer *signer,
2566     void *signer_ctx)
2567 {
2568         struct sshbuf *sigbuf = NULL, *abuf = NULL;
2569         int r = SSH_ERR_INTERNAL_ERROR, wfd = -1, oerrno;
2570         char *wfile = NULL, *asig = NULL, *fp = NULL;
2571         char *pin = NULL, *prompt = NULL;
2572
2573         if (!quiet) {
2574                 if (fd == STDIN_FILENO)
2575                         fprintf(stderr, "Signing data on standard input\n");
2576                 else
2577                         fprintf(stderr, "Signing file %s\n", filename);
2578         }
2579         if (signer == NULL && sshkey_is_sk(signkey)) {
2580                 if ((signkey->sk_flags & SSH_SK_USER_VERIFICATION_REQD)) {
2581                         xasprintf(&prompt, "Enter PIN for %s key: ",
2582                             sshkey_type(signkey));
2583                         if ((pin = read_passphrase(prompt,
2584                             RP_ALLOW_STDIN)) == NULL)
2585                                 fatal_f("couldn't read PIN");
2586                 }
2587                 if ((signkey->sk_flags & SSH_SK_USER_PRESENCE_REQD)) {
2588                         if ((fp = sshkey_fingerprint(signkey, fingerprint_hash,
2589                             SSH_FP_DEFAULT)) == NULL)
2590                                 fatal_f("fingerprint failed");
2591                         fprintf(stderr, "Confirm user presence for key %s %s\n",
2592                             sshkey_type(signkey), fp);
2593                         free(fp);
2594                 }
2595         }
2596         if ((r = sshsig_sign_fd(signkey, hashalg, sk_provider, pin,
2597             fd, sig_namespace, &sigbuf, signer, signer_ctx)) != 0) {
2598                 error_r(r, "Signing %s failed", filename);
2599                 goto out;
2600         }
2601         if ((r = sshsig_armor(sigbuf, &abuf)) != 0) {
2602                 error_fr(r, "sshsig_armor");
2603                 goto out;
2604         }
2605         if ((asig = sshbuf_dup_string(abuf)) == NULL) {
2606                 error_f("buffer error");
2607                 r = SSH_ERR_ALLOC_FAIL;
2608                 goto out;
2609         }
2610
2611         if (fd == STDIN_FILENO) {
2612                 fputs(asig, stdout);
2613                 fflush(stdout);
2614         } else {
2615                 xasprintf(&wfile, "%s.sig", filename);
2616                 if (confirm_overwrite(wfile)) {
2617                         if ((wfd = open(wfile, O_WRONLY|O_CREAT|O_TRUNC,
2618                             0666)) == -1) {
2619                                 oerrno = errno;
2620                                 error("Cannot open %s: %s",
2621                                     wfile, strerror(errno));
2622                                 errno = oerrno;
2623                                 r = SSH_ERR_SYSTEM_ERROR;
2624                                 goto out;
2625                         }
2626                         if (atomicio(vwrite, wfd, asig,
2627                             strlen(asig)) != strlen(asig)) {
2628                                 oerrno = errno;
2629                                 error("Cannot write to %s: %s",
2630                                     wfile, strerror(errno));
2631                                 errno = oerrno;
2632                                 r = SSH_ERR_SYSTEM_ERROR;
2633                                 goto out;
2634                         }
2635                         if (!quiet) {
2636                                 fprintf(stderr, "Write signature to %s\n",
2637                                     wfile);
2638                         }
2639                 }
2640         }
2641         /* success */
2642         r = 0;
2643  out:
2644         free(wfile);
2645         free(prompt);
2646         free(asig);
2647         if (pin != NULL)
2648                 freezero(pin, strlen(pin));
2649         sshbuf_free(abuf);
2650         sshbuf_free(sigbuf);
2651         if (wfd != -1)
2652                 close(wfd);
2653         return r;
2654 }
2655
2656 static int
2657 sig_process_opts(char * const *opts, size_t nopts, char **hashalgp,
2658     uint64_t *verify_timep, int *print_pubkey)
2659 {
2660         size_t i;
2661         time_t now;
2662
2663         if (verify_timep != NULL)
2664                 *verify_timep = 0;
2665         if (print_pubkey != NULL)
2666                 *print_pubkey = 0;
2667         if (hashalgp != NULL)
2668                 *hashalgp = NULL;
2669         for (i = 0; i < nopts; i++) {
2670                 if (hashalgp != NULL &&
2671                     strncasecmp(opts[i], "hashalg=", 8) == 0) {
2672                         *hashalgp = xstrdup(opts[i] + 8);
2673                 } else if (verify_timep &&
2674                     strncasecmp(opts[i], "verify-time=", 12) == 0) {
2675                         if (parse_absolute_time(opts[i] + 12,
2676                             verify_timep) != 0 || *verify_timep == 0) {
2677                                 error("Invalid \"verify-time\" option");
2678                                 return SSH_ERR_INVALID_ARGUMENT;
2679                         }
2680                 } else if (print_pubkey &&
2681                     strcasecmp(opts[i], "print-pubkey") == 0) {
2682                         *print_pubkey = 1;
2683                 } else {
2684                         error("Invalid option \"%s\"", opts[i]);
2685                         return SSH_ERR_INVALID_ARGUMENT;
2686                 }
2687         }
2688         if (verify_timep && *verify_timep == 0) {
2689                 if ((now = time(NULL)) < 0) {
2690                         error("Time is before epoch");
2691                         return SSH_ERR_INVALID_ARGUMENT;
2692                 }
2693                 *verify_timep = (uint64_t)now;
2694         }
2695         return 0;
2696 }
2697
2698
2699 static int
2700 sig_sign(const char *keypath, const char *sig_namespace, int require_agent,
2701     int argc, char **argv, char * const *opts, size_t nopts)
2702 {
2703         int i, fd = -1, r, ret = -1;
2704         int agent_fd = -1;
2705         struct sshkey *pubkey = NULL, *privkey = NULL, *signkey = NULL;
2706         sshsig_signer *signer = NULL;
2707         char *hashalg = NULL;
2708
2709         /* Check file arguments. */
2710         for (i = 0; i < argc; i++) {
2711                 if (strcmp(argv[i], "-") != 0)
2712                         continue;
2713                 if (i > 0 || argc > 1)
2714                         fatal("Cannot sign mix of paths and standard input");
2715         }
2716
2717         if (sig_process_opts(opts, nopts, &hashalg, NULL, NULL) != 0)
2718                 goto done; /* error already logged */
2719
2720         if ((r = sshkey_load_public(keypath, &pubkey, NULL)) != 0) {
2721                 error_r(r, "Couldn't load public key %s", keypath);
2722                 goto done;
2723         }
2724
2725         if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) {
2726                 if (require_agent)
2727                         fatal("Couldn't get agent socket");
2728                 debug_r(r, "Couldn't get agent socket");
2729         } else {
2730                 if ((r = ssh_agent_has_key(agent_fd, pubkey)) == 0)
2731                         signer = agent_signer;
2732                 else {
2733                         if (require_agent)
2734                                 fatal("Couldn't find key in agent");
2735                         debug_r(r, "Couldn't find key in agent");
2736                 }
2737         }
2738
2739         if (signer == NULL) {
2740                 /* Not using agent - try to load private key */
2741                 if ((privkey = load_sign_key(keypath, pubkey)) == NULL)
2742                         goto done;
2743                 signkey = privkey;
2744         } else {
2745                 /* Will use key in agent */
2746                 signkey = pubkey;
2747         }
2748
2749         if (argc == 0) {
2750                 if ((r = sign_one(signkey, "(stdin)", STDIN_FILENO,
2751                     sig_namespace, hashalg, signer, &agent_fd)) != 0)
2752                         goto done;
2753         } else {
2754                 for (i = 0; i < argc; i++) {
2755                         if (strcmp(argv[i], "-") == 0)
2756                                 fd = STDIN_FILENO;
2757                         else if ((fd = open(argv[i], O_RDONLY)) == -1) {
2758                                 error("Cannot open %s for signing: %s",
2759                                     argv[i], strerror(errno));
2760                                 goto done;
2761                         }
2762                         if ((r = sign_one(signkey, argv[i], fd, sig_namespace,
2763                             hashalg, signer, &agent_fd)) != 0)
2764                                 goto done;
2765                         if (fd != STDIN_FILENO)
2766                                 close(fd);
2767                         fd = -1;
2768                 }
2769         }
2770
2771         ret = 0;
2772 done:
2773         if (fd != -1 && fd != STDIN_FILENO)
2774                 close(fd);
2775         sshkey_free(pubkey);
2776         sshkey_free(privkey);
2777         free(hashalg);
2778         return ret;
2779 }
2780
2781 static int
2782 sig_verify(const char *signature, const char *sig_namespace,
2783     const char *principal, const char *allowed_keys, const char *revoked_keys,
2784     char * const *opts, size_t nopts)
2785 {
2786         int r, ret = -1;
2787         int print_pubkey = 0;
2788         struct sshbuf *sigbuf = NULL, *abuf = NULL;
2789         struct sshkey *sign_key = NULL;
2790         char *fp = NULL;
2791         struct sshkey_sig_details *sig_details = NULL;
2792         uint64_t verify_time = 0;
2793
2794         if (sig_process_opts(opts, nopts, NULL, &verify_time,
2795             &print_pubkey) != 0)
2796                 goto done; /* error already logged */
2797
2798         memset(&sig_details, 0, sizeof(sig_details));
2799         if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2800                 error_r(r, "Couldn't read signature file");
2801                 goto done;
2802         }
2803
2804         if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2805                 error_fr(r, "sshsig_armor");
2806                 goto done;
2807         }
2808         if ((r = sshsig_verify_fd(sigbuf, STDIN_FILENO, sig_namespace,
2809             &sign_key, &sig_details)) != 0)
2810                 goto done; /* sshsig_verify() prints error */
2811
2812         if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2813             SSH_FP_DEFAULT)) == NULL)
2814                 fatal_f("sshkey_fingerprint failed");
2815         debug("Valid (unverified) signature from key %s", fp);
2816         if (sig_details != NULL) {
2817                 debug2_f("signature details: counter = %u, flags = 0x%02x",
2818                     sig_details->sk_counter, sig_details->sk_flags);
2819         }
2820         free(fp);
2821         fp = NULL;
2822
2823         if (revoked_keys != NULL) {
2824                 if ((r = sshkey_check_revoked(sign_key, revoked_keys)) != 0) {
2825                         debug3_fr(r, "sshkey_check_revoked");
2826                         goto done;
2827                 }
2828         }
2829
2830         if (allowed_keys != NULL && (r = sshsig_check_allowed_keys(allowed_keys,
2831             sign_key, principal, sig_namespace, verify_time)) != 0) {
2832                 debug3_fr(r, "sshsig_check_allowed_keys");
2833                 goto done;
2834         }
2835         /* success */
2836         ret = 0;
2837 done:
2838         if (!quiet) {
2839                 if (ret == 0) {
2840                         if ((fp = sshkey_fingerprint(sign_key, fingerprint_hash,
2841                             SSH_FP_DEFAULT)) == NULL)
2842                                 fatal_f("sshkey_fingerprint failed");
2843                         if (principal == NULL) {
2844                                 printf("Good \"%s\" signature with %s key %s\n",
2845                                     sig_namespace, sshkey_type(sign_key), fp);
2846
2847                         } else {
2848                                 printf("Good \"%s\" signature for %s with %s key %s\n",
2849                                     sig_namespace, principal,
2850                                     sshkey_type(sign_key), fp);
2851                         }
2852                 } else {
2853                         printf("Could not verify signature.\n");
2854                 }
2855         }
2856         /* Print the signature key if requested */
2857         if (ret == 0 && print_pubkey && sign_key != NULL) {
2858                 if ((r = sshkey_write(sign_key, stdout)) == 0)
2859                         fputc('\n', stdout);
2860                 else {
2861                         error_r(r, "Could not print public key.\n");
2862                         ret = -1;
2863                 }
2864         }
2865         sshbuf_free(sigbuf);
2866         sshbuf_free(abuf);
2867         sshkey_free(sign_key);
2868         sshkey_sig_details_free(sig_details);
2869         free(fp);
2870         return ret;
2871 }
2872
2873 static int
2874 sig_find_principals(const char *signature, const char *allowed_keys,
2875     char * const *opts, size_t nopts)
2876 {
2877         int r, ret = -1;
2878         struct sshbuf *sigbuf = NULL, *abuf = NULL;
2879         struct sshkey *sign_key = NULL;
2880         char *principals = NULL, *cp, *tmp;
2881         uint64_t verify_time = 0;
2882
2883         if (sig_process_opts(opts, nopts, NULL, &verify_time, NULL) != 0)
2884                 goto done; /* error already logged */
2885
2886         if ((r = sshbuf_load_file(signature, &abuf)) != 0) {
2887                 error_r(r, "Couldn't read signature file");
2888                 goto done;
2889         }
2890         if ((r = sshsig_dearmor(abuf, &sigbuf)) != 0) {
2891                 error_fr(r, "sshsig_armor");
2892                 goto done;
2893         }
2894         if ((r = sshsig_get_pubkey(sigbuf, &sign_key)) != 0) {
2895                 error_fr(r, "sshsig_get_pubkey");
2896                 goto done;
2897         }
2898         if ((r = sshsig_find_principals(allowed_keys, sign_key,
2899             verify_time, &principals)) != 0) {
2900                 if (r != SSH_ERR_KEY_NOT_FOUND)
2901                         error_fr(r, "sshsig_find_principal");
2902                 goto done;
2903         }
2904         ret = 0;
2905 done:
2906         if (ret == 0 ) {
2907                 /* Emit matching principals one per line */
2908                 tmp = principals;
2909                 while ((cp = strsep(&tmp, ",")) != NULL && *cp != '\0')
2910                         puts(cp);
2911         } else {
2912                 fprintf(stderr, "No principal matched.\n");
2913         }
2914         sshbuf_free(sigbuf);
2915         sshbuf_free(abuf);
2916         sshkey_free(sign_key);
2917         free(principals);
2918         return ret;
2919 }
2920
2921 static int
2922 sig_match_principals(const char *allowed_keys, char *principal,
2923         char * const *opts, size_t nopts)
2924 {
2925         int r;
2926         char **principals = NULL;
2927         size_t i, nprincipals = 0;
2928
2929         if ((r = sig_process_opts(opts, nopts, NULL, NULL, NULL)) != 0)
2930                 return r; /* error already logged */
2931
2932         if ((r = sshsig_match_principals(allowed_keys, principal,
2933             &principals, &nprincipals)) != 0) {
2934                 debug_f("match: %s", ssh_err(r));
2935                 fprintf(stderr, "No principal matched.\n");
2936                 return r;
2937         }
2938         for (i = 0; i < nprincipals; i++) {
2939                 printf("%s\n", principals[i]);
2940                 free(principals[i]);
2941         }
2942         free(principals);
2943
2944         return 0;
2945 }
2946
2947 static void
2948 do_moduli_gen(const char *out_file, char **opts, size_t nopts)
2949 {
2950 #ifdef WITH_OPENSSL
2951         /* Moduli generation/screening */
2952         u_int32_t memory = 0;
2953         BIGNUM *start = NULL;
2954         int moduli_bits = 0;
2955         FILE *out;
2956         size_t i;
2957         const char *errstr;
2958
2959         /* Parse options */
2960         for (i = 0; i < nopts; i++) {
2961                 if (strncmp(opts[i], "memory=", 7) == 0) {
2962                         memory = (u_int32_t)strtonum(opts[i]+7, 1,
2963                             UINT_MAX, &errstr);
2964                         if (errstr) {
2965                                 fatal("Memory limit is %s: %s",
2966                                     errstr, opts[i]+7);
2967                         }
2968                 } else if (strncmp(opts[i], "start=", 6) == 0) {
2969                         /* XXX - also compare length against bits */
2970                         if (BN_hex2bn(&start, opts[i]+6) == 0)
2971                                 fatal("Invalid start point.");
2972                 } else if (strncmp(opts[i], "bits=", 5) == 0) {
2973                         moduli_bits = (int)strtonum(opts[i]+5, 1,
2974                             INT_MAX, &errstr);
2975                         if (errstr) {
2976                                 fatal("Invalid number: %s (%s)",
2977                                         opts[i]+12, errstr);
2978                         }
2979                 } else {
2980                         fatal("Option \"%s\" is unsupported for moduli "
2981                             "generation", opts[i]);
2982                 }
2983         }
2984
2985         if ((out = fopen(out_file, "w")) == NULL) {
2986                 fatal("Couldn't open modulus candidate file \"%s\": %s",
2987                     out_file, strerror(errno));
2988         }
2989         setvbuf(out, NULL, _IOLBF, 0);
2990
2991         if (moduli_bits == 0)
2992                 moduli_bits = DEFAULT_BITS;
2993         if (gen_candidates(out, memory, moduli_bits, start) != 0)
2994                 fatal("modulus candidate generation failed");
2995 #else /* WITH_OPENSSL */
2996         fatal("Moduli generation is not supported");
2997 #endif /* WITH_OPENSSL */
2998 }
2999
3000 static void
3001 do_moduli_screen(const char *out_file, char **opts, size_t nopts)
3002 {
3003 #ifdef WITH_OPENSSL
3004         /* Moduli generation/screening */
3005         char *checkpoint = NULL;
3006         u_int32_t generator_wanted = 0;
3007         unsigned long start_lineno = 0, lines_to_process = 0;
3008         int prime_tests = 0;
3009         FILE *out, *in = stdin;
3010         size_t i;
3011         const char *errstr;
3012
3013         /* Parse options */
3014         for (i = 0; i < nopts; i++) {
3015                 if (strncmp(opts[i], "lines=", 6) == 0) {
3016                         lines_to_process = strtoul(opts[i]+6, NULL, 10);
3017                 } else if (strncmp(opts[i], "start-line=", 11) == 0) {
3018                         start_lineno = strtoul(opts[i]+11, NULL, 10);
3019                 } else if (strncmp(opts[i], "checkpoint=", 11) == 0) {
3020                         free(checkpoint);
3021                         checkpoint = xstrdup(opts[i]+11);
3022                 } else if (strncmp(opts[i], "generator=", 10) == 0) {
3023                         generator_wanted = (u_int32_t)strtonum(
3024                             opts[i]+10, 1, UINT_MAX, &errstr);
3025                         if (errstr != NULL) {
3026                                 fatal("Generator invalid: %s (%s)",
3027                                     opts[i]+10, errstr);
3028                         }
3029                 } else if (strncmp(opts[i], "prime-tests=", 12) == 0) {
3030                         prime_tests = (int)strtonum(opts[i]+12, 1,
3031                             INT_MAX, &errstr);
3032                         if (errstr) {
3033                                 fatal("Invalid number: %s (%s)",
3034                                         opts[i]+12, errstr);
3035                         }
3036                 } else {
3037                         fatal("Option \"%s\" is unsupported for moduli "
3038                             "screening", opts[i]);
3039                 }
3040         }
3041
3042         if (have_identity && strcmp(identity_file, "-") != 0) {
3043                 if ((in = fopen(identity_file, "r")) == NULL) {
3044                         fatal("Couldn't open modulus candidate "
3045                             "file \"%s\": %s", identity_file,
3046                             strerror(errno));
3047                 }
3048         }
3049
3050         if ((out = fopen(out_file, "a")) == NULL) {
3051                 fatal("Couldn't open moduli file \"%s\": %s",
3052                     out_file, strerror(errno));
3053         }
3054         setvbuf(out, NULL, _IOLBF, 0);
3055         if (prime_test(in, out, prime_tests == 0 ? 100 : prime_tests,
3056             generator_wanted, checkpoint,
3057             start_lineno, lines_to_process) != 0)
3058                 fatal("modulus screening failed");
3059         if (in != stdin)
3060                 (void)fclose(in);
3061         free(checkpoint);
3062 #else /* WITH_OPENSSL */
3063         fatal("Moduli screening is not supported");
3064 #endif /* WITH_OPENSSL */
3065 }
3066
3067 /* Read and confirm a passphrase */
3068 static char *
3069 read_check_passphrase(const char *prompt1, const char *prompt2,
3070     const char *retry_prompt)
3071 {
3072         char *passphrase1, *passphrase2;
3073
3074         for (;;) {
3075                 passphrase1 = read_passphrase(prompt1, RP_ALLOW_STDIN);
3076                 passphrase2 = read_passphrase(prompt2, RP_ALLOW_STDIN);
3077                 if (strcmp(passphrase1, passphrase2) == 0) {
3078                         freezero(passphrase2, strlen(passphrase2));
3079                         return passphrase1;
3080                 }
3081                 /* The passphrases do not match. Clear them and retry. */
3082                 freezero(passphrase1, strlen(passphrase1));
3083                 freezero(passphrase2, strlen(passphrase2));
3084                 fputs(retry_prompt, stdout);
3085                 fputc('\n', stdout);
3086                 fflush(stdout);
3087         }
3088         /* NOTREACHED */
3089         return NULL;
3090 }
3091
3092 static char *
3093 private_key_passphrase(void)
3094 {
3095         if (identity_passphrase)
3096                 return xstrdup(identity_passphrase);
3097         if (identity_new_passphrase)
3098                 return xstrdup(identity_new_passphrase);
3099
3100         return read_check_passphrase(
3101             "Enter passphrase (empty for no passphrase): ",
3102             "Enter same passphrase again: ",
3103             "Passphrases do not match.  Try again.");
3104 }
3105
3106 static char *
3107 sk_suffix(const char *application, const uint8_t *user, size_t userlen)
3108 {
3109         char *ret, *cp;
3110         size_t slen, i;
3111
3112         /* Trim off URL-like preamble */
3113         if (strncmp(application, "ssh://", 6) == 0)
3114                 ret =  xstrdup(application + 6);
3115         else if (strncmp(application, "ssh:", 4) == 0)
3116                 ret =  xstrdup(application + 4);
3117         else
3118                 ret = xstrdup(application);
3119
3120         /* Count trailing zeros in user */
3121         for (i = 0; i < userlen; i++) {
3122                 if (user[userlen - i - 1] != 0)
3123                         break;
3124         }
3125         if (i >= userlen)
3126                 return ret; /* user-id was default all-zeros */
3127
3128         /* Append user-id, escaping non-UTF-8 characters */
3129         slen = userlen - i;
3130         if (asmprintf(&cp, INT_MAX, NULL, "%.*s", (int)slen, user) == -1)
3131                 fatal_f("asmprintf failed");
3132         /* Don't emit a user-id that contains path or control characters */
3133         if (strchr(cp, '/') != NULL || strstr(cp, "..") != NULL ||
3134             strchr(cp, '\\') != NULL) {
3135                 free(cp);
3136                 cp = tohex(user, slen);
3137         }
3138         xextendf(&ret, "_", "%s", cp);
3139         free(cp);
3140         return ret;
3141 }
3142
3143 static int
3144 do_download_sk(const char *skprovider, const char *device)
3145 {
3146         struct sshsk_resident_key **srks;
3147         size_t nsrks, i;
3148         int r, ret = -1;
3149         char *fp, *pin = NULL, *pass = NULL, *path, *pubpath;
3150         const char *ext;
3151         struct sshkey *key;
3152
3153         if (skprovider == NULL)
3154                 fatal("Cannot download keys without provider");
3155
3156         pin = read_passphrase("Enter PIN for authenticator: ", RP_ALLOW_STDIN);
3157         if (!quiet) {
3158                 printf("You may need to touch your authenticator "
3159                     "to authorize key download.\n");
3160         }
3161         if ((r = sshsk_load_resident(skprovider, device, pin, 0,
3162             &srks, &nsrks)) != 0) {
3163                 if (pin != NULL)
3164                         freezero(pin, strlen(pin));
3165                 error_r(r, "Unable to load resident keys");
3166                 return -1;
3167         }
3168         if (nsrks == 0)
3169                 logit("No keys to download");
3170         if (pin != NULL)
3171                 freezero(pin, strlen(pin));
3172
3173         for (i = 0; i < nsrks; i++) {
3174                 key = srks[i]->key;
3175                 if (key->type != KEY_ECDSA_SK && key->type != KEY_ED25519_SK) {
3176                         error("Unsupported key type %s (%d)",
3177                             sshkey_type(key), key->type);
3178                         continue;
3179                 }
3180                 if ((fp = sshkey_fingerprint(key, fingerprint_hash,
3181                     SSH_FP_DEFAULT)) == NULL)
3182                         fatal_f("sshkey_fingerprint failed");
3183                 debug_f("key %zu: %s %s %s (flags 0x%02x)", i,
3184                     sshkey_type(key), fp, key->sk_application, key->sk_flags);
3185                 ext = sk_suffix(key->sk_application,
3186                     srks[i]->user_id, srks[i]->user_id_len);
3187                 xasprintf(&path, "id_%s_rk%s%s",
3188                     key->type == KEY_ECDSA_SK ? "ecdsa_sk" : "ed25519_sk",
3189                     *ext == '\0' ? "" : "_", ext);
3190
3191                 /* If the file already exists, ask the user to confirm. */
3192                 if (!confirm_overwrite(path)) {
3193                         free(path);
3194                         break;
3195                 }
3196
3197                 /* Save the key with the application string as the comment */
3198                 if (pass == NULL)
3199                         pass = private_key_passphrase();
3200                 if ((r = sshkey_save_private(key, path, pass,
3201                     key->sk_application, private_key_format,
3202                     openssh_format_cipher, rounds)) != 0) {
3203                         error_r(r, "Saving key \"%s\" failed", path);
3204                         free(path);
3205                         break;
3206                 }
3207                 if (!quiet) {
3208                         printf("Saved %s key%s%s to %s\n", sshkey_type(key),
3209                             *ext != '\0' ? " " : "",
3210                             *ext != '\0' ? key->sk_application : "",
3211                             path);
3212                 }
3213
3214                 /* Save public key too */
3215                 xasprintf(&pubpath, "%s.pub", path);
3216                 free(path);
3217                 if ((r = sshkey_save_public(key, pubpath,
3218                     key->sk_application)) != 0) {
3219                         error_r(r, "Saving public key \"%s\" failed", pubpath);
3220                         free(pubpath);
3221                         break;
3222                 }
3223                 free(pubpath);
3224         }
3225
3226         if (i >= nsrks)
3227                 ret = 0; /* success */
3228         if (pass != NULL)
3229                 freezero(pass, strlen(pass));
3230         sshsk_free_resident_keys(srks, nsrks);
3231         return ret;
3232 }
3233
3234 static void
3235 save_attestation(struct sshbuf *attest, const char *path)
3236 {
3237         mode_t omask;
3238         int r;
3239
3240         if (path == NULL)
3241                 return; /* nothing to do */
3242         if (attest == NULL || sshbuf_len(attest) == 0)
3243                 fatal("Enrollment did not return attestation data");
3244         omask = umask(077);
3245         r = sshbuf_write_file(path, attest);
3246         umask(omask);
3247         if (r != 0)
3248                 fatal_r(r, "Unable to write attestation data \"%s\"", path);
3249         if (!quiet)
3250                 printf("Your FIDO attestation certificate has been saved in "
3251                     "%s\n", path);
3252 }
3253
3254 static int
3255 confirm_sk_overwrite(const char *application, const char *user)
3256 {
3257         char yesno[3];
3258
3259         printf("A resident key scoped to '%s' with user id '%s' already "
3260             "exists.\n", application == NULL ? "ssh:" : application,
3261             user == NULL ? "null" : user);
3262         printf("Overwrite key in token (y/n)? ");
3263         fflush(stdout);
3264         if (fgets(yesno, sizeof(yesno), stdin) == NULL)
3265                 return 0;
3266         if (yesno[0] != 'y' && yesno[0] != 'Y')
3267                 return 0;
3268         return 1;
3269 }
3270
3271 static void
3272 usage(void)
3273 {
3274         fprintf(stderr,
3275             "usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]\n"
3276             "                  [-m format] [-N new_passphrase] [-O option]\n"
3277             "                  [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]\n"
3278             "                  [-w provider] [-Z cipher]\n"
3279             "       ssh-keygen -p [-a rounds] [-f keyfile] [-m format] [-N new_passphrase]\n"
3280             "                   [-P old_passphrase] [-Z cipher]\n"
3281 #ifdef WITH_OPENSSL
3282             "       ssh-keygen -i [-f input_keyfile] [-m key_format]\n"
3283             "       ssh-keygen -e [-f input_keyfile] [-m key_format]\n"
3284 #endif
3285             "       ssh-keygen -y [-f input_keyfile]\n"
3286             "       ssh-keygen -c [-a rounds] [-C comment] [-f keyfile] [-P passphrase]\n"
3287             "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
3288             "       ssh-keygen -B [-f input_keyfile]\n");
3289 #ifdef ENABLE_PKCS11
3290         fprintf(stderr,
3291             "       ssh-keygen -D pkcs11\n");
3292 #endif
3293         fprintf(stderr,
3294             "       ssh-keygen -F hostname [-lv] [-f known_hosts_file]\n"
3295             "       ssh-keygen -H [-f known_hosts_file]\n"
3296             "       ssh-keygen -K [-a rounds] [-w provider]\n"
3297             "       ssh-keygen -R hostname [-f known_hosts_file]\n"
3298             "       ssh-keygen -r hostname [-g] [-f input_keyfile]\n"
3299 #ifdef WITH_OPENSSL
3300             "       ssh-keygen -M generate [-O option] output_file\n"
3301             "       ssh-keygen -M screen [-f input_file] [-O option] output_file\n"
3302 #endif
3303             "       ssh-keygen -I certificate_identity -s ca_key [-hU] [-D pkcs11_provider]\n"
3304             "                  [-n principals] [-O option] [-V validity_interval]\n"
3305             "                  [-z serial_number] file ...\n"
3306             "       ssh-keygen -L [-f input_keyfile]\n"
3307             "       ssh-keygen -A [-a rounds] [-f prefix_path]\n"
3308             "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
3309             "                  file ...\n"
3310             "       ssh-keygen -Q [-l] -f krl_file [file ...]\n"
3311             "       ssh-keygen -Y find-principals -s signature_file -f allowed_signers_file\n"
3312             "       ssh-keygen -Y match-principals -I signer_identity -f allowed_signers_file\n"
3313             "       ssh-keygen -Y check-novalidate -n namespace -s signature_file\n"
3314             "       ssh-keygen -Y sign -f key_file -n namespace file [-O option] ...\n"
3315             "       ssh-keygen -Y verify -f allowed_signers_file -I signer_identity\n"
3316             "                  -n namespace -s signature_file [-r krl_file] [-O option]\n");
3317         exit(1);
3318 }
3319
3320 /*
3321  * Main program for key management.
3322  */
3323 int
3324 main(int argc, char **argv)
3325 {
3326         char comment[1024], *passphrase = NULL;
3327         char *rr_hostname = NULL, *ep, *fp, *ra;
3328         struct sshkey *private, *public;
3329         struct passwd *pw;
3330         int r, opt, type;
3331         int change_passphrase = 0, change_comment = 0, show_cert = 0;
3332         int find_host = 0, delete_host = 0, hash_hosts = 0;
3333         int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
3334         int prefer_agent = 0, convert_to = 0, convert_from = 0;
3335         int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
3336         int do_gen_candidates = 0, do_screen_candidates = 0, download_sk = 0;
3337         unsigned long long cert_serial = 0;
3338         char *identity_comment = NULL, *ca_key_path = NULL, **opts = NULL;
3339         char *sk_application = NULL, *sk_device = NULL, *sk_user = NULL;
3340         char *sk_attestation_path = NULL;
3341         struct sshbuf *challenge = NULL, *attest = NULL;
3342         size_t i, nopts = 0;
3343         u_int32_t bits = 0;
3344         uint8_t sk_flags = SSH_SK_USER_PRESENCE_REQD;
3345         const char *errstr;
3346         int log_level = SYSLOG_LEVEL_INFO;
3347         char *sign_op = NULL;
3348
3349         extern int optind;
3350         extern char *optarg;
3351
3352         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
3353         sanitise_stdfd();
3354
3355         __progname = ssh_get_progname(argv[0]);
3356
3357         seed_rng();
3358
3359         log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
3360
3361         msetlocale();
3362
3363         /* we need this for the home * directory.  */
3364         pw = getpwuid(getuid());
3365         if (!pw)
3366                 fatal("No user exists for uid %lu", (u_long)getuid());
3367         pw = pwcopy(pw);
3368         if (gethostname(hostname, sizeof(hostname)) == -1)
3369                 fatal("gethostname: %s", strerror(errno));
3370
3371         sk_provider = getenv("SSH_SK_PROVIDER");
3372
3373         /* Remaining characters: dGjJSTWx */
3374         while ((opt = getopt(argc, argv, "ABHKLQUXceghiklopquvy"
3375             "C:D:E:F:I:M:N:O:P:R:V:Y:Z:"
3376             "a:b:f:g:m:n:r:s:t:w:z:")) != -1) {
3377                 switch (opt) {
3378                 case 'A':
3379                         gen_all_hostkeys = 1;
3380                         break;
3381                 case 'b':
3382                         bits = (u_int32_t)strtonum(optarg, 1, UINT32_MAX,
3383                             &errstr);
3384                         if (errstr)
3385                                 fatal("Bits has bad value %s (%s)",
3386                                         optarg, errstr);
3387                         break;
3388                 case 'E':
3389                         fingerprint_hash = ssh_digest_alg_by_name(optarg);
3390                         if (fingerprint_hash == -1)
3391                                 fatal("Invalid hash algorithm \"%s\"", optarg);
3392                         break;
3393                 case 'F':
3394                         find_host = 1;
3395                         rr_hostname = optarg;
3396                         break;
3397                 case 'H':
3398                         hash_hosts = 1;
3399                         break;
3400                 case 'I':
3401                         cert_key_id = optarg;
3402                         break;
3403                 case 'R':
3404                         delete_host = 1;
3405                         rr_hostname = optarg;
3406                         break;
3407                 case 'L':
3408                         show_cert = 1;
3409                         break;
3410                 case 'l':
3411                         print_fingerprint = 1;
3412                         break;
3413                 case 'B':
3414                         print_bubblebabble = 1;
3415                         break;
3416                 case 'm':
3417                         if (strcasecmp(optarg, "RFC4716") == 0 ||
3418                             strcasecmp(optarg, "ssh2") == 0) {
3419                                 convert_format = FMT_RFC4716;
3420                                 break;
3421                         }
3422                         if (strcasecmp(optarg, "PKCS8") == 0) {
3423                                 convert_format = FMT_PKCS8;
3424                                 private_key_format = SSHKEY_PRIVATE_PKCS8;
3425                                 break;
3426                         }
3427                         if (strcasecmp(optarg, "PEM") == 0) {
3428                                 convert_format = FMT_PEM;
3429                                 private_key_format = SSHKEY_PRIVATE_PEM;
3430                                 break;
3431                         }
3432                         fatal("Unsupported conversion format \"%s\"", optarg);
3433                 case 'n':
3434                         cert_principals = optarg;
3435                         break;
3436                 case 'o':
3437                         /* no-op; new format is already the default */
3438                         break;
3439                 case 'p':
3440                         change_passphrase = 1;
3441                         break;
3442                 case 'c':
3443                         change_comment = 1;
3444                         break;
3445                 case 'f':
3446                         if (strlcpy(identity_file, optarg,
3447                             sizeof(identity_file)) >= sizeof(identity_file))
3448                                 fatal("Identity filename too long");
3449                         have_identity = 1;
3450                         break;
3451                 case 'g':
3452                         print_generic = 1;
3453                         break;
3454                 case 'K':
3455                         download_sk = 1;
3456                         break;
3457                 case 'P':
3458                         identity_passphrase = optarg;
3459                         break;
3460                 case 'N':
3461                         identity_new_passphrase = optarg;
3462                         break;
3463                 case 'Q':
3464                         check_krl = 1;
3465                         break;
3466                 case 'O':
3467                         opts = xrecallocarray(opts, nopts, nopts + 1,
3468                             sizeof(*opts));
3469                         opts[nopts++] = xstrdup(optarg);
3470                         break;
3471                 case 'Z':
3472                         openssh_format_cipher = optarg;
3473                         if (cipher_by_name(openssh_format_cipher) == NULL)
3474                                 fatal("Invalid OpenSSH-format cipher '%s'",
3475                                     openssh_format_cipher);
3476                         break;
3477                 case 'C':
3478                         identity_comment = optarg;
3479                         break;
3480                 case 'q':
3481                         quiet = 1;
3482                         break;
3483                 case 'e':
3484                         /* export key */
3485                         convert_to = 1;
3486                         break;
3487                 case 'h':
3488                         cert_key_type = SSH2_CERT_TYPE_HOST;
3489                         certflags_flags = 0;
3490                         break;
3491                 case 'k':
3492                         gen_krl = 1;
3493                         break;
3494                 case 'i':
3495                 case 'X':
3496                         /* import key */
3497                         convert_from = 1;
3498                         break;
3499                 case 'y':
3500                         print_public = 1;
3501                         break;
3502                 case 's':
3503                         ca_key_path = optarg;
3504                         break;
3505                 case 't':
3506                         key_type_name = optarg;
3507                         break;
3508                 case 'D':
3509                         pkcs11provider = optarg;
3510                         break;
3511                 case 'U':
3512                         prefer_agent = 1;
3513                         break;
3514                 case 'u':
3515                         update_krl = 1;
3516                         break;
3517                 case 'v':
3518                         if (log_level == SYSLOG_LEVEL_INFO)
3519                                 log_level = SYSLOG_LEVEL_DEBUG1;
3520                         else {
3521                                 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
3522                                     log_level < SYSLOG_LEVEL_DEBUG3)
3523                                         log_level++;
3524                         }
3525                         break;
3526                 case 'r':
3527                         rr_hostname = optarg;
3528                         break;
3529                 case 'a':
3530                         rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
3531                         if (errstr)
3532                                 fatal("Invalid number: %s (%s)",
3533                                         optarg, errstr);
3534                         break;
3535                 case 'V':
3536                         parse_cert_times(optarg);
3537                         break;
3538                 case 'Y':
3539                         sign_op = optarg;
3540                         break;
3541                 case 'w':
3542                         sk_provider = optarg;
3543                         break;
3544                 case 'z':
3545                         errno = 0;
3546                         if (*optarg == '+') {
3547                                 cert_serial_autoinc = 1;
3548                                 optarg++;
3549                         }
3550                         cert_serial = strtoull(optarg, &ep, 10);
3551                         if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
3552                             (errno == ERANGE && cert_serial == ULLONG_MAX))
3553                                 fatal("Invalid serial number \"%s\"", optarg);
3554                         break;
3555                 case 'M':
3556                         if (strcmp(optarg, "generate") == 0)
3557                                 do_gen_candidates = 1;
3558                         else if (strcmp(optarg, "screen") == 0)
3559                                 do_screen_candidates = 1;
3560                         else
3561                                 fatal("Unsupported moduli option %s", optarg);
3562                         break;
3563                 default:
3564                         usage();
3565                 }
3566         }
3567
3568 #ifdef ENABLE_SK_INTERNAL
3569         if (sk_provider == NULL)
3570                 sk_provider = "internal";
3571 #endif
3572
3573         /* reinit */
3574         log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
3575
3576         argv += optind;
3577         argc -= optind;
3578
3579         if (sign_op != NULL) {
3580                 if (strncmp(sign_op, "find-principals", 15) == 0) {
3581                         if (ca_key_path == NULL) {
3582                                 error("Too few arguments for find-principals:"
3583                                     "missing signature file");
3584                                 exit(1);
3585                         }
3586                         if (!have_identity) {
3587                                 error("Too few arguments for find-principals:"
3588                                     "missing allowed keys file");
3589                                 exit(1);
3590                         }
3591                         return sig_find_principals(ca_key_path, identity_file,
3592                             opts, nopts);
3593                 } else if (strncmp(sign_op, "match-principals", 16) == 0) {
3594                         if (!have_identity) {
3595                                 error("Too few arguments for match-principals:"
3596                                     "missing allowed keys file");
3597                                 exit(1);
3598                         }
3599                         if (cert_key_id == NULL) {
3600                                 error("Too few arguments for match-principals: "
3601                                     "missing principal ID");
3602                                 exit(1);
3603                         }
3604                         return sig_match_principals(identity_file, cert_key_id,
3605                             opts, nopts);
3606                 } else if (strncmp(sign_op, "sign", 4) == 0) {
3607                         /* NB. cert_principals is actually namespace, via -n */
3608                         if (cert_principals == NULL ||
3609                             *cert_principals == '\0') {
3610                                 error("Too few arguments for sign: "
3611                                     "missing namespace");
3612                                 exit(1);
3613                         }
3614                         if (!have_identity) {
3615                                 error("Too few arguments for sign: "
3616                                     "missing key");
3617                                 exit(1);
3618                         }
3619                         return sig_sign(identity_file, cert_principals,
3620                             prefer_agent, argc, argv, opts, nopts);
3621                 } else if (strncmp(sign_op, "check-novalidate", 16) == 0) {
3622                         /* NB. cert_principals is actually namespace, via -n */
3623                         if (cert_principals == NULL ||
3624                             *cert_principals == '\0') {
3625                                 error("Too few arguments for check-novalidate: "
3626                                     "missing namespace");
3627                                 exit(1);
3628                         }
3629                         if (ca_key_path == NULL) {
3630                                 error("Too few arguments for check-novalidate: "
3631                                     "missing signature file");
3632                                 exit(1);
3633                         }
3634                         return sig_verify(ca_key_path, cert_principals,
3635                             NULL, NULL, NULL, opts, nopts);
3636                 } else if (strncmp(sign_op, "verify", 6) == 0) {
3637                         /* NB. cert_principals is actually namespace, via -n */
3638                         if (cert_principals == NULL ||
3639                             *cert_principals == '\0') {
3640                                 error("Too few arguments for verify: "
3641                                     "missing namespace");
3642                                 exit(1);
3643                         }
3644                         if (ca_key_path == NULL) {
3645                                 error("Too few arguments for verify: "
3646                                     "missing signature file");
3647                                 exit(1);
3648                         }
3649                         if (!have_identity) {
3650                                 error("Too few arguments for sign: "
3651                                     "missing allowed keys file");
3652                                 exit(1);
3653                         }
3654                         if (cert_key_id == NULL) {
3655                                 error("Too few arguments for verify: "
3656                                     "missing principal identity");
3657                                 exit(1);
3658                         }
3659                         return sig_verify(ca_key_path, cert_principals,
3660                             cert_key_id, identity_file, rr_hostname,
3661                             opts, nopts);
3662                 }
3663                 error("Unsupported operation for -Y: \"%s\"", sign_op);
3664                 usage();
3665                 /* NOTREACHED */
3666         }
3667
3668         if (ca_key_path != NULL) {
3669                 if (argc < 1 && !gen_krl) {
3670                         error("Too few arguments.");
3671                         usage();
3672                 }
3673         } else if (argc > 0 && !gen_krl && !check_krl &&
3674             !do_gen_candidates && !do_screen_candidates) {
3675                 error("Too many arguments.");
3676                 usage();
3677         }
3678         if (change_passphrase && change_comment) {
3679                 error("Can only have one of -p and -c.");
3680                 usage();
3681         }
3682         if (print_fingerprint && (delete_host || hash_hosts)) {
3683                 error("Cannot use -l with -H or -R.");
3684                 usage();
3685         }
3686         if (gen_krl) {
3687                 do_gen_krl(pw, update_krl, ca_key_path,
3688                     cert_serial, identity_comment, argc, argv);
3689                 return (0);
3690         }
3691         if (check_krl) {
3692                 do_check_krl(pw, print_fingerprint, argc, argv);
3693                 return (0);
3694         }
3695         if (ca_key_path != NULL) {
3696                 if (cert_key_id == NULL)
3697                         fatal("Must specify key id (-I) when certifying");
3698                 for (i = 0; i < nopts; i++)
3699                         add_cert_option(opts[i]);
3700                 do_ca_sign(pw, ca_key_path, prefer_agent,
3701                     cert_serial, cert_serial_autoinc, argc, argv);
3702         }
3703         if (show_cert)
3704                 do_show_cert(pw);
3705         if (delete_host || hash_hosts || find_host) {
3706                 do_known_hosts(pw, rr_hostname, find_host,
3707                     delete_host, hash_hosts);
3708         }
3709         if (pkcs11provider != NULL)
3710                 do_download(pw);
3711         if (download_sk) {
3712                 for (i = 0; i < nopts; i++) {
3713                         if (strncasecmp(opts[i], "device=", 7) == 0) {
3714                                 sk_device = xstrdup(opts[i] + 7);
3715                         } else {
3716                                 fatal("Option \"%s\" is unsupported for "
3717                                     "FIDO authenticator download", opts[i]);
3718                         }
3719                 }
3720                 return do_download_sk(sk_provider, sk_device);
3721         }
3722         if (print_fingerprint || print_bubblebabble)
3723                 do_fingerprint(pw);
3724         if (change_passphrase)
3725                 do_change_passphrase(pw);
3726         if (change_comment)
3727                 do_change_comment(pw, identity_comment);
3728 #ifdef WITH_OPENSSL
3729         if (convert_to)
3730                 do_convert_to(pw);
3731         if (convert_from)
3732                 do_convert_from(pw);
3733 #else /* WITH_OPENSSL */
3734         if (convert_to || convert_from)
3735                 fatal("key conversion disabled at compile time");
3736 #endif /* WITH_OPENSSL */
3737         if (print_public)
3738                 do_print_public(pw);
3739         if (rr_hostname != NULL) {
3740                 unsigned int n = 0;
3741
3742                 if (have_identity) {
3743                         n = do_print_resource_record(pw, identity_file,
3744                             rr_hostname, print_generic, opts, nopts);
3745                         if (n == 0)
3746                                 fatal("%s: %s", identity_file, strerror(errno));
3747                         exit(0);
3748                 } else {
3749
3750                         n += do_print_resource_record(pw,
3751                             _PATH_HOST_RSA_KEY_FILE, rr_hostname,
3752                             print_generic, opts, nopts);
3753                         n += do_print_resource_record(pw,
3754                             _PATH_HOST_DSA_KEY_FILE, rr_hostname,
3755                             print_generic, opts, nopts);
3756                         n += do_print_resource_record(pw,
3757                             _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
3758                             print_generic, opts, nopts);
3759                         n += do_print_resource_record(pw,
3760                             _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
3761                             print_generic, opts, nopts);
3762                         n += do_print_resource_record(pw,
3763                             _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
3764                             print_generic, opts, nopts);
3765                         if (n == 0)
3766                                 fatal("no keys found.");
3767                         exit(0);
3768                 }
3769         }
3770
3771         if (do_gen_candidates || do_screen_candidates) {
3772                 if (argc <= 0)
3773                         fatal("No output file specified");
3774                 else if (argc > 1)
3775                         fatal("Too many output files specified");
3776         }
3777         if (do_gen_candidates) {
3778                 do_moduli_gen(argv[0], opts, nopts);
3779                 return 0;
3780         }
3781         if (do_screen_candidates) {
3782                 do_moduli_screen(argv[0], opts, nopts);
3783                 return 0;
3784         }
3785
3786         if (gen_all_hostkeys) {
3787                 do_gen_all_hostkeys(pw);
3788                 return (0);
3789         }
3790
3791         if (key_type_name == NULL)
3792                 key_type_name = DEFAULT_KEY_TYPE_NAME;
3793
3794         type = sshkey_type_from_name(key_type_name);
3795         type_bits_valid(type, key_type_name, &bits);
3796
3797         if (!quiet)
3798                 printf("Generating public/private %s key pair.\n",
3799                     key_type_name);
3800         switch (type) {
3801         case KEY_ECDSA_SK:
3802         case KEY_ED25519_SK:
3803                 for (i = 0; i < nopts; i++) {
3804                         if (strcasecmp(opts[i], "no-touch-required") == 0) {
3805                                 sk_flags &= ~SSH_SK_USER_PRESENCE_REQD;
3806                         } else if (strcasecmp(opts[i], "verify-required") == 0) {
3807                                 sk_flags |= SSH_SK_USER_VERIFICATION_REQD;
3808                         } else if (strcasecmp(opts[i], "resident") == 0) {
3809                                 sk_flags |= SSH_SK_RESIDENT_KEY;
3810                         } else if (strncasecmp(opts[i], "device=", 7) == 0) {
3811                                 sk_device = xstrdup(opts[i] + 7);
3812                         } else if (strncasecmp(opts[i], "user=", 5) == 0) {
3813                                 sk_user = xstrdup(opts[i] + 5);
3814                         } else if (strncasecmp(opts[i], "challenge=", 10) == 0) {
3815                                 if ((r = sshbuf_load_file(opts[i] + 10,
3816                                     &challenge)) != 0) {
3817                                         fatal_r(r, "Unable to load FIDO "
3818                                             "enrollment challenge \"%s\"",
3819                                             opts[i] + 10);
3820                                 }
3821                         } else if (strncasecmp(opts[i],
3822                             "write-attestation=", 18) == 0) {
3823                                 sk_attestation_path = opts[i] + 18;
3824                         } else if (strncasecmp(opts[i],
3825                             "application=", 12) == 0) {
3826                                 sk_application = xstrdup(opts[i] + 12);
3827                                 if (strncmp(sk_application, "ssh:", 4) != 0) {
3828                                         fatal("FIDO application string must "
3829                                             "begin with \"ssh:\"");
3830                                 }
3831                         } else {
3832                                 fatal("Option \"%s\" is unsupported for "
3833                                     "FIDO authenticator enrollment", opts[i]);
3834                         }
3835                 }
3836                 if ((attest = sshbuf_new()) == NULL)
3837                         fatal("sshbuf_new failed");
3838                 r = 0;
3839                 for (i = 0 ;;) {
3840                         if (!quiet) {
3841                                 printf("You may need to touch your "
3842                                     "authenticator%s to authorize key "
3843                                     "generation.\n",
3844                                     r == 0 ? "" : " again");
3845                         }
3846                         fflush(stdout);
3847                         r = sshsk_enroll(type, sk_provider, sk_device,
3848                             sk_application == NULL ? "ssh:" : sk_application,
3849                             sk_user, sk_flags, passphrase, challenge,
3850                             &private, attest);
3851                         if (r == 0)
3852                                 break;
3853                         if (r == SSH_ERR_KEY_BAD_PERMISSIONS &&
3854                             (sk_flags & SSH_SK_RESIDENT_KEY) != 0 &&
3855                             (sk_flags & SSH_SK_FORCE_OPERATION) == 0 &&
3856                             confirm_sk_overwrite(sk_application, sk_user)) {
3857                                 sk_flags |= SSH_SK_FORCE_OPERATION;
3858                                 continue;
3859                         }
3860                         if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
3861                                 fatal_r(r, "Key enrollment failed");
3862                         else if (passphrase != NULL) {
3863                                 error("PIN incorrect");
3864                                 freezero(passphrase, strlen(passphrase));
3865                                 passphrase = NULL;
3866                         }
3867                         if (++i >= 3)
3868                                 fatal("Too many incorrect PINs");
3869                         passphrase = read_passphrase("Enter PIN for "
3870                             "authenticator: ", RP_ALLOW_STDIN);
3871                 }
3872                 if (passphrase != NULL) {
3873                         freezero(passphrase, strlen(passphrase));
3874                         passphrase = NULL;
3875                 }
3876                 break;
3877         default:
3878                 if ((r = sshkey_generate(type, bits, &private)) != 0)
3879                         fatal("sshkey_generate failed");
3880                 break;
3881         }
3882         if ((r = sshkey_from_private(private, &public)) != 0)
3883                 fatal_r(r, "sshkey_from_private");
3884
3885         if (!have_identity)
3886                 ask_filename(pw, "Enter file in which to save the key");
3887
3888         /* Create ~/.ssh directory if it doesn't already exist. */
3889         hostfile_create_user_ssh_dir(identity_file, !quiet);
3890
3891         /* If the file already exists, ask the user to confirm. */
3892         if (!confirm_overwrite(identity_file))
3893                 exit(1);
3894
3895         /* Determine the passphrase for the private key */
3896         passphrase = private_key_passphrase();
3897         if (identity_comment) {
3898                 strlcpy(comment, identity_comment, sizeof(comment));
3899         } else {
3900                 /* Create default comment field for the passphrase. */
3901                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
3902         }
3903
3904         /* Save the key with the given passphrase and comment. */
3905         if ((r = sshkey_save_private(private, identity_file, passphrase,
3906             comment, private_key_format, openssh_format_cipher, rounds)) != 0) {
3907                 error_r(r, "Saving key \"%s\" failed", identity_file);
3908                 freezero(passphrase, strlen(passphrase));
3909                 exit(1);
3910         }
3911         freezero(passphrase, strlen(passphrase));
3912         sshkey_free(private);
3913
3914         if (!quiet) {
3915                 printf("Your identification has been saved in %s\n",
3916                     identity_file);
3917         }
3918
3919         strlcat(identity_file, ".pub", sizeof(identity_file));
3920         if ((r = sshkey_save_public(public, identity_file, comment)) != 0)
3921                 fatal_r(r, "Unable to save public key to %s", identity_file);
3922
3923         if (!quiet) {
3924                 fp = sshkey_fingerprint(public, fingerprint_hash,
3925                     SSH_FP_DEFAULT);
3926                 ra = sshkey_fingerprint(public, fingerprint_hash,
3927                     SSH_FP_RANDOMART);
3928                 if (fp == NULL || ra == NULL)
3929                         fatal("sshkey_fingerprint failed");
3930                 printf("Your public key has been saved in %s\n",
3931                     identity_file);
3932                 printf("The key fingerprint is:\n");
3933                 printf("%s %s\n", fp, comment);
3934                 printf("The key's randomart image is:\n");
3935                 printf("%s\n", ra);
3936                 free(ra);
3937                 free(fp);
3938         }
3939
3940         if (sk_attestation_path != NULL)
3941                 save_attestation(attest, sk_attestation_path);
3942
3943         sshbuf_free(attest);
3944         sshkey_free(public);
3945
3946         exit(0);
3947 }