xref: /openbsd-src/usr.bin/ssh/ssh-keygen.c (revision 8500990981f885cbe5e6a4958549cacc238b5ae6)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Identity and host key generation and maintenance.
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  */
13 
14 #include "includes.h"
15 RCSID("$OpenBSD: ssh-keygen.c,v 1.112 2003/11/23 23:18:45 djm Exp $");
16 
17 #include <openssl/evp.h>
18 #include <openssl/pem.h>
19 
20 #include "xmalloc.h"
21 #include "key.h"
22 #include "rsa.h"
23 #include "authfile.h"
24 #include "uuencode.h"
25 #include "buffer.h"
26 #include "bufaux.h"
27 #include "pathnames.h"
28 #include "log.h"
29 #include "readpass.h"
30 #include "moduli.h"
31 
32 #ifdef SMARTCARD
33 #include "scard.h"
34 #endif
35 #include "dns.h"
36 
37 /* Number of bits in the RSA/DSA key.  This value can be changed on the command line. */
38 int bits = 1024;
39 
40 /*
41  * Flag indicating that we just want to change the passphrase.  This can be
42  * set on the command line.
43  */
44 int change_passphrase = 0;
45 
46 /*
47  * Flag indicating that we just want to change the comment.  This can be set
48  * on the command line.
49  */
50 int change_comment = 0;
51 
52 int quiet = 0;
53 
54 /* Flag indicating that we just want to see the key fingerprint */
55 int print_fingerprint = 0;
56 int print_bubblebabble = 0;
57 
58 /* The identity file name, given on the command line or entered by the user. */
59 char identity_file[1024];
60 int have_identity = 0;
61 
62 /* This is set to the passphrase if given on the command line. */
63 char *identity_passphrase = NULL;
64 
65 /* This is set to the new passphrase if given on the command line. */
66 char *identity_new_passphrase = NULL;
67 
68 /* This is set to the new comment if given on the command line. */
69 char *identity_comment = NULL;
70 
71 /* Dump public key file in format used by real and the original SSH 2 */
72 int convert_to_ssh2 = 0;
73 int convert_from_ssh2 = 0;
74 int print_public = 0;
75 int print_generic = 0;
76 
77 char *key_type_name = NULL;
78 
79 /* argv0 */
80 extern char *__progname;
81 
82 char hostname[MAXHOSTNAMELEN];
83 
84 static void
85 ask_filename(struct passwd *pw, const char *prompt)
86 {
87 	char buf[1024];
88 	char *name = NULL;
89 
90 	if (key_type_name == NULL)
91 		name = _PATH_SSH_CLIENT_ID_RSA;
92 	else
93 		switch (key_type_from_name(key_type_name)) {
94 		case KEY_RSA1:
95 			name = _PATH_SSH_CLIENT_IDENTITY;
96 			break;
97 		case KEY_DSA:
98 			name = _PATH_SSH_CLIENT_ID_DSA;
99 			break;
100 		case KEY_RSA:
101 			name = _PATH_SSH_CLIENT_ID_RSA;
102 			break;
103 		default:
104 			fprintf(stderr, "bad key type");
105 			exit(1);
106 			break;
107 		}
108 
109 	snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
110 	fprintf(stderr, "%s (%s): ", prompt, identity_file);
111 	if (fgets(buf, sizeof(buf), stdin) == NULL)
112 		exit(1);
113 	if (strchr(buf, '\n'))
114 		*strchr(buf, '\n') = 0;
115 	if (strcmp(buf, "") != 0)
116 		strlcpy(identity_file, buf, sizeof(identity_file));
117 	have_identity = 1;
118 }
119 
120 static Key *
121 load_identity(char *filename)
122 {
123 	char *pass;
124 	Key *prv;
125 
126 	prv = key_load_private(filename, "", NULL);
127 	if (prv == NULL) {
128 		if (identity_passphrase)
129 			pass = xstrdup(identity_passphrase);
130 		else
131 			pass = read_passphrase("Enter passphrase: ",
132 			    RP_ALLOW_STDIN);
133 		prv = key_load_private(filename, pass, NULL);
134 		memset(pass, 0, strlen(pass));
135 		xfree(pass);
136 	}
137 	return prv;
138 }
139 
140 #define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
141 #define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
142 #define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
143 #define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
144 
145 static void
146 do_convert_to_ssh2(struct passwd *pw)
147 {
148 	Key *k;
149 	u_int len;
150 	u_char *blob;
151 	struct stat st;
152 
153 	if (!have_identity)
154 		ask_filename(pw, "Enter file in which the key is");
155 	if (stat(identity_file, &st) < 0) {
156 		perror(identity_file);
157 		exit(1);
158 	}
159 	if ((k = key_load_public(identity_file, NULL)) == NULL) {
160 		if ((k = load_identity(identity_file)) == NULL) {
161 			fprintf(stderr, "load failed\n");
162 			exit(1);
163 		}
164 	}
165 	if (k->type == KEY_RSA1) {
166 		fprintf(stderr, "version 1 keys are not supported\n");
167 		exit(1);
168 	}
169 	if (key_to_blob(k, &blob, &len) <= 0) {
170 		fprintf(stderr, "key_to_blob failed\n");
171 		exit(1);
172 	}
173 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
174 	fprintf(stdout,
175 	    "Comment: \"%u-bit %s, converted from OpenSSH by %s@%s\"\n",
176 	    key_size(k), key_type(k),
177 	    pw->pw_name, hostname);
178 	dump_base64(stdout, blob, len);
179 	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
180 	key_free(k);
181 	xfree(blob);
182 	exit(0);
183 }
184 
185 static void
186 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
187 {
188 	u_int bits = buffer_get_int(b);
189 	u_int bytes = (bits + 7) / 8;
190 
191 	if (buffer_len(b) < bytes)
192 		fatal("buffer_get_bignum_bits: input buffer too small: "
193 		    "need %d have %d", bytes, buffer_len(b));
194 	BN_bin2bn(buffer_ptr(b), bytes, value);
195 	buffer_consume(b, bytes);
196 }
197 
198 static Key *
199 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
200 {
201 	Buffer b;
202 	Key *key = NULL;
203 	char *type, *cipher;
204 	u_char *sig, data[] = "abcde12345";
205 	int magic, rlen, ktype, i1, i2, i3, i4;
206 	u_int slen;
207 	u_long e;
208 
209 	buffer_init(&b);
210 	buffer_append(&b, blob, blen);
211 
212 	magic  = buffer_get_int(&b);
213 	if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
214 		error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
215 		buffer_free(&b);
216 		return NULL;
217 	}
218 	i1 = buffer_get_int(&b);
219 	type   = buffer_get_string(&b, NULL);
220 	cipher = buffer_get_string(&b, NULL);
221 	i2 = buffer_get_int(&b);
222 	i3 = buffer_get_int(&b);
223 	i4 = buffer_get_int(&b);
224 	debug("ignore (%d %d %d %d)", i1,i2,i3,i4);
225 	if (strcmp(cipher, "none") != 0) {
226 		error("unsupported cipher %s", cipher);
227 		xfree(cipher);
228 		buffer_free(&b);
229 		xfree(type);
230 		return NULL;
231 	}
232 	xfree(cipher);
233 
234 	if (strstr(type, "dsa")) {
235 		ktype = KEY_DSA;
236 	} else if (strstr(type, "rsa")) {
237 		ktype = KEY_RSA;
238 	} else {
239 		xfree(type);
240 		return NULL;
241 	}
242 	key = key_new_private(ktype);
243 	xfree(type);
244 
245 	switch (key->type) {
246 	case KEY_DSA:
247 		buffer_get_bignum_bits(&b, key->dsa->p);
248 		buffer_get_bignum_bits(&b, key->dsa->g);
249 		buffer_get_bignum_bits(&b, key->dsa->q);
250 		buffer_get_bignum_bits(&b, key->dsa->pub_key);
251 		buffer_get_bignum_bits(&b, key->dsa->priv_key);
252 		break;
253 	case KEY_RSA:
254 		e  = buffer_get_char(&b);
255 		debug("e %lx", e);
256 		if (e < 30) {
257 			e <<= 8;
258 			e += buffer_get_char(&b);
259 			debug("e %lx", e);
260 			e <<= 8;
261 			e += buffer_get_char(&b);
262 			debug("e %lx", e);
263 		}
264 		if (!BN_set_word(key->rsa->e, e)) {
265 			buffer_free(&b);
266 			key_free(key);
267 			return NULL;
268 		}
269 		buffer_get_bignum_bits(&b, key->rsa->d);
270 		buffer_get_bignum_bits(&b, key->rsa->n);
271 		buffer_get_bignum_bits(&b, key->rsa->iqmp);
272 		buffer_get_bignum_bits(&b, key->rsa->q);
273 		buffer_get_bignum_bits(&b, key->rsa->p);
274 		rsa_generate_additional_parameters(key->rsa);
275 		break;
276 	}
277 	rlen = buffer_len(&b);
278 	if (rlen != 0)
279 		error("do_convert_private_ssh2_from_blob: "
280 		    "remaining bytes in key blob %d", rlen);
281 	buffer_free(&b);
282 
283 	/* try the key */
284 	key_sign(key, &sig, &slen, data, sizeof(data));
285 	key_verify(key, sig, slen, data, sizeof(data));
286 	xfree(sig);
287 	return key;
288 }
289 
290 static void
291 do_convert_from_ssh2(struct passwd *pw)
292 {
293 	Key *k;
294 	int blen;
295 	u_int len;
296 	char line[1024], *p;
297 	u_char blob[8096];
298 	char encoded[8096];
299 	struct stat st;
300 	int escaped = 0, private = 0, ok;
301 	FILE *fp;
302 
303 	if (!have_identity)
304 		ask_filename(pw, "Enter file in which the key is");
305 	if (stat(identity_file, &st) < 0) {
306 		perror(identity_file);
307 		exit(1);
308 	}
309 	fp = fopen(identity_file, "r");
310 	if (fp == NULL) {
311 		perror(identity_file);
312 		exit(1);
313 	}
314 	encoded[0] = '\0';
315 	while (fgets(line, sizeof(line), fp)) {
316 		if (!(p = strchr(line, '\n'))) {
317 			fprintf(stderr, "input line too long.\n");
318 			exit(1);
319 		}
320 		if (p > line && p[-1] == '\\')
321 			escaped++;
322 		if (strncmp(line, "----", 4) == 0 ||
323 		    strstr(line, ": ") != NULL) {
324 			if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
325 				private = 1;
326 			if (strstr(line, " END ") != NULL) {
327 				break;
328 			}
329 			/* fprintf(stderr, "ignore: %s", line); */
330 			continue;
331 		}
332 		if (escaped) {
333 			escaped--;
334 			/* fprintf(stderr, "escaped: %s", line); */
335 			continue;
336 		}
337 		*p = '\0';
338 		strlcat(encoded, line, sizeof(encoded));
339 	}
340 	len = strlen(encoded);
341 	if (((len % 4) == 3) &&
342 	    (encoded[len-1] == '=') &&
343 	    (encoded[len-2] == '=') &&
344 	    (encoded[len-3] == '='))
345 		encoded[len-3] = '\0';
346 	blen = uudecode(encoded, blob, sizeof(blob));
347 	if (blen < 0) {
348 		fprintf(stderr, "uudecode failed.\n");
349 		exit(1);
350 	}
351 	k = private ?
352 	    do_convert_private_ssh2_from_blob(blob, blen) :
353 	    key_from_blob(blob, blen);
354 	if (k == NULL) {
355 		fprintf(stderr, "decode blob failed.\n");
356 		exit(1);
357 	}
358 	ok = private ?
359 	    (k->type == KEY_DSA ?
360 		 PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, NULL, 0, NULL, NULL) :
361 		 PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, NULL, 0, NULL, NULL)) :
362 	    key_write(k, stdout);
363 	if (!ok) {
364 		fprintf(stderr, "key write failed");
365 		exit(1);
366 	}
367 	key_free(k);
368 	if (!private)
369 		fprintf(stdout, "\n");
370 	fclose(fp);
371 	exit(0);
372 }
373 
374 static void
375 do_print_public(struct passwd *pw)
376 {
377 	Key *prv;
378 	struct stat st;
379 
380 	if (!have_identity)
381 		ask_filename(pw, "Enter file in which the key is");
382 	if (stat(identity_file, &st) < 0) {
383 		perror(identity_file);
384 		exit(1);
385 	}
386 	prv = load_identity(identity_file);
387 	if (prv == NULL) {
388 		fprintf(stderr, "load failed\n");
389 		exit(1);
390 	}
391 	if (!key_write(prv, stdout))
392 		fprintf(stderr, "key_write failed");
393 	key_free(prv);
394 	fprintf(stdout, "\n");
395 	exit(0);
396 }
397 
398 #ifdef SMARTCARD
399 static void
400 do_upload(struct passwd *pw, const char *sc_reader_id)
401 {
402 	Key *prv = NULL;
403 	struct stat st;
404 	int ret;
405 
406 	if (!have_identity)
407 		ask_filename(pw, "Enter file in which the key is");
408 	if (stat(identity_file, &st) < 0) {
409 		perror(identity_file);
410 		exit(1);
411 	}
412 	prv = load_identity(identity_file);
413 	if (prv == NULL) {
414 		error("load failed");
415 		exit(1);
416 	}
417 	ret = sc_put_key(prv, sc_reader_id);
418 	key_free(prv);
419 	if (ret < 0)
420 		exit(1);
421 	logit("loading key done");
422 	exit(0);
423 }
424 
425 static void
426 do_download(struct passwd *pw, const char *sc_reader_id)
427 {
428 	Key **keys = NULL;
429 	int i;
430 
431 	keys = sc_get_keys(sc_reader_id, NULL);
432 	if (keys == NULL)
433 		fatal("cannot read public key from smartcard");
434 	for (i = 0; keys[i]; i++) {
435 		key_write(keys[i], stdout);
436 		key_free(keys[i]);
437 		fprintf(stdout, "\n");
438 	}
439 	xfree(keys);
440 	exit(0);
441 }
442 #endif /* SMARTCARD */
443 
444 static void
445 do_fingerprint(struct passwd *pw)
446 {
447 	FILE *f;
448 	Key *public;
449 	char *comment = NULL, *cp, *ep, line[16*1024], *fp;
450 	int i, skip = 0, num = 1, invalid = 1;
451 	enum fp_rep rep;
452 	enum fp_type fptype;
453 	struct stat st;
454 
455 	fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
456 	rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
457 
458 	if (!have_identity)
459 		ask_filename(pw, "Enter file in which the key is");
460 	if (stat(identity_file, &st) < 0) {
461 		perror(identity_file);
462 		exit(1);
463 	}
464 	public = key_load_public(identity_file, &comment);
465 	if (public != NULL) {
466 		fp = key_fingerprint(public, fptype, rep);
467 		printf("%u %s %s\n", key_size(public), fp, comment);
468 		key_free(public);
469 		xfree(comment);
470 		xfree(fp);
471 		exit(0);
472 	}
473 	if (comment)
474 		xfree(comment);
475 
476 	f = fopen(identity_file, "r");
477 	if (f != NULL) {
478 		while (fgets(line, sizeof(line), f)) {
479 			i = strlen(line) - 1;
480 			if (line[i] != '\n') {
481 				error("line %d too long: %.40s...", num, line);
482 				skip = 1;
483 				continue;
484 			}
485 			num++;
486 			if (skip) {
487 				skip = 0;
488 				continue;
489 			}
490 			line[i] = '\0';
491 
492 			/* Skip leading whitespace, empty and comment lines. */
493 			for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
494 				;
495 			if (!*cp || *cp == '\n' || *cp == '#')
496 				continue ;
497 			i = strtol(cp, &ep, 10);
498 			if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
499 				int quoted = 0;
500 				comment = cp;
501 				for (; *cp && (quoted || (*cp != ' ' &&
502 				    *cp != '\t')); cp++) {
503 					if (*cp == '\\' && cp[1] == '"')
504 						cp++;	/* Skip both */
505 					else if (*cp == '"')
506 						quoted = !quoted;
507 				}
508 				if (!*cp)
509 					continue;
510 				*cp++ = '\0';
511 			}
512 			ep = cp;
513 			public = key_new(KEY_RSA1);
514 			if (key_read(public, &cp) != 1) {
515 				cp = ep;
516 				key_free(public);
517 				public = key_new(KEY_UNSPEC);
518 				if (key_read(public, &cp) != 1) {
519 					key_free(public);
520 					continue;
521 				}
522 			}
523 			comment = *cp ? cp : comment;
524 			fp = key_fingerprint(public, fptype, rep);
525 			printf("%u %s %s\n", key_size(public), fp,
526 			    comment ? comment : "no comment");
527 			xfree(fp);
528 			key_free(public);
529 			invalid = 0;
530 		}
531 		fclose(f);
532 	}
533 	if (invalid) {
534 		printf("%s is not a public key file.\n", identity_file);
535 		exit(1);
536 	}
537 	exit(0);
538 }
539 
540 /*
541  * Perform changing a passphrase.  The argument is the passwd structure
542  * for the current user.
543  */
544 static void
545 do_change_passphrase(struct passwd *pw)
546 {
547 	char *comment;
548 	char *old_passphrase, *passphrase1, *passphrase2;
549 	struct stat st;
550 	Key *private;
551 
552 	if (!have_identity)
553 		ask_filename(pw, "Enter file in which the key is");
554 	if (stat(identity_file, &st) < 0) {
555 		perror(identity_file);
556 		exit(1);
557 	}
558 	/* Try to load the file with empty passphrase. */
559 	private = key_load_private(identity_file, "", &comment);
560 	if (private == NULL) {
561 		if (identity_passphrase)
562 			old_passphrase = xstrdup(identity_passphrase);
563 		else
564 			old_passphrase =
565 			    read_passphrase("Enter old passphrase: ",
566 			    RP_ALLOW_STDIN);
567 		private = key_load_private(identity_file, old_passphrase,
568 		    &comment);
569 		memset(old_passphrase, 0, strlen(old_passphrase));
570 		xfree(old_passphrase);
571 		if (private == NULL) {
572 			printf("Bad passphrase.\n");
573 			exit(1);
574 		}
575 	}
576 	printf("Key has comment '%s'\n", comment);
577 
578 	/* Ask the new passphrase (twice). */
579 	if (identity_new_passphrase) {
580 		passphrase1 = xstrdup(identity_new_passphrase);
581 		passphrase2 = NULL;
582 	} else {
583 		passphrase1 =
584 			read_passphrase("Enter new passphrase (empty for no "
585 			    "passphrase): ", RP_ALLOW_STDIN);
586 		passphrase2 = read_passphrase("Enter same passphrase again: ",
587 		    RP_ALLOW_STDIN);
588 
589 		/* Verify that they are the same. */
590 		if (strcmp(passphrase1, passphrase2) != 0) {
591 			memset(passphrase1, 0, strlen(passphrase1));
592 			memset(passphrase2, 0, strlen(passphrase2));
593 			xfree(passphrase1);
594 			xfree(passphrase2);
595 			printf("Pass phrases do not match.  Try again.\n");
596 			exit(1);
597 		}
598 		/* Destroy the other copy. */
599 		memset(passphrase2, 0, strlen(passphrase2));
600 		xfree(passphrase2);
601 	}
602 
603 	/* Save the file using the new passphrase. */
604 	if (!key_save_private(private, identity_file, passphrase1, comment)) {
605 		printf("Saving the key failed: %s.\n", identity_file);
606 		memset(passphrase1, 0, strlen(passphrase1));
607 		xfree(passphrase1);
608 		key_free(private);
609 		xfree(comment);
610 		exit(1);
611 	}
612 	/* Destroy the passphrase and the copy of the key in memory. */
613 	memset(passphrase1, 0, strlen(passphrase1));
614 	xfree(passphrase1);
615 	key_free(private);		 /* Destroys contents */
616 	xfree(comment);
617 
618 	printf("Your identification has been saved with the new passphrase.\n");
619 	exit(0);
620 }
621 
622 /*
623  * Print the SSHFP RR.
624  */
625 static void
626 do_print_resource_record(struct passwd *pw, char *hostname)
627 {
628 	Key *public;
629 	char *comment = NULL;
630 	struct stat st;
631 
632 	if (!have_identity)
633 		ask_filename(pw, "Enter file in which the key is");
634 	if (stat(identity_file, &st) < 0) {
635 		perror(identity_file);
636 		exit(1);
637 	}
638 	public = key_load_public(identity_file, &comment);
639 	if (public != NULL) {
640 		export_dns_rr(hostname, public, stdout, print_generic);
641 		key_free(public);
642 		xfree(comment);
643 		exit(0);
644 	}
645 	if (comment)
646 		xfree(comment);
647 
648 	printf("failed to read v2 public key from %s.\n", identity_file);
649 	exit(1);
650 }
651 
652 /*
653  * Change the comment of a private key file.
654  */
655 static void
656 do_change_comment(struct passwd *pw)
657 {
658 	char new_comment[1024], *comment, *passphrase;
659 	Key *private;
660 	Key *public;
661 	struct stat st;
662 	FILE *f;
663 	int fd;
664 
665 	if (!have_identity)
666 		ask_filename(pw, "Enter file in which the key is");
667 	if (stat(identity_file, &st) < 0) {
668 		perror(identity_file);
669 		exit(1);
670 	}
671 	private = key_load_private(identity_file, "", &comment);
672 	if (private == NULL) {
673 		if (identity_passphrase)
674 			passphrase = xstrdup(identity_passphrase);
675 		else if (identity_new_passphrase)
676 			passphrase = xstrdup(identity_new_passphrase);
677 		else
678 			passphrase = read_passphrase("Enter passphrase: ",
679 			    RP_ALLOW_STDIN);
680 		/* Try to load using the passphrase. */
681 		private = key_load_private(identity_file, passphrase, &comment);
682 		if (private == NULL) {
683 			memset(passphrase, 0, strlen(passphrase));
684 			xfree(passphrase);
685 			printf("Bad passphrase.\n");
686 			exit(1);
687 		}
688 	} else {
689 		passphrase = xstrdup("");
690 	}
691 	if (private->type != KEY_RSA1) {
692 		fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
693 		key_free(private);
694 		exit(1);
695 	}
696 	printf("Key now has comment '%s'\n", comment);
697 
698 	if (identity_comment) {
699 		strlcpy(new_comment, identity_comment, sizeof(new_comment));
700 	} else {
701 		printf("Enter new comment: ");
702 		fflush(stdout);
703 		if (!fgets(new_comment, sizeof(new_comment), stdin)) {
704 			memset(passphrase, 0, strlen(passphrase));
705 			key_free(private);
706 			exit(1);
707 		}
708 		if (strchr(new_comment, '\n'))
709 			*strchr(new_comment, '\n') = 0;
710 	}
711 
712 	/* Save the file using the new passphrase. */
713 	if (!key_save_private(private, identity_file, passphrase, new_comment)) {
714 		printf("Saving the key failed: %s.\n", identity_file);
715 		memset(passphrase, 0, strlen(passphrase));
716 		xfree(passphrase);
717 		key_free(private);
718 		xfree(comment);
719 		exit(1);
720 	}
721 	memset(passphrase, 0, strlen(passphrase));
722 	xfree(passphrase);
723 	public = key_from_private(private);
724 	key_free(private);
725 
726 	strlcat(identity_file, ".pub", sizeof(identity_file));
727 	fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
728 	if (fd == -1) {
729 		printf("Could not save your public key in %s\n", identity_file);
730 		exit(1);
731 	}
732 	f = fdopen(fd, "w");
733 	if (f == NULL) {
734 		printf("fdopen %s failed", identity_file);
735 		exit(1);
736 	}
737 	if (!key_write(public, f))
738 		fprintf(stderr, "write key failed");
739 	key_free(public);
740 	fprintf(f, " %s\n", new_comment);
741 	fclose(f);
742 
743 	xfree(comment);
744 
745 	printf("The comment in your key file has been changed.\n");
746 	exit(0);
747 }
748 
749 static void
750 usage(void)
751 {
752 	fprintf(stderr, "Usage: %s [options]\n", __progname);
753 	fprintf(stderr, "Options:\n");
754 	fprintf(stderr, "  -b bits     Number of bits in the key to create.\n");
755 	fprintf(stderr, "  -c          Change comment in private and public key files.\n");
756 	fprintf(stderr, "  -e          Convert OpenSSH to IETF SECSH key file.\n");
757 	fprintf(stderr, "  -f filename Filename of the key file.\n");
758 	fprintf(stderr, "  -g          Use generic DNS resource record format.\n");
759 	fprintf(stderr, "  -i          Convert IETF SECSH to OpenSSH key file.\n");
760 	fprintf(stderr, "  -l          Show fingerprint of key file.\n");
761 	fprintf(stderr, "  -p          Change passphrase of private key file.\n");
762 	fprintf(stderr, "  -q          Quiet.\n");
763 	fprintf(stderr, "  -y          Read private key file and print public key.\n");
764 	fprintf(stderr, "  -t type     Specify type of key to create.\n");
765 	fprintf(stderr, "  -B          Show bubblebabble digest of key file.\n");
766 	fprintf(stderr, "  -C comment  Provide new comment.\n");
767 	fprintf(stderr, "  -N phrase   Provide new passphrase.\n");
768 	fprintf(stderr, "  -P phrase   Provide old passphrase.\n");
769 	fprintf(stderr, "  -r hostname Print DNS resource record.\n");
770 #ifdef SMARTCARD
771 	fprintf(stderr, "  -D reader   Download public key from smartcard.\n");
772 	fprintf(stderr, "  -U reader   Upload private key to smartcard.\n");
773 #endif /* SMARTCARD */
774 
775 	fprintf(stderr, "  -G file     Generate candidates for DH-GEX moduli\n");
776 	fprintf(stderr, "  -T file     Screen candidates for DH-GEX moduli\n");
777 
778 	exit(1);
779 }
780 
781 /*
782  * Main program for key management.
783  */
784 int
785 main(int ac, char **av)
786 {
787 	char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
788 	char out_file[MAXPATHLEN], *reader_id = NULL;
789 	char *resource_record_hostname = NULL;
790 	Key *private, *public;
791 	struct passwd *pw;
792 	struct stat st;
793 	int opt, type, fd, download = 0, memory = 0;
794 	int generator_wanted = 0, trials = 100;
795 	int do_gen_candidates = 0, do_screen_candidates = 0;
796 	BIGNUM *start = NULL;
797 	FILE *f;
798 
799 	extern int optind;
800 	extern char *optarg;
801 
802 	SSLeay_add_all_algorithms();
803 	log_init(av[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
804 
805 	/* we need this for the home * directory.  */
806 	pw = getpwuid(getuid());
807 	if (!pw) {
808 		printf("You don't exist, go away!\n");
809 		exit(1);
810 	}
811 	if (gethostname(hostname, sizeof(hostname)) < 0) {
812 		perror("gethostname");
813 		exit(1);
814 	}
815 
816 	while ((opt = getopt(ac, av,
817 	    "degiqpclBRxXyb:f:t:U:D:P:N:C:r:g:T:G:M:S:a:W:")) != -1) {
818 		switch (opt) {
819 		case 'b':
820 			bits = atoi(optarg);
821 			if (bits < 512 || bits > 32768) {
822 				printf("Bits has bad value.\n");
823 				exit(1);
824 			}
825 			break;
826 		case 'l':
827 			print_fingerprint = 1;
828 			break;
829 		case 'B':
830 			print_bubblebabble = 1;
831 			break;
832 		case 'p':
833 			change_passphrase = 1;
834 			break;
835 		case 'c':
836 			change_comment = 1;
837 			break;
838 		case 'f':
839 			strlcpy(identity_file, optarg, sizeof(identity_file));
840 			have_identity = 1;
841 			break;
842 		case 'g':
843 			print_generic = 1;
844 			break;
845 		case 'P':
846 			identity_passphrase = optarg;
847 			break;
848 		case 'N':
849 			identity_new_passphrase = optarg;
850 			break;
851 		case 'C':
852 			identity_comment = optarg;
853 			break;
854 		case 'q':
855 			quiet = 1;
856 			break;
857 		case 'R':
858 			/* unused */
859 			exit(0);
860 			break;
861 		case 'e':
862 		case 'x':
863 			/* export key */
864 			convert_to_ssh2 = 1;
865 			break;
866 		case 'i':
867 		case 'X':
868 			/* import key */
869 			convert_from_ssh2 = 1;
870 			break;
871 		case 'y':
872 			print_public = 1;
873 			break;
874 		case 'd':
875 			key_type_name = "dsa";
876 			break;
877 		case 't':
878 			key_type_name = optarg;
879 			break;
880 		case 'D':
881 			download = 1;
882 		case 'U':
883 			reader_id = optarg;
884 			break;
885 		case 'r':
886 			resource_record_hostname = optarg;
887 			break;
888 		case 'W':
889 			generator_wanted = atoi(optarg);
890 			if (generator_wanted < 1)
891 				fatal("Desired generator has bad value.");
892 			break;
893 		case 'a':
894 			trials = atoi(optarg);
895 			if (trials < TRIAL_MINIMUM) {
896 				fatal("Minimum primality trials is %d",
897 				    TRIAL_MINIMUM);
898 			}
899 			break;
900 		case 'M':
901 			memory = atoi(optarg);
902 			if (memory != 0 &&
903 			   (memory < LARGE_MINIMUM || memory > LARGE_MAXIMUM)) {
904 				fatal("Invalid memory amount (min %ld, max %ld)",
905 				    LARGE_MINIMUM, LARGE_MAXIMUM);
906 			}
907 			break;
908 		case 'G':
909 			do_gen_candidates = 1;
910 			strlcpy(out_file, optarg, sizeof(out_file));
911 			break;
912 		case 'T':
913 			do_screen_candidates = 1;
914 			strlcpy(out_file, optarg, sizeof(out_file));
915 			break;
916 		case 'S':
917 			/* XXX - also compare length against bits */
918 			if (BN_hex2bn(&start, optarg) == 0)
919 				fatal("Invalid start point.");
920 			break;
921 		case '?':
922 		default:
923 			usage();
924 		}
925 	}
926 	if (optind < ac) {
927 		printf("Too many arguments.\n");
928 		usage();
929 	}
930 	if (change_passphrase && change_comment) {
931 		printf("Can only have one of -p and -c.\n");
932 		usage();
933 	}
934 	if (print_fingerprint || print_bubblebabble)
935 		do_fingerprint(pw);
936 	if (change_passphrase)
937 		do_change_passphrase(pw);
938 	if (change_comment)
939 		do_change_comment(pw);
940 	if (convert_to_ssh2)
941 		do_convert_to_ssh2(pw);
942 	if (convert_from_ssh2)
943 		do_convert_from_ssh2(pw);
944 	if (print_public)
945 		do_print_public(pw);
946 	if (resource_record_hostname != NULL) {
947 		do_print_resource_record(pw, resource_record_hostname);
948 	}
949 	if (reader_id != NULL) {
950 #ifdef SMARTCARD
951 		if (download)
952 			do_download(pw, reader_id);
953 		else
954 			do_upload(pw, reader_id);
955 #else /* SMARTCARD */
956 		fatal("no support for smartcards.");
957 #endif /* SMARTCARD */
958 	}
959 
960 	if (do_gen_candidates) {
961 		FILE *out = fopen(out_file, "w");
962 
963 		if (out == NULL) {
964 			error("Couldn't open modulus candidate file \"%s\": %s",
965 			    out_file, strerror(errno));
966 			return (1);
967 		}
968 		if (gen_candidates(out, memory, bits, start) != 0)
969 			fatal("modulus candidate generation failed\n");
970 
971 		return (0);
972 	}
973 
974 	if (do_screen_candidates) {
975 		FILE *in;
976 		FILE *out = fopen(out_file, "w");
977 
978 		if (have_identity && strcmp(identity_file, "-") != 0) {
979 			if ((in = fopen(identity_file, "r")) == NULL) {
980 				fatal("Couldn't open modulus candidate "
981 				    "file \"%s\": %s", identity_file,
982 				    strerror(errno));
983 			}
984 		} else
985 			in = stdin;
986 
987 		if (out == NULL) {
988 			fatal("Couldn't open moduli file \"%s\": %s",
989 			    out_file, strerror(errno));
990 		}
991 		if (prime_test(in, out, trials, generator_wanted) != 0)
992 			fatal("modulus screening failed\n");
993 		return (0);
994 	}
995 
996 	arc4random_stir();
997 
998 	if (key_type_name == NULL) {
999 		printf("You must specify a key type (-t).\n");
1000 		usage();
1001 	}
1002 	type = key_type_from_name(key_type_name);
1003 	if (type == KEY_UNSPEC) {
1004 		fprintf(stderr, "unknown key type %s\n", key_type_name);
1005 		exit(1);
1006 	}
1007 	if (!quiet)
1008 		printf("Generating public/private %s key pair.\n", key_type_name);
1009 	private = key_generate(type, bits);
1010 	if (private == NULL) {
1011 		fprintf(stderr, "key_generate failed");
1012 		exit(1);
1013 	}
1014 	public  = key_from_private(private);
1015 
1016 	if (!have_identity)
1017 		ask_filename(pw, "Enter file in which to save the key");
1018 
1019 	/* Create ~/.ssh directory if it doesn\'t already exist. */
1020 	snprintf(dotsshdir, sizeof dotsshdir, "%s/%s", pw->pw_dir, _PATH_SSH_USER_DIR);
1021 	if (strstr(identity_file, dotsshdir) != NULL &&
1022 	    stat(dotsshdir, &st) < 0) {
1023 		if (mkdir(dotsshdir, 0700) < 0)
1024 			error("Could not create directory '%s'.", dotsshdir);
1025 		else if (!quiet)
1026 			printf("Created directory '%s'.\n", dotsshdir);
1027 	}
1028 	/* If the file already exists, ask the user to confirm. */
1029 	if (stat(identity_file, &st) >= 0) {
1030 		char yesno[3];
1031 		printf("%s already exists.\n", identity_file);
1032 		printf("Overwrite (y/n)? ");
1033 		fflush(stdout);
1034 		if (fgets(yesno, sizeof(yesno), stdin) == NULL)
1035 			exit(1);
1036 		if (yesno[0] != 'y' && yesno[0] != 'Y')
1037 			exit(1);
1038 	}
1039 	/* Ask for a passphrase (twice). */
1040 	if (identity_passphrase)
1041 		passphrase1 = xstrdup(identity_passphrase);
1042 	else if (identity_new_passphrase)
1043 		passphrase1 = xstrdup(identity_new_passphrase);
1044 	else {
1045 passphrase_again:
1046 		passphrase1 =
1047 			read_passphrase("Enter passphrase (empty for no "
1048 			    "passphrase): ", RP_ALLOW_STDIN);
1049 		passphrase2 = read_passphrase("Enter same passphrase again: ",
1050 		    RP_ALLOW_STDIN);
1051 		if (strcmp(passphrase1, passphrase2) != 0) {
1052 			/*
1053 			 * The passphrases do not match.  Clear them and
1054 			 * retry.
1055 			 */
1056 			memset(passphrase1, 0, strlen(passphrase1));
1057 			memset(passphrase2, 0, strlen(passphrase2));
1058 			xfree(passphrase1);
1059 			xfree(passphrase2);
1060 			printf("Passphrases do not match.  Try again.\n");
1061 			goto passphrase_again;
1062 		}
1063 		/* Clear the other copy of the passphrase. */
1064 		memset(passphrase2, 0, strlen(passphrase2));
1065 		xfree(passphrase2);
1066 	}
1067 
1068 	if (identity_comment) {
1069 		strlcpy(comment, identity_comment, sizeof(comment));
1070 	} else {
1071 		/* Create default commend field for the passphrase. */
1072 		snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
1073 	}
1074 
1075 	/* Save the key with the given passphrase and comment. */
1076 	if (!key_save_private(private, identity_file, passphrase1, comment)) {
1077 		printf("Saving the key failed: %s.\n", identity_file);
1078 		memset(passphrase1, 0, strlen(passphrase1));
1079 		xfree(passphrase1);
1080 		exit(1);
1081 	}
1082 	/* Clear the passphrase. */
1083 	memset(passphrase1, 0, strlen(passphrase1));
1084 	xfree(passphrase1);
1085 
1086 	/* Clear the private key and the random number generator. */
1087 	key_free(private);
1088 	arc4random_stir();
1089 
1090 	if (!quiet)
1091 		printf("Your identification has been saved in %s.\n", identity_file);
1092 
1093 	strlcat(identity_file, ".pub", sizeof(identity_file));
1094 	fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1095 	if (fd == -1) {
1096 		printf("Could not save your public key in %s\n", identity_file);
1097 		exit(1);
1098 	}
1099 	f = fdopen(fd, "w");
1100 	if (f == NULL) {
1101 		printf("fdopen %s failed", identity_file);
1102 		exit(1);
1103 	}
1104 	if (!key_write(public, f))
1105 		fprintf(stderr, "write key failed");
1106 	fprintf(f, " %s\n", comment);
1107 	fclose(f);
1108 
1109 	if (!quiet) {
1110 		char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
1111 		printf("Your public key has been saved in %s.\n",
1112 		    identity_file);
1113 		printf("The key fingerprint is:\n");
1114 		printf("%s %s\n", fp, comment);
1115 		xfree(fp);
1116 	}
1117 
1118 	key_free(public);
1119 	exit(0);
1120 }
1121