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