- (dtucker) [platform.c] includes.h instead of defines.h so that we get
[openssh-git.git] / ssh-keygen.c
blob560c4818a44baf831a7a78a9dc8934b53cc10728
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 case KEY_ECDSA_CERT:
181 case KEY_ECDSA:
182 name = _PATH_SSH_CLIENT_ID_ECDSA;
183 break;
184 case KEY_RSA_CERT:
185 case KEY_RSA_CERT_V00:
186 case KEY_RSA:
187 name = _PATH_SSH_CLIENT_ID_RSA;
188 break;
189 default:
190 fprintf(stderr, "bad key type\n");
191 exit(1);
192 break;
195 snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
196 fprintf(stderr, "%s (%s): ", prompt, identity_file);
197 if (fgets(buf, sizeof(buf), stdin) == NULL)
198 exit(1);
199 buf[strcspn(buf, "\n")] = '\0';
200 if (strcmp(buf, "") != 0)
201 strlcpy(identity_file, buf, sizeof(identity_file));
202 have_identity = 1;
205 static Key *
206 load_identity(char *filename)
208 char *pass;
209 Key *prv;
211 prv = key_load_private(filename, "", NULL);
212 if (prv == NULL) {
213 if (identity_passphrase)
214 pass = xstrdup(identity_passphrase);
215 else
216 pass = read_passphrase("Enter passphrase: ",
217 RP_ALLOW_STDIN);
218 prv = key_load_private(filename, pass, NULL);
219 memset(pass, 0, strlen(pass));
220 xfree(pass);
222 return prv;
225 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
226 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
227 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
228 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
230 static void
231 do_convert_to_ssh2(struct passwd *pw, Key *k)
233 u_int len;
234 u_char *blob;
235 char comment[61];
237 if (key_to_blob(k, &blob, &len) <= 0) {
238 fprintf(stderr, "key_to_blob failed\n");
239 exit(1);
241 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
242 snprintf(comment, sizeof(comment),
243 "%u-bit %s, converted by %s@%s from OpenSSH",
244 key_size(k), key_type(k),
245 pw->pw_name, hostname);
247 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
248 fprintf(stdout, "Comment: \"%s\"\n", comment);
249 dump_base64(stdout, blob, len);
250 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
251 key_free(k);
252 xfree(blob);
253 exit(0);
256 static void
257 do_convert_to_pkcs8(Key *k)
259 switch (key_type_plain(k->type)) {
260 case KEY_RSA:
261 if (!PEM_write_RSA_PUBKEY(stdout, k->rsa))
262 fatal("PEM_write_RSA_PUBKEY failed");
263 break;
264 case KEY_DSA:
265 if (!PEM_write_DSA_PUBKEY(stdout, k->dsa))
266 fatal("PEM_write_DSA_PUBKEY failed");
267 break;
268 #ifdef OPENSSL_HAS_ECC
269 case KEY_ECDSA:
270 if (!PEM_write_EC_PUBKEY(stdout, k->ecdsa))
271 fatal("PEM_write_EC_PUBKEY failed");
272 break;
273 #endif
274 default:
275 fatal("%s: unsupported key type %s", __func__, key_type(k));
277 exit(0);
280 static void
281 do_convert_to_pem(Key *k)
283 switch (key_type_plain(k->type)) {
284 case KEY_RSA:
285 if (!PEM_write_RSAPublicKey(stdout, k->rsa))
286 fatal("PEM_write_RSAPublicKey failed");
287 break;
288 #if notyet /* OpenSSH 0.9.8 lacks this function */
289 case KEY_DSA:
290 if (!PEM_write_DSAPublicKey(stdout, k->dsa))
291 fatal("PEM_write_DSAPublicKey failed");
292 break;
293 #endif
294 /* XXX ECDSA? */
295 default:
296 fatal("%s: unsupported key type %s", __func__, key_type(k));
298 exit(0);
301 static void
302 do_convert_to(struct passwd *pw)
304 Key *k;
305 struct stat st;
307 if (!have_identity)
308 ask_filename(pw, "Enter file in which the key is");
309 if (stat(identity_file, &st) < 0)
310 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
311 if ((k = key_load_public(identity_file, NULL)) == NULL) {
312 if ((k = load_identity(identity_file)) == NULL) {
313 fprintf(stderr, "load failed\n");
314 exit(1);
317 if (k->type == KEY_RSA1) {
318 fprintf(stderr, "version 1 keys are not supported\n");
319 exit(1);
322 switch (convert_format) {
323 case FMT_RFC4716:
324 do_convert_to_ssh2(pw, k);
325 break;
326 case FMT_PKCS8:
327 do_convert_to_pkcs8(k);
328 break;
329 case FMT_PEM:
330 do_convert_to_pem(k);
331 break;
332 default:
333 fatal("%s: unknown key format %d", __func__, convert_format);
335 exit(0);
338 static void
339 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
341 u_int bignum_bits = buffer_get_int(b);
342 u_int bytes = (bignum_bits + 7) / 8;
344 if (buffer_len(b) < bytes)
345 fatal("buffer_get_bignum_bits: input buffer too small: "
346 "need %d have %d", bytes, buffer_len(b));
347 if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL)
348 fatal("buffer_get_bignum_bits: BN_bin2bn failed");
349 buffer_consume(b, bytes);
352 static Key *
353 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
355 Buffer b;
356 Key *key = NULL;
357 char *type, *cipher;
358 u_char *sig, data[] = "abcde12345";
359 int magic, rlen, ktype, i1, i2, i3, i4;
360 u_int slen;
361 u_long e;
363 buffer_init(&b);
364 buffer_append(&b, blob, blen);
366 magic = buffer_get_int(&b);
367 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
368 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
369 buffer_free(&b);
370 return NULL;
372 i1 = buffer_get_int(&b);
373 type = buffer_get_string(&b, NULL);
374 cipher = buffer_get_string(&b, NULL);
375 i2 = buffer_get_int(&b);
376 i3 = buffer_get_int(&b);
377 i4 = buffer_get_int(&b);
378 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
379 if (strcmp(cipher, "none") != 0) {
380 error("unsupported cipher %s", cipher);
381 xfree(cipher);
382 buffer_free(&b);
383 xfree(type);
384 return NULL;
386 xfree(cipher);
388 if (strstr(type, "dsa")) {
389 ktype = KEY_DSA;
390 } else if (strstr(type, "rsa")) {
391 ktype = KEY_RSA;
392 } else {
393 buffer_free(&b);
394 xfree(type);
395 return NULL;
397 key = key_new_private(ktype);
398 xfree(type);
400 switch (key->type) {
401 case KEY_DSA:
402 buffer_get_bignum_bits(&b, key->dsa->p);
403 buffer_get_bignum_bits(&b, key->dsa->g);
404 buffer_get_bignum_bits(&b, key->dsa->q);
405 buffer_get_bignum_bits(&b, key->dsa->pub_key);
406 buffer_get_bignum_bits(&b, key->dsa->priv_key);
407 break;
408 case KEY_RSA:
409 e = buffer_get_char(&b);
410 debug("e %lx", e);
411 if (e < 30) {
412 e <<= 8;
413 e += buffer_get_char(&b);
414 debug("e %lx", e);
415 e <<= 8;
416 e += buffer_get_char(&b);
417 debug("e %lx", e);
419 if (!BN_set_word(key->rsa->e, e)) {
420 buffer_free(&b);
421 key_free(key);
422 return NULL;
424 buffer_get_bignum_bits(&b, key->rsa->d);
425 buffer_get_bignum_bits(&b, key->rsa->n);
426 buffer_get_bignum_bits(&b, key->rsa->iqmp);
427 buffer_get_bignum_bits(&b, key->rsa->q);
428 buffer_get_bignum_bits(&b, key->rsa->p);
429 rsa_generate_additional_parameters(key->rsa);
430 break;
432 rlen = buffer_len(&b);
433 if (rlen != 0)
434 error("do_convert_private_ssh2_from_blob: "
435 "remaining bytes in key blob %d", rlen);
436 buffer_free(&b);
438 /* try the key */
439 key_sign(key, &sig, &slen, data, sizeof(data));
440 key_verify(key, sig, slen, data, sizeof(data));
441 xfree(sig);
442 return key;
445 static int
446 get_line(FILE *fp, char *line, size_t len)
448 int c;
449 size_t pos = 0;
451 line[0] = '\0';
452 while ((c = fgetc(fp)) != EOF) {
453 if (pos >= len - 1) {
454 fprintf(stderr, "input line too long.\n");
455 exit(1);
457 switch (c) {
458 case '\r':
459 c = fgetc(fp);
460 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) {
461 fprintf(stderr, "unget: %s\n", strerror(errno));
462 exit(1);
464 return pos;
465 case '\n':
466 return pos;
468 line[pos++] = c;
469 line[pos] = '\0';
471 /* We reached EOF */
472 return -1;
475 static void
476 do_convert_from_ssh2(struct passwd *pw, Key **k, int *private)
478 int blen;
479 u_int len;
480 char line[1024];
481 u_char blob[8096];
482 char encoded[8096];
483 int escaped = 0;
484 FILE *fp;
486 if ((fp = fopen(identity_file, "r")) == NULL)
487 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
488 encoded[0] = '\0';
489 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
490 if (line[blen - 1] == '\\')
491 escaped++;
492 if (strncmp(line, "----", 4) == 0 ||
493 strstr(line, ": ") != NULL) {
494 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
495 *private = 1;
496 if (strstr(line, " END ") != NULL) {
497 break;
499 /* fprintf(stderr, "ignore: %s", line); */
500 continue;
502 if (escaped) {
503 escaped--;
504 /* fprintf(stderr, "escaped: %s", line); */
505 continue;
507 strlcat(encoded, line, sizeof(encoded));
509 len = strlen(encoded);
510 if (((len % 4) == 3) &&
511 (encoded[len-1] == '=') &&
512 (encoded[len-2] == '=') &&
513 (encoded[len-3] == '='))
514 encoded[len-3] = '\0';
515 blen = uudecode(encoded, blob, sizeof(blob));
516 if (blen < 0) {
517 fprintf(stderr, "uudecode failed.\n");
518 exit(1);
520 *k = *private ?
521 do_convert_private_ssh2_from_blob(blob, blen) :
522 key_from_blob(blob, blen);
523 if (*k == NULL) {
524 fprintf(stderr, "decode blob failed.\n");
525 exit(1);
527 fclose(fp);
530 static void
531 do_convert_from_pkcs8(Key **k, int *private)
533 EVP_PKEY *pubkey;
534 FILE *fp;
536 if ((fp = fopen(identity_file, "r")) == NULL)
537 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
538 if ((pubkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL)) == NULL) {
539 fatal("%s: %s is not a recognised public key format", __func__,
540 identity_file);
542 fclose(fp);
543 switch (EVP_PKEY_type(pubkey->type)) {
544 case EVP_PKEY_RSA:
545 *k = key_new(KEY_UNSPEC);
546 (*k)->type = KEY_RSA;
547 (*k)->rsa = EVP_PKEY_get1_RSA(pubkey);
548 break;
549 case EVP_PKEY_DSA:
550 *k = key_new(KEY_UNSPEC);
551 (*k)->type = KEY_DSA;
552 (*k)->dsa = EVP_PKEY_get1_DSA(pubkey);
553 break;
554 #ifdef OPENSSL_HAS_ECC
555 case EVP_PKEY_EC:
556 *k = key_new(KEY_UNSPEC);
557 (*k)->type = KEY_ECDSA;
558 (*k)->ecdsa = EVP_PKEY_get1_EC_KEY(pubkey);
559 (*k)->ecdsa_nid = key_ecdsa_key_to_nid((*k)->ecdsa);
560 break;
561 #endif
562 default:
563 fatal("%s: unsupported pubkey type %d", __func__,
564 EVP_PKEY_type(pubkey->type));
566 EVP_PKEY_free(pubkey);
567 return;
570 static void
571 do_convert_from_pem(Key **k, int *private)
573 FILE *fp;
574 RSA *rsa;
575 #ifdef notyet
576 DSA *dsa;
577 #endif
579 if ((fp = fopen(identity_file, "r")) == NULL)
580 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
581 if ((rsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
582 *k = key_new(KEY_UNSPEC);
583 (*k)->type = KEY_RSA;
584 (*k)->rsa = rsa;
585 fclose(fp);
586 return;
588 #if notyet /* OpenSSH 0.9.8 lacks this function */
589 rewind(fp);
590 if ((dsa = PEM_read_DSAPublicKey(fp, NULL, NULL, NULL)) != NULL) {
591 *k = key_new(KEY_UNSPEC);
592 (*k)->type = KEY_DSA;
593 (*k)->dsa = dsa;
594 fclose(fp);
595 return;
597 /* XXX ECDSA */
598 #endif
599 fatal("%s: unrecognised raw private key format", __func__);
602 static void
603 do_convert_from(struct passwd *pw)
605 Key *k = NULL;
606 int private = 0, ok = 0;
607 struct stat st;
609 if (!have_identity)
610 ask_filename(pw, "Enter file in which the key is");
611 if (stat(identity_file, &st) < 0)
612 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
614 switch (convert_format) {
615 case FMT_RFC4716:
616 do_convert_from_ssh2(pw, &k, &private);
617 break;
618 case FMT_PKCS8:
619 do_convert_from_pkcs8(&k, &private);
620 break;
621 case FMT_PEM:
622 do_convert_from_pem(&k, &private);
623 break;
624 default:
625 fatal("%s: unknown key format %d", __func__, convert_format);
628 if (!private)
629 ok = key_write(k, stdout);
630 if (ok)
631 fprintf(stdout, "\n");
632 else {
633 switch (k->type) {
634 case KEY_DSA:
635 ok = PEM_write_DSAPrivateKey(stdout, k->dsa, NULL,
636 NULL, 0, NULL, NULL);
637 break;
638 #ifdef OPENSSL_HAS_ECC
639 case KEY_ECDSA:
640 ok = PEM_write_ECPrivateKey(stdout, k->ecdsa, NULL,
641 NULL, 0, NULL, NULL);
642 break;
643 #endif
644 case KEY_RSA:
645 ok = PEM_write_RSAPrivateKey(stdout, k->rsa, NULL,
646 NULL, 0, NULL, NULL);
647 break;
648 default:
649 fatal("%s: unsupported key type %s", __func__,
650 key_type(k));
654 if (!ok) {
655 fprintf(stderr, "key write failed\n");
656 exit(1);
658 key_free(k);
659 exit(0);
662 static void
663 do_print_public(struct passwd *pw)
665 Key *prv;
666 struct stat st;
668 if (!have_identity)
669 ask_filename(pw, "Enter file in which the key is");
670 if (stat(identity_file, &st) < 0) {
671 perror(identity_file);
672 exit(1);
674 prv = load_identity(identity_file);
675 if (prv == NULL) {
676 fprintf(stderr, "load failed\n");
677 exit(1);
679 if (!key_write(prv, stdout))
680 fprintf(stderr, "key_write failed");
681 key_free(prv);
682 fprintf(stdout, "\n");
683 exit(0);
686 static void
687 do_download(struct passwd *pw)
689 #ifdef ENABLE_PKCS11
690 Key **keys = NULL;
691 int i, nkeys;
693 pkcs11_init(0);
694 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
695 if (nkeys <= 0)
696 fatal("cannot read public key from pkcs11");
697 for (i = 0; i < nkeys; i++) {
698 key_write(keys[i], stdout);
699 key_free(keys[i]);
700 fprintf(stdout, "\n");
702 xfree(keys);
703 pkcs11_terminate();
704 exit(0);
705 #else
706 fatal("no pkcs11 support");
707 #endif /* ENABLE_PKCS11 */
710 static void
711 do_fingerprint(struct passwd *pw)
713 FILE *f;
714 Key *public;
715 char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra;
716 int i, skip = 0, num = 0, invalid = 1;
717 enum fp_rep rep;
718 enum fp_type fptype;
719 struct stat st;
721 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
722 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
724 if (!have_identity)
725 ask_filename(pw, "Enter file in which the key is");
726 if (stat(identity_file, &st) < 0) {
727 perror(identity_file);
728 exit(1);
730 public = key_load_public(identity_file, &comment);
731 if (public != NULL) {
732 fp = key_fingerprint(public, fptype, rep);
733 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
734 printf("%u %s %s (%s)\n", key_size(public), fp, comment,
735 key_type(public));
736 if (log_level >= SYSLOG_LEVEL_VERBOSE)
737 printf("%s\n", ra);
738 key_free(public);
739 xfree(comment);
740 xfree(ra);
741 xfree(fp);
742 exit(0);
744 if (comment) {
745 xfree(comment);
746 comment = NULL;
749 if ((f = fopen(identity_file, "r")) == NULL)
750 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
752 while (fgets(line, sizeof(line), f)) {
753 if ((cp = strchr(line, '\n')) == NULL) {
754 error("line %d too long: %.40s...",
755 num + 1, line);
756 skip = 1;
757 continue;
759 num++;
760 if (skip) {
761 skip = 0;
762 continue;
764 *cp = '\0';
766 /* Skip leading whitespace, empty and comment lines. */
767 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
769 if (!*cp || *cp == '\n' || *cp == '#')
770 continue;
771 i = strtol(cp, &ep, 10);
772 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
773 int quoted = 0;
774 comment = cp;
775 for (; *cp && (quoted || (*cp != ' ' &&
776 *cp != '\t')); cp++) {
777 if (*cp == '\\' && cp[1] == '"')
778 cp++; /* Skip both */
779 else if (*cp == '"')
780 quoted = !quoted;
782 if (!*cp)
783 continue;
784 *cp++ = '\0';
786 ep = cp;
787 public = key_new(KEY_RSA1);
788 if (key_read(public, &cp) != 1) {
789 cp = ep;
790 key_free(public);
791 public = key_new(KEY_UNSPEC);
792 if (key_read(public, &cp) != 1) {
793 key_free(public);
794 continue;
797 comment = *cp ? cp : comment;
798 fp = key_fingerprint(public, fptype, rep);
799 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
800 printf("%u %s %s (%s)\n", key_size(public), fp,
801 comment ? comment : "no comment", key_type(public));
802 if (log_level >= SYSLOG_LEVEL_VERBOSE)
803 printf("%s\n", ra);
804 xfree(ra);
805 xfree(fp);
806 key_free(public);
807 invalid = 0;
809 fclose(f);
811 if (invalid) {
812 printf("%s is not a public key file.\n", identity_file);
813 exit(1);
815 exit(0);
818 static void
819 printhost(FILE *f, const char *name, Key *public, int ca, int hash)
821 if (print_fingerprint) {
822 enum fp_rep rep;
823 enum fp_type fptype;
824 char *fp, *ra;
826 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
827 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
828 fp = key_fingerprint(public, fptype, rep);
829 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
830 printf("%u %s %s (%s)\n", key_size(public), fp, name,
831 key_type(public));
832 if (log_level >= SYSLOG_LEVEL_VERBOSE)
833 printf("%s\n", ra);
834 xfree(ra);
835 xfree(fp);
836 } else {
837 if (hash && (name = host_hash(name, NULL, 0)) == NULL)
838 fatal("hash_host failed");
839 fprintf(f, "%s%s%s ", ca ? CA_MARKER : "", ca ? " " : "", name);
840 if (!key_write(public, f))
841 fatal("key_write failed");
842 fprintf(f, "\n");
846 static void
847 do_known_hosts(struct passwd *pw, const char *name)
849 FILE *in, *out = stdout;
850 Key *pub;
851 char *cp, *cp2, *kp, *kp2;
852 char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN];
853 int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0;
854 int ca;
856 if (!have_identity) {
857 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
858 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
859 sizeof(identity_file))
860 fatal("Specified known hosts path too long");
861 xfree(cp);
862 have_identity = 1;
864 if ((in = fopen(identity_file, "r")) == NULL)
865 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
868 * Find hosts goes to stdout, hash and deletions happen in-place
869 * A corner case is ssh-keygen -HF foo, which should go to stdout
871 if (!find_host && (hash_hosts || delete_host)) {
872 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
873 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
874 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
875 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
876 fatal("known_hosts path too long");
877 umask(077);
878 if ((c = mkstemp(tmp)) == -1)
879 fatal("mkstemp: %s", strerror(errno));
880 if ((out = fdopen(c, "w")) == NULL) {
881 c = errno;
882 unlink(tmp);
883 fatal("fdopen: %s", strerror(c));
885 inplace = 1;
888 while (fgets(line, sizeof(line), in)) {
889 if ((cp = strchr(line, '\n')) == NULL) {
890 error("line %d too long: %.40s...", num + 1, line);
891 skip = 1;
892 invalid = 1;
893 continue;
895 num++;
896 if (skip) {
897 skip = 0;
898 continue;
900 *cp = '\0';
902 /* Skip leading whitespace, empty and comment lines. */
903 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
905 if (!*cp || *cp == '\n' || *cp == '#') {
906 if (inplace)
907 fprintf(out, "%s\n", cp);
908 continue;
910 /* Check whether this is a CA key */
911 if (strncasecmp(cp, CA_MARKER, sizeof(CA_MARKER) - 1) == 0 &&
912 (cp[sizeof(CA_MARKER) - 1] == ' ' ||
913 cp[sizeof(CA_MARKER) - 1] == '\t')) {
914 ca = 1;
915 cp += sizeof(CA_MARKER);
916 } else
917 ca = 0;
919 /* Find the end of the host name portion. */
920 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++)
923 if (*kp == '\0' || *(kp + 1) == '\0') {
924 error("line %d missing key: %.40s...",
925 num, line);
926 invalid = 1;
927 continue;
929 *kp++ = '\0';
930 kp2 = kp;
932 pub = key_new(KEY_RSA1);
933 if (key_read(pub, &kp) != 1) {
934 kp = kp2;
935 key_free(pub);
936 pub = key_new(KEY_UNSPEC);
937 if (key_read(pub, &kp) != 1) {
938 error("line %d invalid key: %.40s...",
939 num, line);
940 key_free(pub);
941 invalid = 1;
942 continue;
946 if (*cp == HASH_DELIM) {
947 if (find_host || delete_host) {
948 cp2 = host_hash(name, cp, strlen(cp));
949 if (cp2 == NULL) {
950 error("line %d: invalid hashed "
951 "name: %.64s...", num, line);
952 invalid = 1;
953 continue;
955 c = (strcmp(cp2, cp) == 0);
956 if (find_host && c) {
957 printf("# Host %s found: "
958 "line %d type %s%s\n", name,
959 num, key_type(pub),
960 ca ? " (CA key)" : "");
961 printhost(out, cp, pub, ca, 0);
963 if (delete_host && !c && !ca)
964 printhost(out, cp, pub, ca, 0);
965 } else if (hash_hosts)
966 printhost(out, cp, pub, ca, 0);
967 } else {
968 if (find_host || delete_host) {
969 c = (match_hostname(name, cp,
970 strlen(cp)) == 1);
971 if (find_host && c) {
972 printf("# Host %s found: "
973 "line %d type %s%s\n", name,
974 num, key_type(pub),
975 ca ? " (CA key)" : "");
976 printhost(out, name, pub,
977 ca, hash_hosts && !ca);
979 if (delete_host && !c && !ca)
980 printhost(out, cp, pub, ca, 0);
981 } else if (hash_hosts) {
982 for (cp2 = strsep(&cp, ",");
983 cp2 != NULL && *cp2 != '\0';
984 cp2 = strsep(&cp, ",")) {
985 if (ca) {
986 fprintf(stderr, "Warning: "
987 "ignoring CA key for host: "
988 "%.64s\n", cp2);
989 printhost(out, cp2, pub, ca, 0);
990 } else if (strcspn(cp2, "*?!") !=
991 strlen(cp2)) {
992 fprintf(stderr, "Warning: "
993 "ignoring host name with "
994 "metacharacters: %.64s\n",
995 cp2);
996 printhost(out, cp2, pub, ca, 0);
997 } else
998 printhost(out, cp2, pub, ca, 1);
1000 has_unhashed = 1;
1003 key_free(pub);
1005 fclose(in);
1007 if (invalid) {
1008 fprintf(stderr, "%s is not a valid known_hosts file.\n",
1009 identity_file);
1010 if (inplace) {
1011 fprintf(stderr, "Not replacing existing known_hosts "
1012 "file because of errors\n");
1013 fclose(out);
1014 unlink(tmp);
1016 exit(1);
1019 if (inplace) {
1020 fclose(out);
1022 /* Backup existing file */
1023 if (unlink(old) == -1 && errno != ENOENT)
1024 fatal("unlink %.100s: %s", old, strerror(errno));
1025 if (link(identity_file, old) == -1)
1026 fatal("link %.100s to %.100s: %s", identity_file, old,
1027 strerror(errno));
1028 /* Move new one into place */
1029 if (rename(tmp, identity_file) == -1) {
1030 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
1031 strerror(errno));
1032 unlink(tmp);
1033 unlink(old);
1034 exit(1);
1037 fprintf(stderr, "%s updated.\n", identity_file);
1038 fprintf(stderr, "Original contents retained as %s\n", old);
1039 if (has_unhashed) {
1040 fprintf(stderr, "WARNING: %s contains unhashed "
1041 "entries\n", old);
1042 fprintf(stderr, "Delete this file to ensure privacy "
1043 "of hostnames\n");
1047 exit(0);
1051 * Perform changing a passphrase. The argument is the passwd structure
1052 * for the current user.
1054 static void
1055 do_change_passphrase(struct passwd *pw)
1057 char *comment;
1058 char *old_passphrase, *passphrase1, *passphrase2;
1059 struct stat st;
1060 Key *private;
1062 if (!have_identity)
1063 ask_filename(pw, "Enter file in which the key is");
1064 if (stat(identity_file, &st) < 0) {
1065 perror(identity_file);
1066 exit(1);
1068 /* Try to load the file with empty passphrase. */
1069 private = key_load_private(identity_file, "", &comment);
1070 if (private == NULL) {
1071 if (identity_passphrase)
1072 old_passphrase = xstrdup(identity_passphrase);
1073 else
1074 old_passphrase =
1075 read_passphrase("Enter old passphrase: ",
1076 RP_ALLOW_STDIN);
1077 private = key_load_private(identity_file, old_passphrase,
1078 &comment);
1079 memset(old_passphrase, 0, strlen(old_passphrase));
1080 xfree(old_passphrase);
1081 if (private == NULL) {
1082 printf("Bad passphrase.\n");
1083 exit(1);
1086 printf("Key has comment '%s'\n", comment);
1088 /* Ask the new passphrase (twice). */
1089 if (identity_new_passphrase) {
1090 passphrase1 = xstrdup(identity_new_passphrase);
1091 passphrase2 = NULL;
1092 } else {
1093 passphrase1 =
1094 read_passphrase("Enter new passphrase (empty for no "
1095 "passphrase): ", RP_ALLOW_STDIN);
1096 passphrase2 = read_passphrase("Enter same passphrase again: ",
1097 RP_ALLOW_STDIN);
1099 /* Verify that they are the same. */
1100 if (strcmp(passphrase1, passphrase2) != 0) {
1101 memset(passphrase1, 0, strlen(passphrase1));
1102 memset(passphrase2, 0, strlen(passphrase2));
1103 xfree(passphrase1);
1104 xfree(passphrase2);
1105 printf("Pass phrases do not match. Try again.\n");
1106 exit(1);
1108 /* Destroy the other copy. */
1109 memset(passphrase2, 0, strlen(passphrase2));
1110 xfree(passphrase2);
1113 /* Save the file using the new passphrase. */
1114 if (!key_save_private(private, identity_file, passphrase1, comment)) {
1115 printf("Saving the key failed: %s.\n", identity_file);
1116 memset(passphrase1, 0, strlen(passphrase1));
1117 xfree(passphrase1);
1118 key_free(private);
1119 xfree(comment);
1120 exit(1);
1122 /* Destroy the passphrase and the copy of the key in memory. */
1123 memset(passphrase1, 0, strlen(passphrase1));
1124 xfree(passphrase1);
1125 key_free(private); /* Destroys contents */
1126 xfree(comment);
1128 printf("Your identification has been saved with the new passphrase.\n");
1129 exit(0);
1133 * Print the SSHFP RR.
1135 static int
1136 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
1138 Key *public;
1139 char *comment = NULL;
1140 struct stat st;
1142 if (fname == NULL)
1143 ask_filename(pw, "Enter file in which the key is");
1144 if (stat(fname, &st) < 0) {
1145 if (errno == ENOENT)
1146 return 0;
1147 perror(fname);
1148 exit(1);
1150 public = key_load_public(fname, &comment);
1151 if (public != NULL) {
1152 export_dns_rr(hname, public, stdout, print_generic);
1153 key_free(public);
1154 xfree(comment);
1155 return 1;
1157 if (comment)
1158 xfree(comment);
1160 printf("failed to read v2 public key from %s.\n", fname);
1161 exit(1);
1165 * Change the comment of a private key file.
1167 static void
1168 do_change_comment(struct passwd *pw)
1170 char new_comment[1024], *comment, *passphrase;
1171 Key *private;
1172 Key *public;
1173 struct stat st;
1174 FILE *f;
1175 int fd;
1177 if (!have_identity)
1178 ask_filename(pw, "Enter file in which the key is");
1179 if (stat(identity_file, &st) < 0) {
1180 perror(identity_file);
1181 exit(1);
1183 private = key_load_private(identity_file, "", &comment);
1184 if (private == NULL) {
1185 if (identity_passphrase)
1186 passphrase = xstrdup(identity_passphrase);
1187 else if (identity_new_passphrase)
1188 passphrase = xstrdup(identity_new_passphrase);
1189 else
1190 passphrase = read_passphrase("Enter passphrase: ",
1191 RP_ALLOW_STDIN);
1192 /* Try to load using the passphrase. */
1193 private = key_load_private(identity_file, passphrase, &comment);
1194 if (private == NULL) {
1195 memset(passphrase, 0, strlen(passphrase));
1196 xfree(passphrase);
1197 printf("Bad passphrase.\n");
1198 exit(1);
1200 } else {
1201 passphrase = xstrdup("");
1203 if (private->type != KEY_RSA1) {
1204 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
1205 key_free(private);
1206 exit(1);
1208 printf("Key now has comment '%s'\n", comment);
1210 if (identity_comment) {
1211 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1212 } else {
1213 printf("Enter new comment: ");
1214 fflush(stdout);
1215 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1216 memset(passphrase, 0, strlen(passphrase));
1217 key_free(private);
1218 exit(1);
1220 new_comment[strcspn(new_comment, "\n")] = '\0';
1223 /* Save the file using the new passphrase. */
1224 if (!key_save_private(private, identity_file, passphrase, new_comment)) {
1225 printf("Saving the key failed: %s.\n", identity_file);
1226 memset(passphrase, 0, strlen(passphrase));
1227 xfree(passphrase);
1228 key_free(private);
1229 xfree(comment);
1230 exit(1);
1232 memset(passphrase, 0, strlen(passphrase));
1233 xfree(passphrase);
1234 public = key_from_private(private);
1235 key_free(private);
1237 strlcat(identity_file, ".pub", sizeof(identity_file));
1238 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1239 if (fd == -1) {
1240 printf("Could not save your public key in %s\n", identity_file);
1241 exit(1);
1243 f = fdopen(fd, "w");
1244 if (f == NULL) {
1245 printf("fdopen %s failed\n", identity_file);
1246 exit(1);
1248 if (!key_write(public, f))
1249 fprintf(stderr, "write key failed\n");
1250 key_free(public);
1251 fprintf(f, " %s\n", new_comment);
1252 fclose(f);
1254 xfree(comment);
1256 printf("The comment in your key file has been changed.\n");
1257 exit(0);
1260 static const char *
1261 fmt_validity(u_int64_t valid_from, u_int64_t valid_to)
1263 char from[32], to[32];
1264 static char ret[64];
1265 time_t tt;
1266 struct tm *tm;
1268 *from = *to = '\0';
1269 if (valid_from == 0 && valid_to == 0xffffffffffffffffULL)
1270 return "forever";
1272 if (valid_from != 0) {
1273 /* XXX revisit INT_MAX in 2038 :) */
1274 tt = valid_from > INT_MAX ? INT_MAX : valid_from;
1275 tm = localtime(&tt);
1276 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
1278 if (valid_to != 0xffffffffffffffffULL) {
1279 /* XXX revisit INT_MAX in 2038 :) */
1280 tt = valid_to > INT_MAX ? INT_MAX : valid_to;
1281 tm = localtime(&tt);
1282 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
1285 if (valid_from == 0) {
1286 snprintf(ret, sizeof(ret), "before %s", to);
1287 return ret;
1289 if (valid_to == 0xffffffffffffffffULL) {
1290 snprintf(ret, sizeof(ret), "after %s", from);
1291 return ret;
1294 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
1295 return ret;
1298 static void
1299 add_flag_option(Buffer *c, const char *name)
1301 debug3("%s: %s", __func__, name);
1302 buffer_put_cstring(c, name);
1303 buffer_put_string(c, NULL, 0);
1306 static void
1307 add_string_option(Buffer *c, const char *name, const char *value)
1309 Buffer b;
1311 debug3("%s: %s=%s", __func__, name, value);
1312 buffer_init(&b);
1313 buffer_put_cstring(&b, value);
1315 buffer_put_cstring(c, name);
1316 buffer_put_string(c, buffer_ptr(&b), buffer_len(&b));
1318 buffer_free(&b);
1321 #define OPTIONS_CRITICAL 1
1322 #define OPTIONS_EXTENSIONS 2
1323 static void
1324 prepare_options_buf(Buffer *c, int which)
1326 buffer_clear(c);
1327 if ((which & OPTIONS_CRITICAL) != 0 &&
1328 certflags_command != NULL)
1329 add_string_option(c, "force-command", certflags_command);
1330 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1331 (certflags_flags & CERTOPT_AGENT_FWD) != 0)
1332 add_flag_option(c, "permit-agent-forwarding");
1333 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1334 (certflags_flags & CERTOPT_PORT_FWD) != 0)
1335 add_flag_option(c, "permit-port-forwarding");
1336 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1337 (certflags_flags & CERTOPT_PTY) != 0)
1338 add_flag_option(c, "permit-pty");
1339 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1340 (certflags_flags & CERTOPT_USER_RC) != 0)
1341 add_flag_option(c, "permit-user-rc");
1342 if ((which & OPTIONS_EXTENSIONS) != 0 &&
1343 (certflags_flags & CERTOPT_X_FWD) != 0)
1344 add_flag_option(c, "permit-X11-forwarding");
1345 if ((which & OPTIONS_CRITICAL) != 0 &&
1346 certflags_src_addr != NULL)
1347 add_string_option(c, "source-address", certflags_src_addr);
1350 static Key *
1351 load_pkcs11_key(char *path)
1353 #ifdef ENABLE_PKCS11
1354 Key **keys = NULL, *public, *private = NULL;
1355 int i, nkeys;
1357 if ((public = key_load_public(path, NULL)) == NULL)
1358 fatal("Couldn't load CA public key \"%s\"", path);
1360 nkeys = pkcs11_add_provider(pkcs11provider, identity_passphrase, &keys);
1361 debug3("%s: %d keys", __func__, nkeys);
1362 if (nkeys <= 0)
1363 fatal("cannot read public key from pkcs11");
1364 for (i = 0; i < nkeys; i++) {
1365 if (key_equal_public(public, keys[i])) {
1366 private = keys[i];
1367 continue;
1369 key_free(keys[i]);
1371 xfree(keys);
1372 key_free(public);
1373 return private;
1374 #else
1375 fatal("no pkcs11 support");
1376 #endif /* ENABLE_PKCS11 */
1379 static void
1380 do_ca_sign(struct passwd *pw, int argc, char **argv)
1382 int i, fd;
1383 u_int n;
1384 Key *ca, *public;
1385 char *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1386 FILE *f;
1387 int v00 = 0; /* legacy keys */
1389 if (key_type_name != NULL) {
1390 switch (key_type_from_name(key_type_name)) {
1391 case KEY_RSA_CERT_V00:
1392 case KEY_DSA_CERT_V00:
1393 v00 = 1;
1394 break;
1395 case KEY_UNSPEC:
1396 if (strcasecmp(key_type_name, "v00") == 0) {
1397 v00 = 1;
1398 break;
1399 } else if (strcasecmp(key_type_name, "v01") == 0)
1400 break;
1401 /* FALLTHROUGH */
1402 default:
1403 fprintf(stderr, "unknown key type %s\n", key_type_name);
1404 exit(1);
1408 pkcs11_init(1);
1409 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1410 if (pkcs11provider != NULL) {
1411 if ((ca = load_pkcs11_key(tmp)) == NULL)
1412 fatal("No PKCS#11 key matching %s found", ca_key_path);
1413 } else if ((ca = load_identity(tmp)) == NULL)
1414 fatal("Couldn't load CA key \"%s\"", tmp);
1415 xfree(tmp);
1417 for (i = 0; i < argc; i++) {
1418 /* Split list of principals */
1419 n = 0;
1420 if (cert_principals != NULL) {
1421 otmp = tmp = xstrdup(cert_principals);
1422 plist = NULL;
1423 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1424 plist = xrealloc(plist, n + 1, sizeof(*plist));
1425 if (*(plist[n] = xstrdup(cp)) == '\0')
1426 fatal("Empty principal name");
1428 xfree(otmp);
1431 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1432 if ((public = key_load_public(tmp, &comment)) == NULL)
1433 fatal("%s: unable to open \"%s\"", __func__, tmp);
1434 if (public->type != KEY_RSA && public->type != KEY_DSA &&
1435 public->type != KEY_ECDSA)
1436 fatal("%s: key \"%s\" type %s cannot be certified",
1437 __func__, tmp, key_type(public));
1439 /* Prepare certificate to sign */
1440 if (key_to_certified(public, v00) != 0)
1441 fatal("Could not upgrade key %s to certificate", tmp);
1442 public->cert->type = cert_key_type;
1443 public->cert->serial = (u_int64_t)cert_serial;
1444 public->cert->key_id = xstrdup(cert_key_id);
1445 public->cert->nprincipals = n;
1446 public->cert->principals = plist;
1447 public->cert->valid_after = cert_valid_from;
1448 public->cert->valid_before = cert_valid_to;
1449 if (v00) {
1450 prepare_options_buf(&public->cert->critical,
1451 OPTIONS_CRITICAL|OPTIONS_EXTENSIONS);
1452 } else {
1453 prepare_options_buf(&public->cert->critical,
1454 OPTIONS_CRITICAL);
1455 prepare_options_buf(&public->cert->extensions,
1456 OPTIONS_EXTENSIONS);
1458 public->cert->signature_key = key_from_private(ca);
1460 if (key_certify(public, ca) != 0)
1461 fatal("Couldn't not certify key %s", tmp);
1463 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1464 *cp = '\0';
1465 xasprintf(&out, "%s-cert.pub", tmp);
1466 xfree(tmp);
1468 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1469 fatal("Could not open \"%s\" for writing: %s", out,
1470 strerror(errno));
1471 if ((f = fdopen(fd, "w")) == NULL)
1472 fatal("%s: fdopen: %s", __func__, strerror(errno));
1473 if (!key_write(public, f))
1474 fatal("Could not write certified key to %s", out);
1475 fprintf(f, " %s\n", comment);
1476 fclose(f);
1478 if (!quiet) {
1479 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1480 "valid %s", key_cert_type(public),
1481 out, public->cert->key_id, public->cert->serial,
1482 cert_principals != NULL ? " for " : "",
1483 cert_principals != NULL ? cert_principals : "",
1484 fmt_validity(cert_valid_from, cert_valid_to));
1487 key_free(public);
1488 xfree(out);
1490 pkcs11_terminate();
1491 exit(0);
1494 static u_int64_t
1495 parse_relative_time(const char *s, time_t now)
1497 int64_t mul, secs;
1499 mul = *s == '-' ? -1 : 1;
1501 if ((secs = convtime(s + 1)) == -1)
1502 fatal("Invalid relative certificate time %s", s);
1503 if (mul == -1 && secs > now)
1504 fatal("Certificate time %s cannot be represented", s);
1505 return now + (u_int64_t)(secs * mul);
1508 static u_int64_t
1509 parse_absolute_time(const char *s)
1511 struct tm tm;
1512 time_t tt;
1513 char buf[32], *fmt;
1516 * POSIX strptime says "The application shall ensure that there
1517 * is white-space or other non-alphanumeric characters between
1518 * any two conversion specifications" so arrange things this way.
1520 switch (strlen(s)) {
1521 case 8:
1522 fmt = "%Y-%m-%d";
1523 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1524 break;
1525 case 14:
1526 fmt = "%Y-%m-%dT%H:%M:%S";
1527 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1528 s, s + 4, s + 6, s + 8, s + 10, s + 12);
1529 break;
1530 default:
1531 fatal("Invalid certificate time format %s", s);
1534 bzero(&tm, sizeof(tm));
1535 if (strptime(buf, fmt, &tm) == NULL)
1536 fatal("Invalid certificate time %s", s);
1537 if ((tt = mktime(&tm)) < 0)
1538 fatal("Certificate time %s cannot be represented", s);
1539 return (u_int64_t)tt;
1542 static void
1543 parse_cert_times(char *timespec)
1545 char *from, *to;
1546 time_t now = time(NULL);
1547 int64_t secs;
1549 /* +timespec relative to now */
1550 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1551 if ((secs = convtime(timespec + 1)) == -1)
1552 fatal("Invalid relative certificate life %s", timespec);
1553 cert_valid_to = now + secs;
1555 * Backdate certificate one minute to avoid problems on hosts
1556 * with poorly-synchronised clocks.
1558 cert_valid_from = ((now - 59)/ 60) * 60;
1559 return;
1563 * from:to, where
1564 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1565 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1567 from = xstrdup(timespec);
1568 to = strchr(from, ':');
1569 if (to == NULL || from == to || *(to + 1) == '\0')
1570 fatal("Invalid certificate life specification %s", timespec);
1571 *to++ = '\0';
1573 if (*from == '-' || *from == '+')
1574 cert_valid_from = parse_relative_time(from, now);
1575 else
1576 cert_valid_from = parse_absolute_time(from);
1578 if (*to == '-' || *to == '+')
1579 cert_valid_to = parse_relative_time(to, cert_valid_from);
1580 else
1581 cert_valid_to = parse_absolute_time(to);
1583 if (cert_valid_to <= cert_valid_from)
1584 fatal("Empty certificate validity interval");
1585 xfree(from);
1588 static void
1589 add_cert_option(char *opt)
1591 char *val;
1593 if (strcmp(opt, "clear") == 0)
1594 certflags_flags = 0;
1595 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1596 certflags_flags &= ~CERTOPT_X_FWD;
1597 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1598 certflags_flags |= CERTOPT_X_FWD;
1599 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1600 certflags_flags &= ~CERTOPT_AGENT_FWD;
1601 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1602 certflags_flags |= CERTOPT_AGENT_FWD;
1603 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1604 certflags_flags &= ~CERTOPT_PORT_FWD;
1605 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1606 certflags_flags |= CERTOPT_PORT_FWD;
1607 else if (strcasecmp(opt, "no-pty") == 0)
1608 certflags_flags &= ~CERTOPT_PTY;
1609 else if (strcasecmp(opt, "permit-pty") == 0)
1610 certflags_flags |= CERTOPT_PTY;
1611 else if (strcasecmp(opt, "no-user-rc") == 0)
1612 certflags_flags &= ~CERTOPT_USER_RC;
1613 else if (strcasecmp(opt, "permit-user-rc") == 0)
1614 certflags_flags |= CERTOPT_USER_RC;
1615 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1616 val = opt + 14;
1617 if (*val == '\0')
1618 fatal("Empty force-command option");
1619 if (certflags_command != NULL)
1620 fatal("force-command already specified");
1621 certflags_command = xstrdup(val);
1622 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1623 val = opt + 15;
1624 if (*val == '\0')
1625 fatal("Empty source-address option");
1626 if (certflags_src_addr != NULL)
1627 fatal("source-address already specified");
1628 if (addr_match_cidr_list(NULL, val) != 0)
1629 fatal("Invalid source-address list");
1630 certflags_src_addr = xstrdup(val);
1631 } else
1632 fatal("Unsupported certificate option \"%s\"", opt);
1635 static void
1636 show_options(const Buffer *optbuf, int v00, int in_critical)
1638 u_char *name, *data;
1639 u_int dlen;
1640 Buffer options, option;
1642 buffer_init(&options);
1643 buffer_append(&options, buffer_ptr(optbuf), buffer_len(optbuf));
1645 buffer_init(&option);
1646 while (buffer_len(&options) != 0) {
1647 name = buffer_get_string(&options, NULL);
1648 data = buffer_get_string_ptr(&options, &dlen);
1649 buffer_append(&option, data, dlen);
1650 printf(" %s", name);
1651 if ((v00 || !in_critical) &&
1652 (strcmp(name, "permit-X11-forwarding") == 0 ||
1653 strcmp(name, "permit-agent-forwarding") == 0 ||
1654 strcmp(name, "permit-port-forwarding") == 0 ||
1655 strcmp(name, "permit-pty") == 0 ||
1656 strcmp(name, "permit-user-rc") == 0))
1657 printf("\n");
1658 else if ((v00 || in_critical) &&
1659 (strcmp(name, "force-command") == 0 ||
1660 strcmp(name, "source-address") == 0)) {
1661 data = buffer_get_string(&option, NULL);
1662 printf(" %s\n", data);
1663 xfree(data);
1664 } else {
1665 printf(" UNKNOWN OPTION (len %u)\n",
1666 buffer_len(&option));
1667 buffer_clear(&option);
1669 xfree(name);
1670 if (buffer_len(&option) != 0)
1671 fatal("Option corrupt: extra data at end");
1673 buffer_free(&option);
1674 buffer_free(&options);
1677 static void
1678 do_show_cert(struct passwd *pw)
1680 Key *key;
1681 struct stat st;
1682 char *key_fp, *ca_fp;
1683 u_int i, v00;
1685 if (!have_identity)
1686 ask_filename(pw, "Enter file in which the key is");
1687 if (stat(identity_file, &st) < 0)
1688 fatal("%s: %s: %s", __progname, identity_file, strerror(errno));
1689 if ((key = key_load_public(identity_file, NULL)) == NULL)
1690 fatal("%s is not a public key", identity_file);
1691 if (!key_is_cert(key))
1692 fatal("%s is not a certificate", identity_file);
1693 v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1695 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1696 ca_fp = key_fingerprint(key->cert->signature_key,
1697 SSH_FP_MD5, SSH_FP_HEX);
1699 printf("%s:\n", identity_file);
1700 printf(" Type: %s %s certificate\n", key_ssh_name(key),
1701 key_cert_type(key));
1702 printf(" Public key: %s %s\n", key_type(key), key_fp);
1703 printf(" Signing CA: %s %s\n",
1704 key_type(key->cert->signature_key), ca_fp);
1705 printf(" Key ID: \"%s\"\n", key->cert->key_id);
1706 if (!v00)
1707 printf(" Serial: %llu\n", key->cert->serial);
1708 printf(" Valid: %s\n",
1709 fmt_validity(key->cert->valid_after, key->cert->valid_before));
1710 printf(" Principals: ");
1711 if (key->cert->nprincipals == 0)
1712 printf("(none)\n");
1713 else {
1714 for (i = 0; i < key->cert->nprincipals; i++)
1715 printf("\n %s",
1716 key->cert->principals[i]);
1717 printf("\n");
1719 printf(" Critical Options: ");
1720 if (buffer_len(&key->cert->critical) == 0)
1721 printf("(none)\n");
1722 else {
1723 printf("\n");
1724 show_options(&key->cert->critical, v00, 1);
1726 if (!v00) {
1727 printf(" Extensions: ");
1728 if (buffer_len(&key->cert->extensions) == 0)
1729 printf("(none)\n");
1730 else {
1731 printf("\n");
1732 show_options(&key->cert->extensions, v00, 0);
1735 exit(0);
1738 static void
1739 usage(void)
1741 fprintf(stderr, "usage: %s [options]\n", __progname);
1742 fprintf(stderr, "Options:\n");
1743 fprintf(stderr, " -a trials Number of trials for screening DH-GEX moduli.\n");
1744 fprintf(stderr, " -B Show bubblebabble digest of key file.\n");
1745 fprintf(stderr, " -b bits Number of bits in the key to create.\n");
1746 fprintf(stderr, " -C comment Provide new comment.\n");
1747 fprintf(stderr, " -c Change comment in private and public key files.\n");
1748 #ifdef ENABLE_PKCS11
1749 fprintf(stderr, " -D pkcs11 Download public key from pkcs11 token.\n");
1750 #endif
1751 fprintf(stderr, " -e Export OpenSSH to foreign format key file.\n");
1752 fprintf(stderr, " -F hostname Find hostname in known hosts file.\n");
1753 fprintf(stderr, " -f filename Filename of the key file.\n");
1754 fprintf(stderr, " -G file Generate candidates for DH-GEX moduli.\n");
1755 fprintf(stderr, " -g Use generic DNS resource record format.\n");
1756 fprintf(stderr, " -H Hash names in known_hosts file.\n");
1757 fprintf(stderr, " -h Generate host certificate instead of a user certificate.\n");
1758 fprintf(stderr, " -I key_id Key identifier to include in certificate.\n");
1759 fprintf(stderr, " -i Import foreign format to OpenSSH key file.\n");
1760 fprintf(stderr, " -L Print the contents of a certificate.\n");
1761 fprintf(stderr, " -l Show fingerprint of key file.\n");
1762 fprintf(stderr, " -M memory Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1763 fprintf(stderr, " -m key_fmt Conversion format for -e/-i (PEM|PKCS8|RFC4716).\n");
1764 fprintf(stderr, " -N phrase Provide new passphrase.\n");
1765 fprintf(stderr, " -n name,... User/host principal names to include in certificate\n");
1766 fprintf(stderr, " -O option Specify a certificate option.\n");
1767 fprintf(stderr, " -P phrase Provide old passphrase.\n");
1768 fprintf(stderr, " -p Change passphrase of private key file.\n");
1769 fprintf(stderr, " -q Quiet.\n");
1770 fprintf(stderr, " -R hostname Remove host from known_hosts file.\n");
1771 fprintf(stderr, " -r hostname Print DNS resource record.\n");
1772 fprintf(stderr, " -S start Start point (hex) for generating DH-GEX moduli.\n");
1773 fprintf(stderr, " -s ca_key Certify keys with CA key.\n");
1774 fprintf(stderr, " -T file Screen candidates for DH-GEX moduli.\n");
1775 fprintf(stderr, " -t type Specify type of key to create.\n");
1776 fprintf(stderr, " -V from:to Specify certificate validity interval.\n");
1777 fprintf(stderr, " -v Verbose.\n");
1778 fprintf(stderr, " -W gen Generator to use for generating DH-GEX moduli.\n");
1779 fprintf(stderr, " -y Read private key file and print public key.\n");
1780 fprintf(stderr, " -z serial Specify a serial number.\n");
1782 exit(1);
1786 * Main program for key management.
1789 main(int argc, char **argv)
1791 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1792 char out_file[MAXPATHLEN], *rr_hostname = NULL;
1793 Key *private, *public;
1794 struct passwd *pw;
1795 struct stat st;
1796 int opt, type, fd;
1797 u_int maxbits;
1798 u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1799 int do_gen_candidates = 0, do_screen_candidates = 0;
1800 BIGNUM *start = NULL;
1801 FILE *f;
1802 const char *errstr;
1804 extern int optind;
1805 extern char *optarg;
1807 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1808 sanitise_stdfd();
1810 __progname = ssh_get_progname(argv[0]);
1812 OpenSSL_add_all_algorithms();
1813 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1815 init_rng();
1816 seed_rng();
1818 /* we need this for the home * directory. */
1819 pw = getpwuid(getuid());
1820 if (!pw) {
1821 printf("You don't exist, go away!\n");
1822 exit(1);
1824 if (gethostname(hostname, sizeof(hostname)) < 0) {
1825 perror("gethostname");
1826 exit(1);
1829 while ((opt = getopt(argc, argv, "degiqpclBHLhvxXyF:b:f:t:D:I:P:m:N:n:"
1830 "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) {
1831 switch (opt) {
1832 case 'b':
1833 bits = (u_int32_t)strtonum(optarg, 256, 32768, &errstr);
1834 if (errstr)
1835 fatal("Bits has bad value %s (%s)",
1836 optarg, errstr);
1837 break;
1838 case 'F':
1839 find_host = 1;
1840 rr_hostname = optarg;
1841 break;
1842 case 'H':
1843 hash_hosts = 1;
1844 break;
1845 case 'I':
1846 cert_key_id = optarg;
1847 break;
1848 case 'R':
1849 delete_host = 1;
1850 rr_hostname = optarg;
1851 break;
1852 case 'L':
1853 show_cert = 1;
1854 break;
1855 case 'l':
1856 print_fingerprint = 1;
1857 break;
1858 case 'B':
1859 print_bubblebabble = 1;
1860 break;
1861 case 'm':
1862 if (strcasecmp(optarg, "RFC4716") == 0 ||
1863 strcasecmp(optarg, "ssh2") == 0) {
1864 convert_format = FMT_RFC4716;
1865 break;
1867 if (strcasecmp(optarg, "PKCS8") == 0) {
1868 convert_format = FMT_PKCS8;
1869 break;
1871 if (strcasecmp(optarg, "PEM") == 0) {
1872 convert_format = FMT_PEM;
1873 break;
1875 fatal("Unsupported conversion format \"%s\"", optarg);
1876 case 'n':
1877 cert_principals = optarg;
1878 break;
1879 case 'p':
1880 change_passphrase = 1;
1881 break;
1882 case 'c':
1883 change_comment = 1;
1884 break;
1885 case 'f':
1886 if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
1887 sizeof(identity_file))
1888 fatal("Identity filename too long");
1889 have_identity = 1;
1890 break;
1891 case 'g':
1892 print_generic = 1;
1893 break;
1894 case 'P':
1895 identity_passphrase = optarg;
1896 break;
1897 case 'N':
1898 identity_new_passphrase = optarg;
1899 break;
1900 case 'O':
1901 add_cert_option(optarg);
1902 break;
1903 case 'C':
1904 identity_comment = optarg;
1905 break;
1906 case 'q':
1907 quiet = 1;
1908 break;
1909 case 'e':
1910 case 'x':
1911 /* export key */
1912 convert_to = 1;
1913 break;
1914 case 'h':
1915 cert_key_type = SSH2_CERT_TYPE_HOST;
1916 certflags_flags = 0;
1917 break;
1918 case 'i':
1919 case 'X':
1920 /* import key */
1921 convert_from = 1;
1922 break;
1923 case 'y':
1924 print_public = 1;
1925 break;
1926 case 'd':
1927 key_type_name = "dsa";
1928 break;
1929 case 's':
1930 ca_key_path = optarg;
1931 break;
1932 case 't':
1933 key_type_name = optarg;
1934 break;
1935 case 'D':
1936 pkcs11provider = optarg;
1937 break;
1938 case 'v':
1939 if (log_level == SYSLOG_LEVEL_INFO)
1940 log_level = SYSLOG_LEVEL_DEBUG1;
1941 else {
1942 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1943 log_level < SYSLOG_LEVEL_DEBUG3)
1944 log_level++;
1946 break;
1947 case 'r':
1948 rr_hostname = optarg;
1949 break;
1950 case 'W':
1951 generator_wanted = (u_int32_t)strtonum(optarg, 1,
1952 UINT_MAX, &errstr);
1953 if (errstr)
1954 fatal("Desired generator has bad value: %s (%s)",
1955 optarg, errstr);
1956 break;
1957 case 'a':
1958 trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1959 if (errstr)
1960 fatal("Invalid number of trials: %s (%s)",
1961 optarg, errstr);
1962 break;
1963 case 'M':
1964 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1965 if (errstr)
1966 fatal("Memory limit is %s: %s", errstr, optarg);
1967 break;
1968 case 'G':
1969 do_gen_candidates = 1;
1970 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1971 sizeof(out_file))
1972 fatal("Output filename too long");
1973 break;
1974 case 'T':
1975 do_screen_candidates = 1;
1976 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1977 sizeof(out_file))
1978 fatal("Output filename too long");
1979 break;
1980 case 'S':
1981 /* XXX - also compare length against bits */
1982 if (BN_hex2bn(&start, optarg) == 0)
1983 fatal("Invalid start point.");
1984 break;
1985 case 'V':
1986 parse_cert_times(optarg);
1987 break;
1988 case 'z':
1989 cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr);
1990 if (errstr)
1991 fatal("Invalid serial number: %s", errstr);
1992 break;
1993 case '?':
1994 default:
1995 usage();
1999 /* reinit */
2000 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
2002 argv += optind;
2003 argc -= optind;
2005 if (ca_key_path != NULL) {
2006 if (argc < 1) {
2007 printf("Too few arguments.\n");
2008 usage();
2010 } else if (argc > 0) {
2011 printf("Too many arguments.\n");
2012 usage();
2014 if (change_passphrase && change_comment) {
2015 printf("Can only have one of -p and -c.\n");
2016 usage();
2018 if (print_fingerprint && (delete_host || hash_hosts)) {
2019 printf("Cannot use -l with -D or -R.\n");
2020 usage();
2022 if (ca_key_path != NULL) {
2023 if (cert_key_id == NULL)
2024 fatal("Must specify key id (-I) when certifying");
2025 do_ca_sign(pw, argc, argv);
2027 if (show_cert)
2028 do_show_cert(pw);
2029 if (delete_host || hash_hosts || find_host)
2030 do_known_hosts(pw, rr_hostname);
2031 if (print_fingerprint || print_bubblebabble)
2032 do_fingerprint(pw);
2033 if (change_passphrase)
2034 do_change_passphrase(pw);
2035 if (change_comment)
2036 do_change_comment(pw);
2037 if (convert_to)
2038 do_convert_to(pw);
2039 if (convert_from)
2040 do_convert_from(pw);
2041 if (print_public)
2042 do_print_public(pw);
2043 if (rr_hostname != NULL) {
2044 unsigned int n = 0;
2046 if (have_identity) {
2047 n = do_print_resource_record(pw,
2048 identity_file, rr_hostname);
2049 if (n == 0) {
2050 perror(identity_file);
2051 exit(1);
2053 exit(0);
2054 } else {
2056 n += do_print_resource_record(pw,
2057 _PATH_HOST_RSA_KEY_FILE, rr_hostname);
2058 n += do_print_resource_record(pw,
2059 _PATH_HOST_DSA_KEY_FILE, rr_hostname);
2061 if (n == 0)
2062 fatal("no keys found.");
2063 exit(0);
2066 if (pkcs11provider != NULL)
2067 do_download(pw);
2069 if (do_gen_candidates) {
2070 FILE *out = fopen(out_file, "w");
2072 if (out == NULL) {
2073 error("Couldn't open modulus candidate file \"%s\": %s",
2074 out_file, strerror(errno));
2075 return (1);
2077 if (bits == 0)
2078 bits = DEFAULT_BITS;
2079 if (gen_candidates(out, memory, bits, start) != 0)
2080 fatal("modulus candidate generation failed");
2082 return (0);
2085 if (do_screen_candidates) {
2086 FILE *in;
2087 FILE *out = fopen(out_file, "w");
2089 if (have_identity && strcmp(identity_file, "-") != 0) {
2090 if ((in = fopen(identity_file, "r")) == NULL) {
2091 fatal("Couldn't open modulus candidate "
2092 "file \"%s\": %s", identity_file,
2093 strerror(errno));
2095 } else
2096 in = stdin;
2098 if (out == NULL) {
2099 fatal("Couldn't open moduli file \"%s\": %s",
2100 out_file, strerror(errno));
2102 if (prime_test(in, out, trials, generator_wanted) != 0)
2103 fatal("modulus screening failed");
2104 return (0);
2107 arc4random_stir();
2109 if (key_type_name == NULL)
2110 key_type_name = "rsa";
2112 type = key_type_from_name(key_type_name);
2113 if (type == KEY_UNSPEC) {
2114 fprintf(stderr, "unknown key type %s\n", key_type_name);
2115 exit(1);
2117 if (bits == 0) {
2118 if (type == KEY_DSA)
2119 bits = DEFAULT_BITS_DSA;
2120 else if (type == KEY_ECDSA)
2121 bits = DEFAULT_BITS_ECDSA;
2122 else
2123 bits = DEFAULT_BITS;
2125 maxbits = (type == KEY_DSA) ?
2126 OPENSSL_DSA_MAX_MODULUS_BITS : OPENSSL_RSA_MAX_MODULUS_BITS;
2127 if (bits > maxbits) {
2128 fprintf(stderr, "key bits exceeds maximum %d\n", maxbits);
2129 exit(1);
2131 if (type == KEY_DSA && bits != 1024)
2132 fatal("DSA keys must be 1024 bits");
2133 else if (type != KEY_ECDSA && bits < 768)
2134 fatal("Key must at least be 768 bits");
2135 else if (type == KEY_ECDSA && key_ecdsa_bits_to_nid(bits) == -1)
2136 fatal("Invalid ECDSA key length - valid lengths are "
2137 "256, 384 or 521 bits");
2138 if (!quiet)
2139 printf("Generating public/private %s key pair.\n", key_type_name);
2140 private = key_generate(type, bits);
2141 if (private == NULL) {
2142 fprintf(stderr, "key_generate failed\n");
2143 exit(1);
2145 public = key_from_private(private);
2147 if (!have_identity)
2148 ask_filename(pw, "Enter file in which to save the key");
2150 /* Create ~/.ssh directory if it doesn't already exist. */
2151 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s",
2152 pw->pw_dir, _PATH_SSH_USER_DIR);
2153 if (strstr(identity_file, dotsshdir) != NULL) {
2154 if (stat(dotsshdir, &st) < 0) {
2155 if (errno != ENOENT) {
2156 error("Could not stat %s: %s", dotsshdir,
2157 strerror(errno));
2158 } else if (mkdir(dotsshdir, 0700) < 0) {
2159 error("Could not create directory '%s': %s",
2160 dotsshdir, strerror(errno));
2161 } else if (!quiet)
2162 printf("Created directory '%s'.\n", dotsshdir);
2165 /* If the file already exists, ask the user to confirm. */
2166 if (stat(identity_file, &st) >= 0) {
2167 char yesno[3];
2168 printf("%s already exists.\n", identity_file);
2169 printf("Overwrite (y/n)? ");
2170 fflush(stdout);
2171 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
2172 exit(1);
2173 if (yesno[0] != 'y' && yesno[0] != 'Y')
2174 exit(1);
2176 /* Ask for a passphrase (twice). */
2177 if (identity_passphrase)
2178 passphrase1 = xstrdup(identity_passphrase);
2179 else if (identity_new_passphrase)
2180 passphrase1 = xstrdup(identity_new_passphrase);
2181 else {
2182 passphrase_again:
2183 passphrase1 =
2184 read_passphrase("Enter passphrase (empty for no "
2185 "passphrase): ", RP_ALLOW_STDIN);
2186 passphrase2 = read_passphrase("Enter same passphrase again: ",
2187 RP_ALLOW_STDIN);
2188 if (strcmp(passphrase1, passphrase2) != 0) {
2190 * The passphrases do not match. Clear them and
2191 * retry.
2193 memset(passphrase1, 0, strlen(passphrase1));
2194 memset(passphrase2, 0, strlen(passphrase2));
2195 xfree(passphrase1);
2196 xfree(passphrase2);
2197 printf("Passphrases do not match. Try again.\n");
2198 goto passphrase_again;
2200 /* Clear the other copy of the passphrase. */
2201 memset(passphrase2, 0, strlen(passphrase2));
2202 xfree(passphrase2);
2205 if (identity_comment) {
2206 strlcpy(comment, identity_comment, sizeof(comment));
2207 } else {
2208 /* Create default comment field for the passphrase. */
2209 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
2212 /* Save the key with the given passphrase and comment. */
2213 if (!key_save_private(private, identity_file, passphrase1, comment)) {
2214 printf("Saving the key failed: %s.\n", identity_file);
2215 memset(passphrase1, 0, strlen(passphrase1));
2216 xfree(passphrase1);
2217 exit(1);
2219 /* Clear the passphrase. */
2220 memset(passphrase1, 0, strlen(passphrase1));
2221 xfree(passphrase1);
2223 /* Clear the private key and the random number generator. */
2224 key_free(private);
2225 arc4random_stir();
2227 if (!quiet)
2228 printf("Your identification has been saved in %s.\n", identity_file);
2230 strlcat(identity_file, ".pub", sizeof(identity_file));
2231 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
2232 if (fd == -1) {
2233 printf("Could not save your public key in %s\n", identity_file);
2234 exit(1);
2236 f = fdopen(fd, "w");
2237 if (f == NULL) {
2238 printf("fdopen %s failed\n", identity_file);
2239 exit(1);
2241 if (!key_write(public, f))
2242 fprintf(stderr, "write key failed\n");
2243 fprintf(f, " %s\n", comment);
2244 fclose(f);
2246 if (!quiet) {
2247 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
2248 char *ra = key_fingerprint(public, SSH_FP_MD5,
2249 SSH_FP_RANDOMART);
2250 printf("Your public key has been saved in %s.\n",
2251 identity_file);
2252 printf("The key fingerprint is:\n");
2253 printf("%s %s\n", fp, comment);
2254 printf("The key's randomart image is:\n");
2255 printf("%s\n", ra);
2256 xfree(ra);
2257 xfree(fp);
2260 key_free(public);
2261 exit(0);