remove unused variable
[dropbear.git] / keyimport.c
blob76b92f1331428e5460d11389519c03649ca29db5
1 /*
2 * Based on PuTTY's import.c for importing/exporting OpenSSH and SSH.com
3 * keyfiles.
5 * The horribleness of the code is probably mine (matt).
7 * Modifications copyright 2003 Matt Johnston
9 * PuTTY is copyright 1997-2003 Simon Tatham.
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.
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:
23 * The above copyright notice and this permission notice shall be
24 * included in all copies or substantial portions of the Software.
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.
35 #include "keyimport.h"
36 #include "bignum.h"
37 #include "buffer.h"
38 #include "dbutil.h"
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)
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]))
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);
57 static int dropbear_write(const char*filename, sign_key * key);
58 static sign_key *dropbear_read(const char* filename);
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
67 int import_encrypted(const char* filename, int filetype) {
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
76 return 0;
79 sign_key *import_read(const char *filename, char *passphrase, int filetype) {
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
90 return NULL;
93 int import_write(const char *filename, sign_key *key, char *passphrase,
94 int filetype) {
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
105 return 0;
108 static sign_key *dropbear_read(const char* filename) {
110 buffer * buf = NULL;
111 sign_key *ret = NULL;
112 int type;
114 buf = buf_new(MAX_PRIVKEY_SIZE);
115 if (buf_readfile(buf, filename) == DROPBEAR_FAILURE) {
116 goto error;
119 buf_setpos(buf, 0);
120 ret = new_sign_key();
122 type = DROPBEAR_SIGNKEY_ANY;
123 if (buf_get_priv_key(buf, ret, &type) == DROPBEAR_FAILURE){
124 goto error;
126 buf_free(buf);
128 return ret;
130 error:
131 if (buf) {
132 buf_free(buf);
134 if (ret) {
135 sign_key_free(ret);
137 return NULL;
140 /* returns 0 on fail, 1 on success */
141 static int dropbear_write(const char*filename, sign_key * key) {
143 int keytype = -1;
144 buffer * buf;
145 FILE*fp;
146 int len;
147 int ret;
149 #ifdef DROPBEAR_RSA
150 if (key->rsakey != NULL) {
151 keytype = DROPBEAR_SIGNKEY_RSA;
153 #endif
154 #ifdef DROPBEAR_DSS
155 if (key->dsskey != NULL) {
156 keytype = DROPBEAR_SIGNKEY_DSS;
158 #endif
160 buf = buf_new(MAX_PRIVKEY_SIZE);
161 buf_put_priv_key(buf, key, keytype);
163 fp = fopen(filename, "w");
164 if (!fp) {
165 ret = 0;
166 goto out;
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);
176 fclose(fp);
178 if (buf->pos != buf->len) {
179 ret = 0;
180 } else {
181 ret = 1;
183 out:
184 buf_free(buf);
185 return ret;
189 /* ----------------------------------------------------------------------
190 * Helper routines. (The base64 ones are defined in sshpubk.c.)
193 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
194 ((c) >= 'a' && (c) <= 'z') || \
195 ((c) >= '0' && (c) <= '9') || \
196 (c) == '+' || (c) == '/' || (c) == '=' \
199 /* cpl has to be less than 100 */
200 static void base64_encode_fp(FILE * fp, unsigned char *data,
201 int datalen, int cpl)
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));
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);
221 * Read an ASN.1/BER identifier and length pair.
223 * Flags are a combination of the #defines listed below.
225 * Returns -1 if unsuccessful; otherwise returns the number of
226 * bytes used out of the source data.
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)
236 /* Primitive versus constructed bit. */
237 #define ASN1_CONSTRUCTED (1 << 5)
239 static int ber_read_id_len(void *source, int sourcelen,
240 int *id, int *length, int *flags)
242 unsigned char *p = (unsigned char *) source;
244 if (sourcelen == 0)
245 return -1;
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;
256 *id = (*id << 7) | (*p & 0x7F);
257 p++, sourcelen--;
258 } else {
259 *id = *p & 0x1F;
260 p++, sourcelen--;
263 if (sourcelen == 0)
264 return -1;
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--;
280 return p - (unsigned char *) source;
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.
289 static int ber_write_id_len(void *dest, int id, int length, int flags)
291 unsigned char *d = (unsigned char *)dest;
292 int len = 0;
294 if (id <= 30) {
296 * Identifier is one byte.
298 len++;
299 if (d) *d++ = id | flags;
300 } else {
301 int n;
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.
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);
318 if (length < 128) {
320 * Length is one byte.
322 len++;
323 if (d) *d++ = length;
324 } else {
325 int n;
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.
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;
341 return len;
345 /* Simple structure to point to an mp-int within a blob. */
346 struct mpint_pos { void *start; int bytes; };
348 /* ----------------------------------------------------------------------
349 * Code to read and write OpenSSH private keys.
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;
361 static struct openssh_key *load_openssh_key(const char *filename)
363 struct openssh_key *ret;
364 FILE *fp = NULL;
365 char buffer[256];
366 char *errmsg = NULL, *p = NULL;
367 int headers_done;
368 unsigned long len, outlen;
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));
376 if (strlen(filename) == 1 && filename[0] == '-') {
377 fp = stdin;
378 } else {
379 fp = fopen(filename, "r");
381 if (!fp) {
382 errmsg = "Unable to open key file";
383 goto error;
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;
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;
400 headers_done = 0;
401 while (1) {
402 if (!fgets(buffer, sizeof(buffer), fp)) {
403 errmsg = "Unexpected end of file";
404 goto error;
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;
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;
421 p += 2;
422 if (!strcmp(p, "ENCRYPTED\n"))
423 ret->encrypted = 1;
424 } else if (!strcmp(buffer, "DEK-Info")) {
425 int i, j;
427 if (strncmp(p, "DES-EDE3-CBC,", 13)) {
428 errmsg = "Ciphers other than DES-EDE3-CBC not supported";
429 goto error;
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;
438 if (i < 8) {
439 errmsg = "Expected 16-digit iv in DEK-Info";
440 goto error;
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);
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;
458 ret->keyblob_len += outlen;
462 if (ret->keyblob_len == 0 || !ret->keyblob) {
463 errmsg = "Key body not present";
464 goto error;
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;
472 memset(buffer, 0, sizeof(buffer));
473 return ret;
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);
482 memset(&ret, 0, sizeof(ret));
483 m_free(ret);
485 if (fp) {
486 fclose(fp);
488 if (errmsg) {
489 fprintf(stderr, "Error: %s\n", errmsg);
491 return NULL;
494 static int openssh_encrypted(const char *filename)
496 struct openssh_key *key = load_openssh_key(filename);
497 int ret;
499 if (!key)
500 return 0;
501 ret = key->encrypted;
502 memset(key->keyblob, 0, key->keyblob_size);
503 m_free(key->keyblob);
504 memset(&key, 0, sizeof(key));
505 m_free(key);
506 return ret;
509 static sign_key *openssh_read(const char *filename, char *passphrase)
511 struct openssh_key *key;
512 unsigned char *p;
513 int ret, id, len, flags;
514 int i, num_integers = 0;
515 sign_key *retval = NULL;
516 char *errmsg;
517 char *modptr = NULL;
518 int modlen = -9999;
519 int type;
521 sign_key *retkey;
522 buffer * blobbuf = NULL;
524 key = load_openssh_key(filename);
526 if (!key)
527 return NULL;
529 if (key->encrypted) {
530 errmsg = "encrypted keys not supported currently";
531 goto error;
532 #if 0
533 /* matt TODO */
535 * Derive encryption key from passphrase and iv/salt:
537 * - let block A equal MD5(passphrase || iv)
538 * - let block B equal MD5(A || passphrase || iv)
539 * - block C would be MD5(B || passphrase || iv) and so on
540 * - encryption key is the first N bytes of A || B
542 struct MD5Context md5c;
543 unsigned char keybuf[32];
545 MD5Init(&md5c);
546 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
547 MD5Update(&md5c, (unsigned char *)key->iv, 8);
548 MD5Final(keybuf, &md5c);
550 MD5Init(&md5c);
551 MD5Update(&md5c, keybuf, 16);
552 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
553 MD5Update(&md5c, (unsigned char *)key->iv, 8);
554 MD5Final(keybuf+16, &md5c);
557 * Now decrypt the key blob.
559 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
560 key->keyblob, key->keyblob_len);
562 memset(&md5c, 0, sizeof(md5c));
563 memset(keybuf, 0, sizeof(keybuf));
564 #endif
568 * Now we have a decrypted key blob, which contains an ASN.1
569 * encoded private key. We must now untangle the ASN.1.
571 * We expect the whole key blob to be formatted as a SEQUENCE
572 * (0x30 followed by a length code indicating that the rest of
573 * the blob is part of the sequence). Within that SEQUENCE we
574 * expect to see a bunch of INTEGERs. What those integers mean
575 * depends on the key type:
577 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
578 * dmp1, dmq1, iqmp in that order. (The last three are d mod
579 * (p-1), d mod (q-1), inverse of q mod p respectively.)
581 * - For DSA, we expect them to be 0, p, q, g, y, x in that
582 * order.
585 p = key->keyblob;
587 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
588 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
589 p += ret;
590 if (ret < 0 || id != 16) {
591 errmsg = "ASN.1 decoding failure - wrong password?";
592 goto error;
595 /* Expect a load of INTEGERs. */
596 if (key->type == OSSH_RSA)
597 num_integers = 9;
598 else if (key->type == OSSH_DSA)
599 num_integers = 6;
602 * Space to create key blob in.
604 blobbuf = buf_new(3000);
606 if (key->type == OSSH_DSA) {
607 buf_putstring(blobbuf, "ssh-dss", 7);
608 } else if (key->type == OSSH_RSA) {
609 buf_putstring(blobbuf, "ssh-rsa", 7);
612 for (i = 0; i < num_integers; i++) {
613 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
614 &id, &len, &flags);
615 p += ret;
616 if (ret < 0 || id != 2 ||
617 key->keyblob+key->keyblob_len-p < len) {
618 errmsg = "ASN.1 decoding failure";
619 goto error;
622 if (i == 0) {
624 * The first integer should be zero always (I think
625 * this is some sort of version indication).
627 if (len != 1 || p[0] != 0) {
628 errmsg = "Version number mismatch";
629 goto error;
631 } else if (key->type == OSSH_RSA) {
633 * OpenSSH key order is n, e, d, p, q, dmp1, dmq1, iqmp
634 * but we want e, n, d, p, q
636 if (i == 1) {
637 /* Save the details for after we deal with number 2. */
638 modptr = (char *)p;
639 modlen = len;
640 } else if (i >= 2 && i <= 5) {
641 buf_putstring(blobbuf, p, len);
642 if (i == 2) {
643 buf_putstring(blobbuf, modptr, modlen);
646 } else if (key->type == OSSH_DSA) {
648 * OpenSSH key order is p, q, g, y, x,
649 * we want the same.
651 buf_putstring(blobbuf, p, len);
654 /* Skip past the number. */
655 p += len;
659 * Now put together the actual key. Simplest way to do this is
660 * to assemble our own key blobs and feed them to the createkey
661 * functions; this is a bit faffy but it does mean we get all
662 * the sanity checks for free.
664 retkey = new_sign_key();
665 buf_setpos(blobbuf, 0);
666 type = DROPBEAR_SIGNKEY_ANY;
667 if (buf_get_priv_key(blobbuf, retkey, &type)
668 != DROPBEAR_SUCCESS) {
669 errmsg = "unable to create key structure";
670 sign_key_free(retkey);
671 retkey = NULL;
672 goto error;
675 errmsg = NULL; /* no error */
676 retval = retkey;
678 error:
679 if (blobbuf) {
680 buf_burn(blobbuf);
681 buf_free(blobbuf);
683 m_burn(key->keyblob, key->keyblob_size);
684 m_free(key->keyblob);
685 m_burn(key, sizeof(key));
686 m_free(key);
687 if (errmsg) {
688 fprintf(stderr, "Error: %s\n", errmsg);
690 return retval;
693 static int openssh_write(const char *filename, sign_key *key,
694 char *passphrase)
696 buffer * keyblob = NULL;
697 buffer * extrablob = NULL; /* used for calculated values to write */
698 unsigned char *outblob = NULL;
699 int outlen = -9999;
700 struct mpint_pos numbers[9];
701 int nnumbers = -1, pos, len, seqlen, i;
702 char *header = NULL, *footer = NULL;
703 char zero[1];
704 int ret = 0;
705 FILE *fp;
706 int keytype = -1;
708 #ifdef DROPBEAR_RSA
709 mp_int dmp1, dmq1, iqmp, tmpval; /* for rsa */
711 if (key->rsakey != NULL) {
712 keytype = DROPBEAR_SIGNKEY_RSA;
714 #endif
715 #ifdef DROPBEAR_DSS
716 if (key->dsskey != NULL) {
717 keytype = DROPBEAR_SIGNKEY_DSS;
719 #endif
721 dropbear_assert(keytype != -1);
724 * Fetch the key blobs.
726 keyblob = buf_new(3000);
727 buf_put_priv_key(keyblob, key, keytype);
729 buf_setpos(keyblob, 0);
730 /* skip the "ssh-rsa" or "ssh-dss" header */
731 buf_incrpos(keyblob, buf_getint(keyblob));
734 * Find the sequence of integers to be encoded into the OpenSSH
735 * key blob, and also decide on the header line.
737 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
739 #ifdef DROPBEAR_RSA
740 if (keytype == DROPBEAR_SIGNKEY_RSA) {
742 if (key->rsakey->p == NULL || key->rsakey->q == NULL) {
743 fprintf(stderr, "Pre-0.33 Dropbear keys cannot be converted to OpenSSH keys.\n");
744 goto error;
747 /* e */
748 numbers[2].bytes = buf_getint(keyblob);
749 numbers[2].start = buf_getptr(keyblob, numbers[2].bytes);
750 buf_incrpos(keyblob, numbers[2].bytes);
752 /* n */
753 numbers[1].bytes = buf_getint(keyblob);
754 numbers[1].start = buf_getptr(keyblob, numbers[1].bytes);
755 buf_incrpos(keyblob, numbers[1].bytes);
757 /* d */
758 numbers[3].bytes = buf_getint(keyblob);
759 numbers[3].start = buf_getptr(keyblob, numbers[3].bytes);
760 buf_incrpos(keyblob, numbers[3].bytes);
762 /* p */
763 numbers[4].bytes = buf_getint(keyblob);
764 numbers[4].start = buf_getptr(keyblob, numbers[4].bytes);
765 buf_incrpos(keyblob, numbers[4].bytes);
767 /* q */
768 numbers[5].bytes = buf_getint(keyblob);
769 numbers[5].start = buf_getptr(keyblob, numbers[5].bytes);
770 buf_incrpos(keyblob, numbers[5].bytes);
772 /* now calculate some extra parameters: */
773 m_mp_init(&tmpval);
774 m_mp_init(&dmp1);
775 m_mp_init(&dmq1);
776 m_mp_init(&iqmp);
778 /* dmp1 = d mod (p-1) */
779 if (mp_sub_d(key->rsakey->p, 1, &tmpval) != MP_OKAY) {
780 fprintf(stderr, "Bignum error for p-1\n");
781 goto error;
783 if (mp_mod(key->rsakey->d, &tmpval, &dmp1) != MP_OKAY) {
784 fprintf(stderr, "Bignum error for dmp1\n");
785 goto error;
788 /* dmq1 = d mod (q-1) */
789 if (mp_sub_d(key->rsakey->q, 1, &tmpval) != MP_OKAY) {
790 fprintf(stderr, "Bignum error for q-1\n");
791 goto error;
793 if (mp_mod(key->rsakey->d, &tmpval, &dmq1) != MP_OKAY) {
794 fprintf(stderr, "Bignum error for dmq1\n");
795 goto error;
798 /* iqmp = (q^-1) mod p */
799 if (mp_invmod(key->rsakey->q, key->rsakey->p, &iqmp) != MP_OKAY) {
800 fprintf(stderr, "Bignum error for iqmp\n");
801 goto error;
804 extrablob = buf_new(2000);
805 buf_putmpint(extrablob, &dmp1);
806 buf_putmpint(extrablob, &dmq1);
807 buf_putmpint(extrablob, &iqmp);
808 buf_setpos(extrablob, 0);
809 mp_clear(&dmp1);
810 mp_clear(&dmq1);
811 mp_clear(&iqmp);
812 mp_clear(&tmpval);
814 /* dmp1 */
815 numbers[6].bytes = buf_getint(extrablob);
816 numbers[6].start = buf_getptr(extrablob, numbers[6].bytes);
817 buf_incrpos(extrablob, numbers[6].bytes);
819 /* dmq1 */
820 numbers[7].bytes = buf_getint(extrablob);
821 numbers[7].start = buf_getptr(extrablob, numbers[7].bytes);
822 buf_incrpos(extrablob, numbers[7].bytes);
824 /* iqmp */
825 numbers[8].bytes = buf_getint(extrablob);
826 numbers[8].start = buf_getptr(extrablob, numbers[8].bytes);
827 buf_incrpos(extrablob, numbers[8].bytes);
829 nnumbers = 9;
830 header = "-----BEGIN RSA PRIVATE KEY-----\n";
831 footer = "-----END RSA PRIVATE KEY-----\n";
833 #endif /* DROPBEAR_RSA */
835 #ifdef DROPBEAR_DSS
836 if (keytype == DROPBEAR_SIGNKEY_DSS) {
838 /* p */
839 numbers[1].bytes = buf_getint(keyblob);
840 numbers[1].start = buf_getptr(keyblob, numbers[1].bytes);
841 buf_incrpos(keyblob, numbers[1].bytes);
843 /* q */
844 numbers[2].bytes = buf_getint(keyblob);
845 numbers[2].start = buf_getptr(keyblob, numbers[2].bytes);
846 buf_incrpos(keyblob, numbers[2].bytes);
848 /* g */
849 numbers[3].bytes = buf_getint(keyblob);
850 numbers[3].start = buf_getptr(keyblob, numbers[3].bytes);
851 buf_incrpos(keyblob, numbers[3].bytes);
853 /* y */
854 numbers[4].bytes = buf_getint(keyblob);
855 numbers[4].start = buf_getptr(keyblob, numbers[4].bytes);
856 buf_incrpos(keyblob, numbers[4].bytes);
858 /* x */
859 numbers[5].bytes = buf_getint(keyblob);
860 numbers[5].start = buf_getptr(keyblob, numbers[5].bytes);
861 buf_incrpos(keyblob, numbers[5].bytes);
863 nnumbers = 6;
864 header = "-----BEGIN DSA PRIVATE KEY-----\n";
865 footer = "-----END DSA PRIVATE KEY-----\n";
867 #endif /* DROPBEAR_DSS */
870 * Now count up the total size of the ASN.1 encoded integers,
871 * so as to determine the length of the containing SEQUENCE.
873 len = 0;
874 for (i = 0; i < nnumbers; i++) {
875 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
876 len += numbers[i].bytes;
878 seqlen = len;
879 /* Now add on the SEQUENCE header. */
880 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
881 /* Round up to the cipher block size, ensuring we have at least one
882 * byte of padding (see below). */
883 outlen = len;
884 if (passphrase)
885 outlen = (outlen+8) &~ 7;
888 * Now we know how big outblob needs to be. Allocate it.
890 outblob = (unsigned char*)m_malloc(outlen);
893 * And write the data into it.
895 pos = 0;
896 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
897 for (i = 0; i < nnumbers; i++) {
898 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
899 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
900 pos += numbers[i].bytes;
904 * Padding on OpenSSH keys is deterministic. The number of
905 * padding bytes is always more than zero, and always at most
906 * the cipher block length. The value of each padding byte is
907 * equal to the number of padding bytes. So a plaintext that's
908 * an exact multiple of the block size will be padded with 08
909 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
910 * plaintext one byte less than a multiple of the block size
911 * will be padded with just 01.
913 * This enables the OpenSSL key decryption function to strip
914 * off the padding algorithmically and return the unpadded
915 * plaintext to the next layer: it looks at the final byte, and
916 * then expects to find that many bytes at the end of the data
917 * with the same value. Those are all removed and the rest is
918 * returned.
920 dropbear_assert(pos == len);
921 while (pos < outlen) {
922 outblob[pos++] = outlen - len;
926 * Encrypt the key.
928 if (passphrase) {
929 fprintf(stderr, "Encrypted keys aren't supported currently\n");
930 goto error;
934 * And save it. We'll use Unix line endings just in case it's
935 * subsequently transferred in binary mode.
937 if (strlen(filename) == 1 && filename[0] == '-') {
938 fp = stdout;
939 } else {
940 fp = fopen(filename, "wb"); /* ensure Unix line endings */
942 if (!fp) {
943 fprintf(stderr, "Failed opening output file\n");
944 goto error;
946 fputs(header, fp);
947 base64_encode_fp(fp, outblob, outlen, 64);
948 fputs(footer, fp);
949 fclose(fp);
950 ret = 1;
952 error:
953 if (outblob) {
954 memset(outblob, 0, outlen);
955 m_free(outblob);
957 if (keyblob) {
958 buf_burn(keyblob);
959 buf_free(keyblob);
961 if (extrablob) {
962 buf_burn(extrablob);
963 buf_free(extrablob);
965 return ret;
968 #if 0
969 /* XXX TODO ssh.com stuff isn't going yet */
971 /* ----------------------------------------------------------------------
972 * Code to read ssh.com private keys.
976 * The format of the base64 blob is largely ssh2-packet-formatted,
977 * except that mpints are a bit different: they're more like the
978 * old ssh1 mpint. You have a 32-bit bit count N, followed by
979 * (N+7)/8 bytes of data.
981 * So. The blob contains:
983 * - uint32 0x3f6ff9eb (magic number)
984 * - uint32 size (total blob size)
985 * - string key-type (see below)
986 * - string cipher-type (tells you if key is encrypted)
987 * - string encrypted-blob
989 * (The first size field includes the size field itself and the
990 * magic number before it. All other size fields are ordinary ssh2
991 * strings, so the size field indicates how much data is to
992 * _follow_.)
994 * The encrypted blob, once decrypted, contains a single string
995 * which in turn contains the payload. (This allows padding to be
996 * added after that string while still making it clear where the
997 * real payload ends. Also it probably makes for a reasonable
998 * decryption check.)
1000 * The payload blob, for an RSA key, contains:
1001 * - mpint e
1002 * - mpint d
1003 * - mpint n (yes, the public and private stuff is intermixed)
1004 * - mpint u (presumably inverse of p mod q)
1005 * - mpint p (p is the smaller prime)
1006 * - mpint q (q is the larger)
1008 * For a DSA key, the payload blob contains:
1009 * - uint32 0
1010 * - mpint p
1011 * - mpint g
1012 * - mpint q
1013 * - mpint y
1014 * - mpint x
1016 * Alternatively, if the parameters are `predefined', that
1017 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1018 * containing some predefined parameter specification. *shudder*,
1019 * but I doubt we'll encounter this in real life.
1021 * The key type strings are ghastly. The RSA key I looked at had a
1022 * type string of
1024 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1026 * and the DSA key wasn't much better:
1028 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1030 * It isn't clear that these will always be the same. I think it
1031 * might be wise just to look at the `if-modn{sign{rsa' and
1032 * `dl-modp{sign{dsa' prefixes.
1034 * Finally, the encryption. The cipher-type string appears to be
1035 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
1036 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1037 * from the passphrase by means of yet another hashing faff:
1039 * - first 16 bytes are MD5(passphrase)
1040 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1041 * - if there were more, they'd be MD5(passphrase || first 32),
1042 * and so on.
1045 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1047 struct sshcom_key {
1048 char comment[256]; /* allowing any length is overkill */
1049 unsigned char *keyblob;
1050 int keyblob_len, keyblob_size;
1053 static struct sshcom_key *load_sshcom_key(const char *filename)
1055 struct sshcom_key *ret;
1056 FILE *fp;
1057 char buffer[256];
1058 int len;
1059 char *errmsg, *p;
1060 int headers_done;
1061 char base64_bit[4];
1062 int base64_chars = 0;
1064 ret = snew(struct sshcom_key);
1065 ret->comment[0] = '\0';
1066 ret->keyblob = NULL;
1067 ret->keyblob_len = ret->keyblob_size = 0;
1069 fp = fopen(filename, "r");
1070 if (!fp) {
1071 errmsg = "Unable to open key file";
1072 goto error;
1074 if (!fgets(buffer, sizeof(buffer), fp) ||
1075 0 != strcmp(buffer, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1076 errmsg = "File does not begin with ssh.com key header";
1077 goto error;
1080 headers_done = 0;
1081 while (1) {
1082 if (!fgets(buffer, sizeof(buffer), fp)) {
1083 errmsg = "Unexpected end of file";
1084 goto error;
1086 if (!strcmp(buffer, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1087 break; /* done */
1088 if ((p = strchr(buffer, ':')) != NULL) {
1089 if (headers_done) {
1090 errmsg = "Header found in body of key data";
1091 goto error;
1093 *p++ = '\0';
1094 while (*p && isspace((unsigned char)*p)) p++;
1096 * Header lines can end in a trailing backslash for
1097 * continuation.
1099 while ((len = strlen(p)) > (int)(sizeof(buffer) - (p-buffer) -1) ||
1100 p[len-1] != '\n' || p[len-2] == '\\') {
1101 if (len > (int)((p-buffer) + sizeof(buffer)-2)) {
1102 errmsg = "Header line too long to deal with";
1103 goto error;
1105 if (!fgets(p+len-2, sizeof(buffer)-(p-buffer)-(len-2), fp)) {
1106 errmsg = "Unexpected end of file";
1107 goto error;
1110 p[strcspn(p, "\n")] = '\0';
1111 if (!strcmp(buffer, "Comment")) {
1112 /* Strip quotes in comment if present. */
1113 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1114 p++;
1115 p[strlen(p)-1] = '\0';
1117 strncpy(ret->comment, p, sizeof(ret->comment));
1118 ret->comment[sizeof(ret->comment)-1] = '\0';
1120 } else {
1121 headers_done = 1;
1123 p = buffer;
1124 while (isbase64(*p)) {
1125 base64_bit[base64_chars++] = *p;
1126 if (base64_chars == 4) {
1127 unsigned char out[3];
1129 base64_chars = 0;
1131 len = base64_decode_atom(base64_bit, out);
1133 if (len <= 0) {
1134 errmsg = "Invalid base64 encoding";
1135 goto error;
1138 if (ret->keyblob_len + len > ret->keyblob_size) {
1139 ret->keyblob_size = ret->keyblob_len + len + 256;
1140 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1141 unsigned char);
1144 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1145 ret->keyblob_len += len;
1148 p++;
1153 if (ret->keyblob_len == 0 || !ret->keyblob) {
1154 errmsg = "Key body not present";
1155 goto error;
1158 return ret;
1160 error:
1161 if (ret) {
1162 if (ret->keyblob) {
1163 memset(ret->keyblob, 0, ret->keyblob_size);
1164 m_free(ret->keyblob);
1166 memset(&ret, 0, sizeof(ret));
1167 m_free(ret);
1169 return NULL;
1172 int sshcom_encrypted(const char *filename, char **comment)
1174 struct sshcom_key *key = load_sshcom_key(filename);
1175 int pos, len, answer;
1177 *comment = NULL;
1178 if (!key)
1179 return 0;
1182 * Check magic number.
1184 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
1185 return 0; /* key is invalid */
1188 * Find the cipher-type string.
1190 answer = 0;
1191 pos = 8;
1192 if (key->keyblob_len < pos+4)
1193 goto done; /* key is far too short */
1194 pos += 4 + GET_32BIT(key->keyblob + pos); /* skip key type */
1195 if (key->keyblob_len < pos+4)
1196 goto done; /* key is far too short */
1197 len = GET_32BIT(key->keyblob + pos); /* find cipher-type length */
1198 if (key->keyblob_len < pos+4+len)
1199 goto done; /* cipher type string is incomplete */
1200 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1201 answer = 1;
1203 done:
1204 *comment = dupstr(key->comment);
1205 memset(key->keyblob, 0, key->keyblob_size);
1206 m_free(key->keyblob);
1207 memset(&key, 0, sizeof(key));
1208 m_free(key);
1209 return answer;
1212 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1214 int bits;
1215 int bytes;
1216 unsigned char *d = (unsigned char *) data;
1218 if (len < 4)
1219 goto error;
1220 bits = GET_32BIT(d);
1222 bytes = (bits + 7) / 8;
1223 if (len < 4+bytes)
1224 goto error;
1226 ret->start = d + 4;
1227 ret->bytes = bytes;
1228 return bytes+4;
1230 error:
1231 ret->start = NULL;
1232 ret->bytes = -1;
1233 return len; /* ensure further calls fail as well */
1236 static int sshcom_put_mpint(void *target, void *data, int len)
1238 unsigned char *d = (unsigned char *)target;
1239 unsigned char *i = (unsigned char *)data;
1240 int bits = len * 8 - 1;
1242 while (bits > 0) {
1243 if (*i & (1 << (bits & 7)))
1244 break;
1245 if (!(bits-- & 7))
1246 i++, len--;
1249 PUT_32BIT(d, bits+1);
1250 memcpy(d+4, i, len);
1251 return len+4;
1254 sign_key *sshcom_read(const char *filename, char *passphrase)
1256 struct sshcom_key *key = load_sshcom_key(filename);
1257 char *errmsg;
1258 int pos, len;
1259 const char prefix_rsa[] = "if-modn{sign{rsa";
1260 const char prefix_dsa[] = "dl-modp{sign{dsa";
1261 enum { RSA, DSA } type;
1262 int encrypted;
1263 char *ciphertext;
1264 int cipherlen;
1265 struct ssh2_userkey *ret = NULL, *retkey;
1266 const struct ssh_signkey *alg;
1267 unsigned char *blob = NULL;
1268 int blobsize, publen, privlen;
1270 if (!key)
1271 return NULL;
1274 * Check magic number.
1276 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1277 errmsg = "Key does not begin with magic number";
1278 goto error;
1282 * Determine the key type.
1284 pos = 8;
1285 if (key->keyblob_len < pos+4 ||
1286 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1287 errmsg = "Key blob does not contain a key type string";
1288 goto error;
1290 if (len > sizeof(prefix_rsa) - 1 &&
1291 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1292 type = RSA;
1293 } else if (len > sizeof(prefix_dsa) - 1 &&
1294 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1295 type = DSA;
1296 } else {
1297 errmsg = "Key is of unknown type";
1298 goto error;
1300 pos += 4+len;
1303 * Determine the cipher type.
1305 if (key->keyblob_len < pos+4 ||
1306 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1307 errmsg = "Key blob does not contain a cipher type string";
1308 goto error;
1310 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1311 encrypted = 0;
1312 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1313 encrypted = 1;
1314 else {
1315 errmsg = "Key encryption is of unknown type";
1316 goto error;
1318 pos += 4+len;
1321 * Get hold of the encrypted part of the key.
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 actual key data";
1326 goto error;
1328 ciphertext = (char *)key->keyblob + pos + 4;
1329 cipherlen = len;
1330 if (cipherlen == 0) {
1331 errmsg = "Length of key data is zero";
1332 goto error;
1336 * Decrypt it if necessary.
1338 if (encrypted) {
1340 * Derive encryption key from passphrase and iv/salt:
1342 * - let block A equal MD5(passphrase)
1343 * - let block B equal MD5(passphrase || A)
1344 * - block C would be MD5(passphrase || A || B) and so on
1345 * - encryption key is the first N bytes of A || B
1347 struct MD5Context md5c;
1348 unsigned char keybuf[32], iv[8];
1350 if (cipherlen % 8 != 0) {
1351 errmsg = "Encrypted part of key is not a multiple of cipher block"
1352 " size";
1353 goto error;
1356 MD5Init(&md5c);
1357 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1358 MD5Final(keybuf, &md5c);
1360 MD5Init(&md5c);
1361 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1362 MD5Update(&md5c, keybuf, 16);
1363 MD5Final(keybuf+16, &md5c);
1366 * Now decrypt the key blob.
1368 memset(iv, 0, sizeof(iv));
1369 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1370 cipherlen);
1372 memset(&md5c, 0, sizeof(md5c));
1373 memset(keybuf, 0, sizeof(keybuf));
1376 * Hereafter we return WRONG_PASSPHRASE for any parsing
1377 * error. (But only if we've just tried to decrypt it!
1378 * Returning WRONG_PASSPHRASE for an unencrypted key is
1379 * automatic doom.)
1381 if (encrypted)
1382 ret = SSH2_WRONG_PASSPHRASE;
1386 * Strip away the containing string to get to the real meat.
1388 len = GET_32BIT(ciphertext);
1389 if (len > cipherlen-4) {
1390 errmsg = "containing string was ill-formed";
1391 goto error;
1393 ciphertext += 4;
1394 cipherlen = len;
1397 * Now we break down into RSA versus DSA. In either case we'll
1398 * construct public and private blobs in our own format, and
1399 * end up feeding them to alg->createkey().
1401 blobsize = cipherlen + 256;
1402 blob = snewn(blobsize, unsigned char);
1403 privlen = 0;
1404 if (type == RSA) {
1405 struct mpint_pos n, e, d, u, p, q;
1406 int pos = 0;
1407 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1408 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1409 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1410 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1411 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1412 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1413 if (!q.start) {
1414 errmsg = "key data did not contain six integers";
1415 goto error;
1418 alg = &ssh_rsa;
1419 pos = 0;
1420 pos += put_string(blob+pos, "ssh-rsa", 7);
1421 pos += put_mp(blob+pos, e.start, e.bytes);
1422 pos += put_mp(blob+pos, n.start, n.bytes);
1423 publen = pos;
1424 pos += put_string(blob+pos, d.start, d.bytes);
1425 pos += put_mp(blob+pos, q.start, q.bytes);
1426 pos += put_mp(blob+pos, p.start, p.bytes);
1427 pos += put_mp(blob+pos, u.start, u.bytes);
1428 privlen = pos - publen;
1429 } else if (type == DSA) {
1430 struct mpint_pos p, q, g, x, y;
1431 int pos = 4;
1432 if (GET_32BIT(ciphertext) != 0) {
1433 errmsg = "predefined DSA parameters not supported";
1434 goto error;
1436 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1437 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1438 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1439 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1440 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1441 if (!x.start) {
1442 errmsg = "key data did not contain five integers";
1443 goto error;
1446 alg = &ssh_dss;
1447 pos = 0;
1448 pos += put_string(blob+pos, "ssh-dss", 7);
1449 pos += put_mp(blob+pos, p.start, p.bytes);
1450 pos += put_mp(blob+pos, q.start, q.bytes);
1451 pos += put_mp(blob+pos, g.start, g.bytes);
1452 pos += put_mp(blob+pos, y.start, y.bytes);
1453 publen = pos;
1454 pos += put_mp(blob+pos, x.start, x.bytes);
1455 privlen = pos - publen;
1458 dropbear_assert(privlen > 0); /* should have bombed by now if not */
1460 retkey = snew(struct ssh2_userkey);
1461 retkey->alg = alg;
1462 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1463 if (!retkey->data) {
1464 m_free(retkey);
1465 errmsg = "unable to create key data structure";
1466 goto error;
1468 retkey->comment = dupstr(key->comment);
1470 errmsg = NULL; /* no error */
1471 ret = retkey;
1473 error:
1474 if (blob) {
1475 memset(blob, 0, blobsize);
1476 m_free(blob);
1478 memset(key->keyblob, 0, key->keyblob_size);
1479 m_free(key->keyblob);
1480 memset(&key, 0, sizeof(key));
1481 m_free(key);
1482 return ret;
1485 int sshcom_write(const char *filename, sign_key *key,
1486 char *passphrase)
1488 unsigned char *pubblob, *privblob;
1489 int publen, privlen;
1490 unsigned char *outblob;
1491 int outlen;
1492 struct mpint_pos numbers[6];
1493 int nnumbers, initial_zero, pos, lenpos, i;
1494 char *type;
1495 char *ciphertext;
1496 int cipherlen;
1497 int ret = 0;
1498 FILE *fp;
1501 * Fetch the key blobs.
1503 pubblob = key->alg->public_blob(key->data, &publen);
1504 privblob = key->alg->private_blob(key->data, &privlen);
1505 outblob = NULL;
1508 * Find the sequence of integers to be encoded into the OpenSSH
1509 * key blob, and also decide on the header line.
1511 if (key->alg == &ssh_rsa) {
1512 int pos;
1513 struct mpint_pos n, e, d, p, q, iqmp;
1515 pos = 4 + GET_32BIT(pubblob);
1516 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1517 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1518 pos = 0;
1519 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1520 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1521 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1522 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1524 dropbear_assert(e.start && iqmp.start); /* can't go wrong */
1526 numbers[0] = e;
1527 numbers[1] = d;
1528 numbers[2] = n;
1529 numbers[3] = iqmp;
1530 numbers[4] = q;
1531 numbers[5] = p;
1533 nnumbers = 6;
1534 initial_zero = 0;
1535 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1536 } else if (key->alg == &ssh_dss) {
1537 int pos;
1538 struct mpint_pos p, q, g, y, x;
1540 pos = 4 + GET_32BIT(pubblob);
1541 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1542 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1543 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1544 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1545 pos = 0;
1546 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1548 dropbear_assert(y.start && x.start); /* can't go wrong */
1550 numbers[0] = p;
1551 numbers[1] = g;
1552 numbers[2] = q;
1553 numbers[3] = y;
1554 numbers[4] = x;
1556 nnumbers = 5;
1557 initial_zero = 1;
1558 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1559 } else {
1560 dropbear_assert(0); /* zoinks! */
1564 * Total size of key blob will be somewhere under 512 plus
1565 * combined length of integers. We'll calculate the more
1566 * precise size as we construct the blob.
1568 outlen = 512;
1569 for (i = 0; i < nnumbers; i++)
1570 outlen += 4 + numbers[i].bytes;
1571 outblob = snewn(outlen, unsigned char);
1574 * Create the unencrypted key blob.
1576 pos = 0;
1577 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1578 pos += 4; /* length field, fill in later */
1579 pos += put_string(outblob+pos, type, strlen(type));
1581 char *ciphertype = passphrase ? "3des-cbc" : "none";
1582 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1584 lenpos = pos; /* remember this position */
1585 pos += 4; /* encrypted-blob size */
1586 pos += 4; /* encrypted-payload size */
1587 if (initial_zero) {
1588 PUT_32BIT(outblob+pos, 0);
1589 pos += 4;
1591 for (i = 0; i < nnumbers; i++)
1592 pos += sshcom_put_mpint(outblob+pos,
1593 numbers[i].start, numbers[i].bytes);
1594 /* Now wrap up the encrypted payload. */
1595 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1596 /* Pad encrypted blob to a multiple of cipher block size. */
1597 if (passphrase) {
1598 int padding = -(pos - (lenpos+4)) & 7;
1599 while (padding--)
1600 outblob[pos++] = random_byte();
1602 ciphertext = (char *)outblob+lenpos+4;
1603 cipherlen = pos - (lenpos+4);
1604 dropbear_assert(!passphrase || cipherlen % 8 == 0);
1605 /* Wrap up the encrypted blob string. */
1606 PUT_32BIT(outblob+lenpos, cipherlen);
1607 /* And finally fill in the total length field. */
1608 PUT_32BIT(outblob+4, pos);
1610 dropbear_assert(pos < outlen);
1613 * Encrypt the key.
1615 if (passphrase) {
1617 * Derive encryption key from passphrase and iv/salt:
1619 * - let block A equal MD5(passphrase)
1620 * - let block B equal MD5(passphrase || A)
1621 * - block C would be MD5(passphrase || A || B) and so on
1622 * - encryption key is the first N bytes of A || B
1624 struct MD5Context md5c;
1625 unsigned char keybuf[32], iv[8];
1627 MD5Init(&md5c);
1628 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1629 MD5Final(keybuf, &md5c);
1631 MD5Init(&md5c);
1632 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1633 MD5Update(&md5c, keybuf, 16);
1634 MD5Final(keybuf+16, &md5c);
1637 * Now decrypt the key blob.
1639 memset(iv, 0, sizeof(iv));
1640 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1641 cipherlen);
1643 memset(&md5c, 0, sizeof(md5c));
1644 memset(keybuf, 0, sizeof(keybuf));
1648 * And save it. We'll use Unix line endings just in case it's
1649 * subsequently transferred in binary mode.
1651 fp = fopen(filename, "wb"); /* ensure Unix line endings */
1652 if (!fp)
1653 goto error;
1654 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1655 fprintf(fp, "Comment: \"");
1657 * Comment header is broken with backslash-newline if it goes
1658 * over 70 chars. Although it's surrounded by quotes, it
1659 * _doesn't_ escape backslashes or quotes within the string.
1660 * Don't ask me, I didn't design it.
1663 int slen = 60; /* starts at 60 due to "Comment: " */
1664 char *c = key->comment;
1665 while ((int)strlen(c) > slen) {
1666 fprintf(fp, "%.*s\\\n", slen, c);
1667 c += slen;
1668 slen = 70; /* allow 70 chars on subsequent lines */
1670 fprintf(fp, "%s\"\n", c);
1672 base64_encode_fp(fp, outblob, pos, 70);
1673 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1674 fclose(fp);
1675 ret = 1;
1677 error:
1678 if (outblob) {
1679 memset(outblob, 0, outlen);
1680 m_free(outblob);
1682 if (privblob) {
1683 memset(privblob, 0, privlen);
1684 m_free(privblob);
1686 if (pubblob) {
1687 memset(pubblob, 0, publen);
1688 m_free(pubblob);
1690 return ret;
1692 #endif /* ssh.com stuff disabled */