Merge branch 'vendor/MPFR'
[dragonfly.git] / crypto / openssh / ssh-keygen.c
1 /* $OpenBSD: ssh-keygen.c,v 1.197 2010/08/04 06:07:11 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 #include <sys/param.h>
21
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #ifdef HAVE_PATHS_H
30 # include <paths.h>
31 #endif
32 #include <pwd.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38
39 #include "xmalloc.h"
40 #include "key.h"
41 #include "rsa.h"
42 #include "authfile.h"
43 #include "uuencode.h"
44 #include "buffer.h"
45 #include "pathnames.h"
46 #include "log.h"
47 #include "misc.h"
48 #include "match.h"
49 #include "hostfile.h"
50 #include "dns.h"
51 #include "ssh2.h"
52
53 #ifdef ENABLE_PKCS11
54 #include "ssh-pkcs11.h"
55 #endif
56
57 /* Number of bits in the RSA/DSA key.  This value can be set on the command line. */
58 #define DEFAULT_BITS            2048
59 #define DEFAULT_BITS_DSA        1024
60 u_int32_t bits = 0;
61
62 /*
63  * Flag indicating that we just want to change the passphrase.  This can be
64  * set on the command line.
65  */
66 int change_passphrase = 0;
67
68 /*
69  * Flag indicating that we just want to change the comment.  This can be set
70  * on the command line.
71  */
72 int change_comment = 0;
73
74 int quiet = 0;
75
76 int log_level = SYSLOG_LEVEL_INFO;
77
78 /* Flag indicating that we want to hash a known_hosts file */
79 int hash_hosts = 0;
80 /* Flag indicating that we want lookup a host in known_hosts file */
81 int find_host = 0;
82 /* Flag indicating that we want to delete a host from a known_hosts file */
83 int delete_host = 0;
84
85 /* Flag indicating that we want to show the contents of a certificate */
86 int show_cert = 0;
87
88 /* Flag indicating that we just want to see the key fingerprint */
89 int print_fingerprint = 0;
90 int print_bubblebabble = 0;
91
92 /* The identity file name, given on the command line or entered by the user. */
93 char identity_file[1024];
94 int have_identity = 0;
95
96 /* This is set to the passphrase if given on the command line. */
97 char *identity_passphrase = NULL;
98
99 /* This is set to the new passphrase if given on the command line. */
100 char *identity_new_passphrase = NULL;
101
102 /* This is set to the new comment if given on the command line. */
103 char *identity_comment = NULL;
104
105 /* Path to CA key when certifying keys. */
106 char *ca_key_path = NULL;
107
108 /* Certificate serial number */
109 long long cert_serial = 0;
110
111 /* Key type when certifying */
112 u_int cert_key_type = SSH2_CERT_TYPE_USER;
113
114 /* "key ID" of signed key */
115 char *cert_key_id = NULL;
116
117 /* Comma-separated list of principal names for certifying keys */
118 char *cert_principals = NULL;
119
120 /* Validity period for certificates */
121 u_int64_t cert_valid_from = 0;
122 u_int64_t cert_valid_to = ~0ULL;
123
124 /* Certificate options */
125 #define CERTOPT_X_FWD   (1)
126 #define CERTOPT_AGENT_FWD       (1<<1)
127 #define CERTOPT_PORT_FWD        (1<<2)
128 #define CERTOPT_PTY             (1<<3)
129 #define CERTOPT_USER_RC (1<<4)
130 #define CERTOPT_DEFAULT (CERTOPT_X_FWD|CERTOPT_AGENT_FWD| \
131                          CERTOPT_PORT_FWD|CERTOPT_PTY|CERTOPT_USER_RC)
132 u_int32_t certflags_flags = CERTOPT_DEFAULT;
133 char *certflags_command = NULL;
134 char *certflags_src_addr = NULL;
135
136 /* Conversion to/from various formats */
137 int convert_to = 0;
138 int convert_from = 0;
139 enum {
140         FMT_RFC4716,
141         FMT_PKCS8,
142         FMT_PEM
143 } convert_format = FMT_RFC4716;
144 int print_public = 0;
145 int print_generic = 0;
146
147 char *key_type_name = NULL;
148
149 /* Load key from this PKCS#11 provider */
150 char *pkcs11provider = NULL;
151
152 /* argv0 */
153 extern char *__progname;
154
155 char hostname[MAXHOSTNAMELEN];
156
157 /* moduli.c */
158 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
159 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
160
161 static void
162 ask_filename(struct passwd *pw, const char *prompt)
163 {
164         char buf[1024];
165         char *name = NULL;
166
167         if (key_type_name == NULL)
168                 name = _PATH_SSH_CLIENT_ID_RSA;
169         else {
170                 switch (key_type_from_name(key_type_name)) {
171                 case KEY_RSA1:
172                         name = _PATH_SSH_CLIENT_IDENTITY;
173                         break;
174                 case KEY_DSA_CERT:
175                 case KEY_DSA_CERT_V00:
176                 case KEY_DSA:
177                         name = _PATH_SSH_CLIENT_ID_DSA;
178                         break;
179                 case KEY_RSA_CERT:
180                 case KEY_RSA_CERT_V00:
181                 case KEY_RSA:
182                         name = _PATH_SSH_CLIENT_ID_RSA;
183                         break;
184                 default:
185                         fprintf(stderr, "bad key type\n");
186                         exit(1);
187                         break;
188                 }
189         }
190         snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
191         fprintf(stderr, "%s (%s): ", prompt, identity_file);
192         if (fgets(buf, sizeof(buf), stdin) == NULL)
193                 exit(1);
194         buf[strcspn(buf, "\n")] = '\0';
195         if (strcmp(buf, "") != 0)
196                 strlcpy(identity_file, buf, sizeof(identity_file));
197         have_identity = 1;
198 }
199
200 static Key *
201 load_identity(char *filename)
202 {
203         char *pass;
204         Key *prv;
205
206         prv = key_load_private(filename, "", NULL);
207         if (prv == NULL) {
208                 if (identity_passphrase)
209                         pass = xstrdup(identity_passphrase);
210                 else
211                         pass = read_passphrase("Enter passphrase: ",
212                             RP_ALLOW_STDIN);
213                 prv = key_load_private(filename, pass, NULL);
214                 memset(pass, 0, strlen(pass));
215                 xfree(pass);
216         }
217         return prv;
218 }
219
220 #define SSH_COM_PUBLIC_BEGIN            "---- BEGIN SSH2 PUBLIC KEY ----"
221 #define SSH_COM_PUBLIC_END              "---- END SSH2 PUBLIC KEY ----"
222 #define SSH_COM_PRIVATE_BEGIN           "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
223 #define SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
224
225 static void
226 do_convert_to_ssh2(struct passwd *pw, Key *k)
227 {
228         u_int len;
229         u_char *blob;
230         char comment[61];
231
232         if (key_to_blob(k, &blob, &len) <= 0) {
233                 fprintf(stderr, "key_to_blob failed\n");
234                 exit(1);
235         }
236         /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
237         snprintf(comment, sizeof(comment),
238             "%u-bit %s, converted by %s@%s from OpenSSH",
239             key_size(k), key_type(k),
240             pw->pw_name, hostname);
241
242         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
243         fprintf(stdout, "Comment: \"%s\"\n", comment);
244         dump_base64(stdout, blob, len);
245         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
246         key_free(k);
247         xfree(blob);
248         exit(0);
249 }
250
251 static void
252 do_convert_to_pkcs8(Key *k)
253 {
254         switch (key_type_plain(k->type)) {
255         case KEY_RSA:
256                 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
257                         fatal("PEM_write_RSA_PUBKEY failed");
258                 break;
259         case KEY_DSA:
260                 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
261                         fatal("PEM_write_DSA_PUBKEY failed");
262                 break;
263         default:
264                 fatal("%s: unsupported key type %s", __func__, key_type(k));
265         }
266         exit(0);
267 }
268
269 static void
270 do_convert_to_pem(Key *k)
271 {
272         switch (key_type_plain(k->type)) {
273         case KEY_RSA:
274                 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
275                         fatal("PEM_write_RSAPublicKey failed");
276                 break;
277 #if notyet /* OpenSSH 0.9.8 lacks this function */
278         case KEY_DSA:
279                 if (!PEM_write_DSAPublicKey(stdout, k->dsa))
280                         fatal("PEM_write_DSAPublicKey failed");
281                 break;
282 #endif
283         default:
284                 fatal("%s: unsupported key type %s", __func__, key_type(k));
285         }
286         exit(0);
287 }
288
289 static void
290 do_convert_to(struct passwd *pw)
291 {
292         Key *k;
293         struct stat st;
294
295         if (!have_identity)
296                 ask_filename(pw, "Enter file in which the key is");
297         if (stat(identity_file, &st) < 0)
298                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
299         if ((k = key_load_public(identity_file, NULL)) == NULL) {
300                 if ((k = load_identity(identity_file)) == NULL) {
301                         fprintf(stderr, "load failed\n");
302                         exit(1);
303                 }
304         }
305         if (k->type == KEY_RSA1) {
306                 fprintf(stderr, "version 1 keys are not supported\n");
307                 exit(1);
308         }
309
310         switch (convert_format) {
311         case FMT_RFC4716:
312                 do_convert_to_ssh2(pw, k);
313                 break;
314         case FMT_PKCS8:
315                 do_convert_to_pkcs8(k);
316                 break;
317         case FMT_PEM:
318                 do_convert_to_pem(k);
319                 break;
320         default:
321                 fatal("%s: unknown key format %d", __func__, convert_format);
322         }
323         exit(0);
324 }
325
326 static void
327 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
328 {
329         u_int bignum_bits = buffer_get_int(b);
330         u_int bytes = (bignum_bits + 7) / 8;
331
332         if (buffer_len(b) < bytes)
333                 fatal("buffer_get_bignum_bits: input buffer too small: "
334                     "need %d have %d", bytes, buffer_len(b));
335         if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL)
336                 fatal("buffer_get_bignum_bits: BN_bin2bn failed");
337         buffer_consume(b, bytes);
338 }
339
340 static Key *
341 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
342 {
343         Buffer b;
344         Key *key = NULL;
345         char *type, *cipher;
346         u_char *sig, data[] = "abcde12345";
347         int magic, rlen, ktype, i1, i2, i3, i4;
348         u_int slen;
349         u_long e;
350
351         buffer_init(&b);
352         buffer_append(&b, blob, blen);
353
354         magic = buffer_get_int(&b);
355         if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
356                 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
357                 buffer_free(&b);
358                 return NULL;
359         }
360         i1 = buffer_get_int(&b);
361         type   = buffer_get_string(&b, NULL);
362         cipher = buffer_get_string(&b, NULL);
363         i2 = buffer_get_int(&b);
364         i3 = buffer_get_int(&b);
365         i4 = buffer_get_int(&b);
366         debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
367         if (strcmp(cipher, "none") != 0) {
368                 error("unsupported cipher %s", cipher);
369                 xfree(cipher);
370                 buffer_free(&b);
371                 xfree(type);
372                 return NULL;
373         }
374         xfree(cipher);
375
376         if (strstr(type, "dsa")) {
377                 ktype = KEY_DSA;
378         } else if (strstr(type, "rsa")) {
379                 ktype = KEY_RSA;
380         } else {
381                 buffer_free(&b);
382                 xfree(type);
383                 return NULL;
384         }
385         key = key_new_private(ktype);
386         xfree(type);
387
388         switch (key->type) {
389         case KEY_DSA:
390                 buffer_get_bignum_bits(&b, key->dsa->p);
391                 buffer_get_bignum_bits(&b, key->dsa->g);
392                 buffer_get_bignum_bits(&b, key->dsa->q);
393                 buffer_get_bignum_bits(&b, key->dsa->pub_key);
394                 buffer_get_bignum_bits(&b, key->dsa->priv_key);
395                 break;
396         case KEY_RSA:
397                 e = buffer_get_char(&b);
398                 debug("e %lx", e);
399                 if (e < 30) {
400                         e <<= 8;
401                         e += buffer_get_char(&b);
402                         debug("e %lx", e);
403                         e <<= 8;
404                         e += buffer_get_char(&b);
405                         debug("e %lx", e);
406                 }
407                 if (!BN_set_word(key->rsa->e, e)) {
408                         buffer_free(&b);
409                         key_free(key);
410                         return NULL;
411                 }
412                 buffer_get_bignum_bits(&b, key->rsa->d);
413                 buffer_get_bignum_bits(&b, key->rsa->n);
414                 buffer_get_bignum_bits(&b, key->rsa->iqmp);
415                 buffer_get_bignum_bits(&b, key->rsa->q);
416                 buffer_get_bignum_bits(&b, key->rsa->p);
417                 rsa_generate_additional_parameters(key->rsa);
418                 break;
419         }
420         rlen = buffer_len(&b);
421         if (rlen != 0)
422                 error("do_convert_private_ssh2_from_blob: "
423                     "remaining bytes in key blob %d", rlen);
424         buffer_free(&b);
425
426         /* try the key */
427         key_sign(key, &sig, &slen, data, sizeof(data));
428         key_verify(key, sig, slen, data, sizeof(data));
429         xfree(sig);
430         return key;
431 }
432
433 static int
434 get_line(FILE *fp, char *line, size_t len)
435 {
436         int c;
437         size_t pos = 0;
438
439         line[0] = '\0';
440         while ((c = fgetc(fp)) != EOF) {
441                 if (pos >= len - 1) {
442                         fprintf(stderr, "input line too long.\n");
443                         exit(1);
444                 }
445                 switch (c) {
446                 case '\r':
447                         c = fgetc(fp);
448                         if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) {
449                                 fprintf(stderr, "unget: %s\n", strerror(errno));
450                                 exit(1);
451                         }
452                         return pos;
453                 case '\n':
454                         return pos;
455                 }
456                 line[pos++] = c;
457                 line[pos] = '\0';
458         }
459         /* We reached EOF */
460         return -1;
461 }
462
463 static void
464 do_convert_from_ssh2(struct passwd *pw, Key **k, int *private)
465 {
466         int blen;
467         u_int len;
468         char line[1024];
469         u_char blob[8096];
470         char encoded[8096];
471         int escaped = 0;
472         FILE *fp;
473
474         if ((fp = fopen(identity_file, "r")) == NULL)
475                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
476         encoded[0] = '\0';
477         while ((blen = get_line(fp, line, sizeof(line))) != -1) {
478                 if (line[blen - 1] == '\\')
479                         escaped++;
480                 if (strncmp(line, "----", 4) == 0 ||
481                     strstr(line, ": ") != NULL) {
482                         if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
483                                 *private = 1;
484                         if (strstr(line, " END ") != NULL) {
485                                 break;
486                         }
487                         /* fprintf(stderr, "ignore: %s", line); */
488                         continue;
489                 }
490                 if (escaped) {
491                         escaped--;
492                         /* fprintf(stderr, "escaped: %s", line); */
493                         continue;
494                 }
495                 strlcat(encoded, line, sizeof(encoded));
496         }
497         len = strlen(encoded);
498         if (((len % 4) == 3) &&
499             (encoded[len-1] == '=') &&
500             (encoded[len-2] == '=') &&
501             (encoded[len-3] == '='))
502                 encoded[len-3] = '\0';
503         blen = uudecode(encoded, blob, sizeof(blob));
504         if (blen < 0) {
505                 fprintf(stderr, "uudecode failed.\n");
506                 exit(1);
507         }
508         *k = *private ?
509             do_convert_private_ssh2_from_blob(blob, blen) :
510             key_from_blob(blob, blen);
511         if (*k == NULL) {
512                 fprintf(stderr, "decode blob failed.\n");
513                 exit(1);
514         }
515         fclose(fp);
516 }
517
518 static void
519 do_convert_from_pkcs8(Key **k, int *private)
520 {
521         EVP_PKEY *pubkey;
522         FILE *fp;
523
524         if ((fp = fopen(identity_file, "r")) == NULL)
525                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
526         if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
527                 fatal("%s: %s is not a recognised public key format", __func__,
528                     identity_file);
529         }
530         fclose(fp);
531         switch (EVP_PKEY_type(pubkey->type)) {
532         case EVP_PKEY_RSA:
533                 *k = key_new(KEY_UNSPEC);
534                 (*k)->type = KEY_RSA;
535                 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
536                 break;
537         case EVP_PKEY_DSA:
538                 *k = key_new(KEY_UNSPEC);
539                 (*k)->type = KEY_DSA;
540                 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
541                 break;
542         default:
543                 fatal("%s: unsupported pubkey type %d", __func__,
544                     EVP_PKEY_type(pubkey->type));
545         }
546         EVP_PKEY_free(pubkey);
547         return;
548 }
549
550 static void
551 do_convert_from_pem(Key **k, int *private)
552 {
553         FILE *fp;
554         RSA *rsa;
555 #ifdef notyet
556         DSA *dsa;
557 #endif
558
559         if ((fp = fopen(identity_file, "r")) == NULL)
560                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
561         if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
562                 *k = key_new(KEY_UNSPEC);
563                 (*k)->type = KEY_RSA;
564                 (*k)->rsa = rsa;
565                 fclose(fp);
566                 return;
567         }
568 #if notyet /* OpenSSH 0.9.8 lacks this function */
569         rewind(fp);
570         if ((dsa = PEM_read_DSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
571                 *k = key_new(KEY_UNSPEC);
572                 (*k)->type = KEY_DSA;
573                 (*k)->dsa = dsa;
574                 fclose(fp);
575                 return;
576         }
577 #endif
578         fatal("%s: unrecognised raw private key format", __func__);
579 }
580
581 static void
582 do_convert_from(struct passwd *pw)
583 {
584         Key *k = NULL;
585         int private = 0, ok = 0;
586         struct stat st;
587
588         if (!have_identity)
589                 ask_filename(pw, "Enter file in which the key is");
590         if (stat(identity_file, &st) < 0)
591                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
592
593         switch (convert_format) {
594         case FMT_RFC4716:
595                 do_convert_from_ssh2(pw, &k, &private);
596                 break;
597         case FMT_PKCS8:
598                 do_convert_from_pkcs8(&k, &private);
599                 break;
600         case FMT_PEM:
601                 do_convert_from_pem(&k, &private);
602                 break;
603         default:
604                 fatal("%s: unknown key format %d", __func__, convert_format);
605         }
606
607         if (!private)
608                 ok = key_write(k, stdout);
609                 if (ok)
610                         fprintf(stdout, "\n");
611         else {
612                 switch (k->type) {
613                 case KEY_DSA:
614                         ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
615                             NULL, 0, NULL, NULL);
616                         break;
617                 case KEY_RSA:
618                         ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
619                             NULL, 0, NULL, NULL);
620                         break;
621                 default:
622                         fatal("%s: unsupported key type %s", __func__,
623                             key_type(k));
624                 }
625         }
626
627         if (!ok) {
628                 fprintf(stderr, "key write failed\n");
629                 exit(1);
630         }
631         key_free(k);
632         exit(0);
633 }
634
635 static void
636 do_print_public(struct passwd *pw)
637 {
638         Key *prv;
639         struct stat st;
640
641         if (!have_identity)
642                 ask_filename(pw, "Enter file in which the key is");
643         if (stat(identity_file, &st) < 0) {
644                 perror(identity_file);
645                 exit(1);
646         }
647         prv = load_identity(identity_file);
648         if (prv == NULL) {
649                 fprintf(stderr, "load failed\n");
650                 exit(1);
651         }
652         if (!key_write(prv, stdout))
653                 fprintf(stderr, "key_write failed");
654         key_free(prv);
655         fprintf(stdout, "\n");
656         exit(0);
657 }
658
659 static void
660 do_download(struct passwd *pw)
661 {
662 #ifdef ENABLE_PKCS11
663         Key **keys = NULL;
664         int i, nkeys;
665
666         pkcs11_init(0);
667         nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
668         if (nkeys <= 0)
669                 fatal("cannot read public key from pkcs11");
670         for (i = 0; i < nkeys; i++) {
671                 key_write(keys[i], stdout);
672                 key_free(keys[i]);
673                 fprintf(stdout, "\n");
674         }
675         xfree(keys);
676         pkcs11_terminate();
677         exit(0);
678 #else
679         fatal("no pkcs11 support");
680 #endif /* ENABLE_PKCS11 */
681 }
682
683 static void
684 do_fingerprint(struct passwd *pw)
685 {
686         FILE *f;
687         Key *public;
688         char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra;
689         int i, skip = 0, num = 0, invalid = 1;
690         enum fp_rep rep;
691         enum fp_type fptype;
692         struct stat st;
693
694         fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
695         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
696
697         if (!have_identity)
698                 ask_filename(pw, "Enter file in which the key is");
699         if (stat(identity_file, &st) < 0) {
700                 perror(identity_file);
701                 exit(1);
702         }
703         public = key_load_public(identity_file, &comment);
704         if (public != NULL) {
705                 fp = key_fingerprint(public, fptype, rep);
706                 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
707                 printf("%u %s %s (%s)\n", key_size(public), fp, comment,
708                     key_type(public));
709                 if (log_level >= SYSLOG_LEVEL_VERBOSE)
710                         printf("%s\n", ra);
711                 key_free(public);
712                 xfree(comment);
713                 xfree(ra);
714                 xfree(fp);
715                 exit(0);
716         }
717         if (comment) {
718                 xfree(comment);
719                 comment = NULL;
720         }
721
722         if ((f = fopen(identity_file, "r")) == NULL)
723                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
724
725         while (fgets(line, sizeof(line), f)) {
726                 if ((cp = strchr(line, '\n')) == NULL) {
727                         error("line %d too long: %.40s...",
728                             num + 1, line);
729                         skip = 1;
730                         continue;
731                 }
732                 num++;
733                 if (skip) {
734                         skip = 0;
735                         continue;
736                 }
737                 *cp = '\0';
738
739                 /* Skip leading whitespace, empty and comment lines. */
740                 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
741                         ;
742                 if (!*cp || *cp == '\n' || *cp == '#')
743                         continue;
744                 i = strtol(cp, &ep, 10);
745                 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
746                         int quoted = 0;
747                         comment = cp;
748                         for (; *cp && (quoted || (*cp != ' ' &&
749                             *cp != '\t')); cp++) {
750                                 if (*cp == '\\' && cp[1] == '"')
751                                         cp++;   /* Skip both */
752                                 else if (*cp == '"')
753                                         quoted = !quoted;
754                         }
755                         if (!*cp)
756                                 continue;
757                         *cp++ = '\0';
758                 }
759                 ep = cp;
760                 public = key_new(KEY_RSA1);
761                 if (key_read(public, &cp) != 1) {
762                         cp = ep;
763                         key_free(public);
764                         public = key_new(KEY_UNSPEC);
765                         if (key_read(public, &cp) != 1) {
766                                 key_free(public);
767                                 continue;
768                         }
769                 }
770                 comment = *cp ? cp : comment;
771                 fp = key_fingerprint(public, fptype, rep);
772                 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
773                 printf("%u %s %s (%s)\n", key_size(public), fp,
774                     comment ? comment : "no comment", key_type(public));
775                 if (log_level >= SYSLOG_LEVEL_VERBOSE)
776                         printf("%s\n", ra);
777                 xfree(ra);
778                 xfree(fp);
779                 key_free(public);
780                 invalid = 0;
781         }
782         fclose(f);
783
784         if (invalid) {
785                 printf("%s is not a public key file.\n", identity_file);
786                 exit(1);
787         }
788         exit(0);
789 }
790
791 static void
792 printhost(FILE *f, const char *name, Key *public, int ca, int hash)
793 {
794         if (print_fingerprint) {
795                 enum fp_rep rep;
796                 enum fp_type fptype;
797                 char *fp, *ra;
798
799                 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
800                 rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
801                 fp = key_fingerprint(public, fptype, rep);
802                 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
803                 printf("%u %s %s (%s)\n", key_size(public), fp, name,
804                     key_type(public));
805                 if (log_level >= SYSLOG_LEVEL_VERBOSE)
806                         printf("%s\n", ra);
807                 xfree(ra);
808                 xfree(fp);
809         } else {
810                 if (hash && (name = host_hash(name, NULL, 0)) == NULL)
811                         fatal("hash_host failed");
812                 fprintf(f, "%s%s%s ", ca ? CA_MARKER : "", ca ? " " : "", name);
813                 if (!key_write(public, f))
814                         fatal("key_write failed");
815                 fprintf(f, "\n");
816         }
817 }
818
819 static void
820 do_known_hosts(struct passwd *pw, const char *name)
821 {
822         FILE *in, *out = stdout;
823         Key *pub;
824         char *cp, *cp2, *kp, *kp2;
825         char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN];
826         int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0;
827         int ca;
828
829         if (!have_identity) {
830                 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
831                 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
832                     sizeof(identity_file))
833                         fatal("Specified known hosts path too long");
834                 xfree(cp);
835                 have_identity = 1;
836         }
837         if ((in = fopen(identity_file, "r")) == NULL)
838                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
839
840         /*
841          * Find hosts goes to stdout, hash and deletions happen in-place
842          * A corner case is ssh-keygen -HF foo, which should go to stdout
843          */
844         if (!find_host && (hash_hosts || delete_host)) {
845                 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
846                     strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
847                     strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
848                     strlcat(old, ".old", sizeof(old)) >= sizeof(old))
849                         fatal("known_hosts path too long");
850                 umask(077);
851                 if ((c = mkstemp(tmp)) == -1)
852                         fatal("mkstemp: %s", strerror(errno));
853                 if ((out = fdopen(c, "w")) == NULL) {
854                         c = errno;
855                         unlink(tmp);
856                         fatal("fdopen: %s", strerror(c));
857                 }
858                 inplace = 1;
859         }
860
861         while (fgets(line, sizeof(line), in)) {
862                 if ((cp = strchr(line, '\n')) == NULL) {
863                         error("line %d too long: %.40s...", num + 1, line);
864                         skip = 1;
865                         invalid = 1;
866                         continue;
867                 }
868                 num++;
869                 if (skip) {
870                         skip = 0;
871                         continue;
872                 }
873                 *cp = '\0';
874
875                 /* Skip leading whitespace, empty and comment lines. */
876                 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
877                         ;
878                 if (!*cp || *cp == '\n' || *cp == '#') {
879                         if (inplace)
880                                 fprintf(out, "%s\n", cp);
881                         continue;
882                 }
883                 /* Check whether this is a CA key */
884                 if (strncasecmp(cp, CA_MARKER, sizeof(CA_MARKER) - 1) == 0 &&
885                     (cp[sizeof(CA_MARKER) - 1] == ' ' ||
886                     cp[sizeof(CA_MARKER) - 1] == '\t')) {
887                         ca = 1;
888                         cp += sizeof(CA_MARKER);
889                 } else
890                         ca = 0;
891
892                 /* Find the end of the host name portion. */
893                 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++)
894                         ;
895
896                 if (*kp == '\0' || *(kp + 1) == '\0') {
897                         error("line %d missing key: %.40s...",
898                             num, line);
899                         invalid = 1;
900                         continue;
901                 }
902                 *kp++ = '\0';
903                 kp2 = kp;
904
905                 pub = key_new(KEY_RSA1);
906                 if (key_read(pub, &kp) != 1) {
907                         kp = kp2;
908                         key_free(pub);
909                         pub = key_new(KEY_UNSPEC);
910                         if (key_read(pub, &kp) != 1) {
911                                 error("line %d invalid key: %.40s...",
912                                     num, line);
913                                 key_free(pub);
914                                 invalid = 1;
915                                 continue;
916                         }
917                 }
918
919                 if (*cp == HASH_DELIM) {
920                         if (find_host || delete_host) {
921                                 cp2 = host_hash(name, cp, strlen(cp));
922                                 if (cp2 == NULL) {
923                                         error("line %d: invalid hashed "
924                                             "name: %.64s...", num, line);
925                                         invalid = 1;
926                                         continue;
927                                 }
928                                 c = (strcmp(cp2, cp) == 0);
929                                 if (find_host && c) {
930                                         printf("# Host %s found: "
931                                             "line %d type %s%s\n", name,
932                                             num, key_type(pub),
933                                             ca ? " (CA key)" : "");
934                                         printhost(out, cp, pub, ca, 0);
935                                 }
936                                 if (delete_host && !c && !ca)
937                                         printhost(out, cp, pub, ca, 0);
938                         } else if (hash_hosts)
939                                 printhost(out, cp, pub, ca, 0);
940                 } else {
941                         if (find_host || delete_host) {
942                                 c = (match_hostname(name, cp,
943                                     strlen(cp)) == 1);
944                                 if (find_host && c) {
945                                         printf("# Host %s found: "
946                                             "line %d type %s%s\n", name,
947                                             num, key_type(pub),
948                                             ca ? " (CA key)" : "");
949                                         printhost(out, name, pub,
950                                             ca, hash_hosts && !ca);
951                                 }
952                                 if (delete_host && !c && !ca)
953                                         printhost(out, cp, pub, ca, 0);
954                         } else if (hash_hosts) {
955                                 for (cp2 = strsep(&cp, ",");
956                                     cp2 != NULL && *cp2 != '\0';
957                                     cp2 = strsep(&cp, ",")) {
958                                         if (ca) {
959                                                 fprintf(stderr, "Warning: "
960                                                     "ignoring CA key for host: "
961                                                     "%.64s\n", cp2);
962                                                 printhost(out, cp2, pub, ca, 0);
963                                         } else if (strcspn(cp2, "*?!") !=
964                                             strlen(cp2)) {
965                                                 fprintf(stderr, "Warning: "
966                                                     "ignoring host name with "
967                                                     "metacharacters: %.64s\n",
968                                                     cp2);
969                                                 printhost(out, cp2, pub, ca, 0);
970                                         } else
971                                                 printhost(out, cp2, pub, ca, 1);
972                                 }
973                                 has_unhashed = 1;
974                         }
975                 }
976                 key_free(pub);
977         }
978         fclose(in);
979
980         if (invalid) {
981                 fprintf(stderr, "%s is not a valid known_hosts file.\n",
982                     identity_file);
983                 if (inplace) {
984                         fprintf(stderr, "Not replacing existing known_hosts "
985                             "file because of errors\n");
986                         fclose(out);
987                         unlink(tmp);
988                 }
989                 exit(1);
990         }
991
992         if (inplace) {
993                 fclose(out);
994
995                 /* Backup existing file */
996                 if (unlink(old) == -1 && errno != ENOENT)
997                         fatal("unlink %.100s: %s", old, strerror(errno));
998                 if (link(identity_file, old) == -1)
999                         fatal("link %.100s to %.100s: %s", identity_file, old,
1000                             strerror(errno));
1001                 /* Move new one into place */
1002                 if (rename(tmp, identity_file) == -1) {
1003                         error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1004                             strerror(errno));
1005                         unlink(tmp);
1006                         unlink(old);
1007                         exit(1);
1008                 }
1009
1010                 fprintf(stderr, "%s updated.\n", identity_file);
1011                 fprintf(stderr, "Original contents retained as %s\n", old);
1012                 if (has_unhashed) {
1013                         fprintf(stderr, "WARNING: %s contains unhashed "
1014                             "entries\n", old);
1015                         fprintf(stderr, "Delete this file to ensure privacy "
1016                             "of hostnames\n");
1017                 }
1018         }
1019
1020         exit(0);
1021 }
1022
1023 /*
1024  * Perform changing a passphrase.  The argument is the passwd structure
1025  * for the current user.
1026  */
1027 static void
1028 do_change_passphrase(struct passwd *pw)
1029 {
1030         char *comment;
1031         char *old_passphrase, *passphrase1, *passphrase2;
1032         struct stat st;
1033         Key *private;
1034
1035         if (!have_identity)
1036                 ask_filename(pw, "Enter file in which the key is");
1037         if (stat(identity_file, &st) < 0) {
1038                 perror(identity_file);
1039                 exit(1);
1040         }
1041         /* Try to load the file with empty passphrase. */
1042         private = key_load_private(identity_file, "", &comment);
1043         if (private == NULL) {
1044                 if (identity_passphrase)
1045                         old_passphrase = xstrdup(identity_passphrase);
1046                 else
1047                         old_passphrase =
1048                             read_passphrase("Enter old passphrase: ",
1049                             RP_ALLOW_STDIN);
1050                 private = key_load_private(identity_file, old_passphrase,
1051                     &comment);
1052                 memset(old_passphrase, 0, strlen(old_passphrase));
1053                 xfree(old_passphrase);
1054                 if (private == NULL) {
1055                         printf("Bad passphrase.\n");
1056                         exit(1);
1057                 }
1058         }
1059         printf("Key has comment '%s'\n", comment);
1060
1061         /* Ask the new passphrase (twice). */
1062         if (identity_new_passphrase) {
1063                 passphrase1 = xstrdup(identity_new_passphrase);
1064                 passphrase2 = NULL;
1065         } else {
1066                 passphrase1 =
1067                         read_passphrase("Enter new passphrase (empty for no "
1068                             "passphrase): ", RP_ALLOW_STDIN);
1069                 passphrase2 = read_passphrase("Enter same passphrase again: ",
1070                     RP_ALLOW_STDIN);
1071
1072                 /* Verify that they are the same. */
1073                 if (strcmp(passphrase1, passphrase2) != 0) {
1074                         memset(passphrase1, 0, strlen(passphrase1));
1075                         memset(passphrase2, 0, strlen(passphrase2));
1076                         xfree(passphrase1);
1077                         xfree(passphrase2);
1078                         printf("Pass phrases do not match.  Try again.\n");
1079                         exit(1);
1080                 }
1081                 /* Destroy the other copy. */
1082                 memset(passphrase2, 0, strlen(passphrase2));
1083                 xfree(passphrase2);
1084         }
1085
1086         /* Save the file using the new passphrase. */
1087         if (!key_save_private(private, identity_file, passphrase1, comment)) {
1088                 printf("Saving the key failed: %s.\n", identity_file);
1089                 memset(passphrase1, 0, strlen(passphrase1));
1090                 xfree(passphrase1);
1091                 key_free(private);
1092                 xfree(comment);
1093                 exit(1);
1094         }
1095         /* Destroy the passphrase and the copy of the key in memory. */
1096         memset(passphrase1, 0, strlen(passphrase1));
1097         xfree(passphrase1);
1098         key_free(private);               /* Destroys contents */
1099         xfree(comment);
1100
1101         printf("Your identification has been saved with the new passphrase.\n");
1102         exit(0);
1103 }
1104
1105 /*
1106  * Print the SSHFP RR.
1107  */
1108 static int
1109 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1110 {
1111         Key *public;
1112         char *comment = NULL;
1113         struct stat st;
1114
1115         if (fname == NULL)
1116                 ask_filename(pw, "Enter file in which the key is");
1117         if (stat(fname, &st) < 0) {
1118                 if (errno == ENOENT)
1119                         return 0;
1120                 perror(fname);
1121                 exit(1);
1122         }
1123         public = key_load_public(fname, &comment);
1124         if (public != NULL) {
1125                 export_dns_rr(hname, public, stdout, print_generic);
1126                 key_free(public);
1127                 xfree(comment);
1128                 return 1;
1129         }
1130         if (comment)
1131                 xfree(comment);
1132
1133         printf("failed to read v2 public key from %s.\n", fname);
1134         exit(1);
1135 }
1136
1137 /*
1138  * Change the comment of a private key file.
1139  */
1140 static void
1141 do_change_comment(struct passwd *pw)
1142 {
1143         char new_comment[1024], *comment, *passphrase;
1144         Key *private;
1145         Key *public;
1146         struct stat st;
1147         FILE *f;
1148         int fd;
1149
1150         if (!have_identity)
1151                 ask_filename(pw, "Enter file in which the key is");
1152         if (stat(identity_file, &st) < 0) {
1153                 perror(identity_file);
1154                 exit(1);
1155         }
1156         private = key_load_private(identity_file, "", &comment);
1157         if (private == NULL) {
1158                 if (identity_passphrase)
1159                         passphrase = xstrdup(identity_passphrase);
1160                 else if (identity_new_passphrase)
1161                         passphrase = xstrdup(identity_new_passphrase);
1162                 else
1163                         passphrase = read_passphrase("Enter passphrase: ",
1164                             RP_ALLOW_STDIN);
1165                 /* Try to load using the passphrase. */
1166                 private = key_load_private(identity_file, passphrase, &comment);
1167                 if (private == NULL) {
1168                         memset(passphrase, 0, strlen(passphrase));
1169                         xfree(passphrase);
1170                         printf("Bad passphrase.\n");
1171                         exit(1);
1172                 }
1173         } else {
1174                 passphrase = xstrdup("");
1175         }
1176         if (private->type != KEY_RSA1) {
1177                 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
1178                 key_free(private);
1179                 exit(1);
1180         }
1181         printf("Key now has comment '%s'\n", comment);
1182
1183         if (identity_comment) {
1184                 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1185         } else {
1186                 printf("Enter new comment: ");
1187                 fflush(stdout);
1188                 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1189                         memset(passphrase, 0, strlen(passphrase));
1190                         key_free(private);
1191                         exit(1);
1192                 }
1193                 new_comment[strcspn(new_comment, "\n")] = '\0';
1194         }
1195
1196         /* Save the file using the new passphrase. */
1197         if (!key_save_private(private, identity_file, passphrase, new_comment)) {
1198                 printf("Saving the key failed: %s.\n", identity_file);
1199                 memset(passphrase, 0, strlen(passphrase));
1200                 xfree(passphrase);
1201                 key_free(private);
1202                 xfree(comment);
1203                 exit(1);
1204         }
1205         memset(passphrase, 0, strlen(passphrase));
1206         xfree(passphrase);
1207         public = key_from_private(private);
1208         key_free(private);
1209
1210         strlcat(identity_file, ".pub", sizeof(identity_file));
1211         fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1212         if (fd == -1) {
1213                 printf("Could not save your public key in %s\n", identity_file);
1214                 exit(1);
1215         }
1216         f = fdopen(fd, "w");
1217         if (f == NULL) {
1218                 printf("fdopen %s failed\n", identity_file);
1219                 exit(1);
1220         }
1221         if (!key_write(public, f))
1222                 fprintf(stderr, "write key failed\n");
1223         key_free(public);
1224         fprintf(f, " %s\n", new_comment);
1225         fclose(f);
1226
1227         xfree(comment);
1228
1229         printf("The comment in your key file has been changed.\n");
1230         exit(0);
1231 }
1232
1233 static const char *
1234 fmt_validity(u_int64_t valid_from, u_int64_t valid_to)
1235 {
1236         char from[32], to[32];
1237         static char ret[64];
1238         time_t tt;
1239         struct tm *tm;
1240
1241         *from = *to = '\0';
1242         if (valid_from == 0 && valid_to == 0xffffffffffffffffULL)
1243                 return "forever";
1244
1245         if (valid_from != 0) {
1246                 /* XXX revisit INT_MAX in 2038 :) */
1247                 tt = valid_from > INT_MAX ? INT_MAX : valid_from;
1248                 tm = localtime(&tt);
1249                 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
1250         }
1251         if (valid_to != 0xffffffffffffffffULL) {
1252                 /* XXX revisit INT_MAX in 2038 :) */
1253                 tt = valid_to > INT_MAX ? INT_MAX : valid_to;
1254                 tm = localtime(&tt);
1255                 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
1256         }
1257
1258         if (valid_from == 0) {
1259                 snprintf(ret, sizeof(ret), "before %s", to);
1260                 return ret;
1261         }
1262         if (valid_to == 0xffffffffffffffffULL) {
1263                 snprintf(ret, sizeof(ret), "after %s", from);
1264                 return ret;
1265         }
1266
1267         snprintf(ret, sizeof(ret), "from %s to %s", from, to);
1268         return ret;
1269 }
1270
1271 static void
1272 add_flag_option(Buffer *c, const char *name)
1273 {
1274         debug3("%s: %s", __func__, name);
1275         buffer_put_cstring(c, name);
1276         buffer_put_string(c, NULL, 0);
1277 }
1278
1279 static void
1280 add_string_option(Buffer *c, const char *name, const char *value)
1281 {
1282         Buffer b;
1283
1284         debug3("%s: %s=%s", __func__, name, value);
1285         buffer_init(&b);
1286         buffer_put_cstring(&b, value);
1287
1288         buffer_put_cstring(c, name);
1289         buffer_put_string(c, buffer_ptr(&b), buffer_len(&b));
1290
1291         buffer_free(&b);
1292 }
1293
1294 #define OPTIONS_CRITICAL        1
1295 #define OPTIONS_EXTENSIONS      2
1296 static void
1297 prepare_options_buf(Buffer *c, int which)
1298 {
1299         buffer_clear(c);
1300         if ((which & OPTIONS_CRITICAL) != 0 &&
1301             certflags_command != NULL)
1302                 add_string_option(c, "force-command", certflags_command);
1303         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1304             (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1305                 add_flag_option(c, "permit-agent-forwarding");
1306         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1307             (certflags_flags & CERTOPT_PORT_FWD) != 0)
1308                 add_flag_option(c, "permit-port-forwarding");
1309         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1310             (certflags_flags & CERTOPT_PTY) != 0)
1311                 add_flag_option(c, "permit-pty");
1312         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1313             (certflags_flags & CERTOPT_USER_RC) != 0)
1314                 add_flag_option(c, "permit-user-rc");
1315         if ((which & OPTIONS_EXTENSIONS) != 0 &&
1316             (certflags_flags & CERTOPT_X_FWD) != 0)
1317                 add_flag_option(c, "permit-X11-forwarding");
1318         if ((which & OPTIONS_CRITICAL) != 0 &&
1319             certflags_src_addr != NULL)
1320                 add_string_option(c, "source-address", certflags_src_addr);
1321 }
1322
1323 static Key *
1324 load_pkcs11_key(char *path)
1325 {
1326 #ifdef ENABLE_PKCS11
1327         Key **keys = NULL, *public, *private = NULL;
1328         int i, nkeys;
1329
1330         if ((public = key_load_public(path, NULL)) == NULL)
1331                 fatal("Couldn't load CA public key \"%s\"", path);
1332
1333         nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1334         debug3("%s: %d keys", __func__, nkeys);
1335         if (nkeys <= 0)
1336                 fatal("cannot read public key from pkcs11");
1337         for (i = 0; i < nkeys; i++) {
1338                 if (key_equal_public(public, keys[i])) {
1339                         private = keys[i];
1340                         continue;
1341                 }
1342                 key_free(keys[i]);
1343         }
1344         xfree(keys);
1345         key_free(public);
1346         return private;
1347 #else
1348         fatal("no pkcs11 support");
1349 #endif /* ENABLE_PKCS11 */
1350 }
1351
1352 static void
1353 do_ca_sign(struct passwd *pw, int argc, char **argv)
1354 {
1355         int i, fd;
1356         u_int n;
1357         Key *ca, *public;
1358         char *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1359         FILE *f;
1360         int v00 = 0; /* legacy keys */
1361
1362         if (key_type_name != NULL) {
1363                 switch (key_type_from_name(key_type_name)) {
1364                 case KEY_RSA_CERT_V00:
1365                 case KEY_DSA_CERT_V00:
1366                         v00 = 1;
1367                         break;
1368                 case KEY_UNSPEC:
1369                         if (strcasecmp(key_type_name, "v00") == 0) {
1370                                 v00 = 1;
1371                                 break;
1372                         } else if (strcasecmp(key_type_name, "v01") == 0)
1373                                 break;
1374                         /* FALLTHROUGH */
1375                 default:
1376                         fprintf(stderr, "unknown key type %s\n", key_type_name);
1377                         exit(1);
1378                 }
1379         }
1380
1381         pkcs11_init(1);
1382         tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1383         if (pkcs11provider != NULL) {
1384                 if ((ca = load_pkcs11_key(tmp)) == NULL)
1385                         fatal("No PKCS#11 key matching %s found", ca_key_path);
1386         } else if ((ca = load_identity(tmp)) == NULL)
1387                 fatal("Couldn't load CA key \"%s\"", tmp);
1388         xfree(tmp);
1389
1390         for (i = 0; i < argc; i++) {
1391                 /* Split list of principals */
1392                 n = 0;
1393                 if (cert_principals != NULL) {
1394                         otmp = tmp = xstrdup(cert_principals);
1395                         plist = NULL;
1396                         for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1397                                 plist = xrealloc(plist, n + 1, sizeof(*plist));
1398                                 if (*(plist[n] = xstrdup(cp)) == '\0')
1399                                         fatal("Empty principal name");
1400                         }
1401                         xfree(otmp);
1402                 }
1403         
1404                 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1405                 if ((public = key_load_public(tmp, &comment)) == NULL)
1406                         fatal("%s: unable to open \"%s\"", __func__, tmp);
1407                 if (public->type != KEY_RSA && public->type != KEY_DSA)
1408                         fatal("%s: key \"%s\" type %s cannot be certified",
1409                             __func__, tmp, key_type(public));
1410
1411                 /* Prepare certificate to sign */
1412                 if (key_to_certified(public, v00) != 0)
1413                         fatal("Could not upgrade key %s to certificate", tmp);
1414                 public->cert->type = cert_key_type;
1415                 public->cert->serial = (u_int64_t)cert_serial;
1416                 public->cert->key_id = xstrdup(cert_key_id);
1417                 public->cert->nprincipals = n;
1418                 public->cert->principals = plist;
1419                 public->cert->valid_after = cert_valid_from;
1420                 public->cert->valid_before = cert_valid_to;
1421                 if (v00) {
1422                         prepare_options_buf(&public->cert->critical,
1423                             OPTIONS_CRITICAL|OPTIONS_EXTENSIONS);
1424                 } else {
1425                         prepare_options_buf(&public->cert->critical,
1426                             OPTIONS_CRITICAL);
1427                         prepare_options_buf(&public->cert->extensions,
1428                             OPTIONS_EXTENSIONS);
1429                 }
1430                 public->cert->signature_key = key_from_private(ca);
1431
1432                 if (key_certify(public, ca) != 0)
1433                         fatal("Couldn't not certify key %s", tmp);
1434
1435                 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1436                         *cp = '\0';
1437                 xasprintf(&out, "%s-cert.pub", tmp);
1438                 xfree(tmp);
1439
1440                 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1441                         fatal("Could not open \"%s\" for writing: %s", out,
1442                             strerror(errno));
1443                 if ((f = fdopen(fd, "w")) == NULL)
1444                         fatal("%s: fdopen: %s", __func__, strerror(errno));
1445                 if (!key_write(public, f))
1446                         fatal("Could not write certified key to %s", out);
1447                 fprintf(f, " %s\n", comment);
1448                 fclose(f);
1449
1450                 if (!quiet) {
1451                         logit("Signed %s key %s: id \"%s\" serial %ju%s%s "
1452                             "valid %s", key_cert_type(public), 
1453                             out, public->cert->key_id,
1454                             (intmax_t)public->cert->serial,
1455                             cert_principals != NULL ? " for " : "",
1456                             cert_principals != NULL ? cert_principals : "",
1457                             fmt_validity(cert_valid_from, cert_valid_to));
1458                 }
1459
1460                 key_free(public);
1461                 xfree(out);
1462         }
1463         pkcs11_terminate();
1464         exit(0);
1465 }
1466
1467 static u_int64_t
1468 parse_relative_time(const char *s, time_t now)
1469 {
1470         int64_t mul, secs;
1471
1472         mul = *s == '-' ? -1 : 1;
1473
1474         if ((secs = convtime(s + 1)) == -1)
1475                 fatal("Invalid relative certificate time %s", s);
1476         if (mul == -1 && secs > now)
1477                 fatal("Certificate time %s cannot be represented", s);
1478         return now + (u_int64_t)(secs * mul);
1479 }
1480
1481 static u_int64_t
1482 parse_absolute_time(const char *s)
1483 {
1484         struct tm tm;
1485         time_t tt;
1486         char buf[32], *fmt;
1487
1488         /*
1489          * POSIX strptime says "The application shall ensure that there 
1490          * is white-space or other non-alphanumeric characters between
1491          * any two conversion specifications" so arrange things this way.
1492          */
1493         switch (strlen(s)) {
1494         case 8:
1495                 fmt = "%Y-%m-%d";
1496                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1497                 break;
1498         case 14:
1499                 fmt = "%Y-%m-%dT%H:%M:%S";
1500                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1501                     s, s + 4, s + 6, s + 8, s + 10, s + 12);
1502                 break;
1503         default:
1504                 fatal("Invalid certificate time format %s", s);
1505         }
1506
1507         bzero(&tm, sizeof(tm));
1508         if (strptime(buf, fmt, &tm) == NULL)
1509                 fatal("Invalid certificate time %s", s);
1510         if ((tt = mktime(&tm)) < 0)
1511                 fatal("Certificate time %s cannot be represented", s);
1512         return (u_int64_t)tt;
1513 }
1514
1515 static void
1516 parse_cert_times(char *timespec)
1517 {
1518         char *from, *to;
1519         time_t now = time(NULL);
1520         int64_t secs;
1521
1522         /* +timespec relative to now */
1523         if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1524                 if ((secs = convtime(timespec + 1)) == -1)
1525                         fatal("Invalid relative certificate life %s", timespec);
1526                 cert_valid_to = now + secs;
1527                 /*
1528                  * Backdate certificate one minute to avoid problems on hosts
1529                  * with poorly-synchronised clocks.
1530                  */
1531                 cert_valid_from = ((now - 59)/ 60) * 60;
1532                 return;
1533         }
1534
1535         /*
1536          * from:to, where
1537          * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1538          *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1539          */
1540         from = xstrdup(timespec);
1541         to = strchr(from, ':');
1542         if (to == NULL || from == to || *(to + 1) == '\0')
1543                 fatal("Invalid certificate life specification %s", timespec);
1544         *to++ = '\0';
1545
1546         if (*from == '-' || *from == '+')
1547                 cert_valid_from = parse_relative_time(from, now);
1548         else
1549                 cert_valid_from = parse_absolute_time(from);
1550
1551         if (*to == '-' || *to == '+')
1552                 cert_valid_to = parse_relative_time(to, cert_valid_from);
1553         else
1554                 cert_valid_to = parse_absolute_time(to);
1555
1556         if (cert_valid_to <= cert_valid_from)
1557                 fatal("Empty certificate validity interval");
1558         xfree(from);
1559 }
1560
1561 static void
1562 add_cert_option(char *opt)
1563 {
1564         char *val;
1565
1566         if (strcmp(opt, "clear") == 0)
1567                 certflags_flags = 0;
1568         else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1569                 certflags_flags &= ~CERTOPT_X_FWD;
1570         else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1571                 certflags_flags |= CERTOPT_X_FWD;
1572         else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1573                 certflags_flags &= ~CERTOPT_AGENT_FWD;
1574         else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1575                 certflags_flags |= CERTOPT_AGENT_FWD;
1576         else if (strcasecmp(opt, "no-port-forwarding") == 0)
1577                 certflags_flags &= ~CERTOPT_PORT_FWD;
1578         else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1579                 certflags_flags |= CERTOPT_PORT_FWD;
1580         else if (strcasecmp(opt, "no-pty") == 0)
1581                 certflags_flags &= ~CERTOPT_PTY;
1582         else if (strcasecmp(opt, "permit-pty") == 0)
1583                 certflags_flags |= CERTOPT_PTY;
1584         else if (strcasecmp(opt, "no-user-rc") == 0)
1585                 certflags_flags &= ~CERTOPT_USER_RC;
1586         else if (strcasecmp(opt, "permit-user-rc") == 0)
1587                 certflags_flags |= CERTOPT_USER_RC;
1588         else if (strncasecmp(opt, "force-command=", 14) == 0) {
1589                 val = opt + 14;
1590                 if (*val == '\0')
1591                         fatal("Empty force-command option");
1592                 if (certflags_command != NULL)
1593                         fatal("force-command already specified");
1594                 certflags_command = xstrdup(val);
1595         } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1596                 val = opt + 15;
1597                 if (*val == '\0')
1598                         fatal("Empty source-address option");
1599                 if (certflags_src_addr != NULL)
1600                         fatal("source-address already specified");
1601                 if (addr_match_cidr_list(NULL, val) != 0)
1602                         fatal("Invalid source-address list");
1603                 certflags_src_addr = xstrdup(val);
1604         } else
1605                 fatal("Unsupported certificate option \"%s\"", opt);
1606 }
1607
1608 static void
1609 show_options(const Buffer *optbuf, int v00, int in_critical)
1610 {
1611         u_char *name, *data;
1612         u_int dlen;
1613         Buffer options, option;
1614
1615         buffer_init(&options);
1616         buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1617
1618         buffer_init(&option);
1619         while (buffer_len(&options) != 0) {
1620                 name = buffer_get_string(&options, NULL);
1621                 data = buffer_get_string_ptr(&options, &dlen);
1622                 buffer_append(&option, data, dlen);
1623                 printf("                %s", name);
1624                 if ((v00 || !in_critical) && 
1625                     (strcmp(name, "permit-X11-forwarding") == 0 ||
1626                     strcmp(name, "permit-agent-forwarding") == 0 ||
1627                     strcmp(name, "permit-port-forwarding") == 0 ||
1628                     strcmp(name, "permit-pty") == 0 ||
1629                     strcmp(name, "permit-user-rc") == 0))
1630                         printf("\n");
1631                 else if ((v00 || in_critical) &&
1632                     (strcmp(name, "force-command") == 0 ||
1633                     strcmp(name, "source-address") == 0)) {
1634                         data = buffer_get_string(&option, NULL);
1635                         printf(" %s\n", data);
1636                         xfree(data);
1637                 } else {
1638                         printf(" UNKNOWN OPTION (len %u)\n",
1639                             buffer_len(&option));
1640                         buffer_clear(&option);
1641                 }
1642                 xfree(name);
1643                 if (buffer_len(&option) != 0)
1644                         fatal("Option corrupt: extra data at end");
1645         }
1646         buffer_free(&option);
1647         buffer_free(&options);
1648 }
1649
1650 static void
1651 do_show_cert(struct passwd *pw)
1652 {
1653         Key *key;
1654         struct stat st;
1655         char *key_fp, *ca_fp;
1656         u_int i, v00;
1657
1658         if (!have_identity)
1659                 ask_filename(pw, "Enter file in which the key is");
1660         if (stat(identity_file, &st) < 0)
1661                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1662         if ((key = key_load_public(identity_file, NULL)) == NULL)
1663                 fatal("%s is not a public key", identity_file);
1664         if (!key_is_cert(key))
1665                 fatal("%s is not a certificate", identity_file);
1666         v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1667
1668         key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1669         ca_fp = key_fingerprint(key->cert->signature_key,
1670             SSH_FP_MD5, SSH_FP_HEX);
1671
1672         printf("%s:\n", identity_file);
1673         printf("        Type: %s %s certificate\n", key_ssh_name(key),
1674             key_cert_type(key));
1675         printf("        Public key: %s %s\n", key_type(key), key_fp);
1676         printf("        Signing CA: %s %s\n",
1677             key_type(key->cert->signature_key), ca_fp);
1678         printf("        Key ID: \"%s\"\n", key->cert->key_id);
1679         if (!v00)
1680                 printf("        Serial: %ju\n", (intmax_t)key->cert->serial);
1681         printf("        Valid: %s\n",
1682             fmt_validity(key->cert->valid_after, key->cert->valid_before));
1683         printf("        Principals: ");
1684         if (key->cert->nprincipals == 0)
1685                 printf("(none)\n");
1686         else {
1687                 for (i = 0; i < key->cert->nprincipals; i++)
1688                         printf("\n                %s",
1689                             key->cert->principals[i]);
1690                 printf("\n");
1691         }
1692         printf("        Critical Options: ");
1693         if (buffer_len(&key->cert->critical) == 0)
1694                 printf("(none)\n");
1695         else {
1696                 printf("\n");
1697                 show_options(&key->cert->critical, v00, 1);
1698         }
1699         if (!v00) {
1700                 printf("        Extensions: ");
1701                 if (buffer_len(&key->cert->extensions) == 0)
1702                         printf("(none)\n");
1703                 else {
1704                         printf("\n");
1705                         show_options(&key->cert->extensions, v00, 0);
1706                 }
1707         }
1708         exit(0);
1709 }
1710
1711 static void
1712 usage(void)
1713 {
1714         fprintf(stderr, "usage: %s [options]\n", __progname);
1715         fprintf(stderr, "Options:\n");
1716         fprintf(stderr, "  -a trials   Number of trials for screening DH-GEX moduli.\n");
1717         fprintf(stderr, "  -B          Show bubblebabble digest of key file.\n");
1718         fprintf(stderr, "  -b bits     Number of bits in the key to create.\n");
1719         fprintf(stderr, "  -C comment  Provide new comment.\n");
1720         fprintf(stderr, "  -c          Change comment in private and public key files.\n");
1721 #ifdef ENABLE_PKCS11
1722         fprintf(stderr, "  -D pkcs11   Download public key from pkcs11 token.\n");
1723 #endif
1724         fprintf(stderr, "  -e          Export OpenSSH to foreign format key file.\n");
1725         fprintf(stderr, "  -F hostname Find hostname in known hosts file.\n");
1726         fprintf(stderr, "  -f filename Filename of the key file.\n");
1727         fprintf(stderr, "  -G file     Generate candidates for DH-GEX moduli.\n");
1728         fprintf(stderr, "  -g          Use generic DNS resource record format.\n");
1729         fprintf(stderr, "  -H          Hash names in known_hosts file.\n");
1730         fprintf(stderr, "  -h          Generate host certificate instead of a user certificate.\n");
1731         fprintf(stderr, "  -I key_id   Key identifier to include in certificate.\n");
1732         fprintf(stderr, "  -i          Import foreign format to OpenSSH key file.\n");
1733         fprintf(stderr, "  -L          Print the contents of a certificate.\n");
1734         fprintf(stderr, "  -l          Show fingerprint of key file.\n");
1735         fprintf(stderr, "  -M memory   Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1736         fprintf(stderr, "  -m key_fmt  Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
1737         fprintf(stderr, "  -N phrase   Provide new passphrase.\n");
1738         fprintf(stderr, "  -n name,... User/host principal names to include in certificate\n");
1739         fprintf(stderr, "  -O option   Specify a certificate option.\n");
1740         fprintf(stderr, "  -P phrase   Provide old passphrase.\n");
1741         fprintf(stderr, "  -p          Change passphrase of private key file.\n");
1742         fprintf(stderr, "  -q          Quiet.\n");
1743         fprintf(stderr, "  -R hostname Remove host from known_hosts file.\n");
1744         fprintf(stderr, "  -r hostname Print DNS resource record.\n");
1745         fprintf(stderr, "  -S start    Start point (hex) for generating DH-GEX moduli.\n");
1746         fprintf(stderr, "  -s ca_key   Certify keys with CA key.\n");
1747         fprintf(stderr, "  -T file     Screen candidates for DH-GEX moduli.\n");
1748         fprintf(stderr, "  -t type     Specify type of key to create.\n");
1749         fprintf(stderr, "  -V from:to  Specify certificate validity interval.\n");
1750         fprintf(stderr, "  -v          Verbose.\n");
1751         fprintf(stderr, "  -W gen      Generator to use for generating DH-GEX moduli.\n");
1752         fprintf(stderr, "  -y          Read private key file and print public key.\n");
1753         fprintf(stderr, "  -z serial   Specify a serial number.\n");
1754
1755         exit(1);
1756 }
1757
1758 /*
1759  * Main program for key management.
1760  */
1761 int
1762 main(int argc, char **argv)
1763 {
1764         char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1765         char out_file[MAXPATHLEN], *rr_hostname = NULL;
1766         Key *private, *public;
1767         struct passwd *pw;
1768         struct stat st;
1769         int opt, type, fd;
1770         u_int maxbits;
1771         u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1772         int do_gen_candidates = 0, do_screen_candidates = 0;
1773         BIGNUM *start = NULL;
1774         FILE *f;
1775         const char *errstr;
1776
1777         extern int optind;
1778         extern char *optarg;
1779
1780         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1781         sanitise_stdfd();
1782
1783         __progname = ssh_get_progname(argv[0]);
1784
1785         SSLeay_add_all_algorithms();
1786         log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1787
1788         init_rng();
1789         seed_rng();
1790
1791         /* we need this for the home * directory.  */
1792         pw = getpwuid(getuid());
1793         if (!pw) {
1794                 printf("You don't exist, go away!\n");
1795                 exit(1);
1796         }
1797         if (gethostname(hostname, sizeof(hostname)) < 0) {
1798                 perror("gethostname");
1799                 exit(1);
1800         }
1801
1802         while ((opt = getopt(argc, argv, "degiqpclBHLhvxXyF:b:f:t:D:I:P:m:N:n:"
1803             "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) {
1804                 switch (opt) {
1805                 case 'b':
1806                         bits = (u_int32_t)strtonum(optarg, 768, 32768, &errstr);
1807                         if (errstr)
1808                                 fatal("Bits has bad value %s (%s)",
1809                                         optarg, errstr);
1810                         break;
1811                 case 'F':
1812                         find_host = 1;
1813                         rr_hostname = optarg;
1814                         break;
1815                 case 'H':
1816                         hash_hosts = 1;
1817                         break;
1818                 case 'I':
1819                         cert_key_id = optarg;
1820                         break;
1821                 case 'R':
1822                         delete_host = 1;
1823                         rr_hostname = optarg;
1824                         break;
1825                 case 'L':
1826                         show_cert = 1;
1827                         break;
1828                 case 'l':
1829                         print_fingerprint = 1;
1830                         break;
1831                 case 'B':
1832                         print_bubblebabble = 1;
1833                         break;
1834                 case 'm':
1835                         if (strcasecmp(optarg, "RFC4716") == 0 ||
1836                             strcasecmp(optarg, "ssh2") == 0) {
1837                                 convert_format = FMT_RFC4716;
1838                                 break;
1839                         }
1840                         if (strcasecmp(optarg, "PKCS8") == 0) {
1841                                 convert_format = FMT_PKCS8;
1842                                 break;
1843                         }
1844                         if (strcasecmp(optarg, "PEM") == 0) {
1845                                 convert_format = FMT_PEM;
1846                                 break;
1847                         }
1848                         fatal("Unsupported conversion format \"%s\"", optarg);
1849                 case 'n':
1850                         cert_principals = optarg;
1851                         break;
1852                 case 'p':
1853                         change_passphrase = 1;
1854                         break;
1855                 case 'c':
1856                         change_comment = 1;
1857                         break;
1858                 case 'f':
1859                         if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
1860                             sizeof(identity_file))
1861                                 fatal("Identity filename too long");
1862                         have_identity = 1;
1863                         break;
1864                 case 'g':
1865                         print_generic = 1;
1866                         break;
1867                 case 'P':
1868                         identity_passphrase = optarg;
1869                         break;
1870                 case 'N':
1871                         identity_new_passphrase = optarg;
1872                         break;
1873                 case 'O':
1874                         add_cert_option(optarg);
1875                         break;
1876                 case 'C':
1877                         identity_comment = optarg;
1878                         break;
1879                 case 'q':
1880                         quiet = 1;
1881                         break;
1882                 case 'e':
1883                 case 'x':
1884                         /* export key */
1885                         convert_to = 1;
1886                         break;
1887                 case 'h':
1888                         cert_key_type = SSH2_CERT_TYPE_HOST;
1889                         certflags_flags = 0;
1890                         break;
1891                 case 'i':
1892                 case 'X':
1893                         /* import key */
1894                         convert_from = 1;
1895                         break;
1896                 case 'y':
1897                         print_public = 1;
1898                         break;
1899                 case 'd':
1900                         key_type_name = "dsa";
1901                         break;
1902                 case 's':
1903                         ca_key_path = optarg;
1904                         break;
1905                 case 't':
1906                         key_type_name = optarg;
1907                         break;
1908                 case 'D':
1909                         pkcs11provider = optarg;
1910                         break;
1911                 case 'v':
1912                         if (log_level == SYSLOG_LEVEL_INFO)
1913                                 log_level = SYSLOG_LEVEL_DEBUG1;
1914                         else {
1915                                 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1916                                     log_level < SYSLOG_LEVEL_DEBUG3)
1917                                         log_level++;
1918                         }
1919                         break;
1920                 case 'r':
1921                         rr_hostname = optarg;
1922                         break;
1923                 case 'W':
1924                         generator_wanted = (u_int32_t)strtonum(optarg, 1,
1925                             UINT_MAX, &errstr);
1926                         if (errstr)
1927                                 fatal("Desired generator has bad value: %s (%s)",
1928                                         optarg, errstr);
1929                         break;
1930                 case 'a':
1931                         trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1932                         if (errstr)
1933                                 fatal("Invalid number of trials: %s (%s)",
1934                                         optarg, errstr);
1935                         break;
1936                 case 'M':
1937                         memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1938                         if (errstr)
1939                                 fatal("Memory limit is %s: %s", errstr, optarg);
1940                         break;
1941                 case 'G':
1942                         do_gen_candidates = 1;
1943                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1944                             sizeof(out_file))
1945                                 fatal("Output filename too long");
1946                         break;
1947                 case 'T':
1948                         do_screen_candidates = 1;
1949                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1950                             sizeof(out_file))
1951                                 fatal("Output filename too long");
1952                         break;
1953                 case 'S':
1954                         /* XXX - also compare length against bits */
1955                         if (BN_hex2bn(&start, optarg) == 0)
1956                                 fatal("Invalid start point.");
1957                         break;
1958                 case 'V':
1959                         parse_cert_times(optarg);
1960                         break;
1961                 case 'z':
1962                         cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr);
1963                         if (errstr)
1964                                 fatal("Invalid serial number: %s", errstr);
1965                         break;
1966                 case '?':
1967                 default:
1968                         usage();
1969                 }
1970         }
1971
1972         /* reinit */
1973         log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1974
1975         argv += optind;
1976         argc -= optind;
1977
1978         if (ca_key_path != NULL) {
1979                 if (argc < 1) {
1980                         printf("Too few arguments.\n");
1981                         usage();
1982                 }
1983         } else if (argc > 0) {
1984                 printf("Too many arguments.\n");
1985                 usage();
1986         }
1987         if (change_passphrase && change_comment) {
1988                 printf("Can only have one of -p and -c.\n");
1989                 usage();
1990         }
1991         if (print_fingerprint && (delete_host || hash_hosts)) {
1992                 printf("Cannot use -l with -D or -R.\n");
1993                 usage();
1994         }
1995         if (ca_key_path != NULL) {
1996                 if (cert_key_id == NULL)
1997                         fatal("Must specify key id (-I) when certifying");
1998                 do_ca_sign(pw, argc, argv);
1999         }
2000         if (show_cert)
2001                 do_show_cert(pw);
2002         if (delete_host || hash_hosts || find_host)
2003                 do_known_hosts(pw, rr_hostname);
2004         if (print_fingerprint || print_bubblebabble)
2005                 do_fingerprint(pw);
2006         if (change_passphrase)
2007                 do_change_passphrase(pw);
2008         if (change_comment)
2009                 do_change_comment(pw);
2010         if (convert_to)
2011                 do_convert_to(pw);
2012         if (convert_from)
2013                 do_convert_from(pw);
2014         if (print_public)
2015                 do_print_public(pw);
2016         if (rr_hostname != NULL) {
2017                 unsigned int n = 0;
2018
2019                 if (have_identity) {
2020                         n = do_print_resource_record(pw,
2021                             identity_file, rr_hostname);
2022                         if (n == 0) {
2023                                 perror(identity_file);
2024                                 exit(1);
2025                         }
2026                         exit(0);
2027                 } else {
2028
2029                         n += do_print_resource_record(pw,
2030                             _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2031                         n += do_print_resource_record(pw,
2032                             _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2033
2034                         if (n == 0)
2035                                 fatal("no keys found.");
2036                         exit(0);
2037                 }
2038         }
2039         if (pkcs11provider != NULL)
2040                 do_download(pw);
2041
2042         if (do_gen_candidates) {
2043                 FILE *out = fopen(out_file, "w");
2044
2045                 if (out == NULL) {
2046                         error("Couldn't open modulus candidate file \"%s\": %s",
2047                             out_file, strerror(errno));
2048                         return (1);
2049                 }
2050                 if (bits == 0)
2051                         bits = DEFAULT_BITS;
2052                 if (gen_candidates(out, memory, bits, start) != 0)
2053                         fatal("modulus candidate generation failed");
2054
2055                 return (0);
2056         }
2057
2058         if (do_screen_candidates) {
2059                 FILE *in;
2060                 FILE *out = fopen(out_file, "w");
2061
2062                 if (have_identity && strcmp(identity_file, "-") != 0) {
2063                         if ((in = fopen(identity_file, "r")) == NULL) {
2064                                 fatal("Couldn't open modulus candidate "
2065                                     "file \"%s\": %s", identity_file,
2066                                     strerror(errno));
2067                         }
2068                 } else
2069                         in = stdin;
2070
2071                 if (out == NULL) {
2072                         fatal("Couldn't open moduli file \"%s\": %s",
2073                             out_file, strerror(errno));
2074                 }
2075                 if (prime_test(in, out, trials, generator_wanted) != 0)
2076                         fatal("modulus screening failed");
2077                 return (0);
2078         }
2079
2080         arc4random_stir();
2081
2082         if (key_type_name == NULL)
2083                 key_type_name = "rsa";
2084
2085         type = key_type_from_name(key_type_name);
2086         if (type == KEY_UNSPEC) {
2087                 fprintf(stderr, "unknown key type %s\n", key_type_name);
2088                 exit(1);
2089         }
2090         if (bits == 0)
2091                 bits = (type == KEY_DSA) ? DEFAULT_BITS_DSA : DEFAULT_BITS;
2092         maxbits = (type == KEY_DSA) ?
2093             OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
2094         if (bits > maxbits) {
2095                 fprintf(stderr, "key bits exceeds maximum %d\n", maxbits);
2096                 exit(1);
2097         }
2098         if (type == KEY_DSA && bits != 1024)
2099                 fatal("DSA keys must be 1024 bits");
2100         if (!quiet)
2101                 printf("Generating public/private %s key pair.\n", key_type_name);
2102         private = key_generate(type, bits);
2103         if (private == NULL) {
2104                 fprintf(stderr, "key_generate failed\n");
2105                 exit(1);
2106         }
2107         public  = key_from_private(private);
2108
2109         if (!have_identity)
2110                 ask_filename(pw, "Enter file in which to save the key");
2111
2112         /* Create ~/.ssh directory if it doesn't already exist. */
2113         snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2114             pw->pw_dir, _PATH_SSH_USER_DIR);
2115         if (strstr(identity_file, dotsshdir) != NULL) {
2116                 if (stat(dotsshdir, &st) < 0) {
2117                         if (errno != ENOENT) {
2118                                 error("Could not stat %s: %s", dotsshdir,
2119                                     strerror(errno));
2120                         } else if (mkdir(dotsshdir, 0700) < 0) {
2121                                 error("Could not create directory '%s': %s",
2122                                     dotsshdir, strerror(errno));
2123                         } else if (!quiet)
2124                                 printf("Created directory '%s'.\n", dotsshdir);
2125                 }
2126         }
2127         /* If the file already exists, ask the user to confirm. */
2128         if (stat(identity_file, &st) >= 0) {
2129                 char yesno[3];
2130                 printf("%s already exists.\n", identity_file);
2131                 printf("Overwrite (y/n)? ");
2132                 fflush(stdout);
2133                 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2134                         exit(1);
2135                 if (yesno[0] != 'y' && yesno[0] != 'Y')
2136                         exit(1);
2137         }
2138         /* Ask for a passphrase (twice). */
2139         if (identity_passphrase)
2140                 passphrase1 = xstrdup(identity_passphrase);
2141         else if (identity_new_passphrase)
2142                 passphrase1 = xstrdup(identity_new_passphrase);
2143         else {
2144 passphrase_again:
2145                 passphrase1 =
2146                         read_passphrase("Enter passphrase (empty for no "
2147                             "passphrase): ", RP_ALLOW_STDIN);
2148                 passphrase2 = read_passphrase("Enter same passphrase again: ",
2149                     RP_ALLOW_STDIN);
2150                 if (strcmp(passphrase1, passphrase2) != 0) {
2151                         /*
2152                          * The passphrases do not match.  Clear them and
2153                          * retry.
2154                          */
2155                         memset(passphrase1, 0, strlen(passphrase1));
2156                         memset(passphrase2, 0, strlen(passphrase2));
2157                         xfree(passphrase1);
2158                         xfree(passphrase2);
2159                         printf("Passphrases do not match.  Try again.\n");
2160                         goto passphrase_again;
2161                 }
2162                 /* Clear the other copy of the passphrase. */
2163                 memset(passphrase2, 0, strlen(passphrase2));
2164                 xfree(passphrase2);
2165         }
2166
2167         if (identity_comment) {
2168                 strlcpy(comment, identity_comment, sizeof(comment));
2169         } else {
2170                 /* Create default comment field for the passphrase. */
2171                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2172         }
2173
2174         /* Save the key with the given passphrase and comment. */
2175         if (!key_save_private(private, identity_file, passphrase1, comment)) {
2176                 printf("Saving the key failed: %s.\n", identity_file);
2177                 memset(passphrase1, 0, strlen(passphrase1));
2178                 xfree(passphrase1);
2179                 exit(1);
2180         }
2181         /* Clear the passphrase. */
2182         memset(passphrase1, 0, strlen(passphrase1));
2183         xfree(passphrase1);
2184
2185         /* Clear the private key and the random number generator. */
2186         key_free(private);
2187         arc4random_stir();
2188
2189         if (!quiet)
2190                 printf("Your identification has been saved in %s.\n", identity_file);
2191
2192         strlcat(identity_file, ".pub", sizeof(identity_file));
2193         fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2194         if (fd == -1) {
2195                 printf("Could not save your public key in %s\n", identity_file);
2196                 exit(1);
2197         }
2198         f = fdopen(fd, "w");
2199         if (f == NULL) {
2200                 printf("fdopen %s failed\n", identity_file);
2201                 exit(1);
2202         }
2203         if (!key_write(public, f))
2204                 fprintf(stderr, "write key failed\n");
2205         fprintf(f, " %s\n", comment);
2206         fclose(f);
2207
2208         if (!quiet) {
2209                 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2210                 char *ra = key_fingerprint(public, SSH_FP_MD5,
2211                     SSH_FP_RANDOMART);
2212                 printf("Your public key has been saved in %s.\n",
2213                     identity_file);
2214                 printf("The key fingerprint is:\n");
2215                 printf("%s %s\n", fp, comment);
2216                 printf("The key's randomart image is:\n");
2217                 printf("%s\n", ra);
2218                 xfree(ra);
2219                 xfree(fp);
2220         }
2221
2222         key_free(public);
2223         exit(0);
2224 }