ssh-keygen.c revision 98675
1189251Ssam/*
2189251Ssam * Author: Tatu Ylonen <ylo@cs.hut.fi>
3189251Ssam * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4189251Ssam *                    All rights reserved
5252726Srpaulo * Identity and host key generation and maintenance.
6252726Srpaulo *
7189251Ssam * As far as I am concerned, the code I have written for this software
8189251Ssam * can be used freely for any purpose.  Any derived versions of this
9189251Ssam * software must be clearly marked as such, and if the derived work is
10189251Ssam * incompatible with the protocol description in the RFC file, it must be
11189251Ssam * called by a name other than "ssh" or "Secure Shell".
12189251Ssam */
13189251Ssam
14189251Ssam#include "includes.h"
15189251SsamRCSID("$OpenBSD: ssh-keygen.c,v 1.100 2002/06/19 00:27:55 deraadt Exp $");
16189251Ssam
17189251Ssam#include <openssl/evp.h>
18189251Ssam#include <openssl/pem.h>
19189251Ssam
20189251Ssam#include "xmalloc.h"
21189251Ssam#include "key.h"
22189251Ssam#include "rsa.h"
23189251Ssam#include "authfile.h"
24189251Ssam#include "uuencode.h"
25189251Ssam#include "buffer.h"
26189251Ssam#include "bufaux.h"
27189251Ssam#include "pathnames.h"
28189251Ssam#include "log.h"
29189251Ssam#include "readpass.h"
30189251Ssam
31189251Ssam#ifdef SMARTCARD
32189251Ssam#include "scard.h"
33189251Ssam#endif
34189251Ssam
35189251Ssam/* Number of bits in the RSA/DSA key.  This value can be changed on the command line. */
36189251Ssamint bits = 1024;
37189251Ssam
38189251Ssam/*
39189251Ssam * Flag indicating that we just want to change the passphrase.  This can be
40189251Ssam * set on the command line.
41189251Ssam */
42189251Ssamint change_passphrase = 0;
43189251Ssam
44189251Ssam/*
45189251Ssam * Flag indicating that we just want to change the comment.  This can be set
46189251Ssam * on the command line.
47189251Ssam */
48189251Ssamint change_comment = 0;
49189251Ssam
50189251Ssamint quiet = 0;
51189251Ssam
52189251Ssam/* Flag indicating that we just want to see the key fingerprint */
53189251Ssamint print_fingerprint = 0;
54189251Ssamint print_bubblebabble = 0;
55189251Ssam
56189251Ssam/* The identity file name, given on the command line or entered by the user. */
57189251Ssamchar identity_file[1024];
58189251Ssamint have_identity = 0;
59189251Ssam
60189251Ssam/* This is set to the passphrase if given on the command line. */
61189251Ssamchar *identity_passphrase = NULL;
62189251Ssam
63189251Ssam/* This is set to the new passphrase if given on the command line. */
64189251Ssamchar *identity_new_passphrase = NULL;
65189251Ssam
66189251Ssam/* This is set to the new comment if given on the command line. */
67189251Ssamchar *identity_comment = NULL;
68189251Ssam
69189251Ssam/* Dump public key file in format used by real and the original SSH 2 */
70189251Ssamint convert_to_ssh2 = 0;
71189251Ssamint convert_from_ssh2 = 0;
72189251Ssamint print_public = 0;
73189251Ssam
74189251Ssamchar *key_type_name = NULL;
75189251Ssam
76189251Ssam/* argv0 */
77189251Ssamextern char *__progname;
78189251Ssam
79189251Ssamchar hostname[MAXHOSTNAMELEN];
80189251Ssam
81189251Ssamstatic void
82189251Ssamask_filename(struct passwd *pw, const char *prompt)
83189251Ssam{
84189251Ssam	char buf[1024];
85189251Ssam	char *name = NULL;
86189251Ssam
87189251Ssam	if (key_type_name == NULL)
88189251Ssam		name = _PATH_SSH_CLIENT_ID_RSA;
89189251Ssam	else
90189251Ssam		switch (key_type_from_name(key_type_name)) {
91214734Srpaulo		case KEY_RSA1:
92189251Ssam			name = _PATH_SSH_CLIENT_IDENTITY;
93189251Ssam			break;
94189251Ssam		case KEY_DSA:
95189251Ssam			name = _PATH_SSH_CLIENT_ID_DSA;
96189251Ssam			break;
97189251Ssam		case KEY_RSA:
98189251Ssam			name = _PATH_SSH_CLIENT_ID_RSA;
99189251Ssam			break;
100189251Ssam		default:
101189251Ssam			fprintf(stderr, "bad key type");
102189251Ssam			exit(1);
103189251Ssam			break;
104189251Ssam		}
105189251Ssam
106189251Ssam	snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
107214734Srpaulo	fprintf(stderr, "%s (%s): ", prompt, identity_file);
108189251Ssam	fflush(stderr);
109189251Ssam	if (fgets(buf, sizeof(buf), stdin) == NULL)
110189251Ssam		exit(1);
111189251Ssam	if (strchr(buf, '\n'))
112189251Ssam		*strchr(buf, '\n') = 0;
113189251Ssam	if (strcmp(buf, "") != 0)
114189251Ssam		strlcpy(identity_file, buf, sizeof(identity_file));
115189251Ssam	have_identity = 1;
116189251Ssam}
117189251Ssam
118189251Ssamstatic Key *
119189251Ssamload_identity(char *filename)
120189251Ssam{
121189251Ssam	char *pass;
122189251Ssam	Key *prv;
123189251Ssam
124189251Ssam	prv = key_load_private(filename, "", NULL);
125189251Ssam	if (prv == NULL) {
126189251Ssam		if (identity_passphrase)
127189251Ssam			pass = xstrdup(identity_passphrase);
128189251Ssam		else
129189251Ssam			pass = read_passphrase("Enter passphrase: ",
130189251Ssam			    RP_ALLOW_STDIN);
131189251Ssam		prv = key_load_private(filename, pass, NULL);
132214734Srpaulo		memset(pass, 0, strlen(pass));
133189251Ssam		xfree(pass);
134189251Ssam	}
135189251Ssam	return prv;
136189251Ssam}
137189251Ssam
138189251Ssam#define SSH_COM_PUBLIC_BEGIN		"---- BEGIN SSH2 PUBLIC KEY ----"
139189251Ssam#define SSH_COM_PUBLIC_END		"---- END SSH2 PUBLIC KEY ----"
140189251Ssam#define SSH_COM_PRIVATE_BEGIN		"---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
141189251Ssam#define	SSH_COM_PRIVATE_KEY_MAGIC	0x3f6ff9eb
142189251Ssam
143189251Ssamstatic void
144189251Ssamdo_convert_to_ssh2(struct passwd *pw)
145189251Ssam{
146189251Ssam	Key *k;
147189251Ssam	u_int len;
148189251Ssam	u_char *blob;
149189251Ssam	struct stat st;
150189251Ssam
151189251Ssam	if (!have_identity)
152189251Ssam		ask_filename(pw, "Enter file in which the key is");
153189251Ssam	if (stat(identity_file, &st) < 0) {
154189251Ssam		perror(identity_file);
155189251Ssam		exit(1);
156189251Ssam	}
157189251Ssam	if ((k = key_load_public(identity_file, NULL)) == NULL) {
158189251Ssam		if ((k = load_identity(identity_file)) == NULL) {
159189251Ssam			fprintf(stderr, "load failed\n");
160189251Ssam			exit(1);
161189251Ssam		}
162189251Ssam	}
163189251Ssam	if (key_to_blob(k, &blob, &len) <= 0) {
164189251Ssam		fprintf(stderr, "key_to_blob failed\n");
165189251Ssam		exit(1);
166189251Ssam	}
167189251Ssam	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
168189251Ssam	fprintf(stdout,
169189251Ssam	    "Comment: \"%d-bit %s, converted from OpenSSH by %s@%s\"\n",
170189251Ssam	    key_size(k), key_type(k),
171189251Ssam	    pw->pw_name, hostname);
172189251Ssam	dump_base64(stdout, blob, len);
173189251Ssam	fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
174189251Ssam	key_free(k);
175189251Ssam	xfree(blob);
176189251Ssam	exit(0);
177189251Ssam}
178189251Ssam
179189251Ssamstatic void
180189251Ssambuffer_get_bignum_bits(Buffer *b, BIGNUM *value)
181189251Ssam{
182189251Ssam	int bits = buffer_get_int(b);
183189251Ssam	int bytes = (bits + 7) / 8;
184189251Ssam
185189251Ssam	if (buffer_len(b) < bytes)
186189251Ssam		fatal("buffer_get_bignum_bits: input buffer too small: "
187189251Ssam		    "need %d have %d", bytes, buffer_len(b));
188189251Ssam	BN_bin2bn(buffer_ptr(b), bytes, value);
189189251Ssam	buffer_consume(b, bytes);
190189251Ssam}
191189251Ssam
192189251Ssamstatic Key *
193189251Ssamdo_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
194189251Ssam{
195189251Ssam	Buffer b;
196189251Ssam	Key *key = NULL;
197189251Ssam	char *type, *cipher;
198189251Ssam	u_char *sig, data[] = "abcde12345";
199189251Ssam	int magic, rlen, ktype, i1, i2, i3, i4;
200189251Ssam	u_int slen;
201189251Ssam	u_long e;
202189251Ssam
203189251Ssam	buffer_init(&b);
204189251Ssam	buffer_append(&b, blob, blen);
205189251Ssam
206189251Ssam	magic  = buffer_get_int(&b);
207189251Ssam	if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
208189251Ssam		error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
209189251Ssam		buffer_free(&b);
210189251Ssam		return NULL;
211189251Ssam	}
212189251Ssam	i1 = buffer_get_int(&b);
213189251Ssam	type   = buffer_get_string(&b, NULL);
214189251Ssam	cipher = buffer_get_string(&b, NULL);
215189251Ssam	i2 = buffer_get_int(&b);
216189251Ssam	i3 = buffer_get_int(&b);
217189251Ssam	i4 = buffer_get_int(&b);
218189251Ssam	debug("ignore (%d %d %d %d)", i1,i2,i3,i4);
219189251Ssam	if (strcmp(cipher, "none") != 0) {
220189251Ssam		error("unsupported cipher %s", cipher);
221189251Ssam		xfree(cipher);
222189251Ssam		buffer_free(&b);
223189251Ssam		xfree(type);
224189251Ssam		return NULL;
225189251Ssam	}
226189251Ssam	xfree(cipher);
227189251Ssam
228189251Ssam	if (strstr(type, "dsa")) {
229189251Ssam		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
284static void
285do_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
368static void
369do_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
393static void
394do_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
419static void
420do_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
438static void
439do_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 */
537static void
538do_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 */
618static void
619do_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
712static void
713usage(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 */
742int
743main(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 {
919passphrase_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