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