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