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