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