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