]> andersk Git - openssh.git/blob - ssh-keygen.c
- grunk@cvs.openbsd.org 2008/06/11 21:38:25
[openssh.git] / ssh-keygen.c
1 /* $OpenBSD: ssh-keygen.c,v 1.168 2008/06/11 21:38:25 grunk Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1994 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Identity and host key generation and maintenance.
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14
15 #include "includes.h"
16
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <sys/param.h>
21
22 #include <openssl/evp.h>
23 #include <openssl/pem.h>
24 #include "openbsd-compat/openssl-compat.h"
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <netdb.h>
29 #ifdef HAVE_PATHS_H
30 # include <paths.h>
31 #endif
32 #include <pwd.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38
39 #include "xmalloc.h"
40 #include "key.h"
41 #include "rsa.h"
42 #include "authfile.h"
43 #include "uuencode.h"
44 #include "buffer.h"
45 #include "pathnames.h"
46 #include "log.h"
47 #include "misc.h"
48 #include "match.h"
49 #include "hostfile.h"
50 #include "dns.h"
51
52 #ifdef SMARTCARD
53 #include "scard.h"
54 #endif
55
56 /* Number of bits in the RSA/DSA key.  This value can be set on the command line. */
57 #define DEFAULT_BITS            2048
58 #define DEFAULT_BITS_DSA        1024
59 u_int32_t bits = 0;
60
61 /*
62  * Flag indicating that we just want to change the passphrase.  This can be
63  * set on the command line.
64  */
65 int change_passphrase = 0;
66
67 /*
68  * Flag indicating that we just want to change the comment.  This can be set
69  * on the command line.
70  */
71 int change_comment = 0;
72
73 int quiet = 0;
74
75 /* Flag indicating that we want to hash a known_hosts file */
76 int hash_hosts = 0;
77 /* Flag indicating that we want lookup a host in known_hosts file */
78 int find_host = 0;
79 /* Flag indicating that we want to delete a host from a known_hosts file */
80 int delete_host = 0;
81
82 /* Flag indicating that we just want to see the key fingerprint */
83 int print_fingerprint = 0;
84 int print_bubblebabble = 0;
85
86 /* The identity file name, given on the command line or entered by the user. */
87 char identity_file[1024];
88 int have_identity = 0;
89
90 /* This is set to the passphrase if given on the command line. */
91 char *identity_passphrase = NULL;
92
93 /* This is set to the new passphrase if given on the command line. */
94 char *identity_new_passphrase = NULL;
95
96 /* This is set to the new comment if given on the command line. */
97 char *identity_comment = NULL;
98
99 /* Dump public key file in format used by real and the original SSH 2 */
100 int convert_to_ssh2 = 0;
101 int convert_from_ssh2 = 0;
102 int print_public = 0;
103 int print_generic = 0;
104
105 char *key_type_name = NULL;
106
107 /* argv0 */
108 extern char *__progname;
109
110 char hostname[MAXHOSTNAMELEN];
111
112 /* moduli.c */
113 int gen_candidates(FILE *, u_int32_t, u_int32_t, BIGNUM *);
114 int prime_test(FILE *, FILE *, u_int32_t, u_int32_t);
115
116 static void
117 ask_filename(struct passwd *pw, const char *prompt)
118 {
119         char buf[1024];
120         char *name = NULL;
121
122         if (key_type_name == NULL)
123                 name = _PATH_SSH_CLIENT_ID_RSA;
124         else {
125                 switch (key_type_from_name(key_type_name)) {
126                 case KEY_RSA1:
127                         name = _PATH_SSH_CLIENT_IDENTITY;
128                         break;
129                 case KEY_DSA:
130                         name = _PATH_SSH_CLIENT_ID_DSA;
131                         break;
132                 case KEY_RSA:
133                         name = _PATH_SSH_CLIENT_ID_RSA;
134                         break;
135                 default:
136                         fprintf(stderr, "bad key type");
137                         exit(1);
138                         break;
139                 }
140         }
141         snprintf(identity_file, sizeof(identity_file), "%s/%s", pw->pw_dir, name);
142         fprintf(stderr, "%s (%s): ", prompt, identity_file);
143         if (fgets(buf, sizeof(buf), stdin) == NULL)
144                 exit(1);
145         buf[strcspn(buf, "\n")] = '\0';
146         if (strcmp(buf, "") != 0)
147                 strlcpy(identity_file, buf, sizeof(identity_file));
148         have_identity = 1;
149 }
150
151 static Key *
152 load_identity(char *filename)
153 {
154         char *pass;
155         Key *prv;
156
157         prv = key_load_private(filename, "", NULL);
158         if (prv == NULL) {
159                 if (identity_passphrase)
160                         pass = xstrdup(identity_passphrase);
161                 else
162                         pass = read_passphrase("Enter passphrase: ",
163                             RP_ALLOW_STDIN);
164                 prv = key_load_private(filename, pass, NULL);
165                 memset(pass, 0, strlen(pass));
166                 xfree(pass);
167         }
168         return prv;
169 }
170
171 #define SSH_COM_PUBLIC_BEGIN            "---- BEGIN SSH2 PUBLIC KEY ----"
172 #define SSH_COM_PUBLIC_END              "---- END SSH2 PUBLIC KEY ----"
173 #define SSH_COM_PRIVATE_BEGIN           "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----"
174 #define SSH_COM_PRIVATE_KEY_MAGIC       0x3f6ff9eb
175
176 static void
177 do_convert_to_ssh2(struct passwd *pw)
178 {
179         Key *k;
180         u_int len;
181         u_char *blob;
182         struct stat st;
183
184         if (!have_identity)
185                 ask_filename(pw, "Enter file in which the key is");
186         if (stat(identity_file, &st) < 0) {
187                 perror(identity_file);
188                 exit(1);
189         }
190         if ((k = key_load_public(identity_file, NULL)) == NULL) {
191                 if ((k = load_identity(identity_file)) == NULL) {
192                         fprintf(stderr, "load failed\n");
193                         exit(1);
194                 }
195         }
196         if (k->type == KEY_RSA1) {
197                 fprintf(stderr, "version 1 keys are not supported\n");
198                 exit(1);
199         }
200         if (key_to_blob(k, &blob, &len) <= 0) {
201                 fprintf(stderr, "key_to_blob failed\n");
202                 exit(1);
203         }
204         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_BEGIN);
205         fprintf(stdout,
206             "Comment: \"%u-bit %s, converted from OpenSSH by %s@%s\"\n",
207             key_size(k), key_type(k),
208             pw->pw_name, hostname);
209         dump_base64(stdout, blob, len);
210         fprintf(stdout, "%s\n", SSH_COM_PUBLIC_END);
211         key_free(k);
212         xfree(blob);
213         exit(0);
214 }
215
216 static void
217 buffer_get_bignum_bits(Buffer *b, BIGNUM *value)
218 {
219         u_int bignum_bits = buffer_get_int(b);
220         u_int bytes = (bignum_bits + 7) / 8;
221
222         if (buffer_len(b) < bytes)
223                 fatal("buffer_get_bignum_bits: input buffer too small: "
224                     "need %d have %d", bytes, buffer_len(b));
225         if (BN_bin2bn(buffer_ptr(b), bytes, value) == NULL)
226                 fatal("buffer_get_bignum_bits: BN_bin2bn failed");
227         buffer_consume(b, bytes);
228 }
229
230 static Key *
231 do_convert_private_ssh2_from_blob(u_char *blob, u_int blen)
232 {
233         Buffer b;
234         Key *key = NULL;
235         char *type, *cipher;
236         u_char *sig, data[] = "abcde12345";
237         int magic, rlen, ktype, i1, i2, i3, i4;
238         u_int slen;
239         u_long e;
240
241         buffer_init(&b);
242         buffer_append(&b, blob, blen);
243
244         magic = buffer_get_int(&b);
245         if (magic != SSH_COM_PRIVATE_KEY_MAGIC) {
246                 error("bad magic 0x%x != 0x%x", magic, SSH_COM_PRIVATE_KEY_MAGIC);
247                 buffer_free(&b);
248                 return NULL;
249         }
250         i1 = buffer_get_int(&b);
251         type   = buffer_get_string(&b, NULL);
252         cipher = buffer_get_string(&b, NULL);
253         i2 = buffer_get_int(&b);
254         i3 = buffer_get_int(&b);
255         i4 = buffer_get_int(&b);
256         debug("ignore (%d %d %d %d)", i1, i2, i3, i4);
257         if (strcmp(cipher, "none") != 0) {
258                 error("unsupported cipher %s", cipher);
259                 xfree(cipher);
260                 buffer_free(&b);
261                 xfree(type);
262                 return NULL;
263         }
264         xfree(cipher);
265
266         if (strstr(type, "dsa")) {
267                 ktype = KEY_DSA;
268         } else if (strstr(type, "rsa")) {
269                 ktype = KEY_RSA;
270         } else {
271                 buffer_free(&b);
272                 xfree(type);
273                 return NULL;
274         }
275         key = key_new_private(ktype);
276         xfree(type);
277
278         switch (key->type) {
279         case KEY_DSA:
280                 buffer_get_bignum_bits(&b, key->dsa->p);
281                 buffer_get_bignum_bits(&b, key->dsa->g);
282                 buffer_get_bignum_bits(&b, key->dsa->q);
283                 buffer_get_bignum_bits(&b, key->dsa->pub_key);
284                 buffer_get_bignum_bits(&b, key->dsa->priv_key);
285                 break;
286         case KEY_RSA:
287                 e = buffer_get_char(&b);
288                 debug("e %lx", e);
289                 if (e < 30) {
290                         e <<= 8;
291                         e += buffer_get_char(&b);
292                         debug("e %lx", e);
293                         e <<= 8;
294                         e += buffer_get_char(&b);
295                         debug("e %lx", e);
296                 }
297                 if (!BN_set_word(key->rsa->e, e)) {
298                         buffer_free(&b);
299                         key_free(key);
300                         return NULL;
301                 }
302                 buffer_get_bignum_bits(&b, key->rsa->d);
303                 buffer_get_bignum_bits(&b, key->rsa->n);
304                 buffer_get_bignum_bits(&b, key->rsa->iqmp);
305                 buffer_get_bignum_bits(&b, key->rsa->q);
306                 buffer_get_bignum_bits(&b, key->rsa->p);
307                 rsa_generate_additional_parameters(key->rsa);
308                 break;
309         }
310         rlen = buffer_len(&b);
311         if (rlen != 0)
312                 error("do_convert_private_ssh2_from_blob: "
313                     "remaining bytes in key blob %d", rlen);
314         buffer_free(&b);
315
316         /* try the key */
317         key_sign(key, &sig, &slen, data, sizeof(data));
318         key_verify(key, sig, slen, data, sizeof(data));
319         xfree(sig);
320         return key;
321 }
322
323 static int
324 get_line(FILE *fp, char *line, size_t len)
325 {
326         int c;
327         size_t pos = 0;
328
329         line[0] = '\0';
330         while ((c = fgetc(fp)) != EOF) {
331                 if (pos >= len - 1) {
332                         fprintf(stderr, "input line too long.\n");
333                         exit(1);
334                 }
335                 switch (c) {
336                 case '\r':
337                         c = fgetc(fp);
338                         if (c != EOF && c != '\n' && ungetc(c, fp) == EOF) {
339                                 fprintf(stderr, "unget: %s\n", strerror(errno));
340                                 exit(1);
341                         }
342                         return pos;
343                 case '\n':
344                         return pos;
345                 }
346                 line[pos++] = c;
347                 line[pos] = '\0';
348         }
349         /* We reached EOF */
350         return -1;
351 }
352
353 static void
354 do_convert_from_ssh2(struct passwd *pw)
355 {
356         Key *k;
357         int blen;
358         u_int len;
359         char line[1024];
360         u_char blob[8096];
361         char encoded[8096];
362         struct stat st;
363         int escaped = 0, private = 0, ok;
364         FILE *fp;
365
366         if (!have_identity)
367                 ask_filename(pw, "Enter file in which the key is");
368         if (stat(identity_file, &st) < 0) {
369                 perror(identity_file);
370                 exit(1);
371         }
372         fp = fopen(identity_file, "r");
373         if (fp == NULL) {
374                 perror(identity_file);
375                 exit(1);
376         }
377         encoded[0] = '\0';
378         while ((blen = get_line(fp, line, sizeof(line))) != -1) {
379                 if (line[blen - 1] == '\\')
380                         escaped++;
381                 if (strncmp(line, "----", 4) == 0 ||
382                     strstr(line, ": ") != NULL) {
383                         if (strstr(line, SSH_COM_PRIVATE_BEGIN) != NULL)
384                                 private = 1;
385                         if (strstr(line, " END ") != NULL) {
386                                 break;
387                         }
388                         /* fprintf(stderr, "ignore: %s", line); */
389                         continue;
390                 }
391                 if (escaped) {
392                         escaped--;
393                         /* fprintf(stderr, "escaped: %s", line); */
394                         continue;
395                 }
396                 strlcat(encoded, line, sizeof(encoded));
397         }
398         len = strlen(encoded);
399         if (((len % 4) == 3) &&
400             (encoded[len-1] == '=') &&
401             (encoded[len-2] == '=') &&
402             (encoded[len-3] == '='))
403                 encoded[len-3] = '\0';
404         blen = uudecode(encoded, blob, sizeof(blob));
405         if (blen < 0) {
406                 fprintf(stderr, "uudecode failed.\n");
407                 exit(1);
408         }
409         k = private ?
410             do_convert_private_ssh2_from_blob(blob, blen) :
411             key_from_blob(blob, blen);
412         if (k == NULL) {
413                 fprintf(stderr, "decode blob failed.\n");
414                 exit(1);
415         }
416         ok = private ?
417             (k->type == KEY_DSA ?
418                  PEM_write_DSAPrivateKey(stdout, k->dsa, NULL, NULL, 0, NULL, NULL) :
419                  PEM_write_RSAPrivateKey(stdout, k->rsa, NULL, NULL, 0, NULL, NULL)) :
420             key_write(k, stdout);
421         if (!ok) {
422                 fprintf(stderr, "key write failed");
423                 exit(1);
424         }
425         key_free(k);
426         if (!private)
427                 fprintf(stdout, "\n");
428         fclose(fp);
429         exit(0);
430 }
431
432 static void
433 do_print_public(struct passwd *pw)
434 {
435         Key *prv;
436         struct stat st;
437
438         if (!have_identity)
439                 ask_filename(pw, "Enter file in which the key is");
440         if (stat(identity_file, &st) < 0) {
441                 perror(identity_file);
442                 exit(1);
443         }
444         prv = load_identity(identity_file);
445         if (prv == NULL) {
446                 fprintf(stderr, "load failed\n");
447                 exit(1);
448         }
449         if (!key_write(prv, stdout))
450                 fprintf(stderr, "key_write failed");
451         key_free(prv);
452         fprintf(stdout, "\n");
453         exit(0);
454 }
455
456 #ifdef SMARTCARD
457 static void
458 do_upload(struct passwd *pw, const char *sc_reader_id)
459 {
460         Key *prv = NULL;
461         struct stat st;
462         int ret;
463
464         if (!have_identity)
465                 ask_filename(pw, "Enter file in which the key is");
466         if (stat(identity_file, &st) < 0) {
467                 perror(identity_file);
468                 exit(1);
469         }
470         prv = load_identity(identity_file);
471         if (prv == NULL) {
472                 error("load failed");
473                 exit(1);
474         }
475         ret = sc_put_key(prv, sc_reader_id);
476         key_free(prv);
477         if (ret < 0)
478                 exit(1);
479         logit("loading key done");
480         exit(0);
481 }
482
483 static void
484 do_download(struct passwd *pw, const char *sc_reader_id)
485 {
486         Key **keys = NULL;
487         int i;
488
489         keys = sc_get_keys(sc_reader_id, NULL);
490         if (keys == NULL)
491                 fatal("cannot read public key from smartcard");
492         for (i = 0; keys[i]; i++) {
493                 key_write(keys[i], stdout);
494                 key_free(keys[i]);
495                 fprintf(stdout, "\n");
496         }
497         xfree(keys);
498         exit(0);
499 }
500 #endif /* SMARTCARD */
501
502 static void
503 do_fingerprint(struct passwd *pw)
504 {
505         FILE *f;
506         Key *public;
507         char *comment = NULL, *cp, *ep, line[16*1024], *fp, *ra;
508         int i, skip = 0, num = 0, invalid = 1;
509         enum fp_rep rep;
510         enum fp_type fptype;
511         struct stat st;
512
513         fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
514         rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
515
516         if (!have_identity)
517                 ask_filename(pw, "Enter file in which the key is");
518         if (stat(identity_file, &st) < 0) {
519                 perror(identity_file);
520                 exit(1);
521         }
522         public = key_load_public(identity_file, &comment);
523         if (public != NULL) {
524                 fp = key_fingerprint(public, fptype, rep);
525                 ra = key_fingerprint(public, fptype, SSH_FP_RANDOMART);
526                 printf("%u %s %s\n", key_size(public), fp, comment);
527                 verbose("%s", ra);
528                 key_free(public);
529                 xfree(comment);
530                 xfree(ra);
531                 xfree(fp);
532                 exit(0);
533         }
534         if (comment) {
535                 xfree(comment);
536                 comment = NULL;
537         }
538
539         f = fopen(identity_file, "r");
540         if (f != NULL) {
541                 while (fgets(line, sizeof(line), f)) {
542                         if ((cp = strchr(line, '\n')) == NULL) {
543                                 error("line %d too long: %.40s...",
544                                     num + 1, line);
545                                 skip = 1;
546                                 continue;
547                         }
548                         num++;
549                         if (skip) {
550                                 skip = 0;
551                                 continue;
552                         }
553                         *cp = '\0';
554
555                         /* Skip leading whitespace, empty and comment lines. */
556                         for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
557                                 ;
558                         if (!*cp || *cp == '\n' || *cp == '#')
559                                 continue;
560                         i = strtol(cp, &ep, 10);
561                         if (i == 0 || ep == NULL || (*ep != ' ' && *ep != '\t')) {
562                                 int quoted = 0;
563                                 comment = cp;
564                                 for (; *cp && (quoted || (*cp != ' ' &&
565                                     *cp != '\t')); cp++) {
566                                         if (*cp == '\\' && cp[1] == '"')
567                                                 cp++;   /* Skip both */
568                                         else if (*cp == '"')
569                                                 quoted = !quoted;
570                                 }
571                                 if (!*cp)
572                                         continue;
573                                 *cp++ = '\0';
574                         }
575                         ep = cp;
576                         public = key_new(KEY_RSA1);
577                         if (key_read(public, &cp) != 1) {
578                                 cp = ep;
579                                 key_free(public);
580                                 public = key_new(KEY_UNSPEC);
581                                 if (key_read(public, &cp) != 1) {
582                                         key_free(public);
583                                         continue;
584                                 }
585                         }
586                         comment = *cp ? cp : comment;
587                         fp = key_fingerprint(public, fptype, rep);
588                         ra = key_fingerprint(public, fptype, SSH_FP_RANDOMART);
589                         printf("%u %s %s\n", key_size(public), fp,
590                             comment ? comment : "no comment");
591                         verbose("%s\n", ra);
592                         xfree(ra);
593                         xfree(fp);
594                         key_free(public);
595                         invalid = 0;
596                 }
597                 fclose(f);
598         }
599         if (invalid) {
600                 printf("%s is not a public key file.\n", identity_file);
601                 exit(1);
602         }
603         exit(0);
604 }
605
606 static void
607 print_host(FILE *f, const char *name, Key *public, int hash)
608 {
609         if (print_fingerprint) {
610                 enum fp_rep rep;
611                 enum fp_type fptype;
612                 char *fp, *ra;
613
614                 fptype = print_bubblebabble ? SSH_FP_SHA1 : SSH_FP_MD5;
615                 rep =    print_bubblebabble ? SSH_FP_BUBBLEBABBLE : SSH_FP_HEX;
616                 fp = key_fingerprint(public, fptype, rep);
617                 ra = key_fingerprint(public, fptype, SSH_FP_RANDOMART);
618                 printf("%u %s %s\n%s\n", key_size(public), fp, name, ra);
619                 xfree(ra);
620                 xfree(fp);
621         } else {
622                 if (hash && (name = host_hash(name, NULL, 0)) == NULL)
623                         fatal("hash_host failed");
624                 fprintf(f, "%s ", name);
625                 if (!key_write(public, f))
626                         fatal("key_write failed");
627                 fprintf(f, "\n");
628         }
629 }
630
631 static void
632 do_known_hosts(struct passwd *pw, const char *name)
633 {
634         FILE *in, *out = stdout;
635         Key *public;
636         char *cp, *cp2, *kp, *kp2;
637         char line[16*1024], tmp[MAXPATHLEN], old[MAXPATHLEN];
638         int c, skip = 0, inplace = 0, num = 0, invalid = 0, has_unhashed = 0;
639
640         if (!have_identity) {
641                 cp = tilde_expand_filename(_PATH_SSH_USER_HOSTFILE, pw->pw_uid);
642                 if (strlcpy(identity_file, cp, sizeof(identity_file)) >=
643                     sizeof(identity_file))
644                         fatal("Specified known hosts path too long");
645                 xfree(cp);
646                 have_identity = 1;
647         }
648         if ((in = fopen(identity_file, "r")) == NULL)
649                 fatal("fopen: %s", strerror(errno));
650
651         /*
652          * Find hosts goes to stdout, hash and deletions happen in-place
653          * A corner case is ssh-keygen -HF foo, which should go to stdout
654          */
655         if (!find_host && (hash_hosts || delete_host)) {
656                 if (strlcpy(tmp, identity_file, sizeof(tmp)) >= sizeof(tmp) ||
657                     strlcat(tmp, ".XXXXXXXXXX", sizeof(tmp)) >= sizeof(tmp) ||
658                     strlcpy(old, identity_file, sizeof(old)) >= sizeof(old) ||
659                     strlcat(old, ".old", sizeof(old)) >= sizeof(old))
660                         fatal("known_hosts path too long");
661                 umask(077);
662                 if ((c = mkstemp(tmp)) == -1)
663                         fatal("mkstemp: %s", strerror(errno));
664                 if ((out = fdopen(c, "w")) == NULL) {
665                         c = errno;
666                         unlink(tmp);
667                         fatal("fdopen: %s", strerror(c));
668                 }
669                 inplace = 1;
670         }
671
672         while (fgets(line, sizeof(line), in)) {
673                 if ((cp = strchr(line, '\n')) == NULL) {
674                         error("line %d too long: %.40s...", num + 1, line);
675                         skip = 1;
676                         invalid = 1;
677                         continue;
678                 }
679                 num++;
680                 if (skip) {
681                         skip = 0;
682                         continue;
683                 }
684                 *cp = '\0';
685
686                 /* Skip leading whitespace, empty and comment lines. */
687                 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
688                         ;
689                 if (!*cp || *cp == '\n' || *cp == '#') {
690                         if (inplace)
691                                 fprintf(out, "%s\n", cp);
692                         continue;
693                 }
694                 /* Find the end of the host name portion. */
695                 for (kp = cp; *kp && *kp != ' ' && *kp != '\t'; kp++)
696                         ;
697                 if (*kp == '\0' || *(kp + 1) == '\0') {
698                         error("line %d missing key: %.40s...",
699                             num, line);
700                         invalid = 1;
701                         continue;
702                 }
703                 *kp++ = '\0';
704                 kp2 = kp;
705
706                 public = key_new(KEY_RSA1);
707                 if (key_read(public, &kp) != 1) {
708                         kp = kp2;
709                         key_free(public);
710                         public = key_new(KEY_UNSPEC);
711                         if (key_read(public, &kp) != 1) {
712                                 error("line %d invalid key: %.40s...",
713                                     num, line);
714                                 key_free(public);
715                                 invalid = 1;
716                                 continue;
717                         }
718                 }
719
720                 if (*cp == HASH_DELIM) {
721                         if (find_host || delete_host) {
722                                 cp2 = host_hash(name, cp, strlen(cp));
723                                 if (cp2 == NULL) {
724                                         error("line %d: invalid hashed "
725                                             "name: %.64s...", num, line);
726                                         invalid = 1;
727                                         continue;
728                                 }
729                                 c = (strcmp(cp2, cp) == 0);
730                                 if (find_host && c) {
731                                         printf("# Host %s found: "
732                                             "line %d type %s\n", name,
733                                             num, key_type(public));
734                                         print_host(out, cp, public, 0);
735                                 }
736                                 if (delete_host && !c)
737                                         print_host(out, cp, public, 0);
738                         } else if (hash_hosts)
739                                 print_host(out, cp, public, 0);
740                 } else {
741                         if (find_host || delete_host) {
742                                 c = (match_hostname(name, cp,
743                                     strlen(cp)) == 1);
744                                 if (find_host && c) {
745                                         printf("# Host %s found: "
746                                             "line %d type %s\n", name,
747                                             num, key_type(public));
748                                         print_host(out, name, public,
749                                             hash_hosts);
750                                 }
751                                 if (delete_host && !c)
752                                         print_host(out, cp, public, 0);
753                         } else if (hash_hosts) {
754                                 for (cp2 = strsep(&cp, ",");
755                                     cp2 != NULL && *cp2 != '\0';
756                                     cp2 = strsep(&cp, ",")) {
757                                         if (strcspn(cp2, "*?!") != strlen(cp2))
758                                                 fprintf(stderr, "Warning: "
759                                                     "ignoring host name with "
760                                                     "metacharacters: %.64s\n",
761                                                     cp2);
762                                         else
763                                                 print_host(out, cp2, public, 1);
764                                 }
765                                 has_unhashed = 1;
766                         }
767                 }
768                 key_free(public);
769         }
770         fclose(in);
771
772         if (invalid) {
773                 fprintf(stderr, "%s is not a valid known_hosts file.\n",
774                     identity_file);
775                 if (inplace) {
776                         fprintf(stderr, "Not replacing existing known_hosts "
777                             "file because of errors\n");
778                         fclose(out);
779                         unlink(tmp);
780                 }
781                 exit(1);
782         }
783
784         if (inplace) {
785                 fclose(out);
786
787                 /* Backup existing file */
788                 if (unlink(old) == -1 && errno != ENOENT)
789                         fatal("unlink %.100s: %s", old, strerror(errno));
790                 if (link(identity_file, old) == -1)
791                         fatal("link %.100s to %.100s: %s", identity_file, old,
792                             strerror(errno));
793                 /* Move new one into place */
794                 if (rename(tmp, identity_file) == -1) {
795                         error("rename\"%s\" to \"%s\": %s", tmp, identity_file,
796                             strerror(errno));
797                         unlink(tmp);
798                         unlink(old);
799                         exit(1);
800                 }
801
802                 fprintf(stderr, "%s updated.\n", identity_file);
803                 fprintf(stderr, "Original contents retained as %s\n", old);
804                 if (has_unhashed) {
805                         fprintf(stderr, "WARNING: %s contains unhashed "
806                             "entries\n", old);
807                         fprintf(stderr, "Delete this file to ensure privacy "
808                             "of hostnames\n");
809                 }
810         }
811
812         exit(0);
813 }
814
815 /*
816  * Perform changing a passphrase.  The argument is the passwd structure
817  * for the current user.
818  */
819 static void
820 do_change_passphrase(struct passwd *pw)
821 {
822         char *comment;
823         char *old_passphrase, *passphrase1, *passphrase2;
824         struct stat st;
825         Key *private;
826
827         if (!have_identity)
828                 ask_filename(pw, "Enter file in which the key is");
829         if (stat(identity_file, &st) < 0) {
830                 perror(identity_file);
831                 exit(1);
832         }
833         /* Try to load the file with empty passphrase. */
834         private = key_load_private(identity_file, "", &comment);
835         if (private == NULL) {
836                 if (identity_passphrase)
837                         old_passphrase = xstrdup(identity_passphrase);
838                 else
839                         old_passphrase =
840                             read_passphrase("Enter old passphrase: ",
841                             RP_ALLOW_STDIN);
842                 private = key_load_private(identity_file, old_passphrase,
843                     &comment);
844                 memset(old_passphrase, 0, strlen(old_passphrase));
845                 xfree(old_passphrase);
846                 if (private == NULL) {
847                         printf("Bad passphrase.\n");
848                         exit(1);
849                 }
850         }
851         printf("Key has comment '%s'\n", comment);
852
853         /* Ask the new passphrase (twice). */
854         if (identity_new_passphrase) {
855                 passphrase1 = xstrdup(identity_new_passphrase);
856                 passphrase2 = NULL;
857         } else {
858                 passphrase1 =
859                         read_passphrase("Enter new passphrase (empty for no "
860                             "passphrase): ", RP_ALLOW_STDIN);
861                 passphrase2 = read_passphrase("Enter same passphrase again: ",
862                     RP_ALLOW_STDIN);
863
864                 /* Verify that they are the same. */
865                 if (strcmp(passphrase1, passphrase2) != 0) {
866                         memset(passphrase1, 0, strlen(passphrase1));
867                         memset(passphrase2, 0, strlen(passphrase2));
868                         xfree(passphrase1);
869                         xfree(passphrase2);
870                         printf("Pass phrases do not match.  Try again.\n");
871                         exit(1);
872                 }
873                 /* Destroy the other copy. */
874                 memset(passphrase2, 0, strlen(passphrase2));
875                 xfree(passphrase2);
876         }
877
878         /* Save the file using the new passphrase. */
879         if (!key_save_private(private, identity_file, passphrase1, comment)) {
880                 printf("Saving the key failed: %s.\n", identity_file);
881                 memset(passphrase1, 0, strlen(passphrase1));
882                 xfree(passphrase1);
883                 key_free(private);
884                 xfree(comment);
885                 exit(1);
886         }
887         /* Destroy the passphrase and the copy of the key in memory. */
888         memset(passphrase1, 0, strlen(passphrase1));
889         xfree(passphrase1);
890         key_free(private);               /* Destroys contents */
891         xfree(comment);
892
893         printf("Your identification has been saved with the new passphrase.\n");
894         exit(0);
895 }
896
897 /*
898  * Print the SSHFP RR.
899  */
900 static int
901 do_print_resource_record(struct passwd *pw, char *fname, char *hname)
902 {
903         Key *public;
904         char *comment = NULL;
905         struct stat st;
906
907         if (fname == NULL)
908                 ask_filename(pw, "Enter file in which the key is");
909         if (stat(fname, &st) < 0) {
910                 if (errno == ENOENT)
911                         return 0;
912                 perror(fname);
913                 exit(1);
914         }
915         public = key_load_public(fname, &comment);
916         if (public != NULL) {
917                 export_dns_rr(hname, public, stdout, print_generic);
918                 key_free(public);
919                 xfree(comment);
920                 return 1;
921         }
922         if (comment)
923                 xfree(comment);
924
925         printf("failed to read v2 public key from %s.\n", fname);
926         exit(1);
927 }
928
929 /*
930  * Change the comment of a private key file.
931  */
932 static void
933 do_change_comment(struct passwd *pw)
934 {
935         char new_comment[1024], *comment, *passphrase;
936         Key *private;
937         Key *public;
938         struct stat st;
939         FILE *f;
940         int fd;
941
942         if (!have_identity)
943                 ask_filename(pw, "Enter file in which the key is");
944         if (stat(identity_file, &st) < 0) {
945                 perror(identity_file);
946                 exit(1);
947         }
948         private = key_load_private(identity_file, "", &comment);
949         if (private == NULL) {
950                 if (identity_passphrase)
951                         passphrase = xstrdup(identity_passphrase);
952                 else if (identity_new_passphrase)
953                         passphrase = xstrdup(identity_new_passphrase);
954                 else
955                         passphrase = read_passphrase("Enter passphrase: ",
956                             RP_ALLOW_STDIN);
957                 /* Try to load using the passphrase. */
958                 private = key_load_private(identity_file, passphrase, &comment);
959                 if (private == NULL) {
960                         memset(passphrase, 0, strlen(passphrase));
961                         xfree(passphrase);
962                         printf("Bad passphrase.\n");
963                         exit(1);
964                 }
965         } else {
966                 passphrase = xstrdup("");
967         }
968         if (private->type != KEY_RSA1) {
969                 fprintf(stderr, "Comments are only supported for RSA1 keys.\n");
970                 key_free(private);
971                 exit(1);
972         }
973         printf("Key now has comment '%s'\n", comment);
974
975         if (identity_comment) {
976                 strlcpy(new_comment, identity_comment, sizeof(new_comment));
977         } else {
978                 printf("Enter new comment: ");
979                 fflush(stdout);
980                 if (!fgets(new_comment, sizeof(new_comment), stdin)) {
981                         memset(passphrase, 0, strlen(passphrase));
982                         key_free(private);
983                         exit(1);
984                 }
985                 new_comment[strcspn(new_comment, "\n")] = '\0';
986         }
987
988         /* Save the file using the new passphrase. */
989         if (!key_save_private(private, identity_file, passphrase, new_comment)) {
990                 printf("Saving the key failed: %s.\n", identity_file);
991                 memset(passphrase, 0, strlen(passphrase));
992                 xfree(passphrase);
993                 key_free(private);
994                 xfree(comment);
995                 exit(1);
996         }
997         memset(passphrase, 0, strlen(passphrase));
998         xfree(passphrase);
999         public = key_from_private(private);
1000         key_free(private);
1001
1002         strlcat(identity_file, ".pub", sizeof(identity_file));
1003         fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1004         if (fd == -1) {
1005                 printf("Could not save your public key in %s\n", identity_file);
1006                 exit(1);
1007         }
1008         f = fdopen(fd, "w");
1009         if (f == NULL) {
1010                 printf("fdopen %s failed", identity_file);
1011                 exit(1);
1012         }
1013         if (!key_write(public, f))
1014                 fprintf(stderr, "write key failed");
1015         key_free(public);
1016         fprintf(f, " %s\n", new_comment);
1017         fclose(f);
1018
1019         xfree(comment);
1020
1021         printf("The comment in your key file has been changed.\n");
1022         exit(0);
1023 }
1024
1025 static void
1026 usage(void)
1027 {
1028         fprintf(stderr, "usage: %s [options]\n", __progname);
1029         fprintf(stderr, "Options:\n");
1030         fprintf(stderr, "  -a trials   Number of trials for screening DH-GEX moduli.\n");
1031         fprintf(stderr, "  -B          Show bubblebabble digest of key file.\n");
1032         fprintf(stderr, "  -b bits     Number of bits in the key to create.\n");
1033         fprintf(stderr, "  -C comment  Provide new comment.\n");
1034         fprintf(stderr, "  -c          Change comment in private and public key files.\n");
1035 #ifdef SMARTCARD
1036         fprintf(stderr, "  -D reader   Download public key from smartcard.\n");
1037 #endif /* SMARTCARD */
1038         fprintf(stderr, "  -e          Convert OpenSSH to RFC 4716 key file.\n");
1039         fprintf(stderr, "  -F hostname Find hostname in known hosts file.\n");
1040         fprintf(stderr, "  -f filename Filename of the key file.\n");
1041         fprintf(stderr, "  -G file     Generate candidates for DH-GEX moduli.\n");
1042         fprintf(stderr, "  -g          Use generic DNS resource record format.\n");
1043         fprintf(stderr, "  -H          Hash names in known_hosts file.\n");
1044         fprintf(stderr, "  -i          Convert RFC 4716 to OpenSSH key file.\n");
1045         fprintf(stderr, "  -l          Show fingerprint of key file.\n");
1046         fprintf(stderr, "  -M memory   Amount of memory (MB) to use for generating DH-GEX moduli.\n");
1047         fprintf(stderr, "  -N phrase   Provide new passphrase.\n");
1048         fprintf(stderr, "  -P phrase   Provide old passphrase.\n");
1049         fprintf(stderr, "  -p          Change passphrase of private key file.\n");
1050         fprintf(stderr, "  -q          Quiet.\n");
1051         fprintf(stderr, "  -R hostname Remove host from known_hosts file.\n");
1052         fprintf(stderr, "  -r hostname Print DNS resource record.\n");
1053         fprintf(stderr, "  -S start    Start point (hex) for generating DH-GEX moduli.\n");
1054         fprintf(stderr, "  -T file     Screen candidates for DH-GEX moduli.\n");
1055         fprintf(stderr, "  -t type     Specify type of key to create.\n");
1056 #ifdef SMARTCARD
1057         fprintf(stderr, "  -U reader   Upload private key to smartcard.\n");
1058 #endif /* SMARTCARD */
1059         fprintf(stderr, "  -v          Verbose.\n");
1060         fprintf(stderr, "  -W gen      Generator to use for generating DH-GEX moduli.\n");
1061         fprintf(stderr, "  -y          Read private key file and print public key.\n");
1062
1063         exit(1);
1064 }
1065
1066 /*
1067  * Main program for key management.
1068  */
1069 int
1070 main(int argc, char **argv)
1071 {
1072         char dotsshdir[MAXPATHLEN], comment[1024], *passphrase1, *passphrase2;
1073         char out_file[MAXPATHLEN], *reader_id = NULL;
1074         char *rr_hostname = NULL;
1075         Key *private, *public;
1076         struct passwd *pw;
1077         struct stat st;
1078         int opt, type, fd, download = 0;
1079         u_int32_t memory = 0, generator_wanted = 0, trials = 100;
1080         int do_gen_candidates = 0, do_screen_candidates = 0;
1081         int log_level = SYSLOG_LEVEL_INFO;
1082         BIGNUM *start = NULL;
1083         FILE *f;
1084         const char *errstr;
1085
1086         extern int optind;
1087         extern char *optarg;
1088
1089         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1090         sanitise_stdfd();
1091
1092         __progname = ssh_get_progname(argv[0]);
1093
1094         SSLeay_add_all_algorithms();
1095         log_init(argv[0], SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_USER, 1);
1096
1097         init_rng();
1098         seed_rng();
1099
1100         /* we need this for the home * directory.  */
1101         pw = getpwuid(getuid());
1102         if (!pw) {
1103                 printf("You don't exist, go away!\n");
1104                 exit(1);
1105         }
1106         if (gethostname(hostname, sizeof(hostname)) < 0) {
1107                 perror("gethostname");
1108                 exit(1);
1109         }
1110
1111         while ((opt = getopt(argc, argv,
1112             "degiqpclBHvxXyF:b:f:t:U:D:P:N:C:r:g:R:T:G:M:S:a:W:")) != -1) {
1113                 switch (opt) {
1114                 case 'b':
1115                         bits = (u_int32_t)strtonum(optarg, 768, 32768, &errstr);
1116                         if (errstr)
1117                                 fatal("Bits has bad value %s (%s)",
1118                                         optarg, errstr);
1119                         break;
1120                 case 'F':
1121                         find_host = 1;
1122                         rr_hostname = optarg;
1123                         break;
1124                 case 'H':
1125                         hash_hosts = 1;
1126                         break;
1127                 case 'R':
1128                         delete_host = 1;
1129                         rr_hostname = optarg;
1130                         break;
1131                 case 'l':
1132                         print_fingerprint = 1;
1133                         break;
1134                 case 'B':
1135                         print_bubblebabble = 1;
1136                         break;
1137                 case 'p':
1138                         change_passphrase = 1;
1139                         break;
1140                 case 'c':
1141                         change_comment = 1;
1142                         break;
1143                 case 'f':
1144                         if (strlcpy(identity_file, optarg, sizeof(identity_file)) >=
1145                             sizeof(identity_file))
1146                                 fatal("Identity filename too long");
1147                         have_identity = 1;
1148                         break;
1149                 case 'g':
1150                         print_generic = 1;
1151                         break;
1152                 case 'P':
1153                         identity_passphrase = optarg;
1154                         break;
1155                 case 'N':
1156                         identity_new_passphrase = optarg;
1157                         break;
1158                 case 'C':
1159                         identity_comment = optarg;
1160                         break;
1161                 case 'q':
1162                         quiet = 1;
1163                         break;
1164                 case 'e':
1165                 case 'x':
1166                         /* export key */
1167                         convert_to_ssh2 = 1;
1168                         break;
1169                 case 'i':
1170                 case 'X':
1171                         /* import key */
1172                         convert_from_ssh2 = 1;
1173                         break;
1174                 case 'y':
1175                         print_public = 1;
1176                         break;
1177                 case 'd':
1178                         key_type_name = "dsa";
1179                         break;
1180                 case 't':
1181                         key_type_name = optarg;
1182                         break;
1183                 case 'D':
1184                         download = 1;
1185                         /*FALLTHROUGH*/
1186                 case 'U':
1187                         reader_id = optarg;
1188                         break;
1189                 case 'v':
1190                         if (log_level == SYSLOG_LEVEL_INFO)
1191                                 log_level = SYSLOG_LEVEL_DEBUG1;
1192                         else {
1193                                 if (log_level >= SYSLOG_LEVEL_DEBUG1 &&
1194                                     log_level < SYSLOG_LEVEL_DEBUG3)
1195                                         log_level++;
1196                         }
1197                         break;
1198                 case 'r':
1199                         rr_hostname = optarg;
1200                         break;
1201                 case 'W':
1202                         generator_wanted = (u_int32_t)strtonum(optarg, 1,
1203                             UINT_MAX, &errstr);
1204                         if (errstr)
1205                                 fatal("Desired generator has bad value: %s (%s)",
1206                                         optarg, errstr);
1207                         break;
1208                 case 'a':
1209                         trials = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1210                         if (errstr)
1211                                 fatal("Invalid number of trials: %s (%s)",
1212                                         optarg, errstr);
1213                         break;
1214                 case 'M':
1215                         memory = (u_int32_t)strtonum(optarg, 1, UINT_MAX, &errstr);
1216                         if (errstr) {
1217                                 fatal("Memory limit is %s: %s", errstr, optarg);
1218                         }
1219                         break;
1220                 case 'G':
1221                         do_gen_candidates = 1;
1222                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1223                             sizeof(out_file))
1224                                 fatal("Output filename too long");
1225                         break;
1226                 case 'T':
1227                         do_screen_candidates = 1;
1228                         if (strlcpy(out_file, optarg, sizeof(out_file)) >=
1229                             sizeof(out_file))
1230                                 fatal("Output filename too long");
1231                         break;
1232                 case 'S':
1233                         /* XXX - also compare length against bits */
1234                         if (BN_hex2bn(&start, optarg) == 0)
1235                                 fatal("Invalid start point.");
1236                         break;
1237                 case '?':
1238                 default:
1239                         usage();
1240                 }
1241         }
1242
1243         /* reinit */
1244         log_init(argv[0], log_level, SYSLOG_FACILITY_USER, 1);
1245
1246         if (optind < argc) {
1247                 printf("Too many arguments.\n");
1248                 usage();
1249         }
1250         if (change_passphrase && change_comment) {
1251                 printf("Can only have one of -p and -c.\n");
1252                 usage();
1253         }
1254         if (print_fingerprint && (delete_host || hash_hosts)) {
1255                 printf("Cannot use -l with -D or -R.\n");
1256                 usage();
1257         }
1258         if (delete_host || hash_hosts || find_host)
1259                 do_known_hosts(pw, rr_hostname);
1260         if (print_fingerprint || print_bubblebabble)
1261                 do_fingerprint(pw);
1262         if (change_passphrase)
1263                 do_change_passphrase(pw);
1264         if (change_comment)
1265                 do_change_comment(pw);
1266         if (convert_to_ssh2)
1267                 do_convert_to_ssh2(pw);
1268         if (convert_from_ssh2)
1269                 do_convert_from_ssh2(pw);
1270         if (print_public)
1271                 do_print_public(pw);
1272         if (rr_hostname != NULL) {
1273                 unsigned int n = 0;
1274
1275                 if (have_identity) {
1276                         n = do_print_resource_record(pw,
1277                             identity_file, rr_hostname);
1278                         if (n == 0) {
1279                                 perror(identity_file);
1280                                 exit(1);
1281                         }
1282                         exit(0);
1283                 } else {
1284
1285                         n += do_print_resource_record(pw,
1286                             _PATH_HOST_RSA_KEY_FILE, rr_hostname);
1287                         n += do_print_resource_record(pw,
1288                             _PATH_HOST_DSA_KEY_FILE, rr_hostname);
1289
1290                         if (n == 0)
1291                                 fatal("no keys found.");
1292                         exit(0);
1293                 }
1294         }
1295         if (reader_id != NULL) {
1296 #ifdef SMARTCARD
1297                 if (download)
1298                         do_download(pw, reader_id);
1299                 else
1300                         do_upload(pw, reader_id);
1301 #else /* SMARTCARD */
1302                 fatal("no support for smartcards.");
1303 #endif /* SMARTCARD */
1304         }
1305
1306         if (do_gen_candidates) {
1307                 FILE *out = fopen(out_file, "w");
1308
1309                 if (out == NULL) {
1310                         error("Couldn't open modulus candidate file \"%s\": %s",
1311                             out_file, strerror(errno));
1312                         return (1);
1313                 }
1314                 if (bits == 0)
1315                         bits = DEFAULT_BITS;
1316                 if (gen_candidates(out, memory, bits, start) != 0)
1317                         fatal("modulus candidate generation failed");
1318
1319                 return (0);
1320         }
1321
1322         if (do_screen_candidates) {
1323                 FILE *in;
1324                 FILE *out = fopen(out_file, "w");
1325
1326                 if (have_identity && strcmp(identity_file, "-") != 0) {
1327                         if ((in = fopen(identity_file, "r")) == NULL) {
1328                                 fatal("Couldn't open modulus candidate "
1329                                     "file \"%s\": %s", identity_file,
1330                                     strerror(errno));
1331                         }
1332                 } else
1333                         in = stdin;
1334
1335                 if (out == NULL) {
1336                         fatal("Couldn't open moduli file \"%s\": %s",
1337                             out_file, strerror(errno));
1338                 }
1339                 if (prime_test(in, out, trials, generator_wanted) != 0)
1340                         fatal("modulus screening failed");
1341                 return (0);
1342         }
1343
1344         arc4random_stir();
1345
1346         if (key_type_name == NULL)
1347                 key_type_name = "rsa";
1348
1349         type = key_type_from_name(key_type_name);
1350         if (type == KEY_UNSPEC) {
1351                 fprintf(stderr, "unknown key type %s\n", key_type_name);
1352                 exit(1);
1353         }
1354         if (bits == 0)
1355                 bits = (type == KEY_DSA) ? DEFAULT_BITS_DSA : DEFAULT_BITS;
1356         if (type == KEY_DSA && bits != 1024)
1357                 fatal("DSA keys must be 1024 bits");
1358         if (!quiet)
1359                 printf("Generating public/private %s key pair.\n", key_type_name);
1360         private = key_generate(type, bits);
1361         if (private == NULL) {
1362                 fprintf(stderr, "key_generate failed");
1363                 exit(1);
1364         }
1365         public  = key_from_private(private);
1366
1367         if (!have_identity)
1368                 ask_filename(pw, "Enter file in which to save the key");
1369
1370         /* Create ~/.ssh directory if it doesn't already exist. */
1371         snprintf(dotsshdir, sizeof dotsshdir, "%s/%s", pw->pw_dir, _PATH_SSH_USER_DIR);
1372         if (strstr(identity_file, dotsshdir) != NULL &&
1373             stat(dotsshdir, &st) < 0) {
1374                 if (mkdir(dotsshdir, 0700) < 0)
1375                         error("Could not create directory '%s'.", dotsshdir);
1376                 else if (!quiet)
1377                         printf("Created directory '%s'.\n", dotsshdir);
1378         }
1379         /* If the file already exists, ask the user to confirm. */
1380         if (stat(identity_file, &st) >= 0) {
1381                 char yesno[3];
1382                 printf("%s already exists.\n", identity_file);
1383                 printf("Overwrite (y/n)? ");
1384                 fflush(stdout);
1385                 if (fgets(yesno, sizeof(yesno), stdin) == NULL)
1386                         exit(1);
1387                 if (yesno[0] != 'y' && yesno[0] != 'Y')
1388                         exit(1);
1389         }
1390         /* Ask for a passphrase (twice). */
1391         if (identity_passphrase)
1392                 passphrase1 = xstrdup(identity_passphrase);
1393         else if (identity_new_passphrase)
1394                 passphrase1 = xstrdup(identity_new_passphrase);
1395         else {
1396 passphrase_again:
1397                 passphrase1 =
1398                         read_passphrase("Enter passphrase (empty for no "
1399                             "passphrase): ", RP_ALLOW_STDIN);
1400                 passphrase2 = read_passphrase("Enter same passphrase again: ",
1401                     RP_ALLOW_STDIN);
1402                 if (strcmp(passphrase1, passphrase2) != 0) {
1403                         /*
1404                          * The passphrases do not match.  Clear them and
1405                          * retry.
1406                          */
1407                         memset(passphrase1, 0, strlen(passphrase1));
1408                         memset(passphrase2, 0, strlen(passphrase2));
1409                         xfree(passphrase1);
1410                         xfree(passphrase2);
1411                         printf("Passphrases do not match.  Try again.\n");
1412                         goto passphrase_again;
1413                 }
1414                 /* Clear the other copy of the passphrase. */
1415                 memset(passphrase2, 0, strlen(passphrase2));
1416                 xfree(passphrase2);
1417         }
1418
1419         if (identity_comment) {
1420                 strlcpy(comment, identity_comment, sizeof(comment));
1421         } else {
1422                 /* Create default commend field for the passphrase. */
1423                 snprintf(comment, sizeof comment, "%s@%s", pw->pw_name, hostname);
1424         }
1425
1426         /* Save the key with the given passphrase and comment. */
1427         if (!key_save_private(private, identity_file, passphrase1, comment)) {
1428                 printf("Saving the key failed: %s.\n", identity_file);
1429                 memset(passphrase1, 0, strlen(passphrase1));
1430                 xfree(passphrase1);
1431                 exit(1);
1432         }
1433         /* Clear the passphrase. */
1434         memset(passphrase1, 0, strlen(passphrase1));
1435         xfree(passphrase1);
1436
1437         /* Clear the private key and the random number generator. */
1438         key_free(private);
1439         arc4random_stir();
1440
1441         if (!quiet)
1442                 printf("Your identification has been saved in %s.\n", identity_file);
1443
1444         strlcat(identity_file, ".pub", sizeof(identity_file));
1445         fd = open(identity_file, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1446         if (fd == -1) {
1447                 printf("Could not save your public key in %s\n", identity_file);
1448                 exit(1);
1449         }
1450         f = fdopen(fd, "w");
1451         if (f == NULL) {
1452                 printf("fdopen %s failed", identity_file);
1453                 exit(1);
1454         }
1455         if (!key_write(public, f))
1456                 fprintf(stderr, "write key failed");
1457         fprintf(f, " %s\n", comment);
1458         fclose(f);
1459
1460         if (!quiet) {
1461                 char *fp = key_fingerprint(public, SSH_FP_MD5, SSH_FP_HEX);
1462                 char *ra = key_fingerprint(public, SSH_FP_MD5,
1463                     SSH_FP_RANDOMART);
1464                 printf("Your public key has been saved in %s.\n",
1465                     identity_file);
1466                 printf("The key fingerprint is:\n");
1467                 printf("%s %s\n", fp, comment);
1468                 printf("The key's randomart image is:\n");
1469                 printf("%s\n", ra);
1470                 xfree(ra);
1471                 xfree(fp);
1472         }
1473
1474         key_free(public);
1475         exit(0);
1476 }
This page took 0.16252 seconds and 5 git commands to generate.