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