]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshpubk.c
Remove the list of key algorithms in pageant.c.
[PuTTY.git] / sshpubk.c
1 /*
2  * Generic SSH public-key handling operations. In particular,
3  * reading of SSH public-key files, and also the generic `sign'
4  * operation for SSH-2 (which checks the type of the key and
5  * dispatches to the appropriate key-type specific function).
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <assert.h>
11
12 #include "putty.h"
13 #include "ssh.h"
14 #include "misc.h"
15
16 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
17
18 #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
19                           (x)-'a'<26 ? (x)-'a'+26 :\
20                           (x)-'0'<10 ? (x)-'0'+52 :\
21                           (x)=='+' ? 62 : \
22                           (x)=='/' ? 63 : 0 )
23
24 static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only,
25                            char **commentptr, char *passphrase,
26                            const char **error)
27 {
28     unsigned char buf[16384];
29     unsigned char keybuf[16];
30     int len;
31     int i, j, ciphertype;
32     int ret = 0;
33     struct MD5Context md5c;
34     char *comment;
35
36     *error = NULL;
37
38     /* Slurp the whole file (minus the header) into a buffer. */
39     len = fread(buf, 1, sizeof(buf), fp);
40     fclose(fp);
41     if (len < 0 || len == sizeof(buf)) {
42         *error = "error reading file";
43         goto end;                      /* file too big or not read */
44     }
45
46     i = 0;
47     *error = "file format error";
48
49     /*
50      * A zero byte. (The signature includes a terminating NUL.)
51      */
52     if (len - i < 1 || buf[i] != 0)
53         goto end;
54     i++;
55
56     /* One byte giving encryption type, and one reserved uint32. */
57     if (len - i < 1)
58         goto end;
59     ciphertype = buf[i];
60     if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
61         goto end;
62     i++;
63     if (len - i < 4)
64         goto end;                      /* reserved field not present */
65     if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
66         || buf[i + 3] != 0) goto end;  /* reserved field nonzero, panic! */
67     i += 4;
68
69     /* Now the serious stuff. An ordinary SSH-1 public key. */
70     j = makekey(buf + i, len - i, key, NULL, 1);
71     if (j < 0)
72         goto end;                      /* overran */
73     i += j;
74
75     /* Next, the comment field. */
76     j = toint(GET_32BIT(buf + i));
77     i += 4;
78     if (j < 0 || len - i < j)
79         goto end;
80     comment = snewn(j + 1, char);
81     if (comment) {
82         memcpy(comment, buf + i, j);
83         comment[j] = '\0';
84     }
85     i += j;
86     if (commentptr)
87         *commentptr = dupstr(comment);
88     if (key)
89         key->comment = comment;
90     else
91         sfree(comment);
92
93     if (pub_only) {
94         ret = 1;
95         goto end;
96     }
97
98     if (!key) {
99         ret = ciphertype != 0;
100         *error = NULL;
101         goto end;
102     }
103
104     /*
105      * Decrypt remainder of buffer.
106      */
107     if (ciphertype) {
108         MD5Init(&md5c);
109         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
110         MD5Final(keybuf, &md5c);
111         des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
112         smemclr(keybuf, sizeof(keybuf));        /* burn the evidence */
113     }
114
115     /*
116      * We are now in the secret part of the key. The first four
117      * bytes should be of the form a, b, a, b.
118      */
119     if (len - i < 4)
120         goto end;
121     if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
122         *error = "wrong passphrase";
123         ret = -1;
124         goto end;
125     }
126     i += 4;
127
128     /*
129      * After that, we have one further bignum which is our
130      * decryption exponent, and then the three auxiliary values
131      * (iqmp, q, p).
132      */
133     j = makeprivate(buf + i, len - i, key);
134     if (j < 0) goto end;
135     i += j;
136     j = ssh1_read_bignum(buf + i, len - i, &key->iqmp);
137     if (j < 0) goto end;
138     i += j;
139     j = ssh1_read_bignum(buf + i, len - i, &key->q);
140     if (j < 0) goto end;
141     i += j;
142     j = ssh1_read_bignum(buf + i, len - i, &key->p);
143     if (j < 0) goto end;
144     i += j;
145
146     if (!rsa_verify(key)) {
147         *error = "rsa_verify failed";
148         freersakey(key);
149         ret = 0;
150     } else
151         ret = 1;
152
153   end:
154     smemclr(buf, sizeof(buf));       /* burn the evidence */
155     return ret;
156 }
157
158 int loadrsakey(const Filename *filename, struct RSAKey *key, char *passphrase,
159                const char **errorstr)
160 {
161     FILE *fp;
162     char buf[64];
163     int ret = 0;
164     const char *error = NULL;
165
166     fp = f_open(filename, "rb", FALSE);
167     if (!fp) {
168         error = "can't open file";
169         goto end;
170     }
171
172     /*
173      * Read the first line of the file and see if it's a v1 private
174      * key file.
175      */
176     if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
177         /*
178          * This routine will take care of calling fclose() for us.
179          */
180         ret = loadrsakey_main(fp, key, FALSE, NULL, passphrase, &error);
181         fp = NULL;
182         goto end;
183     }
184
185     /*
186      * Otherwise, we have nothing. Return empty-handed.
187      */
188     error = "not an SSH-1 RSA file";
189
190   end:
191     if (fp)
192         fclose(fp);
193     if ((ret != 1) && errorstr)
194         *errorstr = error;
195     return ret;
196 }
197
198 /*
199  * See whether an RSA key is encrypted. Return its comment field as
200  * well.
201  */
202 int rsakey_encrypted(const Filename *filename, char **comment)
203 {
204     FILE *fp;
205     char buf[64];
206
207     fp = f_open(filename, "rb", FALSE);
208     if (!fp)
209         return 0;                      /* doesn't even exist */
210
211     /*
212      * Read the first line of the file and see if it's a v1 private
213      * key file.
214      */
215     if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
216         const char *dummy;
217         /*
218          * This routine will take care of calling fclose() for us.
219          */
220         return loadrsakey_main(fp, NULL, FALSE, comment, NULL, &dummy);
221     }
222     fclose(fp);
223     return 0;                          /* wasn't the right kind of file */
224 }
225
226 /*
227  * Return a malloc'ed chunk of memory containing the public blob of
228  * an RSA key, as given in the agent protocol (modulus bits,
229  * exponent, modulus).
230  */
231 int rsakey_pubblob(const Filename *filename, void **blob, int *bloblen,
232                    char **commentptr, const char **errorstr)
233 {
234     FILE *fp;
235     char buf[64];
236     struct RSAKey key;
237     int ret;
238     const char *error = NULL;
239
240     /* Default return if we fail. */
241     *blob = NULL;
242     *bloblen = 0;
243     ret = 0;
244
245     fp = f_open(filename, "rb", FALSE);
246     if (!fp) {
247         error = "can't open file";
248         goto end;
249     }
250
251     /*
252      * Read the first line of the file and see if it's a v1 private
253      * key file.
254      */
255     if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
256         memset(&key, 0, sizeof(key));
257         if (loadrsakey_main(fp, &key, TRUE, commentptr, NULL, &error)) {
258             *blob = rsa_public_blob(&key, bloblen);
259             freersakey(&key);
260             ret = 1;
261         }
262         fp = NULL; /* loadrsakey_main unconditionally closes fp */
263     } else {
264         error = "not an SSH-1 RSA file";
265     }
266
267   end:
268     if (fp)
269         fclose(fp);
270     if ((ret != 1) && errorstr)
271         *errorstr = error;
272     return ret;
273 }
274
275 /*
276  * Save an RSA key file. Return nonzero on success.
277  */
278 int saversakey(const Filename *filename, struct RSAKey *key, char *passphrase)
279 {
280     unsigned char buf[16384];
281     unsigned char keybuf[16];
282     struct MD5Context md5c;
283     unsigned char *p, *estart;
284     FILE *fp;
285
286     /*
287      * Write the initial signature.
288      */
289     p = buf;
290     memcpy(p, rsa_signature, sizeof(rsa_signature));
291     p += sizeof(rsa_signature);
292
293     /*
294      * One byte giving encryption type, and one reserved (zero)
295      * uint32.
296      */
297     *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
298     PUT_32BIT(p, 0);
299     p += 4;
300
301     /*
302      * An ordinary SSH-1 public key consists of: a uint32
303      * containing the bit count, then two bignums containing the
304      * modulus and exponent respectively.
305      */
306     PUT_32BIT(p, bignum_bitcount(key->modulus));
307     p += 4;
308     p += ssh1_write_bignum(p, key->modulus);
309     p += ssh1_write_bignum(p, key->exponent);
310
311     /*
312      * A string containing the comment field.
313      */
314     if (key->comment) {
315         PUT_32BIT(p, strlen(key->comment));
316         p += 4;
317         memcpy(p, key->comment, strlen(key->comment));
318         p += strlen(key->comment);
319     } else {
320         PUT_32BIT(p, 0);
321         p += 4;
322     }
323
324     /*
325      * The encrypted portion starts here.
326      */
327     estart = p;
328
329     /*
330      * Two bytes, then the same two bytes repeated.
331      */
332     *p++ = random_byte();
333     *p++ = random_byte();
334     p[0] = p[-2];
335     p[1] = p[-1];
336     p += 2;
337
338     /*
339      * Four more bignums: the decryption exponent, then iqmp, then
340      * q, then p.
341      */
342     p += ssh1_write_bignum(p, key->private_exponent);
343     p += ssh1_write_bignum(p, key->iqmp);
344     p += ssh1_write_bignum(p, key->q);
345     p += ssh1_write_bignum(p, key->p);
346
347     /*
348      * Now write zeros until the encrypted portion is a multiple of
349      * 8 bytes.
350      */
351     while ((p - estart) % 8)
352         *p++ = '\0';
353
354     /*
355      * Now encrypt the encrypted portion.
356      */
357     if (passphrase) {
358         MD5Init(&md5c);
359         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
360         MD5Final(keybuf, &md5c);
361         des3_encrypt_pubkey(keybuf, estart, p - estart);
362         smemclr(keybuf, sizeof(keybuf));        /* burn the evidence */
363     }
364
365     /*
366      * Done. Write the result to the file.
367      */
368     fp = f_open(filename, "wb", TRUE);
369     if (fp) {
370         int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
371         if (fclose(fp))
372             ret = 0;
373         return ret;
374     } else
375         return 0;
376 }
377
378 /* ----------------------------------------------------------------------
379  * SSH-2 private key load/store functions.
380  */
381
382 /*
383  * PuTTY's own format for SSH-2 keys is as follows:
384  *
385  * The file is text. Lines are terminated by CRLF, although CR-only
386  * and LF-only are tolerated on input.
387  *
388  * The first line says "PuTTY-User-Key-File-2: " plus the name of the
389  * algorithm ("ssh-dss", "ssh-rsa" etc).
390  *
391  * The next line says "Encryption: " plus an encryption type.
392  * Currently the only supported encryption types are "aes256-cbc"
393  * and "none".
394  *
395  * The next line says "Comment: " plus the comment string.
396  *
397  * Next there is a line saying "Public-Lines: " plus a number N.
398  * The following N lines contain a base64 encoding of the public
399  * part of the key. This is encoded as the standard SSH-2 public key
400  * blob (with no initial length): so for RSA, for example, it will
401  * read
402  *
403  *    string "ssh-rsa"
404  *    mpint  exponent
405  *    mpint  modulus
406  *
407  * Next, there is a line saying "Private-Lines: " plus a number N,
408  * and then N lines containing the (potentially encrypted) private
409  * part of the key. For the key type "ssh-rsa", this will be
410  * composed of
411  *
412  *    mpint  private_exponent
413  *    mpint  p                  (the larger of the two primes)
414  *    mpint  q                  (the smaller prime)
415  *    mpint  iqmp               (the inverse of q modulo p)
416  *    data   padding            (to reach a multiple of the cipher block size)
417  *
418  * And for "ssh-dss", it will be composed of
419  *
420  *    mpint  x                  (the private key parameter)
421  *  [ string hash   20-byte hash of mpints p || q || g   only in old format ]
422  * 
423  * Finally, there is a line saying "Private-MAC: " plus a hex
424  * representation of a HMAC-SHA-1 of:
425  *
426  *    string  name of algorithm ("ssh-dss", "ssh-rsa")
427  *    string  encryption type
428  *    string  comment
429  *    string  public-blob
430  *    string  private-plaintext (the plaintext version of the
431  *                               private part, including the final
432  *                               padding)
433  * 
434  * The key to the MAC is itself a SHA-1 hash of:
435  * 
436  *    data    "putty-private-key-file-mac-key"
437  *    data    passphrase
438  *
439  * (An empty passphrase is used for unencrypted keys.)
440  *
441  * If the key is encrypted, the encryption key is derived from the
442  * passphrase by means of a succession of SHA-1 hashes. Each hash
443  * is the hash of:
444  *
445  *    uint32  sequence-number
446  *    data    passphrase
447  *
448  * where the sequence-number increases from zero. As many of these
449  * hashes are used as necessary.
450  *
451  * For backwards compatibility with snapshots between 0.51 and
452  * 0.52, we also support the older key file format, which begins
453  * with "PuTTY-User-Key-File-1" (version number differs). In this
454  * format the Private-MAC: field only covers the private-plaintext
455  * field and nothing else (and without the 4-byte string length on
456  * the front too). Moreover, the Private-MAC: field can be replaced
457  * with a Private-Hash: field which is a plain SHA-1 hash instead of
458  * an HMAC (this was generated for unencrypted keys).
459  */
460
461 static int read_header(FILE * fp, char *header)
462 {
463     int len = 39;
464     int c;
465
466     while (1) {
467         c = fgetc(fp);
468         if (c == '\n' || c == '\r' || c == EOF)
469             return 0;                  /* failure */
470         if (c == ':') {
471             c = fgetc(fp);
472             if (c != ' ')
473                 return 0;
474             *header = '\0';
475             return 1;                  /* success! */
476         }
477         if (len == 0)
478             return 0;                  /* failure */
479         *header++ = c;
480         len--;
481     }
482     return 0;                          /* failure */
483 }
484
485 static char *read_body(FILE * fp)
486 {
487     char *text;
488     int len;
489     int size;
490     int c;
491
492     size = 128;
493     text = snewn(size, char);
494     len = 0;
495     text[len] = '\0';
496
497     while (1) {
498         c = fgetc(fp);
499         if (c == '\r' || c == '\n' || c == EOF) {
500             if (c != EOF) {
501                 c = fgetc(fp);
502                 if (c != '\r' && c != '\n')
503                     ungetc(c, fp);
504             }
505             return text;
506         }
507         if (len + 1 >= size) {
508             size += 128;
509             text = sresize(text, size, char);
510         }
511         text[len++] = c;
512         text[len] = '\0';
513     }
514 }
515
516 static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)
517 {
518     unsigned char *blob;
519     char *line;
520     int linelen, len;
521     int i, j, k;
522
523     /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
524     blob = snewn(48 * nlines, unsigned char);
525     len = 0;
526     for (i = 0; i < nlines; i++) {
527         line = read_body(fp);
528         if (!line) {
529             sfree(blob);
530             return NULL;
531         }
532         linelen = strlen(line);
533         if (linelen % 4 != 0 || linelen > 64) {
534             sfree(blob);
535             sfree(line);
536             return NULL;
537         }
538         for (j = 0; j < linelen; j += 4) {
539             k = base64_decode_atom(line + j, blob + len);
540             if (!k) {
541                 sfree(line);
542                 sfree(blob);
543                 return NULL;
544             }
545             len += k;
546         }
547         sfree(line);
548     }
549     *bloblen = len;
550     return blob;
551 }
552
553 /*
554  * Magic error return value for when the passphrase is wrong.
555  */
556 struct ssh2_userkey ssh2_wrong_passphrase = {
557     NULL, NULL, NULL
558 };
559
560 const struct ssh_signkey *find_pubkey_alg_len(int namelen, const char *name)
561 {
562     if (match_ssh_id(namelen, name, "ssh-rsa"))
563         return &ssh_rsa;
564     else if (match_ssh_id(namelen, name, "ssh-dss"))
565         return &ssh_dss;
566     else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp256"))
567         return &ssh_ecdsa_nistp256;
568     else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp384"))
569         return &ssh_ecdsa_nistp384;
570     else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp521"))
571         return &ssh_ecdsa_nistp521;
572     else
573         return NULL;
574 }
575
576 const struct ssh_signkey *find_pubkey_alg(const char *name)
577 {
578     return find_pubkey_alg_len(strlen(name), name);
579 }
580
581 struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,
582                                        char *passphrase, const char **errorstr)
583 {
584     FILE *fp;
585     char header[40], *b, *encryption, *comment, *mac;
586     const struct ssh_signkey *alg;
587     struct ssh2_userkey *ret;
588     int cipher, cipherblk;
589     unsigned char *public_blob, *private_blob;
590     int public_blob_len, private_blob_len;
591     int i, is_mac, old_fmt;
592     int passlen = passphrase ? strlen(passphrase) : 0;
593     const char *error = NULL;
594
595     ret = NULL;                        /* return NULL for most errors */
596     encryption = comment = mac = NULL;
597     public_blob = private_blob = NULL;
598
599     fp = f_open(filename, "rb", FALSE);
600     if (!fp) {
601         error = "can't open file";
602         goto error;
603     }
604
605     /* Read the first header line which contains the key type. */
606     if (!read_header(fp, header))
607         goto error;
608     if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
609         old_fmt = 0;
610     } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
611         /* this is an old key file; warn and then continue */
612         old_keyfile_warning();
613         old_fmt = 1;
614     } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
615         /* this is a key file FROM THE FUTURE; refuse it, but with a
616          * more specific error message than the generic one below */
617         error = "PuTTY key format too new";
618         goto error;
619     } else {
620         error = "not a PuTTY SSH-2 private key";
621         goto error;
622     }
623     error = "file format error";
624     if ((b = read_body(fp)) == NULL)
625         goto error;
626     /* Select key algorithm structure. */
627     alg = find_pubkey_alg(b);
628     if (!alg) {
629         sfree(b);
630         goto error;
631     }
632     sfree(b);
633
634     /* Read the Encryption header line. */
635     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
636         goto error;
637     if ((encryption = read_body(fp)) == NULL)
638         goto error;
639     if (!strcmp(encryption, "aes256-cbc")) {
640         cipher = 1;
641         cipherblk = 16;
642     } else if (!strcmp(encryption, "none")) {
643         cipher = 0;
644         cipherblk = 1;
645     } else {
646         goto error;
647     }
648
649     /* Read the Comment header line. */
650     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
651         goto error;
652     if ((comment = read_body(fp)) == NULL)
653         goto error;
654
655     /* Read the Public-Lines header line and the public blob. */
656     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
657         goto error;
658     if ((b = read_body(fp)) == NULL)
659         goto error;
660     i = atoi(b);
661     sfree(b);
662     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
663         goto error;
664
665     /* Read the Private-Lines header line and the Private blob. */
666     if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
667         goto error;
668     if ((b = read_body(fp)) == NULL)
669         goto error;
670     i = atoi(b);
671     sfree(b);
672     if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
673         goto error;
674
675     /* Read the Private-MAC or Private-Hash header line. */
676     if (!read_header(fp, header))
677         goto error;
678     if (0 == strcmp(header, "Private-MAC")) {
679         if ((mac = read_body(fp)) == NULL)
680             goto error;
681         is_mac = 1;
682     } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {
683         if ((mac = read_body(fp)) == NULL)
684             goto error;
685         is_mac = 0;
686     } else
687         goto error;
688
689     fclose(fp);
690     fp = NULL;
691
692     /*
693      * Decrypt the private blob.
694      */
695     if (cipher) {
696         unsigned char key[40];
697         SHA_State s;
698
699         if (!passphrase)
700             goto error;
701         if (private_blob_len % cipherblk)
702             goto error;
703
704         SHA_Init(&s);
705         SHA_Bytes(&s, "\0\0\0\0", 4);
706         SHA_Bytes(&s, passphrase, passlen);
707         SHA_Final(&s, key + 0);
708         SHA_Init(&s);
709         SHA_Bytes(&s, "\0\0\0\1", 4);
710         SHA_Bytes(&s, passphrase, passlen);
711         SHA_Final(&s, key + 20);
712         aes256_decrypt_pubkey(key, private_blob, private_blob_len);
713     }
714
715     /*
716      * Verify the MAC.
717      */
718     {
719         char realmac[41];
720         unsigned char binary[20];
721         unsigned char *macdata;
722         int maclen;
723         int free_macdata;
724
725         if (old_fmt) {
726             /* MAC (or hash) only covers the private blob. */
727             macdata = private_blob;
728             maclen = private_blob_len;
729             free_macdata = 0;
730         } else {
731             unsigned char *p;
732             int namelen = strlen(alg->name);
733             int enclen = strlen(encryption);
734             int commlen = strlen(comment);
735             maclen = (4 + namelen +
736                       4 + enclen +
737                       4 + commlen +
738                       4 + public_blob_len +
739                       4 + private_blob_len);
740             macdata = snewn(maclen, unsigned char);
741             p = macdata;
742 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
743             DO_STR(alg->name, namelen);
744             DO_STR(encryption, enclen);
745             DO_STR(comment, commlen);
746             DO_STR(public_blob, public_blob_len);
747             DO_STR(private_blob, private_blob_len);
748
749             free_macdata = 1;
750         }
751
752         if (is_mac) {
753             SHA_State s;
754             unsigned char mackey[20];
755             char header[] = "putty-private-key-file-mac-key";
756
757             SHA_Init(&s);
758             SHA_Bytes(&s, header, sizeof(header)-1);
759             if (cipher && passphrase)
760                 SHA_Bytes(&s, passphrase, passlen);
761             SHA_Final(&s, mackey);
762
763             hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
764
765             smemclr(mackey, sizeof(mackey));
766             smemclr(&s, sizeof(s));
767         } else {
768             SHA_Simple(macdata, maclen, binary);
769         }
770
771         if (free_macdata) {
772             smemclr(macdata, maclen);
773             sfree(macdata);
774         }
775
776         for (i = 0; i < 20; i++)
777             sprintf(realmac + 2 * i, "%02x", binary[i]);
778
779         if (strcmp(mac, realmac)) {
780             /* An incorrect MAC is an unconditional Error if the key is
781              * unencrypted. Otherwise, it means Wrong Passphrase. */
782             if (cipher) {
783                 error = "wrong passphrase";
784                 ret = SSH2_WRONG_PASSPHRASE;
785             } else {
786                 error = "MAC failed";
787                 ret = NULL;
788             }
789             goto error;
790         }
791     }
792     sfree(mac);
793     mac = NULL;
794
795     /*
796      * Create and return the key.
797      */
798     ret = snew(struct ssh2_userkey);
799     ret->alg = alg;
800     ret->comment = comment;
801     ret->data = alg->createkey(public_blob, public_blob_len,
802                                private_blob, private_blob_len);
803     if (!ret->data) {
804         sfree(ret);
805         ret = NULL;
806         error = "createkey failed";
807         goto error;
808     }
809     sfree(public_blob);
810     smemclr(private_blob, private_blob_len);
811     sfree(private_blob);
812     sfree(encryption);
813     if (errorstr)
814         *errorstr = NULL;
815     return ret;
816
817     /*
818      * Error processing.
819      */
820   error:
821     if (fp)
822         fclose(fp);
823     if (comment)
824         sfree(comment);
825     if (encryption)
826         sfree(encryption);
827     if (mac)
828         sfree(mac);
829     if (public_blob)
830         sfree(public_blob);
831     if (private_blob) {
832         smemclr(private_blob, private_blob_len);
833         sfree(private_blob);
834     }
835     if (errorstr)
836         *errorstr = error;
837     return ret;
838 }
839
840 unsigned char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
841                                     int *pub_blob_len, char **commentptr,
842                                     const char **errorstr)
843 {
844     FILE *fp;
845     char header[40], *b;
846     const struct ssh_signkey *alg;
847     unsigned char *public_blob;
848     int public_blob_len;
849     int i;
850     const char *error = NULL;
851     char *comment = NULL;
852
853     public_blob = NULL;
854
855     fp = f_open(filename, "rb", FALSE);
856     if (!fp) {
857         error = "can't open file";
858         goto error;
859     }
860
861     /* Read the first header line which contains the key type. */
862     if (!read_header(fp, header)
863         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
864             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
865         if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
866             error = "PuTTY key format too new";
867         else
868             error = "not a PuTTY SSH-2 private key";
869         goto error;
870     }
871     error = "file format error";
872     if ((b = read_body(fp)) == NULL)
873         goto error;
874     /* Select key algorithm structure. */
875     alg = find_pubkey_alg(b);
876     sfree(b);
877     if (!alg) {
878         goto error;
879     }
880
881     /* Read the Encryption header line. */
882     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
883         goto error;
884     if ((b = read_body(fp)) == NULL)
885         goto error;
886     sfree(b);                          /* we don't care */
887
888     /* Read the Comment header line. */
889     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
890         goto error;
891     if ((comment = read_body(fp)) == NULL)
892         goto error;
893
894     if (commentptr)
895         *commentptr = comment;
896     else
897         sfree(comment);
898
899     /* Read the Public-Lines header line and the public blob. */
900     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
901         goto error;
902     if ((b = read_body(fp)) == NULL)
903         goto error;
904     i = atoi(b);
905     sfree(b);
906     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
907         goto error;
908
909     fclose(fp);
910     if (pub_blob_len)
911         *pub_blob_len = public_blob_len;
912     if (algorithm)
913         *algorithm = alg->name;
914     return public_blob;
915
916     /*
917      * Error processing.
918      */
919   error:
920     if (fp)
921         fclose(fp);
922     if (public_blob)
923         sfree(public_blob);
924     if (errorstr)
925         *errorstr = error;
926     if (comment && commentptr) {
927         sfree(comment);
928         *commentptr = NULL;
929     }
930     return NULL;
931 }
932
933 int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
934 {
935     FILE *fp;
936     char header[40], *b, *comment;
937     int ret;
938
939     if (commentptr)
940         *commentptr = NULL;
941
942     fp = f_open(filename, "rb", FALSE);
943     if (!fp)
944         return 0;
945     if (!read_header(fp, header)
946         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
947             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
948         fclose(fp);
949         return 0;
950     }
951     if ((b = read_body(fp)) == NULL) {
952         fclose(fp);
953         return 0;
954     }
955     sfree(b);                          /* we don't care about key type here */
956     /* Read the Encryption header line. */
957     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
958         fclose(fp);
959         return 0;
960     }
961     if ((b = read_body(fp)) == NULL) {
962         fclose(fp);
963         return 0;
964     }
965
966     /* Read the Comment header line. */
967     if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
968         fclose(fp);
969         sfree(b);
970         return 1;
971     }
972     if ((comment = read_body(fp)) == NULL) {
973         fclose(fp);
974         sfree(b);
975         return 1;
976     }
977
978     if (commentptr)
979         *commentptr = comment;
980     else
981         sfree(comment);
982
983     fclose(fp);
984     if (!strcmp(b, "aes256-cbc"))
985         ret = 1;
986     else
987         ret = 0;
988     sfree(b);
989     return ret;
990 }
991
992 int base64_lines(int datalen)
993 {
994     /* When encoding, we use 64 chars/line, which equals 48 real chars. */
995     return (datalen + 47) / 48;
996 }
997
998 void base64_encode(FILE * fp, unsigned char *data, int datalen, int cpl)
999 {
1000     int linelen = 0;
1001     char out[4];
1002     int n, i;
1003
1004     while (datalen > 0) {
1005         n = (datalen < 3 ? datalen : 3);
1006         base64_encode_atom(data, n, out);
1007         data += n;
1008         datalen -= n;
1009         for (i = 0; i < 4; i++) {
1010             if (linelen >= cpl) {
1011                 linelen = 0;
1012                 fputc('\n', fp);
1013             }
1014             fputc(out[i], fp);
1015             linelen++;
1016         }
1017     }
1018     fputc('\n', fp);
1019 }
1020
1021 int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
1022                       char *passphrase)
1023 {
1024     FILE *fp;
1025     unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1026     int pub_blob_len, priv_blob_len, priv_encrypted_len;
1027     int passlen;
1028     int cipherblk;
1029     int i;
1030     char *cipherstr;
1031     unsigned char priv_mac[20];
1032
1033     /*
1034      * Fetch the key component blobs.
1035      */
1036     pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1037     priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1038     if (!pub_blob || !priv_blob) {
1039         sfree(pub_blob);
1040         sfree(priv_blob);
1041         return 0;
1042     }
1043
1044     /*
1045      * Determine encryption details, and encrypt the private blob.
1046      */
1047     if (passphrase) {
1048         cipherstr = "aes256-cbc";
1049         cipherblk = 16;
1050     } else {
1051         cipherstr = "none";
1052         cipherblk = 1;
1053     }
1054     priv_encrypted_len = priv_blob_len + cipherblk - 1;
1055     priv_encrypted_len -= priv_encrypted_len % cipherblk;
1056     priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
1057     memset(priv_blob_encrypted, 0, priv_encrypted_len);
1058     memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1059     /* Create padding based on the SHA hash of the unpadded blob. This prevents
1060      * too easy a known-plaintext attack on the last block. */
1061     SHA_Simple(priv_blob, priv_blob_len, priv_mac);
1062     assert(priv_encrypted_len - priv_blob_len < 20);
1063     memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
1064            priv_encrypted_len - priv_blob_len);
1065
1066     /* Now create the MAC. */
1067     {
1068         unsigned char *macdata;
1069         int maclen;
1070         unsigned char *p;
1071         int namelen = strlen(key->alg->name);
1072         int enclen = strlen(cipherstr);
1073         int commlen = strlen(key->comment);
1074         SHA_State s;
1075         unsigned char mackey[20];
1076         char header[] = "putty-private-key-file-mac-key";
1077
1078         maclen = (4 + namelen +
1079                   4 + enclen +
1080                   4 + commlen +
1081                   4 + pub_blob_len +
1082                   4 + priv_encrypted_len);
1083         macdata = snewn(maclen, unsigned char);
1084         p = macdata;
1085 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1086         DO_STR(key->alg->name, namelen);
1087         DO_STR(cipherstr, enclen);
1088         DO_STR(key->comment, commlen);
1089         DO_STR(pub_blob, pub_blob_len);
1090         DO_STR(priv_blob_encrypted, priv_encrypted_len);
1091
1092         SHA_Init(&s);
1093         SHA_Bytes(&s, header, sizeof(header)-1);
1094         if (passphrase)
1095             SHA_Bytes(&s, passphrase, strlen(passphrase));
1096         SHA_Final(&s, mackey);
1097         hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1098         smemclr(macdata, maclen);
1099         sfree(macdata);
1100         smemclr(mackey, sizeof(mackey));
1101         smemclr(&s, sizeof(s));
1102     }
1103
1104     if (passphrase) {
1105         unsigned char key[40];
1106         SHA_State s;
1107
1108         passlen = strlen(passphrase);
1109
1110         SHA_Init(&s);
1111         SHA_Bytes(&s, "\0\0\0\0", 4);
1112         SHA_Bytes(&s, passphrase, passlen);
1113         SHA_Final(&s, key + 0);
1114         SHA_Init(&s);
1115         SHA_Bytes(&s, "\0\0\0\1", 4);
1116         SHA_Bytes(&s, passphrase, passlen);
1117         SHA_Final(&s, key + 20);
1118         aes256_encrypt_pubkey(key, priv_blob_encrypted,
1119                               priv_encrypted_len);
1120
1121         smemclr(key, sizeof(key));
1122         smemclr(&s, sizeof(s));
1123     }
1124
1125     fp = f_open(filename, "w", TRUE);
1126     if (!fp) {
1127         sfree(pub_blob);
1128         smemclr(priv_blob, priv_blob_len);
1129         sfree(priv_blob);
1130         smemclr(priv_blob_encrypted, priv_blob_len);
1131         sfree(priv_blob_encrypted);
1132         return 0;
1133     }
1134     fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
1135     fprintf(fp, "Encryption: %s\n", cipherstr);
1136     fprintf(fp, "Comment: %s\n", key->comment);
1137     fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1138     base64_encode(fp, pub_blob, pub_blob_len, 64);
1139     fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1140     base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
1141     fprintf(fp, "Private-MAC: ");
1142     for (i = 0; i < 20; i++)
1143         fprintf(fp, "%02x", priv_mac[i]);
1144     fprintf(fp, "\n");
1145     fclose(fp);
1146
1147     sfree(pub_blob);
1148     smemclr(priv_blob, priv_blob_len);
1149     sfree(priv_blob);
1150     smemclr(priv_blob_encrypted, priv_blob_len);
1151     sfree(priv_blob_encrypted);
1152     return 1;
1153 }
1154
1155 /* ----------------------------------------------------------------------
1156  * A function to determine the type of a private key file. Returns
1157  * 0 on failure, 1 or 2 on success.
1158  */
1159 int key_type(const Filename *filename)
1160 {
1161     FILE *fp;
1162     char buf[32];
1163     const char putty2_sig[] = "PuTTY-User-Key-File-";
1164     const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1165     const char openssh_new_sig[] = "-----BEGIN OPENSSH PRIVATE KEY";
1166     const char openssh_sig[] = "-----BEGIN ";
1167     int i;
1168
1169     fp = f_open(filename, "r", FALSE);
1170     if (!fp)
1171         return SSH_KEYTYPE_UNOPENABLE;
1172     i = fread(buf, 1, sizeof(buf), fp);
1173     fclose(fp);
1174     if (i < 0)
1175         return SSH_KEYTYPE_UNOPENABLE;
1176     if (i < 32)
1177         return SSH_KEYTYPE_UNKNOWN;
1178     if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1179         return SSH_KEYTYPE_SSH1;
1180     if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1181         return SSH_KEYTYPE_SSH2;
1182     if (!memcmp(buf, openssh_new_sig, sizeof(openssh_new_sig)-1))
1183         return SSH_KEYTYPE_OPENSSH_NEW;
1184     if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1185         return SSH_KEYTYPE_OPENSSH_PEM;
1186     if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1187         return SSH_KEYTYPE_SSHCOM;
1188     return SSH_KEYTYPE_UNKNOWN;        /* unrecognised or EOF */
1189 }
1190
1191 /*
1192  * Convert the type word to a string, for `wrong type' error
1193  * messages.
1194  */
1195 char *key_type_to_str(int type)
1196 {
1197     switch (type) {
1198       case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1199       case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;
1200       case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
1201       case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
1202       case SSH_KEYTYPE_OPENSSH_PEM: return "OpenSSH SSH-2 private key (old PEM format)"; break;
1203       case SSH_KEYTYPE_OPENSSH_NEW: return "OpenSSH SSH-2 private key (new format)"; break;
1204       case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
1205       default: return "INTERNAL ERROR"; break;
1206     }
1207 }