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