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