]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - sshpubk.c
Trivial bug fix pointed out by Paul Fox: potentially missing fclose().
[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, len, key, NULL, 1);
83     if (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     j = makeprivate(buf + i, len - i, key);
142     if (j < 0) goto end;
143     i += j;
144     j = ssh1_read_bignum(buf + i, len - i, &key->iqmp);
145     if (j < 0) goto end;
146     i += j;
147     j = ssh1_read_bignum(buf + i, len - i, &key->q);
148     if (j < 0) goto end;
149     i += j;
150     j = ssh1_read_bignum(buf + i, len - i, &key->p);
151     if (j < 0) goto end;
152     i += j;
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         if (fclose(fp))
380             ret = 0;
381         return ret;
382     } else
383         return 0;
384 }
385
386 /* ----------------------------------------------------------------------
387  * SSH2 private key load/store functions.
388  */
389
390 /*
391  * PuTTY's own format for SSH2 keys is as follows:
392  *
393  * The file is text. Lines are terminated by CRLF, although CR-only
394  * and LF-only are tolerated on input.
395  *
396  * The first line says "PuTTY-User-Key-File-2: " plus the name of the
397  * algorithm ("ssh-dss", "ssh-rsa" etc).
398  *
399  * The next line says "Encryption: " plus an encryption type.
400  * Currently the only supported encryption types are "aes256-cbc"
401  * and "none".
402  *
403  * The next line says "Comment: " plus the comment string.
404  *
405  * Next there is a line saying "Public-Lines: " plus a number N.
406  * The following N lines contain a base64 encoding of the public
407  * part of the key. This is encoded as the standard SSH2 public key
408  * blob (with no initial length): so for RSA, for example, it will
409  * read
410  *
411  *    string "ssh-rsa"
412  *    mpint  exponent
413  *    mpint  modulus
414  *
415  * Next, there is a line saying "Private-Lines: " plus a number N,
416  * and then N lines containing the (potentially encrypted) private
417  * part of the key. For the key type "ssh-rsa", this will be
418  * composed of
419  *
420  *    mpint  private_exponent
421  *    mpint  p                  (the larger of the two primes)
422  *    mpint  q                  (the smaller prime)
423  *    mpint  iqmp               (the inverse of q modulo p)
424  *    data   padding            (to reach a multiple of the cipher block size)
425  *
426  * And for "ssh-dss", it will be composed of
427  *
428  *    mpint  x                  (the private key parameter)
429  *  [ string hash   20-byte hash of mpints p || q || g   only in old format ]
430  * 
431  * Finally, there is a line saying "Private-MAC: " plus a hex
432  * representation of a HMAC-SHA-1 of:
433  *
434  *    string  name of algorithm ("ssh-dss", "ssh-rsa")
435  *    string  encryption type
436  *    string  comment
437  *    string  public-blob
438  *    string  private-plaintext (the plaintext version of the
439  *                               private part, including the final
440  *                               padding)
441  * 
442  * The key to the MAC is itself a SHA-1 hash of:
443  * 
444  *    data    "putty-private-key-file-mac-key"
445  *    data    passphrase
446  *
447  * (An empty passphrase is used for unencrypted keys.)
448  *
449  * If the key is encrypted, the encryption key is derived from the
450  * passphrase by means of a succession of SHA-1 hashes. Each hash
451  * is the hash of:
452  *
453  *    uint32  sequence-number
454  *    data    passphrase
455  *
456  * where the sequence-number increases from zero. As many of these
457  * hashes are used as necessary.
458  *
459  * For backwards compatibility with snapshots between 0.51 and
460  * 0.52, we also support the older key file format, which begins
461  * with "PuTTY-User-Key-File-1" (version number differs). In this
462  * format the Private-MAC: field only covers the private-plaintext
463  * field and nothing else (and without the 4-byte string length on
464  * the front too). Moreover, for RSA keys the Private-MAC: field
465  * can be replaced with a Private-Hash: field which is a plain
466  * SHA-1 hash instead of an HMAC. This is not allowable in DSA
467  * keys. (Yes, the old format was a mess. Guess why it changed :-)
468  */
469
470 static int read_header(FILE * fp, char *header)
471 {
472     int len = 39;
473     int c;
474
475     while (len > 0) {
476         c = fgetc(fp);
477         if (c == '\n' || c == '\r' || c == EOF)
478             return 0;                  /* failure */
479         if (c == ':') {
480             c = fgetc(fp);
481             if (c != ' ')
482                 return 0;
483             *header = '\0';
484             return 1;                  /* success! */
485         }
486         if (len == 0)
487             return 0;                  /* failure */
488         *header++ = c;
489         len--;
490     }
491     return 0;                          /* failure */
492 }
493
494 static char *read_body(FILE * fp)
495 {
496     char *text;
497     int len;
498     int size;
499     int c;
500
501     size = 128;
502     text = snewn(size, char);
503     len = 0;
504     text[len] = '\0';
505
506     while (1) {
507         c = fgetc(fp);
508         if (c == '\r' || c == '\n') {
509             c = fgetc(fp);
510             if (c != '\r' && c != '\n' && c != EOF)
511                 ungetc(c, fp);
512             return text;
513         }
514         if (c == EOF) {
515             sfree(text);
516             return NULL;
517         }
518         if (len + 1 > size) {
519             size += 128;
520             text = sresize(text, size, char);
521         }
522         text[len++] = c;
523         text[len] = '\0';
524     }
525 }
526
527 int base64_decode_atom(char *atom, unsigned char *out)
528 {
529     int vals[4];
530     int i, v, len;
531     unsigned word;
532     char c;
533
534     for (i = 0; i < 4; i++) {
535         c = atom[i];
536         if (c >= 'A' && c <= 'Z')
537             v = c - 'A';
538         else if (c >= 'a' && c <= 'z')
539             v = c - 'a' + 26;
540         else if (c >= '0' && c <= '9')
541             v = c - '0' + 52;
542         else if (c == '+')
543             v = 62;
544         else if (c == '/')
545             v = 63;
546         else if (c == '=')
547             v = -1;
548         else
549             return 0;                  /* invalid atom */
550         vals[i] = v;
551     }
552
553     if (vals[0] == -1 || vals[1] == -1)
554         return 0;
555     if (vals[2] == -1 && vals[3] != -1)
556         return 0;
557
558     if (vals[3] != -1)
559         len = 3;
560     else if (vals[2] != -1)
561         len = 2;
562     else
563         len = 1;
564
565     word = ((vals[0] << 18) |
566             (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
567     out[0] = (word >> 16) & 0xFF;
568     if (len > 1)
569         out[1] = (word >> 8) & 0xFF;
570     if (len > 2)
571         out[2] = word & 0xFF;
572     return len;
573 }
574
575 static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)
576 {
577     unsigned char *blob;
578     char *line;
579     int linelen, len;
580     int i, j, k;
581
582     /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
583     blob = snewn(48 * nlines, unsigned char);
584     len = 0;
585     for (i = 0; i < nlines; i++) {
586         line = read_body(fp);
587         if (!line) {
588             sfree(blob);
589             return NULL;
590         }
591         linelen = strlen(line);
592         if (linelen % 4 != 0 || linelen > 64) {
593             sfree(blob);
594             sfree(line);
595             return NULL;
596         }
597         for (j = 0; j < linelen; j += 4) {
598             k = base64_decode_atom(line + j, blob + len);
599             if (!k) {
600                 sfree(line);
601                 sfree(blob);
602                 return NULL;
603             }
604             len += k;
605         }
606         sfree(line);
607     }
608     *bloblen = len;
609     return blob;
610 }
611
612 /*
613  * Magic error return value for when the passphrase is wrong.
614  */
615 struct ssh2_userkey ssh2_wrong_passphrase = {
616     NULL, NULL, NULL
617 };
618
619 const struct ssh_signkey *find_pubkey_alg(const char *name)
620 {
621     if (!strcmp(name, "ssh-rsa"))
622         return &ssh_rsa;
623     else if (!strcmp(name, "ssh-dss"))
624         return &ssh_dss;
625     else
626         return NULL;
627 }
628
629 struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,
630                                        char *passphrase, const char **errorstr)
631 {
632     FILE *fp;
633     char header[40], *b, *encryption, *comment, *mac;
634     const struct ssh_signkey *alg;
635     struct ssh2_userkey *ret;
636     int cipher, cipherblk;
637     unsigned char *public_blob, *private_blob;
638     int public_blob_len, private_blob_len;
639     int i, is_mac, old_fmt;
640     int passlen = passphrase ? strlen(passphrase) : 0;
641     const char *error = NULL;
642
643     ret = NULL;                        /* return NULL for most errors */
644     encryption = comment = mac = NULL;
645     public_blob = private_blob = NULL;
646
647     fp = f_open(*filename, "rb");
648     if (!fp) {
649         error = "can't open file";
650         goto error;
651     }
652
653     /* Read the first header line which contains the key type. */
654     if (!read_header(fp, header))
655         goto error;
656     if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
657         old_fmt = 0;
658     } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
659         /* this is an old key file; warn and then continue */
660         old_keyfile_warning();
661         old_fmt = 1;
662     } else {
663         error = "not a PuTTY SSH-2 private key";
664         goto error;
665     }
666     error = "file format error";
667     if ((b = read_body(fp)) == NULL)
668         goto error;
669     /* Select key algorithm structure. */
670     alg = find_pubkey_alg(b);
671     if (!alg) {
672         sfree(b);
673         goto error;
674     }
675     sfree(b);
676
677     /* Read the Encryption header line. */
678     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
679         goto error;
680     if ((encryption = read_body(fp)) == NULL)
681         goto error;
682     if (!strcmp(encryption, "aes256-cbc")) {
683         cipher = 1;
684         cipherblk = 16;
685     } else if (!strcmp(encryption, "none")) {
686         cipher = 0;
687         cipherblk = 1;
688     } else {
689         sfree(encryption);
690         goto error;
691     }
692
693     /* Read the Comment header line. */
694     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
695         goto error;
696     if ((comment = read_body(fp)) == NULL)
697         goto error;
698
699     /* Read the Public-Lines header line and the public blob. */
700     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
701         goto error;
702     if ((b = read_body(fp)) == NULL)
703         goto error;
704     i = atoi(b);
705     sfree(b);
706     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
707         goto error;
708
709     /* Read the Private-Lines header line and the Private blob. */
710     if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
711         goto error;
712     if ((b = read_body(fp)) == NULL)
713         goto error;
714     i = atoi(b);
715     sfree(b);
716     if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
717         goto error;
718
719     /* Read the Private-MAC or Private-Hash header line. */
720     if (!read_header(fp, header))
721         goto error;
722     if (0 == strcmp(header, "Private-MAC")) {
723         if ((mac = read_body(fp)) == NULL)
724             goto error;
725         is_mac = 1;
726     } else if (0 == strcmp(header, "Private-Hash") &&
727                            alg == &ssh_rsa && old_fmt) {
728         if ((mac = read_body(fp)) == NULL)
729             goto error;
730         is_mac = 0;
731     } else
732         goto error;
733
734     fclose(fp);
735     fp = NULL;
736
737     /*
738      * Decrypt the private blob.
739      */
740     if (cipher) {
741         unsigned char key[40];
742         SHA_State s;
743
744         if (!passphrase)
745             goto error;
746         if (private_blob_len % cipherblk)
747             goto error;
748
749         SHA_Init(&s);
750         SHA_Bytes(&s, "\0\0\0\0", 4);
751         SHA_Bytes(&s, passphrase, passlen);
752         SHA_Final(&s, key + 0);
753         SHA_Init(&s);
754         SHA_Bytes(&s, "\0\0\0\1", 4);
755         SHA_Bytes(&s, passphrase, passlen);
756         SHA_Final(&s, key + 20);
757         aes256_decrypt_pubkey(key, private_blob, private_blob_len);
758     }
759
760     /*
761      * Verify the MAC.
762      */
763     {
764         char realmac[41];
765         unsigned char binary[20];
766         unsigned char *macdata;
767         int maclen;
768         int free_macdata;
769
770         if (old_fmt) {
771             /* MAC (or hash) only covers the private blob. */
772             macdata = private_blob;
773             maclen = private_blob_len;
774             free_macdata = 0;
775         } else {
776             unsigned char *p;
777             int namelen = strlen(alg->name);
778             int enclen = strlen(encryption);
779             int commlen = strlen(comment);
780             maclen = (4 + namelen +
781                       4 + enclen +
782                       4 + commlen +
783                       4 + public_blob_len +
784                       4 + private_blob_len);
785             macdata = snewn(maclen, unsigned char);
786             p = macdata;
787 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
788             DO_STR(alg->name, namelen);
789             DO_STR(encryption, enclen);
790             DO_STR(comment, commlen);
791             DO_STR(public_blob, public_blob_len);
792             DO_STR(private_blob, private_blob_len);
793
794             free_macdata = 1;
795         }
796
797         if (is_mac) {
798             SHA_State s;
799             unsigned char mackey[20];
800             char header[] = "putty-private-key-file-mac-key";
801
802             SHA_Init(&s);
803             SHA_Bytes(&s, header, sizeof(header)-1);
804             if (cipher && passphrase)
805                 SHA_Bytes(&s, passphrase, passlen);
806             SHA_Final(&s, mackey);
807
808             hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
809
810             memset(mackey, 0, sizeof(mackey));
811             memset(&s, 0, sizeof(s));
812         } else {
813             SHA_Simple(macdata, maclen, binary);
814         }
815
816         if (free_macdata) {
817             memset(macdata, 0, maclen);
818             sfree(macdata);
819         }
820
821         for (i = 0; i < 20; i++)
822             sprintf(realmac + 2 * i, "%02x", binary[i]);
823
824         if (strcmp(mac, realmac)) {
825             /* An incorrect MAC is an unconditional Error if the key is
826              * unencrypted. Otherwise, it means Wrong Passphrase. */
827             if (cipher) {
828                 error = "wrong passphrase";
829                 ret = SSH2_WRONG_PASSPHRASE;
830             } else {
831                 error = "MAC failed";
832                 ret = NULL;
833             }
834             goto error;
835         }
836     }
837     sfree(mac);
838
839     /*
840      * Create and return the key.
841      */
842     ret = snew(struct ssh2_userkey);
843     ret->alg = alg;
844     ret->comment = comment;
845     ret->data = alg->createkey(public_blob, public_blob_len,
846                                private_blob, private_blob_len);
847     if (!ret->data) {
848         sfree(ret->comment);
849         sfree(ret);
850         ret = NULL;
851         error = "createkey failed";
852         goto error;
853     }
854     sfree(public_blob);
855     sfree(private_blob);
856     sfree(encryption);
857     if (errorstr)
858         *errorstr = NULL;
859     return ret;
860
861     /*
862      * Error processing.
863      */
864   error:
865     if (fp)
866         fclose(fp);
867     if (comment)
868         sfree(comment);
869     if (encryption)
870         sfree(encryption);
871     if (mac)
872         sfree(mac);
873     if (public_blob)
874         sfree(public_blob);
875     if (private_blob)
876         sfree(private_blob);
877     if (errorstr)
878         *errorstr = error;
879     return ret;
880 }
881
882 char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
883                            int *pub_blob_len, const char **errorstr)
884 {
885     FILE *fp;
886     char header[40], *b;
887     const struct ssh_signkey *alg;
888     unsigned char *public_blob;
889     int public_blob_len;
890     int i;
891     const char *error = NULL;
892
893     public_blob = NULL;
894
895     fp = f_open(*filename, "rb");
896     if (!fp) {
897         error = "can't open file";
898         goto error;
899     }
900
901     /* Read the first header line which contains the key type. */
902     if (!read_header(fp, header)
903         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
904             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
905         error = "not a PuTTY SSH-2 private key";
906         goto error;
907     }
908     error = "file format error";
909     if ((b = read_body(fp)) == NULL)
910         goto error;
911     /* Select key algorithm structure. Currently only ssh-rsa. */
912     alg = find_pubkey_alg(b);
913     if (!alg) {
914         sfree(b);
915         goto error;
916     }
917     sfree(b);
918
919     /* Read the Encryption header line. */
920     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
921         goto error;
922     if ((b = read_body(fp)) == NULL)
923         goto error;
924     sfree(b);                          /* we don't care */
925
926     /* Read the Comment header line. */
927     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
928         goto error;
929     if ((b = read_body(fp)) == NULL)
930         goto error;
931     sfree(b);                          /* we don't care */
932
933     /* Read the Public-Lines header line and the public blob. */
934     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
935         goto error;
936     if ((b = read_body(fp)) == NULL)
937         goto error;
938     i = atoi(b);
939     sfree(b);
940     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
941         goto error;
942
943     fclose(fp);
944     if (pub_blob_len)
945         *pub_blob_len = public_blob_len;
946     if (algorithm)
947         *algorithm = alg->name;
948     return (char *)public_blob;
949
950     /*
951      * Error processing.
952      */
953   error:
954     if (fp)
955         fclose(fp);
956     if (public_blob)
957         sfree(public_blob);
958     if (errorstr)
959         *errorstr = error;
960     return NULL;
961 }
962
963 int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
964 {
965     FILE *fp;
966     char header[40], *b, *comment;
967     int ret;
968
969     if (commentptr)
970         *commentptr = NULL;
971
972     fp = f_open(*filename, "rb");
973     if (!fp)
974         return 0;
975     if (!read_header(fp, header)
976         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
977             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
978         fclose(fp);
979         return 0;
980     }
981     if ((b = read_body(fp)) == NULL) {
982         fclose(fp);
983         return 0;
984     }
985     sfree(b);                          /* we don't care about key type here */
986     /* Read the Encryption header line. */
987     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
988         fclose(fp);
989         return 0;
990     }
991     if ((b = read_body(fp)) == NULL) {
992         fclose(fp);
993         return 0;
994     }
995
996     /* Read the Comment header line. */
997     if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
998         fclose(fp);
999         sfree(b);
1000         return 1;
1001     }
1002     if ((comment = read_body(fp)) == NULL) {
1003         fclose(fp);
1004         sfree(b);
1005         return 1;
1006     }
1007
1008     if (commentptr)
1009         *commentptr = comment;
1010
1011     fclose(fp);
1012     if (!strcmp(b, "aes256-cbc"))
1013         ret = 1;
1014     else
1015         ret = 0;
1016     sfree(b);
1017     return ret;
1018 }
1019
1020 int base64_lines(int datalen)
1021 {
1022     /* When encoding, we use 64 chars/line, which equals 48 real chars. */
1023     return (datalen + 47) / 48;
1024 }
1025
1026 void base64_encode(FILE * fp, unsigned char *data, int datalen, int cpl)
1027 {
1028     int linelen = 0;
1029     char out[4];
1030     int n, i;
1031
1032     while (datalen > 0) {
1033         n = (datalen < 3 ? datalen : 3);
1034         base64_encode_atom(data, n, out);
1035         data += n;
1036         datalen -= n;
1037         for (i = 0; i < 4; i++) {
1038             if (linelen >= cpl) {
1039                 linelen = 0;
1040                 fputc('\n', fp);
1041             }
1042             fputc(out[i], fp);
1043             linelen++;
1044         }
1045     }
1046     fputc('\n', fp);
1047 }
1048
1049 int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
1050                       char *passphrase)
1051 {
1052     FILE *fp;
1053     unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1054     int pub_blob_len, priv_blob_len, priv_encrypted_len;
1055     int passlen;
1056     int cipherblk;
1057     int i;
1058     char *cipherstr;
1059     unsigned char priv_mac[20];
1060
1061     /*
1062      * Fetch the key component blobs.
1063      */
1064     pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1065     priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1066     if (!pub_blob || !priv_blob) {
1067         sfree(pub_blob);
1068         sfree(priv_blob);
1069         return 0;
1070     }
1071
1072     /*
1073      * Determine encryption details, and encrypt the private blob.
1074      */
1075     if (passphrase) {
1076         cipherstr = "aes256-cbc";
1077         cipherblk = 16;
1078     } else {
1079         cipherstr = "none";
1080         cipherblk = 1;
1081     }
1082     priv_encrypted_len = priv_blob_len + cipherblk - 1;
1083     priv_encrypted_len -= priv_encrypted_len % cipherblk;
1084     priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
1085     memset(priv_blob_encrypted, 0, priv_encrypted_len);
1086     memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1087     /* Create padding based on the SHA hash of the unpadded blob. This prevents
1088      * too easy a known-plaintext attack on the last block. */
1089     SHA_Simple(priv_blob, priv_blob_len, priv_mac);
1090     assert(priv_encrypted_len - priv_blob_len < 20);
1091     memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
1092            priv_encrypted_len - priv_blob_len);
1093
1094     /* Now create the MAC. */
1095     {
1096         unsigned char *macdata;
1097         int maclen;
1098         unsigned char *p;
1099         int namelen = strlen(key->alg->name);
1100         int enclen = strlen(cipherstr);
1101         int commlen = strlen(key->comment);
1102         SHA_State s;
1103         unsigned char mackey[20];
1104         char header[] = "putty-private-key-file-mac-key";
1105
1106         maclen = (4 + namelen +
1107                   4 + enclen +
1108                   4 + commlen +
1109                   4 + pub_blob_len +
1110                   4 + priv_encrypted_len);
1111         macdata = snewn(maclen, unsigned char);
1112         p = macdata;
1113 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1114         DO_STR(key->alg->name, namelen);
1115         DO_STR(cipherstr, enclen);
1116         DO_STR(key->comment, commlen);
1117         DO_STR(pub_blob, pub_blob_len);
1118         DO_STR(priv_blob_encrypted, priv_encrypted_len);
1119
1120         SHA_Init(&s);
1121         SHA_Bytes(&s, header, sizeof(header)-1);
1122         if (passphrase)
1123             SHA_Bytes(&s, passphrase, strlen(passphrase));
1124         SHA_Final(&s, mackey);
1125         hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1126         memset(macdata, 0, maclen);
1127         sfree(macdata);
1128         memset(mackey, 0, sizeof(mackey));
1129         memset(&s, 0, sizeof(s));
1130     }
1131
1132     if (passphrase) {
1133         unsigned char key[40];
1134         SHA_State s;
1135
1136         passlen = strlen(passphrase);
1137
1138         SHA_Init(&s);
1139         SHA_Bytes(&s, "\0\0\0\0", 4);
1140         SHA_Bytes(&s, passphrase, passlen);
1141         SHA_Final(&s, key + 0);
1142         SHA_Init(&s);
1143         SHA_Bytes(&s, "\0\0\0\1", 4);
1144         SHA_Bytes(&s, passphrase, passlen);
1145         SHA_Final(&s, key + 20);
1146         aes256_encrypt_pubkey(key, priv_blob_encrypted,
1147                               priv_encrypted_len);
1148
1149         memset(key, 0, sizeof(key));
1150         memset(&s, 0, sizeof(s));
1151     }
1152
1153     fp = f_open(*filename, "w");
1154     if (!fp)
1155         return 0;
1156     fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
1157     fprintf(fp, "Encryption: %s\n", cipherstr);
1158     fprintf(fp, "Comment: %s\n", key->comment);
1159     fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1160     base64_encode(fp, pub_blob, pub_blob_len, 64);
1161     fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1162     base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
1163     fprintf(fp, "Private-MAC: ");
1164     for (i = 0; i < 20; i++)
1165         fprintf(fp, "%02x", priv_mac[i]);
1166     fprintf(fp, "\n");
1167     fclose(fp);
1168
1169     sfree(pub_blob);
1170     memset(priv_blob, 0, priv_blob_len);
1171     sfree(priv_blob);
1172     sfree(priv_blob_encrypted);
1173     return 1;
1174 }
1175
1176 /* ----------------------------------------------------------------------
1177  * A function to determine the type of a private key file. Returns
1178  * 0 on failure, 1 or 2 on success.
1179  */
1180 int key_type(const Filename *filename)
1181 {
1182     FILE *fp;
1183     char buf[32];
1184     const char putty2_sig[] = "PuTTY-User-Key-File-";
1185     const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1186     const char openssh_sig[] = "-----BEGIN ";
1187     int i;
1188
1189     fp = f_open(*filename, "r");
1190     if (!fp)
1191         return SSH_KEYTYPE_UNOPENABLE;
1192     i = fread(buf, 1, sizeof(buf), fp);
1193     fclose(fp);
1194     if (i < 0)
1195         return SSH_KEYTYPE_UNOPENABLE;
1196     if (i < 32)
1197         return SSH_KEYTYPE_UNKNOWN;
1198     if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1199         return SSH_KEYTYPE_SSH1;
1200     if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1201         return SSH_KEYTYPE_SSH2;
1202     if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1203         return SSH_KEYTYPE_OPENSSH;
1204     if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1205         return SSH_KEYTYPE_SSHCOM;
1206     return SSH_KEYTYPE_UNKNOWN;        /* unrecognised or EOF */
1207 }
1208
1209 /*
1210  * Convert the type word to a string, for `wrong type' error
1211  * messages.
1212  */
1213 char *key_type_to_str(int type)
1214 {
1215     switch (type) {
1216       case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1217       case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;
1218       case SSH_KEYTYPE_SSH1: return "SSH1 private key"; break;
1219       case SSH_KEYTYPE_SSH2: return "PuTTY SSH2 private key"; break;
1220       case SSH_KEYTYPE_OPENSSH: return "OpenSSH SSH2 private key"; break;
1221       case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH2 private key"; break;
1222       default: return "INTERNAL ERROR"; break;
1223     }
1224 }