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