]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - import.c
Pass the ssh_signkey structure itself to public key methods.
[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(retkey->alg,
781                                               blob, 4+19+4+8+4+len,
782                                               blob+4+19+4+8+4+len,
783                                               4+privlen);
784         if (!retkey->data) {
785             sfree(retkey);
786             errmsg = "unable to create key data structure";
787             goto error;
788         }
789
790     } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
791
792         /*
793          * Space to create key blob in.
794          */
795         blobsize = 256+key->keyblob_len;
796         blob = snewn(blobsize, unsigned char);
797         PUT_32BIT(blob, 7);
798         if (key->keytype == OP_DSA)
799             memcpy(blob+4, "ssh-dss", 7);
800         else if (key->keytype == OP_RSA)
801             memcpy(blob+4, "ssh-rsa", 7);
802         blobptr = 4+7;
803         privptr = -1;
804
805         for (i = 0; i < num_integers; i++) {
806             ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
807                                   &id, &len, &flags);
808             p += ret;
809             if (ret < 0 || id != 2 ||
810                 key->keyblob+key->keyblob_len-p < len) {
811                 errmsg = "ASN.1 decoding failure";
812                 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
813                 goto error;
814             }
815
816             if (i == 0) {
817                 /*
818                  * The first integer should be zero always (I think
819                  * this is some sort of version indication).
820                  */
821                 if (len != 1 || p[0] != 0) {
822                     errmsg = "version number mismatch";
823                     goto error;
824                 }
825             } else if (key->keytype == OP_RSA) {
826                 /*
827                  * Integers 1 and 2 go into the public blob but in the
828                  * opposite order; integers 3, 4, 5 and 8 go into the
829                  * private blob. The other two (6 and 7) are ignored.
830                  */
831                 if (i == 1) {
832                     /* Save the details for after we deal with number 2. */
833                     modptr = (char *)p;
834                     modlen = len;
835                 } else if (i != 6 && i != 7) {
836                     PUT_32BIT(blob+blobptr, len);
837                     memcpy(blob+blobptr+4, p, len);
838                     blobptr += 4+len;
839                     if (i == 2) {
840                         PUT_32BIT(blob+blobptr, modlen);
841                         memcpy(blob+blobptr+4, modptr, modlen);
842                         blobptr += 4+modlen;
843                         privptr = blobptr;
844                     }
845                 }
846             } else if (key->keytype == OP_DSA) {
847                 /*
848                  * Integers 1-4 go into the public blob; integer 5 goes
849                  * into the private blob.
850                  */
851                 PUT_32BIT(blob+blobptr, len);
852                 memcpy(blob+blobptr+4, p, len);
853                 blobptr += 4+len;
854                 if (i == 4)
855                     privptr = blobptr;
856             }
857
858             /* Skip past the number. */
859             p += len;
860         }
861
862         /*
863          * Now put together the actual key. Simplest way to do this is
864          * to assemble our own key blobs and feed them to the createkey
865          * functions; this is a bit faffy but it does mean we get all
866          * the sanity checks for free.
867          */
868         assert(privptr > 0);          /* should have bombed by now if not */
869         retkey = snew(struct ssh2_userkey);
870         retkey->alg = (key->keytype == OP_RSA ? &ssh_rsa : &ssh_dss);
871         retkey->data = retkey->alg->createkey(retkey->alg, blob, privptr,
872                                               blob+privptr,
873                                               blobptr-privptr);
874         if (!retkey->data) {
875             sfree(retkey);
876             errmsg = "unable to create key data structure";
877             goto error;
878         }
879
880     } else {
881         assert(0 && "Bad key type from load_openssh_pem_key");
882     }
883
884     /*
885      * The old key format doesn't include a comment in the private
886      * key file.
887      */
888     retkey->comment = dupstr("imported-openssh-key");
889
890     errmsg = NULL;                     /* no error */
891     retval = retkey;
892
893     error:
894     if (blob) {
895         smemclr(blob, blobsize);
896         sfree(blob);
897     }
898     smemclr(key->keyblob, key->keyblob_size);
899     sfree(key->keyblob);
900     smemclr(key, sizeof(*key));
901     sfree(key);
902     if (errmsg_p) *errmsg_p = errmsg;
903     return retval;
904 }
905
906 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
907                       char *passphrase)
908 {
909     unsigned char *pubblob, *privblob, *spareblob;
910     int publen, privlen, sparelen = 0;
911     unsigned char *outblob;
912     int outlen;
913     struct mpint_pos numbers[9];
914     int nnumbers, pos, len, seqlen, i;
915     char *header, *footer;
916     char zero[1];
917     unsigned char iv[8];
918     int ret = 0;
919     FILE *fp;
920
921     /*
922      * Fetch the key blobs.
923      */
924     pubblob = key->alg->public_blob(key->data, &publen);
925     privblob = key->alg->private_blob(key->data, &privlen);
926     spareblob = outblob = NULL;
927
928     outblob = NULL;
929     len = 0;
930
931     /*
932      * Encode the OpenSSH key blob, and also decide on the header
933      * line.
934      */
935     if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
936         /*
937          * The RSA and DSS handlers share some code because the two
938          * key types have very similar ASN.1 representations, as a
939          * plain SEQUENCE of big integers. So we set up a list of
940          * bignums per key type and then construct the actual blob in
941          * common code after that.
942          */
943         if (key->alg == &ssh_rsa) {
944             int pos;
945             struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
946             Bignum bd, bp, bq, bdmp1, bdmq1;
947
948             /*
949              * These blobs were generated from inside PuTTY, so we needn't
950              * treat them as untrusted.
951              */
952             pos = 4 + GET_32BIT(pubblob);
953             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
954             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
955             pos = 0;
956             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
957             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
958             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
959             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
960
961             assert(e.start && iqmp.start); /* can't go wrong */
962
963             /* We also need d mod (p-1) and d mod (q-1). */
964             bd = bignum_from_bytes(d.start, d.bytes);
965             bp = bignum_from_bytes(p.start, p.bytes);
966             bq = bignum_from_bytes(q.start, q.bytes);
967             decbn(bp);
968             decbn(bq);
969             bdmp1 = bigmod(bd, bp);
970             bdmq1 = bigmod(bd, bq);
971             freebn(bd);
972             freebn(bp);
973             freebn(bq);
974
975             dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
976             dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
977             sparelen = dmp1.bytes + dmq1.bytes;
978             spareblob = snewn(sparelen, unsigned char);
979             dmp1.start = spareblob;
980             dmq1.start = spareblob + dmp1.bytes;
981             for (i = 0; i < dmp1.bytes; i++)
982                 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
983             for (i = 0; i < dmq1.bytes; i++)
984                 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
985             freebn(bdmp1);
986             freebn(bdmq1);
987
988             numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
989             numbers[1] = n;
990             numbers[2] = e;
991             numbers[3] = d;
992             numbers[4] = p;
993             numbers[5] = q;
994             numbers[6] = dmp1;
995             numbers[7] = dmq1;
996             numbers[8] = iqmp;
997
998             nnumbers = 9;
999             header = "-----BEGIN RSA PRIVATE KEY-----\n";
1000             footer = "-----END RSA PRIVATE KEY-----\n";
1001         } else {                       /* ssh-dss */
1002             int pos;
1003             struct mpint_pos p, q, g, y, x;
1004
1005             /*
1006              * These blobs were generated from inside PuTTY, so we needn't
1007              * treat them as untrusted.
1008              */
1009             pos = 4 + GET_32BIT(pubblob);
1010             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1011             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1012             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1013             pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1014             pos = 0;
1015             pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1016
1017             assert(y.start && x.start); /* can't go wrong */
1018
1019             numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1020             numbers[1] = p;
1021             numbers[2] = q;
1022             numbers[3] = g;
1023             numbers[4] = y;
1024             numbers[5] = x;
1025
1026             nnumbers = 6;
1027             header = "-----BEGIN DSA PRIVATE KEY-----\n";
1028             footer = "-----END DSA PRIVATE KEY-----\n";
1029         }
1030
1031         /*
1032          * Now count up the total size of the ASN.1 encoded integers,
1033          * so as to determine the length of the containing SEQUENCE.
1034          */
1035         len = 0;
1036         for (i = 0; i < nnumbers; i++) {
1037             len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
1038             len += numbers[i].bytes;
1039         }
1040         seqlen = len;
1041         /* Now add on the SEQUENCE header. */
1042         len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1043
1044         /*
1045          * Now we know how big outblob needs to be. Allocate it.
1046          */
1047         outblob = snewn(len, unsigned char);
1048
1049         /*
1050          * And write the data into it.
1051          */
1052         pos = 0;
1053         pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1054         for (i = 0; i < nnumbers; i++) {
1055             pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
1056             memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
1057             pos += numbers[i].bytes;
1058         }
1059     } else if (key->alg == &ssh_ecdsa_nistp256 ||
1060                key->alg == &ssh_ecdsa_nistp384 ||
1061                key->alg == &ssh_ecdsa_nistp521) {
1062         unsigned char *oid;
1063         int oidlen;
1064         int pointlen;
1065
1066         /*
1067          * Structure of asn1:
1068          * SEQUENCE
1069          *   INTEGER 1
1070          *   OCTET STRING (private key)
1071          *   [0]
1072          *     OID (curve)
1073          *   [1]
1074          *     BIT STRING (0x00 public key point)
1075          */
1076         switch (((struct ec_key *)key->data)->publicKey.curve->fieldBits) {
1077           case 256:
1078             /* OID: 1.2.840.10045.3.1.7 (ansiX9p256r1) */
1079             oid = nistp256_oid;
1080             oidlen = nistp256_oid_len;
1081             pointlen = 32 * 2;
1082             break;
1083           case 384:
1084             /* OID: 1.3.132.0.34 (secp384r1) */
1085             oid = nistp384_oid;
1086             oidlen = nistp384_oid_len;
1087             pointlen = 48 * 2;
1088             break;
1089           case 521:
1090             /* OID: 1.3.132.0.35 (secp521r1) */
1091             oid = nistp521_oid;
1092             oidlen = nistp521_oid_len;
1093             pointlen = 66 * 2;
1094             break;
1095           default:
1096             assert(0);
1097         }
1098
1099         len = ber_write_id_len(NULL, 2, 1, 0);
1100         len += 1;
1101         len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1102         len+= privlen - 4;
1103         len += ber_write_id_len(NULL, 0, oidlen +
1104                                 ber_write_id_len(NULL, 6, oidlen, 0),
1105                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1106         len += ber_write_id_len(NULL, 6, oidlen, 0);
1107         len += oidlen;
1108         len += ber_write_id_len(NULL, 1, 2 + pointlen +
1109                                 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1110                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1111         len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1112         len += 2 + pointlen;
1113
1114         seqlen = len;
1115         len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1116
1117         outblob = snewn(len, unsigned char);
1118         assert(outblob);
1119
1120         pos = 0;
1121         pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1122         pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1123         outblob[pos++] = 1;
1124         pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1125         memcpy(outblob+pos, privblob + 4, privlen - 4);
1126         pos += privlen - 4;
1127         pos += ber_write_id_len(outblob+pos, 0, oidlen +
1128                                 ber_write_id_len(NULL, 6, oidlen, 0),
1129                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1130         pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1131         memcpy(outblob+pos, oid, oidlen);
1132         pos += oidlen;
1133         pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1134                                 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1135                                 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1136         pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1137         outblob[pos++] = 0;
1138         memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1139         pos += 1 + pointlen;
1140
1141         header = "-----BEGIN EC PRIVATE KEY-----\n";
1142         footer = "-----END EC PRIVATE KEY-----\n";
1143     } else {
1144         assert(0);                     /* zoinks! */
1145         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1146     }
1147
1148     /*
1149      * Encrypt the key.
1150      *
1151      * For the moment, we still encrypt our OpenSSH keys using
1152      * old-style 3DES.
1153      */
1154     if (passphrase) {
1155         struct MD5Context md5c;
1156         unsigned char keybuf[32];
1157
1158         /*
1159          * Round up to the cipher block size, ensuring we have at
1160          * least one byte of padding (see below).
1161          */
1162         outlen = (len+8) &~ 7;
1163         {
1164             unsigned char *tmp = snewn(outlen, unsigned char);
1165             memcpy(tmp, outblob, len);
1166             smemclr(outblob, len);
1167             sfree(outblob);
1168             outblob = tmp;
1169         }
1170
1171         /*
1172          * Padding on OpenSSH keys is deterministic. The number of
1173          * padding bytes is always more than zero, and always at most
1174          * the cipher block length. The value of each padding byte is
1175          * equal to the number of padding bytes. So a plaintext that's
1176          * an exact multiple of the block size will be padded with 08
1177          * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1178          * plaintext one byte less than a multiple of the block size
1179          * will be padded with just 01.
1180          *
1181          * This enables the OpenSSL key decryption function to strip
1182          * off the padding algorithmically and return the unpadded
1183          * plaintext to the next layer: it looks at the final byte, and
1184          * then expects to find that many bytes at the end of the data
1185          * with the same value. Those are all removed and the rest is
1186          * returned.
1187          */
1188         assert(pos == len);
1189         while (pos < outlen) {
1190             outblob[pos++] = outlen - len;
1191         }
1192
1193         /*
1194          * Invent an iv. Then derive encryption key from passphrase
1195          * and iv/salt:
1196          * 
1197          *  - let block A equal MD5(passphrase || iv)
1198          *  - let block B equal MD5(A || passphrase || iv)
1199          *  - block C would be MD5(B || passphrase || iv) and so on
1200          *  - encryption key is the first N bytes of A || B
1201          */
1202         for (i = 0; i < 8; i++) iv[i] = random_byte();
1203
1204         MD5Init(&md5c);
1205         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1206         MD5Update(&md5c, iv, 8);
1207         MD5Final(keybuf, &md5c);
1208
1209         MD5Init(&md5c);
1210         MD5Update(&md5c, keybuf, 16);
1211         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1212         MD5Update(&md5c, iv, 8);
1213         MD5Final(keybuf+16, &md5c);
1214
1215         /*
1216          * Now encrypt the key blob.
1217          */
1218         des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1219
1220         smemclr(&md5c, sizeof(md5c));
1221         smemclr(keybuf, sizeof(keybuf));
1222     } else {
1223         /*
1224          * If no encryption, the blob has exactly its original
1225          * cleartext size.
1226          */
1227         outlen = len;
1228     }
1229
1230     /*
1231      * And save it. We'll use Unix line endings just in case it's
1232      * subsequently transferred in binary mode.
1233      */
1234     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
1235     if (!fp)
1236         goto error;
1237     fputs(header, fp);
1238     if (passphrase) {
1239         fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1240         for (i = 0; i < 8; i++)
1241             fprintf(fp, "%02X", iv[i]);
1242         fprintf(fp, "\n\n");
1243     }
1244     base64_encode(fp, outblob, outlen, 64);
1245     fputs(footer, fp);
1246     fclose(fp);
1247     ret = 1;
1248
1249     error:
1250     if (outblob) {
1251         smemclr(outblob, outlen);
1252         sfree(outblob);
1253     }
1254     if (spareblob) {
1255         smemclr(spareblob, sparelen);
1256         sfree(spareblob);
1257     }
1258     if (privblob) {
1259         smemclr(privblob, privlen);
1260         sfree(privblob);
1261     }
1262     if (pubblob) {
1263         smemclr(pubblob, publen);
1264         sfree(pubblob);
1265     }
1266     return ret;
1267 }
1268
1269 /* ----------------------------------------------------------------------
1270  * Code to read and write OpenSSH private keys in the new-style format.
1271  */
1272
1273 typedef enum {
1274     ON_E_NONE, ON_E_AES256CBC
1275 } openssh_new_cipher;
1276 typedef enum {
1277     ON_K_NONE, ON_K_BCRYPT
1278 } openssh_new_kdf;
1279
1280 struct openssh_new_key {
1281     openssh_new_cipher cipher;
1282     openssh_new_kdf kdf;
1283     union {
1284         struct {
1285             int rounds;
1286             /* This points to a position within keyblob, not a
1287              * separately allocated thing */
1288             const unsigned char *salt;
1289             int saltlen;
1290         } bcrypt;
1291     } kdfopts;
1292     int nkeys, key_wanted;
1293     /* This too points to a position within keyblob */
1294     unsigned char *privatestr;
1295     int privatelen;
1296
1297     unsigned char *keyblob;
1298     int keyblob_len, keyblob_size;
1299 };
1300
1301 static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
1302                                                     const char **errmsg_p)
1303 {
1304     struct openssh_new_key *ret;
1305     FILE *fp = NULL;
1306     char *line = NULL;
1307     char *errmsg, *p;
1308     char base64_bit[4];
1309     int base64_chars = 0;
1310     const void *filedata;
1311     int filelen;
1312     const void *string, *kdfopts, *bcryptsalt, *pubkey;
1313     int stringlen, kdfoptlen, bcryptsaltlen, pubkeylen;
1314     unsigned bcryptrounds, nkeys, key_index;
1315
1316     ret = snew(struct openssh_new_key);
1317     ret->keyblob = NULL;
1318     ret->keyblob_len = ret->keyblob_size = 0;
1319
1320     fp = f_open(filename, "r", FALSE);
1321     if (!fp) {
1322         errmsg = "unable to open key file";
1323         goto error;
1324     }
1325
1326     if (!(line = fgetline(fp))) {
1327         errmsg = "unexpected end of file";
1328         goto error;
1329     }
1330     strip_crlf(line);
1331     if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
1332         errmsg = "file does not begin with OpenSSH new-style key header";
1333         goto error;
1334     }
1335     smemclr(line, strlen(line));
1336     sfree(line);
1337     line = NULL;
1338
1339     while (1) {
1340         if (!(line = fgetline(fp))) {
1341             errmsg = "unexpected end of file";
1342             goto error;
1343         }
1344         strip_crlf(line);
1345         if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
1346             sfree(line);
1347             line = NULL;
1348             break;                     /* done */
1349         }
1350
1351         p = line;
1352         while (isbase64(*p)) {
1353             base64_bit[base64_chars++] = *p;
1354             if (base64_chars == 4) {
1355                 unsigned char out[3];
1356                 int len;
1357
1358                 base64_chars = 0;
1359
1360                 len = base64_decode_atom(base64_bit, out);
1361
1362                 if (len <= 0) {
1363                     errmsg = "invalid base64 encoding";
1364                     goto error;
1365                 }
1366
1367                 if (ret->keyblob_len + len > ret->keyblob_size) {
1368                     ret->keyblob_size = ret->keyblob_len + len + 256;
1369                     ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1370                                            unsigned char);
1371                 }
1372
1373                 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1374                 ret->keyblob_len += len;
1375
1376                 smemclr(out, sizeof(out));
1377             }
1378
1379             p++;
1380         }
1381         smemclr(line, strlen(line));
1382         sfree(line);
1383         line = NULL;
1384     }
1385
1386     fclose(fp);
1387     fp = NULL;
1388
1389     if (ret->keyblob_len == 0 || !ret->keyblob) {
1390         errmsg = "key body not present";
1391         goto error;
1392     }
1393
1394     filedata = ret->keyblob;
1395     filelen = ret->keyblob_len;
1396
1397     if (filelen < 15 || 0 != memcmp(filedata, "openssh-key-v1\0", 15)) {
1398         errmsg = "new-style OpenSSH magic number missing\n";
1399         goto error;
1400     }
1401     filedata = (const char *)filedata + 15;
1402     filelen -= 15;
1403
1404     if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1405         errmsg = "encountered EOF before cipher name\n";
1406         goto error;
1407     }
1408     if (match_ssh_id(stringlen, string, "none")) {
1409         ret->cipher = ON_E_NONE;
1410     } else if (match_ssh_id(stringlen, string, "aes256-cbc")) {
1411         ret->cipher = ON_E_AES256CBC;
1412     } else {
1413         errmsg = "unrecognised cipher name\n";
1414         goto error;
1415     }
1416
1417     if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1418         errmsg = "encountered EOF before kdf name\n";
1419         goto error;
1420     }
1421     if (match_ssh_id(stringlen, string, "none")) {
1422         ret->kdf = ON_K_NONE;
1423     } else if (match_ssh_id(stringlen, string, "bcrypt")) {
1424         ret->kdf = ON_K_BCRYPT;
1425     } else {
1426         errmsg = "unrecognised kdf name\n";
1427         goto error;
1428     }
1429
1430     if (!(kdfopts = get_ssh_string(&filelen, &filedata, &kdfoptlen))) {
1431         errmsg = "encountered EOF before kdf options\n";
1432         goto error;
1433     }
1434     switch (ret->kdf) {
1435       case ON_K_NONE:
1436         if (kdfoptlen != 0) {
1437             errmsg = "expected empty options string for 'none' kdf";
1438             goto error;
1439         }
1440         break;
1441       case ON_K_BCRYPT:
1442         if (!(bcryptsalt = get_ssh_string(&kdfoptlen, &kdfopts,
1443                                           &bcryptsaltlen))) {
1444             errmsg = "bcrypt options string did not contain salt\n";
1445             goto error;
1446         }
1447         if (!get_ssh_uint32(&kdfoptlen, &kdfopts, &bcryptrounds)) {
1448             errmsg = "bcrypt options string did not contain round count\n";
1449             goto error;
1450         }
1451         ret->kdfopts.bcrypt.salt = bcryptsalt;
1452         ret->kdfopts.bcrypt.saltlen = bcryptsaltlen;
1453         ret->kdfopts.bcrypt.rounds = bcryptrounds;
1454         break;
1455     }
1456
1457     /*
1458      * At this point we expect a uint32 saying how many keys are
1459      * stored in this file. OpenSSH new-style key files can
1460      * contain more than one. Currently we don't have any user
1461      * interface to specify which one we're trying to extract, so
1462      * we just bomb out with an error if more than one is found in
1463      * the file. However, I've put in all the mechanism here to
1464      * extract the nth one for a given n, in case we later connect
1465      * up some UI to that mechanism. Just arrange that the
1466      * 'key_wanted' field is set to a value in the range [0,
1467      * nkeys) by some mechanism.
1468      */
1469     if (!get_ssh_uint32(&filelen, &filedata, &nkeys)) {
1470         errmsg = "encountered EOF before key count\n";
1471         goto error;
1472     }
1473     if (nkeys != 1) {
1474         errmsg = "multiple keys in new-style OpenSSH key file "
1475             "not supported\n";
1476         goto error;
1477     }
1478     ret->nkeys = nkeys;
1479     ret->key_wanted = 0;
1480
1481     for (key_index = 0; key_index < nkeys; key_index++) {
1482         if (!(pubkey = get_ssh_string(&filelen, &filedata, &pubkeylen))) {
1483             errmsg = "encountered EOF before kdf options\n";
1484             goto error;
1485         }
1486     }
1487
1488     /*
1489      * Now we expect a string containing the encrypted part of the
1490      * key file.
1491      */
1492     if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1493         errmsg = "encountered EOF before private key container\n";
1494         goto error;
1495     }
1496     ret->privatestr = (unsigned char *)string;
1497     ret->privatelen = stringlen;
1498
1499     /*
1500      * And now we're done, until asked to actually decrypt.
1501      */
1502
1503     smemclr(base64_bit, sizeof(base64_bit));
1504     if (errmsg_p) *errmsg_p = NULL;
1505     return ret;
1506
1507     error:
1508     if (line) {
1509         smemclr(line, strlen(line));
1510         sfree(line);
1511         line = NULL;
1512     }
1513     smemclr(base64_bit, sizeof(base64_bit));
1514     if (ret) {
1515         if (ret->keyblob) {
1516             smemclr(ret->keyblob, ret->keyblob_size);
1517             sfree(ret->keyblob);
1518         }
1519         smemclr(ret, sizeof(*ret));
1520         sfree(ret);
1521     }
1522     if (errmsg_p) *errmsg_p = errmsg;
1523     if (fp) fclose(fp);
1524     return NULL;
1525 }
1526
1527 int openssh_new_encrypted(const Filename *filename)
1528 {
1529     struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
1530     int ret;
1531
1532     if (!key)
1533         return 0;
1534     ret = (key->cipher != ON_E_NONE);
1535     smemclr(key->keyblob, key->keyblob_size);
1536     sfree(key->keyblob);
1537     smemclr(key, sizeof(*key));
1538     sfree(key);
1539     return ret;
1540 }
1541
1542 struct ssh2_userkey *openssh_new_read(const Filename *filename,
1543                                       char *passphrase,
1544                                       const char **errmsg_p)
1545 {
1546     struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
1547     struct ssh2_userkey *retkey;
1548     int i;
1549     struct ssh2_userkey *retval = NULL;
1550     char *errmsg;
1551     unsigned char *blob;
1552     int blobsize = 0;
1553     unsigned checkint0, checkint1;
1554     const void *priv, *string;
1555     int privlen, stringlen, key_index;
1556     const struct ssh_signkey *alg;
1557
1558     blob = NULL;
1559
1560     if (!key)
1561         return NULL;
1562
1563     if (key->cipher != ON_E_NONE) {
1564         unsigned char keybuf[48];
1565         int keysize;
1566
1567         /*
1568          * Construct the decryption key, and decrypt the string.
1569          */
1570         switch (key->cipher) {
1571           case ON_E_NONE:
1572             keysize = 0;
1573             break;
1574           case ON_E_AES256CBC:
1575             keysize = 48;              /* 32 byte key + 16 byte IV */
1576             break;
1577           default:
1578             assert(0 && "Bad cipher enumeration value");
1579         }
1580         assert(keysize <= sizeof(keybuf));
1581         switch (key->kdf) {
1582           case ON_K_NONE:
1583             memset(keybuf, 0, keysize);
1584             break;
1585           case ON_K_BCRYPT:
1586             openssh_bcrypt(passphrase,
1587                            key->kdfopts.bcrypt.salt,
1588                            key->kdfopts.bcrypt.saltlen,
1589                            key->kdfopts.bcrypt.rounds,
1590                            keybuf, keysize);
1591             break;
1592           default:
1593             assert(0 && "Bad kdf enumeration value");
1594         }
1595         switch (key->cipher) {
1596           case ON_E_NONE:
1597             break;
1598           case ON_E_AES256CBC:
1599             if (key->privatelen % 16 != 0) {
1600                 errmsg = "private key container length is not a"
1601                     " multiple of AES block size\n";
1602                 goto error;
1603             }
1604             {
1605                 void *ctx = aes_make_context();
1606                 aes256_key(ctx, keybuf);
1607                 aes_iv(ctx, keybuf + 32);
1608                 aes_ssh2_decrypt_blk(ctx, key->privatestr,
1609                                      key->privatelen);
1610                 aes_free_context(ctx);
1611             }
1612             break;
1613           default:
1614             assert(0 && "Bad cipher enumeration value");
1615         }
1616     }
1617
1618     /*
1619      * Now parse the entire encrypted section, and extract the key
1620      * identified by key_wanted.
1621      */
1622     priv = key->privatestr;
1623     privlen = key->privatelen;
1624
1625     if (!get_ssh_uint32(&privlen, &priv, &checkint0) ||
1626         !get_ssh_uint32(&privlen, &priv, &checkint1) ||
1627         checkint0 != checkint1) {
1628         errmsg = "decryption check failed";
1629         goto error;
1630     }
1631
1632     retkey = NULL;
1633     for (key_index = 0; key_index < key->nkeys; key_index++) {
1634         const unsigned char *thiskey;
1635         int thiskeylen;
1636
1637         /*
1638          * Read the key type, which will tell us how to scan over
1639          * the key to get to the next one.
1640          */
1641         if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1642             errmsg = "expected key type in private string";
1643             goto error;
1644         }
1645
1646         /*
1647          * Preliminary key type identification, and decide how
1648          * many pieces of key we expect to see. Currently
1649          * (conveniently) all key types can be seen as some number
1650          * of strings, so we just need to know how many of them to
1651          * skip over. (The numbers below exclude the key comment.)
1652          */
1653         {
1654             /* find_pubkey_alg needs a zero-terminated copy of the
1655              * algorithm name */
1656             char *name_zt = dupprintf("%.*s", stringlen, (char *)string);
1657             alg = find_pubkey_alg(name_zt);
1658             sfree(name_zt);
1659         }
1660
1661         if (!alg) {
1662             errmsg = "private key type not recognised\n";
1663             goto error;
1664         }
1665
1666         thiskey = priv;
1667
1668         /*
1669          * Skip over the pieces of key.
1670          */
1671         for (i = 0; i < alg->openssh_private_npieces; i++) {
1672             if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1673                 errmsg = "ran out of data in mid-private-key";
1674                 goto error;
1675             }
1676         }
1677
1678         thiskeylen = (int)((const unsigned char *)priv -
1679                            (const unsigned char *)thiskey);
1680         if (key_index == key->key_wanted) {
1681             retkey = snew(struct ssh2_userkey);
1682             retkey->alg = alg;
1683             retkey->data = alg->openssh_createkey(alg, &thiskey, &thiskeylen);
1684             if (!retkey->data) {
1685                 sfree(retkey);
1686                 errmsg = "unable to create key data structure";
1687                 goto error;
1688             }
1689         }
1690
1691         /*
1692          * Read the key comment.
1693          */
1694         if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1695             errmsg = "ran out of data at key comment";
1696             goto error;
1697         }
1698         if (key_index == key->key_wanted) {
1699             assert(retkey);
1700             retkey->comment = dupprintf("%.*s", stringlen,
1701                                         (const char *)string);
1702         }
1703     }
1704
1705     if (!retkey) {
1706         errmsg = "key index out of range";
1707         goto error;
1708     }
1709
1710     /*
1711      * Now we expect nothing left but padding.
1712      */
1713     for (i = 0; i < privlen; i++) {
1714         if (((const unsigned char *)priv)[i] != (unsigned char)(i+1)) {
1715             errmsg = "padding at end of private string did not match";
1716             goto error;
1717         }
1718     }
1719
1720     errmsg = NULL;                     /* no error */
1721     retval = retkey;
1722
1723     error:
1724     if (blob) {
1725         smemclr(blob, blobsize);
1726         sfree(blob);
1727     }
1728     smemclr(key->keyblob, key->keyblob_size);
1729     sfree(key->keyblob);
1730     smemclr(key, sizeof(*key));
1731     sfree(key);
1732     if (errmsg_p) *errmsg_p = errmsg;
1733     return retval;
1734 }
1735
1736 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
1737                       char *passphrase)
1738 {
1739     unsigned char *pubblob, *privblob, *outblob, *p;
1740     unsigned char *private_section_start, *private_section_length_field;
1741     int publen, privlen, commentlen, maxsize, padvalue, i;
1742     unsigned checkint;
1743     int ret = 0;
1744     unsigned char bcrypt_salt[16];
1745     const int bcrypt_rounds = 16;
1746     FILE *fp;
1747
1748     /*
1749      * Fetch the key blobs and find out the lengths of things.
1750      */
1751     pubblob = key->alg->public_blob(key->data, &publen);
1752     i = key->alg->openssh_fmtkey(key->data, NULL, 0);
1753     privblob = snewn(i, unsigned char);
1754     privlen = key->alg->openssh_fmtkey(key->data, privblob, i);
1755     assert(privlen == i);
1756     commentlen = strlen(key->comment);
1757
1758     /*
1759      * Allocate enough space for the full binary key format. No need
1760      * to be absolutely precise here.
1761      */
1762     maxsize = (16 +                    /* magic number */
1763                32 +                    /* cipher name string */
1764                32 +                    /* kdf name string */
1765                64 +                    /* kdf options string */
1766                4 +                     /* key count */
1767                4+publen +              /* public key string */
1768                4 +                     /* string header for private section */
1769                8 +                     /* checkint x 2 */
1770                4+strlen(key->alg->name) + /* key type string */
1771                privlen +               /* private blob */
1772                4+commentlen +          /* comment string */
1773                16);                    /* padding at end of private section */
1774     outblob = snewn(maxsize, unsigned char);
1775
1776     /*
1777      * Construct the cleartext version of the blob.
1778      */
1779     p = outblob;
1780
1781     /* Magic number. */
1782     memcpy(p, "openssh-key-v1\0", 15);
1783     p += 15;
1784
1785     /* Cipher and kdf names, and kdf options. */
1786     if (!passphrase) {
1787         memset(bcrypt_salt, 0, sizeof(bcrypt_salt)); /* prevent warnings */
1788         p += put_string_z(p, "none");
1789         p += put_string_z(p, "none");
1790         p += put_string_z(p, "");
1791     } else {
1792         unsigned char *q;
1793         for (i = 0; i < (int)sizeof(bcrypt_salt); i++)
1794             bcrypt_salt[i] = random_byte();
1795         p += put_string_z(p, "aes256-cbc");
1796         p += put_string_z(p, "bcrypt");
1797         q = p;
1798         p += 4;
1799         p += put_string(p, bcrypt_salt, sizeof(bcrypt_salt));
1800         p += put_uint32(p, bcrypt_rounds);
1801         PUT_32BIT_MSB_FIRST(q, (unsigned)(p - (q+4)));
1802     }
1803
1804     /* Number of keys. */
1805     p += put_uint32(p, 1);
1806
1807     /* Public blob. */
1808     p += put_string(p, pubblob, publen);
1809
1810     /* Begin private section. */
1811     private_section_length_field = p;
1812     p += 4;
1813     private_section_start = p;
1814
1815     /* checkint. */
1816     checkint = 0;
1817     for (i = 0; i < 4; i++)
1818         checkint = (checkint << 8) + random_byte();
1819     p += put_uint32(p, checkint);
1820     p += put_uint32(p, checkint);
1821
1822     /* Private key. The main private blob goes inline, with no string
1823      * wrapper. */
1824     p += put_string_z(p, key->alg->name);
1825     memcpy(p, privblob, privlen);
1826     p += privlen;
1827
1828     /* Comment. */
1829     p += put_string_z(p, key->comment);
1830
1831     /* Pad out the encrypted section. */
1832     padvalue = 1;
1833     do {
1834         *p++ = padvalue++;
1835     } while ((p - private_section_start) & 15);
1836
1837     assert(p - outblob < maxsize);
1838
1839     /* Go back and fill in the length field for the private section. */
1840     PUT_32BIT_MSB_FIRST(private_section_length_field,
1841                         p - private_section_start);
1842
1843     if (passphrase) {
1844         /*
1845          * Encrypt the private section. We need 48 bytes of key
1846          * material: 32 bytes AES key + 16 bytes iv.
1847          */
1848         unsigned char keybuf[48];
1849         void *ctx;
1850
1851         openssh_bcrypt(passphrase,
1852                        bcrypt_salt, sizeof(bcrypt_salt), bcrypt_rounds,
1853                        keybuf, sizeof(keybuf));
1854
1855         ctx = aes_make_context();
1856         aes256_key(ctx, keybuf);
1857         aes_iv(ctx, keybuf + 32);
1858         aes_ssh2_encrypt_blk(ctx, private_section_start,
1859                              p - private_section_start);
1860         aes_free_context(ctx);
1861
1862         smemclr(keybuf, sizeof(keybuf));
1863     }
1864
1865     /*
1866      * And save it. We'll use Unix line endings just in case it's
1867      * subsequently transferred in binary mode.
1868      */
1869     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
1870     if (!fp)
1871         goto error;
1872     fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp);
1873     base64_encode(fp, outblob, p - outblob, 64);
1874     fputs("-----END OPENSSH PRIVATE KEY-----\n", fp);
1875     fclose(fp);
1876     ret = 1;
1877
1878     error:
1879     if (outblob) {
1880         smemclr(outblob, maxsize);
1881         sfree(outblob);
1882     }
1883     if (privblob) {
1884         smemclr(privblob, privlen);
1885         sfree(privblob);
1886     }
1887     if (pubblob) {
1888         smemclr(pubblob, publen);
1889         sfree(pubblob);
1890     }
1891     return ret;
1892 }
1893
1894 /* ----------------------------------------------------------------------
1895  * The switch function openssh_auto_write(), which chooses one of the
1896  * concrete OpenSSH output formats based on the key type.
1897  */
1898 int openssh_auto_write(const Filename *filename, struct ssh2_userkey *key,
1899                        char *passphrase)
1900 {
1901     /*
1902      * The old OpenSSH format supports a fixed list of key types. We
1903      * assume that anything not in that fixed list is newer, and hence
1904      * will use the new format.
1905      */
1906     if (key->alg == &ssh_dss ||
1907         key->alg == &ssh_rsa ||
1908         key->alg == &ssh_ecdsa_nistp256 ||
1909         key->alg == &ssh_ecdsa_nistp384 ||
1910         key->alg == &ssh_ecdsa_nistp521)
1911         return openssh_pem_write(filename, key, passphrase);
1912     else
1913         return openssh_new_write(filename, key, passphrase);
1914 }
1915
1916 /* ----------------------------------------------------------------------
1917  * Code to read ssh.com private keys.
1918  */
1919
1920 /*
1921  * The format of the base64 blob is largely SSH-2-packet-formatted,
1922  * except that mpints are a bit different: they're more like the
1923  * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1924  * (N+7)/8 bytes of data.
1925  * 
1926  * So. The blob contains:
1927  * 
1928  *  - uint32 0x3f6ff9eb       (magic number)
1929  *  - uint32 size             (total blob size)
1930  *  - string key-type         (see below)
1931  *  - string cipher-type      (tells you if key is encrypted)
1932  *  - string encrypted-blob
1933  * 
1934  * (The first size field includes the size field itself and the
1935  * magic number before it. All other size fields are ordinary SSH-2
1936  * strings, so the size field indicates how much data is to
1937  * _follow_.)
1938  * 
1939  * The encrypted blob, once decrypted, contains a single string
1940  * which in turn contains the payload. (This allows padding to be
1941  * added after that string while still making it clear where the
1942  * real payload ends. Also it probably makes for a reasonable
1943  * decryption check.)
1944  * 
1945  * The payload blob, for an RSA key, contains:
1946  *  - mpint e
1947  *  - mpint d
1948  *  - mpint n  (yes, the public and private stuff is intermixed)
1949  *  - mpint u  (presumably inverse of p mod q)
1950  *  - mpint p  (p is the smaller prime)
1951  *  - mpint q  (q is the larger)
1952  * 
1953  * For a DSA key, the payload blob contains:
1954  *  - uint32 0
1955  *  - mpint p
1956  *  - mpint g
1957  *  - mpint q
1958  *  - mpint y
1959  *  - mpint x
1960  * 
1961  * Alternatively, if the parameters are `predefined', that
1962  * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1963  * containing some predefined parameter specification. *shudder*,
1964  * but I doubt we'll encounter this in real life.
1965  * 
1966  * The key type strings are ghastly. The RSA key I looked at had a
1967  * type string of
1968  * 
1969  *   `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1970  * 
1971  * and the DSA key wasn't much better:
1972  * 
1973  *   `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1974  * 
1975  * It isn't clear that these will always be the same. I think it
1976  * might be wise just to look at the `if-modn{sign{rsa' and
1977  * `dl-modp{sign{dsa' prefixes.
1978  * 
1979  * Finally, the encryption. The cipher-type string appears to be
1980  * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1981  * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1982  * from the passphrase by means of yet another hashing faff:
1983  * 
1984  *  - first 16 bytes are MD5(passphrase)
1985  *  - next 16 bytes are MD5(passphrase || first 16 bytes)
1986  *  - if there were more, they'd be MD5(passphrase || first 32),
1987  *    and so on.
1988  */
1989
1990 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1991
1992 struct sshcom_key {
1993     char comment[256];                 /* allowing any length is overkill */
1994     unsigned char *keyblob;
1995     int keyblob_len, keyblob_size;
1996 };
1997
1998 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1999                                           const char **errmsg_p)
2000 {
2001     struct sshcom_key *ret;
2002     FILE *fp;
2003     char *line = NULL;
2004     int hdrstart, len;
2005     char *errmsg, *p;
2006     int headers_done;
2007     char base64_bit[4];
2008     int base64_chars = 0;
2009
2010     ret = snew(struct sshcom_key);
2011     ret->comment[0] = '\0';
2012     ret->keyblob = NULL;
2013     ret->keyblob_len = ret->keyblob_size = 0;
2014
2015     fp = f_open(filename, "r", FALSE);
2016     if (!fp) {
2017         errmsg = "unable to open key file";
2018         goto error;
2019     }
2020     if (!(line = fgetline(fp))) {
2021         errmsg = "unexpected end of file";
2022         goto error;
2023     }
2024     strip_crlf(line);
2025     if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
2026         errmsg = "file does not begin with ssh.com key header";
2027         goto error;
2028     }
2029     smemclr(line, strlen(line));
2030     sfree(line);
2031     line = NULL;
2032
2033     headers_done = 0;
2034     while (1) {
2035         if (!(line = fgetline(fp))) {
2036             errmsg = "unexpected end of file";
2037             goto error;
2038         }
2039         strip_crlf(line);
2040         if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
2041             sfree(line);
2042             line = NULL;
2043             break;                     /* done */
2044         }
2045         if ((p = strchr(line, ':')) != NULL) {
2046             if (headers_done) {
2047                 errmsg = "header found in body of key data";
2048                 goto error;
2049             }
2050             *p++ = '\0';
2051             while (*p && isspace((unsigned char)*p)) p++;
2052             hdrstart = p - line;
2053
2054             /*
2055              * Header lines can end in a trailing backslash for
2056              * continuation.
2057              */
2058             len = hdrstart + strlen(line+hdrstart);
2059             assert(!line[len]);
2060             while (line[len-1] == '\\') {
2061                 char *line2;
2062                 int line2len;
2063
2064                 line2 = fgetline(fp);
2065                 if (!line2) {
2066                     errmsg = "unexpected end of file";
2067                     goto error;
2068                 }
2069                 strip_crlf(line2);
2070
2071                 line2len = strlen(line2);
2072                 line = sresize(line, len + line2len + 1, char);
2073                 strcpy(line + len - 1, line2);
2074                 len += line2len - 1;
2075                 assert(!line[len]);
2076
2077                 smemclr(line2, strlen(line2));
2078                 sfree(line2);
2079                 line2 = NULL;
2080             }
2081             p = line + hdrstart;
2082             strip_crlf(p);
2083             if (!strcmp(line, "Comment")) {
2084                 /* Strip quotes in comment if present. */
2085                 if (p[0] == '"' && p[strlen(p)-1] == '"') {
2086                     p++;
2087                     p[strlen(p)-1] = '\0';
2088                 }
2089                 strncpy(ret->comment, p, sizeof(ret->comment));
2090                 ret->comment[sizeof(ret->comment)-1] = '\0';
2091             }
2092         } else {
2093             headers_done = 1;
2094
2095             p = line;
2096             while (isbase64(*p)) {
2097                 base64_bit[base64_chars++] = *p;
2098                 if (base64_chars == 4) {
2099                     unsigned char out[3];
2100
2101                     base64_chars = 0;
2102
2103                     len = base64_decode_atom(base64_bit, out);
2104
2105                     if (len <= 0) {
2106                         errmsg = "invalid base64 encoding";
2107                         goto error;
2108                     }
2109
2110                     if (ret->keyblob_len + len > ret->keyblob_size) {
2111                         ret->keyblob_size = ret->keyblob_len + len + 256;
2112                         ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
2113                                                unsigned char);
2114                     }
2115
2116                     memcpy(ret->keyblob + ret->keyblob_len, out, len);
2117                     ret->keyblob_len += len;
2118                 }
2119
2120                 p++;
2121             }
2122         }
2123         smemclr(line, strlen(line));
2124         sfree(line);
2125         line = NULL;
2126     }
2127
2128     if (ret->keyblob_len == 0 || !ret->keyblob) {
2129         errmsg = "key body not present";
2130         goto error;
2131     }
2132
2133     fclose(fp);
2134     if (errmsg_p) *errmsg_p = NULL;
2135     return ret;
2136
2137     error:
2138     if (fp)
2139         fclose(fp);
2140
2141     if (line) {
2142         smemclr(line, strlen(line));
2143         sfree(line);
2144         line = NULL;
2145     }
2146     if (ret) {
2147         if (ret->keyblob) {
2148             smemclr(ret->keyblob, ret->keyblob_size);
2149             sfree(ret->keyblob);
2150         }
2151         smemclr(ret, sizeof(*ret));
2152         sfree(ret);
2153     }
2154     if (errmsg_p) *errmsg_p = errmsg;
2155     return NULL;
2156 }
2157
2158 int sshcom_encrypted(const Filename *filename, char **comment)
2159 {
2160     struct sshcom_key *key = load_sshcom_key(filename, NULL);
2161     int pos, len, answer;
2162
2163     answer = 0;
2164
2165     *comment = NULL;
2166     if (!key)
2167         goto done;
2168
2169     /*
2170      * Check magic number.
2171      */
2172     if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
2173         goto done;                     /* key is invalid */
2174     }
2175
2176     /*
2177      * Find the cipher-type string.
2178      */
2179     pos = 8;
2180     if (key->keyblob_len < pos+4)
2181         goto done;                     /* key is far too short */
2182     len = toint(GET_32BIT(key->keyblob + pos));
2183     if (len < 0 || len > key->keyblob_len - pos - 4)
2184         goto done;                     /* key is far too short */
2185     pos += 4 + len;                    /* skip key type */
2186     len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
2187     if (len < 0 || len > key->keyblob_len - pos - 4)
2188         goto done;                     /* cipher type string is incomplete */
2189     if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
2190         answer = 1;
2191
2192     done:
2193     if (key) {
2194         *comment = dupstr(key->comment);
2195         smemclr(key->keyblob, key->keyblob_size);
2196         sfree(key->keyblob);
2197         smemclr(key, sizeof(*key));
2198         sfree(key);
2199     } else {
2200         *comment = dupstr("");
2201     }
2202     return answer;
2203 }
2204
2205 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
2206 {
2207     unsigned bits, bytes;
2208     unsigned char *d = (unsigned char *) data;
2209
2210     if (len < 4)
2211         goto error;
2212     bits = GET_32BIT(d);
2213
2214     bytes = (bits + 7) / 8;
2215     if (len < 4+bytes)
2216         goto error;
2217
2218     ret->start = d + 4;
2219     ret->bytes = bytes;
2220     return bytes+4;
2221
2222     error:
2223     ret->start = NULL;
2224     ret->bytes = -1;
2225     return len;                        /* ensure further calls fail as well */
2226 }
2227
2228 static int sshcom_put_mpint(void *target, void *data, int len)
2229 {
2230     unsigned char *d = (unsigned char *)target;
2231     unsigned char *i = (unsigned char *)data;
2232     int bits = len * 8 - 1;
2233
2234     while (bits > 0) {
2235         if (*i & (1 << (bits & 7)))
2236             break;
2237         if (!(bits-- & 7))
2238             i++, len--;
2239     }
2240
2241     PUT_32BIT(d, bits+1);
2242     memcpy(d+4, i, len);
2243     return len+4;
2244 }
2245
2246 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
2247                                  const char **errmsg_p)
2248 {
2249     struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
2250     char *errmsg;
2251     int pos, len;
2252     const char prefix_rsa[] = "if-modn{sign{rsa";
2253     const char prefix_dsa[] = "dl-modp{sign{dsa";
2254     enum { RSA, DSA } type;
2255     int encrypted;
2256     char *ciphertext;
2257     int cipherlen;
2258     struct ssh2_userkey *ret = NULL, *retkey;
2259     const struct ssh_signkey *alg;
2260     unsigned char *blob = NULL;
2261     int blobsize = 0, publen, privlen;
2262
2263     if (!key)
2264         return NULL;
2265
2266     /*
2267      * Check magic number.
2268      */
2269     if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
2270         errmsg = "key does not begin with magic number";
2271         goto error;
2272     }
2273
2274     /*
2275      * Determine the key type.
2276      */
2277     pos = 8;
2278     if (key->keyblob_len < pos+4 ||
2279         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2280         len > key->keyblob_len - pos - 4) {
2281         errmsg = "key blob does not contain a key type string";
2282         goto error;
2283     }
2284     if (len > sizeof(prefix_rsa) - 1 &&
2285         !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
2286         type = RSA;
2287     } else if (len > sizeof(prefix_dsa) - 1 &&
2288         !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
2289         type = DSA;
2290     } else {
2291         errmsg = "key is of unknown type";
2292         goto error;
2293     }
2294     pos += 4+len;
2295
2296     /*
2297      * Determine the cipher type.
2298      */
2299     if (key->keyblob_len < pos+4 ||
2300         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2301         len > key->keyblob_len - pos - 4) {
2302         errmsg = "key blob does not contain a cipher type string";
2303         goto error;
2304     }
2305     if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
2306         encrypted = 0;
2307     else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
2308         encrypted = 1;
2309     else {
2310         errmsg = "key encryption is of unknown type";
2311         goto error;
2312     }
2313     pos += 4+len;
2314
2315     /*
2316      * Get hold of the encrypted part of the key.
2317      */
2318     if (key->keyblob_len < pos+4 ||
2319         (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2320         len > key->keyblob_len - pos - 4) {
2321         errmsg = "key blob does not contain actual key data";
2322         goto error;
2323     }
2324     ciphertext = (char *)key->keyblob + pos + 4;
2325     cipherlen = len;
2326     if (cipherlen == 0) {
2327         errmsg = "length of key data is zero";
2328         goto error;
2329     }
2330
2331     /*
2332      * Decrypt it if necessary.
2333      */
2334     if (encrypted) {
2335         /*
2336          * Derive encryption key from passphrase and iv/salt:
2337          * 
2338          *  - let block A equal MD5(passphrase)
2339          *  - let block B equal MD5(passphrase || A)
2340          *  - block C would be MD5(passphrase || A || B) and so on
2341          *  - encryption key is the first N bytes of A || B
2342          */
2343         struct MD5Context md5c;
2344         unsigned char keybuf[32], iv[8];
2345
2346         if (cipherlen % 8 != 0) {
2347             errmsg = "encrypted part of key is not a multiple of cipher block"
2348                 " size";
2349             goto error;
2350         }
2351
2352         MD5Init(&md5c);
2353         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2354         MD5Final(keybuf, &md5c);
2355
2356         MD5Init(&md5c);
2357         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2358         MD5Update(&md5c, keybuf, 16);
2359         MD5Final(keybuf+16, &md5c);
2360
2361         /*
2362          * Now decrypt the key blob.
2363          */
2364         memset(iv, 0, sizeof(iv));
2365         des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2366                                  cipherlen);
2367
2368         smemclr(&md5c, sizeof(md5c));
2369         smemclr(keybuf, sizeof(keybuf));
2370
2371         /*
2372          * Hereafter we return WRONG_PASSPHRASE for any parsing
2373          * error. (But only if we've just tried to decrypt it!
2374          * Returning WRONG_PASSPHRASE for an unencrypted key is
2375          * automatic doom.)
2376          */
2377         if (encrypted)
2378             ret = SSH2_WRONG_PASSPHRASE;
2379     }
2380
2381     /*
2382      * Strip away the containing string to get to the real meat.
2383      */
2384     len = toint(GET_32BIT(ciphertext));
2385     if (len < 0 || len > cipherlen-4) {
2386         errmsg = "containing string was ill-formed";
2387         goto error;
2388     }
2389     ciphertext += 4;
2390     cipherlen = len;
2391
2392     /*
2393      * Now we break down into RSA versus DSA. In either case we'll
2394      * construct public and private blobs in our own format, and
2395      * end up feeding them to alg->createkey().
2396      */
2397     blobsize = cipherlen + 256;
2398     blob = snewn(blobsize, unsigned char);
2399     privlen = 0;
2400     if (type == RSA) {
2401         struct mpint_pos n, e, d, u, p, q;
2402         int pos = 0;
2403         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
2404         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
2405         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
2406         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
2407         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2408         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2409         if (!q.start) {
2410             errmsg = "key data did not contain six integers";
2411             goto error;
2412         }
2413
2414         alg = &ssh_rsa;
2415         pos = 0;
2416         pos += put_string(blob+pos, "ssh-rsa", 7);
2417         pos += put_mp(blob+pos, e.start, e.bytes);
2418         pos += put_mp(blob+pos, n.start, n.bytes);
2419         publen = pos;
2420         pos += put_string(blob+pos, d.start, d.bytes);
2421         pos += put_mp(blob+pos, q.start, q.bytes);
2422         pos += put_mp(blob+pos, p.start, p.bytes);
2423         pos += put_mp(blob+pos, u.start, u.bytes);
2424         privlen = pos - publen;
2425     } else {
2426         struct mpint_pos p, q, g, x, y;
2427         int pos = 4;
2428
2429         assert(type == DSA); /* the only other option from the if above */
2430
2431         if (GET_32BIT(ciphertext) != 0) {
2432             errmsg = "predefined DSA parameters not supported";
2433             goto error;
2434         }
2435         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2436         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
2437         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2438         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
2439         pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
2440         if (!x.start) {
2441             errmsg = "key data did not contain five integers";
2442             goto error;
2443         }
2444
2445         alg = &ssh_dss;
2446         pos = 0;
2447         pos += put_string(blob+pos, "ssh-dss", 7);
2448         pos += put_mp(blob+pos, p.start, p.bytes);
2449         pos += put_mp(blob+pos, q.start, q.bytes);
2450         pos += put_mp(blob+pos, g.start, g.bytes);
2451         pos += put_mp(blob+pos, y.start, y.bytes);
2452         publen = pos;
2453         pos += put_mp(blob+pos, x.start, x.bytes);
2454         privlen = pos - publen;
2455     }
2456
2457     assert(privlen > 0);               /* should have bombed by now if not */
2458
2459     retkey = snew(struct ssh2_userkey);
2460     retkey->alg = alg;
2461     retkey->data = alg->createkey(alg, blob, publen, blob+publen, privlen);
2462     if (!retkey->data) {
2463         sfree(retkey);
2464         errmsg = "unable to create key data structure";
2465         goto error;
2466     }
2467     retkey->comment = dupstr(key->comment);
2468
2469     errmsg = NULL; /* no error */
2470     ret = retkey;
2471
2472     error:
2473     if (blob) {
2474         smemclr(blob, blobsize);
2475         sfree(blob);
2476     }
2477     smemclr(key->keyblob, key->keyblob_size);
2478     sfree(key->keyblob);
2479     smemclr(key, sizeof(*key));
2480     sfree(key);
2481     if (errmsg_p) *errmsg_p = errmsg;
2482     return ret;
2483 }
2484
2485 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
2486                  char *passphrase)
2487 {
2488     unsigned char *pubblob, *privblob;
2489     int publen, privlen;
2490     unsigned char *outblob;
2491     int outlen;
2492     struct mpint_pos numbers[6];
2493     int nnumbers, initial_zero, pos, lenpos, i;
2494     char *type;
2495     char *ciphertext;
2496     int cipherlen;
2497     int ret = 0;
2498     FILE *fp;
2499
2500     /*
2501      * Fetch the key blobs.
2502      */
2503     pubblob = key->alg->public_blob(key->data, &publen);
2504     privblob = key->alg->private_blob(key->data, &privlen);
2505     outblob = NULL;
2506
2507     /*
2508      * Find the sequence of integers to be encoded into the OpenSSH
2509      * key blob, and also decide on the header line.
2510      */
2511     if (key->alg == &ssh_rsa) {
2512         int pos;
2513         struct mpint_pos n, e, d, p, q, iqmp;
2514
2515         /*
2516          * These blobs were generated from inside PuTTY, so we needn't
2517          * treat them as untrusted.
2518          */
2519         pos = 4 + GET_32BIT(pubblob);
2520         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
2521         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
2522         pos = 0;
2523         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
2524         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
2525         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
2526         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
2527
2528         assert(e.start && iqmp.start); /* can't go wrong */
2529
2530         numbers[0] = e;
2531         numbers[1] = d;
2532         numbers[2] = n;
2533         numbers[3] = iqmp;
2534         numbers[4] = q;
2535         numbers[5] = p;
2536
2537         nnumbers = 6;
2538         initial_zero = 0;
2539         type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
2540     } else if (key->alg == &ssh_dss) {
2541         int pos;
2542         struct mpint_pos p, q, g, y, x;
2543
2544         /*
2545          * These blobs were generated from inside PuTTY, so we needn't
2546          * treat them as untrusted.
2547          */
2548         pos = 4 + GET_32BIT(pubblob);
2549         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
2550         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
2551         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
2552         pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
2553         pos = 0;
2554         pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
2555
2556         assert(y.start && x.start); /* can't go wrong */
2557
2558         numbers[0] = p;
2559         numbers[1] = g;
2560         numbers[2] = q;
2561         numbers[3] = y;
2562         numbers[4] = x;
2563
2564         nnumbers = 5;
2565         initial_zero = 1;
2566         type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
2567     } else {
2568         assert(0);                     /* zoinks! */
2569         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
2570     }
2571
2572     /*
2573      * Total size of key blob will be somewhere under 512 plus
2574      * combined length of integers. We'll calculate the more
2575      * precise size as we construct the blob.
2576      */
2577     outlen = 512;
2578     for (i = 0; i < nnumbers; i++)
2579         outlen += 4 + numbers[i].bytes;
2580     outblob = snewn(outlen, unsigned char);
2581
2582     /*
2583      * Create the unencrypted key blob.
2584      */
2585     pos = 0;
2586     PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
2587     pos += 4;                          /* length field, fill in later */
2588     pos += put_string(outblob+pos, type, strlen(type));
2589     {
2590         char *ciphertype = passphrase ? "3des-cbc" : "none";
2591         pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
2592     }
2593     lenpos = pos;                      /* remember this position */
2594     pos += 4;                          /* encrypted-blob size */
2595     pos += 4;                          /* encrypted-payload size */
2596     if (initial_zero) {
2597         PUT_32BIT(outblob+pos, 0);
2598         pos += 4;
2599     }
2600     for (i = 0; i < nnumbers; i++)
2601         pos += sshcom_put_mpint(outblob+pos,
2602                                 numbers[i].start, numbers[i].bytes);
2603     /* Now wrap up the encrypted payload. */
2604     PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
2605     /* Pad encrypted blob to a multiple of cipher block size. */
2606     if (passphrase) {
2607         int padding = -(pos - (lenpos+4)) & 7;
2608         while (padding--)
2609             outblob[pos++] = random_byte();
2610     }
2611     ciphertext = (char *)outblob+lenpos+4;
2612     cipherlen = pos - (lenpos+4);
2613     assert(!passphrase || cipherlen % 8 == 0);
2614     /* Wrap up the encrypted blob string. */
2615     PUT_32BIT(outblob+lenpos, cipherlen);
2616     /* And finally fill in the total length field. */
2617     PUT_32BIT(outblob+4, pos);
2618
2619     assert(pos < outlen);
2620
2621     /*
2622      * Encrypt the key.
2623      */
2624     if (passphrase) {
2625         /*
2626          * Derive encryption key from passphrase and iv/salt:
2627          * 
2628          *  - let block A equal MD5(passphrase)
2629          *  - let block B equal MD5(passphrase || A)
2630          *  - block C would be MD5(passphrase || A || B) and so on
2631          *  - encryption key is the first N bytes of A || B
2632          */
2633         struct MD5Context md5c;
2634         unsigned char keybuf[32], iv[8];
2635
2636         MD5Init(&md5c);
2637         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2638         MD5Final(keybuf, &md5c);
2639
2640         MD5Init(&md5c);
2641         MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2642         MD5Update(&md5c, keybuf, 16);
2643         MD5Final(keybuf+16, &md5c);
2644
2645         /*
2646          * Now decrypt the key blob.
2647          */
2648         memset(iv, 0, sizeof(iv));
2649         des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2650                                  cipherlen);
2651
2652         smemclr(&md5c, sizeof(md5c));
2653         smemclr(keybuf, sizeof(keybuf));
2654     }
2655
2656     /*
2657      * And save it. We'll use Unix line endings just in case it's
2658      * subsequently transferred in binary mode.
2659      */
2660     fp = f_open(filename, "wb", TRUE);      /* ensure Unix line endings */
2661     if (!fp)
2662         goto error;
2663     fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2664     fprintf(fp, "Comment: \"");
2665     /*
2666      * Comment header is broken with backslash-newline if it goes
2667      * over 70 chars. Although it's surrounded by quotes, it
2668      * _doesn't_ escape backslashes or quotes within the string.
2669      * Don't ask me, I didn't design it.
2670      */
2671     {
2672         int slen = 60;                 /* starts at 60 due to "Comment: " */
2673         char *c = key->comment;
2674         while ((int)strlen(c) > slen) {
2675             fprintf(fp, "%.*s\\\n", slen, c);
2676             c += slen;
2677             slen = 70;                 /* allow 70 chars on subsequent lines */
2678         }
2679         fprintf(fp, "%s\"\n", c);
2680     }
2681     base64_encode(fp, outblob, pos, 70);
2682     fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2683     fclose(fp);
2684     ret = 1;
2685
2686     error:
2687     if (outblob) {
2688         smemclr(outblob, outlen);
2689         sfree(outblob);
2690     }
2691     if (privblob) {
2692         smemclr(privblob, privlen);
2693         sfree(privblob);
2694     }
2695     if (pubblob) {
2696         smemclr(pubblob, publen);
2697         sfree(pubblob);
2698     }
2699     return ret;
2700 }