]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - import.c
Another two mis-fixes from r9919: when we sfree(line) on exit from the
[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     /*
617      * Space to create key blob in.
618      */
619     blobsize = 256+key->keyblob_len;
620     blob = snewn(blobsize, unsigned char);
621     PUT_32BIT(blob, 7);
622     if (key->type == OSSH_DSA)
623         memcpy(blob+4, "ssh-dss", 7);
624     else if (key->type == OSSH_RSA)
625         memcpy(blob+4, "ssh-rsa", 7);
626     blobptr = 4+7;
627     privptr = -1;
628
629     for (i = 0; i < num_integers; i++) {
630         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
631                               &id, &len, &flags);
632         p += ret;
633         if (ret < 0 || id != 2 ||
634             key->keyblob+key->keyblob_len-p < len) {
635             errmsg = "ASN.1 decoding failure";
636             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
637             goto error;
638         }
639
640         if (i == 0) {
641             /*
642              * The first integer should be zero always (I think
643              * this is some sort of version indication).
644              */
645             if (len != 1 || p[0] != 0) {
646                 errmsg = "version number mismatch";
647                 goto error;
648             }
649         } else if (key->type == OSSH_RSA) {
650             /*
651              * Integers 1 and 2 go into the public blob but in the
652              * opposite order; integers 3, 4, 5 and 8 go into the
653              * private blob. The other two (6 and 7) are ignored.
654              */
655             if (i == 1) {
656                 /* Save the details for after we deal with number 2. */
657                 modptr = (char *)p;
658                 modlen = len;
659             } else if (i != 6 && i != 7) {
660                 PUT_32BIT(blob+blobptr, len);
661                 memcpy(blob+blobptr+4, p, len);
662                 blobptr += 4+len;
663                 if (i == 2) {
664                     PUT_32BIT(blob+blobptr, modlen);
665                     memcpy(blob+blobptr+4, modptr, modlen);
666                     blobptr += 4+modlen;
667                     privptr = blobptr;
668                 }
669             }
670         } else if (key->type == OSSH_DSA) {
671             /*
672              * Integers 1-4 go into the public blob; integer 5 goes
673              * into the private blob.
674              */
675             PUT_32BIT(blob+blobptr, len);
676             memcpy(blob+blobptr+4, p, len);
677             blobptr += 4+len;
678             if (i == 4)
679                 privptr = blobptr;
680         }
681
682         /* Skip past the number. */
683         p += len;
684     }
685
686     /*
687      * Now put together the actual key. Simplest way to do this is
688      * to assemble our own key blobs and feed them to the createkey
689      * functions; this is a bit faffy but it does mean we get all
690      * the sanity checks for free.
691      */
692     assert(privptr > 0);               /* should have bombed by now if not */
693     retkey = snew(struct ssh2_userkey);
694     retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
695     retkey->data = retkey->alg->createkey(blob, privptr,
696                                           blob+privptr, blobptr-privptr);
697     if (!retkey->data) {
698         sfree(retkey);
699         errmsg = "unable to create key data structure";
700         goto error;
701     }
702
703     retkey->comment = dupstr("imported-openssh-key");
704     errmsg = NULL;                     /* no error */
705     retval = retkey;
706
707     error:
708     if (blob) {
709         smemclr(blob, blobsize);
710         sfree(blob);
711     }
712     smemclr(key->keyblob, key->keyblob_size);
713     sfree(key->keyblob);
714     smemclr(key, sizeof(*key));
715     sfree(key);
716     if (errmsg_p) *errmsg_p = errmsg;
717     return retval;
718 }
719
720 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
721                   char *passphrase)
722 {
723     unsigned char *pubblob, *privblob, *spareblob;
724     int publen, privlen, sparelen = 0;
725     unsigned char *outblob;
726     int outlen;
727     struct mpint_pos numbers[9];
728     int nnumbers, pos, len, seqlen, i;
729     char *header, *footer;
730     char zero[1];
731     unsigned char iv[8];
732     int ret = 0;
733     FILE *fp;
734
735     /*
736      * Fetch the key blobs.
737      */
738     pubblob = key->alg->public_blob(key->data, &publen);
739     privblob = key->alg->private_blob(key->data, &privlen);
740     spareblob = outblob = NULL;
741
742     /*
743      * Find the sequence of integers to be encoded into the OpenSSH
744      * key blob, and also decide on the header line.
745      */
746     if (key->alg == &ssh_rsa) {
747         int pos;
748         struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
749         Bignum bd, bp, bq, bdmp1, bdmq1;
750
751         /*
752          * These blobs were generated from inside PuTTY, so we needn't
753          * treat them as untrusted.
754          */
755         pos = 4 + GET_32BIT(pubblob);
756         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
757         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
758         pos = 0;
759         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
760         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
761         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
762         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
763
764         assert(e.start && iqmp.start); /* can't go wrong */
765
766         /* We also need d mod (p-1) and d mod (q-1). */
767         bd = bignum_from_bytes(d.start, d.bytes);
768         bp = bignum_from_bytes(p.start, p.bytes);
769         bq = bignum_from_bytes(q.start, q.bytes);
770         decbn(bp);
771         decbn(bq);
772         bdmp1 = bigmod(bd, bp);
773         bdmq1 = bigmod(bd, bq);
774         freebn(bd);
775         freebn(bp);
776         freebn(bq);
777
778         dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
779         dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
780         sparelen = dmp1.bytes + dmq1.bytes;
781         spareblob = snewn(sparelen, unsigned char);
782         dmp1.start = spareblob;
783         dmq1.start = spareblob + dmp1.bytes;
784         for (i = 0; i < dmp1.bytes; i++)
785             spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
786         for (i = 0; i < dmq1.bytes; i++)
787             spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
788         freebn(bdmp1);
789         freebn(bdmq1);
790
791         numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
792         numbers[1] = n;
793         numbers[2] = e;
794         numbers[3] = d;
795         numbers[4] = p;
796         numbers[5] = q;
797         numbers[6] = dmp1;
798         numbers[7] = dmq1;
799         numbers[8] = iqmp;
800
801         nnumbers = 9;
802         header = "-----BEGIN RSA PRIVATE KEY-----\n";
803         footer = "-----END RSA PRIVATE KEY-----\n";
804     } else if (key->alg == &ssh_dss) {
805         int pos;
806         struct mpint_pos p, q, g, y, x;
807
808         /*
809          * These blobs were generated from inside PuTTY, so we needn't
810          * treat them as untrusted.
811          */
812         pos = 4 + GET_32BIT(pubblob);
813         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
814         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
815         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
816         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
817         pos = 0;
818         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
819
820         assert(y.start && x.start); /* can't go wrong */
821
822         numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0'; 
823         numbers[1] = p;
824         numbers[2] = q;
825         numbers[3] = g;
826         numbers[4] = y;
827         numbers[5] = x;
828
829         nnumbers = 6;
830         header = "-----BEGIN DSA PRIVATE KEY-----\n";
831         footer = "-----END DSA PRIVATE KEY-----\n";
832     } else {
833         assert(0);                     /* zoinks! */
834         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
835     }
836
837     /*
838      * Now count up the total size of the ASN.1 encoded integers,
839      * so as to determine the length of the containing SEQUENCE.
840      */
841     len = 0;
842     for (i = 0; i < nnumbers; i++) {
843         len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
844         len += numbers[i].bytes;
845     }
846     seqlen = len;
847     /* Now add on the SEQUENCE header. */
848     len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
849     /* Round up to the cipher block size, ensuring we have at least one
850      * byte of padding (see below). */
851     outlen = len;
852     if (passphrase)
853         outlen = (outlen+8) &~ 7;
854
855     /*
856      * Now we know how big outblob needs to be. Allocate it.
857      */
858     outblob = snewn(outlen, unsigned char);
859
860     /*
861      * And write the data into it.
862      */
863     pos = 0;
864     pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
865     for (i = 0; i < nnumbers; i++) {
866         pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
867         memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
868         pos += numbers[i].bytes;
869     }
870
871     /*
872      * Padding on OpenSSH keys is deterministic. The number of
873      * padding bytes is always more than zero, and always at most
874      * the cipher block length. The value of each padding byte is
875      * equal to the number of padding bytes. So a plaintext that's
876      * an exact multiple of the block size will be padded with 08
877      * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
878      * plaintext one byte less than a multiple of the block size
879      * will be padded with just 01.
880      * 
881      * This enables the OpenSSL key decryption function to strip
882      * off the padding algorithmically and return the unpadded
883      * plaintext to the next layer: it looks at the final byte, and
884      * then expects to find that many bytes at the end of the data
885      * with the same value. Those are all removed and the rest is
886      * returned.
887      */
888     assert(pos == len);
889     while (pos < outlen) {
890         outblob[pos++] = outlen - len;
891     }
892
893     /*
894      * Encrypt the key.
895      *
896      * For the moment, we still encrypt our OpenSSH keys using
897      * old-style 3DES.
898      */
899     if (passphrase) {
900         /*
901          * Invent an iv. Then derive encryption key from passphrase
902          * and iv/salt:
903          * 
904          *  - let block A equal MD5(passphrase || iv)
905          *  - let block B equal MD5(A || passphrase || iv)
906          *  - block C would be MD5(B || passphrase || iv) and so on
907          *  - encryption key is the first N bytes of A || B
908          */
909         struct MD5Context md5c;
910         unsigned char keybuf[32];
911
912         for (i = 0; i < 8; i++) iv[i] = random_byte();
913
914         MD5Init(&md5c);
915         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
916         MD5Update(&md5c, iv, 8);
917         MD5Final(keybuf, &md5c);
918
919         MD5Init(&md5c);
920         MD5Update(&md5c, keybuf, 16);
921         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
922         MD5Update(&md5c, iv, 8);
923         MD5Final(keybuf+16, &md5c);
924
925         /*
926          * Now encrypt the key blob.
927          */
928         des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
929
930         smemclr(&md5c, sizeof(md5c));
931         smemclr(keybuf, sizeof(keybuf));
932     }
933
934     /*
935      * And save it. We'll use Unix line endings just in case it's
936      * subsequently transferred in binary mode.
937      */
938     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
939     if (!fp)
940         goto error;
941     fputs(header, fp);
942     if (passphrase) {
943         fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
944         for (i = 0; i < 8; i++)
945             fprintf(fp, "%02X", iv[i]);
946         fprintf(fp, "\n\n");
947     }
948     base64_encode(fp, outblob, outlen, 64);
949     fputs(footer, fp);
950     fclose(fp);
951     ret = 1;
952
953     error:
954     if (outblob) {
955         smemclr(outblob, outlen);
956         sfree(outblob);
957     }
958     if (spareblob) {
959         smemclr(spareblob, sparelen);
960         sfree(spareblob);
961     }
962     if (privblob) {
963         smemclr(privblob, privlen);
964         sfree(privblob);
965     }
966     if (pubblob) {
967         smemclr(pubblob, publen);
968         sfree(pubblob);
969     }
970     return ret;
971 }
972
973 /* ----------------------------------------------------------------------
974  * Code to read ssh.com private keys.
975  */
976
977 /*
978  * The format of the base64 blob is largely SSH-2-packet-formatted,
979  * except that mpints are a bit different: they're more like the
980  * old SSH-1 mpint. You have a 32-bit bit count N, followed by
981  * (N+7)/8 bytes of data.
982  * 
983  * So. The blob contains:
984  * 
985  *  - uint32 0x3f6ff9eb       (magic number)
986  *  - uint32 size             (total blob size)
987  *  - string key-type         (see below)
988  *  - string cipher-type      (tells you if key is encrypted)
989  *  - string encrypted-blob
990  * 
991  * (The first size field includes the size field itself and the
992  * magic number before it. All other size fields are ordinary SSH-2
993  * strings, so the size field indicates how much data is to
994  * _follow_.)
995  * 
996  * The encrypted blob, once decrypted, contains a single string
997  * which in turn contains the payload. (This allows padding to be
998  * added after that string while still making it clear where the
999  * real payload ends. Also it probably makes for a reasonable
1000  * decryption check.)
1001  * 
1002  * The payload blob, for an RSA key, contains:
1003  *  - mpint e
1004  *  - mpint d
1005  *  - mpint n  (yes, the public and private stuff is intermixed)
1006  *  - mpint u  (presumably inverse of p mod q)
1007  *  - mpint p  (p is the smaller prime)
1008  *  - mpint q  (q is the larger)
1009  * 
1010  * For a DSA key, the payload blob contains:
1011  *  - uint32 0
1012  *  - mpint p
1013  *  - mpint g
1014  *  - mpint q
1015  *  - mpint y
1016  *  - mpint x
1017  * 
1018  * Alternatively, if the parameters are `predefined', that
1019  * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1020  * containing some predefined parameter specification. *shudder*,
1021  * but I doubt we'll encounter this in real life.
1022  * 
1023  * The key type strings are ghastly. The RSA key I looked at had a
1024  * type string of
1025  * 
1026  *   `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1027  * 
1028  * and the DSA key wasn't much better:
1029  * 
1030  *   `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1031  * 
1032  * It isn't clear that these will always be the same. I think it
1033  * might be wise just to look at the `if-modn{sign{rsa' and
1034  * `dl-modp{sign{dsa' prefixes.
1035  * 
1036  * Finally, the encryption. The cipher-type string appears to be
1037  * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1038  * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1039  * from the passphrase by means of yet another hashing faff:
1040  * 
1041  *  - first 16 bytes are MD5(passphrase)
1042  *  - next 16 bytes are MD5(passphrase || first 16 bytes)
1043  *  - if there were more, they'd be MD5(passphrase || first 32),
1044  *    and so on.
1045  */
1046
1047 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1048
1049 struct sshcom_key {
1050     char comment[256];                 /* allowing any length is overkill */
1051     unsigned char *keyblob;
1052     int keyblob_len, keyblob_size;
1053 };
1054
1055 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1056                                           const char **errmsg_p)
1057 {
1058     struct sshcom_key *ret;
1059     FILE *fp;
1060     char *line = NULL;
1061     int hdrstart, len;
1062     char *errmsg, *p;
1063     int headers_done;
1064     char base64_bit[4];
1065     int base64_chars = 0;
1066
1067     ret = snew(struct sshcom_key);
1068     ret->comment[0] = '\0';
1069     ret->keyblob = NULL;
1070     ret->keyblob_len = ret->keyblob_size = 0;
1071
1072     fp = f_open(filename, "r", FALSE);
1073     if (!fp) {
1074         errmsg = "unable to open key file";
1075         goto error;
1076     }
1077     if (!(line = fgetline(fp))) {
1078         errmsg = "unexpected end of file";
1079         goto error;
1080     }
1081     strip_crlf(line);
1082     if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1083         errmsg = "file does not begin with ssh.com key header";
1084         goto error;
1085     }
1086     smemclr(line, strlen(line));
1087     sfree(line);
1088     line = NULL;
1089
1090     headers_done = 0;
1091     while (1) {
1092         if (!(line = fgetline(fp))) {
1093             errmsg = "unexpected end of file";
1094             goto error;
1095         }
1096         strip_crlf(line);
1097         if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1098             sfree(line);
1099             line = NULL;
1100             break;                     /* done */
1101         }
1102         if ((p = strchr(line, ':')) != NULL) {
1103             if (headers_done) {
1104                 errmsg = "header found in body of key data";
1105                 goto error;
1106             }
1107             *p++ = '\0';
1108             while (*p && isspace((unsigned char)*p)) p++;
1109             hdrstart = p - line;
1110
1111             /*
1112              * Header lines can end in a trailing backslash for
1113              * continuation.
1114              */
1115             len = hdrstart + strlen(line+hdrstart);
1116             assert(!line[len]);
1117             while (line[len-1] == '\\') {
1118                 char *line2;
1119                 int line2len;
1120
1121                 line2 = fgetline(fp);
1122                 if (!line2) {
1123                     errmsg = "unexpected end of file";
1124                     goto error;
1125                 }
1126                 strip_crlf(line2);
1127
1128                 line2len = strlen(line2);
1129                 line = sresize(line, len + line2len + 1, char);
1130                 strcpy(line + len - 1, line2);
1131                 len += line2len - 1;
1132                 assert(!line[len]);
1133
1134                 smemclr(line2, strlen(line2));
1135                 sfree(line2);
1136                 line2 = NULL;
1137             }
1138             p = line + hdrstart;
1139             strip_crlf(p);
1140             if (!strcmp(line, "Comment")) {
1141                 /* Strip quotes in comment if present. */
1142                 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1143                     p++;
1144                     p[strlen(p)-1] = '\0';
1145                 }
1146                 strncpy(ret->comment, p, sizeof(ret->comment));
1147                 ret->comment[sizeof(ret->comment)-1] = '\0';
1148             }
1149         } else {
1150             headers_done = 1;
1151
1152             p = line;
1153             while (isbase64(*p)) {
1154                 base64_bit[base64_chars++] = *p;
1155                 if (base64_chars == 4) {
1156                     unsigned char out[3];
1157
1158                     base64_chars = 0;
1159
1160                     len = base64_decode_atom(base64_bit, out);
1161
1162                     if (len <= 0) {
1163                         errmsg = "invalid base64 encoding";
1164                         goto error;
1165                     }
1166
1167                     if (ret->keyblob_len + len > ret->keyblob_size) {
1168                         ret->keyblob_size = ret->keyblob_len + len + 256;
1169                         ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1170                                                unsigned char);
1171                     }
1172
1173                     memcpy(ret->keyblob + ret->keyblob_len, out, len);
1174                     ret->keyblob_len += len;
1175                 }
1176
1177                 p++;
1178             }
1179         }
1180         smemclr(line, strlen(line));
1181         sfree(line);
1182         line = NULL;
1183     }
1184
1185     if (ret->keyblob_len == 0 || !ret->keyblob) {
1186         errmsg = "key body not present";
1187         goto error;
1188     }
1189
1190     fclose(fp);
1191     if (errmsg_p) *errmsg_p = NULL;
1192     return ret;
1193
1194     error:
1195     if (fp)
1196         fclose(fp);
1197
1198     if (line) {
1199         smemclr(line, strlen(line));
1200         sfree(line);
1201         line = NULL;
1202     }
1203     if (ret) {
1204         if (ret->keyblob) {
1205             smemclr(ret->keyblob, ret->keyblob_size);
1206             sfree(ret->keyblob);
1207         }
1208         smemclr(ret, sizeof(*ret));
1209         sfree(ret);
1210     }
1211     if (errmsg_p) *errmsg_p = errmsg;
1212     return NULL;
1213 }
1214
1215 int sshcom_encrypted(const Filename *filename, char **comment)
1216 {
1217     struct sshcom_key *key = load_sshcom_key(filename, NULL);
1218     int pos, len, answer;
1219
1220     answer = 0;
1221
1222     *comment = NULL;
1223     if (!key)
1224         goto done;
1225
1226     /*
1227      * Check magic number.
1228      */
1229     if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1230         goto done;                     /* key is invalid */
1231     }
1232
1233     /*
1234      * Find the cipher-type string.
1235      */
1236     pos = 8;
1237     if (key->keyblob_len < pos+4)
1238         goto done;                     /* key is far too short */
1239     len = toint(GET_32BIT(key->keyblob + pos));
1240     if (len < 0 || len > key->keyblob_len - pos - 4)
1241         goto done;                     /* key is far too short */
1242     pos += 4 + len;                    /* skip key type */
1243     len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1244     if (len < 0 || len > key->keyblob_len - pos - 4)
1245         goto done;                     /* cipher type string is incomplete */
1246     if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1247         answer = 1;
1248
1249     done:
1250     *comment = dupstr(key ? key->comment : "");
1251     smemclr(key->keyblob, key->keyblob_size);
1252     sfree(key->keyblob);
1253     smemclr(key, sizeof(*key));
1254     sfree(key);
1255     return answer;
1256 }
1257
1258 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1259 {
1260     unsigned bits, bytes;
1261     unsigned char *d = (unsigned char *) data;
1262
1263     if (len < 4)
1264         goto error;
1265     bits = GET_32BIT(d);
1266
1267     bytes = (bits + 7) / 8;
1268     if (len < 4+bytes)
1269         goto error;
1270
1271     ret->start = d + 4;
1272     ret->bytes = bytes;
1273     return bytes+4;
1274
1275     error:
1276     ret->start = NULL;
1277     ret->bytes = -1;
1278     return len;                        /* ensure further calls fail as well */
1279 }
1280
1281 static int sshcom_put_mpint(void *target, void *data, int len)
1282 {
1283     unsigned char *d = (unsigned char *)target;
1284     unsigned char *i = (unsigned char *)data;
1285     int bits = len * 8 - 1;
1286
1287     while (bits > 0) {
1288         if (*i & (1 << (bits & 7)))
1289             break;
1290         if (!(bits-- & 7))
1291             i++, len--;
1292     }
1293
1294     PUT_32BIT(d, bits+1);
1295     memcpy(d+4, i, len);
1296     return len+4;
1297 }
1298
1299 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1300                                  const char **errmsg_p)
1301 {
1302     struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1303     char *errmsg;
1304     int pos, len;
1305     const char prefix_rsa[] = "if-modn{sign{rsa";
1306     const char prefix_dsa[] = "dl-modp{sign{dsa";
1307     enum { RSA, DSA } type;
1308     int encrypted;
1309     char *ciphertext;
1310     int cipherlen;
1311     struct ssh2_userkey *ret = NULL, *retkey;
1312     const struct ssh_signkey *alg;
1313     unsigned char *blob = NULL;
1314     int blobsize = 0, publen, privlen;
1315
1316     if (!key)
1317         return NULL;
1318
1319     /*
1320      * Check magic number.
1321      */
1322     if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1323         errmsg = "key does not begin with magic number";
1324         goto error;
1325     }
1326
1327     /*
1328      * Determine the key type.
1329      */
1330     pos = 8;
1331     if (key->keyblob_len < pos+4 ||
1332         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1333         len > key->keyblob_len - pos - 4) {
1334         errmsg = "key blob does not contain a key type string";
1335         goto error;
1336     }
1337     if (len > sizeof(prefix_rsa) - 1 &&
1338         !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1339         type = RSA;
1340     } else if (len > sizeof(prefix_dsa) - 1 &&
1341         !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1342         type = DSA;
1343     } else {
1344         errmsg = "key is of unknown type";
1345         goto error;
1346     }
1347     pos += 4+len;
1348
1349     /*
1350      * Determine the cipher type.
1351      */
1352     if (key->keyblob_len < pos+4 ||
1353         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1354         len > key->keyblob_len - pos - 4) {
1355         errmsg = "key blob does not contain a cipher type string";
1356         goto error;
1357     }
1358     if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1359         encrypted = 0;
1360     else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1361         encrypted = 1;
1362     else {
1363         errmsg = "key encryption is of unknown type";
1364         goto error;
1365     }
1366     pos += 4+len;
1367
1368     /*
1369      * Get hold of the encrypted part of the key.
1370      */
1371     if (key->keyblob_len < pos+4 ||
1372         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1373         len > key->keyblob_len - pos - 4) {
1374         errmsg = "key blob does not contain actual key data";
1375         goto error;
1376     }
1377     ciphertext = (char *)key->keyblob + pos + 4;
1378     cipherlen = len;
1379     if (cipherlen == 0) {
1380         errmsg = "length of key data is zero";
1381         goto error;
1382     }
1383
1384     /*
1385      * Decrypt it if necessary.
1386      */
1387     if (encrypted) {
1388         /*
1389          * Derive encryption key from passphrase and iv/salt:
1390          * 
1391          *  - let block A equal MD5(passphrase)
1392          *  - let block B equal MD5(passphrase || A)
1393          *  - block C would be MD5(passphrase || A || B) and so on
1394          *  - encryption key is the first N bytes of A || B
1395          */
1396         struct MD5Context md5c;
1397         unsigned char keybuf[32], iv[8];
1398
1399         if (cipherlen % 8 != 0) {
1400             errmsg = "encrypted part of key is not a multiple of cipher block"
1401                 " size";
1402             goto error;
1403         }
1404
1405         MD5Init(&md5c);
1406         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1407         MD5Final(keybuf, &md5c);
1408
1409         MD5Init(&md5c);
1410         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1411         MD5Update(&md5c, keybuf, 16);
1412         MD5Final(keybuf+16, &md5c);
1413
1414         /*
1415          * Now decrypt the key blob.
1416          */
1417         memset(iv, 0, sizeof(iv));
1418         des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1419                                  cipherlen);
1420
1421         smemclr(&md5c, sizeof(md5c));
1422         smemclr(keybuf, sizeof(keybuf));
1423
1424         /*
1425          * Hereafter we return WRONG_PASSPHRASE for any parsing
1426          * error. (But only if we've just tried to decrypt it!
1427          * Returning WRONG_PASSPHRASE for an unencrypted key is
1428          * automatic doom.)
1429          */
1430         if (encrypted)
1431             ret = SSH2_WRONG_PASSPHRASE;
1432     }
1433
1434     /*
1435      * Strip away the containing string to get to the real meat.
1436      */
1437     len = toint(GET_32BIT(ciphertext));
1438     if (len < 0 || len > cipherlen-4) {
1439         errmsg = "containing string was ill-formed";
1440         goto error;
1441     }
1442     ciphertext += 4;
1443     cipherlen = len;
1444
1445     /*
1446      * Now we break down into RSA versus DSA. In either case we'll
1447      * construct public and private blobs in our own format, and
1448      * end up feeding them to alg->createkey().
1449      */
1450     blobsize = cipherlen + 256;
1451     blob = snewn(blobsize, unsigned char);
1452     privlen = 0;
1453     if (type == RSA) {
1454         struct mpint_pos n, e, d, u, p, q;
1455         int pos = 0;
1456         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1457         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1458         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1459         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1460         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1461         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1462         if (!q.start) {
1463             errmsg = "key data did not contain six integers";
1464             goto error;
1465         }
1466
1467         alg = &ssh_rsa;
1468         pos = 0;
1469         pos += put_string(blob+pos, "ssh-rsa", 7);
1470         pos += put_mp(blob+pos, e.start, e.bytes);
1471         pos += put_mp(blob+pos, n.start, n.bytes);
1472         publen = pos;
1473         pos += put_string(blob+pos, d.start, d.bytes);
1474         pos += put_mp(blob+pos, q.start, q.bytes);
1475         pos += put_mp(blob+pos, p.start, p.bytes);
1476         pos += put_mp(blob+pos, u.start, u.bytes);
1477         privlen = pos - publen;
1478     } else {
1479         struct mpint_pos p, q, g, x, y;
1480         int pos = 4;
1481
1482         assert(type == DSA); /* the only other option from the if above */
1483
1484         if (GET_32BIT(ciphertext) != 0) {
1485             errmsg = "predefined DSA parameters not supported";
1486             goto error;
1487         }
1488         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1489         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1490         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1491         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1492         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1493         if (!x.start) {
1494             errmsg = "key data did not contain five integers";
1495             goto error;
1496         }
1497
1498         alg = &ssh_dss;
1499         pos = 0;
1500         pos += put_string(blob+pos, "ssh-dss", 7);
1501         pos += put_mp(blob+pos, p.start, p.bytes);
1502         pos += put_mp(blob+pos, q.start, q.bytes);
1503         pos += put_mp(blob+pos, g.start, g.bytes);
1504         pos += put_mp(blob+pos, y.start, y.bytes);
1505         publen = pos;
1506         pos += put_mp(blob+pos, x.start, x.bytes);
1507         privlen = pos - publen;
1508     }
1509
1510     assert(privlen > 0);               /* should have bombed by now if not */
1511
1512     retkey = snew(struct ssh2_userkey);
1513     retkey->alg = alg;
1514     retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1515     if (!retkey->data) {
1516         sfree(retkey);
1517         errmsg = "unable to create key data structure";
1518         goto error;
1519     }
1520     retkey->comment = dupstr(key->comment);
1521
1522     errmsg = NULL; /* no error */
1523     ret = retkey;
1524
1525     error:
1526     if (blob) {
1527         smemclr(blob, blobsize);
1528         sfree(blob);
1529     }
1530     smemclr(key->keyblob, key->keyblob_size);
1531     sfree(key->keyblob);
1532     smemclr(key, sizeof(*key));
1533     sfree(key);
1534     if (errmsg_p) *errmsg_p = errmsg;
1535     return ret;
1536 }
1537
1538 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1539                  char *passphrase)
1540 {
1541     unsigned char *pubblob, *privblob;
1542     int publen, privlen;
1543     unsigned char *outblob;
1544     int outlen;
1545     struct mpint_pos numbers[6];
1546     int nnumbers, initial_zero, pos, lenpos, i;
1547     char *type;
1548     char *ciphertext;
1549     int cipherlen;
1550     int ret = 0;
1551     FILE *fp;
1552
1553     /*
1554      * Fetch the key blobs.
1555      */
1556     pubblob = key->alg->public_blob(key->data, &publen);
1557     privblob = key->alg->private_blob(key->data, &privlen);
1558     outblob = NULL;
1559
1560     /*
1561      * Find the sequence of integers to be encoded into the OpenSSH
1562      * key blob, and also decide on the header line.
1563      */
1564     if (key->alg == &ssh_rsa) {
1565         int pos;
1566         struct mpint_pos n, e, d, p, q, iqmp;
1567
1568         /*
1569          * These blobs were generated from inside PuTTY, so we needn't
1570          * treat them as untrusted.
1571          */
1572         pos = 4 + GET_32BIT(pubblob);
1573         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1574         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1575         pos = 0;
1576         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1577         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1578         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1579         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1580
1581         assert(e.start && iqmp.start); /* can't go wrong */
1582
1583         numbers[0] = e;
1584         numbers[1] = d;
1585         numbers[2] = n;
1586         numbers[3] = iqmp;
1587         numbers[4] = q;
1588         numbers[5] = p;
1589
1590         nnumbers = 6;
1591         initial_zero = 0;
1592         type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1593     } else if (key->alg == &ssh_dss) {
1594         int pos;
1595         struct mpint_pos p, q, g, y, x;
1596
1597         /*
1598          * These blobs were generated from inside PuTTY, so we needn't
1599          * treat them as untrusted.
1600          */
1601         pos = 4 + GET_32BIT(pubblob);
1602         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1603         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1604         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1605         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1606         pos = 0;
1607         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1608
1609         assert(y.start && x.start); /* can't go wrong */
1610
1611         numbers[0] = p;
1612         numbers[1] = g;
1613         numbers[2] = q;
1614         numbers[3] = y;
1615         numbers[4] = x;
1616
1617         nnumbers = 5;
1618         initial_zero = 1;
1619         type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1620     } else {
1621         assert(0);                     /* zoinks! */
1622         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1623     }
1624
1625     /*
1626      * Total size of key blob will be somewhere under 512 plus
1627      * combined length of integers. We'll calculate the more
1628      * precise size as we construct the blob.
1629      */
1630     outlen = 512;
1631     for (i = 0; i < nnumbers; i++)
1632         outlen += 4 + numbers[i].bytes;
1633     outblob = snewn(outlen, unsigned char);
1634
1635     /*
1636      * Create the unencrypted key blob.
1637      */
1638     pos = 0;
1639     PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1640     pos += 4;                          /* length field, fill in later */
1641     pos += put_string(outblob+pos, type, strlen(type));
1642     {
1643         char *ciphertype = passphrase ? "3des-cbc" : "none";
1644         pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1645     }
1646     lenpos = pos;                      /* remember this position */
1647     pos += 4;                          /* encrypted-blob size */
1648     pos += 4;                          /* encrypted-payload size */
1649     if (initial_zero) {
1650         PUT_32BIT(outblob+pos, 0);
1651         pos += 4;
1652     }
1653     for (i = 0; i < nnumbers; i++)
1654         pos += sshcom_put_mpint(outblob+pos,
1655                                 numbers[i].start, numbers[i].bytes);
1656     /* Now wrap up the encrypted payload. */
1657     PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1658     /* Pad encrypted blob to a multiple of cipher block size. */
1659     if (passphrase) {
1660         int padding = -(pos - (lenpos+4)) & 7;
1661         while (padding--)
1662             outblob[pos++] = random_byte();
1663     }
1664     ciphertext = (char *)outblob+lenpos+4;
1665     cipherlen = pos - (lenpos+4);
1666     assert(!passphrase || cipherlen % 8 == 0);
1667     /* Wrap up the encrypted blob string. */
1668     PUT_32BIT(outblob+lenpos, cipherlen);
1669     /* And finally fill in the total length field. */
1670     PUT_32BIT(outblob+4, pos);
1671
1672     assert(pos < outlen);
1673
1674     /*
1675      * Encrypt the key.
1676      */
1677     if (passphrase) {
1678         /*
1679          * Derive encryption key from passphrase and iv/salt:
1680          * 
1681          *  - let block A equal MD5(passphrase)
1682          *  - let block B equal MD5(passphrase || A)
1683          *  - block C would be MD5(passphrase || A || B) and so on
1684          *  - encryption key is the first N bytes of A || B
1685          */
1686         struct MD5Context md5c;
1687         unsigned char keybuf[32], iv[8];
1688
1689         MD5Init(&md5c);
1690         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1691         MD5Final(keybuf, &md5c);
1692
1693         MD5Init(&md5c);
1694         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1695         MD5Update(&md5c, keybuf, 16);
1696         MD5Final(keybuf+16, &md5c);
1697
1698         /*
1699          * Now decrypt the key blob.
1700          */
1701         memset(iv, 0, sizeof(iv));
1702         des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1703                                  cipherlen);
1704
1705         smemclr(&md5c, sizeof(md5c));
1706         smemclr(keybuf, sizeof(keybuf));
1707     }
1708
1709     /*
1710      * And save it. We'll use Unix line endings just in case it's
1711      * subsequently transferred in binary mode.
1712      */
1713     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
1714     if (!fp)
1715         goto error;
1716     fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1717     fprintf(fp, "Comment: \"");
1718     /*
1719      * Comment header is broken with backslash-newline if it goes
1720      * over 70 chars. Although it's surrounded by quotes, it
1721      * _doesn't_ escape backslashes or quotes within the string.
1722      * Don't ask me, I didn't design it.
1723      */
1724     {
1725         int slen = 60;                 /* starts at 60 due to "Comment: " */
1726         char *c = key->comment;
1727         while ((int)strlen(c) > slen) {
1728             fprintf(fp, "%.*s\\\n", slen, c);
1729             c += slen;
1730             slen = 70;                 /* allow 70 chars on subsequent lines */
1731         }
1732         fprintf(fp, "%s\"\n", c);
1733     }
1734     base64_encode(fp, outblob, pos, 70);
1735     fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1736     fclose(fp);
1737     ret = 1;
1738
1739     error:
1740     if (outblob) {
1741         smemclr(outblob, outlen);
1742         sfree(outblob);
1743     }
1744     if (privblob) {
1745         smemclr(privblob, privlen);
1746         sfree(privblob);
1747     }
1748     if (pubblob) {
1749         smemclr(pubblob, publen);
1750         sfree(pubblob);
1751     }
1752     return ret;
1753 }