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