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