Fixed issue #2495: "Show Reflog" dialog shows empty action for "push" entries
[TortoiseGit.git] / src / TortoisePlink / SSHPUBK.C
blobd91c1eee32ea575fde3952716a79cb079c98e4f1
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 - i, 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 static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)\r
518     unsigned char *blob;\r
519     char *line;\r
520     int linelen, len;\r
521     int i, j, k;\r
523     /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */\r
524     blob = snewn(48 * nlines, unsigned char);\r
525     len = 0;\r
526     for (i = 0; i < nlines; i++) {\r
527         line = read_body(fp);\r
528         if (!line) {\r
529             sfree(blob);\r
530             return NULL;\r
531         }\r
532         linelen = strlen(line);\r
533         if (linelen % 4 != 0 || linelen > 64) {\r
534             sfree(blob);\r
535             sfree(line);\r
536             return NULL;\r
537         }\r
538         for (j = 0; j < linelen; j += 4) {\r
539             k = base64_decode_atom(line + j, blob + len);\r
540             if (!k) {\r
541                 sfree(line);\r
542                 sfree(blob);\r
543                 return NULL;\r
544             }\r
545             len += k;\r
546         }\r
547         sfree(line);\r
548     }\r
549     *bloblen = len;\r
550     return blob;\r
553 /*\r
554  * Magic error return value for when the passphrase is wrong.\r
555  */\r
556 struct ssh2_userkey ssh2_wrong_passphrase = {\r
557     NULL, NULL, NULL\r
558 };\r
560 const struct ssh_signkey *find_pubkey_alg(const char *name)\r
562     if (!strcmp(name, "ssh-rsa"))\r
563         return &ssh_rsa;\r
564     else if (!strcmp(name, "ssh-dss"))\r
565         return &ssh_dss;\r
566     else\r
567         return NULL;\r
570 struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,\r
571                                        char *passphrase, const char **errorstr)\r
573     FILE *fp;\r
574     char header[40], *b, *encryption, *comment, *mac;\r
575     const struct ssh_signkey *alg;\r
576     struct ssh2_userkey *ret;\r
577     int cipher, cipherblk;\r
578     unsigned char *public_blob, *private_blob;\r
579     int public_blob_len, private_blob_len;\r
580     int i, is_mac, old_fmt;\r
581     int passlen = passphrase ? strlen(passphrase) : 0;\r
582     const char *error = NULL;\r
584     ret = NULL;                        /* return NULL for most errors */\r
585     encryption = comment = mac = NULL;\r
586     public_blob = private_blob = NULL;\r
588     fp = f_open(filename, "rb", FALSE);\r
589     if (!fp) {\r
590         error = "can't open file";\r
591         goto error;\r
592     }\r
594     /* Read the first header line which contains the key type. */\r
595     if (!read_header(fp, header))\r
596         goto error;\r
597     if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {\r
598         old_fmt = 0;\r
599     } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {\r
600         /* this is an old key file; warn and then continue */\r
601         old_keyfile_warning();\r
602         old_fmt = 1;\r
603     } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {\r
604         /* this is a key file FROM THE FUTURE; refuse it, but with a\r
605          * more specific error message than the generic one below */\r
606         error = "PuTTY key format too new";\r
607         goto error;\r
608     } else {\r
609         error = "not a PuTTY SSH-2 private key";\r
610         goto error;\r
611     }\r
612     error = "file format error";\r
613     if ((b = read_body(fp)) == NULL)\r
614         goto error;\r
615     /* Select key algorithm structure. */\r
616     alg = find_pubkey_alg(b);\r
617     if (!alg) {\r
618         sfree(b);\r
619         goto error;\r
620     }\r
621     sfree(b);\r
623     /* Read the Encryption header line. */\r
624     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))\r
625         goto error;\r
626     if ((encryption = read_body(fp)) == NULL)\r
627         goto error;\r
628     if (!strcmp(encryption, "aes256-cbc")) {\r
629         cipher = 1;\r
630         cipherblk = 16;\r
631     } else if (!strcmp(encryption, "none")) {\r
632         cipher = 0;\r
633         cipherblk = 1;\r
634     } else {\r
635         goto error;\r
636     }\r
638     /* Read the Comment header line. */\r
639     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))\r
640         goto error;\r
641     if ((comment = read_body(fp)) == NULL)\r
642         goto error;\r
644     /* Read the Public-Lines header line and the public blob. */\r
645     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))\r
646         goto error;\r
647     if ((b = read_body(fp)) == NULL)\r
648         goto error;\r
649     i = atoi(b);\r
650     sfree(b);\r
651     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)\r
652         goto error;\r
654     /* Read the Private-Lines header line and the Private blob. */\r
655     if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))\r
656         goto error;\r
657     if ((b = read_body(fp)) == NULL)\r
658         goto error;\r
659     i = atoi(b);\r
660     sfree(b);\r
661     if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)\r
662         goto error;\r
664     /* Read the Private-MAC or Private-Hash header line. */\r
665     if (!read_header(fp, header))\r
666         goto error;\r
667     if (0 == strcmp(header, "Private-MAC")) {\r
668         if ((mac = read_body(fp)) == NULL)\r
669             goto error;\r
670         is_mac = 1;\r
671     } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {\r
672         if ((mac = read_body(fp)) == NULL)\r
673             goto error;\r
674         is_mac = 0;\r
675     } else\r
676         goto error;\r
678     fclose(fp);\r
679     fp = NULL;\r
681     /*\r
682      * Decrypt the private blob.\r
683      */\r
684     if (cipher) {\r
685         unsigned char key[40];\r
686         SHA_State s;\r
688         if (!passphrase)\r
689             goto error;\r
690         if (private_blob_len % cipherblk)\r
691             goto error;\r
693         SHA_Init(&s);\r
694         SHA_Bytes(&s, "\0\0\0\0", 4);\r
695         SHA_Bytes(&s, passphrase, passlen);\r
696         SHA_Final(&s, key + 0);\r
697         SHA_Init(&s);\r
698         SHA_Bytes(&s, "\0\0\0\1", 4);\r
699         SHA_Bytes(&s, passphrase, passlen);\r
700         SHA_Final(&s, key + 20);\r
701         aes256_decrypt_pubkey(key, private_blob, private_blob_len);\r
702     }\r
704     /*\r
705      * Verify the MAC.\r
706      */\r
707     {\r
708         char realmac[41];\r
709         unsigned char binary[20];\r
710         unsigned char *macdata;\r
711         int maclen;\r
712         int free_macdata;\r
714         if (old_fmt) {\r
715             /* MAC (or hash) only covers the private blob. */\r
716             macdata = private_blob;\r
717             maclen = private_blob_len;\r
718             free_macdata = 0;\r
719         } else {\r
720             unsigned char *p;\r
721             int namelen = strlen(alg->name);\r
722             int enclen = strlen(encryption);\r
723             int commlen = strlen(comment);\r
724             maclen = (4 + namelen +\r
725                       4 + enclen +\r
726                       4 + commlen +\r
727                       4 + public_blob_len +\r
728                       4 + private_blob_len);\r
729             macdata = snewn(maclen, unsigned char);\r
730             p = macdata;\r
731 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)\r
732             DO_STR(alg->name, namelen);\r
733             DO_STR(encryption, enclen);\r
734             DO_STR(comment, commlen);\r
735             DO_STR(public_blob, public_blob_len);\r
736             DO_STR(private_blob, private_blob_len);\r
738             free_macdata = 1;\r
739         }\r
741         if (is_mac) {\r
742             SHA_State s;\r
743             unsigned char mackey[20];\r
744             char header[] = "putty-private-key-file-mac-key";\r
746             SHA_Init(&s);\r
747             SHA_Bytes(&s, header, sizeof(header)-1);\r
748             if (cipher && passphrase)\r
749                 SHA_Bytes(&s, passphrase, passlen);\r
750             SHA_Final(&s, mackey);\r
752             hmac_sha1_simple(mackey, 20, macdata, maclen, binary);\r
754             smemclr(mackey, sizeof(mackey));\r
755             smemclr(&s, sizeof(s));\r
756         } else {\r
757             SHA_Simple(macdata, maclen, binary);\r
758         }\r
760         if (free_macdata) {\r
761             smemclr(macdata, maclen);\r
762             sfree(macdata);\r
763         }\r
765         for (i = 0; i < 20; i++)\r
766             sprintf(realmac + 2 * i, "%02x", binary[i]);\r
768         if (strcmp(mac, realmac)) {\r
769             /* An incorrect MAC is an unconditional Error if the key is\r
770              * unencrypted. Otherwise, it means Wrong Passphrase. */\r
771             if (cipher) {\r
772                 error = "wrong passphrase";\r
773                 ret = SSH2_WRONG_PASSPHRASE;\r
774             } else {\r
775                 error = "MAC failed";\r
776                 ret = NULL;\r
777             }\r
778             goto error;\r
779         }\r
780     }\r
781     sfree(mac);\r
782     mac = NULL;\r
784     /*\r
785      * Create and return the key.\r
786      */\r
787     ret = snew(struct ssh2_userkey);\r
788     ret->alg = alg;\r
789     ret->comment = comment;\r
790     ret->data = alg->createkey(public_blob, public_blob_len,\r
791                                private_blob, private_blob_len);\r
792     if (!ret->data) {\r
793         sfree(ret);\r
794         ret = NULL;\r
795         error = "createkey failed";\r
796         goto error;\r
797     }\r
798     sfree(public_blob);\r
799     smemclr(private_blob, private_blob_len);\r
800     sfree(private_blob);\r
801     sfree(encryption);\r
802     if (errorstr)\r
803         *errorstr = NULL;\r
804     return ret;\r
806     /*\r
807      * Error processing.\r
808      */\r
809   error:\r
810     if (fp)\r
811         fclose(fp);\r
812     if (comment)\r
813         sfree(comment);\r
814     if (encryption)\r
815         sfree(encryption);\r
816     if (mac)\r
817         sfree(mac);\r
818     if (public_blob)\r
819         sfree(public_blob);\r
820     if (private_blob) {\r
821         smemclr(private_blob, private_blob_len);\r
822         sfree(private_blob);\r
823     }\r
824     if (errorstr)\r
825         *errorstr = error;\r
826     return ret;\r
829 unsigned char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,\r
830                                     int *pub_blob_len, char **commentptr,\r
831                                     const char **errorstr)\r
833     FILE *fp;\r
834     char header[40], *b;\r
835     const struct ssh_signkey *alg;\r
836     unsigned char *public_blob;\r
837     int public_blob_len;\r
838     int i;\r
839     const char *error = NULL;\r
840     char *comment;\r
842     public_blob = NULL;\r
844     fp = f_open(filename, "rb", FALSE);\r
845     if (!fp) {\r
846         error = "can't open file";\r
847         goto error;\r
848     }\r
850     /* Read the first header line which contains the key type. */\r
851     if (!read_header(fp, header)\r
852         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&\r
853             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {\r
854         if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))\r
855             error = "PuTTY key format too new";\r
856         else\r
857             error = "not a PuTTY SSH-2 private key";\r
858         goto error;\r
859     }\r
860     error = "file format error";\r
861     if ((b = read_body(fp)) == NULL)\r
862         goto error;\r
863     /* Select key algorithm structure. */\r
864     alg = find_pubkey_alg(b);\r
865     if (!alg) {\r
866         sfree(b);\r
867         goto error;\r
868     }\r
869     sfree(b);\r
871     /* Read the Encryption header line. */\r
872     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))\r
873         goto error;\r
874     if ((b = read_body(fp)) == NULL)\r
875         goto error;\r
876     sfree(b);                          /* we don't care */\r
878     /* Read the Comment header line. */\r
879     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))\r
880         goto error;\r
881     if ((comment = read_body(fp)) == NULL)\r
882         goto error;\r
884     if (commentptr)\r
885         *commentptr = comment;\r
886     else\r
887         sfree(comment);\r
889     /* Read the Public-Lines header line and the public blob. */\r
890     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))\r
891         goto error;\r
892     if ((b = read_body(fp)) == NULL)\r
893         goto error;\r
894     i = atoi(b);\r
895     sfree(b);\r
896     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)\r
897         goto error;\r
899     fclose(fp);\r
900     if (pub_blob_len)\r
901         *pub_blob_len = public_blob_len;\r
902     if (algorithm)\r
903         *algorithm = alg->name;\r
904     return public_blob;\r
906     /*\r
907      * Error processing.\r
908      */\r
909   error:\r
910     if (fp)\r
911         fclose(fp);\r
912     if (public_blob)\r
913         sfree(public_blob);\r
914     if (errorstr)\r
915         *errorstr = error;\r
916     return NULL;\r
919 int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)\r
921     FILE *fp;\r
922     char header[40], *b, *comment;\r
923     int ret;\r
925     if (commentptr)\r
926         *commentptr = NULL;\r
928     fp = f_open(filename, "rb", FALSE);\r
929     if (!fp)\r
930         return 0;\r
931     if (!read_header(fp, header)\r
932         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&\r
933             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {\r
934         fclose(fp);\r
935         return 0;\r
936     }\r
937     if ((b = read_body(fp)) == NULL) {\r
938         fclose(fp);\r
939         return 0;\r
940     }\r
941     sfree(b);                          /* we don't care about key type here */\r
942     /* Read the Encryption header line. */\r
943     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {\r
944         fclose(fp);\r
945         return 0;\r
946     }\r
947     if ((b = read_body(fp)) == NULL) {\r
948         fclose(fp);\r
949         return 0;\r
950     }\r
952     /* Read the Comment header line. */\r
953     if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {\r
954         fclose(fp);\r
955         sfree(b);\r
956         return 1;\r
957     }\r
958     if ((comment = read_body(fp)) == NULL) {\r
959         fclose(fp);\r
960         sfree(b);\r
961         return 1;\r
962     }\r
964     if (commentptr)\r
965         *commentptr = comment;\r
966     else\r
967         sfree(comment);\r
969     fclose(fp);\r
970     if (!strcmp(b, "aes256-cbc"))\r
971         ret = 1;\r
972     else\r
973         ret = 0;\r
974     sfree(b);\r
975     return ret;\r
978 int base64_lines(int datalen)\r
980     /* When encoding, we use 64 chars/line, which equals 48 real chars. */\r
981     return (datalen + 47) / 48;\r
984 void base64_encode(FILE * fp, unsigned char *data, int datalen, int cpl)\r
986     int linelen = 0;\r
987     char out[4];\r
988     int n, i;\r
990     while (datalen > 0) {\r
991         n = (datalen < 3 ? datalen : 3);\r
992         base64_encode_atom(data, n, out);\r
993         data += n;\r
994         datalen -= n;\r
995         for (i = 0; i < 4; i++) {\r
996             if (linelen >= cpl) {\r
997                 linelen = 0;\r
998                 fputc('\n', fp);\r
999             }\r
1000             fputc(out[i], fp);\r
1001             linelen++;\r
1002         }\r
1003     }\r
1004     fputc('\n', fp);\r
1007 int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,\r
1008                       char *passphrase)\r
1010     FILE *fp;\r
1011     unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;\r
1012     int pub_blob_len, priv_blob_len, priv_encrypted_len;\r
1013     int passlen;\r
1014     int cipherblk;\r
1015     int i;\r
1016     char *cipherstr;\r
1017     unsigned char priv_mac[20];\r
1019     /*\r
1020      * Fetch the key component blobs.\r
1021      */\r
1022     pub_blob = key->alg->public_blob(key->data, &pub_blob_len);\r
1023     priv_blob = key->alg->private_blob(key->data, &priv_blob_len);\r
1024     if (!pub_blob || !priv_blob) {\r
1025         sfree(pub_blob);\r
1026         sfree(priv_blob);\r
1027         return 0;\r
1028     }\r
1030     /*\r
1031      * Determine encryption details, and encrypt the private blob.\r
1032      */\r
1033     if (passphrase) {\r
1034         cipherstr = "aes256-cbc";\r
1035         cipherblk = 16;\r
1036     } else {\r
1037         cipherstr = "none";\r
1038         cipherblk = 1;\r
1039     }\r
1040     priv_encrypted_len = priv_blob_len + cipherblk - 1;\r
1041     priv_encrypted_len -= priv_encrypted_len % cipherblk;\r
1042     priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);\r
1043     memset(priv_blob_encrypted, 0, priv_encrypted_len);\r
1044     memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);\r
1045     /* Create padding based on the SHA hash of the unpadded blob. This prevents\r
1046      * too easy a known-plaintext attack on the last block. */\r
1047     SHA_Simple(priv_blob, priv_blob_len, priv_mac);\r
1048     assert(priv_encrypted_len - priv_blob_len < 20);\r
1049     memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,\r
1050            priv_encrypted_len - priv_blob_len);\r
1052     /* Now create the MAC. */\r
1053     {\r
1054         unsigned char *macdata;\r
1055         int maclen;\r
1056         unsigned char *p;\r
1057         int namelen = strlen(key->alg->name);\r
1058         int enclen = strlen(cipherstr);\r
1059         int commlen = strlen(key->comment);\r
1060         SHA_State s;\r
1061         unsigned char mackey[20];\r
1062         char header[] = "putty-private-key-file-mac-key";\r
1064         maclen = (4 + namelen +\r
1065                   4 + enclen +\r
1066                   4 + commlen +\r
1067                   4 + pub_blob_len +\r
1068                   4 + priv_encrypted_len);\r
1069         macdata = snewn(maclen, unsigned char);\r
1070         p = macdata;\r
1071 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)\r
1072         DO_STR(key->alg->name, namelen);\r
1073         DO_STR(cipherstr, enclen);\r
1074         DO_STR(key->comment, commlen);\r
1075         DO_STR(pub_blob, pub_blob_len);\r
1076         DO_STR(priv_blob_encrypted, priv_encrypted_len);\r
1078         SHA_Init(&s);\r
1079         SHA_Bytes(&s, header, sizeof(header)-1);\r
1080         if (passphrase)\r
1081             SHA_Bytes(&s, passphrase, strlen(passphrase));\r
1082         SHA_Final(&s, mackey);\r
1083         hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);\r
1084         smemclr(macdata, maclen);\r
1085         sfree(macdata);\r
1086         smemclr(mackey, sizeof(mackey));\r
1087         smemclr(&s, sizeof(s));\r
1088     }\r
1090     if (passphrase) {\r
1091         unsigned char key[40];\r
1092         SHA_State s;\r
1094         passlen = strlen(passphrase);\r
1096         SHA_Init(&s);\r
1097         SHA_Bytes(&s, "\0\0\0\0", 4);\r
1098         SHA_Bytes(&s, passphrase, passlen);\r
1099         SHA_Final(&s, key + 0);\r
1100         SHA_Init(&s);\r
1101         SHA_Bytes(&s, "\0\0\0\1", 4);\r
1102         SHA_Bytes(&s, passphrase, passlen);\r
1103         SHA_Final(&s, key + 20);\r
1104         aes256_encrypt_pubkey(key, priv_blob_encrypted,\r
1105                               priv_encrypted_len);\r
1107         smemclr(key, sizeof(key));\r
1108         smemclr(&s, sizeof(s));\r
1109     }\r
1111     fp = f_open(filename, "w", TRUE);\r
1112     if (!fp) {\r
1113         sfree(pub_blob);\r
1114         smemclr(priv_blob, priv_blob_len);\r
1115         sfree(priv_blob);\r
1116         smemclr(priv_blob_encrypted, priv_blob_len);\r
1117         sfree(priv_blob_encrypted);\r
1118         return 0;\r
1119     }\r
1120     fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);\r
1121     fprintf(fp, "Encryption: %s\n", cipherstr);\r
1122     fprintf(fp, "Comment: %s\n", key->comment);\r
1123     fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));\r
1124     base64_encode(fp, pub_blob, pub_blob_len, 64);\r
1125     fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));\r
1126     base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);\r
1127     fprintf(fp, "Private-MAC: ");\r
1128     for (i = 0; i < 20; i++)\r
1129         fprintf(fp, "%02x", priv_mac[i]);\r
1130     fprintf(fp, "\n");\r
1131     fclose(fp);\r
1133     sfree(pub_blob);\r
1134     smemclr(priv_blob, priv_blob_len);\r
1135     sfree(priv_blob);\r
1136     smemclr(priv_blob_encrypted, priv_blob_len);\r
1137     sfree(priv_blob_encrypted);\r
1138     return 1;\r
1141 /* ----------------------------------------------------------------------\r
1142  * A function to determine the type of a private key file. Returns\r
1143  * 0 on failure, 1 or 2 on success.\r
1144  */\r
1145 int key_type(const Filename *filename)\r
1147     FILE *fp;\r
1148     char buf[32];\r
1149     const char putty2_sig[] = "PuTTY-User-Key-File-";\r
1150     const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";\r
1151     const char openssh_sig[] = "-----BEGIN ";\r
1152     int i;\r
1154     fp = f_open(filename, "r", FALSE);\r
1155     if (!fp)\r
1156         return SSH_KEYTYPE_UNOPENABLE;\r
1157     i = fread(buf, 1, sizeof(buf), fp);\r
1158     fclose(fp);\r
1159     if (i < 0)\r
1160         return SSH_KEYTYPE_UNOPENABLE;\r
1161     if (i < 32)\r
1162         return SSH_KEYTYPE_UNKNOWN;\r
1163     if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))\r
1164         return SSH_KEYTYPE_SSH1;\r
1165     if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))\r
1166         return SSH_KEYTYPE_SSH2;\r
1167     if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))\r
1168         return SSH_KEYTYPE_OPENSSH;\r
1169     if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))\r
1170         return SSH_KEYTYPE_SSHCOM;\r
1171     return SSH_KEYTYPE_UNKNOWN;        /* unrecognised or EOF */\r
1174 /*\r
1175  * Convert the type word to a string, for `wrong type' error\r
1176  * messages.\r
1177  */\r
1178 char *key_type_to_str(int type)\r
1180     switch (type) {\r
1181       case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;\r
1182       case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;\r
1183       case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;\r
1184       case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;\r
1185       case SSH_KEYTYPE_OPENSSH: return "OpenSSH SSH-2 private key"; break;\r
1186       case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;\r
1187       default: return "INTERNAL ERROR"; break;\r
1188     }\r