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