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