Merge branch 'master' of /home/www-data/gitweb/dragonfly
[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 %llu%s%s "
1452                             "valid %s", key_cert_type(public), 
1453                             out, public->cert->key_id, public->cert->serial,
1454                             cert_principals != NULL ? " for " : "",
1455                             cert_principals != NULL ? cert_principals : "",
1456                             fmt_validity(cert_valid_from, cert_valid_to));
1457                 }
1458
1459                 key_free(public);
1460                 xfree(out);
1461         }
1462         pkcs11_terminate();
1463         exit(0);
1464 }
1465
1466 static u_int64_t
1467 parse_relative_time(const char *s, time_t now)
1468 {
1469         int64_t mul, secs;
1470
1471         mul = *s == '-' ? -1 : 1;
1472
1473         if ((secs = convtime(s + 1)) == -1)
1474                 fatal("Invalid relative certificate time %s", s);
1475         if (mul == -1 && secs > now)
1476                 fatal("Certificate time %s cannot be represented", s);
1477         return now + (u_int64_t)(secs * mul);
1478 }
1479
1480 static u_int64_t
1481 parse_absolute_time(const char *s)
1482 {
1483         struct tm tm;
1484         time_t tt;
1485         char buf[32], *fmt;
1486
1487         /*
1488          * POSIX strptime says "The application shall ensure that there 
1489          * is white-space or other non-alphanumeric characters between
1490          * any two conversion specifications" so arrange things this way.
1491          */
1492         switch (strlen(s)) {
1493         case 8:
1494                 fmt = "%Y-%m-%d";
1495                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1496                 break;
1497         case 14:
1498                 fmt = "%Y-%m-%dT%H:%M:%S";
1499                 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1500                     s, s + 4, s + 6, s + 8, s + 10, s + 12);
1501                 break;
1502         default:
1503                 fatal("Invalid certificate time format %s", s);
1504         }
1505
1506         bzero(&tm, sizeof(tm));
1507         if (strptime(buf, fmt, &tm) == NULL)
1508                 fatal("Invalid certificate time %s", s);
1509         if ((tt = mktime(&tm)) < 0)
1510                 fatal("Certificate time %s cannot be represented", s);
1511         return (u_int64_t)tt;
1512 }
1513
1514 static void
1515 parse_cert_times(char *timespec)
1516 {
1517         char *from, *to;
1518         time_t now = time(NULL);
1519         int64_t secs;
1520
1521         /* +timespec relative to now */
1522         if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1523                 if ((secs = convtime(timespec + 1)) == -1)
1524                         fatal("Invalid relative certificate life %s", timespec);
1525                 cert_valid_to = now + secs;
1526                 /*
1527                  * Backdate certificate one minute to avoid problems on hosts
1528                  * with poorly-synchronised clocks.
1529                  */
1530                 cert_valid_from = ((now - 59)/ 60) * 60;
1531                 return;
1532         }
1533
1534         /*
1535          * from:to, where
1536          * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1537          *   to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1538          */
1539         from = xstrdup(timespec);
1540         to = strchr(from, ':');
1541         if (to == NULL || from == to || *(to + 1) == '\0')
1542                 fatal("Invalid certificate life specification %s", timespec);
1543         *to++ = '\0';
1544
1545         if (*from == '-' || *from == '+')
1546                 cert_valid_from = parse_relative_time(from, now);
1547         else
1548                 cert_valid_from = parse_absolute_time(from);
1549
1550         if (*to == '-' || *to == '+')
1551                 cert_valid_to = parse_relative_time(to, cert_valid_from);
1552         else
1553                 cert_valid_to = parse_absolute_time(to);
1554
1555         if (cert_valid_to <= cert_valid_from)
1556                 fatal("Empty certificate validity interval");
1557         xfree(from);
1558 }
1559
1560 static void
1561 add_cert_option(char *opt)
1562 {
1563         char *val;
1564
1565         if (strcmp(opt, "clear") == 0)
1566                 certflags_flags = 0;
1567         else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1568                 certflags_flags &= ~CERTOPT_X_FWD;
1569         else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1570                 certflags_flags |= CERTOPT_X_FWD;
1571         else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1572                 certflags_flags &= ~CERTOPT_AGENT_FWD;
1573         else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1574                 certflags_flags |= CERTOPT_AGENT_FWD;
1575         else if (strcasecmp(opt, "no-port-forwarding") == 0)
1576                 certflags_flags &= ~CERTOPT_PORT_FWD;
1577         else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1578                 certflags_flags |= CERTOPT_PORT_FWD;
1579         else if (strcasecmp(opt, "no-pty") == 0)
1580                 certflags_flags &= ~CERTOPT_PTY;
1581         else if (strcasecmp(opt, "permit-pty") == 0)
1582                 certflags_flags |= CERTOPT_PTY;
1583         else if (strcasecmp(opt, "no-user-rc") == 0)
1584                 certflags_flags &= ~CERTOPT_USER_RC;
1585         else if (strcasecmp(opt, "permit-user-rc") == 0)
1586                 certflags_flags |= CERTOPT_USER_RC;
1587         else if (strncasecmp(opt, "force-command=", 14) == 0) {
1588                 val = opt + 14;
1589                 if (*val == '\0')
1590                         fatal("Empty force-command option");
1591                 if (certflags_command != NULL)
1592                         fatal("force-command already specified");
1593                 certflags_command = xstrdup(val);
1594         } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1595                 val = opt + 15;
1596                 if (*val == '\0')
1597                         fatal("Empty source-address option");
1598                 if (certflags_src_addr != NULL)
1599                         fatal("source-address already specified");
1600                 if (addr_match_cidr_list(NULL, val) != 0)
1601                         fatal("Invalid source-address list");
1602                 certflags_src_addr = xstrdup(val);
1603         } else
1604                 fatal("Unsupported certificate option \"%s\"", opt);
1605 }
1606
1607 static void
1608 show_options(const Buffer *optbuf, int v00, int in_critical)
1609 {
1610         u_char *name, *data;
1611         u_int dlen;
1612         Buffer options, option;
1613
1614         buffer_init(&options);
1615         buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1616
1617         buffer_init(&option);
1618         while (buffer_len(&options) != 0) {
1619                 name = buffer_get_string(&options, NULL);
1620                 data = buffer_get_string_ptr(&options, &dlen);
1621                 buffer_append(&option, data, dlen);
1622                 printf("                %s", name);
1623                 if ((v00 || !in_critical) && 
1624                     (strcmp(name, "permit-X11-forwarding") == 0 ||
1625                     strcmp(name, "permit-agent-forwarding") == 0 ||
1626                     strcmp(name, "permit-port-forwarding") == 0 ||
1627                     strcmp(name, "permit-pty") == 0 ||
1628                     strcmp(name, "permit-user-rc") == 0))
1629                         printf("\n");
1630                 else if ((v00 || in_critical) &&
1631                     (strcmp(name, "force-command") == 0 ||
1632                     strcmp(name, "source-address") == 0)) {
1633                         data = buffer_get_string(&option, NULL);
1634                         printf(" %s\n", data);
1635                         xfree(data);
1636                 } else {
1637                         printf(" UNKNOWN OPTION (len %u)\n",
1638                             buffer_len(&option));
1639                         buffer_clear(&option);
1640                 }
1641                 xfree(name);
1642                 if (buffer_len(&option) != 0)
1643                         fatal("Option corrupt: extra data at end");
1644         }
1645         buffer_free(&option);
1646         buffer_free(&options);
1647 }
1648
1649 static void
1650 do_show_cert(struct passwd *pw)
1651 {
1652         Key *key;
1653         struct stat st;
1654         char *key_fp, *ca_fp;
1655         u_int i, v00;
1656
1657         if (!have_identity)
1658                 ask_filename(pw, "Enter file in which the key is");
1659         if (stat(identity_file, &st) < 0)
1660                 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1661         if ((key = key_load_public(identity_file, NULL)) == NULL)
1662                 fatal("%s is not a public key", identity_file);
1663         if (!key_is_cert(key))
1664                 fatal("%s is not a certificate", identity_file);
1665         v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1666
1667         key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1668         ca_fp = key_fingerprint(key->cert->signature_key,
1669             SSH_FP_MD5, SSH_FP_HEX);
1670
1671         printf("%s:\n", identity_file);
1672         printf("        Type: %s %s certificate\n", key_ssh_name(key),
1673             key_cert_type(key));
1674         printf("        Public key: %s %s\n", key_type(key), key_fp);
1675         printf("        Signing CA: %s %s\n",
1676             key_type(key->cert->signature_key), ca_fp);
1677         printf("        Key ID: \"%s\"\n", key->cert->key_id);
1678         if (!v00)
1679                 printf("        Serial: %llu\n", key->cert->serial);
1680         printf("        Valid: %s\n",
1681             fmt_validity(key->cert->valid_after, key->cert->valid_before));
1682         printf("        Principals: ");
1683         if (key->cert->nprincipals == 0)
1684                 printf("(none)\n");
1685         else {
1686                 for (i = 0; i < key->cert->nprincipals; i++)
1687                         printf("\n                %s",
1688                             key->cert->principals[i]);
1689                 printf("\n");
1690         }
1691         printf("        Critical Options: ");
1692         if (buffer_len(&key->cert->critical) == 0)
1693                 printf("(none)\n");
1694         else {
1695                 printf("\n");
1696                 show_options(&key->cert->critical, v00, 1);
1697         }
1698         if (!v00) {
1699                 printf("        Extensions: ");
1700                 if (buffer_len(&key->cert->extensions) == 0)
1701                         printf("(none)\n");
1702                 else {
1703                         printf("\n");
1704                         show_options(&key->cert->extensions, v00, 0);
1705                 }
1706         }
1707         exit(0);
1708 }
1709
1710 static void
1711 usage(void)
1712 {
1713         fprintf(stderr, "usage: %s [options]\n", __progname);
1714         fprintf(stderr, "Options:\n");
1715         fprintf(stderr, "  -a trials   Number of trials for screening DH-GEX moduli.\n");
1716         fprintf(stderr, "  -B          Show bubblebabble digest of key file.\n");
1717         fprintf(stderr, "  -b bits     Number of bits in the key to create.\n");
1718         fprintf(stderr, "  -C comment  Provide new comment.\n");
1719         fprintf(stderr, "  -c          Change comment in private and public key files.\n");
1720 #ifdef ENABLE_PKCS11
1721         fprintf(stderr, "  -D pkcs11   Download public key from pkcs11 token.\n");
1722 #endif
1723         fprintf(stderr, "  -e          Export OpenSSH to foreign format key file.\n");
1724         fprintf(stderr, "  -F hostname Find hostname in known hosts file.\n");
1725         fprintf(stderr, "  -f filename Filename of the key file.\n");
1726         fprintf(stderr, "  -G file     Generate candidates for DH-GEX moduli.\n");
1727         fprintf(stderr, "  -g          Use generic DNS resource record format.\n");
1728         fprintf(stderr, "  -H          Hash names in known_hosts file.\n");
1729         fprintf(stderr, "  -h          Generate host certificate instead of a user certificate.\n");
1730         fprintf(stderr, "  -I key_id   Key identifier to include in certificate.\n");
1731         fprintf(stderr, "  -i          Import foreign format to OpenSSH key file.\n");
1732         fprintf(stderr, "  -L          Print the contents of a certificate.\n");
1733         fprintf(stderr, "  -l          Show fingerprint of key file.\n");
1734         fprintf(stderr, "  -M memory   Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1735         fprintf(stderr, "  -m key_fmt  Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
1736         fprintf(stderr, "  -N phrase   Provide new passphrase.\n");
1737         fprintf(stderr, "  -n name,... User/host principal names to include in certificate\n");
1738         fprintf(stderr, "  -O option   Specify a certificate option.\n");
1739         fprintf(stderr, "  -P phrase   Provide old passphrase.\n");
1740         fprintf(stderr, "  -p          Change passphrase of private key file.\n");
1741         fprintf(stderr, "  -q          Quiet.\n");
1742         fprintf(stderr, "  -R hostname Remove host from known_hosts file.\n");
1743         fprintf(stderr, "  -r hostname Print DNS resource record.\n");
1744         fprintf(stderr, "  -S start    Start point (hex) for generating DH-GEX moduli.\n");
1745         fprintf(stderr, "  -s ca_key   Certify keys with CA key.\n");
1746         fprintf(stderr, "  -T file     Screen candidates for DH-GEX moduli.\n");
1747         fprintf(stderr, "  -t type     Specify type of key to create.\n");
1748         fprintf(stderr, "  -V from:to  Specify certificate validity interval.\n");
1749         fprintf(stderr, "  -v          Verbose.\n");
1750         fprintf(stderr, "  -W gen      Generator to use for generating DH-GEX moduli.\n");
1751         fprintf(stderr, "  -y          Read private key file and print public key.\n");
1752         fprintf(stderr, "  -z serial   Specify a serial number.\n");
1753
1754         exit(1);
1755 }
1756
1757 /*
1758  * Main program for key management.
1759  */
1760 int
1761 main(int argc, char **argv)
1762 {
1763         char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1764         char out_file[MAXPATHLEN], *rr_hostname = NULL;
1765         Key *private, *public;
1766         struct passwd *pw;
1767         struct stat st;
1768         int opt, type, fd;
1769         u_int maxbits;
1770         u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1771         int do_gen_candidates = 0, do_screen_candidates = 0;
1772         BIGNUM *start = NULL;
1773         FILE *f;
1774         const char *errstr;
1775
1776         extern int optind;
1777         extern char *optarg;
1778
1779         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1780         sanitise_stdfd();
1781
1782         __progname = ssh_get_progname(argv[0]);
1783
1784         SSLeay_add_all_algorithms();
1785         log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1786
1787         init_rng();
1788         seed_rng();
1789
1790         /* we need this for the home * directory.  */
1791         pw = getpwuid(getuid());
1792         if (!pw) {
1793                 printf("You don't exist, go away!\n");
1794                 exit(1);
1795         }
1796         if (gethostname(hostname, sizeof(hostname)) < 0) {
1797                 perror("gethostname");
1798                 exit(1);
1799         }
1800
1801         while ((opt = getopt(argc, argv, "degiqpclBHLhvxXyF:b:f:t:D:I:P:m:N:n:"
1802             "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) {
1803                 switch (opt) {
1804                 case 'b':
1805                         bits = (u_int32_t)strtonum(optarg, 768, 32768, &errstr);
1806                         if (errstr)
1807                                 fatal("Bits has bad value %s (%s)",
1808                                         optarg, errstr);
1809                         break;
1810                 case 'F':
1811                         find_host = 1;
1812                         rr_hostname = optarg;
1813                         break;
1814                 case 'H':
1815                         hash_hosts = 1;
1816                         break;
1817                 case 'I':
1818                         cert_key_id = optarg;
1819                         break;
1820                 case 'R':
1821                         delete_host = 1;
1822                         rr_hostname = optarg;
1823                         break;
1824                 case 'L':
1825                         show_cert = 1;
1826                         break;
1827                 case 'l':
1828                         print_fingerprint = 1;
1829                         break;
1830                 case 'B':
1831                         print_bubblebabble = 1;
1832                         break;
1833                 case 'm':
1834                         if (strcasecmp(optarg, "RFC4716") == 0 ||
1835                             strcasecmp(optarg, "ssh2") == 0) {
1836                                 convert_format = FMT_RFC4716;
1837                                 break;
1838                         }
1839                         if (strcasecmp(optarg, "PKCS8") == 0) {
1840                                 convert_format = FMT_PKCS8;
1841                                 break;
1842                         }
1843                         if (strcasecmp(optarg, "PEM") == 0) {
1844                                 convert_format = FMT_PEM;
1845                                 break;
1846                         }
1847                         fatal("Unsupported conversion format \"%s\"", optarg);
1848                 case 'n':
1849                         cert_principals = optarg;
1850                         break;
1851                 case 'p':
1852                         change_passphrase = 1;
1853                         break;
1854                 case 'c':
1855                         change_comment = 1;
1856                         break;
1857                 case 'f':
1858                         if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
1859                             sizeof(identity_file))
1860                                 fatal("Identity filename too long");
1861                         have_identity = 1;
1862                         break;
1863                 case 'g':
1864                         print_generic = 1;
1865                         break;
1866                 case 'P':
1867                         identity_passphrase = optarg;
1868                         break;
1869                 case 'N':
1870                         identity_new_passphrase = optarg;
1871                         break;
1872                 case 'O':
1873                         add_cert_option(optarg);
1874                         break;
1875                 case 'C':
1876                         identity_comment = optarg;
1877                         break;
1878                 case 'q':
1879                         quiet = 1;
1880                         break;
1881                 case 'e':
1882                 case 'x':
1883                         /* export key */
1884                         convert_to = 1;
1885                         break;
1886                 case 'h':
1887                         cert_key_type = SSH2_CERT_TYPE_HOST;
1888                         certflags_flags = 0;
1889                         break;
1890                 case 'i':
1891                 case 'X':
1892                         /* import key */
1893                         convert_from = 1;
1894                         break;
1895                 case 'y':
1896                         print_public = 1;
1897                         break;
1898                 case 'd':
1899                         key_type_name = "dsa";
1900                         break;
1901                 case 's':
1902                         ca_key_path = optarg;
1903                         break;
1904                 case 't':
1905                         key_type_name = optarg;
1906                         break;
1907                 case 'D':
1908                         pkcs11provider = optarg;
1909                         break;
1910                 case 'v':
1911                         if (log_level == SYSLOG_LEVEL_INFO)
1912                                 log_level = SYSLOG_LEVEL_DEBUG1;
1913                         else {
1914                                 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1915                                     log_level < SYSLOG_LEVEL_DEBUG3)
1916                                         log_level++;
1917                         }
1918                         break;
1919                 case 'r':
1920                         rr_hostname = optarg;
1921                         break;
1922                 case 'W':
1923                         generator_wanted = (u_int32_t)strtonum(optarg, 1,
1924                             UINT_MAX, &errstr);
1925                         if (errstr)
1926                                 fatal("Desired generator has bad value: %s (%s)",
1927                                         optarg, errstr);
1928                         break;
1929                 case 'a':
1930                         trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1931                         if (errstr)
1932                                 fatal("Invalid number of trials: %s (%s)",
1933                                         optarg, errstr);
1934                         break;
1935                 case 'M':
1936                         memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1937                         if (errstr)
1938                                 fatal("Memory limit is %s: %s", errstr, optarg);
1939                         break;
1940                 case 'G':
1941                         do_gen_candidates = 1;
1942                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1943                             sizeof(out_file))
1944                                 fatal("Output filename too long");
1945                         break;
1946                 case 'T':
1947                         do_screen_candidates = 1;
1948                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1949                             sizeof(out_file))
1950                                 fatal("Output filename too long");
1951                         break;
1952                 case 'S':
1953                         /* XXX - also compare length against bits */
1954                         if (BN_hex2bn(&start, optarg) == 0)
1955                                 fatal("Invalid start point.");
1956                         break;
1957                 case 'V':
1958                         parse_cert_times(optarg);
1959                         break;
1960                 case 'z':
1961                         cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr);
1962                         if (errstr)
1963                                 fatal("Invalid serial number: %s", errstr);
1964                         break;
1965                 case '?':
1966                 default:
1967                         usage();
1968                 }
1969         }
1970
1971         /* reinit */
1972         log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1973
1974         argv += optind;
1975         argc -= optind;
1976
1977         if (ca_key_path != NULL) {
1978                 if (argc < 1) {
1979                         printf("Too few arguments.\n");
1980                         usage();
1981                 }
1982         } else if (argc > 0) {
1983                 printf("Too many arguments.\n");
1984                 usage();
1985         }
1986         if (change_passphrase && change_comment) {
1987                 printf("Can only have one of -p and -c.\n");
1988                 usage();
1989         }
1990         if (print_fingerprint && (delete_host || hash_hosts)) {
1991                 printf("Cannot use -l with -D or -R.\n");
1992                 usage();
1993         }
1994         if (ca_key_path != NULL) {
1995                 if (cert_key_id == NULL)
1996                         fatal("Must specify key id (-I) when certifying");
1997                 do_ca_sign(pw, argc, argv);
1998         }
1999         if (show_cert)
2000                 do_show_cert(pw);
2001         if (delete_host || hash_hosts || find_host)
2002                 do_known_hosts(pw, rr_hostname);
2003         if (print_fingerprint || print_bubblebabble)
2004                 do_fingerprint(pw);
2005         if (change_passphrase)
2006                 do_change_passphrase(pw);
2007         if (change_comment)
2008                 do_change_comment(pw);
2009         if (convert_to)
2010                 do_convert_to(pw);
2011         if (convert_from)
2012                 do_convert_from(pw);
2013         if (print_public)
2014                 do_print_public(pw);
2015         if (rr_hostname != NULL) {
2016                 unsigned int n = 0;
2017
2018                 if (have_identity) {
2019                         n = do_print_resource_record(pw,
2020                             identity_file, rr_hostname);
2021                         if (n == 0) {
2022                                 perror(identity_file);
2023                                 exit(1);
2024                         }
2025                         exit(0);
2026                 } else {
2027
2028                         n += do_print_resource_record(pw,
2029                             _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2030                         n += do_print_resource_record(pw,
2031                             _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2032
2033                         if (n == 0)
2034                                 fatal("no keys found.");
2035                         exit(0);
2036                 }
2037         }
2038         if (pkcs11provider != NULL)
2039                 do_download(pw);
2040
2041         if (do_gen_candidates) {
2042                 FILE *out = fopen(out_file, "w");
2043
2044                 if (out == NULL) {
2045                         error("Couldn't open modulus candidate file \"%s\": %s",
2046                             out_file, strerror(errno));
2047                         return (1);
2048                 }
2049                 if (bits == 0)
2050                         bits = DEFAULT_BITS;
2051                 if (gen_candidates(out, memory, bits, start) != 0)
2052                         fatal("modulus candidate generation failed");
2053
2054                 return (0);
2055         }
2056
2057         if (do_screen_candidates) {
2058                 FILE *in;
2059                 FILE *out = fopen(out_file, "w");
2060
2061                 if (have_identity && strcmp(identity_file, "-") != 0) {
2062                         if ((in = fopen(identity_file, "r")) == NULL) {
2063                                 fatal("Couldn't open modulus candidate "
2064                                     "file \"%s\": %s", identity_file,
2065                                     strerror(errno));
2066                         }
2067                 } else
2068                         in = stdin;
2069
2070                 if (out == NULL) {
2071                         fatal("Couldn't open moduli file \"%s\": %s",
2072                             out_file, strerror(errno));
2073                 }
2074                 if (prime_test(in, out, trials, generator_wanted) != 0)
2075                         fatal("modulus screening failed");
2076                 return (0);
2077         }
2078
2079         arc4random_stir();
2080
2081         if (key_type_name == NULL)
2082                 key_type_name = "rsa";
2083
2084         type = key_type_from_name(key_type_name);
2085         if (type == KEY_UNSPEC) {
2086                 fprintf(stderr, "unknown key type %s\n", key_type_name);
2087                 exit(1);
2088         }
2089         if (bits == 0)
2090                 bits = (type == KEY_DSA) ? DEFAULT_BITS_DSA : DEFAULT_BITS;
2091         maxbits = (type == KEY_DSA) ?
2092             OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
2093         if (bits > maxbits) {
2094                 fprintf(stderr, "key bits exceeds maximum %d\n", maxbits);
2095                 exit(1);
2096         }
2097         if (type == KEY_DSA && bits != 1024)
2098                 fatal("DSA keys must be 1024 bits");
2099         if (!quiet)
2100                 printf("Generating public/private %s key pair.\n", key_type_name);
2101         private = key_generate(type, bits);
2102         if (private == NULL) {
2103                 fprintf(stderr, "key_generate failed\n");
2104                 exit(1);
2105         }
2106         public  = key_from_private(private);
2107
2108         if (!have_identity)
2109                 ask_filename(pw, "Enter file in which to save the key");
2110
2111         /* Create ~/.ssh directory if it doesn't already exist. */
2112         snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2113             pw->pw_dir, _PATH_SSH_USER_DIR);
2114         if (strstr(identity_file, dotsshdir) != NULL) {
2115                 if (stat(dotsshdir, &st) < 0) {
2116                         if (errno != ENOENT) {
2117                                 error("Could not stat %s: %s", dotsshdir,
2118                                     strerror(errno));
2119                         } else if (mkdir(dotsshdir, 0700) < 0) {
2120                                 error("Could not create directory '%s': %s",
2121                                     dotsshdir, strerror(errno));
2122                         } else if (!quiet)
2123                                 printf("Created directory '%s'.\n", dotsshdir);
2124                 }
2125         }
2126         /* If the file already exists, ask the user to confirm. */
2127         if (stat(identity_file, &st) >= 0) {
2128                 char yesno[3];
2129                 printf("%s already exists.\n", identity_file);
2130                 printf("Overwrite (y/n)? ");
2131                 fflush(stdout);
2132                 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2133                         exit(1);
2134                 if (yesno[0] != 'y' && yesno[0] != 'Y')
2135                         exit(1);
2136         }
2137         /* Ask for a passphrase (twice). */
2138         if (identity_passphrase)
2139                 passphrase1 = xstrdup(identity_passphrase);
2140         else if (identity_new_passphrase)
2141                 passphrase1 = xstrdup(identity_new_passphrase);
2142         else {
2143 passphrase_again:
2144                 passphrase1 =
2145                         read_passphrase("Enter passphrase (empty for no "
2146                             "passphrase): ", RP_ALLOW_STDIN);
2147                 passphrase2 = read_passphrase("Enter same passphrase again: ",
2148                     RP_ALLOW_STDIN);
2149                 if (strcmp(passphrase1, passphrase2) != 0) {
2150                         /*
2151                          * The passphrases do not match.  Clear them and
2152                          * retry.
2153                          */
2154                         memset(passphrase1, 0, strlen(passphrase1));
2155                         memset(passphrase2, 0, strlen(passphrase2));
2156                         xfree(passphrase1);
2157                         xfree(passphrase2);
2158                         printf("Passphrases do not match.  Try again.\n");
2159                         goto passphrase_again;
2160                 }
2161                 /* Clear the other copy of the passphrase. */
2162                 memset(passphrase2, 0, strlen(passphrase2));
2163                 xfree(passphrase2);
2164         }
2165
2166         if (identity_comment) {
2167                 strlcpy(comment, identity_comment, sizeof(comment));
2168         } else {
2169                 /* Create default comment field for the passphrase. */
2170                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2171         }
2172
2173         /* Save the key with the given passphrase and comment. */
2174         if (!key_save_private(private, identity_file, passphrase1, comment)) {
2175                 printf("Saving the key failed: %s.\n", identity_file);
2176                 memset(passphrase1, 0, strlen(passphrase1));
2177                 xfree(passphrase1);
2178                 exit(1);
2179         }
2180         /* Clear the passphrase. */
2181         memset(passphrase1, 0, strlen(passphrase1));
2182         xfree(passphrase1);
2183
2184         /* Clear the private key and the random number generator. */
2185         key_free(private);
2186         arc4random_stir();
2187
2188         if (!quiet)
2189                 printf("Your identification has been saved in %s.\n", identity_file);
2190
2191         strlcat(identity_file, ".pub", sizeof(identity_file));
2192         fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2193         if (fd == -1) {
2194                 printf("Could not save your public key in %s\n", identity_file);
2195                 exit(1);
2196         }
2197         f = fdopen(fd, "w");
2198         if (f == NULL) {
2199                 printf("fdopen %s failed\n", identity_file);
2200                 exit(1);
2201         }
2202         if (!key_write(public, f))
2203                 fprintf(stderr, "write key failed\n");
2204         fprintf(f, " %s\n", comment);
2205         fclose(f);
2206
2207         if (!quiet) {
2208                 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2209                 char *ra = key_fingerprint(public, SSH_FP_MD5,
2210                     SSH_FP_RANDOMART);
2211                 printf("Your public key has been saved in %s.\n",
2212                     identity_file);
2213                 printf("The key fingerprint is:\n");
2214                 printf("%s %s\n", fp, comment);
2215                 printf("The key's randomart image is:\n");
2216                 printf("%s\n", ra);
2217                 xfree(ra);
2218                 xfree(fp);
2219         }
2220
2221         key_free(public);
2222         exit(0);
2223 }