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