comparison keyimport.c @ 285:1b9e69c058d2

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