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