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