OSDN Git Service

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