]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - import.c
Refactoring to prepare for extra public key types.
[PuTTY.git] / import.c
1 /*
2  * Code for PuTTY to import and export private key files in other
3  * SSH clients' formats.
4  */
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <assert.h>
9 #include <ctype.h>
10
11 #include "putty.h"
12 #include "ssh.h"
13 #include "misc.h"
14
15 int openssh_encrypted(const Filename *filename);
16 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
17                                   const char **errmsg_p);
18 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
19                   char *passphrase);
20
21 int sshcom_encrypted(const Filename *filename, char **comment);
22 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
23                                  const char **errmsg_p);
24 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
25                  char *passphrase);
26
27 /*
28  * Given a key type, determine whether we know how to import it.
29  */
30 int import_possible(int type)
31 {
32     if (type == SSH_KEYTYPE_OPENSSH)
33         return 1;
34     if (type == SSH_KEYTYPE_SSHCOM)
35         return 1;
36     return 0;
37 }
38
39 /*
40  * Given a key type, determine what native key type
41  * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
42  * we've imported it.
43  */
44 int import_target_type(int type)
45 {
46     /*
47      * There are no known foreign SSH-1 key formats.
48      */
49     return SSH_KEYTYPE_SSH2;
50 }
51
52 /*
53  * Determine whether a foreign key is encrypted.
54  */
55 int import_encrypted(const Filename *filename, int type, char **comment)
56 {
57     if (type == SSH_KEYTYPE_OPENSSH) {
58         /* OpenSSH doesn't do key comments */
59         *comment = dupstr(filename_to_str(filename));
60         return openssh_encrypted(filename);
61     }
62     if (type == SSH_KEYTYPE_SSHCOM) {
63         return sshcom_encrypted(filename, comment);
64     }
65     return 0;
66 }
67
68 /*
69  * Import an SSH-1 key.
70  */
71 int import_ssh1(const Filename *filename, int type,
72                 struct RSAKey *key, char *passphrase, const char **errmsg_p)
73 {
74     return 0;
75 }
76
77 /*
78  * Import an SSH-2 key.
79  */
80 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
81                                  char *passphrase, const char **errmsg_p)
82 {
83     if (type == SSH_KEYTYPE_OPENSSH)
84         return openssh_read(filename, passphrase, errmsg_p);
85     if (type == SSH_KEYTYPE_SSHCOM)
86         return sshcom_read(filename, passphrase, errmsg_p);
87     return NULL;
88 }
89
90 /*
91  * Export an SSH-1 key.
92  */
93 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
94                 char *passphrase)
95 {
96     return 0;
97 }
98
99 /*
100  * Export an SSH-2 key.
101  */
102 int export_ssh2(const Filename *filename, int type,
103                 struct ssh2_userkey *key, char *passphrase)
104 {
105     if (type == SSH_KEYTYPE_OPENSSH)
106         return openssh_write(filename, key, passphrase);
107     if (type == SSH_KEYTYPE_SSHCOM)
108         return sshcom_write(filename, key, passphrase);
109     return 0;
110 }
111
112 /*
113  * Strip trailing CRs and LFs at the end of a line of text.
114  */
115 void strip_crlf(char *str)
116 {
117     char *p = str + strlen(str);
118
119     while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
120         *--p = '\0';
121 }
122
123 /* ----------------------------------------------------------------------
124  * Helper routines. (The base64 ones are defined in sshpubk.c.)
125  */
126
127 #define isbase64(c) (    ((c) >= 'A' && (c) <= 'Z') || \
128                          ((c) >= 'a' && (c) <= 'z') || \
129                          ((c) >= '0' && (c) <= '9') || \
130                          (c) == '+' || (c) == '/' || (c) == '=' \
131                          )
132
133 /*
134  * Read an ASN.1/BER identifier and length pair.
135  * 
136  * Flags are a combination of the #defines listed below.
137  * 
138  * Returns -1 if unsuccessful; otherwise returns the number of
139  * bytes used out of the source data.
140  */
141
142 /* ASN.1 tag classes. */
143 #define ASN1_CLASS_UNIVERSAL        (0 << 6)
144 #define ASN1_CLASS_APPLICATION      (1 << 6)
145 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
146 #define ASN1_CLASS_PRIVATE          (3 << 6)
147 #define ASN1_CLASS_MASK             (3 << 6)
148
149 /* Primitive versus constructed bit. */
150 #define ASN1_CONSTRUCTED            (1 << 5)
151
152 static int ber_read_id_len(void *source, int sourcelen,
153                            int *id, int *length, int *flags)
154 {
155     unsigned char *p = (unsigned char *) source;
156
157     if (sourcelen == 0)
158         return -1;
159
160     *flags = (*p & 0xE0);
161     if ((*p & 0x1F) == 0x1F) {
162         *id = 0;
163         while (*p & 0x80) {
164             p++, sourcelen--;
165             if (sourcelen == 0)
166                 return -1;
167             *id = (*id << 7) | (*p & 0x7F);
168         }
169         p++, sourcelen--;
170     } else {
171         *id = *p & 0x1F;
172         p++, sourcelen--;
173     }
174
175     if (sourcelen == 0)
176         return -1;
177
178     if (*p & 0x80) {
179         int n = *p & 0x7F;
180         p++, sourcelen--;
181         if (sourcelen < n)
182             return -1;
183         *length = 0;
184         while (n--)
185             *length = (*length << 8) | (*p++);
186         sourcelen -= n;
187     } else {
188         *length = *p;
189         p++, sourcelen--;
190     }
191
192     return p - (unsigned char *) source;
193 }
194
195 /*
196  * Write an ASN.1/BER identifier and length pair. Returns the
197  * number of bytes consumed. Assumes dest contains enough space.
198  * Will avoid writing anything if dest is NULL, but still return
199  * amount of space required.
200  */
201 static int ber_write_id_len(void *dest, int id, int length, int flags)
202 {
203     unsigned char *d = (unsigned char *)dest;
204     int len = 0;
205
206     if (id <= 30) {
207         /*
208          * Identifier is one byte.
209          */
210         len++;
211         if (d) *d++ = id | flags;
212     } else {
213         int n;
214         /*
215          * Identifier is multiple bytes: the first byte is 11111
216          * plus the flags, and subsequent bytes encode the value of
217          * the identifier, 7 bits at a time, with the top bit of
218          * each byte 1 except the last one which is 0.
219          */
220         len++;
221         if (d) *d++ = 0x1F | flags;
222         for (n = 1; (id >> (7*n)) > 0; n++)
223             continue;                  /* count the bytes */
224         while (n--) {
225             len++;
226             if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
227         }
228     }
229
230     if (length < 128) {
231         /*
232          * Length is one byte.
233          */
234         len++;
235         if (d) *d++ = length;
236     } else {
237         int n;
238         /*
239          * Length is multiple bytes. The first is 0x80 plus the
240          * number of subsequent bytes, and the subsequent bytes
241          * encode the actual length.
242          */
243         for (n = 1; (length >> (8*n)) > 0; n++)
244             continue;                  /* count the bytes */
245         len++;
246         if (d) *d++ = 0x80 | n;
247         while (n--) {
248             len++;
249             if (d) *d++ = (length >> (8*n)) & 0xFF;
250         }
251     }
252
253     return len;
254 }
255
256 static int put_string(void *target, void *data, int len)
257 {
258     unsigned char *d = (unsigned char *)target;
259
260     PUT_32BIT(d, len);
261     memcpy(d+4, data, len);
262     return len+4;
263 }
264
265 static int put_mp(void *target, void *data, int len)
266 {
267     unsigned char *d = (unsigned char *)target;
268     unsigned char *i = (unsigned char *)data;
269
270     if (*i & 0x80) {
271         PUT_32BIT(d, len+1);
272         d[4] = 0;
273         memcpy(d+5, data, len);
274         return len+5;
275     } else {
276         PUT_32BIT(d, len);
277         memcpy(d+4, data, len);
278         return len+4;
279     }
280 }
281
282 /* Simple structure to point to an mp-int within a blob. */
283 struct mpint_pos { void *start; int bytes; };
284
285 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
286 {
287     int bytes;
288     unsigned char *d = (unsigned char *) data;
289
290     if (len < 4)
291         goto error;
292     bytes = toint(GET_32BIT(d));
293     if (bytes < 0 || len-4 < bytes)
294         goto error;
295
296     ret->start = d + 4;
297     ret->bytes = bytes;
298     return bytes+4;
299
300     error:
301     ret->start = NULL;
302     ret->bytes = -1;
303     return len;                        /* ensure further calls fail as well */
304 }
305
306 /* ----------------------------------------------------------------------
307  * Code to read and write OpenSSH private keys.
308  */
309
310 enum { OSSH_DSA, OSSH_RSA };
311 enum { OSSH_ENC_3DES, OSSH_ENC_AES };
312 struct openssh_key {
313     int type;
314     int encrypted, encryption;
315     char iv[32];
316     unsigned char *keyblob;
317     int keyblob_len, keyblob_size;
318 };
319
320 static struct openssh_key *load_openssh_key(const Filename *filename,
321                                             const char **errmsg_p)
322 {
323     struct openssh_key *ret;
324     FILE *fp = NULL;
325     char *line = NULL;
326     char *errmsg, *p;
327     int headers_done;
328     char base64_bit[4];
329     int base64_chars = 0;
330
331     ret = snew(struct openssh_key);
332     ret->keyblob = NULL;
333     ret->keyblob_len = ret->keyblob_size = 0;
334     ret->encrypted = 0;
335     memset(ret->iv, 0, sizeof(ret->iv));
336
337     fp = f_open(filename, "r", FALSE);
338     if (!fp) {
339         errmsg = "unable to open key file";
340         goto error;
341     }
342
343     if (!(line = fgetline(fp))) {
344         errmsg = "unexpected end of file";
345         goto error;
346     }
347     strip_crlf(line);
348     if (0 != strncmp(line, "-----BEGIN ", 11) ||
349         0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
350         errmsg = "file does not begin with OpenSSH key header";
351         goto error;
352     }
353     if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----"))
354         ret->type = OSSH_RSA;
355     else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----"))
356         ret->type = OSSH_DSA;
357     else {
358         errmsg = "unrecognised key type";
359         goto error;
360     }
361     smemclr(line, strlen(line));
362     sfree(line);
363     line = NULL;
364
365     headers_done = 0;
366     while (1) {
367         if (!(line = fgetline(fp))) {
368             errmsg = "unexpected end of file";
369             goto error;
370         }
371         strip_crlf(line);
372         if (0 == strncmp(line, "-----END ", 9) &&
373             0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
374             sfree(line);
375             line = NULL;
376             break;                     /* done */
377         }
378         if ((p = strchr(line, ':')) != NULL) {
379             if (headers_done) {
380                 errmsg = "header found in body of key data";
381                 goto error;
382             }
383             *p++ = '\0';
384             while (*p && isspace((unsigned char)*p)) p++;
385             if (!strcmp(line, "Proc-Type")) {
386                 if (p[0] != '4' || p[1] != ',') {
387                     errmsg = "Proc-Type is not 4 (only 4 is supported)";
388                     goto error;
389                 }
390                 p += 2;
391                 if (!strcmp(p, "ENCRYPTED"))
392                     ret->encrypted = 1;
393             } else if (!strcmp(line, "DEK-Info")) {
394                 int i, j, ivlen;
395
396                 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
397                     ret->encryption = OSSH_ENC_3DES;
398                     ivlen = 8;
399                 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
400                     ret->encryption = OSSH_ENC_AES;
401                     ivlen = 16;
402                 } else {
403                     errmsg = "unsupported cipher";
404                     goto error;
405                 }
406                 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
407                 for (i = 0; i < ivlen; i++) {
408                     if (1 != sscanf(p, "%2x", &j)) {
409                         errmsg = "expected more iv data in DEK-Info";
410                         goto error;
411                     }
412                     ret->iv[i] = j;
413                     p += 2;
414                 }
415                 if (*p) {
416                     errmsg = "more iv data than expected in DEK-Info";
417                     goto error;
418                 }
419             }
420         } else {
421             headers_done = 1;
422
423             p = line;
424             while (isbase64(*p)) {
425                 base64_bit[base64_chars++] = *p;
426                 if (base64_chars == 4) {
427                     unsigned char out[3];
428                     int len;
429
430                     base64_chars = 0;
431
432                     len = base64_decode_atom(base64_bit, out);
433
434                     if (len <= 0) {
435                         errmsg = "invalid base64 encoding";
436                         goto error;
437                     }
438
439                     if (ret->keyblob_len + len > ret->keyblob_size) {
440                         ret->keyblob_size = ret->keyblob_len + len + 256;
441                         ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
442                                                unsigned char);
443                     }
444
445                     memcpy(ret->keyblob + ret->keyblob_len, out, len);
446                     ret->keyblob_len += len;
447
448                     smemclr(out, sizeof(out));
449                 }
450
451                 p++;
452             }
453         }
454         smemclr(line, strlen(line));
455         sfree(line);
456         line = NULL;
457     }
458
459     fclose(fp);
460     fp = NULL;
461
462     if (ret->keyblob_len == 0 || !ret->keyblob) {
463         errmsg = "key body not present";
464         goto error;
465     }
466
467     if (ret->encrypted && ret->keyblob_len % 8 != 0) {
468         errmsg = "encrypted key blob is not a multiple of cipher block size";
469         goto error;
470     }
471
472     smemclr(base64_bit, sizeof(base64_bit));
473     if (errmsg_p) *errmsg_p = NULL;
474     return ret;
475
476     error:
477     if (line) {
478         smemclr(line, strlen(line));
479         sfree(line);
480         line = NULL;
481     }
482     smemclr(base64_bit, sizeof(base64_bit));
483     if (ret) {
484         if (ret->keyblob) {
485             smemclr(ret->keyblob, ret->keyblob_size);
486             sfree(ret->keyblob);
487         }
488         smemclr(ret, sizeof(*ret));
489         sfree(ret);
490     }
491     if (errmsg_p) *errmsg_p = errmsg;
492     if (fp) fclose(fp);
493     return NULL;
494 }
495
496 int openssh_encrypted(const Filename *filename)
497 {
498     struct openssh_key *key = load_openssh_key(filename, NULL);
499     int ret;
500
501     if (!key)
502         return 0;
503     ret = key->encrypted;
504     smemclr(key->keyblob, key->keyblob_size);
505     sfree(key->keyblob);
506     smemclr(key, sizeof(*key));
507     sfree(key);
508     return ret;
509 }
510
511 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
512                                   const char **errmsg_p)
513 {
514     struct openssh_key *key = load_openssh_key(filename, errmsg_p);
515     struct ssh2_userkey *retkey;
516     unsigned char *p;
517     int ret, id, len, flags;
518     int i, num_integers;
519     struct ssh2_userkey *retval = NULL;
520     char *errmsg;
521     unsigned char *blob;
522     int blobsize = 0, blobptr, privptr;
523     char *modptr = NULL;
524     int modlen = 0;
525
526     blob = NULL;
527
528     if (!key)
529         return NULL;
530
531     if (key->encrypted) {
532         /*
533          * Derive encryption key from passphrase and iv/salt:
534          * 
535          *  - let block A equal MD5(passphrase || iv)
536          *  - let block B equal MD5(A || passphrase || iv)
537          *  - block C would be MD5(B || passphrase || iv) and so on
538          *  - encryption key is the first N bytes of A || B
539          *
540          * (Note that only 8 bytes of the iv are used for key
541          * derivation, even when the key is encrypted with AES and
542          * hence there are 16 bytes available.)
543          */
544         struct MD5Context md5c;
545         unsigned char keybuf[32];
546
547         MD5Init(&md5c);
548         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
549         MD5Update(&md5c, (unsigned char *)key->iv, 8);
550         MD5Final(keybuf, &md5c);
551
552         MD5Init(&md5c);
553         MD5Update(&md5c, keybuf, 16);
554         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
555         MD5Update(&md5c, (unsigned char *)key->iv, 8);
556         MD5Final(keybuf+16, &md5c);
557
558         /*
559          * Now decrypt the key blob.
560          */
561         if (key->encryption == OSSH_ENC_3DES)
562             des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
563                                      key->keyblob, key->keyblob_len);
564         else {
565             void *ctx;
566             assert(key->encryption == OSSH_ENC_AES);
567             ctx = aes_make_context();
568             aes128_key(ctx, keybuf);
569             aes_iv(ctx, (unsigned char *)key->iv);
570             aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
571             aes_free_context(ctx);
572         }
573
574         smemclr(&md5c, sizeof(md5c));
575         smemclr(keybuf, sizeof(keybuf));
576     }
577
578     /*
579      * Now we have a decrypted key blob, which contains an ASN.1
580      * encoded private key. We must now untangle the ASN.1.
581      *
582      * We expect the whole key blob to be formatted as a SEQUENCE
583      * (0x30 followed by a length code indicating that the rest of
584      * the blob is part of the sequence). Within that SEQUENCE we
585      * expect to see a bunch of INTEGERs. What those integers mean
586      * depends on the key type:
587      *
588      *  - For RSA, we expect the integers to be 0, n, e, d, p, q,
589      *    dmp1, dmq1, iqmp in that order. (The last three are d mod
590      *    (p-1), d mod (q-1), inverse of q mod p respectively.)
591      *
592      *  - For DSA, we expect them to be 0, p, q, g, y, x in that
593      *    order.
594      */
595     
596     p = key->keyblob;
597
598     /* Expect the SEQUENCE header. Take its absence as a failure to
599      * decrypt, if the key was encrypted. */
600     ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
601     p += ret;
602     if (ret < 0 || id != 16) {
603         errmsg = "ASN.1 decoding failure";
604         retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
605         goto error;
606     }
607
608     /* Expect a load of INTEGERs. */
609     if (key->type == OSSH_RSA)
610         num_integers = 9;
611     else if (key->type == OSSH_DSA)
612         num_integers = 6;
613     else
614         num_integers = 0;              /* placate compiler warnings */
615
616     if (key->type == OSSH_RSA || key->type == OSSH_DSA) {
617         /*
618          * Space to create key blob in.
619          */
620         blobsize = 256+key->keyblob_len;
621         blob = snewn(blobsize, unsigned char);
622         PUT_32BIT(blob, 7);
623         if (key->type == OSSH_DSA)
624             memcpy(blob+4, "ssh-dss", 7);
625         else if (key->type == OSSH_RSA)
626             memcpy(blob+4, "ssh-rsa", 7);
627         blobptr = 4+7;
628         privptr = -1;
629
630         for (i = 0; i < num_integers; i++) {
631             ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
632                                   &id, &len, &flags);
633             p += ret;
634             if (ret < 0 || id != 2 ||
635                 key->keyblob+key->keyblob_len-p < len) {
636                 errmsg = "ASN.1 decoding failure";
637                 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
638                 goto error;
639             }
640
641             if (i == 0) {
642                 /*
643                  * The first integer should be zero always (I think
644                  * this is some sort of version indication).
645                  */
646                 if (len != 1 || p[0] != 0) {
647                     errmsg = "version number mismatch";
648                     goto error;
649                 }
650             } else if (key->type == OSSH_RSA) {
651                 /*
652                  * Integers 1 and 2 go into the public blob but in the
653                  * opposite order; integers 3, 4, 5 and 8 go into the
654                  * private blob. The other two (6 and 7) are ignored.
655                  */
656                 if (i == 1) {
657                     /* Save the details for after we deal with number 2. */
658                     modptr = (char *)p;
659                     modlen = len;
660                 } else if (i != 6 && i != 7) {
661                     PUT_32BIT(blob+blobptr, len);
662                     memcpy(blob+blobptr+4, p, len);
663                     blobptr += 4+len;
664                     if (i == 2) {
665                         PUT_32BIT(blob+blobptr, modlen);
666                         memcpy(blob+blobptr+4, modptr, modlen);
667                         blobptr += 4+modlen;
668                         privptr = blobptr;
669                     }
670                 }
671             } else if (key->type == OSSH_DSA) {
672                 /*
673                  * Integers 1-4 go into the public blob; integer 5 goes
674                  * into the private blob.
675                  */
676                 PUT_32BIT(blob+blobptr, len);
677                 memcpy(blob+blobptr+4, p, len);
678                 blobptr += 4+len;
679                 if (i == 4)
680                     privptr = blobptr;
681             }
682
683             /* Skip past the number. */
684             p += len;
685         }
686
687         /*
688          * Now put together the actual key. Simplest way to do this is
689          * to assemble our own key blobs and feed them to the createkey
690          * functions; this is a bit faffy but it does mean we get all
691          * the sanity checks for free.
692          */
693         assert(privptr > 0);          /* should have bombed by now if not */
694         retkey = snew(struct ssh2_userkey);
695         retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
696         retkey->data = retkey->alg->createkey(blob, privptr,
697                                               blob+privptr, blobptr-privptr);
698         if (!retkey->data) {
699             sfree(retkey);
700             errmsg = "unable to create key data structure";
701             goto error;
702         }
703
704     } else {
705         assert(0 && "Bad key type from load_openssh_key");
706     }
707
708     retkey->comment = dupstr("imported-openssh-key");
709     errmsg = NULL;                     /* no error */
710     retval = retkey;
711
712     error:
713     if (blob) {
714         smemclr(blob, blobsize);
715         sfree(blob);
716     }
717     smemclr(key->keyblob, key->keyblob_size);
718     sfree(key->keyblob);
719     smemclr(key, sizeof(*key));
720     sfree(key);
721     if (errmsg_p) *errmsg_p = errmsg;
722     return retval;
723 }
724
725 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
726                   char *passphrase)
727 {
728     unsigned char *pubblob, *privblob, *spareblob;
729     int publen, privlen, sparelen = 0;
730     unsigned char *outblob;
731     int outlen;
732     struct mpint_pos numbers[9];
733     int nnumbers, pos, len, seqlen, i;
734     char *header, *footer;
735     char zero[1];
736     unsigned char iv[8];
737     int ret = 0;
738     FILE *fp;
739
740     /*
741      * Fetch the key blobs.
742      */
743     pubblob = key->alg->public_blob(key->data, &publen);
744     privblob = key->alg->private_blob(key->data, &privlen);
745     spareblob = outblob = NULL;
746
747     outblob = NULL;
748     len = 0;
749
750     /*
751      * Encode the OpenSSH key blob, and also decide on the header
752      * line.
753      */
754     if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
755         /*
756          * The RSA and DSS handlers share some code because the two
757          * key types have very similar ASN.1 representations, as a
758          * plain SEQUENCE of big integers. So we set up a list of
759          * bignums per key type and then construct the actual blob in
760          * common code after that.
761          */
762         if (key->alg == &ssh_rsa) {
763             int pos;
764             struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
765             Bignum bd, bp, bq, bdmp1, bdmq1;
766
767             /*
768              * These blobs were generated from inside PuTTY, so we needn't
769              * treat them as untrusted.
770              */
771             pos = 4 + GET_32BIT(pubblob);
772             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
773             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
774             pos = 0;
775             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
776             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
777             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
778             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
779
780             assert(e.start && iqmp.start); /* can't go wrong */
781
782             /* We also need d mod (p-1) and d mod (q-1). */
783             bd = bignum_from_bytes(d.start, d.bytes);
784             bp = bignum_from_bytes(p.start, p.bytes);
785             bq = bignum_from_bytes(q.start, q.bytes);
786             decbn(bp);
787             decbn(bq);
788             bdmp1 = bigmod(bd, bp);
789             bdmq1 = bigmod(bd, bq);
790             freebn(bd);
791             freebn(bp);
792             freebn(bq);
793
794             dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
795             dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
796             sparelen = dmp1.bytes + dmq1.bytes;
797             spareblob = snewn(sparelen, unsigned char);
798             dmp1.start = spareblob;
799             dmq1.start = spareblob + dmp1.bytes;
800             for (i = 0; i < dmp1.bytes; i++)
801                 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
802             for (i = 0; i < dmq1.bytes; i++)
803                 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
804             freebn(bdmp1);
805             freebn(bdmq1);
806
807             numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
808             numbers[1] = n;
809             numbers[2] = e;
810             numbers[3] = d;
811             numbers[4] = p;
812             numbers[5] = q;
813             numbers[6] = dmp1;
814             numbers[7] = dmq1;
815             numbers[8] = iqmp;
816
817             nnumbers = 9;
818             header = "-----BEGIN RSA PRIVATE KEY-----\n";
819             footer = "-----END RSA PRIVATE KEY-----\n";
820         } else {                       /* ssh-dss */
821             int pos;
822             struct mpint_pos p, q, g, y, x;
823
824             /*
825              * These blobs were generated from inside PuTTY, so we needn't
826              * treat them as untrusted.
827              */
828             pos = 4 + GET_32BIT(pubblob);
829             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
830             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
831             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
832             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
833             pos = 0;
834             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
835
836             assert(y.start && x.start); /* can't go wrong */
837
838             numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
839             numbers[1] = p;
840             numbers[2] = q;
841             numbers[3] = g;
842             numbers[4] = y;
843             numbers[5] = x;
844
845             nnumbers = 6;
846             header = "-----BEGIN DSA PRIVATE KEY-----\n";
847             footer = "-----END DSA PRIVATE KEY-----\n";
848         }
849
850         /*
851          * Now count up the total size of the ASN.1 encoded integers,
852          * so as to determine the length of the containing SEQUENCE.
853          */
854         len = 0;
855         for (i = 0; i < nnumbers; i++) {
856             len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
857             len += numbers[i].bytes;
858         }
859         seqlen = len;
860         /* Now add on the SEQUENCE header. */
861         len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
862
863         /*
864          * Now we know how big outblob needs to be. Allocate it.
865          */
866         outblob = snewn(len, unsigned char);
867
868         /*
869          * And write the data into it.
870          */
871         pos = 0;
872         pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
873         for (i = 0; i < nnumbers; i++) {
874             pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
875             memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
876             pos += numbers[i].bytes;
877         }
878     } else {
879         assert(0);                     /* zoinks! */
880         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
881     }
882
883     /*
884      * Encrypt the key.
885      *
886      * For the moment, we still encrypt our OpenSSH keys using
887      * old-style 3DES.
888      */
889     if (passphrase) {
890         struct MD5Context md5c;
891         unsigned char keybuf[32];
892
893         /*
894          * Round up to the cipher block size, ensuring we have at
895          * least one byte of padding (see below).
896          */
897         outlen = (len+8) &~ 7;
898         {
899             unsigned char *tmp = snewn(outlen, unsigned char);
900             memcpy(tmp, outblob, len);
901             smemclr(outblob, len);
902             sfree(outblob);
903             outblob = tmp;
904         }
905
906         /*
907          * Padding on OpenSSH keys is deterministic. The number of
908          * padding bytes is always more than zero, and always at most
909          * the cipher block length. The value of each padding byte is
910          * equal to the number of padding bytes. So a plaintext that's
911          * an exact multiple of the block size will be padded with 08
912          * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
913          * plaintext one byte less than a multiple of the block size
914          * will be padded with just 01.
915          *
916          * This enables the OpenSSL key decryption function to strip
917          * off the padding algorithmically and return the unpadded
918          * plaintext to the next layer: it looks at the final byte, and
919          * then expects to find that many bytes at the end of the data
920          * with the same value. Those are all removed and the rest is
921          * returned.
922          */
923         assert(pos == len);
924         while (pos < outlen) {
925             outblob[pos++] = outlen - len;
926         }
927
928         /*
929          * Invent an iv. Then derive encryption key from passphrase
930          * and iv/salt:
931          * 
932          *  - let block A equal MD5(passphrase || iv)
933          *  - let block B equal MD5(A || passphrase || iv)
934          *  - block C would be MD5(B || passphrase || iv) and so on
935          *  - encryption key is the first N bytes of A || B
936          */
937         for (i = 0; i < 8; i++) iv[i] = random_byte();
938
939         MD5Init(&md5c);
940         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
941         MD5Update(&md5c, iv, 8);
942         MD5Final(keybuf, &md5c);
943
944         MD5Init(&md5c);
945         MD5Update(&md5c, keybuf, 16);
946         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
947         MD5Update(&md5c, iv, 8);
948         MD5Final(keybuf+16, &md5c);
949
950         /*
951          * Now encrypt the key blob.
952          */
953         des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
954
955         smemclr(&md5c, sizeof(md5c));
956         smemclr(keybuf, sizeof(keybuf));
957     } else {
958         /*
959          * If no encryption, the blob has exactly its original
960          * cleartext size.
961          */
962         outlen = len;
963     }
964
965     /*
966      * And save it. We'll use Unix line endings just in case it's
967      * subsequently transferred in binary mode.
968      */
969     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
970     if (!fp)
971         goto error;
972     fputs(header, fp);
973     if (passphrase) {
974         fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
975         for (i = 0; i < 8; i++)
976             fprintf(fp, "%02X", iv[i]);
977         fprintf(fp, "\n\n");
978     }
979     base64_encode(fp, outblob, outlen, 64);
980     fputs(footer, fp);
981     fclose(fp);
982     ret = 1;
983
984     error:
985     if (outblob) {
986         smemclr(outblob, outlen);
987         sfree(outblob);
988     }
989     if (spareblob) {
990         smemclr(spareblob, sparelen);
991         sfree(spareblob);
992     }
993     if (privblob) {
994         smemclr(privblob, privlen);
995         sfree(privblob);
996     }
997     if (pubblob) {
998         smemclr(pubblob, publen);
999         sfree(pubblob);
1000     }
1001     return ret;
1002 }
1003
1004 /* ----------------------------------------------------------------------
1005  * Code to read ssh.com private keys.
1006  */
1007
1008 /*
1009  * The format of the base64 blob is largely SSH-2-packet-formatted,
1010  * except that mpints are a bit different: they're more like the
1011  * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1012  * (N+7)/8 bytes of data.
1013  * 
1014  * So. The blob contains:
1015  * 
1016  *  - uint32 0x3f6ff9eb       (magic number)
1017  *  - uint32 size             (total blob size)
1018  *  - string key-type         (see below)
1019  *  - string cipher-type      (tells you if key is encrypted)
1020  *  - string encrypted-blob
1021  * 
1022  * (The first size field includes the size field itself and the
1023  * magic number before it. All other size fields are ordinary SSH-2
1024  * strings, so the size field indicates how much data is to
1025  * _follow_.)
1026  * 
1027  * The encrypted blob, once decrypted, contains a single string
1028  * which in turn contains the payload. (This allows padding to be
1029  * added after that string while still making it clear where the
1030  * real payload ends. Also it probably makes for a reasonable
1031  * decryption check.)
1032  * 
1033  * The payload blob, for an RSA key, contains:
1034  *  - mpint e
1035  *  - mpint d
1036  *  - mpint n  (yes, the public and private stuff is intermixed)
1037  *  - mpint u  (presumably inverse of p mod q)
1038  *  - mpint p  (p is the smaller prime)
1039  *  - mpint q  (q is the larger)
1040  * 
1041  * For a DSA key, the payload blob contains:
1042  *  - uint32 0
1043  *  - mpint p
1044  *  - mpint g
1045  *  - mpint q
1046  *  - mpint y
1047  *  - mpint x
1048  * 
1049  * Alternatively, if the parameters are `predefined', that
1050  * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1051  * containing some predefined parameter specification. *shudder*,
1052  * but I doubt we'll encounter this in real life.
1053  * 
1054  * The key type strings are ghastly. The RSA key I looked at had a
1055  * type string of
1056  * 
1057  *   `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1058  * 
1059  * and the DSA key wasn't much better:
1060  * 
1061  *   `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1062  * 
1063  * It isn't clear that these will always be the same. I think it
1064  * might be wise just to look at the `if-modn{sign{rsa' and
1065  * `dl-modp{sign{dsa' prefixes.
1066  * 
1067  * Finally, the encryption. The cipher-type string appears to be
1068  * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1069  * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1070  * from the passphrase by means of yet another hashing faff:
1071  * 
1072  *  - first 16 bytes are MD5(passphrase)
1073  *  - next 16 bytes are MD5(passphrase || first 16 bytes)
1074  *  - if there were more, they'd be MD5(passphrase || first 32),
1075  *    and so on.
1076  */
1077
1078 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1079
1080 struct sshcom_key {
1081     char comment[256];                 /* allowing any length is overkill */
1082     unsigned char *keyblob;
1083     int keyblob_len, keyblob_size;
1084 };
1085
1086 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1087                                           const char **errmsg_p)
1088 {
1089     struct sshcom_key *ret;
1090     FILE *fp;
1091     char *line = NULL;
1092     int hdrstart, len;
1093     char *errmsg, *p;
1094     int headers_done;
1095     char base64_bit[4];
1096     int base64_chars = 0;
1097
1098     ret = snew(struct sshcom_key);
1099     ret->comment[0] = '\0';
1100     ret->keyblob = NULL;
1101     ret->keyblob_len = ret->keyblob_size = 0;
1102
1103     fp = f_open(filename, "r", FALSE);
1104     if (!fp) {
1105         errmsg = "unable to open key file";
1106         goto error;
1107     }
1108     if (!(line = fgetline(fp))) {
1109         errmsg = "unexpected end of file";
1110         goto error;
1111     }
1112     strip_crlf(line);
1113     if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1114         errmsg = "file does not begin with ssh.com key header";
1115         goto error;
1116     }
1117     smemclr(line, strlen(line));
1118     sfree(line);
1119     line = NULL;
1120
1121     headers_done = 0;
1122     while (1) {
1123         if (!(line = fgetline(fp))) {
1124             errmsg = "unexpected end of file";
1125             goto error;
1126         }
1127         strip_crlf(line);
1128         if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1129             sfree(line);
1130             line = NULL;
1131             break;                     /* done */
1132         }
1133         if ((p = strchr(line, ':')) != NULL) {
1134             if (headers_done) {
1135                 errmsg = "header found in body of key data";
1136                 goto error;
1137             }
1138             *p++ = '\0';
1139             while (*p && isspace((unsigned char)*p)) p++;
1140             hdrstart = p - line;
1141
1142             /*
1143              * Header lines can end in a trailing backslash for
1144              * continuation.
1145              */
1146             len = hdrstart + strlen(line+hdrstart);
1147             assert(!line[len]);
1148             while (line[len-1] == '\\') {
1149                 char *line2;
1150                 int line2len;
1151
1152                 line2 = fgetline(fp);
1153                 if (!line2) {
1154                     errmsg = "unexpected end of file";
1155                     goto error;
1156                 }
1157                 strip_crlf(line2);
1158
1159                 line2len = strlen(line2);
1160                 line = sresize(line, len + line2len + 1, char);
1161                 strcpy(line + len - 1, line2);
1162                 len += line2len - 1;
1163                 assert(!line[len]);
1164
1165                 smemclr(line2, strlen(line2));
1166                 sfree(line2);
1167                 line2 = NULL;
1168             }
1169             p = line + hdrstart;
1170             strip_crlf(p);
1171             if (!strcmp(line, "Comment")) {
1172                 /* Strip quotes in comment if present. */
1173                 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1174                     p++;
1175                     p[strlen(p)-1] = '\0';
1176                 }
1177                 strncpy(ret->comment, p, sizeof(ret->comment));
1178                 ret->comment[sizeof(ret->comment)-1] = '\0';
1179             }
1180         } else {
1181             headers_done = 1;
1182
1183             p = line;
1184             while (isbase64(*p)) {
1185                 base64_bit[base64_chars++] = *p;
1186                 if (base64_chars == 4) {
1187                     unsigned char out[3];
1188
1189                     base64_chars = 0;
1190
1191                     len = base64_decode_atom(base64_bit, out);
1192
1193                     if (len <= 0) {
1194                         errmsg = "invalid base64 encoding";
1195                         goto error;
1196                     }
1197
1198                     if (ret->keyblob_len + len > ret->keyblob_size) {
1199                         ret->keyblob_size = ret->keyblob_len + len + 256;
1200                         ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1201                                                unsigned char);
1202                     }
1203
1204                     memcpy(ret->keyblob + ret->keyblob_len, out, len);
1205                     ret->keyblob_len += len;
1206                 }
1207
1208                 p++;
1209             }
1210         }
1211         smemclr(line, strlen(line));
1212         sfree(line);
1213         line = NULL;
1214     }
1215
1216     if (ret->keyblob_len == 0 || !ret->keyblob) {
1217         errmsg = "key body not present";
1218         goto error;
1219     }
1220
1221     fclose(fp);
1222     if (errmsg_p) *errmsg_p = NULL;
1223     return ret;
1224
1225     error:
1226     if (fp)
1227         fclose(fp);
1228
1229     if (line) {
1230         smemclr(line, strlen(line));
1231         sfree(line);
1232         line = NULL;
1233     }
1234     if (ret) {
1235         if (ret->keyblob) {
1236             smemclr(ret->keyblob, ret->keyblob_size);
1237             sfree(ret->keyblob);
1238         }
1239         smemclr(ret, sizeof(*ret));
1240         sfree(ret);
1241     }
1242     if (errmsg_p) *errmsg_p = errmsg;
1243     return NULL;
1244 }
1245
1246 int sshcom_encrypted(const Filename *filename, char **comment)
1247 {
1248     struct sshcom_key *key = load_sshcom_key(filename, NULL);
1249     int pos, len, answer;
1250
1251     answer = 0;
1252
1253     *comment = NULL;
1254     if (!key)
1255         goto done;
1256
1257     /*
1258      * Check magic number.
1259      */
1260     if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1261         goto done;                     /* key is invalid */
1262     }
1263
1264     /*
1265      * Find the cipher-type string.
1266      */
1267     pos = 8;
1268     if (key->keyblob_len < pos+4)
1269         goto done;                     /* key is far too short */
1270     len = toint(GET_32BIT(key->keyblob + pos));
1271     if (len < 0 || len > key->keyblob_len - pos - 4)
1272         goto done;                     /* key is far too short */
1273     pos += 4 + len;                    /* skip key type */
1274     len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1275     if (len < 0 || len > key->keyblob_len - pos - 4)
1276         goto done;                     /* cipher type string is incomplete */
1277     if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1278         answer = 1;
1279
1280     done:
1281     if (key) {
1282         *comment = dupstr(key->comment);
1283         smemclr(key->keyblob, key->keyblob_size);
1284         sfree(key->keyblob);
1285         smemclr(key, sizeof(*key));
1286         sfree(key);
1287     } else {
1288         *comment = dupstr("");
1289     }
1290     return answer;
1291 }
1292
1293 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1294 {
1295     unsigned bits, bytes;
1296     unsigned char *d = (unsigned char *) data;
1297
1298     if (len < 4)
1299         goto error;
1300     bits = GET_32BIT(d);
1301
1302     bytes = (bits + 7) / 8;
1303     if (len < 4+bytes)
1304         goto error;
1305
1306     ret->start = d + 4;
1307     ret->bytes = bytes;
1308     return bytes+4;
1309
1310     error:
1311     ret->start = NULL;
1312     ret->bytes = -1;
1313     return len;                        /* ensure further calls fail as well */
1314 }
1315
1316 static int sshcom_put_mpint(void *target, void *data, int len)
1317 {
1318     unsigned char *d = (unsigned char *)target;
1319     unsigned char *i = (unsigned char *)data;
1320     int bits = len * 8 - 1;
1321
1322     while (bits > 0) {
1323         if (*i & (1 << (bits & 7)))
1324             break;
1325         if (!(bits-- & 7))
1326             i++, len--;
1327     }
1328
1329     PUT_32BIT(d, bits+1);
1330     memcpy(d+4, i, len);
1331     return len+4;
1332 }
1333
1334 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1335                                  const char **errmsg_p)
1336 {
1337     struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1338     char *errmsg;
1339     int pos, len;
1340     const char prefix_rsa[] = "if-modn{sign{rsa";
1341     const char prefix_dsa[] = "dl-modp{sign{dsa";
1342     enum { RSA, DSA } type;
1343     int encrypted;
1344     char *ciphertext;
1345     int cipherlen;
1346     struct ssh2_userkey *ret = NULL, *retkey;
1347     const struct ssh_signkey *alg;
1348     unsigned char *blob = NULL;
1349     int blobsize = 0, publen, privlen;
1350
1351     if (!key)
1352         return NULL;
1353
1354     /*
1355      * Check magic number.
1356      */
1357     if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1358         errmsg = "key does not begin with magic number";
1359         goto error;
1360     }
1361
1362     /*
1363      * Determine the key type.
1364      */
1365     pos = 8;
1366     if (key->keyblob_len < pos+4 ||
1367         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1368         len > key->keyblob_len - pos - 4) {
1369         errmsg = "key blob does not contain a key type string";
1370         goto error;
1371     }
1372     if (len > sizeof(prefix_rsa) - 1 &&
1373         !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1374         type = RSA;
1375     } else if (len > sizeof(prefix_dsa) - 1 &&
1376         !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1377         type = DSA;
1378     } else {
1379         errmsg = "key is of unknown type";
1380         goto error;
1381     }
1382     pos += 4+len;
1383
1384     /*
1385      * Determine the cipher type.
1386      */
1387     if (key->keyblob_len < pos+4 ||
1388         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1389         len > key->keyblob_len - pos - 4) {
1390         errmsg = "key blob does not contain a cipher type string";
1391         goto error;
1392     }
1393     if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1394         encrypted = 0;
1395     else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1396         encrypted = 1;
1397     else {
1398         errmsg = "key encryption is of unknown type";
1399         goto error;
1400     }
1401     pos += 4+len;
1402
1403     /*
1404      * Get hold of the encrypted part of the key.
1405      */
1406     if (key->keyblob_len < pos+4 ||
1407         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1408         len > key->keyblob_len - pos - 4) {
1409         errmsg = "key blob does not contain actual key data";
1410         goto error;
1411     }
1412     ciphertext = (char *)key->keyblob + pos + 4;
1413     cipherlen = len;
1414     if (cipherlen == 0) {
1415         errmsg = "length of key data is zero";
1416         goto error;
1417     }
1418
1419     /*
1420      * Decrypt it if necessary.
1421      */
1422     if (encrypted) {
1423         /*
1424          * Derive encryption key from passphrase and iv/salt:
1425          * 
1426          *  - let block A equal MD5(passphrase)
1427          *  - let block B equal MD5(passphrase || A)
1428          *  - block C would be MD5(passphrase || A || B) and so on
1429          *  - encryption key is the first N bytes of A || B
1430          */
1431         struct MD5Context md5c;
1432         unsigned char keybuf[32], iv[8];
1433
1434         if (cipherlen % 8 != 0) {
1435             errmsg = "encrypted part of key is not a multiple of cipher block"
1436                 " size";
1437             goto error;
1438         }
1439
1440         MD5Init(&md5c);
1441         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1442         MD5Final(keybuf, &md5c);
1443
1444         MD5Init(&md5c);
1445         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1446         MD5Update(&md5c, keybuf, 16);
1447         MD5Final(keybuf+16, &md5c);
1448
1449         /*
1450          * Now decrypt the key blob.
1451          */
1452         memset(iv, 0, sizeof(iv));
1453         des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1454                                  cipherlen);
1455
1456         smemclr(&md5c, sizeof(md5c));
1457         smemclr(keybuf, sizeof(keybuf));
1458
1459         /*
1460          * Hereafter we return WRONG_PASSPHRASE for any parsing
1461          * error. (But only if we've just tried to decrypt it!
1462          * Returning WRONG_PASSPHRASE for an unencrypted key is
1463          * automatic doom.)
1464          */
1465         if (encrypted)
1466             ret = SSH2_WRONG_PASSPHRASE;
1467     }
1468
1469     /*
1470      * Strip away the containing string to get to the real meat.
1471      */
1472     len = toint(GET_32BIT(ciphertext));
1473     if (len < 0 || len > cipherlen-4) {
1474         errmsg = "containing string was ill-formed";
1475         goto error;
1476     }
1477     ciphertext += 4;
1478     cipherlen = len;
1479
1480     /*
1481      * Now we break down into RSA versus DSA. In either case we'll
1482      * construct public and private blobs in our own format, and
1483      * end up feeding them to alg->createkey().
1484      */
1485     blobsize = cipherlen + 256;
1486     blob = snewn(blobsize, unsigned char);
1487     privlen = 0;
1488     if (type == RSA) {
1489         struct mpint_pos n, e, d, u, p, q;
1490         int pos = 0;
1491         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1492         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1493         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1494         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1495         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1496         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1497         if (!q.start) {
1498             errmsg = "key data did not contain six integers";
1499             goto error;
1500         }
1501
1502         alg = &ssh_rsa;
1503         pos = 0;
1504         pos += put_string(blob+pos, "ssh-rsa", 7);
1505         pos += put_mp(blob+pos, e.start, e.bytes);
1506         pos += put_mp(blob+pos, n.start, n.bytes);
1507         publen = pos;
1508         pos += put_string(blob+pos, d.start, d.bytes);
1509         pos += put_mp(blob+pos, q.start, q.bytes);
1510         pos += put_mp(blob+pos, p.start, p.bytes);
1511         pos += put_mp(blob+pos, u.start, u.bytes);
1512         privlen = pos - publen;
1513     } else {
1514         struct mpint_pos p, q, g, x, y;
1515         int pos = 4;
1516
1517         assert(type == DSA); /* the only other option from the if above */
1518
1519         if (GET_32BIT(ciphertext) != 0) {
1520             errmsg = "predefined DSA parameters not supported";
1521             goto error;
1522         }
1523         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1524         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1525         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1526         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1527         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1528         if (!x.start) {
1529             errmsg = "key data did not contain five integers";
1530             goto error;
1531         }
1532
1533         alg = &ssh_dss;
1534         pos = 0;
1535         pos += put_string(blob+pos, "ssh-dss", 7);
1536         pos += put_mp(blob+pos, p.start, p.bytes);
1537         pos += put_mp(blob+pos, q.start, q.bytes);
1538         pos += put_mp(blob+pos, g.start, g.bytes);
1539         pos += put_mp(blob+pos, y.start, y.bytes);
1540         publen = pos;
1541         pos += put_mp(blob+pos, x.start, x.bytes);
1542         privlen = pos - publen;
1543     }
1544
1545     assert(privlen > 0);               /* should have bombed by now if not */
1546
1547     retkey = snew(struct ssh2_userkey);
1548     retkey->alg = alg;
1549     retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1550     if (!retkey->data) {
1551         sfree(retkey);
1552         errmsg = "unable to create key data structure";
1553         goto error;
1554     }
1555     retkey->comment = dupstr(key->comment);
1556
1557     errmsg = NULL; /* no error */
1558     ret = retkey;
1559
1560     error:
1561     if (blob) {
1562         smemclr(blob, blobsize);
1563         sfree(blob);
1564     }
1565     smemclr(key->keyblob, key->keyblob_size);
1566     sfree(key->keyblob);
1567     smemclr(key, sizeof(*key));
1568     sfree(key);
1569     if (errmsg_p) *errmsg_p = errmsg;
1570     return ret;
1571 }
1572
1573 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1574                  char *passphrase)
1575 {
1576     unsigned char *pubblob, *privblob;
1577     int publen, privlen;
1578     unsigned char *outblob;
1579     int outlen;
1580     struct mpint_pos numbers[6];
1581     int nnumbers, initial_zero, pos, lenpos, i;
1582     char *type;
1583     char *ciphertext;
1584     int cipherlen;
1585     int ret = 0;
1586     FILE *fp;
1587
1588     /*
1589      * Fetch the key blobs.
1590      */
1591     pubblob = key->alg->public_blob(key->data, &publen);
1592     privblob = key->alg->private_blob(key->data, &privlen);
1593     outblob = NULL;
1594
1595     /*
1596      * Find the sequence of integers to be encoded into the OpenSSH
1597      * key blob, and also decide on the header line.
1598      */
1599     if (key->alg == &ssh_rsa) {
1600         int pos;
1601         struct mpint_pos n, e, d, p, q, iqmp;
1602
1603         /*
1604          * These blobs were generated from inside PuTTY, so we needn't
1605          * treat them as untrusted.
1606          */
1607         pos = 4 + GET_32BIT(pubblob);
1608         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1609         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1610         pos = 0;
1611         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1612         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1613         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1614         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1615
1616         assert(e.start && iqmp.start); /* can't go wrong */
1617
1618         numbers[0] = e;
1619         numbers[1] = d;
1620         numbers[2] = n;
1621         numbers[3] = iqmp;
1622         numbers[4] = q;
1623         numbers[5] = p;
1624
1625         nnumbers = 6;
1626         initial_zero = 0;
1627         type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1628     } else if (key->alg == &ssh_dss) {
1629         int pos;
1630         struct mpint_pos p, q, g, y, x;
1631
1632         /*
1633          * These blobs were generated from inside PuTTY, so we needn't
1634          * treat them as untrusted.
1635          */
1636         pos = 4 + GET_32BIT(pubblob);
1637         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1638         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1639         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1640         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1641         pos = 0;
1642         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1643
1644         assert(y.start && x.start); /* can't go wrong */
1645
1646         numbers[0] = p;
1647         numbers[1] = g;
1648         numbers[2] = q;
1649         numbers[3] = y;
1650         numbers[4] = x;
1651
1652         nnumbers = 5;
1653         initial_zero = 1;
1654         type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1655     } else {
1656         assert(0);                     /* zoinks! */
1657         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1658     }
1659
1660     /*
1661      * Total size of key blob will be somewhere under 512 plus
1662      * combined length of integers. We'll calculate the more
1663      * precise size as we construct the blob.
1664      */
1665     outlen = 512;
1666     for (i = 0; i < nnumbers; i++)
1667         outlen += 4 + numbers[i].bytes;
1668     outblob = snewn(outlen, unsigned char);
1669
1670     /*
1671      * Create the unencrypted key blob.
1672      */
1673     pos = 0;
1674     PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1675     pos += 4;                          /* length field, fill in later */
1676     pos += put_string(outblob+pos, type, strlen(type));
1677     {
1678         char *ciphertype = passphrase ? "3des-cbc" : "none";
1679         pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1680     }
1681     lenpos = pos;                      /* remember this position */
1682     pos += 4;                          /* encrypted-blob size */
1683     pos += 4;                          /* encrypted-payload size */
1684     if (initial_zero) {
1685         PUT_32BIT(outblob+pos, 0);
1686         pos += 4;
1687     }
1688     for (i = 0; i < nnumbers; i++)
1689         pos += sshcom_put_mpint(outblob+pos,
1690                                 numbers[i].start, numbers[i].bytes);
1691     /* Now wrap up the encrypted payload. */
1692     PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1693     /* Pad encrypted blob to a multiple of cipher block size. */
1694     if (passphrase) {
1695         int padding = -(pos - (lenpos+4)) & 7;
1696         while (padding--)
1697             outblob[pos++] = random_byte();
1698     }
1699     ciphertext = (char *)outblob+lenpos+4;
1700     cipherlen = pos - (lenpos+4);
1701     assert(!passphrase || cipherlen % 8 == 0);
1702     /* Wrap up the encrypted blob string. */
1703     PUT_32BIT(outblob+lenpos, cipherlen);
1704     /* And finally fill in the total length field. */
1705     PUT_32BIT(outblob+4, pos);
1706
1707     assert(pos < outlen);
1708
1709     /*
1710      * Encrypt the key.
1711      */
1712     if (passphrase) {
1713         /*
1714          * Derive encryption key from passphrase and iv/salt:
1715          * 
1716          *  - let block A equal MD5(passphrase)
1717          *  - let block B equal MD5(passphrase || A)
1718          *  - block C would be MD5(passphrase || A || B) and so on
1719          *  - encryption key is the first N bytes of A || B
1720          */
1721         struct MD5Context md5c;
1722         unsigned char keybuf[32], iv[8];
1723
1724         MD5Init(&md5c);
1725         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1726         MD5Final(keybuf, &md5c);
1727
1728         MD5Init(&md5c);
1729         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1730         MD5Update(&md5c, keybuf, 16);
1731         MD5Final(keybuf+16, &md5c);
1732
1733         /*
1734          * Now decrypt the key blob.
1735          */
1736         memset(iv, 0, sizeof(iv));
1737         des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1738                                  cipherlen);
1739
1740         smemclr(&md5c, sizeof(md5c));
1741         smemclr(keybuf, sizeof(keybuf));
1742     }
1743
1744     /*
1745      * And save it. We'll use Unix line endings just in case it's
1746      * subsequently transferred in binary mode.
1747      */
1748     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
1749     if (!fp)
1750         goto error;
1751     fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1752     fprintf(fp, "Comment: \"");
1753     /*
1754      * Comment header is broken with backslash-newline if it goes
1755      * over 70 chars. Although it's surrounded by quotes, it
1756      * _doesn't_ escape backslashes or quotes within the string.
1757      * Don't ask me, I didn't design it.
1758      */
1759     {
1760         int slen = 60;                 /* starts at 60 due to "Comment: " */
1761         char *c = key->comment;
1762         while ((int)strlen(c) > slen) {
1763             fprintf(fp, "%.*s\\\n", slen, c);
1764             c += slen;
1765             slen = 70;                 /* allow 70 chars on subsequent lines */
1766         }
1767         fprintf(fp, "%s\"\n", c);
1768     }
1769     base64_encode(fp, outblob, pos, 70);
1770     fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1771     fclose(fp);
1772     ret = 1;
1773
1774     error:
1775     if (outblob) {
1776         smemclr(outblob, outlen);
1777         sfree(outblob);
1778     }
1779     if (privblob) {
1780         smemclr(privblob, privlen);
1781         sfree(privblob);
1782     }
1783     if (pubblob) {
1784         smemclr(pubblob, publen);
1785         sfree(pubblob);
1786     }
1787     return ret;
1788 }