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