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