- (dtucker) [contrib/aix/buildbff.sh] Fix creation of ssh_prng_cmds.default
[openssh-git.git] / ssh-keygen.c
blobf0ddd4cfc218b672a9e3be8e3aeeed73eebdaebf
1 /* $OpenBSD: ssh-keygen.c,v 1.187 2010/04/16 06:47:04 jmc 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 u_int32_t bits = 0;
63 * Flag indicating that we just want to change the passphrase. This can be
64 * set on the command line.
66 int change_passphrase = 0;
69 * Flag indicating that we just want to change the comment. This can be set
70 * on the command line.
72 int change_comment = 0;
74 int quiet = 0;
76 int log_level = SYSLOG_LEVEL_INFO;
78 /* Flag indicating that we want to hash a known_hosts file */
79 int hash_hosts = 0;
80 /* Flag indicating that we want lookup a host in known_hosts file */
81 int find_host = 0;
82 /* Flag indicating that we want to delete a host from a known_hosts file */
83 int delete_host = 0;
85 /* Flag indicating that we want to show the contents of a certificate */
86 int show_cert = 0;
88 /* Flag indicating that we just want to see the key fingerprint */
89 int print_fingerprint = 0;
90 int print_bubblebabble = 0;
92 /* The identity file name, given on the command line or entered by the user. */
93 char identity_file[1024];
94 int have_identity = 0;
96 /* This is set to the passphrase if given on the command line. */
97 char *identity_passphrase = NULL;
99 /* This is set to the new passphrase if given on the command line. */
100 char *identity_new_passphrase = NULL;
102 /* This is set to the new comment if given on the command line. */
103 char *identity_comment = NULL;
105 /* Path to CA key when certifying keys. */
106 char *ca_key_path = NULL;
108 /* Certificate serial number */
109 long long cert_serial = 0;
111 /* Key type when certifying */
112 u_int cert_key_type = SSH2_CERT_TYPE_USER;
114 /* "key ID" of signed key */
115 char *cert_key_id = NULL;
117 /* Comma-separated list of principal names for certifying keys */
118 char *cert_principals = NULL;
120 /* Validity period for certificates */
121 u_int64_t cert_valid_from = 0;
122 u_int64_t cert_valid_to = ~0ULL;
124 /* Certificate options */
125 #define CRITOPT_X_FWD (1)
126 #define CRITOPT_AGENT_FWD (1<<1)
127 #define CRITOPT_PORT_FWD (1<<2)
128 #define CRITOPT_PTY (1<<3)
129 #define CRITOPT_USER_RC (1<<4)
130 #define CRITOPT_DEFAULT (CRITOPT_X_FWD|CRITOPT_AGENT_FWD| \
131 CRITOPT_PORT_FWD|CRITOPT_PTY| \
132 CRITOPT_USER_RC)
133 u_int32_t critical_flags = CRITOPT_DEFAULT;
134 char *critical_command = NULL;
135 char *critical_src_addr = NULL;
137 /* Dump public key file in format used by real and the original SSH 2 */
138 int convert_to_ssh2 = 0;
139 int convert_from_ssh2 = 0;
140 int print_public = 0;
141 int print_generic = 0;
143 char *key_type_name = NULL;
145 /* argv0 */
146 extern char *__progname;
148 char hostname[MAXHOSTNAMELEN];
150 /* moduli.c */
151 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
152 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
154 static void
155 ask_filename(struct passwd *pw, const char *prompt)
157 char buf[1024];
158 char *name = NULL;
160 if (key_type_name == NULL)
161 name = _PATH_SSH_CLIENT_ID_RSA;
162 else {
163 switch (key_type_from_name(key_type_name)) {
164 case KEY_RSA1:
165 name = _PATH_SSH_CLIENT_IDENTITY;
166 break;
167 case KEY_DSA_CERT:
168 case KEY_DSA_CERT_V00:
169 case KEY_DSA:
170 name = _PATH_SSH_CLIENT_ID_DSA;
171 break;
172 case KEY_RSA_CERT:
173 case KEY_RSA_CERT_V00:
174 case KEY_RSA:
175 name = _PATH_SSH_CLIENT_ID_RSA;
176 break;
177 default:
178 fprintf(stderr, "bad key type\n");
179 exit(1);
180 break;
183 snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
184 fprintf(stderr, "%s (%s): ", prompt, identity_file);
185 if (fgets(buf, sizeof(buf), stdin) == NULL)
186 exit(1);
187 buf[strcspn(buf, "\n")] = '\0';
188 if (strcmp(buf, "") != 0)
189 strlcpy(identity_file, buf, sizeof(identity_file));
190 have_identity = 1;
193 static Key *
194 load_identity(char *filename)
196 char *pass;
197 Key *prv;
199 prv = key_load_private(filename, "", NULL);
200 if (prv == NULL) {
201 if (identity_passphrase)
202 pass = xstrdup(identity_passphrase);
203 else
204 pass = read_passphrase("Enter passphrase: ",
205 RP_ALLOW_STDIN);
206 prv = key_load_private(filename, pass, NULL);
207 memset(pass, 0, strlen(pass));
208 xfree(pass);
210 return prv;
213 #define SSH_COM_PUBLIC_BEGIN "---- BEGIN SSH2 PUBLIC KEY ----"
214 #define SSH_COM_PUBLIC_END "---- END SSH2 PUBLIC KEY ----"
215 #define SSH_COM_PRIVATE_BEGIN "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
216 #define SSH_COM_PRIVATE_KEY_MAGIC 0x3f6ff9eb
218 static void
219 do_convert_to_ssh2(struct passwd *pw)
221 Key *k;
222 u_int len;
223 u_char *blob;
224 char comment[61];
225 struct stat st;
227 if (!have_identity)
228 ask_filename(pw, "Enter file in which the key is");
229 if (stat(identity_file, &st) < 0) {
230 perror(identity_file);
231 exit(1);
233 if ((k = key_load_public(identity_file, NULL)) == NULL) {
234 if ((k = load_identity(identity_file)) == NULL) {
235 fprintf(stderr, "load failed\n");
236 exit(1);
239 if (k->type == KEY_RSA1) {
240 fprintf(stderr, "version 1 keys are not supported\n");
241 exit(1);
243 if (key_to_blob(k, &blob, &len) <= 0) {
244 fprintf(stderr, "key_to_blob failed\n");
245 exit(1);
247 /* Comment + surrounds must fit into 72 chars (RFC 4716 sec 3.3) */
248 snprintf(comment, sizeof(comment),
249 "%u-bit %s, converted by %s@%s from OpenSSH",
250 key_size(k), key_type(k),
251 pw->pw_name, hostname);
253 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
254 fprintf(stdout, "Comment: \"%s\"\n", comment);
255 dump_base64(stdout, blob, len);
256 fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
257 key_free(k);
258 xfree(blob);
259 exit(0);
262 static void
263 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
265 u_int bignum_bits = buffer_get_int(b);
266 u_int bytes = (bignum_bits + 7) / 8;
268 if (buffer_len(b) < bytes)
269 fatal("buffer_get_bignum_bits: input buffer too small: "
270 "need %d have %d", bytes, buffer_len(b));
271 if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL)
272 fatal("buffer_get_bignum_bits: BN_bin2bn failed");
273 buffer_consume(b, bytes);
276 static Key *
277 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
279 Buffer b;
280 Key *key = NULL;
281 char *type, *cipher;
282 u_char *sig, data[] = "abcde12345";
283 int magic, rlen, ktype, i1, i2, i3, i4;
284 u_int slen;
285 u_long e;
287 buffer_init(&b);
288 buffer_append(&b, blob, blen);
290 magic = buffer_get_int(&b);
291 if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
292 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
293 buffer_free(&b);
294 return NULL;
296 i1 = buffer_get_int(&b);
297 type = buffer_get_string(&b, NULL);
298 cipher = buffer_get_string(&b, NULL);
299 i2 = buffer_get_int(&b);
300 i3 = buffer_get_int(&b);
301 i4 = buffer_get_int(&b);
302 debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
303 if (strcmp(cipher, "none") != 0) {
304 error("unsupported cipher %s", cipher);
305 xfree(cipher);
306 buffer_free(&b);
307 xfree(type);
308 return NULL;
310 xfree(cipher);
312 if (strstr(type, "dsa")) {
313 ktype = KEY_DSA;
314 } else if (strstr(type, "rsa")) {
315 ktype = KEY_RSA;
316 } else {
317 buffer_free(&b);
318 xfree(type);
319 return NULL;
321 key = key_new_private(ktype);
322 xfree(type);
324 switch (key->type) {
325 case KEY_DSA:
326 buffer_get_bignum_bits(&b, key->dsa->p);
327 buffer_get_bignum_bits(&b, key->dsa->g);
328 buffer_get_bignum_bits(&b, key->dsa->q);
329 buffer_get_bignum_bits(&b, key->dsa->pub_key);
330 buffer_get_bignum_bits(&b, key->dsa->priv_key);
331 break;
332 case KEY_RSA:
333 e = buffer_get_char(&b);
334 debug("e %lx", e);
335 if (e < 30) {
336 e <<= 8;
337 e += buffer_get_char(&b);
338 debug("e %lx", e);
339 e <<= 8;
340 e += buffer_get_char(&b);
341 debug("e %lx", e);
343 if (!BN_set_word(key->rsa->e, e)) {
344 buffer_free(&b);
345 key_free(key);
346 return NULL;
348 buffer_get_bignum_bits(&b, key->rsa->d);
349 buffer_get_bignum_bits(&b, key->rsa->n);
350 buffer_get_bignum_bits(&b, key->rsa->iqmp);
351 buffer_get_bignum_bits(&b, key->rsa->q);
352 buffer_get_bignum_bits(&b, key->rsa->p);
353 rsa_generate_additional_parameters(key->rsa);
354 break;
356 rlen = buffer_len(&b);
357 if (rlen != 0)
358 error("do_convert_private_ssh2_from_blob: "
359 "remaining bytes in key blob %d", rlen);
360 buffer_free(&b);
362 /* try the key */
363 key_sign(key, &sig, &slen, data, sizeof(data));
364 key_verify(key, sig, slen, data, sizeof(data));
365 xfree(sig);
366 return key;
369 static int
370 get_line(FILE *fp, char *line, size_t len)
372 int c;
373 size_t pos = 0;
375 line[0] = '\0';
376 while ((c = fgetc(fp)) != EOF) {
377 if (pos >= len - 1) {
378 fprintf(stderr, "input line too long.\n");
379 exit(1);
381 switch (c) {
382 case '\r':
383 c = fgetc(fp);
384 if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) {
385 fprintf(stderr, "unget: %s\n", strerror(errno));
386 exit(1);
388 return pos;
389 case '\n':
390 return pos;
392 line[pos++] = c;
393 line[pos] = '\0';
395 /* We reached EOF */
396 return -1;
399 static void
400 do_convert_from_ssh2(struct passwd *pw)
402 Key *k;
403 int blen;
404 u_int len;
405 char line[1024];
406 u_char blob[8096];
407 char encoded[8096];
408 struct stat st;
409 int escaped = 0, private = 0, ok;
410 FILE *fp;
412 if (!have_identity)
413 ask_filename(pw, "Enter file in which the key is");
414 if (stat(identity_file, &st) < 0) {
415 perror(identity_file);
416 exit(1);
418 fp = fopen(identity_file, "r");
419 if (fp == NULL) {
420 perror(identity_file);
421 exit(1);
423 encoded[0] = '\0';
424 while ((blen = get_line(fp, line, sizeof(line))) != -1) {
425 if (line[blen - 1] == '\\')
426 escaped++;
427 if (strncmp(line, "----", 4) == 0 ||
428 strstr(line, ": ") != NULL) {
429 if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
430 private = 1;
431 if (strstr(line, " END ") != NULL) {
432 break;
434 /* fprintf(stderr, "ignore: %s", line); */
435 continue;
437 if (escaped) {
438 escaped--;
439 /* fprintf(stderr, "escaped: %s", line); */
440 continue;
442 strlcat(encoded, line, sizeof(encoded));
444 len = strlen(encoded);
445 if (((len % 4) == 3) &&
446 (encoded[len-1] == '=') &&
447 (encoded[len-2] == '=') &&
448 (encoded[len-3] == '='))
449 encoded[len-3] = '\0';
450 blen = uudecode(encoded, blob, sizeof(blob));
451 if (blen < 0) {
452 fprintf(stderr, "uudecode failed.\n");
453 exit(1);
455 k = private ?
456 do_convert_private_ssh2_from_blob(blob, blen) :
457 key_from_blob(blob, blen);
458 if (k == NULL) {
459 fprintf(stderr, "decode blob failed.\n");
460 exit(1);
462 ok = private ?
463 (k->type == KEY_DSA ?
464 PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, NULL, 0, NULL, NULL) :
465 PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, NULL, 0, NULL, NULL)) :
466 key_write(k, stdout);
467 if (!ok) {
468 fprintf(stderr, "key write failed\n");
469 exit(1);
471 key_free(k);
472 if (!private)
473 fprintf(stdout, "\n");
474 fclose(fp);
475 exit(0);
478 static void
479 do_print_public(struct passwd *pw)
481 Key *prv;
482 struct stat st;
484 if (!have_identity)
485 ask_filename(pw, "Enter file in which the key is");
486 if (stat(identity_file, &st) < 0) {
487 perror(identity_file);
488 exit(1);
490 prv = load_identity(identity_file);
491 if (prv == NULL) {
492 fprintf(stderr, "load failed\n");
493 exit(1);
495 if (!key_write(prv, stdout))
496 fprintf(stderr, "key_write failed");
497 key_free(prv);
498 fprintf(stdout, "\n");
499 exit(0);
502 static void
503 do_download(struct passwd *pw, char *pkcs11provider)
505 #ifdef ENABLE_PKCS11
506 Key **keys = NULL;
507 int i, nkeys;
509 pkcs11_init(0);
510 nkeys = pkcs11_add_provider(pkcs11provider, NULL, &keys);
511 if (nkeys <= 0)
512 fatal("cannot read public key from pkcs11");
513 for (i = 0; i < nkeys; i++) {
514 key_write(keys[i], stdout);
515 key_free(keys[i]);
516 fprintf(stdout, "\n");
518 xfree(keys);
519 pkcs11_terminate();
520 exit(0);
521 #else
522 fatal("no pkcs11 support");
523 #endif /* ENABLE_PKCS11 */
526 static void
527 do_fingerprint(struct passwd *pw)
529 FILE *f;
530 Key *public;
531 char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra;
532 int i, skip = 0, num = 0, invalid = 1;
533 enum fp_rep rep;
534 enum fp_type fptype;
535 struct stat st;
537 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
538 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
540 if (!have_identity)
541 ask_filename(pw, "Enter file in which the key is");
542 if (stat(identity_file, &st) < 0) {
543 perror(identity_file);
544 exit(1);
546 public = key_load_public(identity_file, &comment);
547 if (public != NULL) {
548 fp = key_fingerprint(public, fptype, rep);
549 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
550 printf("%u %s %s (%s)\n", key_size(public), fp, comment,
551 key_type(public));
552 if (log_level >= SYSLOG_LEVEL_VERBOSE)
553 printf("%s\n", ra);
554 key_free(public);
555 xfree(comment);
556 xfree(ra);
557 xfree(fp);
558 exit(0);
560 if (comment) {
561 xfree(comment);
562 comment = NULL;
565 f = fopen(identity_file, "r");
566 if (f != NULL) {
567 while (fgets(line, sizeof(line), f)) {
568 if ((cp = strchr(line, '\n')) == NULL) {
569 error("line %d too long: %.40s...",
570 num + 1, line);
571 skip = 1;
572 continue;
574 num++;
575 if (skip) {
576 skip = 0;
577 continue;
579 *cp = '\0';
581 /* Skip leading whitespace, empty and comment lines. */
582 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
584 if (!*cp || *cp == '\n' || *cp == '#')
585 continue;
586 i = strtol(cp, &ep, 10);
587 if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
588 int quoted = 0;
589 comment = cp;
590 for (; *cp && (quoted || (*cp != ' ' &&
591 *cp != '\t')); cp++) {
592 if (*cp == '\\' && cp[1] == '"')
593 cp++; /* Skip both */
594 else if (*cp == '"')
595 quoted = !quoted;
597 if (!*cp)
598 continue;
599 *cp++ = '\0';
601 ep = cp;
602 public = key_new(KEY_RSA1);
603 if (key_read(public, &cp) != 1) {
604 cp = ep;
605 key_free(public);
606 public = key_new(KEY_UNSPEC);
607 if (key_read(public, &cp) != 1) {
608 key_free(public);
609 continue;
612 comment = *cp ? cp : comment;
613 fp = key_fingerprint(public, fptype, rep);
614 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
615 printf("%u %s %s (%s)\n", key_size(public), fp,
616 comment ? comment : "no comment", key_type(public));
617 if (log_level >= SYSLOG_LEVEL_VERBOSE)
618 printf("%s\n", ra);
619 xfree(ra);
620 xfree(fp);
621 key_free(public);
622 invalid = 0;
624 fclose(f);
626 if (invalid) {
627 printf("%s is not a public key file.\n", identity_file);
628 exit(1);
630 exit(0);
633 static void
634 printhost(FILE *f, const char *name, Key *public, int ca, int hash)
636 if (print_fingerprint) {
637 enum fp_rep rep;
638 enum fp_type fptype;
639 char *fp, *ra;
641 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
642 rep = print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
643 fp = key_fingerprint(public, fptype, rep);
644 ra = key_fingerprint(public, SSH_FP_MD5, SSH_FP_RANDOMART);
645 printf("%u %s %s (%s)\n", key_size(public), fp, name,
646 key_type(public));
647 if (log_level >= SYSLOG_LEVEL_VERBOSE)
648 printf("%s\n", ra);
649 xfree(ra);
650 xfree(fp);
651 } else {
652 if (hash && (name = host_hash(name, NULL, 0)) == NULL)
653 fatal("hash_host failed");
654 fprintf(f, "%s%s%s ", ca ? CA_MARKER : "", ca ? " " : "", name);
655 if (!key_write(public, f))
656 fatal("key_write failed");
657 fprintf(f, "\n");
661 static void
662 do_known_hosts(struct passwd *pw, const char *name)
664 FILE *in, *out = stdout;
665 Key *pub;
666 char *cp, *cp2, *kp, *kp2;
667 char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN];
668 int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0;
669 int ca;
671 if (!have_identity) {
672 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
673 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
674 sizeof(identity_file))
675 fatal("Specified known hosts path too long");
676 xfree(cp);
677 have_identity = 1;
679 if ((in = fopen(identity_file, "r")) == NULL)
680 fatal("fopen: %s", strerror(errno));
683 * Find hosts goes to stdout, hash and deletions happen in-place
684 * A corner case is ssh-keygen -HF foo, which should go to stdout
686 if (!find_host && (hash_hosts || delete_host)) {
687 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
688 strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
689 strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
690 strlcat(old, ".old", sizeof(old)) >= sizeof(old))
691 fatal("known_hosts path too long");
692 umask(077);
693 if ((c = mkstemp(tmp)) == -1)
694 fatal("mkstemp: %s", strerror(errno));
695 if ((out = fdopen(c, "w")) == NULL) {
696 c = errno;
697 unlink(tmp);
698 fatal("fdopen: %s", strerror(c));
700 inplace = 1;
703 while (fgets(line, sizeof(line), in)) {
704 if ((cp = strchr(line, '\n')) == NULL) {
705 error("line %d too long: %.40s...", num + 1, line);
706 skip = 1;
707 invalid = 1;
708 continue;
710 num++;
711 if (skip) {
712 skip = 0;
713 continue;
715 *cp = '\0';
717 /* Skip leading whitespace, empty and comment lines. */
718 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
720 if (!*cp || *cp == '\n' || *cp == '#') {
721 if (inplace)
722 fprintf(out, "%s\n", cp);
723 continue;
725 /* Check whether this is a CA key */
726 if (strncasecmp(cp, CA_MARKER, sizeof(CA_MARKER) - 1) == 0 &&
727 (cp[sizeof(CA_MARKER) - 1] == ' ' ||
728 cp[sizeof(CA_MARKER) - 1] == '\t')) {
729 ca = 1;
730 cp += sizeof(CA_MARKER);
731 } else
732 ca = 0;
734 /* Find the end of the host name portion. */
735 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++)
738 if (*kp == '\0' || *(kp + 1) == '\0') {
739 error("line %d missing key: %.40s...",
740 num, line);
741 invalid = 1;
742 continue;
744 *kp++ = '\0';
745 kp2 = kp;
747 pub = key_new(KEY_RSA1);
748 if (key_read(pub, &kp) != 1) {
749 kp = kp2;
750 key_free(pub);
751 pub = key_new(KEY_UNSPEC);
752 if (key_read(pub, &kp) != 1) {
753 error("line %d invalid key: %.40s...",
754 num, line);
755 key_free(pub);
756 invalid = 1;
757 continue;
761 if (*cp == HASH_DELIM) {
762 if (find_host || delete_host) {
763 cp2 = host_hash(name, cp, strlen(cp));
764 if (cp2 == NULL) {
765 error("line %d: invalid hashed "
766 "name: %.64s...", num, line);
767 invalid = 1;
768 continue;
770 c = (strcmp(cp2, cp) == 0);
771 if (find_host && c) {
772 printf("# Host %s found: "
773 "line %d type %s%s\n", name,
774 num, key_type(pub),
775 ca ? " (CA key)" : "");
776 printhost(out, cp, pub, ca, 0);
778 if (delete_host && !c && !ca)
779 printhost(out, cp, pub, ca, 0);
780 } else if (hash_hosts)
781 printhost(out, cp, pub, ca, 0);
782 } else {
783 if (find_host || delete_host) {
784 c = (match_hostname(name, cp,
785 strlen(cp)) == 1);
786 if (find_host && c) {
787 printf("# Host %s found: "
788 "line %d type %s%s\n", name,
789 num, key_type(pub),
790 ca ? " (CA key)" : "");
791 printhost(out, name, pub,
792 ca, hash_hosts && !ca);
794 if (delete_host && !c && !ca)
795 printhost(out, cp, pub, ca, 0);
796 } else if (hash_hosts) {
797 for (cp2 = strsep(&cp, ",");
798 cp2 != NULL && *cp2 != '\0';
799 cp2 = strsep(&cp, ",")) {
800 if (ca) {
801 fprintf(stderr, "Warning: "
802 "ignoring CA key for host: "
803 "%.64s\n", cp2);
804 printhost(out, cp2, pub, ca, 0);
805 } else if (strcspn(cp2, "*?!") !=
806 strlen(cp2)) {
807 fprintf(stderr, "Warning: "
808 "ignoring host name with "
809 "metacharacters: %.64s\n",
810 cp2);
811 printhost(out, cp2, pub, ca, 0);
812 } else
813 printhost(out, cp2, pub, ca, 1);
815 has_unhashed = 1;
818 key_free(pub);
820 fclose(in);
822 if (invalid) {
823 fprintf(stderr, "%s is not a valid known_hosts file.\n",
824 identity_file);
825 if (inplace) {
826 fprintf(stderr, "Not replacing existing known_hosts "
827 "file because of errors\n");
828 fclose(out);
829 unlink(tmp);
831 exit(1);
834 if (inplace) {
835 fclose(out);
837 /* Backup existing file */
838 if (unlink(old) == -1 && errno != ENOENT)
839 fatal("unlink %.100s: %s", old, strerror(errno));
840 if (link(identity_file, old) == -1)
841 fatal("link %.100s to %.100s: %s", identity_file, old,
842 strerror(errno));
843 /* Move new one into place */
844 if (rename(tmp, identity_file) == -1) {
845 error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
846 strerror(errno));
847 unlink(tmp);
848 unlink(old);
849 exit(1);
852 fprintf(stderr, "%s updated.\n", identity_file);
853 fprintf(stderr, "Original contents retained as %s\n", old);
854 if (has_unhashed) {
855 fprintf(stderr, "WARNING: %s contains unhashed "
856 "entries\n", old);
857 fprintf(stderr, "Delete this file to ensure privacy "
858 "of hostnames\n");
862 exit(0);
866 * Perform changing a passphrase. The argument is the passwd structure
867 * for the current user.
869 static void
870 do_change_passphrase(struct passwd *pw)
872 char *comment;
873 char *old_passphrase, *passphrase1, *passphrase2;
874 struct stat st;
875 Key *private;
877 if (!have_identity)
878 ask_filename(pw, "Enter file in which the key is");
879 if (stat(identity_file, &st) < 0) {
880 perror(identity_file);
881 exit(1);
883 /* Try to load the file with empty passphrase. */
884 private = key_load_private(identity_file, "", &comment);
885 if (private == NULL) {
886 if (identity_passphrase)
887 old_passphrase = xstrdup(identity_passphrase);
888 else
889 old_passphrase =
890 read_passphrase("Enter old passphrase: ",
891 RP_ALLOW_STDIN);
892 private = key_load_private(identity_file, old_passphrase,
893 &comment);
894 memset(old_passphrase, 0, strlen(old_passphrase));
895 xfree(old_passphrase);
896 if (private == NULL) {
897 printf("Bad passphrase.\n");
898 exit(1);
901 printf("Key has comment '%s'\n", comment);
903 /* Ask the new passphrase (twice). */
904 if (identity_new_passphrase) {
905 passphrase1 = xstrdup(identity_new_passphrase);
906 passphrase2 = NULL;
907 } else {
908 passphrase1 =
909 read_passphrase("Enter new passphrase (empty for no "
910 "passphrase): ", RP_ALLOW_STDIN);
911 passphrase2 = read_passphrase("Enter same passphrase again: ",
912 RP_ALLOW_STDIN);
914 /* Verify that they are the same. */
915 if (strcmp(passphrase1, passphrase2) != 0) {
916 memset(passphrase1, 0, strlen(passphrase1));
917 memset(passphrase2, 0, strlen(passphrase2));
918 xfree(passphrase1);
919 xfree(passphrase2);
920 printf("Pass phrases do not match. Try again.\n");
921 exit(1);
923 /* Destroy the other copy. */
924 memset(passphrase2, 0, strlen(passphrase2));
925 xfree(passphrase2);
928 /* Save the file using the new passphrase. */
929 if (!key_save_private(private, identity_file, passphrase1, comment)) {
930 printf("Saving the key failed: %s.\n", identity_file);
931 memset(passphrase1, 0, strlen(passphrase1));
932 xfree(passphrase1);
933 key_free(private);
934 xfree(comment);
935 exit(1);
937 /* Destroy the passphrase and the copy of the key in memory. */
938 memset(passphrase1, 0, strlen(passphrase1));
939 xfree(passphrase1);
940 key_free(private); /* Destroys contents */
941 xfree(comment);
943 printf("Your identification has been saved with the new passphrase.\n");
944 exit(0);
948 * Print the SSHFP RR.
950 static int
951 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
953 Key *public;
954 char *comment = NULL;
955 struct stat st;
957 if (fname == NULL)
958 ask_filename(pw, "Enter file in which the key is");
959 if (stat(fname, &st) < 0) {
960 if (errno == ENOENT)
961 return 0;
962 perror(fname);
963 exit(1);
965 public = key_load_public(fname, &comment);
966 if (public != NULL) {
967 export_dns_rr(hname, public, stdout, print_generic);
968 key_free(public);
969 xfree(comment);
970 return 1;
972 if (comment)
973 xfree(comment);
975 printf("failed to read v2 public key from %s.\n", fname);
976 exit(1);
980 * Change the comment of a private key file.
982 static void
983 do_change_comment(struct passwd *pw)
985 char new_comment[1024], *comment, *passphrase;
986 Key *private;
987 Key *public;
988 struct stat st;
989 FILE *f;
990 int fd;
992 if (!have_identity)
993 ask_filename(pw, "Enter file in which the key is");
994 if (stat(identity_file, &st) < 0) {
995 perror(identity_file);
996 exit(1);
998 private = key_load_private(identity_file, "", &comment);
999 if (private == NULL) {
1000 if (identity_passphrase)
1001 passphrase = xstrdup(identity_passphrase);
1002 else if (identity_new_passphrase)
1003 passphrase = xstrdup(identity_new_passphrase);
1004 else
1005 passphrase = read_passphrase("Enter passphrase: ",
1006 RP_ALLOW_STDIN);
1007 /* Try to load using the passphrase. */
1008 private = key_load_private(identity_file, passphrase, &comment);
1009 if (private == NULL) {
1010 memset(passphrase, 0, strlen(passphrase));
1011 xfree(passphrase);
1012 printf("Bad passphrase.\n");
1013 exit(1);
1015 } else {
1016 passphrase = xstrdup("");
1018 if (private->type != KEY_RSA1) {
1019 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
1020 key_free(private);
1021 exit(1);
1023 printf("Key now has comment '%s'\n", comment);
1025 if (identity_comment) {
1026 strlcpy(new_comment, identity_comment, sizeof(new_comment));
1027 } else {
1028 printf("Enter new comment: ");
1029 fflush(stdout);
1030 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
1031 memset(passphrase, 0, strlen(passphrase));
1032 key_free(private);
1033 exit(1);
1035 new_comment[strcspn(new_comment, "\n")] = '\0';
1038 /* Save the file using the new passphrase. */
1039 if (!key_save_private(private, identity_file, passphrase, new_comment)) {
1040 printf("Saving the key failed: %s.\n", identity_file);
1041 memset(passphrase, 0, strlen(passphrase));
1042 xfree(passphrase);
1043 key_free(private);
1044 xfree(comment);
1045 exit(1);
1047 memset(passphrase, 0, strlen(passphrase));
1048 xfree(passphrase);
1049 public = key_from_private(private);
1050 key_free(private);
1052 strlcat(identity_file, ".pub", sizeof(identity_file));
1053 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1054 if (fd == -1) {
1055 printf("Could not save your public key in %s\n", identity_file);
1056 exit(1);
1058 f = fdopen(fd, "w");
1059 if (f == NULL) {
1060 printf("fdopen %s failed\n", identity_file);
1061 exit(1);
1063 if (!key_write(public, f))
1064 fprintf(stderr, "write key failed\n");
1065 key_free(public);
1066 fprintf(f, " %s\n", new_comment);
1067 fclose(f);
1069 xfree(comment);
1071 printf("The comment in your key file has been changed.\n");
1072 exit(0);
1075 static const char *
1076 fmt_validity(u_int64_t valid_from, u_int64_t valid_to)
1078 char from[32], to[32];
1079 static char ret[64];
1080 time_t tt;
1081 struct tm *tm;
1083 *from = *to = '\0';
1084 if (valid_from == 0 && valid_to == 0xffffffffffffffffULL)
1085 return "forever";
1087 if (valid_from != 0) {
1088 /* XXX revisit INT_MAX in 2038 :) */
1089 tt = valid_from > INT_MAX ? INT_MAX : valid_from;
1090 tm = localtime(&tt);
1091 strftime(from, sizeof(from), "%Y-%m-%dT%H:%M:%S", tm);
1093 if (valid_to != 0xffffffffffffffffULL) {
1094 /* XXX revisit INT_MAX in 2038 :) */
1095 tt = valid_to > INT_MAX ? INT_MAX : valid_to;
1096 tm = localtime(&tt);
1097 strftime(to, sizeof(to), "%Y-%m-%dT%H:%M:%S", tm);
1100 if (valid_from == 0) {
1101 snprintf(ret, sizeof(ret), "before %s", to);
1102 return ret;
1104 if (valid_to == 0xffffffffffffffffULL) {
1105 snprintf(ret, sizeof(ret), "after %s", from);
1106 return ret;
1109 snprintf(ret, sizeof(ret), "from %s to %s", from, to);
1110 return ret;
1113 static void
1114 add_flag_option(Buffer *c, const char *name)
1116 debug3("%s: %s", __func__, name);
1117 buffer_put_cstring(c, name);
1118 buffer_put_string(c, NULL, 0);
1121 static void
1122 add_string_option(Buffer *c, const char *name, const char *value)
1124 Buffer b;
1126 debug3("%s: %s=%s", __func__, name, value);
1127 buffer_init(&b);
1128 buffer_put_cstring(&b, value);
1130 buffer_put_cstring(c, name);
1131 buffer_put_string(c, buffer_ptr(&b), buffer_len(&b));
1133 buffer_free(&b);
1136 static void
1137 prepare_options_buf(Buffer *c)
1139 buffer_clear(c);
1140 if ((critical_flags & CRITOPT_X_FWD) != 0)
1141 add_flag_option(c, "permit-X11-forwarding");
1142 if ((critical_flags & CRITOPT_AGENT_FWD) != 0)
1143 add_flag_option(c, "permit-agent-forwarding");
1144 if ((critical_flags & CRITOPT_PORT_FWD) != 0)
1145 add_flag_option(c, "permit-port-forwarding");
1146 if ((critical_flags & CRITOPT_PTY) != 0)
1147 add_flag_option(c, "permit-pty");
1148 if ((critical_flags & CRITOPT_USER_RC) != 0)
1149 add_flag_option(c, "permit-user-rc");
1150 if (critical_command != NULL)
1151 add_string_option(c, "force-command", critical_command);
1152 if (critical_src_addr != NULL)
1153 add_string_option(c, "source-address", critical_src_addr);
1156 static void
1157 do_ca_sign(struct passwd *pw, int argc, char **argv)
1159 int i, fd;
1160 u_int n;
1161 Key *ca, *public;
1162 char *otmp, *tmp, *cp, *out, *comment, **plist = NULL;
1163 FILE *f;
1164 int v00 = 0; /* legacy keys */
1166 tmp = tilde_expand_filename(ca_key_path, pw->pw_uid);
1167 if ((ca = load_identity(tmp)) == NULL)
1168 fatal("Couldn't load CA key \"%s\"", tmp);
1169 xfree(tmp);
1171 if (key_type_name != NULL) {
1172 switch (key_type_from_name(key_type_name)) {
1173 case KEY_RSA_CERT_V00:
1174 case KEY_DSA_CERT_V00:
1175 v00 = 1;
1176 break;
1177 case KEY_UNSPEC:
1178 if (strcasecmp(key_type_name, "v00") == 0) {
1179 v00 = 1;
1180 break;
1181 } else if (strcasecmp(key_type_name, "v01") == 0)
1182 break;
1183 /* FALLTHROUGH */
1184 default:
1185 fprintf(stderr, "unknown key type %s\n", key_type_name);
1186 exit(1);
1190 for (i = 0; i < argc; i++) {
1191 /* Split list of principals */
1192 n = 0;
1193 if (cert_principals != NULL) {
1194 otmp = tmp = xstrdup(cert_principals);
1195 plist = NULL;
1196 for (; (cp = strsep(&tmp, ",")) != NULL; n++) {
1197 plist = xrealloc(plist, n + 1, sizeof(*plist));
1198 if (*(plist[n] = xstrdup(cp)) == '\0')
1199 fatal("Empty principal name");
1201 xfree(otmp);
1204 tmp = tilde_expand_filename(argv[i], pw->pw_uid);
1205 if ((public = key_load_public(tmp, &comment)) == NULL)
1206 fatal("%s: unable to open \"%s\"", __func__, tmp);
1207 if (public->type != KEY_RSA && public->type != KEY_DSA)
1208 fatal("%s: key \"%s\" type %s cannot be certified",
1209 __func__, tmp, key_type(public));
1211 /* Prepare certificate to sign */
1212 if (key_to_certified(public, v00) != 0)
1213 fatal("Could not upgrade key %s to certificate", tmp);
1214 public->cert->type = cert_key_type;
1215 public->cert->serial = (u_int64_t)cert_serial;
1216 public->cert->key_id = xstrdup(cert_key_id);
1217 public->cert->nprincipals = n;
1218 public->cert->principals = plist;
1219 public->cert->valid_after = cert_valid_from;
1220 public->cert->valid_before = cert_valid_to;
1221 prepare_options_buf(&public->cert->critical);
1222 public->cert->signature_key = key_from_private(ca);
1224 if (key_certify(public, ca) != 0)
1225 fatal("Couldn't not certify key %s", tmp);
1227 if ((cp = strrchr(tmp, '.')) != NULL && strcmp(cp, ".pub") == 0)
1228 *cp = '\0';
1229 xasprintf(&out, "%s-cert.pub", tmp);
1230 xfree(tmp);
1232 if ((fd = open(out, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1)
1233 fatal("Could not open \"%s\" for writing: %s", out,
1234 strerror(errno));
1235 if ((f = fdopen(fd, "w")) == NULL)
1236 fatal("%s: fdopen: %s", __func__, strerror(errno));
1237 if (!key_write(public, f))
1238 fatal("Could not write certified key to %s", out);
1239 fprintf(f, " %s\n", comment);
1240 fclose(f);
1242 if (!quiet) {
1243 logit("Signed %s key %s: id \"%s\" serial %llu%s%s "
1244 "valid %s", key_cert_type(public),
1245 out, public->cert->key_id, public->cert->serial,
1246 cert_principals != NULL ? " for " : "",
1247 cert_principals != NULL ? cert_principals : "",
1248 fmt_validity(cert_valid_from, cert_valid_to));
1251 key_free(public);
1252 xfree(out);
1254 exit(0);
1257 static u_int64_t
1258 parse_relative_time(const char *s, time_t now)
1260 int64_t mul, secs;
1262 mul = *s == '-' ? -1 : 1;
1264 if ((secs = convtime(s + 1)) == -1)
1265 fatal("Invalid relative certificate time %s", s);
1266 if (mul == -1 && secs > now)
1267 fatal("Certificate time %s cannot be represented", s);
1268 return now + (u_int64_t)(secs * mul);
1271 static u_int64_t
1272 parse_absolute_time(const char *s)
1274 struct tm tm;
1275 time_t tt;
1276 char buf[32], *fmt;
1279 * POSIX strptime says "The application shall ensure that there
1280 * is white-space or other non-alphanumeric characters between
1281 * any two conversion specifications" so arrange things this way.
1283 switch (strlen(s)) {
1284 case 8:
1285 fmt = "%Y-%m-%d";
1286 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2s", s, s + 4, s + 6);
1287 break;
1288 case 14:
1289 fmt = "%Y-%m-%dT%H:%M:%S";
1290 snprintf(buf, sizeof(buf), "%.4s-%.2s-%.2sT%.2s:%.2s:%.2s",
1291 s, s + 4, s + 6, s + 8, s + 10, s + 12);
1292 break;
1293 default:
1294 fatal("Invalid certificate time format %s", s);
1297 bzero(&tm, sizeof(tm));
1298 if (strptime(buf, fmt, &tm) == NULL)
1299 fatal("Invalid certificate time %s", s);
1300 if ((tt = mktime(&tm)) < 0)
1301 fatal("Certificate time %s cannot be represented", s);
1302 return (u_int64_t)tt;
1305 static void
1306 parse_cert_times(char *timespec)
1308 char *from, *to;
1309 time_t now = time(NULL);
1310 int64_t secs;
1312 /* +timespec relative to now */
1313 if (*timespec == '+' && strchr(timespec, ':') == NULL) {
1314 if ((secs = convtime(timespec + 1)) == -1)
1315 fatal("Invalid relative certificate life %s", timespec);
1316 cert_valid_to = now + secs;
1318 * Backdate certificate one minute to avoid problems on hosts
1319 * with poorly-synchronised clocks.
1321 cert_valid_from = ((now - 59)/ 60) * 60;
1322 return;
1326 * from:to, where
1327 * from := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1328 * to := [+-]timespec | YYYYMMDD | YYYYMMDDHHMMSS
1330 from = xstrdup(timespec);
1331 to = strchr(from, ':');
1332 if (to == NULL || from == to || *(to + 1) == '\0')
1333 fatal("Invalid certificate life specification %s", timespec);
1334 *to++ = '\0';
1336 if (*from == '-' || *from == '+')
1337 cert_valid_from = parse_relative_time(from, now);
1338 else
1339 cert_valid_from = parse_absolute_time(from);
1341 if (*to == '-' || *to == '+')
1342 cert_valid_to = parse_relative_time(to, cert_valid_from);
1343 else
1344 cert_valid_to = parse_absolute_time(to);
1346 if (cert_valid_to <= cert_valid_from)
1347 fatal("Empty certificate validity interval");
1348 xfree(from);
1351 static void
1352 add_cert_option(char *opt)
1354 char *val;
1356 if (strcmp(opt, "clear") == 0)
1357 critical_flags = 0;
1358 else if (strcasecmp(opt, "no-x11-forwarding") == 0)
1359 critical_flags &= ~CRITOPT_X_FWD;
1360 else if (strcasecmp(opt, "permit-x11-forwarding") == 0)
1361 critical_flags |= CRITOPT_X_FWD;
1362 else if (strcasecmp(opt, "no-agent-forwarding") == 0)
1363 critical_flags &= ~CRITOPT_AGENT_FWD;
1364 else if (strcasecmp(opt, "permit-agent-forwarding") == 0)
1365 critical_flags |= CRITOPT_AGENT_FWD;
1366 else if (strcasecmp(opt, "no-port-forwarding") == 0)
1367 critical_flags &= ~CRITOPT_PORT_FWD;
1368 else if (strcasecmp(opt, "permit-port-forwarding") == 0)
1369 critical_flags |= CRITOPT_PORT_FWD;
1370 else if (strcasecmp(opt, "no-pty") == 0)
1371 critical_flags &= ~CRITOPT_PTY;
1372 else if (strcasecmp(opt, "permit-pty") == 0)
1373 critical_flags |= CRITOPT_PTY;
1374 else if (strcasecmp(opt, "no-user-rc") == 0)
1375 critical_flags &= ~CRITOPT_USER_RC;
1376 else if (strcasecmp(opt, "permit-user-rc") == 0)
1377 critical_flags |= CRITOPT_USER_RC;
1378 else if (strncasecmp(opt, "force-command=", 14) == 0) {
1379 val = opt + 14;
1380 if (*val == '\0')
1381 fatal("Empty force-command option");
1382 if (critical_command != NULL)
1383 fatal("force-command already specified");
1384 critical_command = xstrdup(val);
1385 } else if (strncasecmp(opt, "source-address=", 15) == 0) {
1386 val = opt + 15;
1387 if (*val == '\0')
1388 fatal("Empty source-address option");
1389 if (critical_src_addr != NULL)
1390 fatal("source-address already specified");
1391 if (addr_match_cidr_list(NULL, val) != 0)
1392 fatal("Invalid source-address list");
1393 critical_src_addr = xstrdup(val);
1394 } else
1395 fatal("Unsupported certificate option \"%s\"", opt);
1398 static void
1399 do_show_cert(struct passwd *pw)
1401 Key *key;
1402 struct stat st;
1403 char *key_fp, *ca_fp;
1404 Buffer options, option;
1405 u_char *name, *data;
1406 u_int i, dlen, v00;
1408 if (!have_identity)
1409 ask_filename(pw, "Enter file in which the key is");
1410 if (stat(identity_file, &st) < 0) {
1411 perror(identity_file);
1412 exit(1);
1414 if ((key = key_load_public(identity_file, NULL)) == NULL)
1415 fatal("%s is not a public key", identity_file);
1416 if (!key_is_cert(key))
1417 fatal("%s is not a certificate", identity_file);
1418 v00 = key->type == KEY_RSA_CERT_V00 || key->type == KEY_DSA_CERT_V00;
1420 key_fp = key_fingerprint(key, SSH_FP_MD5, SSH_FP_HEX);
1421 ca_fp = key_fingerprint(key->cert->signature_key,
1422 SSH_FP_MD5, SSH_FP_HEX);
1424 printf("%s:\n", identity_file);
1425 printf(" Type: %s %s certificate\n", key_ssh_name(key),
1426 key_cert_type(key));
1427 printf(" Public key: %s %s\n", key_type(key), key_fp);
1428 printf(" Signing CA: %s %s\n",
1429 key_type(key->cert->signature_key), ca_fp);
1430 printf(" Key ID: \"%s\"\n", key->cert->key_id);
1431 if (!v00)
1432 printf(" Serial: %llu\n", key->cert->serial);
1433 printf(" Valid: %s\n",
1434 fmt_validity(key->cert->valid_after, key->cert->valid_before));
1435 printf(" Principals: ");
1436 if (key->cert->nprincipals == 0)
1437 printf("(none)\n");
1438 else {
1439 for (i = 0; i < key->cert->nprincipals; i++)
1440 printf("\n %s",
1441 key->cert->principals[i]);
1442 printf("\n");
1444 printf(" Critical Options: ");
1445 if (buffer_len(&key->cert->critical) == 0)
1446 printf("(none)\n");
1447 else {
1448 printf("\n");
1449 buffer_init(&options);
1450 buffer_append(&options,
1451 buffer_ptr(&key->cert->critical),
1452 buffer_len(&key->cert->critical));
1453 buffer_init(&option);
1454 while (buffer_len(&options) != 0) {
1455 name = buffer_get_string(&options, NULL);
1456 data = buffer_get_string_ptr(&options, &dlen);
1457 buffer_append(&option, data, dlen);
1458 printf(" %s", name);
1459 if (strcmp(name, "permit-X11-forwarding") == 0 ||
1460 strcmp(name, "permit-agent-forwarding") == 0 ||
1461 strcmp(name, "permit-port-forwarding") == 0 ||
1462 strcmp(name, "permit-pty") == 0 ||
1463 strcmp(name, "permit-user-rc") == 0)
1464 printf("\n");
1465 else if (strcmp(name, "force-command") == 0 ||
1466 strcmp(name, "source-address") == 0) {
1467 data = buffer_get_string(&option, NULL);
1468 printf(" %s\n", data);
1469 xfree(data);
1470 } else {
1471 printf(" UNKNOWN OPTION (len %u)\n",
1472 buffer_len(&option));
1473 buffer_clear(&option);
1475 xfree(name);
1476 if (buffer_len(&option) != 0)
1477 fatal("Option corrupt: extra data at end");
1479 buffer_free(&option);
1480 buffer_free(&options);
1482 if (!v00) {
1483 printf(" Extensions: ");
1484 if (buffer_len(&key->cert->extensions) == 0)
1485 printf("(none)\n");
1486 else {
1487 printf("\n");
1488 buffer_init(&options);
1489 buffer_append(&options,
1490 buffer_ptr(&key->cert->extensions),
1491 buffer_len(&key->cert->extensions));
1492 buffer_init(&option);
1493 while (buffer_len(&options) != 0) {
1494 name = buffer_get_string(&options, NULL);
1495 (void)buffer_get_string_ptr(&options, &dlen);
1496 printf(" %s UNKNOWN OPTION "
1497 "(len %u)\n", name, dlen);
1498 xfree(name);
1500 buffer_free(&option);
1501 buffer_free(&options);
1504 exit(0);
1507 static void
1508 usage(void)
1510 fprintf(stderr, "usage: %s [options]\n", __progname);
1511 fprintf(stderr, "Options:\n");
1512 fprintf(stderr, " -a trials Number of trials for screening DH-GEX moduli.\n");
1513 fprintf(stderr, " -B Show bubblebabble digest of key file.\n");
1514 fprintf(stderr, " -b bits Number of bits in the key to create.\n");
1515 fprintf(stderr, " -C comment Provide new comment.\n");
1516 fprintf(stderr, " -c Change comment in private and public key files.\n");
1517 #ifdef ENABLE_PKCS11
1518 fprintf(stderr, " -D pkcs11 Download public key from pkcs11 token.\n");
1519 #endif
1520 fprintf(stderr, " -e Convert OpenSSH to RFC 4716 key file.\n");
1521 fprintf(stderr, " -F hostname Find hostname in known hosts file.\n");
1522 fprintf(stderr, " -f filename Filename of the key file.\n");
1523 fprintf(stderr, " -G file Generate candidates for DH-GEX moduli.\n");
1524 fprintf(stderr, " -g Use generic DNS resource record format.\n");
1525 fprintf(stderr, " -H Hash names in known_hosts file.\n");
1526 fprintf(stderr, " -h Generate host certificate instead of a user certificate.\n");
1527 fprintf(stderr, " -I key_id Key identifier to include in certificate.\n");
1528 fprintf(stderr, " -i Convert RFC 4716 to OpenSSH key file.\n");
1529 fprintf(stderr, " -L Print the contents of a certificate.\n");
1530 fprintf(stderr, " -l Show fingerprint of key file.\n");
1531 fprintf(stderr, " -M memory Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1532 fprintf(stderr, " -n name,... User/host principal names to include in certificate\n");
1533 fprintf(stderr, " -N phrase Provide new passphrase.\n");
1534 fprintf(stderr, " -O option Specify a certificate option.\n");
1535 fprintf(stderr, " -P phrase Provide old passphrase.\n");
1536 fprintf(stderr, " -p Change passphrase of private key file.\n");
1537 fprintf(stderr, " -q Quiet.\n");
1538 fprintf(stderr, " -R hostname Remove host from known_hosts file.\n");
1539 fprintf(stderr, " -r hostname Print DNS resource record.\n");
1540 fprintf(stderr, " -s ca_key Certify keys with CA key.\n");
1541 fprintf(stderr, " -S start Start point (hex) for generating DH-GEX moduli.\n");
1542 fprintf(stderr, " -T file Screen candidates for DH-GEX moduli.\n");
1543 fprintf(stderr, " -t type Specify type of key to create.\n");
1544 fprintf(stderr, " -V from:to Specify certificate validity interval.\n");
1545 fprintf(stderr, " -v Verbose.\n");
1546 fprintf(stderr, " -W gen Generator to use for generating DH-GEX moduli.\n");
1547 fprintf(stderr, " -y Read private key file and print public key.\n");
1548 fprintf(stderr, " -z serial Specify a serial number.\n");
1550 exit(1);
1554 * Main program for key management.
1557 main(int argc, char **argv)
1559 char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1560 char out_file[MAXPATHLEN], *pkcs11provider = NULL;
1561 char *rr_hostname = NULL;
1562 Key *private, *public;
1563 struct passwd *pw;
1564 struct stat st;
1565 int opt, type, fd;
1566 u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1567 int do_gen_candidates = 0, do_screen_candidates = 0;
1568 BIGNUM *start = NULL;
1569 FILE *f;
1570 const char *errstr;
1572 extern int optind;
1573 extern char *optarg;
1575 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1576 sanitise_stdfd();
1578 __progname = ssh_get_progname(argv[0]);
1580 SSLeay_add_all_algorithms();
1581 log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1583 init_rng();
1584 seed_rng();
1586 /* we need this for the home * directory. */
1587 pw = getpwuid(getuid());
1588 if (!pw) {
1589 printf("You don't exist, go away!\n");
1590 exit(1);
1592 if (gethostname(hostname, sizeof(hostname)) < 0) {
1593 perror("gethostname");
1594 exit(1);
1597 while ((opt = getopt(argc, argv, "degiqpclBHLhvxXyF:b:f:t:D:I:P:N:n:"
1598 "O:C:r:g:R:T:G:M:S:s:a:V:W:z:")) != -1) {
1599 switch (opt) {
1600 case 'b':
1601 bits = (u_int32_t)strtonum(optarg, 768, 32768, &errstr);
1602 if (errstr)
1603 fatal("Bits has bad value %s (%s)",
1604 optarg, errstr);
1605 break;
1606 case 'F':
1607 find_host = 1;
1608 rr_hostname = optarg;
1609 break;
1610 case 'H':
1611 hash_hosts = 1;
1612 break;
1613 case 'I':
1614 cert_key_id = optarg;
1615 break;
1616 case 'R':
1617 delete_host = 1;
1618 rr_hostname = optarg;
1619 break;
1620 case 'L':
1621 show_cert = 1;
1622 break;
1623 case 'l':
1624 print_fingerprint = 1;
1625 break;
1626 case 'B':
1627 print_bubblebabble = 1;
1628 break;
1629 case 'n':
1630 cert_principals = optarg;
1631 break;
1632 case 'p':
1633 change_passphrase = 1;
1634 break;
1635 case 'c':
1636 change_comment = 1;
1637 break;
1638 case 'f':
1639 if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
1640 sizeof(identity_file))
1641 fatal("Identity filename too long");
1642 have_identity = 1;
1643 break;
1644 case 'g':
1645 print_generic = 1;
1646 break;
1647 case 'P':
1648 identity_passphrase = optarg;
1649 break;
1650 case 'N':
1651 identity_new_passphrase = optarg;
1652 break;
1653 case 'O':
1654 add_cert_option(optarg);
1655 break;
1656 case 'C':
1657 identity_comment = optarg;
1658 break;
1659 case 'q':
1660 quiet = 1;
1661 break;
1662 case 'e':
1663 case 'x':
1664 /* export key */
1665 convert_to_ssh2 = 1;
1666 break;
1667 case 'h':
1668 cert_key_type = SSH2_CERT_TYPE_HOST;
1669 critical_flags = 0;
1670 break;
1671 case 'i':
1672 case 'X':
1673 /* import key */
1674 convert_from_ssh2 = 1;
1675 break;
1676 case 'y':
1677 print_public = 1;
1678 break;
1679 case 'd':
1680 key_type_name = "dsa";
1681 break;
1682 case 's':
1683 ca_key_path = optarg;
1684 break;
1685 case 't':
1686 key_type_name = optarg;
1687 break;
1688 case 'D':
1689 pkcs11provider = optarg;
1690 break;
1691 case 'v':
1692 if (log_level == SYSLOG_LEVEL_INFO)
1693 log_level = SYSLOG_LEVEL_DEBUG1;
1694 else {
1695 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1696 log_level < SYSLOG_LEVEL_DEBUG3)
1697 log_level++;
1699 break;
1700 case 'r':
1701 rr_hostname = optarg;
1702 break;
1703 case 'W':
1704 generator_wanted = (u_int32_t)strtonum(optarg, 1,
1705 UINT_MAX, &errstr);
1706 if (errstr)
1707 fatal("Desired generator has bad value: %s (%s)",
1708 optarg, errstr);
1709 break;
1710 case 'a':
1711 trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1712 if (errstr)
1713 fatal("Invalid number of trials: %s (%s)",
1714 optarg, errstr);
1715 break;
1716 case 'M':
1717 memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1718 if (errstr)
1719 fatal("Memory limit is %s: %s", errstr, optarg);
1720 break;
1721 case 'G':
1722 do_gen_candidates = 1;
1723 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1724 sizeof(out_file))
1725 fatal("Output filename too long");
1726 break;
1727 case 'T':
1728 do_screen_candidates = 1;
1729 if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1730 sizeof(out_file))
1731 fatal("Output filename too long");
1732 break;
1733 case 'S':
1734 /* XXX - also compare length against bits */
1735 if (BN_hex2bn(&start, optarg) == 0)
1736 fatal("Invalid start point.");
1737 break;
1738 case 'V':
1739 parse_cert_times(optarg);
1740 break;
1741 case 'z':
1742 cert_serial = strtonum(optarg, 0, LLONG_MAX, &errstr);
1743 if (errstr)
1744 fatal("Invalid serial number: %s", errstr);
1745 break;
1746 case '?':
1747 default:
1748 usage();
1752 /* reinit */
1753 log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1755 argv += optind;
1756 argc -= optind;
1758 if (ca_key_path != NULL) {
1759 if (argc < 1) {
1760 printf("Too few arguments.\n");
1761 usage();
1763 } else if (argc > 0) {
1764 printf("Too many arguments.\n");
1765 usage();
1767 if (change_passphrase && change_comment) {
1768 printf("Can only have one of -p and -c.\n");
1769 usage();
1771 if (print_fingerprint && (delete_host || hash_hosts)) {
1772 printf("Cannot use -l with -D or -R.\n");
1773 usage();
1775 if (ca_key_path != NULL) {
1776 if (cert_key_id == NULL)
1777 fatal("Must specify key id (-I) when certifying");
1778 do_ca_sign(pw, argc, argv);
1780 if (show_cert)
1781 do_show_cert(pw);
1782 if (delete_host || hash_hosts || find_host)
1783 do_known_hosts(pw, rr_hostname);
1784 if (print_fingerprint || print_bubblebabble)
1785 do_fingerprint(pw);
1786 if (change_passphrase)
1787 do_change_passphrase(pw);
1788 if (change_comment)
1789 do_change_comment(pw);
1790 if (convert_to_ssh2)
1791 do_convert_to_ssh2(pw);
1792 if (convert_from_ssh2)
1793 do_convert_from_ssh2(pw);
1794 if (print_public)
1795 do_print_public(pw);
1796 if (rr_hostname != NULL) {
1797 unsigned int n = 0;
1799 if (have_identity) {
1800 n = do_print_resource_record(pw,
1801 identity_file, rr_hostname);
1802 if (n == 0) {
1803 perror(identity_file);
1804 exit(1);
1806 exit(0);
1807 } else {
1809 n += do_print_resource_record(pw,
1810 _PATH_HOST_RSA_KEY_FILE, rr_hostname);
1811 n += do_print_resource_record(pw,
1812 _PATH_HOST_DSA_KEY_FILE, rr_hostname);
1814 if (n == 0)
1815 fatal("no keys found.");
1816 exit(0);
1819 if (pkcs11provider != NULL)
1820 do_download(pw, pkcs11provider);
1822 if (do_gen_candidates) {
1823 FILE *out = fopen(out_file, "w");
1825 if (out == NULL) {
1826 error("Couldn't open modulus candidate file \"%s\": %s",
1827 out_file, strerror(errno));
1828 return (1);
1830 if (bits == 0)
1831 bits = DEFAULT_BITS;
1832 if (gen_candidates(out, memory, bits, start) != 0)
1833 fatal("modulus candidate generation failed");
1835 return (0);
1838 if (do_screen_candidates) {
1839 FILE *in;
1840 FILE *out = fopen(out_file, "w");
1842 if (have_identity && strcmp(identity_file, "-") != 0) {
1843 if ((in = fopen(identity_file, "r")) == NULL) {
1844 fatal("Couldn't open modulus candidate "
1845 "file \"%s\": %s", identity_file,
1846 strerror(errno));
1848 } else
1849 in = stdin;
1851 if (out == NULL) {
1852 fatal("Couldn't open moduli file \"%s\": %s",
1853 out_file, strerror(errno));
1855 if (prime_test(in, out, trials, generator_wanted) != 0)
1856 fatal("modulus screening failed");
1857 return (0);
1860 arc4random_stir();
1862 if (key_type_name == NULL)
1863 key_type_name = "rsa";
1865 type = key_type_from_name(key_type_name);
1866 if (type == KEY_UNSPEC) {
1867 fprintf(stderr, "unknown key type %s\n", key_type_name);
1868 exit(1);
1870 if (bits == 0)
1871 bits = (type == KEY_DSA) ? DEFAULT_BITS_DSA : DEFAULT_BITS;
1872 if (type == KEY_DSA && bits != 1024)
1873 fatal("DSA keys must be 1024 bits");
1874 if (!quiet)
1875 printf("Generating public/private %s key pair.\n", key_type_name);
1876 private = key_generate(type, bits);
1877 if (private == NULL) {
1878 fprintf(stderr, "key_generate failed\n");
1879 exit(1);
1881 public = key_from_private(private);
1883 if (!have_identity)
1884 ask_filename(pw, "Enter file in which to save the key");
1886 /* Create ~/.ssh directory if it doesn't already exist. */
1887 snprintf(dotsshdir, sizeof dotsshdir, "%s/%s", pw->pw_dir, _PATH_SSH_USER_DIR);
1888 if (strstr(identity_file, dotsshdir) != NULL &&
1889 stat(dotsshdir, &st) < 0) {
1890 if (mkdir(dotsshdir, 0700) < 0)
1891 error("Could not create directory '%s'.", dotsshdir);
1892 else if (!quiet)
1893 printf("Created directory '%s'.\n", dotsshdir);
1895 /* If the file already exists, ask the user to confirm. */
1896 if (stat(identity_file, &st) >= 0) {
1897 char yesno[3];
1898 printf("%s already exists.\n", identity_file);
1899 printf("Overwrite (y/n)? ");
1900 fflush(stdout);
1901 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
1902 exit(1);
1903 if (yesno[0] != 'y' && yesno[0] != 'Y')
1904 exit(1);
1906 /* Ask for a passphrase (twice). */
1907 if (identity_passphrase)
1908 passphrase1 = xstrdup(identity_passphrase);
1909 else if (identity_new_passphrase)
1910 passphrase1 = xstrdup(identity_new_passphrase);
1911 else {
1912 passphrase_again:
1913 passphrase1 =
1914 read_passphrase("Enter passphrase (empty for no "
1915 "passphrase): ", RP_ALLOW_STDIN);
1916 passphrase2 = read_passphrase("Enter same passphrase again: ",
1917 RP_ALLOW_STDIN);
1918 if (strcmp(passphrase1, passphrase2) != 0) {
1920 * The passphrases do not match. Clear them and
1921 * retry.
1923 memset(passphrase1, 0, strlen(passphrase1));
1924 memset(passphrase2, 0, strlen(passphrase2));
1925 xfree(passphrase1);
1926 xfree(passphrase2);
1927 printf("Passphrases do not match. Try again.\n");
1928 goto passphrase_again;
1930 /* Clear the other copy of the passphrase. */
1931 memset(passphrase2, 0, strlen(passphrase2));
1932 xfree(passphrase2);
1935 if (identity_comment) {
1936 strlcpy(comment, identity_comment, sizeof(comment));
1937 } else {
1938 /* Create default comment field for the passphrase. */
1939 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
1942 /* Save the key with the given passphrase and comment. */
1943 if (!key_save_private(private, identity_file, passphrase1, comment)) {
1944 printf("Saving the key failed: %s.\n", identity_file);
1945 memset(passphrase1, 0, strlen(passphrase1));
1946 xfree(passphrase1);
1947 exit(1);
1949 /* Clear the passphrase. */
1950 memset(passphrase1, 0, strlen(passphrase1));
1951 xfree(passphrase1);
1953 /* Clear the private key and the random number generator. */
1954 key_free(private);
1955 arc4random_stir();
1957 if (!quiet)
1958 printf("Your identification has been saved in %s.\n", identity_file);
1960 strlcat(identity_file, ".pub", sizeof(identity_file));
1961 fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1962 if (fd == -1) {
1963 printf("Could not save your public key in %s\n", identity_file);
1964 exit(1);
1966 f = fdopen(fd, "w");
1967 if (f == NULL) {
1968 printf("fdopen %s failed\n", identity_file);
1969 exit(1);
1971 if (!key_write(public, f))
1972 fprintf(stderr, "write key failed\n");
1973 fprintf(f, " %s\n", comment);
1974 fclose(f);
1976 if (!quiet) {
1977 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
1978 char *ra = key_fingerprint(public, SSH_FP_MD5,
1979 SSH_FP_RANDOMART);
1980 printf("Your public key has been saved in %s.\n",
1981 identity_file);
1982 printf("The key fingerprint is:\n");
1983 printf("%s %s\n", fp, comment);
1984 printf("The key's randomart image is:\n");
1985 printf("%s\n", ra);
1986 xfree(ra);
1987 xfree(fp);
1990 key_free(public);
1991 exit(0);