route: ensure RTM_IFINFO is sent first when bring interface down/up
[dragonfly.git] / crypto / openssh / ssh-keygen.c
1 /* $OpenBSD: ssh-keygen.c,v 1.329 2019/03/25 16:19:44 dtucker 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 #include <errno.h>
28 #include <fcntl.h>
29 #include <netdb.h>
30 #ifdef HAVE_PATHS_H
31 # include <paths.h>
32 #endif
33 #include <pwd.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <locale.h>
41 #include <time.h>
42
43 #include "xmalloc.h"
44 #include "sshkey.h"
45 #include "authfile.h"
46 #include "uuencode.h"
47 #include "sshbuf.h"
48 #include "pathnames.h"
49 #include "log.h"
50 #include "misc.h"
51 #include "match.h"
52 #include "hostfile.h"
53 #include "dns.h"
54 #include "ssh.h"
55 #include "ssh2.h"
56 #include "ssherr.h"
57 #include "ssh-pkcs11.h"
58 #include "atomicio.h"
59 #include "krl.h"
60 #include "digest.h"
61 #include "utf8.h"
62 #include "authfd.h"
63
64 #ifdef WITH_OPENSSL
65 # define DEFAULT_KEY_TYPE_NAME "rsa"
66 #else
67 # define DEFAULT_KEY_TYPE_NAME "ed25519"
68 #endif
69
70 /*
71  * Default number of bits in the RSA, DSA and ECDSA keys.  These value can be
72  * overridden on the command line.
73  *
74  * These values, with the exception of DSA, provide security equivalent to at
75  * least 128 bits of security according to NIST Special Publication 800-57:
76  * Recommendation for Key Management Part 1 rev 4 section 5.6.1.
77  * For DSA it (and FIPS-186-4 section 4.2) specifies that the only size for
78  * which a 160bit hash is acceptable is 1kbit, and since ssh-dss specifies only
79  * SHA1 we limit the DSA key size 1k bits.
80  */
81 #define DEFAULT_BITS            3072
82 #define DEFAULT_BITS_DSA        1024
83 #define DEFAULT_BITS_ECDSA      256
84
85 static int quiet = 0;
86
87 /* Flag indicating that we just want to see the key fingerprint */
88 static int print_fingerprint = 0;
89 static int print_bubblebabble = 0;
90
91 /* Hash algorithm to use for fingerprints. */
92 static int fingerprint_hash = SSH_FP_HASH_DEFAULT;
93
94 /* The identity file name, given on the command line or entered by the user. */
95 static char identity_file[1024];
96 static int have_identity = 0;
97
98 /* This is set to the passphrase if given on the command line. */
99 static char *identity_passphrase = NULL;
100
101 /* This is set to the new passphrase if given on the command line. */
102 static char *identity_new_passphrase = NULL;
103
104 /* Key type when certifying */
105 static u_int cert_key_type = SSH2_CERT_TYPE_USER;
106
107 /* "key ID" of signed key */
108 static char *cert_key_id = NULL;
109
110 /* Comma-separated list of principal names for certifying keys */
111 static char *cert_principals = NULL;
112
113 /* Validity period for certificates */
114 static u_int64_t cert_valid_from = 0;
115 static u_int64_t cert_valid_to = ~0ULL;
116
117 /* Certificate options */
118 #define CERTOPT_X_FWD   (1)
119 #define CERTOPT_AGENT_FWD       (1<<1)
120 #define CERTOPT_PORT_FWD        (1<<2)
121 #define CERTOPT_PTY             (1<<3)
122 #define CERTOPT_USER_RC (1<<4)
123 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
124                          CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
125 static u_int32_t certflags_flags = CERTOPT_DEFAULT;
126 static char *certflags_command = NULL;
127 static char *certflags_src_addr = NULL;
128
129 /* Arbitrary extensions specified by user */
130 struct cert_userext {
131         char *key;
132         char *val;
133         int crit;
134 };
135 static struct cert_userext *cert_userext;
136 static size_t ncert_userext;
137
138 /* Conversion to/from various formats */
139 enum {
140         FMT_RFC4716,
141         FMT_PKCS8,
142         FMT_PEM
143 } convert_format = FMT_RFC4716;
144
145 static char *key_type_name = NULL;
146
147 /* Load key from this PKCS#11 provider */
148 static char *pkcs11provider = NULL;
149
150 /* Use new OpenSSH private key format when writing SSH2 keys instead of PEM */
151 static int use_new_format = 1;
152
153 /* Cipher for new-format private keys */
154 static char *new_format_cipher = NULL;
155
156 /*
157  * Number of KDF rounds to derive new format keys /
158  * number of primality trials when screening moduli.
159  */
160 static int rounds = 0;
161
162 /* argv0 */
163 extern char *__progname;
164
165 static char hostname[NI_MAXHOST];
166
167 #ifdef WITH_OPENSSL
168 /* moduli.c */
169 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
170 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t, char *, unsigned long,
171     unsigned long);
172 #endif
173
174 static void
175 type_bits_valid(int type, const char *name, u_int32_t *bitsp)
176 {
177 #ifdef WITH_OPENSSL
178         u_int maxbits, nid;
179 #endif
180
181         if (type == KEY_UNSPEC)
182                 fatal("unknown key type %s", key_type_name);
183         if (*bitsp == 0) {
184 #ifdef WITH_OPENSSL
185                 if (type == KEY_DSA)
186                         *bitsp = DEFAULT_BITS_DSA;
187                 else if (type == KEY_ECDSA) {
188                         if (name != NULL &&
189                             (nid = sshkey_ecdsa_nid_from_name(name)) > 0)
190                                 *bitsp = sshkey_curve_nid_to_bits(nid);
191                         if (*bitsp == 0)
192                                 *bitsp = DEFAULT_BITS_ECDSA;
193                 } else
194 #endif
195                         *bitsp = DEFAULT_BITS;
196         }
197 #ifdef WITH_OPENSSL
198         maxbits = (type == KEY_DSA) ?
199             OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
200         if (*bitsp > maxbits)
201                 fatal("key bits exceeds maximum %d", maxbits);
202         switch (type) {
203         case KEY_DSA:
204                 if (*bitsp != 1024)
205                         fatal("Invalid DSA key length: must be 1024 bits");
206                 break;
207         case KEY_RSA:
208                 if (*bitsp < SSH_RSA_MINIMUM_MODULUS_SIZE)
209                         fatal("Invalid RSA key length: minimum is %d bits",
210                             SSH_RSA_MINIMUM_MODULUS_SIZE);
211                 break;
212         case KEY_ECDSA:
213                 if (sshkey_ecdsa_bits_to_nid(*bitsp) == -1)
214                         fatal("Invalid ECDSA key length: valid lengths are "
215 #ifdef OPENSSL_HAS_NISTP521
216                             "256, 384 or 521 bits");
217 #else
218                             "256 or 384 bits");
219 #endif
220         }
221 #endif
222 }
223
224 static void
225 ask_filename(struct passwd *pw, const char *prompt)
226 {
227         char buf[1024];
228         char *name = NULL;
229
230         if (key_type_name == NULL)
231                 name = _PATH_SSH_CLIENT_ID_RSA;
232         else {
233                 switch (sshkey_type_from_name(key_type_name)) {
234                 case KEY_DSA_CERT:
235                 case KEY_DSA:
236                         name = _PATH_SSH_CLIENT_ID_DSA;
237                         break;
238 #ifdef OPENSSL_HAS_ECC
239                 case KEY_ECDSA_CERT:
240                 case KEY_ECDSA:
241                         name = _PATH_SSH_CLIENT_ID_ECDSA;
242                         break;
243 #endif
244                 case KEY_RSA_CERT:
245                 case KEY_RSA:
246                         name = _PATH_SSH_CLIENT_ID_RSA;
247                         break;
248                 case KEY_ED25519:
249                 case KEY_ED25519_CERT:
250                         name = _PATH_SSH_CLIENT_ID_ED25519;
251                         break;
252                 case KEY_XMSS:
253                 case KEY_XMSS_CERT:
254                         name = _PATH_SSH_CLIENT_ID_XMSS;
255                         break;
256                 default:
257                         fatal("bad key type");
258                 }
259         }
260         snprintf(identity_file, sizeof(identity_file),
261             "%s/%s", pw->pw_dir, name);
262         printf("%s (%s): ", prompt, identity_file);
263         fflush(stdout);
264         if (fgets(buf, sizeof(buf), stdin) == NULL)
265                 exit(1);
266         buf[strcspn(buf, "\n")] = '\0';
267         if (strcmp(buf, "") != 0)
268                 strlcpy(identity_file, buf, sizeof(identity_file));
269         have_identity = 1;
270 }
271
272 static struct sshkey *
273 load_identity(char *filename)
274 {
275         char *pass;
276         struct sshkey *prv;
277         int r;
278
279         if ((r = sshkey_load_private(filename, "", &prv, NULL)) == 0)
280                 return prv;
281         if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
282                 fatal("Load key \"%s\": %s", filename, ssh_err(r));
283         if (identity_passphrase)
284                 pass = xstrdup(identity_passphrase);
285         else
286                 pass = read_passphrase("Enter passphrase: ", RP_ALLOW_STDIN);
287         r = sshkey_load_private(filename, pass, &prv, NULL);
288         explicit_bzero(pass, strlen(pass));
289         free(pass);
290         if (r != 0)
291                 fatal("Load key \"%s\": %s", filename, ssh_err(r));
292         return prv;
293 }
294
295 #define SSH_COM_PUBLIC_BEGIN            "---- BEGIN SSH2 PUBLIC KEY ----"
296 #define SSH_COM_PUBLIC_END              "---- END SSH2 PUBLIC KEY ----"
297 #define SSH_COM_PRIVATE_BEGIN           "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
298 #define SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
299
300 #ifdef WITH_OPENSSL
301 static void
302 do_convert_to_ssh2(struct passwd *pw, struct sshkey *k)
303 {
304         size_t len;
305         u_char *blob;
306         char comment[61];
307         int r;
308
309         if ((r = sshkey_to_blob(k, &blob, &len)) != 0)
310                 fatal("key_to_blob failed: %s", ssh_err(r));
311         /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
312         snprintf(comment, sizeof(comment),
313             "%u-bit %s, converted by %s@%s from OpenSSH",
314             sshkey_size(k), sshkey_type(k),
315             pw->pw_name, hostname);
316
317         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
318         fprintf(stdout, "Comment: \"%s\"\n", comment);
319         dump_base64(stdout, blob, len);
320         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
321         sshkey_free(k);
322         free(blob);
323         exit(0);
324 }
325
326 static void
327 do_convert_to_pkcs8(struct sshkey *k)
328 {
329         switch (sshkey_type_plain(k->type)) {
330         case KEY_RSA:
331                 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
332                         fatal("PEM_write_RSA_PUBKEY failed");
333                 break;
334         case KEY_DSA:
335                 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
336                         fatal("PEM_write_DSA_PUBKEY failed");
337                 break;
338 #ifdef OPENSSL_HAS_ECC
339         case KEY_ECDSA:
340                 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
341                         fatal("PEM_write_EC_PUBKEY failed");
342                 break;
343 #endif
344         default:
345                 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
346         }
347         exit(0);
348 }
349
350 static void
351 do_convert_to_pem(struct sshkey *k)
352 {
353         switch (sshkey_type_plain(k->type)) {
354         case KEY_RSA:
355                 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
356                         fatal("PEM_write_RSAPublicKey failed");
357                 break;
358         default:
359                 fatal("%s: unsupported key type %s", __func__, sshkey_type(k));
360         }
361         exit(0);
362 }
363
364 static void
365 do_convert_to(struct passwd *pw)
366 {
367         struct sshkey *k;
368         struct stat st;
369         int r;
370
371         if (!have_identity)
372                 ask_filename(pw, "Enter file in which the key is");
373         if (stat(identity_file, &st) < 0)
374                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
375         if ((r = sshkey_load_public(identity_file, &k, NULL)) != 0)
376                 k = load_identity(identity_file);
377         switch (convert_format) {
378         case FMT_RFC4716:
379                 do_convert_to_ssh2(pw, k);
380                 break;
381         case FMT_PKCS8:
382                 do_convert_to_pkcs8(k);
383                 break;
384         case FMT_PEM:
385                 do_convert_to_pem(k);
386                 break;
387         default:
388                 fatal("%s: unknown key format %d", __func__, convert_format);
389         }
390         exit(0);
391 }
392
393 /*
394  * This is almost exactly the bignum1 encoding, but with 32 bit for length
395  * instead of 16.
396  */
397 static void
398 buffer_get_bignum_bits(struct sshbuf *b, BIGNUM *value)
399 {
400         u_int bytes, bignum_bits;
401         int r;
402
403         if ((r = sshbuf_get_u32(b, &bignum_bits)) != 0)
404                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
405         bytes = (bignum_bits + 7) / 8;
406         if (sshbuf_len(b) < bytes)
407                 fatal("%s: input buffer too small: need %d have %zu",
408                     __func__, bytes, sshbuf_len(b));
409         if (BN_bin2bn(sshbuf_ptr(b), bytes, value) == NULL)
410                 fatal("%s: BN_bin2bn failed", __func__);
411         if ((r = sshbuf_consume(b, bytes)) != 0)
412                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
413 }
414
415 static struct sshkey *
416 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
417 {
418         struct sshbuf *b;
419         struct sshkey *key = NULL;
420         char *type, *cipher;
421         u_char e1, e2, e3, *sig = NULL, data[] = "abcde12345";
422         int r, rlen, ktype;
423         u_int magic, i1, i2, i3, i4;
424         size_t slen;
425         u_long e;
426         BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL;
427         BIGNUM *dsa_pub_key = NULL, *dsa_priv_key = NULL;
428         BIGNUM *rsa_n = NULL, *rsa_e = NULL, *rsa_d = NULL;
429         BIGNUM *rsa_p = NULL, *rsa_q = NULL, *rsa_iqmp = NULL;
430         if ((b = sshbuf_from(blob, blen)) == NULL)
431                 fatal("%s: sshbuf_from failed", __func__);
432         if ((r = sshbuf_get_u32(b, &magic)) != 0)
433                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
434
435         if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
436                 error("bad magic 0x%x != 0x%x", magic,
437                     SSH_COM_PRIVATE_KEY_MAGIC);
438                 sshbuf_free(b);
439                 return NULL;
440         }
441         if ((r = sshbuf_get_u32(b, &i1)) != 0 ||
442             (r = sshbuf_get_cstring(b, &type, NULL)) != 0 ||
443             (r = sshbuf_get_cstring(b, &cipher, NULL)) != 0 ||
444             (r = sshbuf_get_u32(b, &i2)) != 0 ||
445             (r = sshbuf_get_u32(b, &i3)) != 0 ||
446             (r = sshbuf_get_u32(b, &i4)) != 0)
447                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
448         debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
449         if (strcmp(cipher, "none") != 0) {
450                 error("unsupported cipher %s", cipher);
451                 free(cipher);
452                 sshbuf_free(b);
453                 free(type);
454                 return NULL;
455         }
456         free(cipher);
457
458         if (strstr(type, "dsa")) {
459                 ktype = KEY_DSA;
460         } else if (strstr(type, "rsa")) {
461                 ktype = KEY_RSA;
462         } else {
463                 sshbuf_free(b);
464                 free(type);
465                 return NULL;
466         }
467         if ((key = sshkey_new(ktype)) == NULL)
468                 fatal("sshkey_new failed");
469         free(type);
470
471         switch (key->type) {
472         case KEY_DSA:
473                 if ((dsa_p = BN_new()) == NULL ||
474                     (dsa_q = BN_new()) == NULL ||
475                     (dsa_g = BN_new()) == NULL ||
476                     (dsa_pub_key = BN_new()) == NULL ||
477                     (dsa_priv_key = BN_new()) == NULL)
478                         fatal("%s: BN_new", __func__);
479                 buffer_get_bignum_bits(b, dsa_p);
480                 buffer_get_bignum_bits(b, dsa_g);
481                 buffer_get_bignum_bits(b, dsa_q);
482                 buffer_get_bignum_bits(b, dsa_pub_key);
483                 buffer_get_bignum_bits(b, dsa_priv_key);
484                 if (!DSA_set0_pqg(key->dsa, dsa_p, dsa_q, dsa_g))
485                         fatal("%s: DSA_set0_pqg failed", __func__);
486                 dsa_p = dsa_q = dsa_g = NULL; /* transferred */
487                 if (!DSA_set0_key(key->dsa, dsa_pub_key, dsa_priv_key))
488                         fatal("%s: DSA_set0_key failed", __func__);
489                 dsa_pub_key = dsa_priv_key = NULL; /* transferred */
490                 break;
491         case KEY_RSA:
492                 if ((r = sshbuf_get_u8(b, &e1)) != 0 ||
493                     (e1 < 30 && (r = sshbuf_get_u8(b, &e2)) != 0) ||
494                     (e1 < 30 && (r = sshbuf_get_u8(b, &e3)) != 0))
495                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
496                 e = e1;
497                 debug("e %lx", e);
498                 if (e < 30) {
499                         e <<= 8;
500                         e += e2;
501                         debug("e %lx", e);
502                         e <<= 8;
503                         e += e3;
504                         debug("e %lx", e);
505                 }
506                 if ((rsa_e = BN_new()) == NULL)
507                         fatal("%s: BN_new", __func__);
508                 if (!BN_set_word(rsa_e, e)) {
509                         BN_clear_free(rsa_e);
510                         sshbuf_free(b);
511                         sshkey_free(key);
512                         return NULL;
513                 }
514                 if ((rsa_n = BN_new()) == NULL ||
515                     (rsa_d = BN_new()) == NULL ||
516                     (rsa_p = BN_new()) == NULL ||
517                     (rsa_q = BN_new()) == NULL ||
518                     (rsa_iqmp = BN_new()) == NULL)
519                         fatal("%s: BN_new", __func__);
520                 buffer_get_bignum_bits(b, rsa_d);
521                 buffer_get_bignum_bits(b, rsa_n);
522                 buffer_get_bignum_bits(b, rsa_iqmp);
523                 buffer_get_bignum_bits(b, rsa_q);
524                 buffer_get_bignum_bits(b, rsa_p);
525                 if (!RSA_set0_key(key->rsa, rsa_n, rsa_e, rsa_d))
526                         fatal("%s: RSA_set0_key failed", __func__);
527                 rsa_n = rsa_e = rsa_d = NULL; /* transferred */
528                 if (!RSA_set0_factors(key->rsa, rsa_p, rsa_q))
529                         fatal("%s: RSA_set0_factors failed", __func__);
530                 rsa_p = rsa_q = NULL; /* transferred */
531                 if ((r = ssh_rsa_complete_crt_parameters(key, rsa_iqmp)) != 0)
532                         fatal("generate RSA parameters failed: %s", ssh_err(r));
533                 BN_clear_free(rsa_iqmp);
534                 break;
535         }
536         rlen = sshbuf_len(b);
537         if (rlen != 0)
538                 error("do_convert_private_ssh2_from_blob: "
539                     "remaining bytes in key blob %d", rlen);
540         sshbuf_free(b);
541
542         /* try the key */
543         if (sshkey_sign(key, &sig, &slen, data, sizeof(data), NULL, 0) != 0 ||
544             sshkey_verify(key, sig, slen, data, sizeof(data), NULL, 0) != 0) {
545                 sshkey_free(key);
546                 free(sig);
547                 return NULL;
548         }
549         free(sig);
550         return key;
551 }
552
553 static int
554 get_line(FILE *fp, char *line, size_t len)
555 {
556         int c;
557         size_t pos = 0;
558
559         line[0] = '\0';
560         while ((c = fgetc(fp)) != EOF) {
561                 if (pos >= len - 1)
562                         fatal("input line too long.");
563                 switch (c) {
564                 case '\r':
565                         c = fgetc(fp);
566                         if (c != EOF && c != '\n' && ungetc(c, fp) == EOF)
567                                 fatal("unget: %s", strerror(errno));
568                         return pos;
569                 case '\n':
570                         return pos;
571                 }
572                 line[pos++] = c;
573                 line[pos] = '\0';
574         }
575         /* We reached EOF */
576         return -1;
577 }
578
579 static void
580 do_convert_from_ssh2(struct passwd *pw, struct sshkey **k, int *private)
581 {
582         int r, blen, escaped = 0;
583         u_int len;
584         char line[1024];
585         u_char blob[8096];
586         char encoded[8096];
587         FILE *fp;
588
589         if ((fp = fopen(identity_file, "r")) == NULL)
590                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
591         encoded[0] = '\0';
592         while ((blen = get_line(fp, line, sizeof(line))) != -1) {
593                 if (blen > 0 && line[blen - 1] == '\\')
594                         escaped++;
595                 if (strncmp(line, "----", 4) == 0 ||
596                     strstr(line, ": ") != NULL) {
597                         if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
598                                 *private = 1;
599                         if (strstr(line, " END ") != NULL) {
600                                 break;
601                         }
602                         /* fprintf(stderr, "ignore: %s", line); */
603                         continue;
604                 }
605                 if (escaped) {
606                         escaped--;
607                         /* fprintf(stderr, "escaped: %s", line); */
608                         continue;
609                 }
610                 strlcat(encoded, line, sizeof(encoded));
611         }
612         len = strlen(encoded);
613         if (((len % 4) == 3) &&
614             (encoded[len-1] == '=') &&
615             (encoded[len-2] == '=') &&
616             (encoded[len-3] == '='))
617                 encoded[len-3] = '\0';
618         blen = uudecode(encoded, blob, sizeof(blob));
619         if (blen < 0)
620                 fatal("uudecode failed.");
621         if (*private)
622                 *k = do_convert_private_ssh2_from_blob(blob, blen);
623         else if ((r = sshkey_from_blob(blob, blen, k)) != 0)
624                 fatal("decode blob failed: %s", ssh_err(r));
625         fclose(fp);
626 }
627
628 static void
629 do_convert_from_pkcs8(struct sshkey **k, int *private)
630 {
631         EVP_PKEY *pubkey;
632         FILE *fp;
633
634         if ((fp = fopen(identity_file, "r")) == NULL)
635                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
636         if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
637                 fatal("%s: %s is not a recognised public key format", __func__,
638                     identity_file);
639         }
640         fclose(fp);
641         switch (EVP_PKEY_base_id(pubkey)) {
642         case EVP_PKEY_RSA:
643                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
644                         fatal("sshkey_new failed");
645                 (*k)->type = KEY_RSA;
646                 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
647                 break;
648         case EVP_PKEY_DSA:
649                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
650                         fatal("sshkey_new failed");
651                 (*k)->type = KEY_DSA;
652                 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
653                 break;
654 #ifdef OPENSSL_HAS_ECC
655         case EVP_PKEY_EC:
656                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
657                         fatal("sshkey_new failed");
658                 (*k)->type = KEY_ECDSA;
659                 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
660                 (*k)->ecdsa_nid = sshkey_ecdsa_key_to_nid((*k)->ecdsa);
661                 break;
662 #endif
663         default:
664                 fatal("%s: unsupported pubkey type %d", __func__,
665                     EVP_PKEY_base_id(pubkey));
666         }
667         EVP_PKEY_free(pubkey);
668         return;
669 }
670
671 static void
672 do_convert_from_pem(struct sshkey **k, int *private)
673 {
674         FILE *fp;
675         RSA *rsa;
676
677         if ((fp = fopen(identity_file, "r")) == NULL)
678                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
679         if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
680                 if ((*k = sshkey_new(KEY_UNSPEC)) == NULL)
681                         fatal("sshkey_new failed");
682                 (*k)->type = KEY_RSA;
683                 (*k)->rsa = rsa;
684                 fclose(fp);
685                 return;
686         }
687         fatal("%s: unrecognised raw private key format", __func__);
688 }
689
690 static void
691 do_convert_from(struct passwd *pw)
692 {
693         struct sshkey *k = NULL;
694         int r, private = 0, ok = 0;
695         struct stat st;
696
697         if (!have_identity)
698                 ask_filename(pw, "Enter file in which the key is");
699         if (stat(identity_file, &st) < 0)
700                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
701
702         switch (convert_format) {
703         case FMT_RFC4716:
704                 do_convert_from_ssh2(pw, &k, &private);
705                 break;
706         case FMT_PKCS8:
707                 do_convert_from_pkcs8(&k, &private);
708                 break;
709         case FMT_PEM:
710                 do_convert_from_pem(&k, &private);
711                 break;
712         default:
713                 fatal("%s: unknown key format %d", __func__, convert_format);
714         }
715
716         if (!private) {
717                 if ((r = sshkey_write(k, stdout)) == 0)
718                         ok = 1;
719                 if (ok)
720                         fprintf(stdout, "\n");
721         } else {
722                 switch (k->type) {
723                 case KEY_DSA:
724                         ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
725                             NULL, 0, NULL, NULL);
726                         break;
727 #ifdef OPENSSL_HAS_ECC
728                 case KEY_ECDSA:
729                         ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
730                             NULL, 0, NULL, NULL);
731                         break;
732 #endif
733                 case KEY_RSA:
734                         ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
735                             NULL, 0, NULL, NULL);
736                         break;
737                 default:
738                         fatal("%s: unsupported key type %s", __func__,
739                             sshkey_type(k));
740                 }
741         }
742
743         if (!ok)
744                 fatal("key write failed");
745         sshkey_free(k);
746         exit(0);
747 }
748 #endif
749
750 static void
751 do_print_public(struct passwd *pw)
752 {
753         struct sshkey *prv;
754         struct stat st;
755         int r;
756
757         if (!have_identity)
758                 ask_filename(pw, "Enter file in which the key is");
759         if (stat(identity_file, &st) < 0)
760                 fatal("%s: %s", identity_file, strerror(errno));
761         prv = load_identity(identity_file);
762         if ((r = sshkey_write(prv, stdout)) != 0)
763                 error("sshkey_write failed: %s", ssh_err(r));
764         sshkey_free(prv);
765         fprintf(stdout, "\n");
766         exit(0);
767 }
768
769 static void
770 do_download(struct passwd *pw)
771 {
772 #ifdef ENABLE_PKCS11
773         struct sshkey **keys = NULL;
774         int i, nkeys;
775         enum sshkey_fp_rep rep;
776         int fptype;
777         char *fp, *ra;
778
779         fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
780         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
781
782         pkcs11_init(1);
783         nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
784         if (nkeys <= 0)
785                 fatal("cannot read public key from pkcs11");
786         for (i = 0; i < nkeys; i++) {
787                 if (print_fingerprint) {
788                         fp = sshkey_fingerprint(keys[i], fptype, rep);
789                         ra = sshkey_fingerprint(keys[i], fingerprint_hash,
790                             SSH_FP_RANDOMART);
791                         if (fp == NULL || ra == NULL)
792                                 fatal("%s: sshkey_fingerprint fail", __func__);
793                         printf("%u %s %s (PKCS11 key)\n", sshkey_size(keys[i]),
794                             fp, sshkey_type(keys[i]));
795                         if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
796                                 printf("%s\n", ra);
797                         free(ra);
798                         free(fp);
799                 } else {
800                         (void) sshkey_write(keys[i], stdout); /* XXX check */
801                         fprintf(stdout, "\n");
802                 }
803                 sshkey_free(keys[i]);
804         }
805         free(keys);
806         pkcs11_terminate();
807         exit(0);
808 #else
809         fatal("no pkcs11 support");
810 #endif /* ENABLE_PKCS11 */
811 }
812
813 static struct sshkey *
814 try_read_key(char **cpp)
815 {
816         struct sshkey *ret;
817         int r;
818
819         if ((ret = sshkey_new(KEY_UNSPEC)) == NULL)
820                 fatal("sshkey_new failed");
821         if ((r = sshkey_read(ret, cpp)) == 0)
822                 return ret;
823         /* Not a key */
824         sshkey_free(ret);
825         return NULL;
826 }
827
828 static void
829 fingerprint_one_key(const struct sshkey *public, const char *comment)
830 {
831         char *fp = NULL, *ra = NULL;
832         enum sshkey_fp_rep rep;
833         int fptype;
834
835         fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
836         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
837         fp = sshkey_fingerprint(public, fptype, rep);
838         ra = sshkey_fingerprint(public, fingerprint_hash, SSH_FP_RANDOMART);
839         if (fp == NULL || ra == NULL)
840                 fatal("%s: sshkey_fingerprint failed", __func__);
841         mprintf("%u %s %s (%s)\n", sshkey_size(public), fp,
842             comment ? comment : "no comment", sshkey_type(public));
843         if (log_level_get() >= SYSLOG_LEVEL_VERBOSE)
844                 printf("%s\n", ra);
845         free(ra);
846         free(fp);
847 }
848
849 static void
850 fingerprint_private(const char *path)
851 {
852         struct stat st;
853         char *comment = NULL;
854         struct sshkey *public = NULL;
855         int r;
856
857         if (stat(identity_file, &st) < 0)
858                 fatal("%s: %s", path, strerror(errno));
859         if ((r = sshkey_load_public(path, &public, &comment)) != 0) {
860                 debug("load public \"%s\": %s", path, ssh_err(r));
861                 if ((r = sshkey_load_private(path, NULL,
862                     &public, &comment)) != 0) {
863                         debug("load private \"%s\": %s", path, ssh_err(r));
864                         fatal("%s is not a key file.", path);
865                 }
866         }
867
868         fingerprint_one_key(public, comment);
869         sshkey_free(public);
870         free(comment);
871 }
872
873 static void
874 do_fingerprint(struct passwd *pw)
875 {
876         FILE *f;
877         struct sshkey *public = NULL;
878         char *comment = NULL, *cp, *ep, *line = NULL;
879         size_t linesize = 0;
880         int i, invalid = 1;
881         const char *path;
882         u_long lnum = 0;
883
884         if (!have_identity)
885                 ask_filename(pw, "Enter file in which the key is");
886         path = identity_file;
887
888         if (strcmp(identity_file, "-") == 0) {
889                 f = stdin;
890                 path = "(stdin)";
891         } else if ((f = fopen(path, "r")) == NULL)
892                 fatal("%s: %s: %s", __progname, path, strerror(errno));
893
894         while (getline(&line, &linesize, f) != -1) {
895                 lnum++;
896                 cp = line;
897                 cp[strcspn(cp, "\n")] = '\0';
898                 /* Trim leading space and comments */
899                 cp = line + strspn(line, " \t");
900                 if (*cp == '#' || *cp == '\0')
901                         continue;
902
903                 /*
904                  * Input may be plain keys, private keys, authorized_keys
905                  * or known_hosts.
906                  */
907
908                 /*
909                  * Try private keys first. Assume a key is private if
910                  * "SSH PRIVATE KEY" appears on the first line and we're
911                  * not reading from stdin (XXX support private keys on stdin).
912                  */
913                 if (lnum == 1 && strcmp(identity_file, "-") != 0 &&
914                     strstr(cp, "PRIVATE KEY") != NULL) {
915                         free(line);
916                         fclose(f);
917                         fingerprint_private(path);
918                         exit(0);
919                 }
920
921                 /*
922                  * If it's not a private key, then this must be prepared to
923                  * accept a public key prefixed with a hostname or options.
924                  * Try a bare key first, otherwise skip the leading stuff.
925                  */
926                 if ((public = try_read_key(&cp)) == NULL) {
927                         i = strtol(cp, &ep, 10);
928                         if (i == 0 || ep == NULL ||
929                             (*ep != ' ' && *ep != '\t')) {
930                                 int quoted = 0;
931
932                                 comment = cp;
933                                 for (; *cp && (quoted || (*cp != ' ' &&
934                                     *cp != '\t')); cp++) {
935                                         if (*cp == '\\' && cp[1] == '"')
936                                                 cp++;   /* Skip both */
937                                         else if (*cp == '"')
938                                                 quoted = !quoted;
939                                 }
940                                 if (!*cp)
941                                         continue;
942                                 *cp++ = '\0';
943                         }
944                 }
945                 /* Retry after parsing leading hostname/key options */
946                 if (public == NULL && (public = try_read_key(&cp)) == NULL) {
947                         debug("%s:%lu: not a public key", path, lnum);
948                         continue;
949                 }
950
951                 /* Find trailing comment, if any */
952                 for (; *cp == ' ' || *cp == '\t'; cp++)
953                         ;
954                 if (*cp != '\0' && *cp != '#')
955                         comment = cp;
956
957                 fingerprint_one_key(public, comment);
958                 sshkey_free(public);
959                 invalid = 0; /* One good key in the file is sufficient */
960         }
961         fclose(f);
962         free(line);
963
964         if (invalid)
965                 fatal("%s is not a public key file.", path);
966         exit(0);
967 }
968
969 static void
970 do_gen_all_hostkeys(struct passwd *pw)
971 {
972         struct {
973                 char *key_type;
974                 char *key_type_display;
975                 char *path;
976         } key_types[] = {
977 #ifdef WITH_OPENSSL
978                 { "rsa", "RSA" ,_PATH_HOST_RSA_KEY_FILE },
979                 { "dsa", "DSA", _PATH_HOST_DSA_KEY_FILE },
980 #ifdef OPENSSL_HAS_ECC
981                 { "ecdsa", "ECDSA",_PATH_HOST_ECDSA_KEY_FILE },
982 #endif /* OPENSSL_HAS_ECC */
983 #endif /* WITH_OPENSSL */
984                 { "ed25519", "ED25519",_PATH_HOST_ED25519_KEY_FILE },
985 #ifdef WITH_XMSS
986                 { "xmss", "XMSS",_PATH_HOST_XMSS_KEY_FILE },
987 #endif /* WITH_XMSS */
988                 { NULL, NULL, NULL }
989         };
990
991         u_int bits = 0;
992         int first = 0;
993         struct stat st;
994         struct sshkey *private, *public;
995         char comment[1024], *prv_tmp, *pub_tmp, *prv_file, *pub_file;
996         int i, type, fd, r;
997         FILE *f;
998
999         for (i = 0; key_types[i].key_type; i++) {
1000                 public = private = NULL;
1001                 prv_tmp = pub_tmp = prv_file = pub_file = NULL;
1002
1003                 xasprintf(&prv_file, "%s%s",
1004                     identity_file, key_types[i].path);
1005
1006                 /* Check whether private key exists and is not zero-length */
1007                 if (stat(prv_file, &st) == 0) {
1008                         if (st.st_size != 0)
1009                                 goto next;
1010                 } else if (errno != ENOENT) {
1011                         error("Could not stat %s: %s", key_types[i].path,
1012                             strerror(errno));
1013                         goto failnext;
1014                 }
1015
1016                 /*
1017                  * Private key doesn't exist or is invalid; proceed with
1018                  * key generation.
1019                  */
1020                 xasprintf(&prv_tmp, "%s%s.XXXXXXXXXX",
1021                     identity_file, key_types[i].path);
1022                 xasprintf(&pub_tmp, "%s%s.pub.XXXXXXXXXX",
1023                     identity_file, key_types[i].path);
1024                 xasprintf(&pub_file, "%s%s.pub",
1025                     identity_file, key_types[i].path);
1026
1027                 if (first == 0) {
1028                         first = 1;
1029                         printf("%s: generating new host keys: ", __progname);
1030                 }
1031                 printf("%s ", key_types[i].key_type_display);
1032                 fflush(stdout);
1033                 type = sshkey_type_from_name(key_types[i].key_type);
1034                 if ((fd = mkstemp(prv_tmp)) == -1) {
1035                         error("Could not save your public key in %s: %s",
1036                             prv_tmp, strerror(errno));
1037                         goto failnext;
1038                 }
1039                 close(fd); /* just using mkstemp() to generate/reserve a name */
1040                 bits = 0;
1041                 type_bits_valid(type, NULL, &bits);
1042                 if ((r = sshkey_generate(type, bits, &private)) != 0) {
1043                         error("sshkey_generate failed: %s", ssh_err(r));
1044                         goto failnext;
1045                 }
1046                 if ((r = sshkey_from_private(private, &public)) != 0)
1047                         fatal("sshkey_from_private failed: %s", ssh_err(r));
1048                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name,
1049                     hostname);
1050                 if ((r = sshkey_save_private(private, prv_tmp, "",
1051                     comment, use_new_format, new_format_cipher, rounds)) != 0) {
1052                         error("Saving key \"%s\" failed: %s",
1053                             prv_tmp, ssh_err(r));
1054                         goto failnext;
1055                 }
1056                 if ((fd = mkstemp(pub_tmp)) == -1) {
1057                         error("Could not save your public key in %s: %s",
1058                             pub_tmp, strerror(errno));
1059                         goto failnext;
1060                 }
1061                 (void)fchmod(fd, 0644);
1062                 f = fdopen(fd, "w");
1063                 if (f == NULL) {
1064                         error("fdopen %s failed: %s", pub_tmp, strerror(errno));
1065                         close(fd);
1066                         goto failnext;
1067                 }
1068                 if ((r = sshkey_write(public, f)) != 0) {
1069                         error("write key failed: %s", ssh_err(r));
1070                         fclose(f);
1071                         goto failnext;
1072                 }
1073                 fprintf(f, " %s\n", comment);
1074                 if (ferror(f) != 0) {
1075                         error("write key failed: %s", strerror(errno));
1076                         fclose(f);
1077                         goto failnext;
1078                 }
1079                 if (fclose(f) != 0) {
1080                         error("key close failed: %s", strerror(errno));
1081                         goto failnext;
1082                 }
1083
1084                 /* Rename temporary files to their permanent locations. */
1085                 if (rename(pub_tmp, pub_file) != 0) {
1086                         error("Unable to move %s into position: %s",
1087                             pub_file, strerror(errno));
1088                         goto failnext;
1089                 }
1090                 if (rename(prv_tmp, prv_file) != 0) {
1091                         error("Unable to move %s into position: %s",
1092                             key_types[i].path, strerror(errno));
1093  failnext:
1094                         first = 0;
1095                         goto next;
1096                 }
1097  next:
1098                 sshkey_free(private);
1099                 sshkey_free(public);
1100                 free(prv_tmp);
1101                 free(pub_tmp);
1102                 free(prv_file);
1103                 free(pub_file);
1104         }
1105         if (first != 0)
1106                 printf("\n");
1107 }
1108
1109 struct known_hosts_ctx {
1110         const char *host;       /* Hostname searched for in find/delete case */
1111         FILE *out;              /* Output file, stdout for find_hosts case */
1112         int has_unhashed;       /* When hashing, original had unhashed hosts */
1113         int found_key;          /* For find/delete, host was found */
1114         int invalid;            /* File contained invalid items; don't delete */
1115         int hash_hosts;         /* Hash hostnames as we go */
1116         int find_host;          /* Search for specific hostname */
1117         int delete_host;        /* Delete host from known_hosts */
1118 };
1119
1120 static int
1121 known_hosts_hash(struct hostkey_foreach_line *l, void *_ctx)
1122 {
1123         struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1124         char *hashed, *cp, *hosts, *ohosts;
1125         int has_wild = l->hosts && strcspn(l->hosts, "*?!") != strlen(l->hosts);
1126         int was_hashed = l->hosts && l->hosts[0] == HASH_DELIM;
1127
1128         switch (l->status) {
1129         case HKF_STATUS_OK:
1130         case HKF_STATUS_MATCHED:
1131                 /*
1132                  * Don't hash hosts already already hashed, with wildcard
1133                  * characters or a CA/revocation marker.
1134                  */
1135                 if (was_hashed || has_wild || l->marker != MRK_NONE) {
1136                         fprintf(ctx->out, "%s\n", l->line);
1137                         if (has_wild && !ctx->find_host) {
1138                                 logit("%s:%lu: ignoring host name "
1139                                     "with wildcard: %.64s", l->path,
1140                                     l->linenum, l->hosts);
1141                         }
1142                         return 0;
1143                 }
1144                 /*
1145                  * Split any comma-separated hostnames from the host list,
1146                  * hash and store separately.
1147                  */
1148                 ohosts = hosts = xstrdup(l->hosts);
1149                 while ((cp = strsep(&hosts, ",")) != NULL && *cp != '\0') {
1150                         lowercase(cp);
1151                         if ((hashed = host_hash(cp, NULL, 0)) == NULL)
1152                                 fatal("hash_host failed");
1153                         fprintf(ctx->out, "%s %s\n", hashed, l->rawkey);
1154                         ctx->has_unhashed = 1;
1155                 }
1156                 free(ohosts);
1157                 return 0;
1158         case HKF_STATUS_INVALID:
1159                 /* Retain invalid lines, but mark file as invalid. */
1160                 ctx->invalid = 1;
1161                 logit("%s:%lu: invalid line", l->path, l->linenum);
1162                 /* FALLTHROUGH */
1163         default:
1164                 fprintf(ctx->out, "%s\n", l->line);
1165                 return 0;
1166         }
1167         /* NOTREACHED */
1168         return -1;
1169 }
1170
1171 static int
1172 known_hosts_find_delete(struct hostkey_foreach_line *l, void *_ctx)
1173 {
1174         struct known_hosts_ctx *ctx = (struct known_hosts_ctx *)_ctx;
1175         enum sshkey_fp_rep rep;
1176         int fptype;
1177         char *fp;
1178
1179         fptype = print_bubblebabble ? SSH_DIGEST_SHA1 : fingerprint_hash;
1180         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_DEFAULT;
1181
1182         if (l->status == HKF_STATUS_MATCHED) {
1183                 if (ctx->delete_host) {
1184                         if (l->marker != MRK_NONE) {
1185                                 /* Don't remove CA and revocation lines */
1186                                 fprintf(ctx->out, "%s\n", l->line);
1187                         } else {
1188                                 /*
1189                                  * Hostname matches and has no CA/revoke
1190                                  * marker, delete it by *not* writing the
1191                                  * line to ctx->out.
1192                                  */
1193                                 ctx->found_key = 1;
1194                                 if (!quiet)
1195                                         printf("# Host %s found: line %lu\n",
1196                                             ctx->host, l->linenum);
1197                         }
1198                         return 0;
1199                 } else if (ctx->find_host) {
1200                         ctx->found_key = 1;
1201                         if (!quiet) {
1202                                 printf("# Host %s found: line %lu %s\n",
1203                                     ctx->host,
1204                                     l->linenum, l->marker == MRK_CA ? "CA" :
1205                                     (l->marker == MRK_REVOKE ? "REVOKED" : ""));
1206                         }
1207                         if (ctx->hash_hosts)
1208                                 known_hosts_hash(l, ctx);
1209                         else if (print_fingerprint) {
1210                                 fp = sshkey_fingerprint(l->key, fptype, rep);
1211                                 mprintf("%s %s %s %s\n", ctx->host,
1212                                     sshkey_type(l->key), fp, l->comment);
1213                                 free(fp);
1214                         } else
1215                                 fprintf(ctx->out, "%s\n", l->line);
1216                         return 0;
1217                 }
1218         } else if (ctx->delete_host) {
1219                 /* Retain non-matching hosts when deleting */
1220                 if (l->status == HKF_STATUS_INVALID) {
1221                         ctx->invalid = 1;
1222                         logit("%s:%lu: invalid line", l->path, l->linenum);
1223                 }
1224                 fprintf(ctx->out, "%s\n", l->line);
1225         }
1226         return 0;
1227 }
1228
1229 static void
1230 do_known_hosts(struct passwd *pw, const char *name, int find_host,
1231     int delete_host, int hash_hosts)
1232 {
1233         char *cp, tmp[PATH_MAX], old[PATH_MAX];
1234         int r, fd, oerrno, inplace = 0;
1235         struct known_hosts_ctx ctx;
1236         u_int foreach_options;
1237
1238         if (!have_identity) {
1239                 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
1240                 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
1241                     sizeof(identity_file))
1242                         fatal("Specified known hosts path too long");
1243                 free(cp);
1244                 have_identity = 1;
1245         }
1246
1247         memset(&ctx, 0, sizeof(ctx));
1248         ctx.out = stdout;
1249         ctx.host = name;
1250         ctx.hash_hosts = hash_hosts;
1251         ctx.find_host = find_host;
1252         ctx.delete_host = delete_host;
1253
1254         /*
1255          * Find hosts goes to stdout, hash and deletions happen in-place
1256          * A corner case is ssh-keygen -HF foo, which should go to stdout
1257          */
1258         if (!find_host && (hash_hosts || delete_host)) {
1259                 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
1260                     strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
1261                     strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
1262                     strlcat(old, ".old", sizeof(old)) >= sizeof(old))
1263                         fatal("known_hosts path too long");
1264                 umask(077);
1265                 if ((fd = mkstemp(tmp)) == -1)
1266                         fatal("mkstemp: %s", strerror(errno));
1267                 if ((ctx.out = fdopen(fd, "w")) == NULL) {
1268                         oerrno = errno;
1269                         unlink(tmp);
1270                         fatal("fdopen: %s", strerror(oerrno));
1271                 }
1272                 inplace = 1;
1273         }
1274         /* XXX support identity_file == "-" for stdin */
1275         foreach_options = find_host ? HKF_WANT_MATCH : 0;
1276         foreach_options |= print_fingerprint ? HKF_WANT_PARSE_KEY : 0;
1277         if ((r = hostkeys_foreach(identity_file, (find_host || !hash_hosts) ?
1278             known_hosts_find_delete : known_hosts_hash, &ctx, name, NULL,
1279             foreach_options)) != 0) {
1280                 if (inplace)
1281                         unlink(tmp);
1282                 fatal("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1283         }
1284
1285         if (inplace)
1286                 fclose(ctx.out);
1287
1288         if (ctx.invalid) {
1289                 error("%s is not a valid known_hosts file.", identity_file);
1290                 if (inplace) {
1291                         error("Not replacing existing known_hosts "
1292                             "file because of errors");
1293                         unlink(tmp);
1294                 }
1295                 exit(1);
1296         } else if (delete_host && !ctx.found_key) {
1297                 logit("Host %s not found in %s", name, identity_file);
1298                 if (inplace)
1299                         unlink(tmp);
1300         } else if (inplace) {
1301                 /* Backup existing file */
1302                 if (unlink(old) == -1 && errno != ENOENT)
1303                         fatal("unlink %.100s: %s", old, strerror(errno));
1304                 if (link(identity_file, old) == -1)
1305                         fatal("link %.100s to %.100s: %s", identity_file, old,
1306                             strerror(errno));
1307                 /* Move new one into place */
1308                 if (rename(tmp, identity_file) == -1) {
1309                         error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1310                             strerror(errno));
1311                         unlink(tmp);
1312                         unlink(old);
1313                         exit(1);
1314                 }
1315
1316                 printf("%s updated.\n", identity_file);
1317                 printf("Original contents retained as %s\n", old);
1318                 if (ctx.has_unhashed) {
1319                         logit("WARNING: %s contains unhashed entries", old);
1320                         logit("Delete this file to ensure privacy "
1321                             "of hostnames");
1322                 }
1323         }
1324
1325         exit (find_host && !ctx.found_key);
1326 }
1327
1328 /*
1329  * Perform changing a passphrase.  The argument is the passwd structure
1330  * for the current user.
1331  */
1332 static void
1333 do_change_passphrase(struct passwd *pw)
1334 {
1335         char *comment;
1336         char *old_passphrase, *passphrase1, *passphrase2;
1337         struct stat st;
1338         struct sshkey *private;
1339         int r;
1340
1341         if (!have_identity)
1342                 ask_filename(pw, "Enter file in which the key is");
1343         if (stat(identity_file, &st) < 0)
1344                 fatal("%s: %s", identity_file, strerror(errno));
1345         /* Try to load the file with empty passphrase. */
1346         r = sshkey_load_private(identity_file, "", &private, &comment);
1347         if (r == SSH_ERR_KEY_WRONG_PASSPHRASE) {
1348                 if (identity_passphrase)
1349                         old_passphrase = xstrdup(identity_passphrase);
1350                 else
1351                         old_passphrase =
1352                             read_passphrase("Enter old passphrase: ",
1353                             RP_ALLOW_STDIN);
1354                 r = sshkey_load_private(identity_file, old_passphrase,
1355                     &private, &comment);
1356                 explicit_bzero(old_passphrase, strlen(old_passphrase));
1357                 free(old_passphrase);
1358                 if (r != 0)
1359                         goto badkey;
1360         } else if (r != 0) {
1361  badkey:
1362                 fatal("Failed to load key %s: %s", identity_file, ssh_err(r));
1363         }
1364         if (comment)
1365                 mprintf("Key has comment '%s'\n", comment);
1366
1367         /* Ask the new passphrase (twice). */
1368         if (identity_new_passphrase) {
1369                 passphrase1 = xstrdup(identity_new_passphrase);
1370                 passphrase2 = NULL;
1371         } else {
1372                 passphrase1 =
1373                         read_passphrase("Enter new passphrase (empty for no "
1374                             "passphrase): ", RP_ALLOW_STDIN);
1375                 passphrase2 = read_passphrase("Enter same passphrase again: ",
1376                     RP_ALLOW_STDIN);
1377
1378                 /* Verify that they are the same. */
1379                 if (strcmp(passphrase1, passphrase2) != 0) {
1380                         explicit_bzero(passphrase1, strlen(passphrase1));
1381                         explicit_bzero(passphrase2, strlen(passphrase2));
1382                         free(passphrase1);
1383                         free(passphrase2);
1384                         printf("Pass phrases do not match.  Try again.\n");
1385                         exit(1);
1386                 }
1387                 /* Destroy the other copy. */
1388                 explicit_bzero(passphrase2, strlen(passphrase2));
1389                 free(passphrase2);
1390         }
1391
1392         /* Save the file using the new passphrase. */
1393         if ((r = sshkey_save_private(private, identity_file, passphrase1,
1394             comment, use_new_format, new_format_cipher, rounds)) != 0) {
1395                 error("Saving key \"%s\" failed: %s.",
1396                     identity_file, ssh_err(r));
1397                 explicit_bzero(passphrase1, strlen(passphrase1));
1398                 free(passphrase1);
1399                 sshkey_free(private);
1400                 free(comment);
1401                 exit(1);
1402         }
1403         /* Destroy the passphrase and the copy of the key in memory. */
1404         explicit_bzero(passphrase1, strlen(passphrase1));
1405         free(passphrase1);
1406         sshkey_free(private);            /* Destroys contents */
1407         free(comment);
1408
1409         printf("Your identification has been saved with the new passphrase.\n");
1410         exit(0);
1411 }
1412
1413 /*
1414  * Print the SSHFP RR.
1415  */
1416 static int
1417 do_print_resource_record(struct passwd *pw, char *fname, char *hname,
1418     int print_generic)
1419 {
1420         struct sshkey *public;
1421         char *comment = NULL;
1422         struct stat st;
1423         int r;
1424
1425         if (fname == NULL)
1426                 fatal("%s: no filename", __func__);
1427         if (stat(fname, &st) < 0) {
1428                 if (errno == ENOENT)
1429                         return 0;
1430                 fatal("%s: %s", fname, strerror(errno));
1431         }
1432         if ((r = sshkey_load_public(fname, &public, &comment)) != 0)
1433                 fatal("Failed to read v2 public key from \"%s\": %s.",
1434                     fname, ssh_err(r));
1435         export_dns_rr(hname, public, stdout, print_generic);
1436         sshkey_free(public);
1437         free(comment);
1438         return 1;
1439 }
1440
1441 /*
1442  * Change the comment of a private key file.
1443  */
1444 static void
1445 do_change_comment(struct passwd *pw, const char *identity_comment)
1446 {
1447         char new_comment[1024], *comment, *passphrase;
1448         struct sshkey *private;
1449         struct sshkey *public;
1450         struct stat st;
1451         FILE *f;
1452         int r, fd;
1453
1454         if (!have_identity)
1455                 ask_filename(pw, "Enter file in which the key is");
1456         if (stat(identity_file, &st) < 0)
1457                 fatal("%s: %s", identity_file, strerror(errno));
1458         if ((r = sshkey_load_private(identity_file, "",
1459             &private, &comment)) == 0)
1460                 passphrase = xstrdup("");
1461         else if (r != SSH_ERR_KEY_WRONG_PASSPHRASE)
1462                 fatal("Cannot load private key \"%s\": %s.",
1463                     identity_file, ssh_err(r));
1464         else {
1465                 if (identity_passphrase)
1466                         passphrase = xstrdup(identity_passphrase);
1467                 else if (identity_new_passphrase)
1468                         passphrase = xstrdup(identity_new_passphrase);
1469                 else
1470                         passphrase = read_passphrase("Enter passphrase: ",
1471                             RP_ALLOW_STDIN);
1472                 /* Try to load using the passphrase. */
1473                 if ((r = sshkey_load_private(identity_file, passphrase,
1474                     &private, &comment)) != 0) {
1475                         explicit_bzero(passphrase, strlen(passphrase));
1476                         free(passphrase);
1477                         fatal("Cannot load private key \"%s\": %s.",
1478                             identity_file, ssh_err(r));
1479                 }
1480         }
1481
1482         if (private->type != KEY_ED25519 && private->type != KEY_XMSS &&
1483             !use_new_format) {
1484                 error("Comments are only supported for keys stored in "
1485                     "the new format (-o).");
1486                 explicit_bzero(passphrase, strlen(passphrase));
1487                 sshkey_free(private);
1488                 exit(1);
1489         }
1490         if (comment)
1491                 printf("Key now has comment '%s'\n", comment);
1492         else
1493                 printf("Key now has no comment\n");
1494
1495         if (identity_comment) {
1496                 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1497         } else {
1498                 printf("Enter new comment: ");
1499                 fflush(stdout);
1500                 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1501                         explicit_bzero(passphrase, strlen(passphrase));
1502                         sshkey_free(private);
1503                         exit(1);
1504                 }
1505                 new_comment[strcspn(new_comment, "\n")] = '\0';
1506         }
1507
1508         /* Save the file using the new passphrase. */
1509         if ((r = sshkey_save_private(private, identity_file, passphrase,
1510             new_comment, use_new_format, new_format_cipher, rounds)) != 0) {
1511                 error("Saving key \"%s\" failed: %s",
1512                     identity_file, ssh_err(r));
1513                 explicit_bzero(passphrase, strlen(passphrase));
1514                 free(passphrase);
1515                 sshkey_free(private);
1516                 free(comment);
1517                 exit(1);
1518         }
1519         explicit_bzero(passphrase, strlen(passphrase));
1520         free(passphrase);
1521         if ((r = sshkey_from_private(private, &public)) != 0)
1522                 fatal("sshkey_from_private failed: %s", ssh_err(r));
1523         sshkey_free(private);
1524
1525         strlcat(identity_file, ".pub", sizeof(identity_file));
1526         fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1527         if (fd == -1)
1528                 fatal("Could not save your public key in %s", identity_file);
1529         f = fdopen(fd, "w");
1530         if (f == NULL)
1531                 fatal("fdopen %s failed: %s", identity_file, strerror(errno));
1532         if ((r = sshkey_write(public, f)) != 0)
1533                 fatal("write key failed: %s", ssh_err(r));
1534         sshkey_free(public);
1535         fprintf(f, " %s\n", new_comment);
1536         fclose(f);
1537
1538         free(comment);
1539
1540         printf("The comment in your key file has been changed.\n");
1541         exit(0);
1542 }
1543
1544 static void
1545 add_flag_option(struct sshbuf *c, const char *name)
1546 {
1547         int r;
1548
1549         debug3("%s: %s", __func__, name);
1550         if ((r = sshbuf_put_cstring(c, name)) != 0 ||
1551             (r = sshbuf_put_string(c, NULL, 0)) != 0)
1552                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1553 }
1554
1555 static void
1556 add_string_option(struct sshbuf *c, const char *name, const char *value)
1557 {
1558         struct sshbuf *b;
1559         int r;
1560
1561         debug3("%s: %s=%s", __func__, name, value);
1562         if ((b = sshbuf_new()) == NULL)
1563                 fatal("%s: sshbuf_new failed", __func__);
1564         if ((r = sshbuf_put_cstring(b, value)) != 0 ||
1565             (r = sshbuf_put_cstring(c, name)) != 0 ||
1566             (r = sshbuf_put_stringb(c, b)) != 0)
1567                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1568
1569         sshbuf_free(b);
1570 }
1571
1572 #define OPTIONS_CRITICAL        1
1573 #define OPTIONS_EXTENSIONS      2
1574 static void
1575 prepare_options_buf(struct sshbuf *c, int which)
1576 {
1577         size_t i;
1578
1579         sshbuf_reset(c);
1580         if ((which & OPTIONS_CRITICAL) != 0 &&
1581             certflags_command != NULL)
1582                 add_string_option(c, "force-command", certflags_command);
1583         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1584             (certflags_flags & CERTOPT_X_FWD) != 0)
1585                 add_flag_option(c, "permit-X11-forwarding");
1586         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1587             (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1588                 add_flag_option(c, "permit-agent-forwarding");
1589         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1590             (certflags_flags & CERTOPT_PORT_FWD) != 0)
1591                 add_flag_option(c, "permit-port-forwarding");
1592         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1593             (certflags_flags & CERTOPT_PTY) != 0)
1594                 add_flag_option(c, "permit-pty");
1595         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1596             (certflags_flags & CERTOPT_USER_RC) != 0)
1597                 add_flag_option(c, "permit-user-rc");
1598         if ((which & OPTIONS_CRITICAL) != 0 &&
1599             certflags_src_addr != NULL)
1600                 add_string_option(c, "source-address", certflags_src_addr);
1601         for (i = 0; i < ncert_userext; i++) {
1602                 if ((cert_userext[i].crit && (which & OPTIONS_EXTENSIONS)) ||
1603                     (!cert_userext[i].crit && (which & OPTIONS_CRITICAL)))
1604                         continue;
1605                 if (cert_userext[i].val == NULL)
1606                         add_flag_option(c, cert_userext[i].key);
1607                 else {
1608                         add_string_option(c, cert_userext[i].key,
1609                             cert_userext[i].val);
1610                 }
1611         }
1612 }
1613
1614 static struct sshkey *
1615 load_pkcs11_key(char *path)
1616 {
1617 #ifdef ENABLE_PKCS11
1618         struct sshkey **keys = NULL, *public, *private = NULL;
1619         int r, i, nkeys;
1620
1621         if ((r = sshkey_load_public(path, &public, NULL)) != 0)
1622                 fatal("Couldn't load CA public key \"%s\": %s",
1623                     path, ssh_err(r));
1624
1625         nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1626         debug3("%s: %d keys", __func__, nkeys);
1627         if (nkeys <= 0)
1628                 fatal("cannot read public key from pkcs11");
1629         for (i = 0; i < nkeys; i++) {
1630                 if (sshkey_equal_public(public, keys[i])) {
1631                         private = keys[i];
1632                         continue;
1633                 }
1634                 sshkey_free(keys[i]);
1635         }
1636         free(keys);
1637         sshkey_free(public);
1638         return private;
1639 #else
1640         fatal("no pkcs11 support");
1641 #endif /* ENABLE_PKCS11 */
1642 }
1643
1644 /* Signer for sshkey_certify_custom that uses the agent */
1645 static int
1646 agent_signer(const struct sshkey *key, u_char **sigp, size_t *lenp,
1647     const u_char *data, size_t datalen,
1648     const char *alg, u_int compat, void *ctx)
1649 {
1650         int *agent_fdp = (int *)ctx;
1651
1652         return ssh_agent_sign(*agent_fdp, key, sigp, lenp,
1653             data, datalen, alg, compat);
1654 }
1655
1656 static void
1657 do_ca_sign(struct passwd *pw, const char *ca_key_path, int prefer_agent,
1658     unsigned long long cert_serial, int cert_serial_autoinc,
1659     int argc, char **argv)
1660 {
1661         int r, i, fd, found, agent_fd = -1;
1662         u_int n;
1663         struct sshkey *ca, *public;
1664         char valid[64], *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1665         FILE *f;
1666         struct ssh_identitylist *agent_ids;
1667         size_t j;
1668
1669 #ifdef ENABLE_PKCS11
1670         pkcs11_init(1);
1671 #endif
1672         tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1673         if (pkcs11provider != NULL) {
1674                 /* If a PKCS#11 token was specified then try to use it */
1675                 if ((ca = load_pkcs11_key(tmp)) == NULL)
1676                         fatal("No PKCS#11 key matching %s found", ca_key_path);
1677         } else if (prefer_agent) {
1678                 /*
1679                  * Agent signature requested. Try to use agent after making
1680                  * sure the public key specified is actually present in the
1681                  * agent.
1682                  */
1683                 if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
1684                         fatal("Cannot load CA public key %s: %s",
1685                             tmp, ssh_err(r));
1686                 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0)
1687                         fatal("Cannot use public key for CA signature: %s",
1688                             ssh_err(r));
1689                 if ((r = ssh_fetch_identitylist(agent_fd, &agent_ids)) != 0)
1690                         fatal("Retrieve agent key list: %s", ssh_err(r));
1691                 found = 0;
1692                 for (j = 0; j < agent_ids->nkeys; j++) {
1693                         if (sshkey_equal(ca, agent_ids->keys[j])) {
1694                                 found = 1;
1695                                 break;
1696                         }
1697                 }
1698                 if (!found)
1699                         fatal("CA key %s not found in agent", tmp);
1700                 ssh_free_identitylist(agent_ids);
1701                 ca->flags |= SSHKEY_FLAG_EXT;
1702         } else {
1703                 /* CA key is assumed to be a private key on the filesystem */
1704                 ca = load_identity(tmp);
1705         }
1706         free(tmp);
1707
1708         if (key_type_name != NULL &&
1709             sshkey_type_from_name(key_type_name) != ca->type)  {
1710                 fatal("CA key type %s doesn't match specified %s",
1711                     sshkey_ssh_name(ca), key_type_name);
1712         }
1713
1714         for (i = 0; i < argc; i++) {
1715                 /* Split list of principals */
1716                 n = 0;
1717                 if (cert_principals != NULL) {
1718                         otmp = tmp = xstrdup(cert_principals);
1719                         plist = NULL;
1720                         for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1721                                 plist = xreallocarray(plist, n + 1, sizeof(*plist));
1722                                 if (*(plist[n] = xstrdup(cp)) == '\0')
1723                                         fatal("Empty principal name");
1724                         }
1725                         free(otmp);
1726                 }
1727                 if (n > SSHKEY_CERT_MAX_PRINCIPALS)
1728                         fatal("Too many certificate principals specified");
1729         
1730                 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1731                 if ((r = sshkey_load_public(tmp, &public, &comment)) != 0)
1732                         fatal("%s: unable to open \"%s\": %s",
1733                             __func__, tmp, ssh_err(r));
1734                 if (public->type != KEY_RSA && public->type != KEY_DSA &&
1735                     public->type != KEY_ECDSA && public->type != KEY_ED25519 &&
1736                     public->type != KEY_XMSS)
1737                         fatal("%s: key \"%s\" type %s cannot be certified",
1738                             __func__, tmp, sshkey_type(public));
1739
1740                 /* Prepare certificate to sign */
1741                 if ((r = sshkey_to_certified(public)) != 0)
1742                         fatal("Could not upgrade key %s to certificate: %s",
1743                             tmp, ssh_err(r));
1744                 public->cert->type = cert_key_type;
1745                 public->cert->serial = (u_int64_t)cert_serial;
1746                 public->cert->key_id = xstrdup(cert_key_id);
1747                 public->cert->nprincipals = n;
1748                 public->cert->principals = plist;
1749                 public->cert->valid_after = cert_valid_from;
1750                 public->cert->valid_before = cert_valid_to;
1751                 prepare_options_buf(public->cert->critical, OPTIONS_CRITICAL);
1752                 prepare_options_buf(public->cert->extensions,
1753                     OPTIONS_EXTENSIONS);
1754                 if ((r = sshkey_from_private(ca,
1755                     &public->cert->signature_key)) != 0)
1756                         fatal("sshkey_from_private (ca key): %s", ssh_err(r));
1757
1758                 if (agent_fd != -1 && (ca->flags & SSHKEY_FLAG_EXT) != 0) {
1759                         if ((r = sshkey_certify_custom(public, ca,
1760                             key_type_name, agent_signer, &agent_fd)) != 0)
1761                                 fatal("Couldn't certify key %s via agent: %s",
1762                                     tmp, ssh_err(r));
1763                 } else {
1764                         if ((sshkey_certify(public, ca, key_type_name)) != 0)
1765                                 fatal("Couldn't certify key %s: %s",
1766                                     tmp, ssh_err(r));
1767                 }
1768
1769                 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1770                         *cp = '\0';
1771                 xasprintf(&out, "%s-cert.pub", tmp);
1772                 free(tmp);
1773
1774                 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1775                         fatal("Could not open \"%s\" for writing: %s", out,
1776                             strerror(errno));
1777                 if ((f = fdopen(fd, "w")) == NULL)
1778                         fatal("%s: fdopen: %s", __func__, strerror(errno));
1779                 if ((r = sshkey_write(public, f)) != 0)
1780                         fatal("Could not write certified key to %s: %s",
1781                             out, ssh_err(r));
1782                 fprintf(f, " %s\n", comment);
1783                 fclose(f);
1784
1785                 if (!quiet) {
1786                         sshkey_format_cert_validity(public->cert,
1787                             valid, sizeof(valid));
1788                         logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1789                             "valid %s", sshkey_cert_type(public),
1790                             out, public->cert->key_id,
1791                             (unsigned long long)public->cert->serial,
1792                             cert_principals != NULL ? " for " : "",
1793                             cert_principals != NULL ? cert_principals : "",
1794                             valid);
1795                 }
1796
1797                 sshkey_free(public);
1798                 free(out);
1799                 if (cert_serial_autoinc)
1800                         cert_serial++;
1801         }
1802 #ifdef ENABLE_PKCS11
1803         pkcs11_terminate();
1804 #endif
1805         exit(0);
1806 }
1807
1808 static u_int64_t
1809 parse_relative_time(const char *s, time_t now)
1810 {
1811         int64_t mul, secs;
1812
1813         mul = *s == '-' ? -1 : 1;
1814
1815         if ((secs = convtime(s + 1)) == -1)
1816                 fatal("Invalid relative certificate time %s", s);
1817         if (mul == -1 && secs > now)
1818                 fatal("Certificate time %s cannot be represented", s);
1819         return now + (u_int64_t)(secs * mul);
1820 }
1821
1822 static void
1823 parse_cert_times(char *timespec)
1824 {
1825         char *from, *to;
1826         time_t now = time(NULL);
1827         int64_t secs;
1828
1829         /* +timespec relative to now */
1830         if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1831                 if ((secs = convtime(timespec + 1)) == -1)
1832                         fatal("Invalid relative certificate life %s", timespec);
1833                 cert_valid_to = now + secs;
1834                 /*
1835                  * Backdate certificate one minute to avoid problems on hosts
1836                  * with poorly-synchronised clocks.
1837                  */
1838                 cert_valid_from = ((now - 59)/ 60) * 60;
1839                 return;
1840         }
1841
1842         /*
1843          * from:to, where
1844          * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "always"
1845          *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS | "forever"
1846          */
1847         from = xstrdup(timespec);
1848         to = strchr(from, ':');
1849         if (to == NULL || from == to || *(to + 1) == '\0')
1850                 fatal("Invalid certificate life specification %s", timespec);
1851         *to++ = '\0';
1852
1853         if (*from == '-' || *from == '+')
1854                 cert_valid_from = parse_relative_time(from, now);
1855         else if (strcmp(from, "always") == 0)
1856                 cert_valid_from = 0;
1857         else if (parse_absolute_time(from, &cert_valid_from) != 0)
1858                 fatal("Invalid from time \"%s\"", from);
1859
1860         if (*to == '-' || *to == '+')
1861                 cert_valid_to = parse_relative_time(to, now);
1862         else if (strcmp(to, "forever") == 0)
1863                 cert_valid_to = ~(u_int64_t)0;
1864         else if (parse_absolute_time(to, &cert_valid_to) != 0)
1865                 fatal("Invalid to time \"%s\"", to);
1866
1867         if (cert_valid_to <= cert_valid_from)
1868                 fatal("Empty certificate validity interval");
1869         free(from);
1870 }
1871
1872 static void
1873 add_cert_option(char *opt)
1874 {
1875         char *val, *cp;
1876         int iscrit = 0;
1877
1878         if (strcasecmp(opt, "clear") == 0)
1879                 certflags_flags = 0;
1880         else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1881                 certflags_flags &= ~CERTOPT_X_FWD;
1882         else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1883                 certflags_flags |= CERTOPT_X_FWD;
1884         else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1885                 certflags_flags &= ~CERTOPT_AGENT_FWD;
1886         else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1887                 certflags_flags |= CERTOPT_AGENT_FWD;
1888         else if (strcasecmp(opt, "no-port-forwarding") == 0)
1889                 certflags_flags &= ~CERTOPT_PORT_FWD;
1890         else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1891                 certflags_flags |= CERTOPT_PORT_FWD;
1892         else if (strcasecmp(opt, "no-pty") == 0)
1893                 certflags_flags &= ~CERTOPT_PTY;
1894         else if (strcasecmp(opt, "permit-pty") == 0)
1895                 certflags_flags |= CERTOPT_PTY;
1896         else if (strcasecmp(opt, "no-user-rc") == 0)
1897                 certflags_flags &= ~CERTOPT_USER_RC;
1898         else if (strcasecmp(opt, "permit-user-rc") == 0)
1899                 certflags_flags |= CERTOPT_USER_RC;
1900         else if (strncasecmp(opt, "force-command=", 14) == 0) {
1901                 val = opt + 14;
1902                 if (*val == '\0')
1903                         fatal("Empty force-command option");
1904                 if (certflags_command != NULL)
1905                         fatal("force-command already specified");
1906                 certflags_command = xstrdup(val);
1907         } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1908                 val = opt + 15;
1909                 if (*val == '\0')
1910                         fatal("Empty source-address option");
1911                 if (certflags_src_addr != NULL)
1912                         fatal("source-address already specified");
1913                 if (addr_match_cidr_list(NULL, val) != 0)
1914                         fatal("Invalid source-address list");
1915                 certflags_src_addr = xstrdup(val);
1916         } else if (strncasecmp(opt, "extension:", 10) == 0 ||
1917                    (iscrit = (strncasecmp(opt, "critical:", 9) == 0))) {
1918                 val = xstrdup(strchr(opt, ':') + 1);
1919                 if ((cp = strchr(val, '=')) != NULL)
1920                         *cp++ = '\0';
1921                 cert_userext = xreallocarray(cert_userext, ncert_userext + 1,
1922                     sizeof(*cert_userext));
1923                 cert_userext[ncert_userext].key = val;
1924                 cert_userext[ncert_userext].val = cp == NULL ?
1925                     NULL : xstrdup(cp);
1926                 cert_userext[ncert_userext].crit = iscrit;
1927                 ncert_userext++;
1928         } else
1929                 fatal("Unsupported certificate option \"%s\"", opt);
1930 }
1931
1932 static void
1933 show_options(struct sshbuf *optbuf, int in_critical)
1934 {
1935         char *name, *arg;
1936         struct sshbuf *options, *option = NULL;
1937         int r;
1938
1939         if ((options = sshbuf_fromb(optbuf)) == NULL)
1940                 fatal("%s: sshbuf_fromb failed", __func__);
1941         while (sshbuf_len(options) != 0) {
1942                 sshbuf_free(option);
1943                 option = NULL;
1944                 if ((r = sshbuf_get_cstring(options, &name, NULL)) != 0 ||
1945                     (r = sshbuf_froms(options, &option)) != 0)
1946                         fatal("%s: buffer error: %s", __func__, ssh_err(r));
1947                 printf("                %s", name);
1948                 if (!in_critical &&
1949                     (strcmp(name, "permit-X11-forwarding") == 0 ||
1950                     strcmp(name, "permit-agent-forwarding") == 0 ||
1951                     strcmp(name, "permit-port-forwarding") == 0 ||
1952                     strcmp(name, "permit-pty") == 0 ||
1953                     strcmp(name, "permit-user-rc") == 0))
1954                         printf("\n");
1955                 else if (in_critical &&
1956                     (strcmp(name, "force-command") == 0 ||
1957                     strcmp(name, "source-address") == 0)) {
1958                         if ((r = sshbuf_get_cstring(option, &arg, NULL)) != 0)
1959                                 fatal("%s: buffer error: %s",
1960                                     __func__, ssh_err(r));
1961                         printf(" %s\n", arg);
1962                         free(arg);
1963                 } else {
1964                         printf(" UNKNOWN OPTION (len %zu)\n",
1965                             sshbuf_len(option));
1966                         sshbuf_reset(option);
1967                 }
1968                 free(name);
1969                 if (sshbuf_len(option) != 0)
1970                         fatal("Option corrupt: extra data at end");
1971         }
1972         sshbuf_free(option);
1973         sshbuf_free(options);
1974 }
1975
1976 static void
1977 print_cert(struct sshkey *key)
1978 {
1979         char valid[64], *key_fp, *ca_fp;
1980         u_int i;
1981
1982         key_fp = sshkey_fingerprint(key, fingerprint_hash, SSH_FP_DEFAULT);
1983         ca_fp = sshkey_fingerprint(key->cert->signature_key,
1984             fingerprint_hash, SSH_FP_DEFAULT);
1985         if (key_fp == NULL || ca_fp == NULL)
1986                 fatal("%s: sshkey_fingerprint fail", __func__);
1987         sshkey_format_cert_validity(key->cert, valid, sizeof(valid));
1988
1989         printf("        Type: %s %s certificate\n", sshkey_ssh_name(key),
1990             sshkey_cert_type(key));
1991         printf("        Public key: %s %s\n", sshkey_type(key), key_fp);
1992         printf("        Signing CA: %s %s (using %s)\n",
1993             sshkey_type(key->cert->signature_key), ca_fp,
1994             key->cert->signature_type);
1995         printf("        Key ID: \"%s\"\n", key->cert->key_id);
1996         printf("        Serial: %llu\n", (unsigned long long)key->cert->serial);
1997         printf("        Valid: %s\n", valid);
1998         printf("        Principals: ");
1999         if (key->cert->nprincipals == 0)
2000                 printf("(none)\n");
2001         else {
2002                 for (i = 0; i < key->cert->nprincipals; i++)
2003                         printf("\n                %s",
2004                             key->cert->principals[i]);
2005                 printf("\n");
2006         }
2007         printf("        Critical Options: ");
2008         if (sshbuf_len(key->cert->critical) == 0)
2009                 printf("(none)\n");
2010         else {
2011                 printf("\n");
2012                 show_options(key->cert->critical, 1);
2013         }
2014         printf("        Extensions: ");
2015         if (sshbuf_len(key->cert->extensions) == 0)
2016                 printf("(none)\n");
2017         else {
2018                 printf("\n");
2019                 show_options(key->cert->extensions, 0);
2020         }
2021 }
2022
2023 static void
2024 do_show_cert(struct passwd *pw)
2025 {
2026         struct sshkey *key = NULL;
2027         struct stat st;
2028         int r, is_stdin = 0, ok = 0;
2029         FILE *f;
2030         char *cp, *line = NULL;
2031         const char *path;
2032         size_t linesize = 0;
2033         u_long lnum = 0;
2034
2035         if (!have_identity)
2036                 ask_filename(pw, "Enter file in which the key is");
2037         if (strcmp(identity_file, "-") != 0 && stat(identity_file, &st) < 0)
2038                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
2039
2040         path = identity_file;
2041         if (strcmp(path, "-") == 0) {
2042                 f = stdin;
2043                 path = "(stdin)";
2044                 is_stdin = 1;
2045         } else if ((f = fopen(identity_file, "r")) == NULL)
2046                 fatal("fopen %s: %s", identity_file, strerror(errno));
2047
2048         while (getline(&line, &linesize, f) != -1) {
2049                 lnum++;
2050                 sshkey_free(key);
2051                 key = NULL;
2052                 /* Trim leading space and comments */
2053                 cp = line + strspn(line, " \t");
2054                 if (*cp == '#' || *cp == '\0')
2055                         continue;
2056                 if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2057                         fatal("sshkey_new");
2058                 if ((r = sshkey_read(key, &cp)) != 0) {
2059                         error("%s:%lu: invalid key: %s", path,
2060                             lnum, ssh_err(r));
2061                         continue;
2062                 }
2063                 if (!sshkey_is_cert(key)) {
2064                         error("%s:%lu is not a certificate", path, lnum);
2065                         continue;
2066                 }
2067                 ok = 1;
2068                 if (!is_stdin && lnum == 1)
2069                         printf("%s:\n", path);
2070                 else
2071                         printf("%s:%lu:\n", path, lnum);
2072                 print_cert(key);
2073         }
2074         free(line);
2075         sshkey_free(key);
2076         fclose(f);
2077         exit(ok ? 0 : 1);
2078 }
2079
2080 static void
2081 load_krl(const char *path, struct ssh_krl **krlp)
2082 {
2083         struct sshbuf *krlbuf;
2084         int r, fd;
2085
2086         if ((krlbuf = sshbuf_new()) == NULL)
2087                 fatal("sshbuf_new failed");
2088         if ((fd = open(path, O_RDONLY)) == -1)
2089                 fatal("open %s: %s", path, strerror(errno));
2090         if ((r = sshkey_load_file(fd, krlbuf)) != 0)
2091                 fatal("Unable to load KRL: %s", ssh_err(r));
2092         close(fd);
2093         /* XXX check sigs */
2094         if ((r = ssh_krl_from_blob(krlbuf, krlp, NULL, 0)) != 0 ||
2095             *krlp == NULL)
2096                 fatal("Invalid KRL file: %s", ssh_err(r));
2097         sshbuf_free(krlbuf);
2098 }
2099
2100 static void
2101 hash_to_blob(const char *cp, u_char **blobp, size_t *lenp,
2102     const char *file, u_long lnum)
2103 {
2104         char *tmp;
2105         size_t tlen;
2106         struct sshbuf *b;
2107         int r;
2108
2109         if (strncmp(cp, "SHA256:", 7) != 0)
2110                 fatal("%s:%lu: unsupported hash algorithm", file, lnum);
2111         cp += 7;
2112
2113         /*
2114          * OpenSSH base64 hashes omit trailing '='
2115          * characters; put them back for decode.
2116          */
2117         tlen = strlen(cp);
2118         tmp = xmalloc(tlen + 4 + 1);
2119         strlcpy(tmp, cp, tlen + 1);
2120         while ((tlen % 4) != 0) {
2121                 tmp[tlen++] = '=';
2122                 tmp[tlen] = '\0';
2123         }
2124         if ((b = sshbuf_new()) == NULL)
2125                 fatal("%s: sshbuf_new failed", __func__);
2126         if ((r = sshbuf_b64tod(b, tmp)) != 0)
2127                 fatal("%s:%lu: decode hash failed: %s", file, lnum, ssh_err(r));
2128         free(tmp);
2129         *lenp = sshbuf_len(b);
2130         *blobp = xmalloc(*lenp);
2131         memcpy(*blobp, sshbuf_ptr(b), *lenp);
2132         sshbuf_free(b);
2133 }
2134
2135 static void
2136 update_krl_from_file(struct passwd *pw, const char *file, int wild_ca,
2137     const struct sshkey *ca, struct ssh_krl *krl)
2138 {
2139         struct sshkey *key = NULL;
2140         u_long lnum = 0;
2141         char *path, *cp, *ep, *line = NULL;
2142         u_char *blob = NULL;
2143         size_t blen = 0, linesize = 0;
2144         unsigned long long serial, serial2;
2145         int i, was_explicit_key, was_sha1, was_sha256, was_hash, r;
2146         FILE *krl_spec;
2147
2148         path = tilde_expand_filename(file, pw->pw_uid);
2149         if (strcmp(path, "-") == 0) {
2150                 krl_spec = stdin;
2151                 free(path);
2152                 path = xstrdup("(standard input)");
2153         } else if ((krl_spec = fopen(path, "r")) == NULL)
2154                 fatal("fopen %s: %s", path, strerror(errno));
2155
2156         if (!quiet)
2157                 printf("Revoking from %s\n", path);
2158         while (getline(&line, &linesize, krl_spec) != -1) {
2159                 lnum++;
2160                 was_explicit_key = was_sha1 = was_sha256 = was_hash = 0;
2161                 cp = line + strspn(line, " \t");
2162                 /* Trim trailing space, comments and strip \n */
2163                 for (i = 0, r = -1; cp[i] != '\0'; i++) {
2164                         if (cp[i] == '#' || cp[i] == '\n') {
2165                                 cp[i] = '\0';
2166                                 break;
2167                         }
2168                         if (cp[i] == ' ' || cp[i] == '\t') {
2169                                 /* Remember the start of a span of whitespace */
2170                                 if (r == -1)
2171                                         r = i;
2172                         } else
2173                                 r = -1;
2174                 }
2175                 if (r != -1)
2176                         cp[r] = '\0';
2177                 if (*cp == '\0')
2178                         continue;
2179                 if (strncasecmp(cp, "serial:", 7) == 0) {
2180                         if (ca == NULL && !wild_ca) {
2181                                 fatal("revoking certificates by serial number "
2182                                     "requires specification of a CA key");
2183                         }
2184                         cp += 7;
2185                         cp = cp + strspn(cp, " \t");
2186                         errno = 0;
2187                         serial = strtoull(cp, &ep, 0);
2188                         if (*cp == '\0' || (*ep != '\0' && *ep != '-'))
2189                                 fatal("%s:%lu: invalid serial \"%s\"",
2190                                     path, lnum, cp);
2191                         if (errno == ERANGE && serial == ULLONG_MAX)
2192                                 fatal("%s:%lu: serial out of range",
2193                                     path, lnum);
2194                         serial2 = serial;
2195                         if (*ep == '-') {
2196                                 cp = ep + 1;
2197                                 errno = 0;
2198                                 serial2 = strtoull(cp, &ep, 0);
2199                                 if (*cp == '\0' || *ep != '\0')
2200                                         fatal("%s:%lu: invalid serial \"%s\"",
2201                                             path, lnum, cp);
2202                                 if (errno == ERANGE && serial2 == ULLONG_MAX)
2203                                         fatal("%s:%lu: serial out of range",
2204                                             path, lnum);
2205                                 if (serial2 <= serial)
2206                                         fatal("%s:%lu: invalid serial range "
2207                                             "%llu:%llu", path, lnum,
2208                                             (unsigned long long)serial,
2209                                             (unsigned long long)serial2);
2210                         }
2211                         if (ssh_krl_revoke_cert_by_serial_range(krl,
2212                             ca, serial, serial2) != 0) {
2213                                 fatal("%s: revoke serial failed",
2214                                     __func__);
2215                         }
2216                 } else if (strncasecmp(cp, "id:", 3) == 0) {
2217                         if (ca == NULL && !wild_ca) {
2218                                 fatal("revoking certificates by key ID "
2219                                     "requires specification of a CA key");
2220                         }
2221                         cp += 3;
2222                         cp = cp + strspn(cp, " \t");
2223                         if (ssh_krl_revoke_cert_by_key_id(krl, ca, cp) != 0)
2224                                 fatal("%s: revoke key ID failed", __func__);
2225                 } else if (strncasecmp(cp, "hash:", 5) == 0) {
2226                         cp += 5;
2227                         cp = cp + strspn(cp, " \t");
2228                         hash_to_blob(cp, &blob, &blen, file, lnum);
2229                         r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2230                 } else {
2231                         if (strncasecmp(cp, "key:", 4) == 0) {
2232                                 cp += 4;
2233                                 cp = cp + strspn(cp, " \t");
2234                                 was_explicit_key = 1;
2235                         } else if (strncasecmp(cp, "sha1:", 5) == 0) {
2236                                 cp += 5;
2237                                 cp = cp + strspn(cp, " \t");
2238                                 was_sha1 = 1;
2239                         } else if (strncasecmp(cp, "sha256:", 7) == 0) {
2240                                 cp += 7;
2241                                 cp = cp + strspn(cp, " \t");
2242                                 was_sha256 = 1;
2243                                 /*
2244                                  * Just try to process the line as a key.
2245                                  * Parsing will fail if it isn't.
2246                                  */
2247                         }
2248                         if ((key = sshkey_new(KEY_UNSPEC)) == NULL)
2249                                 fatal("sshkey_new");
2250                         if ((r = sshkey_read(key, &cp)) != 0)
2251                                 fatal("%s:%lu: invalid key: %s",
2252                                     path, lnum, ssh_err(r));
2253                         if (was_explicit_key)
2254                                 r = ssh_krl_revoke_key_explicit(krl, key);
2255                         else if (was_sha1) {
2256                                 if (sshkey_fingerprint_raw(key,
2257                                     SSH_DIGEST_SHA1, &blob, &blen) != 0) {
2258                                         fatal("%s:%lu: fingerprint failed",
2259                                             file, lnum);
2260                                 }
2261                                 r = ssh_krl_revoke_key_sha1(krl, blob, blen);
2262                         } else if (was_sha256) {
2263                                 if (sshkey_fingerprint_raw(key,
2264                                     SSH_DIGEST_SHA256, &blob, &blen) != 0) {
2265                                         fatal("%s:%lu: fingerprint failed",
2266                                             file, lnum);
2267                                 }
2268                                 r = ssh_krl_revoke_key_sha256(krl, blob, blen);
2269                         } else
2270                                 r = ssh_krl_revoke_key(krl, key);
2271                         if (r != 0)
2272                                 fatal("%s: revoke key failed: %s",
2273                                     __func__, ssh_err(r));
2274                         freezero(blob, blen);
2275                         blob = NULL;
2276                         blen = 0;
2277                         sshkey_free(key);
2278                 }
2279         }
2280         if (strcmp(path, "-") != 0)
2281                 fclose(krl_spec);
2282         free(line);
2283         free(path);
2284 }
2285
2286 static void
2287 do_gen_krl(struct passwd *pw, int updating, const char *ca_key_path,
2288     unsigned long long krl_version, const char *krl_comment,
2289     int argc, char **argv)
2290 {
2291         struct ssh_krl *krl;
2292         struct stat sb;
2293         struct sshkey *ca = NULL;
2294         int fd, i, r, wild_ca = 0;
2295         char *tmp;
2296         struct sshbuf *kbuf;
2297
2298         if (*identity_file == '\0')
2299                 fatal("KRL generation requires an output file");
2300         if (stat(identity_file, &sb) == -1) {
2301                 if (errno != ENOENT)
2302                         fatal("Cannot access KRL \"%s\": %s",
2303                             identity_file, strerror(errno));
2304                 if (updating)
2305                         fatal("KRL \"%s\" does not exist", identity_file);
2306         }
2307         if (ca_key_path != NULL) {
2308                 if (strcasecmp(ca_key_path, "none") == 0)
2309                         wild_ca = 1;
2310                 else {
2311                         tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
2312                         if ((r = sshkey_load_public(tmp, &ca, NULL)) != 0)
2313                                 fatal("Cannot load CA public key %s: %s",
2314                                     tmp, ssh_err(r));
2315                         free(tmp);
2316                 }
2317         }
2318
2319         if (updating)
2320                 load_krl(identity_file, &krl);
2321         else if ((krl = ssh_krl_init()) == NULL)
2322                 fatal("couldn't create KRL");
2323
2324         if (krl_version != 0)
2325                 ssh_krl_set_version(krl, krl_version);
2326         if (krl_comment != NULL)
2327                 ssh_krl_set_comment(krl, krl_comment);
2328
2329         for (i = 0; i < argc; i++)
2330                 update_krl_from_file(pw, argv[i], wild_ca, ca, krl);
2331
2332         if ((kbuf = sshbuf_new()) == NULL)
2333                 fatal("sshbuf_new failed");
2334         if (ssh_krl_to_blob(krl, kbuf, NULL, 0) != 0)
2335                 fatal("Couldn't generate KRL");
2336         if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2337                 fatal("open %s: %s", identity_file, strerror(errno));
2338         if (atomicio(vwrite, fd, sshbuf_mutable_ptr(kbuf), sshbuf_len(kbuf)) !=
2339             sshbuf_len(kbuf))
2340                 fatal("write %s: %s", identity_file, strerror(errno));
2341         close(fd);
2342         sshbuf_free(kbuf);
2343         ssh_krl_free(krl);
2344         sshkey_free(ca);
2345 }
2346
2347 static void
2348 do_check_krl(struct passwd *pw, int argc, char **argv)
2349 {
2350         int i, r, ret = 0;
2351         char *comment;
2352         struct ssh_krl *krl;
2353         struct sshkey *k;
2354
2355         if (*identity_file == '\0')
2356                 fatal("KRL checking requires an input file");
2357         load_krl(identity_file, &krl);
2358         for (i = 0; i < argc; i++) {
2359                 if ((r = sshkey_load_public(argv[i], &k, &comment)) != 0)
2360                         fatal("Cannot load public key %s: %s",
2361                             argv[i], ssh_err(r));
2362                 r = ssh_krl_check_key(krl, k);
2363                 printf("%s%s%s%s: %s\n", argv[i],
2364                     *comment ? " (" : "", comment, *comment ? ")" : "",
2365                     r == 0 ? "ok" : "REVOKED");
2366                 if (r != 0)
2367                         ret = 1;
2368                 sshkey_free(k);
2369                 free(comment);
2370         }
2371         ssh_krl_free(krl);
2372         exit(ret);
2373 }
2374
2375 static void
2376 usage(void)
2377 {
2378         fprintf(stderr,
2379             "usage: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa] [-m format]\n"
2380             "                  [-N new_passphrase] [-C comment] [-f output_keyfile]\n"
2381             "       ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-m format]\n"
2382             "                   [-f keyfile]\n"
2383             "       ssh-keygen -i [-m key_format] [-f input_keyfile]\n"
2384             "       ssh-keygen -e [-m key_format] [-f input_keyfile]\n"
2385             "       ssh-keygen -y [-f input_keyfile]\n"
2386             "       ssh-keygen -c [-P passphrase] [-C comment] [-f keyfile]\n"
2387             "       ssh-keygen -l [-v] [-E fingerprint_hash] [-f input_keyfile]\n"
2388             "       ssh-keygen -B [-f input_keyfile]\n");
2389 #ifdef ENABLE_PKCS11
2390         fprintf(stderr,
2391             "       ssh-keygen -D pkcs11\n");
2392 #endif
2393         fprintf(stderr,
2394             "       ssh-keygen -F hostname [-f known_hosts_file] [-l]\n"
2395             "       ssh-keygen -H [-f known_hosts_file]\n"
2396             "       ssh-keygen -R hostname [-f known_hosts_file]\n"
2397             "       ssh-keygen -r hostname [-f input_keyfile] [-g]\n"
2398 #ifdef WITH_OPENSSL
2399             "       ssh-keygen -G output_file [-v] [-b bits] [-M memory] [-S start_point]\n"
2400             "       ssh-keygen -T output_file -f input_file [-v] [-a rounds] [-J num_lines]\n"
2401             "                  [-j start_line] [-K checkpt] [-W generator]\n"
2402 #endif
2403             "       ssh-keygen -s ca_key -I certificate_identity [-h] [-U]\n"
2404             "                  [-D pkcs11_provider] [-n principals] [-O option]\n"
2405             "                  [-V validity_interval] [-z serial_number] file ...\n"
2406             "       ssh-keygen -L [-f input_keyfile]\n"
2407             "       ssh-keygen -A\n"
2408             "       ssh-keygen -k -f krl_file [-u] [-s ca_public] [-z version_number]\n"
2409             "                  file ...\n"
2410             "       ssh-keygen -Q -f krl_file file ...\n");
2411         exit(1);
2412 }
2413
2414 /*
2415  * Main program for key management.
2416  */
2417 int
2418 main(int argc, char **argv)
2419 {
2420         char dotsshdir[PATH_MAX], comment[1024], *passphrase1, *passphrase2;
2421         char *rr_hostname = NULL, *ep, *fp, *ra;
2422         struct sshkey *private, *public;
2423         struct passwd *pw;
2424         struct stat st;
2425         int r, opt, type, fd;
2426         int change_passphrase = 0, change_comment = 0, show_cert = 0;
2427         int find_host = 0, delete_host = 0, hash_hosts = 0;
2428         int gen_all_hostkeys = 0, gen_krl = 0, update_krl = 0, check_krl = 0;
2429         int prefer_agent = 0, convert_to = 0, convert_from = 0;
2430         int print_public = 0, print_generic = 0, cert_serial_autoinc = 0;
2431         unsigned long long cert_serial = 0;
2432         char *identity_comment = NULL, *ca_key_path = NULL;
2433         u_int bits = 0;
2434         FILE *f;
2435         const char *errstr;
2436         int log_level = SYSLOG_LEVEL_INFO;
2437 #ifdef WITH_OPENSSL
2438         /* Moduli generation/screening */
2439         char out_file[PATH_MAX], *checkpoint = NULL;
2440         u_int32_t memory = 0, generator_wanted = 0;
2441         int do_gen_candidates = 0, do_screen_candidates = 0;
2442         unsigned long start_lineno = 0, lines_to_process = 0;
2443         BIGNUM *start = NULL;
2444 #endif
2445
2446         extern int optind;
2447         extern char *optarg;
2448
2449         ssh_malloc_init();      /* must be called before any mallocs */
2450         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
2451         sanitise_stdfd();
2452
2453         __progname = ssh_get_progname(argv[0]);
2454
2455         seed_rng();
2456
2457         log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
2458
2459         msetlocale();
2460
2461         /* we need this for the home * directory.  */
2462         pw = getpwuid(getuid());
2463         if (!pw)
2464                 fatal("No user exists for uid %lu", (u_long)getuid());
2465         if (gethostname(hostname, sizeof(hostname)) < 0)
2466                 fatal("gethostname: %s", strerror(errno));
2467
2468         /* Remaining characters: Ydw */
2469         while ((opt = getopt(argc, argv, "ABHLQUXceghiklopquvxy"
2470             "C:D:E:F:G:I:J:K:M:N:O:P:R:S:T:V:W:Z:"
2471             "a:b:f:g:j:m:n:r:s:t:z:")) != -1) {
2472                 switch (opt) {
2473                 case 'A':
2474                         gen_all_hostkeys = 1;
2475                         break;
2476                 case 'b':
2477                         bits = (u_int32_t)strtonum(optarg, 10, 32768, &errstr);
2478                         if (errstr)
2479                                 fatal("Bits has bad value %s (%s)",
2480                                         optarg, errstr);
2481                         break;
2482                 case 'E':
2483                         fingerprint_hash = ssh_digest_alg_by_name(optarg);
2484                         if (fingerprint_hash == -1)
2485                                 fatal("Invalid hash algorithm \"%s\"", optarg);
2486                         break;
2487                 case 'F':
2488                         find_host = 1;
2489                         rr_hostname = optarg;
2490                         break;
2491                 case 'H':
2492                         hash_hosts = 1;
2493                         break;
2494                 case 'I':
2495                         cert_key_id = optarg;
2496                         break;
2497                 case 'R':
2498                         delete_host = 1;
2499                         rr_hostname = optarg;
2500                         break;
2501                 case 'L':
2502                         show_cert = 1;
2503                         break;
2504                 case 'l':
2505                         print_fingerprint = 1;
2506                         break;
2507                 case 'B':
2508                         print_bubblebabble = 1;
2509                         break;
2510                 case 'm':
2511                         if (strcasecmp(optarg, "RFC4716") == 0 ||
2512                             strcasecmp(optarg, "ssh2") == 0) {
2513                                 convert_format = FMT_RFC4716;
2514                                 break;
2515                         }
2516                         if (strcasecmp(optarg, "PKCS8") == 0) {
2517                                 convert_format = FMT_PKCS8;
2518                                 break;
2519                         }
2520                         if (strcasecmp(optarg, "PEM") == 0) {
2521                                 convert_format = FMT_PEM;
2522                                 use_new_format = 0;
2523                                 break;
2524                         }
2525                         fatal("Unsupported conversion format \"%s\"", optarg);
2526                 case 'n':
2527                         cert_principals = optarg;
2528                         break;
2529                 case 'o':
2530                         /* no-op; new format is already the default */
2531                         break;
2532                 case 'p':
2533                         change_passphrase = 1;
2534                         break;
2535                 case 'c':
2536                         change_comment = 1;
2537                         break;
2538                 case 'f':
2539                         if (strlcpy(identity_file, optarg,
2540                             sizeof(identity_file)) >= sizeof(identity_file))
2541                                 fatal("Identity filename too long");
2542                         have_identity = 1;
2543                         break;
2544                 case 'g':
2545                         print_generic = 1;
2546                         break;
2547                 case 'P':
2548                         identity_passphrase = optarg;
2549                         break;
2550                 case 'N':
2551                         identity_new_passphrase = optarg;
2552                         break;
2553                 case 'Q':
2554                         check_krl = 1;
2555                         break;
2556                 case 'O':
2557                         add_cert_option(optarg);
2558                         break;
2559                 case 'Z':
2560                         new_format_cipher = optarg;
2561                         break;
2562                 case 'C':
2563                         identity_comment = optarg;
2564                         break;
2565                 case 'q':
2566                         quiet = 1;
2567                         break;
2568                 case 'e':
2569                 case 'x':
2570                         /* export key */
2571                         convert_to = 1;
2572                         break;
2573                 case 'h':
2574                         cert_key_type = SSH2_CERT_TYPE_HOST;
2575                         certflags_flags = 0;
2576                         break;
2577                 case 'k':
2578                         gen_krl = 1;
2579                         break;
2580                 case 'i':
2581                 case 'X':
2582                         /* import key */
2583                         convert_from = 1;
2584                         break;
2585                 case 'y':
2586                         print_public = 1;
2587                         break;
2588                 case 's':
2589                         ca_key_path = optarg;
2590                         break;
2591                 case 't':
2592                         key_type_name = optarg;
2593                         break;
2594                 case 'D':
2595                         pkcs11provider = optarg;
2596                         break;
2597                 case 'U':
2598                         prefer_agent = 1;
2599                         break;
2600                 case 'u':
2601                         update_krl = 1;
2602                         break;
2603                 case 'v':
2604                         if (log_level == SYSLOG_LEVEL_INFO)
2605                                 log_level = SYSLOG_LEVEL_DEBUG1;
2606                         else {
2607                                 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
2608                                     log_level < SYSLOG_LEVEL_DEBUG3)
2609                                         log_level++;
2610                         }
2611                         break;
2612                 case 'r':
2613                         rr_hostname = optarg;
2614                         break;
2615                 case 'a':
2616                         rounds = (int)strtonum(optarg, 1, INT_MAX, &errstr);
2617                         if (errstr)
2618                                 fatal("Invalid number: %s (%s)",
2619                                         optarg, errstr);
2620                         break;
2621                 case 'V':
2622                         parse_cert_times(optarg);
2623                         break;
2624                 case 'z':
2625                         errno = 0;
2626                         if (*optarg == '+') {
2627                                 cert_serial_autoinc = 1;
2628                                 optarg++;
2629                         }
2630                         cert_serial = strtoull(optarg, &ep, 10);
2631                         if (*optarg < '0' || *optarg > '9' || *ep != '\0' ||
2632                             (errno == ERANGE && cert_serial == ULLONG_MAX))
2633                                 fatal("Invalid serial number \"%s\"", optarg);
2634                         break;
2635 #ifdef WITH_OPENSSL
2636                 /* Moduli generation/screening */
2637                 case 'G':
2638                         do_gen_candidates = 1;
2639                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2640                             sizeof(out_file))
2641                                 fatal("Output filename too long");
2642                         break;
2643                 case 'J':
2644                         lines_to_process = strtoul(optarg, NULL, 10);
2645                         break;
2646                 case 'j':
2647                         start_lineno = strtoul(optarg, NULL, 10);
2648                         break;
2649                 case 'K':
2650                         if (strlen(optarg) >= PATH_MAX)
2651                                 fatal("Checkpoint filename too long");
2652                         checkpoint = xstrdup(optarg);
2653                         break;
2654                 case 'M':
2655                         memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX,
2656                             &errstr);
2657                         if (errstr)
2658                                 fatal("Memory limit is %s: %s", errstr, optarg);
2659                         break;
2660                 case 'S':
2661                         /* XXX - also compare length against bits */
2662                         if (BN_hex2bn(&start, optarg) == 0)
2663                                 fatal("Invalid start point.");
2664                         break;
2665                 case 'T':
2666                         do_screen_candidates = 1;
2667                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
2668                             sizeof(out_file))
2669                                 fatal("Output filename too long");
2670                         break;
2671                 case 'W':
2672                         generator_wanted = (u_int32_t)strtonum(optarg, 1,
2673                             UINT_MAX, &errstr);
2674                         if (errstr != NULL)
2675                                 fatal("Desired generator invalid: %s (%s)",
2676                                     optarg, errstr);
2677                         break;
2678 #endif /* WITH_OPENSSL */
2679                 case '?':
2680                 default:
2681                         usage();
2682                 }
2683         }
2684
2685         /* reinit */
2686         log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2687
2688         argv += optind;
2689         argc -= optind;
2690
2691         if (ca_key_path != NULL) {
2692                 if (argc < 1 && !gen_krl) {
2693                         error("Too few arguments.");
2694                         usage();
2695                 }
2696         } else if (argc > 0 && !gen_krl && !check_krl) {
2697                 error("Too many arguments.");
2698                 usage();
2699         }
2700         if (change_passphrase && change_comment) {
2701                 error("Can only have one of -p and -c.");
2702                 usage();
2703         }
2704         if (print_fingerprint && (delete_host || hash_hosts)) {
2705                 error("Cannot use -l with -H or -R.");
2706                 usage();
2707         }
2708         if (gen_krl) {
2709                 do_gen_krl(pw, update_krl, ca_key_path,
2710                     cert_serial, identity_comment, argc, argv);
2711                 return (0);
2712         }
2713         if (check_krl) {
2714                 do_check_krl(pw, argc, argv);
2715                 return (0);
2716         }
2717         if (ca_key_path != NULL) {
2718                 if (cert_key_id == NULL)
2719                         fatal("Must specify key id (-I) when certifying");
2720                 do_ca_sign(pw, ca_key_path, prefer_agent,
2721                     cert_serial, cert_serial_autoinc, argc, argv);
2722         }
2723         if (show_cert)
2724                 do_show_cert(pw);
2725         if (delete_host || hash_hosts || find_host) {
2726                 do_known_hosts(pw, rr_hostname, find_host,
2727                     delete_host, hash_hosts);
2728         }
2729         if (pkcs11provider != NULL)
2730                 do_download(pw);
2731         if (print_fingerprint || print_bubblebabble)
2732                 do_fingerprint(pw);
2733         if (change_passphrase)
2734                 do_change_passphrase(pw);
2735         if (change_comment)
2736                 do_change_comment(pw, identity_comment);
2737 #ifdef WITH_OPENSSL
2738         if (convert_to)
2739                 do_convert_to(pw);
2740         if (convert_from)
2741                 do_convert_from(pw);
2742 #endif
2743         if (print_public)
2744                 do_print_public(pw);
2745         if (rr_hostname != NULL) {
2746                 unsigned int n = 0;
2747
2748                 if (have_identity) {
2749                         n = do_print_resource_record(pw, identity_file,
2750                             rr_hostname, print_generic);
2751                         if (n == 0)
2752                                 fatal("%s: %s", identity_file, strerror(errno));
2753                         exit(0);
2754                 } else {
2755
2756                         n += do_print_resource_record(pw,
2757                             _PATH_HOST_RSA_KEY_FILE, rr_hostname,
2758                             print_generic);
2759                         n += do_print_resource_record(pw,
2760                             _PATH_HOST_DSA_KEY_FILE, rr_hostname,
2761                             print_generic);
2762                         n += do_print_resource_record(pw,
2763                             _PATH_HOST_ECDSA_KEY_FILE, rr_hostname,
2764                             print_generic);
2765                         n += do_print_resource_record(pw,
2766                             _PATH_HOST_ED25519_KEY_FILE, rr_hostname,
2767                             print_generic);
2768                         n += do_print_resource_record(pw,
2769                             _PATH_HOST_XMSS_KEY_FILE, rr_hostname,
2770                             print_generic);
2771                         if (n == 0)
2772                                 fatal("no keys found.");
2773                         exit(0);
2774                 }
2775         }
2776
2777 #ifdef WITH_OPENSSL
2778         if (do_gen_candidates) {
2779                 FILE *out = fopen(out_file, "w");
2780
2781                 if (out == NULL) {
2782                         error("Couldn't open modulus candidate file \"%s\": %s",
2783                             out_file, strerror(errno));
2784                         return (1);
2785                 }
2786                 if (bits == 0)
2787                         bits = DEFAULT_BITS;
2788                 if (gen_candidates(out, memory, bits, start) != 0)
2789                         fatal("modulus candidate generation failed");
2790
2791                 return (0);
2792         }
2793
2794         if (do_screen_candidates) {
2795                 FILE *in;
2796                 FILE *out = fopen(out_file, "a");
2797
2798                 if (have_identity && strcmp(identity_file, "-") != 0) {
2799                         if ((in = fopen(identity_file, "r")) == NULL) {
2800                                 fatal("Couldn't open modulus candidate "
2801                                     "file \"%s\": %s", identity_file,
2802                                     strerror(errno));
2803                         }
2804                 } else
2805                         in = stdin;
2806
2807                 if (out == NULL) {
2808                         fatal("Couldn't open moduli file \"%s\": %s",
2809                             out_file, strerror(errno));
2810                 }
2811                 if (prime_test(in, out, rounds == 0 ? 100 : rounds,
2812                     generator_wanted, checkpoint,
2813                     start_lineno, lines_to_process) != 0)
2814                         fatal("modulus screening failed");
2815                 return (0);
2816         }
2817 #endif
2818
2819         if (gen_all_hostkeys) {
2820                 do_gen_all_hostkeys(pw);
2821                 return (0);
2822         }
2823
2824         if (key_type_name == NULL)
2825                 key_type_name = DEFAULT_KEY_TYPE_NAME;
2826
2827         type = sshkey_type_from_name(key_type_name);
2828         type_bits_valid(type, key_type_name, &bits);
2829
2830         if (!quiet)
2831                 printf("Generating public/private %s key pair.\n",
2832                     key_type_name);
2833         if ((r = sshkey_generate(type, bits, &private)) != 0)
2834                 fatal("sshkey_generate failed");
2835         if ((r = sshkey_from_private(private, &public)) != 0)
2836                 fatal("sshkey_from_private failed: %s\n", ssh_err(r));
2837
2838         if (!have_identity)
2839                 ask_filename(pw, "Enter file in which to save the key");
2840
2841         /* Create ~/.ssh directory if it doesn't already exist. */
2842         snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2843             pw->pw_dir, _PATH_SSH_USER_DIR);
2844         if (strstr(identity_file, dotsshdir) != NULL) {
2845                 if (stat(dotsshdir, &st) < 0) {
2846                         if (errno != ENOENT) {
2847                                 error("Could not stat %s: %s", dotsshdir,
2848                                     strerror(errno));
2849                         } else if (mkdir(dotsshdir, 0700) < 0) {
2850                                 error("Could not create directory '%s': %s",
2851                                     dotsshdir, strerror(errno));
2852                         } else if (!quiet)
2853                                 printf("Created directory '%s'.\n", dotsshdir);
2854                 }
2855         }
2856         /* If the file already exists, ask the user to confirm. */
2857         if (stat(identity_file, &st) >= 0) {
2858                 char yesno[3];
2859                 printf("%s already exists.\n", identity_file);
2860                 printf("Overwrite (y/n)? ");
2861                 fflush(stdout);
2862                 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2863                         exit(1);
2864                 if (yesno[0] != 'y' && yesno[0] != 'Y')
2865                         exit(1);
2866         }
2867         /* Ask for a passphrase (twice). */
2868         if (identity_passphrase)
2869                 passphrase1 = xstrdup(identity_passphrase);
2870         else if (identity_new_passphrase)
2871                 passphrase1 = xstrdup(identity_new_passphrase);
2872         else {
2873 passphrase_again:
2874                 passphrase1 =
2875                         read_passphrase("Enter passphrase (empty for no "
2876                             "passphrase): ", RP_ALLOW_STDIN);
2877                 passphrase2 = read_passphrase("Enter same passphrase again: ",
2878                     RP_ALLOW_STDIN);
2879                 if (strcmp(passphrase1, passphrase2) != 0) {
2880                         /*
2881                          * The passphrases do not match.  Clear them and
2882                          * retry.
2883                          */
2884                         explicit_bzero(passphrase1, strlen(passphrase1));
2885                         explicit_bzero(passphrase2, strlen(passphrase2));
2886                         free(passphrase1);
2887                         free(passphrase2);
2888                         printf("Passphrases do not match.  Try again.\n");
2889                         goto passphrase_again;
2890                 }
2891                 /* Clear the other copy of the passphrase. */
2892                 explicit_bzero(passphrase2, strlen(passphrase2));
2893                 free(passphrase2);
2894         }
2895
2896         if (identity_comment) {
2897                 strlcpy(comment, identity_comment, sizeof(comment));
2898         } else {
2899                 /* Create default comment field for the passphrase. */
2900                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2901         }
2902
2903         /* Save the key with the given passphrase and comment. */
2904         if ((r = sshkey_save_private(private, identity_file, passphrase1,
2905             comment, use_new_format, new_format_cipher, rounds)) != 0) {
2906                 error("Saving key \"%s\" failed: %s",
2907                     identity_file, ssh_err(r));
2908                 explicit_bzero(passphrase1, strlen(passphrase1));
2909                 free(passphrase1);
2910                 exit(1);
2911         }
2912         /* Clear the passphrase. */
2913         explicit_bzero(passphrase1, strlen(passphrase1));
2914         free(passphrase1);
2915
2916         /* Clear the private key and the random number generator. */
2917         sshkey_free(private);
2918
2919         if (!quiet)
2920                 printf("Your identification has been saved in %s.\n", identity_file);
2921
2922         strlcat(identity_file, ".pub", sizeof(identity_file));
2923         if ((fd = open(identity_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
2924                 fatal("Unable to save public key to %s: %s",
2925                     identity_file, strerror(errno));
2926         if ((f = fdopen(fd, "w")) == NULL)
2927                 fatal("fdopen %s failed: %s", identity_file, strerror(errno));
2928         if ((r = sshkey_write(public, f)) != 0)
2929                 error("write key failed: %s", ssh_err(r));
2930         fprintf(f, " %s\n", comment);
2931         if (ferror(f) || fclose(f) != 0)
2932                 fatal("write public failed: %s", strerror(errno));
2933
2934         if (!quiet) {
2935                 fp = sshkey_fingerprint(public, fingerprint_hash,
2936                     SSH_FP_DEFAULT);
2937                 ra = sshkey_fingerprint(public, fingerprint_hash,
2938                     SSH_FP_RANDOMART);
2939                 if (fp == NULL || ra == NULL)
2940                         fatal("sshkey_fingerprint failed");
2941                 printf("Your public key has been saved in %s.\n",
2942                     identity_file);
2943                 printf("The key fingerprint is:\n");
2944                 printf("%s %s\n", fp, comment);
2945                 printf("The key's randomart image is:\n");
2946                 printf("%s\n", ra);
2947                 free(ra);
2948                 free(fp);
2949         }
2950
2951         sshkey_free(public);
2952         exit(0);
2953 }