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