]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - import.c
Sort out the mess with OpenSSH key file formats.
[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_pem_encrypted(const Filename *filename);
16 int openssh_new_encrypted(const Filename *filename);
17 struct ssh2_userkey *openssh_pem_read(const Filename *filename,
18                                       char *passphrase,
19                                       const char **errmsg_p);
20 struct ssh2_userkey *openssh_new_read(const Filename *filename,
21                                       char *passphrase,
22                                       const char **errmsg_p);
23 int openssh_auto_write(const Filename *filename, struct ssh2_userkey *key,
24                        char *passphrase);
25 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
26                       char *passphrase);
27 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
28                       char *passphrase);
29
30 int sshcom_encrypted(const Filename *filename, char **comment);
31 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
32                                  const char **errmsg_p);
33 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
34                  char *passphrase);
35
36 /*
37  * Given a key type, determine whether we know how to import it.
38  */
39 int import_possible(int type)
40 {
41     if (type == SSH_KEYTYPE_OPENSSH_PEM)
42         return 1;
43     if (type == SSH_KEYTYPE_OPENSSH_NEW)
44         return 1;
45     if (type == SSH_KEYTYPE_SSHCOM)
46         return 1;
47     return 0;
48 }
49
50 /*
51  * Given a key type, determine what native key type
52  * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
53  * we've imported it.
54  */
55 int import_target_type(int type)
56 {
57     /*
58      * There are no known foreign SSH-1 key formats.
59      */
60     return SSH_KEYTYPE_SSH2;
61 }
62
63 /*
64  * Determine whether a foreign key is encrypted.
65  */
66 int import_encrypted(const Filename *filename, int type, char **comment)
67 {
68     if (type == SSH_KEYTYPE_OPENSSH_PEM) {
69         /* OpenSSH PEM format doesn't contain a key comment at all */
70         *comment = dupstr(filename_to_str(filename));
71         return openssh_pem_encrypted(filename);
72     } else if (type == SSH_KEYTYPE_OPENSSH_NEW) {
73         /* OpenSSH new format does, but it's inside the encrypted
74          * section for some reason */
75         *comment = dupstr(filename_to_str(filename));
76         return openssh_new_encrypted(filename);
77     } else if (type == SSH_KEYTYPE_SSHCOM) {
78         return sshcom_encrypted(filename, comment);
79     }
80     return 0;
81 }
82
83 /*
84  * Import an SSH-1 key.
85  */
86 int import_ssh1(const Filename *filename, int type,
87                 struct RSAKey *key, char *passphrase, const char **errmsg_p)
88 {
89     return 0;
90 }
91
92 /*
93  * Import an SSH-2 key.
94  */
95 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
96                                  char *passphrase, const char **errmsg_p)
97 {
98     if (type == SSH_KEYTYPE_OPENSSH_PEM)
99         return openssh_pem_read(filename, passphrase, errmsg_p);
100     else if (type == SSH_KEYTYPE_OPENSSH_NEW)
101         return openssh_new_read(filename, passphrase, errmsg_p);
102     if (type == SSH_KEYTYPE_SSHCOM)
103         return sshcom_read(filename, passphrase, errmsg_p);
104     return NULL;
105 }
106
107 /*
108  * Export an SSH-1 key.
109  */
110 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
111                 char *passphrase)
112 {
113     return 0;
114 }
115
116 /*
117  * Export an SSH-2 key.
118  */
119 int export_ssh2(const Filename *filename, int type,
120                 struct ssh2_userkey *key, char *passphrase)
121 {
122     if (type == SSH_KEYTYPE_OPENSSH_AUTO)
123         return openssh_auto_write(filename, key, passphrase);
124     if (type == SSH_KEYTYPE_OPENSSH_NEW)
125         return openssh_new_write(filename, key, passphrase);
126     if (type == SSH_KEYTYPE_SSHCOM)
127         return sshcom_write(filename, key, passphrase);
128     return 0;
129 }
130
131 /*
132  * Strip trailing CRs and LFs at the end of a line of text.
133  */
134 void strip_crlf(char *str)
135 {
136     char *p = str + strlen(str);
137
138     while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
139         *--p = '\0';
140 }
141
142 /* ----------------------------------------------------------------------
143  * Helper routines. (The base64 ones are defined in sshpubk.c.)
144  */
145
146 #define isbase64(c) (    ((c) >= 'A' && (c) <= 'Z') || \
147                          ((c) >= 'a' && (c) <= 'z') || \
148                          ((c) >= '0' && (c) <= '9') || \
149                          (c) == '+' || (c) == '/' || (c) == '=' \
150                          )
151
152 /*
153  * Read an ASN.1/BER identifier and length pair.
154  * 
155  * Flags are a combination of the #defines listed below.
156  * 
157  * Returns -1 if unsuccessful; otherwise returns the number of
158  * bytes used out of the source data.
159  */
160
161 /* ASN.1 tag classes. */
162 #define ASN1_CLASS_UNIVERSAL        (0 << 6)
163 #define ASN1_CLASS_APPLICATION      (1 << 6)
164 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
165 #define ASN1_CLASS_PRIVATE          (3 << 6)
166 #define ASN1_CLASS_MASK             (3 << 6)
167
168 /* Primitive versus constructed bit. */
169 #define ASN1_CONSTRUCTED            (1 << 5)
170
171 static int ber_read_id_len(void *source, int sourcelen,
172                            int *id, int *length, int *flags)
173 {
174     unsigned char *p = (unsigned char *) source;
175
176     if (sourcelen == 0)
177         return -1;
178
179     *flags = (*p & 0xE0);
180     if ((*p & 0x1F) == 0x1F) {
181         *id = 0;
182         while (*p & 0x80) {
183             p++, sourcelen--;
184             if (sourcelen == 0)
185                 return -1;
186             *id = (*id << 7) | (*p & 0x7F);
187         }
188         p++, sourcelen--;
189     } else {
190         *id = *p & 0x1F;
191         p++, sourcelen--;
192     }
193
194     if (sourcelen == 0)
195         return -1;
196
197     if (*p & 0x80) {
198         int n = *p & 0x7F;
199         p++, sourcelen--;
200         if (sourcelen < n)
201             return -1;
202         *length = 0;
203         while (n--)
204             *length = (*length << 8) | (*p++);
205         sourcelen -= n;
206     } else {
207         *length = *p;
208         p++, sourcelen--;
209     }
210
211     return p - (unsigned char *) source;
212 }
213
214 /*
215  * Write an ASN.1/BER identifier and length pair. Returns the
216  * number of bytes consumed. Assumes dest contains enough space.
217  * Will avoid writing anything if dest is NULL, but still return
218  * amount of space required.
219  */
220 static int ber_write_id_len(void *dest, int id, int length, int flags)
221 {
222     unsigned char *d = (unsigned char *)dest;
223     int len = 0;
224
225     if (id <= 30) {
226         /*
227          * Identifier is one byte.
228          */
229         len++;
230         if (d) *d++ = id | flags;
231     } else {
232         int n;
233         /*
234          * Identifier is multiple bytes: the first byte is 11111
235          * plus the flags, and subsequent bytes encode the value of
236          * the identifier, 7 bits at a time, with the top bit of
237          * each byte 1 except the last one which is 0.
238          */
239         len++;
240         if (d) *d++ = 0x1F | flags;
241         for (n = 1; (id >> (7*n)) > 0; n++)
242             continue;                  /* count the bytes */
243         while (n--) {
244             len++;
245             if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
246         }
247     }
248
249     if (length < 128) {
250         /*
251          * Length is one byte.
252          */
253         len++;
254         if (d) *d++ = length;
255     } else {
256         int n;
257         /*
258          * Length is multiple bytes. The first is 0x80 plus the
259          * number of subsequent bytes, and the subsequent bytes
260          * encode the actual length.
261          */
262         for (n = 1; (length >> (8*n)) > 0; n++)
263             continue;                  /* count the bytes */
264         len++;
265         if (d) *d++ = 0x80 | n;
266         while (n--) {
267             len++;
268             if (d) *d++ = (length >> (8*n)) & 0xFF;
269         }
270     }
271
272     return len;
273 }
274
275 static int put_uint32(void *target, unsigned val)
276 {
277     unsigned char *d = (unsigned char *)target;
278
279     PUT_32BIT(d, val);
280     return 4;
281 }
282
283 static int put_string(void *target, const void *data, int len)
284 {
285     unsigned char *d = (unsigned char *)target;
286
287     PUT_32BIT(d, len);
288     memcpy(d+4, data, len);
289     return len+4;
290 }
291
292 static int put_string_z(void *target, const char *string)
293 {
294     return put_string(target, string, strlen(string));
295 }
296
297 static int put_mp(void *target, void *data, int len)
298 {
299     unsigned char *d = (unsigned char *)target;
300     unsigned char *i = (unsigned char *)data;
301
302     if (*i & 0x80) {
303         PUT_32BIT(d, len+1);
304         d[4] = 0;
305         memcpy(d+5, data, len);
306         return len+5;
307     } else {
308         PUT_32BIT(d, len);
309         memcpy(d+4, data, len);
310         return len+4;
311     }
312 }
313
314 /* Simple structure to point to an mp-int within a blob. */
315 struct mpint_pos { void *start; int bytes; };
316
317 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
318 {
319     int bytes;
320     unsigned char *d = (unsigned char *) data;
321
322     if (len < 4)
323         goto error;
324     bytes = toint(GET_32BIT(d));
325     if (bytes < 0 || len-4 < bytes)
326         goto error;
327
328     ret->start = d + 4;
329     ret->bytes = bytes;
330     return bytes+4;
331
332     error:
333     ret->start = NULL;
334     ret->bytes = -1;
335     return len;                        /* ensure further calls fail as well */
336 }
337
338 /* ----------------------------------------------------------------------
339  * Code to read and write OpenSSH private keys, in the old-style PEM
340  * format.
341  */
342
343 typedef enum {
344     OP_DSA, OP_RSA, OP_ECDSA
345 } openssh_pem_keytype;
346 typedef enum {
347     OP_E_3DES, OP_E_AES
348 } openssh_pem_enc;
349
350 struct openssh_pem_key {
351     openssh_pem_keytype keytype;
352     int encrypted;
353     openssh_pem_enc encryption;
354     char iv[32];
355     unsigned char *keyblob;
356     int keyblob_len, keyblob_size;
357 };
358
359 static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename,
360                                                     const char **errmsg_p)
361 {
362     struct openssh_pem_key *ret;
363     FILE *fp = NULL;
364     char *line = NULL;
365     char *errmsg, *p;
366     int headers_done;
367     char base64_bit[4];
368     int base64_chars = 0;
369
370     ret = snew(struct openssh_pem_key);
371     ret->keyblob = NULL;
372     ret->keyblob_len = ret->keyblob_size = 0;
373
374     fp = f_open(filename, "r", FALSE);
375     if (!fp) {
376         errmsg = "unable to open key file";
377         goto error;
378     }
379
380     if (!(line = fgetline(fp))) {
381         errmsg = "unexpected end of file";
382         goto error;
383     }
384     strip_crlf(line);
385     if (0 != strncmp(line, "-----BEGIN ", 11) ||
386         0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
387         errmsg = "file does not begin with OpenSSH key header";
388         goto error;
389     }
390     /*
391      * Parse the BEGIN line. For old-format keys, this tells us the
392      * type of the key; for new-format keys, all it tells us is the
393      * format, and we'll find out the key type once we parse the
394      * base64.
395      */
396     if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) {
397         ret->keytype = OP_RSA;
398     } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) {
399         ret->keytype = OP_DSA;
400     } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) {
401         ret->keytype = OP_ECDSA;
402     } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
403         errmsg = "this is a new-style OpenSSH key";
404         goto error;
405     } else {
406         errmsg = "unrecognised key type";
407         goto error;
408     }
409     smemclr(line, strlen(line));
410     sfree(line);
411     line = NULL;
412
413     ret->encrypted = FALSE;
414     memset(ret->iv, 0, sizeof(ret->iv));
415
416     headers_done = 0;
417     while (1) {
418         if (!(line = fgetline(fp))) {
419             errmsg = "unexpected end of file";
420             goto error;
421         }
422         strip_crlf(line);
423         if (0 == strncmp(line, "-----END ", 9) &&
424             0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
425             sfree(line);
426             line = NULL;
427             break;                     /* done */
428         }
429         if ((p = strchr(line, ':')) != NULL) {
430             if (headers_done) {
431                 errmsg = "header found in body of key data";
432                 goto error;
433             }
434             *p++ = '\0';
435             while (*p && isspace((unsigned char)*p)) p++;
436             if (!strcmp(line, "Proc-Type")) {
437                 if (p[0] != '4' || p[1] != ',') {
438                     errmsg = "Proc-Type is not 4 (only 4 is supported)";
439                     goto error;
440                 }
441                 p += 2;
442                 if (!strcmp(p, "ENCRYPTED"))
443                     ret->encrypted = TRUE;
444             } else if (!strcmp(line, "DEK-Info")) {
445                 int i, j, ivlen;
446
447                 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
448                     ret->encryption = OP_E_3DES;
449                     ivlen = 8;
450                 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
451                     ret->encryption = OP_E_AES;
452                     ivlen = 16;
453                 } else {
454                     errmsg = "unsupported cipher";
455                     goto error;
456                 }
457                 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
458                 for (i = 0; i < ivlen; i++) {
459                     if (1 != sscanf(p, "%2x", &j)) {
460                         errmsg = "expected more iv data in DEK-Info";
461                         goto error;
462                     }
463                     ret->iv[i] = j;
464                     p += 2;
465                 }
466                 if (*p) {
467                     errmsg = "more iv data than expected in DEK-Info";
468                     goto error;
469                 }
470             }
471         } else {
472             headers_done = 1;
473
474             p = line;
475             while (isbase64(*p)) {
476                 base64_bit[base64_chars++] = *p;
477                 if (base64_chars == 4) {
478                     unsigned char out[3];
479                     int len;
480
481                     base64_chars = 0;
482
483                     len = base64_decode_atom(base64_bit, out);
484
485                     if (len <= 0) {
486                         errmsg = "invalid base64 encoding";
487                         goto error;
488                     }
489
490                     if (ret->keyblob_len + len > ret->keyblob_size) {
491                         ret->keyblob_size = ret->keyblob_len + len + 256;
492                         ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
493                                                unsigned char);
494                     }
495
496                     memcpy(ret->keyblob + ret->keyblob_len, out, len);
497                     ret->keyblob_len += len;
498
499                     smemclr(out, sizeof(out));
500                 }
501
502                 p++;
503             }
504         }
505         smemclr(line, strlen(line));
506         sfree(line);
507         line = NULL;
508     }
509
510     fclose(fp);
511     fp = NULL;
512
513     if (ret->keyblob_len == 0 || !ret->keyblob) {
514         errmsg = "key body not present";
515         goto error;
516     }
517
518     if (ret->encrypted && ret->keyblob_len % 8 != 0) {
519         errmsg = "encrypted key blob is not a multiple of "
520             "cipher block size";
521         goto error;
522     }
523
524     smemclr(base64_bit, sizeof(base64_bit));
525     if (errmsg_p) *errmsg_p = NULL;
526     return ret;
527
528     error:
529     if (line) {
530         smemclr(line, strlen(line));
531         sfree(line);
532         line = NULL;
533     }
534     smemclr(base64_bit, sizeof(base64_bit));
535     if (ret) {
536         if (ret->keyblob) {
537             smemclr(ret->keyblob, ret->keyblob_size);
538             sfree(ret->keyblob);
539         }
540         smemclr(ret, sizeof(*ret));
541         sfree(ret);
542     }
543     if (errmsg_p) *errmsg_p = errmsg;
544     if (fp) fclose(fp);
545     return NULL;
546 }
547
548 int openssh_pem_encrypted(const Filename *filename)
549 {
550     struct openssh_pem_key *key = load_openssh_pem_key(filename, NULL);
551     int ret;
552
553     if (!key)
554         return 0;
555     ret = key->encrypted;
556     smemclr(key->keyblob, key->keyblob_size);
557     sfree(key->keyblob);
558     smemclr(key, sizeof(*key));
559     sfree(key);
560     return ret;
561 }
562
563 struct ssh2_userkey *openssh_pem_read(const Filename *filename,
564                                       char *passphrase,
565                                       const char **errmsg_p)
566 {
567     struct openssh_pem_key *key = load_openssh_pem_key(filename, errmsg_p);
568     struct ssh2_userkey *retkey;
569     unsigned char *p;
570     int ret, id, len, flags;
571     int i, num_integers;
572     struct ssh2_userkey *retval = NULL;
573     char *errmsg;
574     unsigned char *blob;
575     int blobsize = 0, blobptr, privptr;
576     char *modptr = NULL;
577     int modlen = 0;
578
579     blob = NULL;
580
581     if (!key)
582         return NULL;
583
584     if (key->encrypted) {
585         /*
586          * Derive encryption key from passphrase and iv/salt:
587          * 
588          *  - let block A equal MD5(passphrase || iv)
589          *  - let block B equal MD5(A || passphrase || iv)
590          *  - block C would be MD5(B || passphrase || iv) and so on
591          *  - encryption key is the first N bytes of A || B
592          *
593          * (Note that only 8 bytes of the iv are used for key
594          * derivation, even when the key is encrypted with AES and
595          * hence there are 16 bytes available.)
596          */
597         struct MD5Context md5c;
598         unsigned char keybuf[32];
599
600         MD5Init(&md5c);
601         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
602         MD5Update(&md5c, (unsigned char *)key->iv, 8);
603         MD5Final(keybuf, &md5c);
604
605         MD5Init(&md5c);
606         MD5Update(&md5c, keybuf, 16);
607         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
608         MD5Update(&md5c, (unsigned char *)key->iv, 8);
609         MD5Final(keybuf+16, &md5c);
610
611         /*
612          * Now decrypt the key blob.
613          */
614         if (key->encryption == OP_E_3DES)
615             des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
616                                      key->keyblob, key->keyblob_len);
617         else {
618             void *ctx;
619             assert(key->encryption == OP_E_AES);
620             ctx = aes_make_context();
621             aes128_key(ctx, keybuf);
622             aes_iv(ctx, (unsigned char *)key->iv);
623             aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
624             aes_free_context(ctx);
625         }
626
627         smemclr(&md5c, sizeof(md5c));
628         smemclr(keybuf, sizeof(keybuf));
629     }
630
631     /*
632      * Now we have a decrypted key blob, which contains an ASN.1
633      * encoded private key. We must now untangle the ASN.1.
634      *
635      * We expect the whole key blob to be formatted as a SEQUENCE
636      * (0x30 followed by a length code indicating that the rest of
637      * the blob is part of the sequence). Within that SEQUENCE we
638      * expect to see a bunch of INTEGERs. What those integers mean
639      * depends on the key type:
640      *
641      *  - For RSA, we expect the integers to be 0, n, e, d, p, q,
642      *    dmp1, dmq1, iqmp in that order. (The last three are d mod
643      *    (p-1), d mod (q-1), inverse of q mod p respectively.)
644      *
645      *  - For DSA, we expect them to be 0, p, q, g, y, x in that
646      *    order.
647      *
648      *  - In ECDSA the format is totally different: we see the
649      *    SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
650      *    EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
651      */
652     
653     p = key->keyblob;
654
655     /* Expect the SEQUENCE header. Take its absence as a failure to
656      * decrypt, if the key was encrypted. */
657     ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
658     p += ret;
659     if (ret < 0 || id != 16) {
660         errmsg = "ASN.1 decoding failure";
661         retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
662         goto error;
663     }
664
665     /* Expect a load of INTEGERs. */
666     if (key->keytype == OP_RSA)
667         num_integers = 9;
668     else if (key->keytype == OP_DSA)
669         num_integers = 6;
670     else
671         num_integers = 0;              /* placate compiler warnings */
672
673
674     if (key->keytype == OP_ECDSA) {
675         /* And now for something completely different */
676         unsigned char *priv;
677         int privlen;
678         struct ec_curve *curve;
679         /* Read INTEGER 1 */
680         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
681                               &id, &len, &flags);
682         p += ret;
683         if (ret < 0 || id != 2 || key->keyblob+key->keyblob_len-p < len ||
684             len != 1 || p[0] != 1) {
685             errmsg = "ASN.1 decoding failure";
686             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
687             goto error;
688         }
689         p += 1;
690         /* Read private key OCTET STRING */
691         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
692                               &id, &len, &flags);
693         p += ret;
694         if (ret < 0 || id != 4 || key->keyblob+key->keyblob_len-p < len) {
695             errmsg = "ASN.1 decoding failure";
696             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
697             goto error;
698         }
699         priv = p;
700         privlen = len;
701         p += len;
702         /* Read curve OID */
703         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
704                               &id, &len, &flags);
705         p += ret;
706         if (ret < 0 || id != 0 || key->keyblob+key->keyblob_len-p < len) {
707             errmsg = "ASN.1 decoding failure";
708             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
709             goto error;
710         }
711         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
712                               &id, &len, &flags);
713         p += ret;
714         if (ret < 0 || id != 6 || key->keyblob+key->keyblob_len-p < len) {
715             errmsg = "ASN.1 decoding failure";
716             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
717             goto error;
718         }
719         if (len == 8 && !memcmp(p, nistp256_oid, nistp256_oid_len)) {
720             curve = ec_p256();
721         } else if (len == 5 && !memcmp(p, nistp384_oid,
722                                        nistp384_oid_len)) {
723             curve = ec_p384();
724         } else if (len == 5 && !memcmp(p, nistp521_oid,
725                                        nistp521_oid_len)) {
726             curve = ec_p521();
727         } else {
728             errmsg = "Unsupported ECDSA curve.";
729             retval = NULL;
730             goto error;
731         }
732         p += len;
733         /* Read BIT STRING point */
734         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
735                               &id, &len, &flags);
736         p += ret;
737         if (ret < 0 || id != 1 || key->keyblob+key->keyblob_len-p < len) {
738             errmsg = "ASN.1 decoding failure";
739             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
740             goto error;
741         }
742         ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
743                               &id, &len, &flags);
744         p += ret;
745         if (ret < 0 || id != 3 || key->keyblob+key->keyblob_len-p < len ||
746             len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
747             errmsg = "ASN.1 decoding failure";
748             retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
749             goto error;
750         }
751         p += 1; len -= 1; /* Skip 0x00 before point */
752
753         /* Construct the key */
754         retkey = snew(struct ssh2_userkey);
755         if (!retkey) {
756             errmsg = "out of memory";
757             goto error;
758         }
759         if (curve->fieldBits == 256) {
760             retkey->alg = &ssh_ecdsa_nistp256;
761         } else if (curve->fieldBits == 384) {
762             retkey->alg = &ssh_ecdsa_nistp384;
763         } else {
764             retkey->alg = &ssh_ecdsa_nistp521;
765         }
766         blob = snewn((4+19 + 4+8 + 4+len) + (4+privlen), unsigned char);
767         if (!blob) {
768             sfree(retkey);
769             errmsg = "out of memory";
770             goto error;
771         }
772         PUT_32BIT(blob, 19);
773         sprintf((char*)blob+4, "ecdsa-sha2-nistp%d", curve->fieldBits);
774         PUT_32BIT(blob+4+19, 8);
775         sprintf((char*)blob+4+19+4, "nistp%d", curve->fieldBits);
776         PUT_32BIT(blob+4+19+4+8, len);
777         memcpy(blob+4+19+4+8+4, p, len);
778         PUT_32BIT(blob+4+19+4+8+4+len, privlen);
779         memcpy(blob+4+19+4+8+4+len+4, priv, privlen);
780         retkey->data = retkey->alg->createkey(blob, 4+19+4+8+4+len,
781                                               blob+4+19+4+8+4+len,
782                                               4+privlen);
783         if (!retkey->data) {
784             sfree(retkey);
785             errmsg = "unable to create key data structure";
786             goto error;
787         }
788
789     } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
790
791         /*
792          * Space to create key blob in.
793          */
794         blobsize = 256+key->keyblob_len;
795         blob = snewn(blobsize, unsigned char);
796         PUT_32BIT(blob, 7);
797         if (key->keytype == OP_DSA)
798             memcpy(blob+4, "ssh-dss", 7);
799         else if (key->keytype == OP_RSA)
800             memcpy(blob+4, "ssh-rsa", 7);
801         blobptr = 4+7;
802         privptr = -1;
803
804         for (i = 0; i < num_integers; i++) {
805             ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
806                                   &id, &len, &flags);
807             p += ret;
808             if (ret < 0 || id != 2 ||
809                 key->keyblob+key->keyblob_len-p < len) {
810                 errmsg = "ASN.1 decoding failure";
811                 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
812                 goto error;
813             }
814
815             if (i == 0) {
816                 /*
817                  * The first integer should be zero always (I think
818                  * this is some sort of version indication).
819                  */
820                 if (len != 1 || p[0] != 0) {
821                     errmsg = "version number mismatch";
822                     goto error;
823                 }
824             } else if (key->keytype == OP_RSA) {
825                 /*
826                  * Integers 1 and 2 go into the public blob but in the
827                  * opposite order; integers 3, 4, 5 and 8 go into the
828                  * private blob. The other two (6 and 7) are ignored.
829                  */
830                 if (i == 1) {
831                     /* Save the details for after we deal with number 2. */
832                     modptr = (char *)p;
833                     modlen = len;
834                 } else if (i != 6 && i != 7) {
835                     PUT_32BIT(blob+blobptr, len);
836                     memcpy(blob+blobptr+4, p, len);
837                     blobptr += 4+len;
838                     if (i == 2) {
839                         PUT_32BIT(blob+blobptr, modlen);
840                         memcpy(blob+blobptr+4, modptr, modlen);
841                         blobptr += 4+modlen;
842                         privptr = blobptr;
843                     }
844                 }
845             } else if (key->keytype == OP_DSA) {
846                 /*
847                  * Integers 1-4 go into the public blob; integer 5 goes
848                  * into the private blob.
849                  */
850                 PUT_32BIT(blob+blobptr, len);
851                 memcpy(blob+blobptr+4, p, len);
852                 blobptr += 4+len;
853                 if (i == 4)
854                     privptr = blobptr;
855             }
856
857             /* Skip past the number. */
858             p += len;
859         }
860
861         /*
862          * Now put together the actual key. Simplest way to do this is
863          * to assemble our own key blobs and feed them to the createkey
864          * functions; this is a bit faffy but it does mean we get all
865          * the sanity checks for free.
866          */
867         assert(privptr > 0);          /* should have bombed by now if not */
868         retkey = snew(struct ssh2_userkey);
869         retkey->alg = (key->keytype == OP_RSA ? &ssh_rsa : &ssh_dss);
870         retkey->data = retkey->alg->createkey(blob, privptr,
871                                               blob+privptr,
872                                               blobptr-privptr);
873         if (!retkey->data) {
874             sfree(retkey);
875             errmsg = "unable to create key data structure";
876             goto error;
877         }
878
879     } else {
880         assert(0 && "Bad key type from load_openssh_pem_key");
881     }
882
883     /*
884      * The old key format doesn't include a comment in the private
885      * key file.
886      */
887     retkey->comment = dupstr("imported-openssh-key");
888
889     errmsg = NULL;                     /* no error */
890     retval = retkey;
891
892     error:
893     if (blob) {
894         smemclr(blob, blobsize);
895         sfree(blob);
896     }
897     smemclr(key->keyblob, key->keyblob_size);
898     sfree(key->keyblob);
899     smemclr(key, sizeof(*key));
900     sfree(key);
901     if (errmsg_p) *errmsg_p = errmsg;
902     return retval;
903 }
904
905 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
906                       char *passphrase)
907 {
908     unsigned char *pubblob, *privblob, *spareblob;
909     int publen, privlen, sparelen = 0;
910     unsigned char *outblob;
911     int outlen;
912     struct mpint_pos numbers[9];
913     int nnumbers, pos, len, seqlen, i;
914     char *header, *footer;
915     char zero[1];
916     unsigned char iv[8];
917     int ret = 0;
918     FILE *fp;
919
920     /*
921      * Fetch the key blobs.
922      */
923     pubblob = key->alg->public_blob(key->data, &publen);
924     privblob = key->alg->private_blob(key->data, &privlen);
925     spareblob = outblob = NULL;
926
927     outblob = NULL;
928     len = 0;
929
930     /*
931      * Encode the OpenSSH key blob, and also decide on the header
932      * line.
933      */
934     if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
935         /*
936          * The RSA and DSS handlers share some code because the two
937          * key types have very similar ASN.1 representations, as a
938          * plain SEQUENCE of big integers. So we set up a list of
939          * bignums per key type and then construct the actual blob in
940          * common code after that.
941          */
942         if (key->alg == &ssh_rsa) {
943             int pos;
944             struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
945             Bignum bd, bp, bq, bdmp1, bdmq1;
946
947             /*
948              * These blobs were generated from inside PuTTY, so we needn't
949              * treat them as untrusted.
950              */
951             pos = 4 + GET_32BIT(pubblob);
952             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
953             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
954             pos = 0;
955             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
956             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
957             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
958             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
959
960             assert(e.start && iqmp.start); /* can't go wrong */
961
962             /* We also need d mod (p-1) and d mod (q-1). */
963             bd = bignum_from_bytes(d.start, d.bytes);
964             bp = bignum_from_bytes(p.start, p.bytes);
965             bq = bignum_from_bytes(q.start, q.bytes);
966             decbn(bp);
967             decbn(bq);
968             bdmp1 = bigmod(bd, bp);
969             bdmq1 = bigmod(bd, bq);
970             freebn(bd);
971             freebn(bp);
972             freebn(bq);
973
974             dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
975             dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
976             sparelen = dmp1.bytes + dmq1.bytes;
977             spareblob = snewn(sparelen, unsigned char);
978             dmp1.start = spareblob;
979             dmq1.start = spareblob + dmp1.bytes;
980             for (i = 0; i < dmp1.bytes; i++)
981                 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
982             for (i = 0; i < dmq1.bytes; i++)
983                 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
984             freebn(bdmp1);
985             freebn(bdmq1);
986
987             numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
988             numbers[1] = n;
989             numbers[2] = e;
990             numbers[3] = d;
991             numbers[4] = p;
992             numbers[5] = q;
993             numbers[6] = dmp1;
994             numbers[7] = dmq1;
995             numbers[8] = iqmp;
996
997             nnumbers = 9;
998             header = "-----BEGIN RSA PRIVATE KEY-----\n";
999             footer = "-----END RSA PRIVATE KEY-----\n";
1000         } else {                       /* ssh-dss */
1001             int pos;
1002             struct mpint_pos p, q, g, y, x;
1003
1004             /*
1005              * These blobs were generated from inside PuTTY, so we needn't
1006              * treat them as untrusted.
1007              */
1008             pos = 4 + GET_32BIT(pubblob);
1009             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1010             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1011             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1012             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1013             pos = 0;
1014             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1015
1016             assert(y.start && x.start); /* can't go wrong */
1017
1018             numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1019             numbers[1] = p;
1020             numbers[2] = q;
1021             numbers[3] = g;
1022             numbers[4] = y;
1023             numbers[5] = x;
1024
1025             nnumbers = 6;
1026             header = "-----BEGIN DSA PRIVATE KEY-----\n";
1027             footer = "-----END DSA PRIVATE KEY-----\n";
1028         }
1029
1030         /*
1031          * Now count up the total size of the ASN.1 encoded integers,
1032          * so as to determine the length of the containing SEQUENCE.
1033          */
1034         len = 0;
1035         for (i = 0; i < nnumbers; i++) {
1036             len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
1037             len += numbers[i].bytes;
1038         }
1039         seqlen = len;
1040         /* Now add on the SEQUENCE header. */
1041         len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1042
1043         /*
1044          * Now we know how big outblob needs to be. Allocate it.
1045          */
1046         outblob = snewn(len, unsigned char);
1047
1048         /*
1049          * And write the data into it.
1050          */
1051         pos = 0;
1052         pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1053         for (i = 0; i < nnumbers; i++) {
1054             pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
1055             memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
1056             pos += numbers[i].bytes;
1057         }
1058     } else if (key->alg == &ssh_ecdsa_nistp256 ||
1059                key->alg == &ssh_ecdsa_nistp384 ||
1060                key->alg == &ssh_ecdsa_nistp521) {
1061         unsigned char *oid;
1062         int oidlen;
1063         int pointlen;
1064
1065         /*
1066          * Structure of asn1:
1067          * SEQUENCE
1068          *   INTEGER 1
1069          *   OCTET STRING (private key)
1070          *   [0]
1071          *     OID (curve)
1072          *   [1]
1073          *     BIT STRING (0x00 public key point)
1074          */
1075         switch (((struct ec_key *)key->data)->publicKey.curve->fieldBits) {
1076           case 256:
1077             /* OID: 1.2.840.10045.3.1.7 (ansiX9p256r1) */
1078             oid = nistp256_oid;
1079             oidlen = nistp256_oid_len;
1080             pointlen = 32 * 2;
1081             break;
1082           case 384:
1083             /* OID: 1.3.132.0.34 (secp384r1) */
1084             oid = nistp384_oid;
1085             oidlen = nistp384_oid_len;
1086             pointlen = 48 * 2;
1087             break;
1088           case 521:
1089             /* OID: 1.3.132.0.35 (secp521r1) */
1090             oid = nistp521_oid;
1091             oidlen = nistp521_oid_len;
1092             pointlen = 66 * 2;
1093             break;
1094           default:
1095             assert(0);
1096         }
1097
1098         len = ber_write_id_len(NULL, 2, 1, 0);
1099         len += 1;
1100         len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1101         len+= privlen - 4;
1102         len += ber_write_id_len(NULL, 0, oidlen +
1103                                 ber_write_id_len(NULL, 6, oidlen, 0),
1104                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1105         len += ber_write_id_len(NULL, 6, oidlen, 0);
1106         len += oidlen;
1107         len += ber_write_id_len(NULL, 1, 2 + pointlen +
1108                                 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1109                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1110         len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1111         len += 2 + pointlen;
1112
1113         seqlen = len;
1114         len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1115
1116         outblob = snewn(len, unsigned char);
1117         assert(outblob);
1118
1119         pos = 0;
1120         pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1121         pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1122         outblob[pos++] = 1;
1123         pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1124         memcpy(outblob+pos, privblob + 4, privlen - 4);
1125         pos += privlen - 4;
1126         pos += ber_write_id_len(outblob+pos, 0, oidlen +
1127                                 ber_write_id_len(NULL, 6, oidlen, 0),
1128                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1129         pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1130         memcpy(outblob+pos, oid, oidlen);
1131         pos += oidlen;
1132         pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1133                                 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1134                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1135         pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1136         outblob[pos++] = 0;
1137         memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1138         pos += 1 + pointlen;
1139
1140         header = "-----BEGIN EC PRIVATE KEY-----\n";
1141         footer = "-----END EC PRIVATE KEY-----\n";
1142     } else {
1143         assert(0);                     /* zoinks! */
1144         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1145     }
1146
1147     /*
1148      * Encrypt the key.
1149      *
1150      * For the moment, we still encrypt our OpenSSH keys using
1151      * old-style 3DES.
1152      */
1153     if (passphrase) {
1154         struct MD5Context md5c;
1155         unsigned char keybuf[32];
1156
1157         /*
1158          * Round up to the cipher block size, ensuring we have at
1159          * least one byte of padding (see below).
1160          */
1161         outlen = (len+8) &~ 7;
1162         {
1163             unsigned char *tmp = snewn(outlen, unsigned char);
1164             memcpy(tmp, outblob, len);
1165             smemclr(outblob, len);
1166             sfree(outblob);
1167             outblob = tmp;
1168         }
1169
1170         /*
1171          * Padding on OpenSSH keys is deterministic. The number of
1172          * padding bytes is always more than zero, and always at most
1173          * the cipher block length. The value of each padding byte is
1174          * equal to the number of padding bytes. So a plaintext that's
1175          * an exact multiple of the block size will be padded with 08
1176          * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1177          * plaintext one byte less than a multiple of the block size
1178          * will be padded with just 01.
1179          *
1180          * This enables the OpenSSL key decryption function to strip
1181          * off the padding algorithmically and return the unpadded
1182          * plaintext to the next layer: it looks at the final byte, and
1183          * then expects to find that many bytes at the end of the data
1184          * with the same value. Those are all removed and the rest is
1185          * returned.
1186          */
1187         assert(pos == len);
1188         while (pos < outlen) {
1189             outblob[pos++] = outlen - len;
1190         }
1191
1192         /*
1193          * Invent an iv. Then derive encryption key from passphrase
1194          * and iv/salt:
1195          * 
1196          *  - let block A equal MD5(passphrase || iv)
1197          *  - let block B equal MD5(A || passphrase || iv)
1198          *  - block C would be MD5(B || passphrase || iv) and so on
1199          *  - encryption key is the first N bytes of A || B
1200          */
1201         for (i = 0; i < 8; i++) iv[i] = random_byte();
1202
1203         MD5Init(&md5c);
1204         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1205         MD5Update(&md5c, iv, 8);
1206         MD5Final(keybuf, &md5c);
1207
1208         MD5Init(&md5c);
1209         MD5Update(&md5c, keybuf, 16);
1210         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1211         MD5Update(&md5c, iv, 8);
1212         MD5Final(keybuf+16, &md5c);
1213
1214         /*
1215          * Now encrypt the key blob.
1216          */
1217         des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1218
1219         smemclr(&md5c, sizeof(md5c));
1220         smemclr(keybuf, sizeof(keybuf));
1221     } else {
1222         /*
1223          * If no encryption, the blob has exactly its original
1224          * cleartext size.
1225          */
1226         outlen = len;
1227     }
1228
1229     /*
1230      * And save it. We'll use Unix line endings just in case it's
1231      * subsequently transferred in binary mode.
1232      */
1233     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
1234     if (!fp)
1235         goto error;
1236     fputs(header, fp);
1237     if (passphrase) {
1238         fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1239         for (i = 0; i < 8; i++)
1240             fprintf(fp, "%02X", iv[i]);
1241         fprintf(fp, "\n\n");
1242     }
1243     base64_encode(fp, outblob, outlen, 64);
1244     fputs(footer, fp);
1245     fclose(fp);
1246     ret = 1;
1247
1248     error:
1249     if (outblob) {
1250         smemclr(outblob, outlen);
1251         sfree(outblob);
1252     }
1253     if (spareblob) {
1254         smemclr(spareblob, sparelen);
1255         sfree(spareblob);
1256     }
1257     if (privblob) {
1258         smemclr(privblob, privlen);
1259         sfree(privblob);
1260     }
1261     if (pubblob) {
1262         smemclr(pubblob, publen);
1263         sfree(pubblob);
1264     }
1265     return ret;
1266 }
1267
1268 /* ----------------------------------------------------------------------
1269  * Code to read and write OpenSSH private keys in the new-style format.
1270  */
1271
1272 typedef enum {
1273     ON_E_NONE, ON_E_AES256CBC
1274 } openssh_new_cipher;
1275 typedef enum {
1276     ON_K_NONE, ON_K_BCRYPT
1277 } openssh_new_kdf;
1278
1279 struct openssh_new_key {
1280     openssh_new_cipher cipher;
1281     openssh_new_kdf kdf;
1282     union {
1283         struct {
1284             int rounds;
1285             /* This points to a position within keyblob, not a
1286              * separately allocated thing */
1287             const unsigned char *salt;
1288             int saltlen;
1289         } bcrypt;
1290     } kdfopts;
1291     int nkeys, key_wanted;
1292     /* This too points to a position within keyblob */
1293     unsigned char *privatestr;
1294     int privatelen;
1295
1296     unsigned char *keyblob;
1297     int keyblob_len, keyblob_size;
1298 };
1299
1300 static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
1301                                                     const char **errmsg_p)
1302 {
1303     struct openssh_new_key *ret;
1304     FILE *fp = NULL;
1305     char *line = NULL;
1306     char *errmsg, *p;
1307     char base64_bit[4];
1308     int base64_chars = 0;
1309     const void *filedata;
1310     int filelen;
1311     const void *string, *kdfopts, *bcryptsalt, *pubkey;
1312     int stringlen, kdfoptlen, bcryptsaltlen, pubkeylen;
1313     unsigned bcryptrounds, nkeys, key_index;
1314
1315     ret = snew(struct openssh_new_key);
1316     ret->keyblob = NULL;
1317     ret->keyblob_len = ret->keyblob_size = 0;
1318
1319     fp = f_open(filename, "r", FALSE);
1320     if (!fp) {
1321         errmsg = "unable to open key file";
1322         goto error;
1323     }
1324
1325     if (!(line = fgetline(fp))) {
1326         errmsg = "unexpected end of file";
1327         goto error;
1328     }
1329     strip_crlf(line);
1330     if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
1331         errmsg = "file does not begin with OpenSSH new-style key header";
1332         goto error;
1333     }
1334     smemclr(line, strlen(line));
1335     sfree(line);
1336     line = NULL;
1337
1338     while (1) {
1339         if (!(line = fgetline(fp))) {
1340             errmsg = "unexpected end of file";
1341             goto error;
1342         }
1343         strip_crlf(line);
1344         if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
1345             sfree(line);
1346             line = NULL;
1347             break;                     /* done */
1348         }
1349
1350         p = line;
1351         while (isbase64(*p)) {
1352             base64_bit[base64_chars++] = *p;
1353             if (base64_chars == 4) {
1354                 unsigned char out[3];
1355                 int len;
1356
1357                 base64_chars = 0;
1358
1359                 len = base64_decode_atom(base64_bit, out);
1360
1361                 if (len <= 0) {
1362                     errmsg = "invalid base64 encoding";
1363                     goto error;
1364                 }
1365
1366                 if (ret->keyblob_len + len > ret->keyblob_size) {
1367                     ret->keyblob_size = ret->keyblob_len + len + 256;
1368                     ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1369                                            unsigned char);
1370                 }
1371
1372                 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1373                 ret->keyblob_len += len;
1374
1375                 smemclr(out, sizeof(out));
1376             }
1377
1378             p++;
1379         }
1380         smemclr(line, strlen(line));
1381         sfree(line);
1382         line = NULL;
1383     }
1384
1385     fclose(fp);
1386     fp = NULL;
1387
1388     if (ret->keyblob_len == 0 || !ret->keyblob) {
1389         errmsg = "key body not present";
1390         goto error;
1391     }
1392
1393     filedata = ret->keyblob;
1394     filelen = ret->keyblob_len;
1395
1396     if (filelen < 15 || 0 != memcmp(filedata, "openssh-key-v1\0", 15)) {
1397         errmsg = "new-style OpenSSH magic number missing\n";
1398         goto error;
1399     }
1400     filedata = (const char *)filedata + 15;
1401     filelen -= 15;
1402
1403     if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1404         errmsg = "encountered EOF before cipher name\n";
1405         goto error;
1406     }
1407     if (match_ssh_id(stringlen, string, "none")) {
1408         ret->cipher = ON_E_NONE;
1409     } else if (match_ssh_id(stringlen, string, "aes256-cbc")) {
1410         ret->cipher = ON_E_AES256CBC;
1411     } else {
1412         errmsg = "unrecognised cipher name\n";
1413         goto error;
1414     }
1415
1416     if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1417         errmsg = "encountered EOF before kdf name\n";
1418         goto error;
1419     }
1420     if (match_ssh_id(stringlen, string, "none")) {
1421         ret->kdf = ON_K_NONE;
1422     } else if (match_ssh_id(stringlen, string, "bcrypt")) {
1423         ret->kdf = ON_K_BCRYPT;
1424     } else {
1425         errmsg = "unrecognised kdf name\n";
1426         goto error;
1427     }
1428
1429     if (!(kdfopts = get_ssh_string(&filelen, &filedata, &kdfoptlen))) {
1430         errmsg = "encountered EOF before kdf options\n";
1431         goto error;
1432     }
1433     switch (ret->kdf) {
1434       case ON_K_NONE:
1435         if (kdfoptlen != 0) {
1436             errmsg = "expected empty options string for 'none' kdf";
1437             goto error;
1438         }
1439         break;
1440       case ON_K_BCRYPT:
1441         if (!(bcryptsalt = get_ssh_string(&kdfoptlen, &kdfopts,
1442                                           &bcryptsaltlen))) {
1443             errmsg = "bcrypt options string did not contain salt\n";
1444             goto error;
1445         }
1446         if (!get_ssh_uint32(&kdfoptlen, &kdfopts, &bcryptrounds)) {
1447             errmsg = "bcrypt options string did not contain round count\n";
1448             goto error;
1449         }
1450         ret->kdfopts.bcrypt.salt = bcryptsalt;
1451         ret->kdfopts.bcrypt.saltlen = bcryptsaltlen;
1452         ret->kdfopts.bcrypt.rounds = bcryptrounds;
1453         break;
1454     }
1455
1456     /*
1457      * At this point we expect a uint32 saying how many keys are
1458      * stored in this file. OpenSSH new-style key files can
1459      * contain more than one. Currently we don't have any user
1460      * interface to specify which one we're trying to extract, so
1461      * we just bomb out with an error if more than one is found in
1462      * the file. However, I've put in all the mechanism here to
1463      * extract the nth one for a given n, in case we later connect
1464      * up some UI to that mechanism. Just arrange that the
1465      * 'key_wanted' field is set to a value in the range [0,
1466      * nkeys) by some mechanism.
1467      */
1468     if (!get_ssh_uint32(&filelen, &filedata, &nkeys)) {
1469         errmsg = "encountered EOF before key count\n";
1470         goto error;
1471     }
1472     if (nkeys != 1) {
1473         errmsg = "multiple keys in new-style OpenSSH key file "
1474             "not supported\n";
1475         goto error;
1476     }
1477     ret->nkeys = nkeys;
1478     ret->key_wanted = 0;
1479
1480     for (key_index = 0; key_index < nkeys; key_index++) {
1481         if (!(pubkey = get_ssh_string(&filelen, &filedata, &pubkeylen))) {
1482             errmsg = "encountered EOF before kdf options\n";
1483             goto error;
1484         }
1485     }
1486
1487     /*
1488      * Now we expect a string containing the encrypted part of the
1489      * key file.
1490      */
1491     if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1492         errmsg = "encountered EOF before private key container\n";
1493         goto error;
1494     }
1495     ret->privatestr = (unsigned char *)string;
1496     ret->privatelen = stringlen;
1497
1498     /*
1499      * And now we're done, until asked to actually decrypt.
1500      */
1501
1502     smemclr(base64_bit, sizeof(base64_bit));
1503     if (errmsg_p) *errmsg_p = NULL;
1504     return ret;
1505
1506     error:
1507     if (line) {
1508         smemclr(line, strlen(line));
1509         sfree(line);
1510         line = NULL;
1511     }
1512     smemclr(base64_bit, sizeof(base64_bit));
1513     if (ret) {
1514         if (ret->keyblob) {
1515             smemclr(ret->keyblob, ret->keyblob_size);
1516             sfree(ret->keyblob);
1517         }
1518         smemclr(ret, sizeof(*ret));
1519         sfree(ret);
1520     }
1521     if (errmsg_p) *errmsg_p = errmsg;
1522     if (fp) fclose(fp);
1523     return NULL;
1524 }
1525
1526 int openssh_new_encrypted(const Filename *filename)
1527 {
1528     struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
1529     int ret;
1530
1531     if (!key)
1532         return 0;
1533     ret = (key->cipher != ON_E_NONE);
1534     smemclr(key->keyblob, key->keyblob_size);
1535     sfree(key->keyblob);
1536     smemclr(key, sizeof(*key));
1537     sfree(key);
1538     return ret;
1539 }
1540
1541 struct ssh2_userkey *openssh_new_read(const Filename *filename,
1542                                       char *passphrase,
1543                                       const char **errmsg_p)
1544 {
1545     struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
1546     struct ssh2_userkey *retkey;
1547     int i;
1548     struct ssh2_userkey *retval = NULL;
1549     char *errmsg;
1550     unsigned char *blob;
1551     int blobsize = 0;
1552     unsigned checkint0, checkint1;
1553     const void *priv, *string;
1554     int privlen, stringlen, key_index;
1555     const struct ssh_signkey *alg;
1556
1557     blob = NULL;
1558
1559     if (!key)
1560         return NULL;
1561
1562     if (key->cipher != ON_E_NONE) {
1563         unsigned char keybuf[48];
1564         int keysize;
1565
1566         /*
1567          * Construct the decryption key, and decrypt the string.
1568          */
1569         switch (key->cipher) {
1570           case ON_E_NONE:
1571             keysize = 0;
1572             break;
1573           case ON_E_AES256CBC:
1574             keysize = 48;              /* 32 byte key + 16 byte IV */
1575             break;
1576           default:
1577             assert(0 && "Bad cipher enumeration value");
1578         }
1579         assert(keysize <= sizeof(keybuf));
1580         switch (key->kdf) {
1581           case ON_K_NONE:
1582             memset(keybuf, 0, keysize);
1583             break;
1584           case ON_K_BCRYPT:
1585             openssh_bcrypt(passphrase,
1586                            key->kdfopts.bcrypt.salt,
1587                            key->kdfopts.bcrypt.saltlen,
1588                            key->kdfopts.bcrypt.rounds,
1589                            keybuf, keysize);
1590             break;
1591           default:
1592             assert(0 && "Bad kdf enumeration value");
1593         }
1594         switch (key->cipher) {
1595           case ON_E_NONE:
1596             break;
1597           case ON_E_AES256CBC:
1598             if (key->privatelen % 16 != 0) {
1599                 errmsg = "private key container length is not a"
1600                     " multiple of AES block size\n";
1601                 goto error;
1602             }
1603             {
1604                 void *ctx = aes_make_context();
1605                 aes256_key(ctx, keybuf);
1606                 aes_iv(ctx, keybuf + 32);
1607                 aes_ssh2_decrypt_blk(ctx, key->privatestr,
1608                                      key->privatelen);
1609                 aes_free_context(ctx);
1610             }
1611             break;
1612           default:
1613             assert(0 && "Bad cipher enumeration value");
1614         }
1615     }
1616
1617     /*
1618      * Now parse the entire encrypted section, and extract the key
1619      * identified by key_wanted.
1620      */
1621     priv = key->privatestr;
1622     privlen = key->privatelen;
1623
1624     if (!get_ssh_uint32(&privlen, &priv, &checkint0) ||
1625         !get_ssh_uint32(&privlen, &priv, &checkint1) ||
1626         checkint0 != checkint1) {
1627         errmsg = "decryption check failed";
1628         goto error;
1629     }
1630
1631     retkey = NULL;
1632     for (key_index = 0; key_index < key->nkeys; key_index++) {
1633         const unsigned char *thiskey;
1634         int thiskeylen;
1635
1636         /*
1637          * Read the key type, which will tell us how to scan over
1638          * the key to get to the next one.
1639          */
1640         if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1641             errmsg = "expected key type in private string";
1642             goto error;
1643         }
1644
1645         /*
1646          * Preliminary key type identification, and decide how
1647          * many pieces of key we expect to see. Currently
1648          * (conveniently) all key types can be seen as some number
1649          * of strings, so we just need to know how many of them to
1650          * skip over. (The numbers below exclude the key comment.)
1651          */
1652         {
1653             /* find_pubkey_alg needs a zero-terminated copy of the
1654              * algorithm name */
1655             char *name_zt = dupprintf("%.*s", stringlen, (char *)string);
1656             alg = find_pubkey_alg(name_zt);
1657             sfree(name_zt);
1658         }
1659
1660         if (!alg) {
1661             errmsg = "private key type not recognised\n";
1662             goto error;
1663         }
1664
1665         thiskey = priv;
1666
1667         /*
1668          * Skip over the pieces of key.
1669          */
1670         for (i = 0; i < alg->openssh_private_npieces; i++) {
1671             if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1672                 errmsg = "ran out of data in mid-private-key";
1673                 goto error;
1674             }
1675         }
1676
1677         thiskeylen = (int)((const unsigned char *)priv -
1678                            (const unsigned char *)thiskey);
1679         if (key_index == key->key_wanted) {
1680             retkey = snew(struct ssh2_userkey);
1681             retkey->alg = alg;
1682             retkey->data = alg->openssh_createkey(&thiskey, &thiskeylen);
1683             if (!retkey->data) {
1684                 sfree(retkey);
1685                 errmsg = "unable to create key data structure";
1686                 goto error;
1687             }
1688         }
1689
1690         /*
1691          * Read the key comment.
1692          */
1693         if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1694             errmsg = "ran out of data at key comment";
1695             goto error;
1696         }
1697         if (key_index == key->key_wanted) {
1698             assert(retkey);
1699             retkey->comment = dupprintf("%.*s", stringlen,
1700                                         (const char *)string);
1701         }
1702     }
1703
1704     if (!retkey) {
1705         errmsg = "key index out of range";
1706         goto error;
1707     }
1708
1709     /*
1710      * Now we expect nothing left but padding.
1711      */
1712     for (i = 0; i < privlen; i++) {
1713         if (((const unsigned char *)priv)[i] != (unsigned char)(i+1)) {
1714             errmsg = "padding at end of private string did not match";
1715             goto error;
1716         }
1717     }
1718
1719     errmsg = NULL;                     /* no error */
1720     retval = retkey;
1721
1722     error:
1723     if (blob) {
1724         smemclr(blob, blobsize);
1725         sfree(blob);
1726     }
1727     smemclr(key->keyblob, key->keyblob_size);
1728     sfree(key->keyblob);
1729     smemclr(key, sizeof(*key));
1730     sfree(key);
1731     if (errmsg_p) *errmsg_p = errmsg;
1732     return retval;
1733 }
1734
1735 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
1736                       char *passphrase)
1737 {
1738     unsigned char *pubblob, *privblob, *outblob, *p;
1739     unsigned char *private_section_start, *private_section_length_field;
1740     int publen, privlen, commentlen, maxsize, padvalue, i;
1741     unsigned checkint;
1742     int ret = 0;
1743     unsigned char bcrypt_salt[16];
1744     const int bcrypt_rounds = 16;
1745     FILE *fp;
1746
1747     /*
1748      * Fetch the key blobs and find out the lengths of things.
1749      */
1750     pubblob = key->alg->public_blob(key->data, &publen);
1751     i = key->alg->openssh_fmtkey(key->data, NULL, 0);
1752     privblob = snewn(i, unsigned char);
1753     privlen = key->alg->openssh_fmtkey(key->data, privblob, i);
1754     assert(privlen == i);
1755     commentlen = strlen(key->comment);
1756
1757     /*
1758      * Allocate enough space for the full binary key format. No need
1759      * to be absolutely precise here.
1760      */
1761     maxsize = (16 +                    /* magic number */
1762                32 +                    /* cipher name string */
1763                32 +                    /* kdf name string */
1764                64 +                    /* kdf options string */
1765                4 +                     /* key count */
1766                4+publen +              /* public key string */
1767                4 +                     /* string header for private section */
1768                8 +                     /* checkint x 2 */
1769                4+strlen(key->alg->name) + /* key type string */
1770                privlen +               /* private blob */
1771                4+commentlen +          /* comment string */
1772                16);                    /* padding at end of private section */
1773     outblob = snewn(maxsize, unsigned char);
1774
1775     /*
1776      * Construct the cleartext version of the blob.
1777      */
1778     p = outblob;
1779
1780     /* Magic number. */
1781     memcpy(p, "openssh-key-v1\0", 15);
1782     p += 15;
1783
1784     /* Cipher and kdf names, and kdf options. */
1785     if (!passphrase) {
1786         memset(bcrypt_salt, 0, sizeof(bcrypt_salt)); /* prevent warnings */
1787         p += put_string_z(p, "none");
1788         p += put_string_z(p, "none");
1789         p += put_string_z(p, "");
1790     } else {
1791         unsigned char *q;
1792         for (i = 0; i < (int)sizeof(bcrypt_salt); i++)
1793             bcrypt_salt[i] = random_byte();
1794         p += put_string_z(p, "aes256-cbc");
1795         p += put_string_z(p, "bcrypt");
1796         q = p;
1797         p += 4;
1798         p += put_string(p, bcrypt_salt, sizeof(bcrypt_salt));
1799         p += put_uint32(p, bcrypt_rounds);
1800         PUT_32BIT_MSB_FIRST(q, (unsigned)(p - (q+4)));
1801     }
1802
1803     /* Number of keys. */
1804     p += put_uint32(p, 1);
1805
1806     /* Public blob. */
1807     p += put_string(p, pubblob, publen);
1808
1809     /* Begin private section. */
1810     private_section_length_field = p;
1811     p += 4;
1812     private_section_start = p;
1813
1814     /* checkint. */
1815     checkint = 0;
1816     for (i = 0; i < 4; i++)
1817         checkint = (checkint << 8) + random_byte();
1818     p += put_uint32(p, checkint);
1819     p += put_uint32(p, checkint);
1820
1821     /* Private key. The main private blob goes inline, with no string
1822      * wrapper. */
1823     p += put_string_z(p, key->alg->name);
1824     memcpy(p, privblob, privlen);
1825     p += privlen;
1826
1827     /* Comment. */
1828     p += put_string_z(p, key->comment);
1829
1830     /* Pad out the encrypted section. */
1831     padvalue = 1;
1832     do {
1833         *p++ = padvalue++;
1834     } while ((p - private_section_start) & 15);
1835
1836     assert(p - outblob < maxsize);
1837
1838     /* Go back and fill in the length field for the private section. */
1839     PUT_32BIT_MSB_FIRST(private_section_length_field,
1840                         p - private_section_start);
1841
1842     if (passphrase) {
1843         /*
1844          * Encrypt the private section. We need 48 bytes of key
1845          * material: 32 bytes AES key + 16 bytes iv.
1846          */
1847         unsigned char keybuf[48];
1848         void *ctx;
1849
1850         openssh_bcrypt(passphrase,
1851                        bcrypt_salt, sizeof(bcrypt_salt), bcrypt_rounds,
1852                        keybuf, sizeof(keybuf));
1853
1854         ctx = aes_make_context();
1855         aes256_key(ctx, keybuf);
1856         aes_iv(ctx, keybuf + 32);
1857         aes_ssh2_encrypt_blk(ctx, private_section_start,
1858                              p - private_section_start);
1859         aes_free_context(ctx);
1860
1861         smemclr(keybuf, sizeof(keybuf));
1862     }
1863
1864     /*
1865      * And save it. We'll use Unix line endings just in case it's
1866      * subsequently transferred in binary mode.
1867      */
1868     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
1869     if (!fp)
1870         goto error;
1871     fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp);
1872     base64_encode(fp, outblob, p - outblob, 64);
1873     fputs("-----END OPENSSH PRIVATE KEY-----\n", fp);
1874     fclose(fp);
1875     ret = 1;
1876
1877     error:
1878     if (outblob) {
1879         smemclr(outblob, maxsize);
1880         sfree(outblob);
1881     }
1882     if (privblob) {
1883         smemclr(privblob, privlen);
1884         sfree(privblob);
1885     }
1886     if (pubblob) {
1887         smemclr(pubblob, publen);
1888         sfree(pubblob);
1889     }
1890     return ret;
1891 }
1892
1893 /* ----------------------------------------------------------------------
1894  * The switch function openssh_auto_write(), which chooses one of the
1895  * concrete OpenSSH output formats based on the key type.
1896  */
1897 int openssh_auto_write(const Filename *filename, struct ssh2_userkey *key,
1898                        char *passphrase)
1899 {
1900     /*
1901      * The old OpenSSH format supports a fixed list of key types. We
1902      * assume that anything not in that fixed list is newer, and hence
1903      * will use the new format.
1904      */
1905     if (key->alg == &ssh_dss ||
1906         key->alg == &ssh_rsa ||
1907         key->alg == &ssh_ecdsa_nistp256 ||
1908         key->alg == &ssh_ecdsa_nistp384 ||
1909         key->alg == &ssh_ecdsa_nistp521)
1910         return openssh_pem_write(filename, key, passphrase);
1911     else
1912         return openssh_new_write(filename, key, passphrase);
1913 }
1914
1915 /* ----------------------------------------------------------------------
1916  * Code to read ssh.com private keys.
1917  */
1918
1919 /*
1920  * The format of the base64 blob is largely SSH-2-packet-formatted,
1921  * except that mpints are a bit different: they're more like the
1922  * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1923  * (N+7)/8 bytes of data.
1924  * 
1925  * So. The blob contains:
1926  * 
1927  *  - uint32 0x3f6ff9eb       (magic number)
1928  *  - uint32 size             (total blob size)
1929  *  - string key-type         (see below)
1930  *  - string cipher-type      (tells you if key is encrypted)
1931  *  - string encrypted-blob
1932  * 
1933  * (The first size field includes the size field itself and the
1934  * magic number before it. All other size fields are ordinary SSH-2
1935  * strings, so the size field indicates how much data is to
1936  * _follow_.)
1937  * 
1938  * The encrypted blob, once decrypted, contains a single string
1939  * which in turn contains the payload. (This allows padding to be
1940  * added after that string while still making it clear where the
1941  * real payload ends. Also it probably makes for a reasonable
1942  * decryption check.)
1943  * 
1944  * The payload blob, for an RSA key, contains:
1945  *  - mpint e
1946  *  - mpint d
1947  *  - mpint n  (yes, the public and private stuff is intermixed)
1948  *  - mpint u  (presumably inverse of p mod q)
1949  *  - mpint p  (p is the smaller prime)
1950  *  - mpint q  (q is the larger)
1951  * 
1952  * For a DSA key, the payload blob contains:
1953  *  - uint32 0
1954  *  - mpint p
1955  *  - mpint g
1956  *  - mpint q
1957  *  - mpint y
1958  *  - mpint x
1959  * 
1960  * Alternatively, if the parameters are `predefined', that
1961  * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1962  * containing some predefined parameter specification. *shudder*,
1963  * but I doubt we'll encounter this in real life.
1964  * 
1965  * The key type strings are ghastly. The RSA key I looked at had a
1966  * type string of
1967  * 
1968  *   `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1969  * 
1970  * and the DSA key wasn't much better:
1971  * 
1972  *   `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1973  * 
1974  * It isn't clear that these will always be the same. I think it
1975  * might be wise just to look at the `if-modn{sign{rsa' and
1976  * `dl-modp{sign{dsa' prefixes.
1977  * 
1978  * Finally, the encryption. The cipher-type string appears to be
1979  * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1980  * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1981  * from the passphrase by means of yet another hashing faff:
1982  * 
1983  *  - first 16 bytes are MD5(passphrase)
1984  *  - next 16 bytes are MD5(passphrase || first 16 bytes)
1985  *  - if there were more, they'd be MD5(passphrase || first 32),
1986  *    and so on.
1987  */
1988
1989 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1990
1991 struct sshcom_key {
1992     char comment[256];                 /* allowing any length is overkill */
1993     unsigned char *keyblob;
1994     int keyblob_len, keyblob_size;
1995 };
1996
1997 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1998                                           const char **errmsg_p)
1999 {
2000     struct sshcom_key *ret;
2001     FILE *fp;
2002     char *line = NULL;
2003     int hdrstart, len;
2004     char *errmsg, *p;
2005     int headers_done;
2006     char base64_bit[4];
2007     int base64_chars = 0;
2008
2009     ret = snew(struct sshcom_key);
2010     ret->comment[0] = '\0';
2011     ret->keyblob = NULL;
2012     ret->keyblob_len = ret->keyblob_size = 0;
2013
2014     fp = f_open(filename, "r", FALSE);
2015     if (!fp) {
2016         errmsg = "unable to open key file";
2017         goto error;
2018     }
2019     if (!(line = fgetline(fp))) {
2020         errmsg = "unexpected end of file";
2021         goto error;
2022     }
2023     strip_crlf(line);
2024     if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
2025         errmsg = "file does not begin with ssh.com key header";
2026         goto error;
2027     }
2028     smemclr(line, strlen(line));
2029     sfree(line);
2030     line = NULL;
2031
2032     headers_done = 0;
2033     while (1) {
2034         if (!(line = fgetline(fp))) {
2035             errmsg = "unexpected end of file";
2036             goto error;
2037         }
2038         strip_crlf(line);
2039         if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
2040             sfree(line);
2041             line = NULL;
2042             break;                     /* done */
2043         }
2044         if ((p = strchr(line, ':')) != NULL) {
2045             if (headers_done) {
2046                 errmsg = "header found in body of key data";
2047                 goto error;
2048             }
2049             *p++ = '\0';
2050             while (*p && isspace((unsigned char)*p)) p++;
2051             hdrstart = p - line;
2052
2053             /*
2054              * Header lines can end in a trailing backslash for
2055              * continuation.
2056              */
2057             len = hdrstart + strlen(line+hdrstart);
2058             assert(!line[len]);
2059             while (line[len-1] == '\\') {
2060                 char *line2;
2061                 int line2len;
2062
2063                 line2 = fgetline(fp);
2064                 if (!line2) {
2065                     errmsg = "unexpected end of file";
2066                     goto error;
2067                 }
2068                 strip_crlf(line2);
2069
2070                 line2len = strlen(line2);
2071                 line = sresize(line, len + line2len + 1, char);
2072                 strcpy(line + len - 1, line2);
2073                 len += line2len - 1;
2074                 assert(!line[len]);
2075
2076                 smemclr(line2, strlen(line2));
2077                 sfree(line2);
2078                 line2 = NULL;
2079             }
2080             p = line + hdrstart;
2081             strip_crlf(p);
2082             if (!strcmp(line, "Comment")) {
2083                 /* Strip quotes in comment if present. */
2084                 if (p[0] == '"' && p[strlen(p)-1] == '"') {
2085                     p++;
2086                     p[strlen(p)-1] = '\0';
2087                 }
2088                 strncpy(ret->comment, p, sizeof(ret->comment));
2089                 ret->comment[sizeof(ret->comment)-1] = '\0';
2090             }
2091         } else {
2092             headers_done = 1;
2093
2094             p = line;
2095             while (isbase64(*p)) {
2096                 base64_bit[base64_chars++] = *p;
2097                 if (base64_chars == 4) {
2098                     unsigned char out[3];
2099
2100                     base64_chars = 0;
2101
2102                     len = base64_decode_atom(base64_bit, out);
2103
2104                     if (len <= 0) {
2105                         errmsg = "invalid base64 encoding";
2106                         goto error;
2107                     }
2108
2109                     if (ret->keyblob_len + len > ret->keyblob_size) {
2110                         ret->keyblob_size = ret->keyblob_len + len + 256;
2111                         ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
2112                                                unsigned char);
2113                     }
2114
2115                     memcpy(ret->keyblob + ret->keyblob_len, out, len);
2116                     ret->keyblob_len += len;
2117                 }
2118
2119                 p++;
2120             }
2121         }
2122         smemclr(line, strlen(line));
2123         sfree(line);
2124         line = NULL;
2125     }
2126
2127     if (ret->keyblob_len == 0 || !ret->keyblob) {
2128         errmsg = "key body not present";
2129         goto error;
2130     }
2131
2132     fclose(fp);
2133     if (errmsg_p) *errmsg_p = NULL;
2134     return ret;
2135
2136     error:
2137     if (fp)
2138         fclose(fp);
2139
2140     if (line) {
2141         smemclr(line, strlen(line));
2142         sfree(line);
2143         line = NULL;
2144     }
2145     if (ret) {
2146         if (ret->keyblob) {
2147             smemclr(ret->keyblob, ret->keyblob_size);
2148             sfree(ret->keyblob);
2149         }
2150         smemclr(ret, sizeof(*ret));
2151         sfree(ret);
2152     }
2153     if (errmsg_p) *errmsg_p = errmsg;
2154     return NULL;
2155 }
2156
2157 int sshcom_encrypted(const Filename *filename, char **comment)
2158 {
2159     struct sshcom_key *key = load_sshcom_key(filename, NULL);
2160     int pos, len, answer;
2161
2162     answer = 0;
2163
2164     *comment = NULL;
2165     if (!key)
2166         goto done;
2167
2168     /*
2169      * Check magic number.
2170      */
2171     if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
2172         goto done;                     /* key is invalid */
2173     }
2174
2175     /*
2176      * Find the cipher-type string.
2177      */
2178     pos = 8;
2179     if (key->keyblob_len < pos+4)
2180         goto done;                     /* key is far too short */
2181     len = toint(GET_32BIT(key->keyblob + pos));
2182     if (len < 0 || len > key->keyblob_len - pos - 4)
2183         goto done;                     /* key is far too short */
2184     pos += 4 + len;                    /* skip key type */
2185     len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
2186     if (len < 0 || len > key->keyblob_len - pos - 4)
2187         goto done;                     /* cipher type string is incomplete */
2188     if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
2189         answer = 1;
2190
2191     done:
2192     if (key) {
2193         *comment = dupstr(key->comment);
2194         smemclr(key->keyblob, key->keyblob_size);
2195         sfree(key->keyblob);
2196         smemclr(key, sizeof(*key));
2197         sfree(key);
2198     } else {
2199         *comment = dupstr("");
2200     }
2201     return answer;
2202 }
2203
2204 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
2205 {
2206     unsigned bits, bytes;
2207     unsigned char *d = (unsigned char *) data;
2208
2209     if (len < 4)
2210         goto error;
2211     bits = GET_32BIT(d);
2212
2213     bytes = (bits + 7) / 8;
2214     if (len < 4+bytes)
2215         goto error;
2216
2217     ret->start = d + 4;
2218     ret->bytes = bytes;
2219     return bytes+4;
2220
2221     error:
2222     ret->start = NULL;
2223     ret->bytes = -1;
2224     return len;                        /* ensure further calls fail as well */
2225 }
2226
2227 static int sshcom_put_mpint(void *target, void *data, int len)
2228 {
2229     unsigned char *d = (unsigned char *)target;
2230     unsigned char *i = (unsigned char *)data;
2231     int bits = len * 8 - 1;
2232
2233     while (bits > 0) {
2234         if (*i & (1 << (bits & 7)))
2235             break;
2236         if (!(bits-- & 7))
2237             i++, len--;
2238     }
2239
2240     PUT_32BIT(d, bits+1);
2241     memcpy(d+4, i, len);
2242     return len+4;
2243 }
2244
2245 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
2246                                  const char **errmsg_p)
2247 {
2248     struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
2249     char *errmsg;
2250     int pos, len;
2251     const char prefix_rsa[] = "if-modn{sign{rsa";
2252     const char prefix_dsa[] = "dl-modp{sign{dsa";
2253     enum { RSA, DSA } type;
2254     int encrypted;
2255     char *ciphertext;
2256     int cipherlen;
2257     struct ssh2_userkey *ret = NULL, *retkey;
2258     const struct ssh_signkey *alg;
2259     unsigned char *blob = NULL;
2260     int blobsize = 0, publen, privlen;
2261
2262     if (!key)
2263         return NULL;
2264
2265     /*
2266      * Check magic number.
2267      */
2268     if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
2269         errmsg = "key does not begin with magic number";
2270         goto error;
2271     }
2272
2273     /*
2274      * Determine the key type.
2275      */
2276     pos = 8;
2277     if (key->keyblob_len < pos+4 ||
2278         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2279         len > key->keyblob_len - pos - 4) {
2280         errmsg = "key blob does not contain a key type string";
2281         goto error;
2282     }
2283     if (len > sizeof(prefix_rsa) - 1 &&
2284         !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
2285         type = RSA;
2286     } else if (len > sizeof(prefix_dsa) - 1 &&
2287         !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
2288         type = DSA;
2289     } else {
2290         errmsg = "key is of unknown type";
2291         goto error;
2292     }
2293     pos += 4+len;
2294
2295     /*
2296      * Determine the cipher type.
2297      */
2298     if (key->keyblob_len < pos+4 ||
2299         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2300         len > key->keyblob_len - pos - 4) {
2301         errmsg = "key blob does not contain a cipher type string";
2302         goto error;
2303     }
2304     if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
2305         encrypted = 0;
2306     else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
2307         encrypted = 1;
2308     else {
2309         errmsg = "key encryption is of unknown type";
2310         goto error;
2311     }
2312     pos += 4+len;
2313
2314     /*
2315      * Get hold of the encrypted part of the key.
2316      */
2317     if (key->keyblob_len < pos+4 ||
2318         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2319         len > key->keyblob_len - pos - 4) {
2320         errmsg = "key blob does not contain actual key data";
2321         goto error;
2322     }
2323     ciphertext = (char *)key->keyblob + pos + 4;
2324     cipherlen = len;
2325     if (cipherlen == 0) {
2326         errmsg = "length of key data is zero";
2327         goto error;
2328     }
2329
2330     /*
2331      * Decrypt it if necessary.
2332      */
2333     if (encrypted) {
2334         /*
2335          * Derive encryption key from passphrase and iv/salt:
2336          * 
2337          *  - let block A equal MD5(passphrase)
2338          *  - let block B equal MD5(passphrase || A)
2339          *  - block C would be MD5(passphrase || A || B) and so on
2340          *  - encryption key is the first N bytes of A || B
2341          */
2342         struct MD5Context md5c;
2343         unsigned char keybuf[32], iv[8];
2344
2345         if (cipherlen % 8 != 0) {
2346             errmsg = "encrypted part of key is not a multiple of cipher block"
2347                 " size";
2348             goto error;
2349         }
2350
2351         MD5Init(&md5c);
2352         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2353         MD5Final(keybuf, &md5c);
2354
2355         MD5Init(&md5c);
2356         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2357         MD5Update(&md5c, keybuf, 16);
2358         MD5Final(keybuf+16, &md5c);
2359
2360         /*
2361          * Now decrypt the key blob.
2362          */
2363         memset(iv, 0, sizeof(iv));
2364         des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2365                                  cipherlen);
2366
2367         smemclr(&md5c, sizeof(md5c));
2368         smemclr(keybuf, sizeof(keybuf));
2369
2370         /*
2371          * Hereafter we return WRONG_PASSPHRASE for any parsing
2372          * error. (But only if we've just tried to decrypt it!
2373          * Returning WRONG_PASSPHRASE for an unencrypted key is
2374          * automatic doom.)
2375          */
2376         if (encrypted)
2377             ret = SSH2_WRONG_PASSPHRASE;
2378     }
2379
2380     /*
2381      * Strip away the containing string to get to the real meat.
2382      */
2383     len = toint(GET_32BIT(ciphertext));
2384     if (len < 0 || len > cipherlen-4) {
2385         errmsg = "containing string was ill-formed";
2386         goto error;
2387     }
2388     ciphertext += 4;
2389     cipherlen = len;
2390
2391     /*
2392      * Now we break down into RSA versus DSA. In either case we'll
2393      * construct public and private blobs in our own format, and
2394      * end up feeding them to alg->createkey().
2395      */
2396     blobsize = cipherlen + 256;
2397     blob = snewn(blobsize, unsigned char);
2398     privlen = 0;
2399     if (type == RSA) {
2400         struct mpint_pos n, e, d, u, p, q;
2401         int pos = 0;
2402         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
2403         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
2404         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
2405         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
2406         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2407         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2408         if (!q.start) {
2409             errmsg = "key data did not contain six integers";
2410             goto error;
2411         }
2412
2413         alg = &ssh_rsa;
2414         pos = 0;
2415         pos += put_string(blob+pos, "ssh-rsa", 7);
2416         pos += put_mp(blob+pos, e.start, e.bytes);
2417         pos += put_mp(blob+pos, n.start, n.bytes);
2418         publen = pos;
2419         pos += put_string(blob+pos, d.start, d.bytes);
2420         pos += put_mp(blob+pos, q.start, q.bytes);
2421         pos += put_mp(blob+pos, p.start, p.bytes);
2422         pos += put_mp(blob+pos, u.start, u.bytes);
2423         privlen = pos - publen;
2424     } else {
2425         struct mpint_pos p, q, g, x, y;
2426         int pos = 4;
2427
2428         assert(type == DSA); /* the only other option from the if above */
2429
2430         if (GET_32BIT(ciphertext) != 0) {
2431             errmsg = "predefined DSA parameters not supported";
2432             goto error;
2433         }
2434         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2435         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
2436         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2437         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
2438         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
2439         if (!x.start) {
2440             errmsg = "key data did not contain five integers";
2441             goto error;
2442         }
2443
2444         alg = &ssh_dss;
2445         pos = 0;
2446         pos += put_string(blob+pos, "ssh-dss", 7);
2447         pos += put_mp(blob+pos, p.start, p.bytes);
2448         pos += put_mp(blob+pos, q.start, q.bytes);
2449         pos += put_mp(blob+pos, g.start, g.bytes);
2450         pos += put_mp(blob+pos, y.start, y.bytes);
2451         publen = pos;
2452         pos += put_mp(blob+pos, x.start, x.bytes);
2453         privlen = pos - publen;
2454     }
2455
2456     assert(privlen > 0);               /* should have bombed by now if not */
2457
2458     retkey = snew(struct ssh2_userkey);
2459     retkey->alg = alg;
2460     retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
2461     if (!retkey->data) {
2462         sfree(retkey);
2463         errmsg = "unable to create key data structure";
2464         goto error;
2465     }
2466     retkey->comment = dupstr(key->comment);
2467
2468     errmsg = NULL; /* no error */
2469     ret = retkey;
2470
2471     error:
2472     if (blob) {
2473         smemclr(blob, blobsize);
2474         sfree(blob);
2475     }
2476     smemclr(key->keyblob, key->keyblob_size);
2477     sfree(key->keyblob);
2478     smemclr(key, sizeof(*key));
2479     sfree(key);
2480     if (errmsg_p) *errmsg_p = errmsg;
2481     return ret;
2482 }
2483
2484 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
2485                  char *passphrase)
2486 {
2487     unsigned char *pubblob, *privblob;
2488     int publen, privlen;
2489     unsigned char *outblob;
2490     int outlen;
2491     struct mpint_pos numbers[6];
2492     int nnumbers, initial_zero, pos, lenpos, i;
2493     char *type;
2494     char *ciphertext;
2495     int cipherlen;
2496     int ret = 0;
2497     FILE *fp;
2498
2499     /*
2500      * Fetch the key blobs.
2501      */
2502     pubblob = key->alg->public_blob(key->data, &publen);
2503     privblob = key->alg->private_blob(key->data, &privlen);
2504     outblob = NULL;
2505
2506     /*
2507      * Find the sequence of integers to be encoded into the OpenSSH
2508      * key blob, and also decide on the header line.
2509      */
2510     if (key->alg == &ssh_rsa) {
2511         int pos;
2512         struct mpint_pos n, e, d, p, q, iqmp;
2513
2514         /*
2515          * These blobs were generated from inside PuTTY, so we needn't
2516          * treat them as untrusted.
2517          */
2518         pos = 4 + GET_32BIT(pubblob);
2519         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
2520         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
2521         pos = 0;
2522         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
2523         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
2524         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
2525         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
2526
2527         assert(e.start && iqmp.start); /* can't go wrong */
2528
2529         numbers[0] = e;
2530         numbers[1] = d;
2531         numbers[2] = n;
2532         numbers[3] = iqmp;
2533         numbers[4] = q;
2534         numbers[5] = p;
2535
2536         nnumbers = 6;
2537         initial_zero = 0;
2538         type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
2539     } else if (key->alg == &ssh_dss) {
2540         int pos;
2541         struct mpint_pos p, q, g, y, x;
2542
2543         /*
2544          * These blobs were generated from inside PuTTY, so we needn't
2545          * treat them as untrusted.
2546          */
2547         pos = 4 + GET_32BIT(pubblob);
2548         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
2549         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
2550         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
2551         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
2552         pos = 0;
2553         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
2554
2555         assert(y.start && x.start); /* can't go wrong */
2556
2557         numbers[0] = p;
2558         numbers[1] = g;
2559         numbers[2] = q;
2560         numbers[3] = y;
2561         numbers[4] = x;
2562
2563         nnumbers = 5;
2564         initial_zero = 1;
2565         type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
2566     } else {
2567         assert(0);                     /* zoinks! */
2568         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
2569     }
2570
2571     /*
2572      * Total size of key blob will be somewhere under 512 plus
2573      * combined length of integers. We'll calculate the more
2574      * precise size as we construct the blob.
2575      */
2576     outlen = 512;
2577     for (i = 0; i < nnumbers; i++)
2578         outlen += 4 + numbers[i].bytes;
2579     outblob = snewn(outlen, unsigned char);
2580
2581     /*
2582      * Create the unencrypted key blob.
2583      */
2584     pos = 0;
2585     PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
2586     pos += 4;                          /* length field, fill in later */
2587     pos += put_string(outblob+pos, type, strlen(type));
2588     {
2589         char *ciphertype = passphrase ? "3des-cbc" : "none";
2590         pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
2591     }
2592     lenpos = pos;                      /* remember this position */
2593     pos += 4;                          /* encrypted-blob size */
2594     pos += 4;                          /* encrypted-payload size */
2595     if (initial_zero) {
2596         PUT_32BIT(outblob+pos, 0);
2597         pos += 4;
2598     }
2599     for (i = 0; i < nnumbers; i++)
2600         pos += sshcom_put_mpint(outblob+pos,
2601                                 numbers[i].start, numbers[i].bytes);
2602     /* Now wrap up the encrypted payload. */
2603     PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
2604     /* Pad encrypted blob to a multiple of cipher block size. */
2605     if (passphrase) {
2606         int padding = -(pos - (lenpos+4)) & 7;
2607         while (padding--)
2608             outblob[pos++] = random_byte();
2609     }
2610     ciphertext = (char *)outblob+lenpos+4;
2611     cipherlen = pos - (lenpos+4);
2612     assert(!passphrase || cipherlen % 8 == 0);
2613     /* Wrap up the encrypted blob string. */
2614     PUT_32BIT(outblob+lenpos, cipherlen);
2615     /* And finally fill in the total length field. */
2616     PUT_32BIT(outblob+4, pos);
2617
2618     assert(pos < outlen);
2619
2620     /*
2621      * Encrypt the key.
2622      */
2623     if (passphrase) {
2624         /*
2625          * Derive encryption key from passphrase and iv/salt:
2626          * 
2627          *  - let block A equal MD5(passphrase)
2628          *  - let block B equal MD5(passphrase || A)
2629          *  - block C would be MD5(passphrase || A || B) and so on
2630          *  - encryption key is the first N bytes of A || B
2631          */
2632         struct MD5Context md5c;
2633         unsigned char keybuf[32], iv[8];
2634
2635         MD5Init(&md5c);
2636         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2637         MD5Final(keybuf, &md5c);
2638
2639         MD5Init(&md5c);
2640         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2641         MD5Update(&md5c, keybuf, 16);
2642         MD5Final(keybuf+16, &md5c);
2643
2644         /*
2645          * Now decrypt the key blob.
2646          */
2647         memset(iv, 0, sizeof(iv));
2648         des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2649                                  cipherlen);
2650
2651         smemclr(&md5c, sizeof(md5c));
2652         smemclr(keybuf, sizeof(keybuf));
2653     }
2654
2655     /*
2656      * And save it. We'll use Unix line endings just in case it's
2657      * subsequently transferred in binary mode.
2658      */
2659     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
2660     if (!fp)
2661         goto error;
2662     fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2663     fprintf(fp, "Comment: \"");
2664     /*
2665      * Comment header is broken with backslash-newline if it goes
2666      * over 70 chars. Although it's surrounded by quotes, it
2667      * _doesn't_ escape backslashes or quotes within the string.
2668      * Don't ask me, I didn't design it.
2669      */
2670     {
2671         int slen = 60;                 /* starts at 60 due to "Comment: " */
2672         char *c = key->comment;
2673         while ((int)strlen(c) > slen) {
2674             fprintf(fp, "%.*s\\\n", slen, c);
2675             c += slen;
2676             slen = 70;                 /* allow 70 chars on subsequent lines */
2677         }
2678         fprintf(fp, "%s\"\n", c);
2679     }
2680     base64_encode(fp, outblob, pos, 70);
2681     fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2682     fclose(fp);
2683     ret = 1;
2684
2685     error:
2686     if (outblob) {
2687         smemclr(outblob, outlen);
2688         sfree(outblob);
2689     }
2690     if (privblob) {
2691         smemclr(privblob, privlen);
2692         sfree(privblob);
2693     }
2694     if (pubblob) {
2695         smemclr(pubblob, publen);
2696         sfree(pubblob);
2697     }
2698     return ret;
2699 }