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