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