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