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