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