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