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