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