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