CPatch: New memory management
[TortoiseGit.git] / src / TortoisePlink / SSHPUBK.C
blobe61fabeaecc522affd5025a842139d164eaf4c89
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 key_type_fp(FILE *fp);\r
26 static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only,\r
27                            char **commentptr, const char *passphrase,\r
28                            const char **error)\r
29 {\r
30     unsigned char buf[16384];\r
31     unsigned char keybuf[16];\r
32     int len;\r
33     int i, j, ciphertype;\r
34     int ret = 0;\r
35     struct MD5Context md5c;\r
36     char *comment;\r
38     *error = NULL;\r
40     /* Slurp the whole file (minus the header) into a buffer. */\r
41     len = fread(buf, 1, sizeof(buf), fp);\r
42     fclose(fp);\r
43     if (len < 0 || len == sizeof(buf)) {\r
44         *error = "error reading file";\r
45         goto end;                      /* file too big or not read */\r
46     }\r
48     i = 0;\r
49     *error = "file format error";\r
51     /*\r
52      * A zero byte. (The signature includes a terminating NUL.)\r
53      */\r
54     if (len - i < 1 || buf[i] != 0)\r
55         goto end;\r
56     i++;\r
58     /* One byte giving encryption type, and one reserved uint32. */\r
59     if (len - i < 1)\r
60         goto end;\r
61     ciphertype = buf[i];\r
62     if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)\r
63         goto end;\r
64     i++;\r
65     if (len - i < 4)\r
66         goto end;                      /* reserved field not present */\r
67     if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0\r
68         || buf[i + 3] != 0) goto end;  /* reserved field nonzero, panic! */\r
69     i += 4;\r
71     /* Now the serious stuff. An ordinary SSH-1 public key. */\r
72     j = makekey(buf + i, len - i, key, NULL, 1);\r
73     if (j < 0)\r
74         goto end;                      /* overran */\r
75     i += j;\r
77     /* Next, the comment field. */\r
78     j = toint(GET_32BIT(buf + i));\r
79     i += 4;\r
80     if (j < 0 || len - i < j)\r
81         goto end;\r
82     comment = snewn(j + 1, char);\r
83     if (comment) {\r
84         memcpy(comment, buf + i, j);\r
85         comment[j] = '\0';\r
86     }\r
87     i += j;\r
88     if (commentptr)\r
89         *commentptr = dupstr(comment);\r
90     if (key)\r
91         key->comment = comment;\r
92     else\r
93         sfree(comment);\r
95     if (pub_only) {\r
96         ret = 1;\r
97         goto end;\r
98     }\r
100     if (!key) {\r
101         ret = ciphertype != 0;\r
102         *error = NULL;\r
103         goto end;\r
104     }\r
106     /*\r
107      * Decrypt remainder of buffer.\r
108      */\r
109     if (ciphertype) {\r
110         MD5Init(&md5c);\r
111         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));\r
112         MD5Final(keybuf, &md5c);\r
113         des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);\r
114         smemclr(keybuf, sizeof(keybuf));        /* burn the evidence */\r
115     }\r
117     /*\r
118      * We are now in the secret part of the key. The first four\r
119      * bytes should be of the form a, b, a, b.\r
120      */\r
121     if (len - i < 4)\r
122         goto end;\r
123     if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {\r
124         *error = "wrong passphrase";\r
125         ret = -1;\r
126         goto end;\r
127     }\r
128     i += 4;\r
130     /*\r
131      * After that, we have one further bignum which is our\r
132      * decryption exponent, and then the three auxiliary values\r
133      * (iqmp, q, p).\r
134      */\r
135     j = makeprivate(buf + i, len - i, key);\r
136     if (j < 0) goto end;\r
137     i += j;\r
138     j = ssh1_read_bignum(buf + i, len - i, &key->iqmp);\r
139     if (j < 0) goto end;\r
140     i += j;\r
141     j = ssh1_read_bignum(buf + i, len - i, &key->q);\r
142     if (j < 0) goto end;\r
143     i += j;\r
144     j = ssh1_read_bignum(buf + i, len - i, &key->p);\r
145     if (j < 0) goto end;\r
146     i += j;\r
148     if (!rsa_verify(key)) {\r
149         *error = "rsa_verify failed";\r
150         freersakey(key);\r
151         ret = 0;\r
152     } else\r
153         ret = 1;\r
155   end:\r
156     smemclr(buf, sizeof(buf));       /* burn the evidence */\r
157     return ret;\r
160 int loadrsakey(const Filename *filename, struct RSAKey *key,\r
161                const char *passphrase, const char **errorstr)\r
163     FILE *fp;\r
164     char buf[64];\r
165     int ret = 0;\r
166     const char *error = NULL;\r
168     fp = f_open(filename, "rb", FALSE);\r
169     if (!fp) {\r
170         error = "can't open file";\r
171         goto end;\r
172     }\r
174     /*\r
175      * Read the first line of the file and see if it's a v1 private\r
176      * key file.\r
177      */\r
178     if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {\r
179         /*\r
180          * This routine will take care of calling fclose() for us.\r
181          */\r
182         ret = loadrsakey_main(fp, key, FALSE, NULL, passphrase, &error);\r
183         fp = NULL;\r
184         goto end;\r
185     }\r
187     /*\r
188      * Otherwise, we have nothing. Return empty-handed.\r
189      */\r
190     error = "not an SSH-1 RSA file";\r
192   end:\r
193     if (fp)\r
194         fclose(fp);\r
195     if ((ret != 1) && errorstr)\r
196         *errorstr = error;\r
197     return ret;\r
200 /*\r
201  * See whether an RSA key is encrypted. Return its comment field as\r
202  * well.\r
203  */\r
204 int rsakey_encrypted(const Filename *filename, char **comment)\r
206     FILE *fp;\r
207     char buf[64];\r
209     fp = f_open(filename, "rb", FALSE);\r
210     if (!fp)\r
211         return 0;                      /* doesn't even exist */\r
213     /*\r
214      * Read the first line of the file and see if it's a v1 private\r
215      * key file.\r
216      */\r
217     if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {\r
218         const char *dummy;\r
219         /*\r
220          * This routine will take care of calling fclose() for us.\r
221          */\r
222         return loadrsakey_main(fp, NULL, FALSE, comment, NULL, &dummy);\r
223     }\r
224     fclose(fp);\r
225     return 0;                          /* wasn't the right kind of file */\r
228 /*\r
229  * Return a malloc'ed chunk of memory containing the public blob of\r
230  * an RSA key, as given in the agent protocol (modulus bits,\r
231  * exponent, modulus).\r
232  */\r
233 int rsakey_pubblob(const Filename *filename, void **blob, int *bloblen,\r
234                    char **commentptr, const char **errorstr)\r
236     FILE *fp;\r
237     char buf[64];\r
238     struct RSAKey key;\r
239     int ret;\r
240     const char *error = NULL;\r
242     /* Default return if we fail. */\r
243     *blob = NULL;\r
244     *bloblen = 0;\r
245     ret = 0;\r
247     fp = f_open(filename, "rb", FALSE);\r
248     if (!fp) {\r
249         error = "can't open file";\r
250         goto end;\r
251     }\r
253     /*\r
254      * Read the first line of the file and see if it's a v1 private\r
255      * key file.\r
256      */\r
257     if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {\r
258         memset(&key, 0, sizeof(key));\r
259         if (loadrsakey_main(fp, &key, TRUE, commentptr, NULL, &error)) {\r
260             *blob = rsa_public_blob(&key, bloblen);\r
261             freersakey(&key);\r
262             ret = 1;\r
263         }\r
264         fp = NULL; /* loadrsakey_main unconditionally closes fp */\r
265     } else {\r
266         /*\r
267          * Try interpreting the file as an SSH-1 public key.\r
268          */\r
269         char *line, *p, *bitsp, *expp, *modp, *commentp;\r
271         rewind(fp);\r
272         line = chomp(fgetline(fp));\r
273         p = line;\r
275         bitsp = p;\r
276         p += strspn(p, "0123456789");\r
277         if (*p != ' ')\r
278             goto not_public_either;\r
279         *p++ = '\0';\r
281         expp = p;\r
282         p += strspn(p, "0123456789");\r
283         if (*p != ' ')\r
284             goto not_public_either;\r
285         *p++ = '\0';\r
287         modp = p;\r
288         p += strspn(p, "0123456789");\r
289         if (*p) {\r
290             if (*p != ' ')\r
291                 goto not_public_either;\r
292             *p++ = '\0';\r
293             commentp = p;\r
294         } else {\r
295             commentp = NULL;\r
296         }\r
298         memset(&key, 0, sizeof(key));\r
299         key.exponent = bignum_from_decimal(expp);\r
300         key.modulus = bignum_from_decimal(modp);\r
301         if (atoi(bitsp) != bignum_bitcount(key.modulus)) {\r
302             freebn(key.exponent);\r
303             freebn(key.modulus);\r
304             sfree(line);\r
305             error = "key bit count does not match in SSH-1 public key file";\r
306             goto end;\r
307         }\r
308         if (commentptr)\r
309             *commentptr = commentp ? dupstr(commentp) : NULL;\r
310         *blob = rsa_public_blob(&key, bloblen);\r
311         freersakey(&key);\r
312         sfree(line);\r
313         fclose(fp);\r
314         return 1;\r
316       not_public_either:\r
317         sfree(line);\r
318         error = "not an SSH-1 RSA file";\r
319     }\r
321   end:\r
322     if (fp)\r
323         fclose(fp);\r
324     if ((ret != 1) && errorstr)\r
325         *errorstr = error;\r
326     return ret;\r
329 /*\r
330  * Save an RSA key file. Return nonzero on success.\r
331  */\r
332 int saversakey(const Filename *filename, struct RSAKey *key, char *passphrase)\r
334     unsigned char buf[16384];\r
335     unsigned char keybuf[16];\r
336     struct MD5Context md5c;\r
337     unsigned char *p, *estart;\r
338     FILE *fp;\r
340     /*\r
341      * Write the initial signature.\r
342      */\r
343     p = buf;\r
344     memcpy(p, rsa_signature, sizeof(rsa_signature));\r
345     p += sizeof(rsa_signature);\r
347     /*\r
348      * One byte giving encryption type, and one reserved (zero)\r
349      * uint32.\r
350      */\r
351     *p++ = (passphrase ? SSH_CIPHER_3DES : 0);\r
352     PUT_32BIT(p, 0);\r
353     p += 4;\r
355     /*\r
356      * An ordinary SSH-1 public key consists of: a uint32\r
357      * containing the bit count, then two bignums containing the\r
358      * modulus and exponent respectively.\r
359      */\r
360     PUT_32BIT(p, bignum_bitcount(key->modulus));\r
361     p += 4;\r
362     p += ssh1_write_bignum(p, key->modulus);\r
363     p += ssh1_write_bignum(p, key->exponent);\r
365     /*\r
366      * A string containing the comment field.\r
367      */\r
368     if (key->comment) {\r
369         PUT_32BIT(p, strlen(key->comment));\r
370         p += 4;\r
371         memcpy(p, key->comment, strlen(key->comment));\r
372         p += strlen(key->comment);\r
373     } else {\r
374         PUT_32BIT(p, 0);\r
375         p += 4;\r
376     }\r
378     /*\r
379      * The encrypted portion starts here.\r
380      */\r
381     estart = p;\r
383     /*\r
384      * Two bytes, then the same two bytes repeated.\r
385      */\r
386     *p++ = random_byte();\r
387     *p++ = random_byte();\r
388     p[0] = p[-2];\r
389     p[1] = p[-1];\r
390     p += 2;\r
392     /*\r
393      * Four more bignums: the decryption exponent, then iqmp, then\r
394      * q, then p.\r
395      */\r
396     p += ssh1_write_bignum(p, key->private_exponent);\r
397     p += ssh1_write_bignum(p, key->iqmp);\r
398     p += ssh1_write_bignum(p, key->q);\r
399     p += ssh1_write_bignum(p, key->p);\r
401     /*\r
402      * Now write zeros until the encrypted portion is a multiple of\r
403      * 8 bytes.\r
404      */\r
405     while ((p - estart) % 8)\r
406         *p++ = '\0';\r
408     /*\r
409      * Now encrypt the encrypted portion.\r
410      */\r
411     if (passphrase) {\r
412         MD5Init(&md5c);\r
413         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));\r
414         MD5Final(keybuf, &md5c);\r
415         des3_encrypt_pubkey(keybuf, estart, p - estart);\r
416         smemclr(keybuf, sizeof(keybuf));        /* burn the evidence */\r
417     }\r
419     /*\r
420      * Done. Write the result to the file.\r
421      */\r
422     fp = f_open(filename, "wb", TRUE);\r
423     if (fp) {\r
424         int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));\r
425         if (fclose(fp))\r
426             ret = 0;\r
427         return ret;\r
428     } else\r
429         return 0;\r
432 /* ----------------------------------------------------------------------\r
433  * SSH-2 private key load/store functions.\r
434  */\r
436 /*\r
437  * PuTTY's own format for SSH-2 keys is as follows:\r
438  *\r
439  * The file is text. Lines are terminated by CRLF, although CR-only\r
440  * and LF-only are tolerated on input.\r
441  *\r
442  * The first line says "PuTTY-User-Key-File-2: " plus the name of the\r
443  * algorithm ("ssh-dss", "ssh-rsa" etc).\r
444  *\r
445  * The next line says "Encryption: " plus an encryption type.\r
446  * Currently the only supported encryption types are "aes256-cbc"\r
447  * and "none".\r
448  *\r
449  * The next line says "Comment: " plus the comment string.\r
450  *\r
451  * Next there is a line saying "Public-Lines: " plus a number N.\r
452  * The following N lines contain a base64 encoding of the public\r
453  * part of the key. This is encoded as the standard SSH-2 public key\r
454  * blob (with no initial length): so for RSA, for example, it will\r
455  * read\r
456  *\r
457  *    string "ssh-rsa"\r
458  *    mpint  exponent\r
459  *    mpint  modulus\r
460  *\r
461  * Next, there is a line saying "Private-Lines: " plus a number N,\r
462  * and then N lines containing the (potentially encrypted) private\r
463  * part of the key. For the key type "ssh-rsa", this will be\r
464  * composed of\r
465  *\r
466  *    mpint  private_exponent\r
467  *    mpint  p                  (the larger of the two primes)\r
468  *    mpint  q                  (the smaller prime)\r
469  *    mpint  iqmp               (the inverse of q modulo p)\r
470  *    data   padding            (to reach a multiple of the cipher block size)\r
471  *\r
472  * And for "ssh-dss", it will be composed of\r
473  *\r
474  *    mpint  x                  (the private key parameter)\r
475  *  [ string hash   20-byte hash of mpints p || q || g   only in old format ]\r
476  * \r
477  * Finally, there is a line saying "Private-MAC: " plus a hex\r
478  * representation of a HMAC-SHA-1 of:\r
479  *\r
480  *    string  name of algorithm ("ssh-dss", "ssh-rsa")\r
481  *    string  encryption type\r
482  *    string  comment\r
483  *    string  public-blob\r
484  *    string  private-plaintext (the plaintext version of the\r
485  *                               private part, including the final\r
486  *                               padding)\r
487  * \r
488  * The key to the MAC is itself a SHA-1 hash of:\r
489  * \r
490  *    data    "putty-private-key-file-mac-key"\r
491  *    data    passphrase\r
492  *\r
493  * (An empty passphrase is used for unencrypted keys.)\r
494  *\r
495  * If the key is encrypted, the encryption key is derived from the\r
496  * passphrase by means of a succession of SHA-1 hashes. Each hash\r
497  * is the hash of:\r
498  *\r
499  *    uint32  sequence-number\r
500  *    data    passphrase\r
501  *\r
502  * where the sequence-number increases from zero. As many of these\r
503  * hashes are used as necessary.\r
504  *\r
505  * For backwards compatibility with snapshots between 0.51 and\r
506  * 0.52, we also support the older key file format, which begins\r
507  * with "PuTTY-User-Key-File-1" (version number differs). In this\r
508  * format the Private-MAC: field only covers the private-plaintext\r
509  * field and nothing else (and without the 4-byte string length on\r
510  * the front too). Moreover, the Private-MAC: field can be replaced\r
511  * with a Private-Hash: field which is a plain SHA-1 hash instead of\r
512  * an HMAC (this was generated for unencrypted keys).\r
513  */\r
515 static int read_header(FILE * fp, char *header)\r
517     int len = 39;\r
518     int c;\r
520     while (1) {\r
521         c = fgetc(fp);\r
522         if (c == '\n' || c == '\r' || c == EOF)\r
523             return 0;                  /* failure */\r
524         if (c == ':') {\r
525             c = fgetc(fp);\r
526             if (c != ' ')\r
527                 return 0;\r
528             *header = '\0';\r
529             return 1;                  /* success! */\r
530         }\r
531         if (len == 0)\r
532             return 0;                  /* failure */\r
533         *header++ = c;\r
534         len--;\r
535     }\r
536     return 0;                          /* failure */\r
539 static char *read_body(FILE * fp)\r
541     char *text;\r
542     int len;\r
543     int size;\r
544     int c;\r
546     size = 128;\r
547     text = snewn(size, char);\r
548     len = 0;\r
549     text[len] = '\0';\r
551     while (1) {\r
552         c = fgetc(fp);\r
553         if (c == '\r' || c == '\n' || c == EOF) {\r
554             if (c != EOF) {\r
555                 c = fgetc(fp);\r
556                 if (c != '\r' && c != '\n')\r
557                     ungetc(c, fp);\r
558             }\r
559             return text;\r
560         }\r
561         if (len + 1 >= size) {\r
562             size += 128;\r
563             text = sresize(text, size, char);\r
564         }\r
565         text[len++] = c;\r
566         text[len] = '\0';\r
567     }\r
570 static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)\r
572     unsigned char *blob;\r
573     char *line;\r
574     int linelen, len;\r
575     int i, j, k;\r
577     /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */\r
578     blob = snewn(48 * nlines, unsigned char);\r
579     len = 0;\r
580     for (i = 0; i < nlines; i++) {\r
581         line = read_body(fp);\r
582         if (!line) {\r
583             sfree(blob);\r
584             return NULL;\r
585         }\r
586         linelen = strlen(line);\r
587         if (linelen % 4 != 0 || linelen > 64) {\r
588             sfree(blob);\r
589             sfree(line);\r
590             return NULL;\r
591         }\r
592         for (j = 0; j < linelen; j += 4) {\r
593             k = base64_decode_atom(line + j, blob + len);\r
594             if (!k) {\r
595                 sfree(line);\r
596                 sfree(blob);\r
597                 return NULL;\r
598             }\r
599             len += k;\r
600         }\r
601         sfree(line);\r
602     }\r
603     *bloblen = len;\r
604     return blob;\r
607 /*\r
608  * Magic error return value for when the passphrase is wrong.\r
609  */\r
610 struct ssh2_userkey ssh2_wrong_passphrase = {\r
611     NULL, NULL, NULL\r
612 };\r
614 const struct ssh_signkey *find_pubkey_alg_len(int namelen, const char *name)\r
616     if (match_ssh_id(namelen, name, "ssh-rsa"))\r
617         return &ssh_rsa;\r
618     else if (match_ssh_id(namelen, name, "ssh-dss"))\r
619         return &ssh_dss;\r
620     else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp256"))\r
621         return &ssh_ecdsa_nistp256;\r
622     else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp384"))\r
623         return &ssh_ecdsa_nistp384;\r
624     else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp521"))\r
625         return &ssh_ecdsa_nistp521;\r
626     else if (match_ssh_id(namelen, name, "ssh-ed25519"))\r
627         return &ssh_ecdsa_ed25519;\r
628     else\r
629         return NULL;\r
632 const struct ssh_signkey *find_pubkey_alg(const char *name)\r
634     return find_pubkey_alg_len(strlen(name), name);\r
637 struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,\r
638                                        const char *passphrase,\r
639                                        const char **errorstr)\r
641     FILE *fp;\r
642     char header[40], *b, *encryption, *comment, *mac;\r
643     const struct ssh_signkey *alg;\r
644     struct ssh2_userkey *ret;\r
645     int cipher, cipherblk;\r
646     unsigned char *public_blob, *private_blob;\r
647     int public_blob_len, private_blob_len;\r
648     int i, is_mac, old_fmt;\r
649     int passlen = passphrase ? strlen(passphrase) : 0;\r
650     const char *error = NULL;\r
652     ret = NULL;                        /* return NULL for most errors */\r
653     encryption = comment = mac = NULL;\r
654     public_blob = private_blob = NULL;\r
656     fp = f_open(filename, "rb", FALSE);\r
657     if (!fp) {\r
658         error = "can't open file";\r
659         goto error;\r
660     }\r
662     /* Read the first header line which contains the key type. */\r
663     if (!read_header(fp, header))\r
664         goto error;\r
665     if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {\r
666         old_fmt = 0;\r
667     } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {\r
668         /* this is an old key file; warn and then continue */\r
669         old_keyfile_warning();\r
670         old_fmt = 1;\r
671     } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {\r
672         /* this is a key file FROM THE FUTURE; refuse it, but with a\r
673          * more specific error message than the generic one below */\r
674         error = "PuTTY key format too new";\r
675         goto error;\r
676     } else {\r
677         error = "not a PuTTY SSH-2 private key";\r
678         goto error;\r
679     }\r
680     error = "file format error";\r
681     if ((b = read_body(fp)) == NULL)\r
682         goto error;\r
683     /* Select key algorithm structure. */\r
684     alg = find_pubkey_alg(b);\r
685     if (!alg) {\r
686         sfree(b);\r
687         goto error;\r
688     }\r
689     sfree(b);\r
691     /* Read the Encryption header line. */\r
692     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))\r
693         goto error;\r
694     if ((encryption = read_body(fp)) == NULL)\r
695         goto error;\r
696     if (!strcmp(encryption, "aes256-cbc")) {\r
697         cipher = 1;\r
698         cipherblk = 16;\r
699     } else if (!strcmp(encryption, "none")) {\r
700         cipher = 0;\r
701         cipherblk = 1;\r
702     } else {\r
703         goto error;\r
704     }\r
706     /* Read the Comment header line. */\r
707     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))\r
708         goto error;\r
709     if ((comment = read_body(fp)) == NULL)\r
710         goto error;\r
712     /* Read the Public-Lines header line and the public blob. */\r
713     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))\r
714         goto error;\r
715     if ((b = read_body(fp)) == NULL)\r
716         goto error;\r
717     i = atoi(b);\r
718     sfree(b);\r
719     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)\r
720         goto error;\r
722     /* Read the Private-Lines header line and the Private blob. */\r
723     if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))\r
724         goto error;\r
725     if ((b = read_body(fp)) == NULL)\r
726         goto error;\r
727     i = atoi(b);\r
728     sfree(b);\r
729     if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)\r
730         goto error;\r
732     /* Read the Private-MAC or Private-Hash header line. */\r
733     if (!read_header(fp, header))\r
734         goto error;\r
735     if (0 == strcmp(header, "Private-MAC")) {\r
736         if ((mac = read_body(fp)) == NULL)\r
737             goto error;\r
738         is_mac = 1;\r
739     } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {\r
740         if ((mac = read_body(fp)) == NULL)\r
741             goto error;\r
742         is_mac = 0;\r
743     } else\r
744         goto error;\r
746     fclose(fp);\r
747     fp = NULL;\r
749     /*\r
750      * Decrypt the private blob.\r
751      */\r
752     if (cipher) {\r
753         unsigned char key[40];\r
754         SHA_State s;\r
756         if (!passphrase)\r
757             goto error;\r
758         if (private_blob_len % cipherblk)\r
759             goto error;\r
761         SHA_Init(&s);\r
762         SHA_Bytes(&s, "\0\0\0\0", 4);\r
763         SHA_Bytes(&s, passphrase, passlen);\r
764         SHA_Final(&s, key + 0);\r
765         SHA_Init(&s);\r
766         SHA_Bytes(&s, "\0\0\0\1", 4);\r
767         SHA_Bytes(&s, passphrase, passlen);\r
768         SHA_Final(&s, key + 20);\r
769         aes256_decrypt_pubkey(key, private_blob, private_blob_len);\r
770     }\r
772     /*\r
773      * Verify the MAC.\r
774      */\r
775     {\r
776         char realmac[41];\r
777         unsigned char binary[20];\r
778         unsigned char *macdata;\r
779         int maclen;\r
780         int free_macdata;\r
782         if (old_fmt) {\r
783             /* MAC (or hash) only covers the private blob. */\r
784             macdata = private_blob;\r
785             maclen = private_blob_len;\r
786             free_macdata = 0;\r
787         } else {\r
788             unsigned char *p;\r
789             int namelen = strlen(alg->name);\r
790             int enclen = strlen(encryption);\r
791             int commlen = strlen(comment);\r
792             maclen = (4 + namelen +\r
793                       4 + enclen +\r
794                       4 + commlen +\r
795                       4 + public_blob_len +\r
796                       4 + private_blob_len);\r
797             macdata = snewn(maclen, unsigned char);\r
798             p = macdata;\r
799 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)\r
800             DO_STR(alg->name, namelen);\r
801             DO_STR(encryption, enclen);\r
802             DO_STR(comment, commlen);\r
803             DO_STR(public_blob, public_blob_len);\r
804             DO_STR(private_blob, private_blob_len);\r
806             free_macdata = 1;\r
807         }\r
809         if (is_mac) {\r
810             SHA_State s;\r
811             unsigned char mackey[20];\r
812             char header[] = "putty-private-key-file-mac-key";\r
814             SHA_Init(&s);\r
815             SHA_Bytes(&s, header, sizeof(header)-1);\r
816             if (cipher && passphrase)\r
817                 SHA_Bytes(&s, passphrase, passlen);\r
818             SHA_Final(&s, mackey);\r
820             hmac_sha1_simple(mackey, 20, macdata, maclen, binary);\r
822             smemclr(mackey, sizeof(mackey));\r
823             smemclr(&s, sizeof(s));\r
824         } else {\r
825             SHA_Simple(macdata, maclen, binary);\r
826         }\r
828         if (free_macdata) {\r
829             smemclr(macdata, maclen);\r
830             sfree(macdata);\r
831         }\r
833         for (i = 0; i < 20; i++)\r
834             sprintf(realmac + 2 * i, "%02x", binary[i]);\r
836         if (strcmp(mac, realmac)) {\r
837             /* An incorrect MAC is an unconditional Error if the key is\r
838              * unencrypted. Otherwise, it means Wrong Passphrase. */\r
839             if (cipher) {\r
840                 error = "wrong passphrase";\r
841                 ret = SSH2_WRONG_PASSPHRASE;\r
842             } else {\r
843                 error = "MAC failed";\r
844                 ret = NULL;\r
845             }\r
846             goto error;\r
847         }\r
848     }\r
849     sfree(mac);\r
850     mac = NULL;\r
852     /*\r
853      * Create and return the key.\r
854      */\r
855     ret = snew(struct ssh2_userkey);\r
856     ret->alg = alg;\r
857     ret->comment = comment;\r
858     ret->data = alg->createkey(alg, public_blob, public_blob_len,\r
859                                private_blob, private_blob_len);\r
860     if (!ret->data) {\r
861         sfree(ret);\r
862         ret = NULL;\r
863         error = "createkey failed";\r
864         goto error;\r
865     }\r
866     sfree(public_blob);\r
867     smemclr(private_blob, private_blob_len);\r
868     sfree(private_blob);\r
869     sfree(encryption);\r
870     if (errorstr)\r
871         *errorstr = NULL;\r
872     return ret;\r
874     /*\r
875      * Error processing.\r
876      */\r
877   error:\r
878     if (fp)\r
879         fclose(fp);\r
880     if (comment)\r
881         sfree(comment);\r
882     if (encryption)\r
883         sfree(encryption);\r
884     if (mac)\r
885         sfree(mac);\r
886     if (public_blob)\r
887         sfree(public_blob);\r
888     if (private_blob) {\r
889         smemclr(private_blob, private_blob_len);\r
890         sfree(private_blob);\r
891     }\r
892     if (errorstr)\r
893         *errorstr = error;\r
894     return ret;\r
897 unsigned char *rfc4716_loadpub(FILE *fp, char **algorithm,\r
898                                int *pub_blob_len, char **commentptr,\r
899                                const char **errorstr)\r
901     const char *error;\r
902     char *line, *colon, *value;\r
903     char *comment = NULL;\r
904     unsigned char *pubblob = NULL;\r
905     int pubbloblen, pubblobsize;\r
906     char base64in[4];\r
907     unsigned char base64out[3];\r
908     int base64bytes;\r
909     int alglen;\r
911     line = chomp(fgetline(fp));\r
912     if (!line || 0 != strcmp(line, "---- BEGIN SSH2 PUBLIC KEY ----")) {\r
913         error = "invalid begin line in SSH-2 public key file";\r
914         goto error;\r
915     }\r
916     sfree(line); line = NULL;\r
918     while (1) {\r
919         line = chomp(fgetline(fp));\r
920         if (!line) {\r
921             error = "truncated SSH-2 public key file";\r
922             goto error;\r
923         }\r
924         colon = strstr(line, ": ");\r
925         if (!colon)\r
926             break;\r
927         *colon = '\0';\r
928         value = colon + 2;\r
930         if (!strcmp(line, "Comment")) {\r
931             char *p, *q;\r
933             /* Remove containing double quotes, if present */\r
934             p = value;\r
935             if (*p == '"' && p[strlen(p)-1] == '"') {\r
936                 p[strlen(p)-1] = '\0';\r
937                 p++;\r
938             }\r
940             /* Remove \-escaping, not in RFC4716 but seen in the wild\r
941              * in practice. */\r
942             for (q = line; *p; p++) {\r
943                 if (*p == '\\' && p[1])\r
944                     p++;\r
945                 *q++ = *p;\r
946             }\r
948             *q = '\0';\r
949             sfree(comment);   /* *just* in case of multiple Comment headers */\r
950             comment = dupstr(line);\r
951         } else if (!strcmp(line, "Subject") ||\r
952                    !strncmp(line, "x-", 2)) {\r
953             /* Headers we recognise and ignore. Do nothing. */\r
954         } else {\r
955             error = "unrecognised header in SSH-2 public key file";\r
956             goto error;\r
957         }\r
959         sfree(line); line = NULL;\r
960     }\r
962     /*\r
963      * Now line contains the initial line of base64 data. Loop round\r
964      * while it still does contain base64.\r
965      */\r
966     pubblobsize = 4096;\r
967     pubblob = snewn(pubblobsize, unsigned char);\r
968     pubbloblen = 0;\r
969     base64bytes = 0;\r
970     while (line && line[0] != '-') {\r
971         char *p;\r
972         for (p = line; *p; p++) {\r
973             base64in[base64bytes++] = *p;\r
974             if (base64bytes == 4) {\r
975                 int n = base64_decode_atom(base64in, base64out);\r
976                 if (pubbloblen + n > pubblobsize) {\r
977                     pubblobsize = (pubbloblen + n) * 5 / 4 + 1024;\r
978                     pubblob = sresize(pubblob, pubblobsize, unsigned char);\r
979                 }\r
980                 memcpy(pubblob + pubbloblen, base64out, n);\r
981                 pubbloblen += n;\r
982                 base64bytes = 0;\r
983             }\r
984         }\r
985         sfree(line); line = NULL;\r
986         line = chomp(fgetline(fp));\r
987     }\r
989     /*\r
990      * Finally, check the END line makes sense.\r
991      */\r
992     if (!line || 0 != strcmp(line, "---- END SSH2 PUBLIC KEY ----")) {\r
993         error = "invalid end line in SSH-2 public key file";\r
994         goto error;\r
995     }\r
996     sfree(line); line = NULL;\r
998     /*\r
999      * OK, we now have a public blob and optionally a comment. We must\r
1000      * return the key algorithm string too, so look for that at the\r
1001      * start of the public blob.\r
1002      */\r
1003     if (pubbloblen < 4) {\r
1004         error = "not enough data in SSH-2 public key file";\r
1005         goto error;\r
1006     }\r
1007     alglen = toint(GET_32BIT(pubblob));\r
1008     if (alglen < 0 || alglen > pubbloblen-4) {\r
1009         error = "invalid algorithm prefix in SSH-2 public key file";\r
1010         goto error;\r
1011     }\r
1012     if (algorithm)\r
1013         *algorithm = dupprintf("%.*s", alglen, pubblob+4);\r
1014     if (pub_blob_len)\r
1015         *pub_blob_len = pubbloblen;\r
1016     if (commentptr)\r
1017         *commentptr = comment;\r
1018     else\r
1019         sfree(comment);\r
1020     return pubblob;\r
1022   error:\r
1023     sfree(line);\r
1024     sfree(comment);\r
1025     sfree(pubblob);\r
1026     if (errorstr)\r
1027         *errorstr = error;\r
1028     return NULL;\r
1031 unsigned char *openssh_loadpub(FILE *fp, char **algorithm,\r
1032                                int *pub_blob_len, char **commentptr,\r
1033                                const char **errorstr)\r
1035     const char *error;\r
1036     char *line, *base64;\r
1037     char *comment = NULL;\r
1038     unsigned char *pubblob = NULL;\r
1039     int pubbloblen, pubblobsize;\r
1040     int alglen;\r
1042     line = chomp(fgetline(fp));\r
1044     base64 = strchr(line, ' ');\r
1045     if (!base64) {\r
1046         error = "no key blob in OpenSSH public key file";\r
1047         goto error;\r
1048     }\r
1049     *base64++ = '\0';\r
1051     comment = strchr(base64, ' ');\r
1052     if (comment) {\r
1053         *comment++ = '\0';\r
1054         comment = dupstr(comment);\r
1055     }\r
1057     pubblobsize = strlen(base64) / 4 * 3;\r
1058     pubblob = snewn(pubblobsize, unsigned char);\r
1059     pubbloblen = 0;\r
1061     while (!memchr(base64, '\0', 4)) {\r
1062         assert(pubbloblen + 3 <= pubblobsize);\r
1063         pubbloblen += base64_decode_atom(base64, pubblob + pubbloblen);\r
1064         base64 += 4;\r
1065     }\r
1066     if (*base64) {\r
1067         error = "invalid length for base64 data in OpenSSH public key file";\r
1068         goto error;\r
1069     }\r
1071     /*\r
1072      * Sanity check: the first word on the line should be the key\r
1073      * algorithm, and should match the encoded string at the start of\r
1074      * the public blob.\r
1075      */\r
1076     alglen = strlen(line);\r
1077     if (pubbloblen < alglen + 4 ||\r
1078         GET_32BIT(pubblob) != alglen ||\r
1079         0 != memcmp(pubblob + 4, line, alglen)) {\r
1080         error = "key algorithms do not match in OpenSSH public key file";\r
1081         goto error;\r
1082     }\r
1084     /*\r
1085      * Done.\r
1086      */\r
1087     if (algorithm)\r
1088         *algorithm = dupstr(line);\r
1089     if (pub_blob_len)\r
1090         *pub_blob_len = pubbloblen;\r
1091     if (commentptr)\r
1092         *commentptr = comment;\r
1093     else\r
1094         sfree(comment);\r
1095     sfree(line);\r
1096     return pubblob;\r
1098   error:\r
1099     sfree(line);\r
1100     sfree(comment);\r
1101     sfree(pubblob);\r
1102     if (errorstr)\r
1103         *errorstr = error;\r
1104     return NULL;\r
1107 unsigned char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,\r
1108                                     int *pub_blob_len, char **commentptr,\r
1109                                     const char **errorstr)\r
1111     FILE *fp;\r
1112     char header[40], *b;\r
1113     const struct ssh_signkey *alg;\r
1114     unsigned char *public_blob;\r
1115     int public_blob_len;\r
1116     int type, i;\r
1117     const char *error = NULL;\r
1118     char *comment = NULL;\r
1120     public_blob = NULL;\r
1122     fp = f_open(filename, "rb", FALSE);\r
1123     if (!fp) {\r
1124         error = "can't open file";\r
1125         goto error;\r
1126     }\r
1128     /* Initially, check if this is a public-only key file. Sometimes\r
1129      * we'll be asked to read a public blob from one of those. */\r
1130     type = key_type_fp(fp);\r
1131     if (type == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {\r
1132         unsigned char *ret = rfc4716_loadpub(fp, algorithm, pub_blob_len,\r
1133                                              commentptr, errorstr);\r
1134         fclose(fp);\r
1135         return ret;\r
1136     } else if (type == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {\r
1137         unsigned char *ret = openssh_loadpub(fp, algorithm, pub_blob_len,\r
1138                                              commentptr, errorstr);\r
1139         fclose(fp);\r
1140         return ret;\r
1141     } else if (type != SSH_KEYTYPE_SSH2) {\r
1142         error = "not a PuTTY SSH-2 private key";\r
1143         goto error;\r
1144     }\r
1146     /* Read the first header line which contains the key type. */\r
1147     if (!read_header(fp, header)\r
1148         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&\r
1149             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {\r
1150         if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))\r
1151             error = "PuTTY key format too new";\r
1152         else\r
1153             error = "not a PuTTY SSH-2 private key";\r
1154         goto error;\r
1155     }\r
1156     error = "file format error";\r
1157     if ((b = read_body(fp)) == NULL)\r
1158         goto error;\r
1159     /* Select key algorithm structure. */\r
1160     alg = find_pubkey_alg(b);\r
1161     sfree(b);\r
1162     if (!alg) {\r
1163         goto error;\r
1164     }\r
1166     /* Read the Encryption header line. */\r
1167     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))\r
1168         goto error;\r
1169     if ((b = read_body(fp)) == NULL)\r
1170         goto error;\r
1171     sfree(b);                          /* we don't care */\r
1173     /* Read the Comment header line. */\r
1174     if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))\r
1175         goto error;\r
1176     if ((comment = read_body(fp)) == NULL)\r
1177         goto error;\r
1179     if (commentptr)\r
1180         *commentptr = comment;\r
1181     else\r
1182         sfree(comment);\r
1184     /* Read the Public-Lines header line and the public blob. */\r
1185     if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))\r
1186         goto error;\r
1187     if ((b = read_body(fp)) == NULL)\r
1188         goto error;\r
1189     i = atoi(b);\r
1190     sfree(b);\r
1191     if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)\r
1192         goto error;\r
1194     fclose(fp);\r
1195     if (pub_blob_len)\r
1196         *pub_blob_len = public_blob_len;\r
1197     if (algorithm)\r
1198         *algorithm = dupstr(alg->name);\r
1199     return public_blob;\r
1201     /*\r
1202      * Error processing.\r
1203      */\r
1204   error:\r
1205     if (fp)\r
1206         fclose(fp);\r
1207     if (public_blob)\r
1208         sfree(public_blob);\r
1209     if (errorstr)\r
1210         *errorstr = error;\r
1211     if (comment && commentptr) {\r
1212         sfree(comment);\r
1213         *commentptr = NULL;\r
1214     }\r
1215     return NULL;\r
1218 int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)\r
1220     FILE *fp;\r
1221     char header[40], *b, *comment;\r
1222     int ret;\r
1224     if (commentptr)\r
1225         *commentptr = NULL;\r
1227     fp = f_open(filename, "rb", FALSE);\r
1228     if (!fp)\r
1229         return 0;\r
1230     if (!read_header(fp, header)\r
1231         || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&\r
1232             0 != strcmp(header, "PuTTY-User-Key-File-1"))) {\r
1233         fclose(fp);\r
1234         return 0;\r
1235     }\r
1236     if ((b = read_body(fp)) == NULL) {\r
1237         fclose(fp);\r
1238         return 0;\r
1239     }\r
1240     sfree(b);                          /* we don't care about key type here */\r
1241     /* Read the Encryption header line. */\r
1242     if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {\r
1243         fclose(fp);\r
1244         return 0;\r
1245     }\r
1246     if ((b = read_body(fp)) == NULL) {\r
1247         fclose(fp);\r
1248         return 0;\r
1249     }\r
1251     /* Read the Comment header line. */\r
1252     if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {\r
1253         fclose(fp);\r
1254         sfree(b);\r
1255         return 1;\r
1256     }\r
1257     if ((comment = read_body(fp)) == NULL) {\r
1258         fclose(fp);\r
1259         sfree(b);\r
1260         return 1;\r
1261     }\r
1263     if (commentptr)\r
1264         *commentptr = comment;\r
1265     else\r
1266         sfree(comment);\r
1268     fclose(fp);\r
1269     if (!strcmp(b, "aes256-cbc"))\r
1270         ret = 1;\r
1271     else\r
1272         ret = 0;\r
1273     sfree(b);\r
1274     return ret;\r
1277 int base64_lines(int datalen)\r
1279     /* When encoding, we use 64 chars/line, which equals 48 real chars. */\r
1280     return (datalen + 47) / 48;\r
1283 void base64_encode(FILE *fp, const unsigned char *data, int datalen, int cpl)\r
1285     int linelen = 0;\r
1286     char out[4];\r
1287     int n, i;\r
1289     while (datalen > 0) {\r
1290         n = (datalen < 3 ? datalen : 3);\r
1291         base64_encode_atom(data, n, out);\r
1292         data += n;\r
1293         datalen -= n;\r
1294         for (i = 0; i < 4; i++) {\r
1295             if (linelen >= cpl) {\r
1296                 linelen = 0;\r
1297                 fputc('\n', fp);\r
1298             }\r
1299             fputc(out[i], fp);\r
1300             linelen++;\r
1301         }\r
1302     }\r
1303     fputc('\n', fp);\r
1306 int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,\r
1307                       char *passphrase)\r
1309     FILE *fp;\r
1310     unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;\r
1311     int pub_blob_len, priv_blob_len, priv_encrypted_len;\r
1312     int passlen;\r
1313     int cipherblk;\r
1314     int i;\r
1315     const char *cipherstr;\r
1316     unsigned char priv_mac[20];\r
1318     /*\r
1319      * Fetch the key component blobs.\r
1320      */\r
1321     pub_blob = key->alg->public_blob(key->data, &pub_blob_len);\r
1322     priv_blob = key->alg->private_blob(key->data, &priv_blob_len);\r
1323     if (!pub_blob || !priv_blob) {\r
1324         sfree(pub_blob);\r
1325         sfree(priv_blob);\r
1326         return 0;\r
1327     }\r
1329     /*\r
1330      * Determine encryption details, and encrypt the private blob.\r
1331      */\r
1332     if (passphrase) {\r
1333         cipherstr = "aes256-cbc";\r
1334         cipherblk = 16;\r
1335     } else {\r
1336         cipherstr = "none";\r
1337         cipherblk = 1;\r
1338     }\r
1339     priv_encrypted_len = priv_blob_len + cipherblk - 1;\r
1340     priv_encrypted_len -= priv_encrypted_len % cipherblk;\r
1341     priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);\r
1342     memset(priv_blob_encrypted, 0, priv_encrypted_len);\r
1343     memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);\r
1344     /* Create padding based on the SHA hash of the unpadded blob. This prevents\r
1345      * too easy a known-plaintext attack on the last block. */\r
1346     SHA_Simple(priv_blob, priv_blob_len, priv_mac);\r
1347     assert(priv_encrypted_len - priv_blob_len < 20);\r
1348     memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,\r
1349            priv_encrypted_len - priv_blob_len);\r
1351     /* Now create the MAC. */\r
1352     {\r
1353         unsigned char *macdata;\r
1354         int maclen;\r
1355         unsigned char *p;\r
1356         int namelen = strlen(key->alg->name);\r
1357         int enclen = strlen(cipherstr);\r
1358         int commlen = strlen(key->comment);\r
1359         SHA_State s;\r
1360         unsigned char mackey[20];\r
1361         char header[] = "putty-private-key-file-mac-key";\r
1363         maclen = (4 + namelen +\r
1364                   4 + enclen +\r
1365                   4 + commlen +\r
1366                   4 + pub_blob_len +\r
1367                   4 + priv_encrypted_len);\r
1368         macdata = snewn(maclen, unsigned char);\r
1369         p = macdata;\r
1370 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)\r
1371         DO_STR(key->alg->name, namelen);\r
1372         DO_STR(cipherstr, enclen);\r
1373         DO_STR(key->comment, commlen);\r
1374         DO_STR(pub_blob, pub_blob_len);\r
1375         DO_STR(priv_blob_encrypted, priv_encrypted_len);\r
1377         SHA_Init(&s);\r
1378         SHA_Bytes(&s, header, sizeof(header)-1);\r
1379         if (passphrase)\r
1380             SHA_Bytes(&s, passphrase, strlen(passphrase));\r
1381         SHA_Final(&s, mackey);\r
1382         hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);\r
1383         smemclr(macdata, maclen);\r
1384         sfree(macdata);\r
1385         smemclr(mackey, sizeof(mackey));\r
1386         smemclr(&s, sizeof(s));\r
1387     }\r
1389     if (passphrase) {\r
1390         unsigned char key[40];\r
1391         SHA_State s;\r
1393         passlen = strlen(passphrase);\r
1395         SHA_Init(&s);\r
1396         SHA_Bytes(&s, "\0\0\0\0", 4);\r
1397         SHA_Bytes(&s, passphrase, passlen);\r
1398         SHA_Final(&s, key + 0);\r
1399         SHA_Init(&s);\r
1400         SHA_Bytes(&s, "\0\0\0\1", 4);\r
1401         SHA_Bytes(&s, passphrase, passlen);\r
1402         SHA_Final(&s, key + 20);\r
1403         aes256_encrypt_pubkey(key, priv_blob_encrypted,\r
1404                               priv_encrypted_len);\r
1406         smemclr(key, sizeof(key));\r
1407         smemclr(&s, sizeof(s));\r
1408     }\r
1410     fp = f_open(filename, "w", TRUE);\r
1411     if (!fp) {\r
1412         sfree(pub_blob);\r
1413         smemclr(priv_blob, priv_blob_len);\r
1414         sfree(priv_blob);\r
1415         smemclr(priv_blob_encrypted, priv_blob_len);\r
1416         sfree(priv_blob_encrypted);\r
1417         return 0;\r
1418     }\r
1419     fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);\r
1420     fprintf(fp, "Encryption: %s\n", cipherstr);\r
1421     fprintf(fp, "Comment: %s\n", key->comment);\r
1422     fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));\r
1423     base64_encode(fp, pub_blob, pub_blob_len, 64);\r
1424     fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));\r
1425     base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);\r
1426     fprintf(fp, "Private-MAC: ");\r
1427     for (i = 0; i < 20; i++)\r
1428         fprintf(fp, "%02x", priv_mac[i]);\r
1429     fprintf(fp, "\n");\r
1430     fclose(fp);\r
1432     sfree(pub_blob);\r
1433     smemclr(priv_blob, priv_blob_len);\r
1434     sfree(priv_blob);\r
1435     smemclr(priv_blob_encrypted, priv_blob_len);\r
1436     sfree(priv_blob_encrypted);\r
1437     return 1;\r
1440 /* ----------------------------------------------------------------------\r
1441  * Output public keys.\r
1442  */\r
1443 char *ssh1_pubkey_str(struct RSAKey *key)\r
1445     char *buffer;\r
1446     char *dec1, *dec2;\r
1448     dec1 = bignum_decimal(key->exponent);\r
1449     dec2 = bignum_decimal(key->modulus);\r
1450     buffer = dupprintf("%d %s %s%s%s", bignum_bitcount(key->modulus),\r
1451                        dec1, dec2,\r
1452                        key->comment ? " " : "",\r
1453                        key->comment ? key->comment : "");\r
1454     sfree(dec1);\r
1455     sfree(dec2);\r
1456     return buffer;\r
1459 void ssh1_write_pubkey(FILE *fp, struct RSAKey *key)\r
1461     char *buffer = ssh1_pubkey_str(key);\r
1462     fprintf(fp, "%s\n", buffer);\r
1463     sfree(buffer);\r
1466 static char *ssh2_pubkey_openssh_str_internal(const char *comment,\r
1467                                               const void *v_pub_blob,\r
1468                                               int pub_len)\r
1470     const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;\r
1471     const char *alg;\r
1472     int alglen;\r
1473     char *buffer, *p;\r
1474     int i;\r
1476     if (pub_len < 4) {\r
1477         alg = NULL;\r
1478     } else {\r
1479         alglen = GET_32BIT(ssh2blob);\r
1480         if (alglen > 0 && alglen < pub_len - 4) {\r
1481             alg = (const char *)ssh2blob + 4;\r
1482         } else {\r
1483             alg = NULL;\r
1484         }\r
1485     }\r
1487     if (!alg) {\r
1488         alg = "INVALID-ALGORITHM";\r
1489         alglen = strlen(alg);\r
1490     }\r
1492     buffer = snewn(alglen +\r
1493                    4 * ((pub_len+2) / 3) +\r
1494                    (comment ? strlen(comment) : 0) + 3, char);\r
1495     p = buffer + sprintf(buffer, "%.*s ", alglen, alg);\r
1496     i = 0;\r
1497     while (i < pub_len) {\r
1498         int n = (pub_len - i < 3 ? pub_len - i : 3);\r
1499         base64_encode_atom(ssh2blob + i, n, p);\r
1500         i += n;\r
1501         p += 4;\r
1502     }\r
1503     if (*comment) {\r
1504         *p++ = ' ';\r
1505         strcpy(p, comment);\r
1506     } else\r
1507         *p++ = '\0';\r
1509     return buffer;\r
1512 char *ssh2_pubkey_openssh_str(struct ssh2_userkey *key)\r
1514     int bloblen;\r
1515     unsigned char *blob;\r
1516     char *ret;\r
1518     blob = key->alg->public_blob(key->data, &bloblen);\r
1519     ret = ssh2_pubkey_openssh_str_internal(key->comment, blob, bloblen);\r
1520     sfree(blob);\r
1522     return ret;\r
1525 void ssh2_write_pubkey(FILE *fp, const char *comment,\r
1526                        const void *v_pub_blob, int pub_len,\r
1527                        int keytype)\r
1529     unsigned char *pub_blob = (unsigned char *)v_pub_blob;\r
1531     if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {\r
1532         const char *p;\r
1533         int i, column;\r
1535         fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");\r
1537         if (comment) {\r
1538             fprintf(fp, "Comment: \"");\r
1539             for (p = comment; *p; p++) {\r
1540                 if (*p == '\\' || *p == '\"')\r
1541                     fputc('\\', fp);\r
1542                 fputc(*p, fp);\r
1543             }\r
1544             fprintf(fp, "\"\n");\r
1545         }\r
1547         i = 0;\r
1548         column = 0;\r
1549         while (i < pub_len) {\r
1550             char buf[5];\r
1551             int n = (pub_len - i < 3 ? pub_len - i : 3);\r
1552             base64_encode_atom(pub_blob + i, n, buf);\r
1553             i += n;\r
1554             buf[4] = '\0';\r
1555             fputs(buf, fp);\r
1556             if (++column >= 16) {\r
1557                 fputc('\n', fp);\r
1558                 column = 0;\r
1559             }\r
1560         }\r
1561         if (column > 0)\r
1562             fputc('\n', fp);\r
1564         fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");\r
1565     } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {\r
1566         char *buffer = ssh2_pubkey_openssh_str_internal(comment,\r
1567                                                         v_pub_blob, pub_len);\r
1568         fprintf(fp, "%s\n", buffer);\r
1569         sfree(buffer);\r
1570     } else {\r
1571         assert(0 && "Bad key type in ssh2_write_pubkey");\r
1572     }\r
1575 /* ----------------------------------------------------------------------\r
1576  * Utility functions to compute SSH-2 fingerprints in a uniform way.\r
1577  */\r
1578 char *ssh2_fingerprint_blob(const void *blob, int bloblen)\r
1580     unsigned char digest[16];\r
1581     char fingerprint_str[16*3];\r
1582     const char *algstr;\r
1583     int alglen;\r
1584     const struct ssh_signkey *alg;\r
1585     int i;\r
1587     /*\r
1588      * The fingerprint hash itself is always just the MD5 of the blob.\r
1589      */\r
1590     MD5Simple(blob, bloblen, digest);\r
1591     for (i = 0; i < 16; i++)\r
1592         sprintf(fingerprint_str + i*3, "%02x%s", digest[i], i==15 ? "" : ":");\r
1594     /*\r
1595      * Identify the key algorithm, if possible.\r
1596      */\r
1597     alglen = toint(GET_32BIT((const unsigned char *)blob));\r
1598     if (alglen > 0 && alglen < bloblen-4) {\r
1599         algstr = (const char *)blob + 4;\r
1601         /*\r
1602          * If we can actually identify the algorithm as one we know\r
1603          * about, get hold of the key's bit count too.\r
1604          */\r
1605         alg = find_pubkey_alg_len(alglen, algstr);\r
1606         if (alg) {\r
1607             int bits = alg->pubkey_bits(alg, blob, bloblen);\r
1608             return dupprintf("%.*s %d %s", alglen, algstr,\r
1609                              bits, fingerprint_str);\r
1610         } else {\r
1611             return dupprintf("%.*s %s", alglen, algstr, fingerprint_str);\r
1612         }\r
1613     } else {\r
1614         /*\r
1615          * No algorithm available (which means a seriously confused\r
1616          * key blob, but there we go). Return only the hash.\r
1617          */\r
1618         return dupstr(fingerprint_str);\r
1619     }\r
1622 char *ssh2_fingerprint(const struct ssh_signkey *alg, void *data)\r
1624     int len;\r
1625     unsigned char *blob = alg->public_blob(data, &len);\r
1626     char *ret = ssh2_fingerprint_blob(blob, len);\r
1627     sfree(blob);\r
1628     return ret;\r
1631 /* ----------------------------------------------------------------------\r
1632  * Determine the type of a private key file.\r
1633  */\r
1634 static int key_type_fp(FILE *fp)\r
1636     char buf[1024];\r
1637     const char public_std_sig[] = "---- BEGIN SSH2 PUBLIC KEY";\r
1638     const char putty2_sig[] = "PuTTY-User-Key-File-";\r
1639     const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";\r
1640     const char openssh_new_sig[] = "-----BEGIN OPENSSH PRIVATE KEY";\r
1641     const char openssh_sig[] = "-----BEGIN ";\r
1642     int i;\r
1643     char *p;\r
1645     i = fread(buf, 1, sizeof(buf)-1, fp);\r
1646     rewind(fp);\r
1648     if (i < 0)\r
1649         return SSH_KEYTYPE_UNOPENABLE;\r
1650     if (i < 32)\r
1651         return SSH_KEYTYPE_UNKNOWN;\r
1652     assert(i > 0 && i < sizeof(buf));\r
1653     buf[i] = '\0';\r
1654     if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))\r
1655         return SSH_KEYTYPE_SSH1;\r
1656     if (!memcmp(buf, public_std_sig, sizeof(public_std_sig)-1))\r
1657         return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;\r
1658     if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))\r
1659         return SSH_KEYTYPE_SSH2;\r
1660     if (!memcmp(buf, openssh_new_sig, sizeof(openssh_new_sig)-1))\r
1661         return SSH_KEYTYPE_OPENSSH_NEW;\r
1662     if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))\r
1663         return SSH_KEYTYPE_OPENSSH_PEM;\r
1664     if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))\r
1665         return SSH_KEYTYPE_SSHCOM;\r
1666     if ((p = buf + strspn(buf, "0123456789"), *p == ' ') &&\r
1667         (p = p+1 + strspn(p+1, "0123456789"), *p == ' ') &&\r
1668         (p = p+1 + strspn(p+1, "0123456789"), *p == ' ' || *p == '\n' || !*p))\r
1669         return SSH_KEYTYPE_SSH1_PUBLIC;\r
1670     if ((p = buf + strcspn(buf, " "), find_pubkey_alg_len(p-buf, buf)) &&\r
1671         (p = p+1 + strspn(p+1, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"\r
1672                           "klmnopqrstuvwxyz+/="),\r
1673          *p == ' ' || *p == '\n' || !*p))\r
1674         return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;\r
1675     return SSH_KEYTYPE_UNKNOWN;        /* unrecognised or EOF */\r
1678 int key_type(const Filename *filename)\r
1680     FILE *fp;\r
1681     int ret;\r
1683     fp = f_open(filename, "r", FALSE);\r
1684     if (!fp)\r
1685         return SSH_KEYTYPE_UNOPENABLE;\r
1686     ret = key_type_fp(fp);\r
1687     fclose(fp);\r
1688     return ret;\r
1691 /*\r
1692  * Convert the type word to a string, for `wrong type' error\r
1693  * messages.\r
1694  */\r
1695 const char *key_type_to_str(int type)\r
1697     switch (type) {\r
1698       case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;\r
1699       case SSH_KEYTYPE_UNKNOWN: return "not a recognised key file format"; break;\r
1700       case SSH_KEYTYPE_SSH1_PUBLIC: return "SSH-1 public key"; break;\r
1701       case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716: return "SSH-2 public key (RFC 4716 format)"; break;\r
1702       case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH: return "SSH-2 public key (OpenSSH format)"; break;\r
1703       case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;\r
1704       case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;\r
1705       case SSH_KEYTYPE_OPENSSH_PEM: return "OpenSSH SSH-2 private key (old PEM format)"; break;\r
1706       case SSH_KEYTYPE_OPENSSH_NEW: return "OpenSSH SSH-2 private key (new format)"; break;\r
1707       case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;\r
1708         /*\r
1709          * This function is called with a key type derived from\r
1710          * looking at an actual key file, so the output-only type\r
1711          * OPENSSH_AUTO should never get here, and is much an INTERNAL\r
1712          * ERROR as a code we don't even understand.\r
1713          */\r
1714       case SSH_KEYTYPE_OPENSSH_AUTO: return "INTERNAL ERROR (OPENSSH_AUTO)"; break;\r
1715       default: return "INTERNAL ERROR"; break;\r
1716     }\r