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