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