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