2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 int openssh_encrypted(const Filename *filename);
16 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
17 const char **errmsg_p);
18 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
21 int sshcom_encrypted(const Filename *filename, char **comment);
22 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
23 const char **errmsg_p);
24 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
28 * Given a key type, determine whether we know how to import it.
30 int import_possible(int type)
32 if (type == SSH_KEYTYPE_OPENSSH)
34 if (type == SSH_KEYTYPE_SSHCOM)
40 * Given a key type, determine what native key type
41 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
44 int import_target_type(int type)
47 * There are no known foreign SSH-1 key formats.
49 return SSH_KEYTYPE_SSH2;
53 * Determine whether a foreign key is encrypted.
55 int import_encrypted(const Filename *filename, int type, char **comment)
57 if (type == SSH_KEYTYPE_OPENSSH) {
58 /* OpenSSH doesn't do key comments */
59 *comment = dupstr(filename_to_str(filename));
60 return openssh_encrypted(filename);
62 if (type == SSH_KEYTYPE_SSHCOM) {
63 return sshcom_encrypted(filename, comment);
69 * Import an SSH-1 key.
71 int import_ssh1(const Filename *filename, int type,
72 struct RSAKey *key, char *passphrase, const char **errmsg_p)
78 * Import an SSH-2 key.
80 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
81 char *passphrase, const char **errmsg_p)
83 if (type == SSH_KEYTYPE_OPENSSH)
84 return openssh_read(filename, passphrase, errmsg_p);
85 if (type == SSH_KEYTYPE_SSHCOM)
86 return sshcom_read(filename, passphrase, errmsg_p);
91 * Export an SSH-1 key.
93 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
100 * Export an SSH-2 key.
102 int export_ssh2(const Filename *filename, int type,
103 struct ssh2_userkey *key, char *passphrase)
105 if (type == SSH_KEYTYPE_OPENSSH)
106 return openssh_write(filename, key, passphrase);
107 if (type == SSH_KEYTYPE_SSHCOM)
108 return sshcom_write(filename, key, passphrase);
113 * Strip trailing CRs and LFs at the end of a line of text.
115 void strip_crlf(char *str)
117 char *p = str + strlen(str);
119 while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
123 /* ----------------------------------------------------------------------
124 * Helper routines. (The base64 ones are defined in sshpubk.c.)
127 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
128 ((c) >= 'a' && (c) <= 'z') || \
129 ((c) >= '0' && (c) <= '9') || \
130 (c) == '+' || (c) == '/' || (c) == '=' \
134 * Read an ASN.1/BER identifier and length pair.
136 * Flags are a combination of the #defines listed below.
138 * Returns -1 if unsuccessful; otherwise returns the number of
139 * bytes used out of the source data.
142 /* ASN.1 tag classes. */
143 #define ASN1_CLASS_UNIVERSAL (0 << 6)
144 #define ASN1_CLASS_APPLICATION (1 << 6)
145 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
146 #define ASN1_CLASS_PRIVATE (3 << 6)
147 #define ASN1_CLASS_MASK (3 << 6)
149 /* Primitive versus constructed bit. */
150 #define ASN1_CONSTRUCTED (1 << 5)
152 static int ber_read_id_len(void *source, int sourcelen,
153 int *id, int *length, int *flags)
155 unsigned char *p = (unsigned char *) source;
160 *flags = (*p & 0xE0);
161 if ((*p & 0x1F) == 0x1F) {
167 *id = (*id << 7) | (*p & 0x7F);
185 *length = (*length << 8) | (*p++);
192 return p - (unsigned char *) source;
196 * Write an ASN.1/BER identifier and length pair. Returns the
197 * number of bytes consumed. Assumes dest contains enough space.
198 * Will avoid writing anything if dest is NULL, but still return
199 * amount of space required.
201 static int ber_write_id_len(void *dest, int id, int length, int flags)
203 unsigned char *d = (unsigned char *)dest;
208 * Identifier is one byte.
211 if (d) *d++ = id | flags;
215 * Identifier is multiple bytes: the first byte is 11111
216 * plus the flags, and subsequent bytes encode the value of
217 * the identifier, 7 bits at a time, with the top bit of
218 * each byte 1 except the last one which is 0.
221 if (d) *d++ = 0x1F | flags;
222 for (n = 1; (id >> (7*n)) > 0; n++)
223 continue; /* count the bytes */
226 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
232 * Length is one byte.
235 if (d) *d++ = length;
239 * Length is multiple bytes. The first is 0x80 plus the
240 * number of subsequent bytes, and the subsequent bytes
241 * encode the actual length.
243 for (n = 1; (length >> (8*n)) > 0; n++)
244 continue; /* count the bytes */
246 if (d) *d++ = 0x80 | n;
249 if (d) *d++ = (length >> (8*n)) & 0xFF;
256 static int put_string(void *target, void *data, int len)
258 unsigned char *d = (unsigned char *)target;
261 memcpy(d+4, data, len);
265 static int put_mp(void *target, void *data, int len)
267 unsigned char *d = (unsigned char *)target;
268 unsigned char *i = (unsigned char *)data;
273 memcpy(d+5, data, len);
277 memcpy(d+4, data, len);
282 /* Simple structure to point to an mp-int within a blob. */
283 struct mpint_pos { void *start; int bytes; };
285 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
288 unsigned char *d = (unsigned char *) data;
292 bytes = toint(GET_32BIT(d));
293 if (bytes < 0 || len-4 < bytes)
303 return len; /* ensure further calls fail as well */
306 /* ----------------------------------------------------------------------
307 * Code to read and write OpenSSH private keys.
310 enum { OSSH_DSA, OSSH_RSA, OSSH_ECDSA };
311 enum { OSSH_ENC_3DES, OSSH_ENC_AES };
314 int encrypted, encryption;
316 unsigned char *keyblob;
317 int keyblob_len, keyblob_size;
320 static struct openssh_key *load_openssh_key(const Filename *filename,
321 const char **errmsg_p)
323 struct openssh_key *ret;
329 int base64_chars = 0;
331 ret = snew(struct openssh_key);
333 ret->keyblob_len = ret->keyblob_size = 0;
335 memset(ret->iv, 0, sizeof(ret->iv));
337 fp = f_open(filename, "r", FALSE);
339 errmsg = "unable to open key file";
343 if (!(line = fgetline(fp))) {
344 errmsg = "unexpected end of file";
348 if (0 != strncmp(line, "-----BEGIN ", 11) ||
349 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
350 errmsg = "file does not begin with OpenSSH key header";
353 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----"))
354 ret->type = OSSH_RSA;
355 else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----"))
356 ret->type = OSSH_DSA;
357 else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----"))
358 ret->type = OSSH_ECDSA;
360 errmsg = "unrecognised key type";
363 smemclr(line, strlen(line));
369 if (!(line = fgetline(fp))) {
370 errmsg = "unexpected end of file";
374 if (0 == strncmp(line, "-----END ", 9) &&
375 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
380 if ((p = strchr(line, ':')) != NULL) {
382 errmsg = "header found in body of key data";
386 while (*p && isspace((unsigned char)*p)) p++;
387 if (!strcmp(line, "Proc-Type")) {
388 if (p[0] != '4' || p[1] != ',') {
389 errmsg = "Proc-Type is not 4 (only 4 is supported)";
393 if (!strcmp(p, "ENCRYPTED"))
395 } else if (!strcmp(line, "DEK-Info")) {
398 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
399 ret->encryption = OSSH_ENC_3DES;
401 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
402 ret->encryption = OSSH_ENC_AES;
405 errmsg = "unsupported cipher";
408 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
409 for (i = 0; i < ivlen; i++) {
410 if (1 != sscanf(p, "%2x", &j)) {
411 errmsg = "expected more iv data in DEK-Info";
418 errmsg = "more iv data than expected in DEK-Info";
426 while (isbase64(*p)) {
427 base64_bit[base64_chars++] = *p;
428 if (base64_chars == 4) {
429 unsigned char out[3];
434 len = base64_decode_atom(base64_bit, out);
437 errmsg = "invalid base64 encoding";
441 if (ret->keyblob_len + len > ret->keyblob_size) {
442 ret->keyblob_size = ret->keyblob_len + len + 256;
443 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
447 memcpy(ret->keyblob + ret->keyblob_len, out, len);
448 ret->keyblob_len += len;
450 smemclr(out, sizeof(out));
456 smemclr(line, strlen(line));
464 if (ret->keyblob_len == 0 || !ret->keyblob) {
465 errmsg = "key body not present";
469 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
470 errmsg = "encrypted key blob is not a multiple of cipher block size";
474 smemclr(base64_bit, sizeof(base64_bit));
475 if (errmsg_p) *errmsg_p = NULL;
480 smemclr(line, strlen(line));
484 smemclr(base64_bit, sizeof(base64_bit));
487 smemclr(ret->keyblob, ret->keyblob_size);
490 smemclr(ret, sizeof(*ret));
493 if (errmsg_p) *errmsg_p = errmsg;
498 int openssh_encrypted(const Filename *filename)
500 struct openssh_key *key = load_openssh_key(filename, NULL);
505 ret = key->encrypted;
506 smemclr(key->keyblob, key->keyblob_size);
508 smemclr(key, sizeof(*key));
513 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
514 const char **errmsg_p)
516 struct openssh_key *key = load_openssh_key(filename, errmsg_p);
517 struct ssh2_userkey *retkey;
519 int ret, id, len, flags;
521 struct ssh2_userkey *retval = NULL;
524 int blobsize = 0, blobptr, privptr;
533 if (key->encrypted) {
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 * (Note that only 8 bytes of the iv are used for key
543 * derivation, even when the key is encrypted with AES and
544 * hence there are 16 bytes available.)
546 struct MD5Context md5c;
547 unsigned char keybuf[32];
550 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
551 MD5Update(&md5c, (unsigned char *)key->iv, 8);
552 MD5Final(keybuf, &md5c);
555 MD5Update(&md5c, keybuf, 16);
556 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
557 MD5Update(&md5c, (unsigned char *)key->iv, 8);
558 MD5Final(keybuf+16, &md5c);
561 * Now decrypt the key blob.
563 if (key->encryption == OSSH_ENC_3DES)
564 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
565 key->keyblob, key->keyblob_len);
568 assert(key->encryption == OSSH_ENC_AES);
569 ctx = aes_make_context();
570 aes128_key(ctx, keybuf);
571 aes_iv(ctx, (unsigned char *)key->iv);
572 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
573 aes_free_context(ctx);
576 smemclr(&md5c, sizeof(md5c));
577 smemclr(keybuf, sizeof(keybuf));
581 * Now we have a decrypted key blob, which contains an ASN.1
582 * encoded private key. We must now untangle the ASN.1.
584 * We expect the whole key blob to be formatted as a SEQUENCE
585 * (0x30 followed by a length code indicating that the rest of
586 * the blob is part of the sequence). Within that SEQUENCE we
587 * expect to see a bunch of INTEGERs. What those integers mean
588 * depends on the key type:
590 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
591 * dmp1, dmq1, iqmp in that order. (The last three are d mod
592 * (p-1), d mod (q-1), inverse of q mod p respectively.)
594 * - For DSA, we expect them to be 0, p, q, g, y, x in that
597 * - In ECDSA the format is totally different: we see the
598 * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
599 * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
604 /* Expect the SEQUENCE header. Take its absence as a failure to
605 * decrypt, if the key was encrypted. */
606 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
608 if (ret < 0 || id != 16) {
609 errmsg = "ASN.1 decoding failure";
610 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
614 /* Expect a load of INTEGERs. */
615 if (key->type == OSSH_RSA)
617 else if (key->type == OSSH_DSA)
620 num_integers = 0; /* placate compiler warnings */
623 if (key->type == OSSH_ECDSA)
625 /* And now for something completely different */
628 struct ec_curve *curve;
630 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
633 if (ret < 0 || id != 2 || key->keyblob+key->keyblob_len-p < len ||
634 len != 1 || p[0] != 1) {
635 errmsg = "ASN.1 decoding failure";
636 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
640 /* Read private key OCTET STRING */
641 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
644 if (ret < 0 || id != 4 || key->keyblob+key->keyblob_len-p < len) {
645 errmsg = "ASN.1 decoding failure";
646 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
653 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
656 if (ret < 0 || id != 0 || key->keyblob+key->keyblob_len-p < len) {
657 errmsg = "ASN.1 decoding failure";
658 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
661 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
664 if (ret < 0 || id != 6 || key->keyblob+key->keyblob_len-p < len) {
665 errmsg = "ASN.1 decoding failure";
666 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
669 if (len == 8 && !memcmp(p, nistp256_oid, nistp256_oid_len)) {
671 } else if (len == 5 && !memcmp(p, nistp384_oid, nistp384_oid_len)) {
673 } else if (len == 5 && !memcmp(p, nistp521_oid, nistp521_oid_len)) {
676 errmsg = "Unsupported ECDSA curve.";
681 /* Read BIT STRING point */
682 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
685 if (ret < 0 || id != 1 || key->keyblob+key->keyblob_len-p < len) {
686 errmsg = "ASN.1 decoding failure";
687 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
690 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
693 if (ret < 0 || id != 3 || key->keyblob+key->keyblob_len-p < len ||
694 len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
695 errmsg = "ASN.1 decoding failure";
696 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
699 p += 1; len -= 1; /* Skip 0x00 before point */
701 /* Construct the key */
702 retkey = snew(struct ssh2_userkey);
704 errmsg = "out of memory";
707 if (curve->fieldBits == 256) {
708 retkey->alg = &ssh_ecdsa_nistp256;
709 } else if (curve->fieldBits == 384) {
710 retkey->alg = &ssh_ecdsa_nistp384;
712 retkey->alg = &ssh_ecdsa_nistp521;
714 blob = snewn((4+19 + 4+8 + 4+len) + (4+privlen), unsigned char);
717 errmsg = "out of memory";
721 sprintf((char*)blob+4, "ecdsa-sha2-nistp%d", curve->fieldBits);
722 PUT_32BIT(blob+4+19, 8);
723 sprintf((char*)blob+4+19+4, "nistp%d", curve->fieldBits);
724 PUT_32BIT(blob+4+19+4+8, len);
725 memcpy(blob+4+19+4+8+4, p, len);
726 PUT_32BIT(blob+4+19+4+8+4+len, privlen);
727 memcpy(blob+4+19+4+8+4+len+4, priv, privlen);
728 retkey->data = retkey->alg->createkey(blob, 4+19+4+8+4+len,
729 blob+4+19+4+8+4+len, 4+privlen);
732 errmsg = "unable to create key data structure";
736 } else if (key->type == OSSH_RSA || key->type == OSSH_DSA) {
739 * Space to create key blob in.
741 blobsize = 256+key->keyblob_len;
742 blob = snewn(blobsize, unsigned char);
744 if (key->type == OSSH_DSA)
745 memcpy(blob+4, "ssh-dss", 7);
746 else if (key->type == OSSH_RSA)
747 memcpy(blob+4, "ssh-rsa", 7);
751 for (i = 0; i < num_integers; i++) {
752 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
755 if (ret < 0 || id != 2 ||
756 key->keyblob+key->keyblob_len-p < len) {
757 errmsg = "ASN.1 decoding failure";
758 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
764 * The first integer should be zero always (I think
765 * this is some sort of version indication).
767 if (len != 1 || p[0] != 0) {
768 errmsg = "version number mismatch";
771 } else if (key->type == OSSH_RSA) {
773 * Integers 1 and 2 go into the public blob but in the
774 * opposite order; integers 3, 4, 5 and 8 go into the
775 * private blob. The other two (6 and 7) are ignored.
778 /* Save the details for after we deal with number 2. */
781 } else if (i != 6 && i != 7) {
782 PUT_32BIT(blob+blobptr, len);
783 memcpy(blob+blobptr+4, p, len);
786 PUT_32BIT(blob+blobptr, modlen);
787 memcpy(blob+blobptr+4, modptr, modlen);
792 } else if (key->type == OSSH_DSA) {
794 * Integers 1-4 go into the public blob; integer 5 goes
795 * into the private blob.
797 PUT_32BIT(blob+blobptr, len);
798 memcpy(blob+blobptr+4, p, len);
804 /* Skip past the number. */
809 * Now put together the actual key. Simplest way to do this is
810 * to assemble our own key blobs and feed them to the createkey
811 * functions; this is a bit faffy but it does mean we get all
812 * the sanity checks for free.
814 assert(privptr > 0); /* should have bombed by now if not */
815 retkey = snew(struct ssh2_userkey);
816 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
817 retkey->data = retkey->alg->createkey(blob, privptr,
818 blob+privptr, blobptr-privptr);
821 errmsg = "unable to create key data structure";
826 assert(0 && "Bad key type from load_openssh_key");
829 retkey->comment = dupstr("imported-openssh-key");
830 errmsg = NULL; /* no error */
835 smemclr(blob, blobsize);
838 smemclr(key->keyblob, key->keyblob_size);
840 smemclr(key, sizeof(*key));
842 if (errmsg_p) *errmsg_p = errmsg;
846 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
849 unsigned char *pubblob, *privblob, *spareblob;
850 int publen, privlen, sparelen = 0;
851 unsigned char *outblob;
853 struct mpint_pos numbers[9];
854 int nnumbers, pos, len, seqlen, i;
855 char *header, *footer;
862 * Fetch the key blobs.
864 pubblob = key->alg->public_blob(key->data, &publen);
865 privblob = key->alg->private_blob(key->data, &privlen);
866 spareblob = outblob = NULL;
872 * Encode the OpenSSH key blob, and also decide on the header
875 if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
877 * The RSA and DSS handlers share some code because the two
878 * key types have very similar ASN.1 representations, as a
879 * plain SEQUENCE of big integers. So we set up a list of
880 * bignums per key type and then construct the actual blob in
881 * common code after that.
883 if (key->alg == &ssh_rsa) {
885 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
886 Bignum bd, bp, bq, bdmp1, bdmq1;
889 * These blobs were generated from inside PuTTY, so we needn't
890 * treat them as untrusted.
892 pos = 4 + GET_32BIT(pubblob);
893 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
894 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
896 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
897 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
898 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
899 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
901 assert(e.start && iqmp.start); /* can't go wrong */
903 /* We also need d mod (p-1) and d mod (q-1). */
904 bd = bignum_from_bytes(d.start, d.bytes);
905 bp = bignum_from_bytes(p.start, p.bytes);
906 bq = bignum_from_bytes(q.start, q.bytes);
909 bdmp1 = bigmod(bd, bp);
910 bdmq1 = bigmod(bd, bq);
915 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
916 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
917 sparelen = dmp1.bytes + dmq1.bytes;
918 spareblob = snewn(sparelen, unsigned char);
919 dmp1.start = spareblob;
920 dmq1.start = spareblob + dmp1.bytes;
921 for (i = 0; i < dmp1.bytes; i++)
922 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
923 for (i = 0; i < dmq1.bytes; i++)
924 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
928 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
939 header = "-----BEGIN RSA PRIVATE KEY-----\n";
940 footer = "-----END RSA PRIVATE KEY-----\n";
941 } else { /* ssh-dss */
943 struct mpint_pos p, q, g, y, x;
946 * These blobs were generated from inside PuTTY, so we needn't
947 * treat them as untrusted.
949 pos = 4 + GET_32BIT(pubblob);
950 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
951 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
952 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
953 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
955 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
957 assert(y.start && x.start); /* can't go wrong */
959 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
967 header = "-----BEGIN DSA PRIVATE KEY-----\n";
968 footer = "-----END DSA PRIVATE KEY-----\n";
972 * Now count up the total size of the ASN.1 encoded integers,
973 * so as to determine the length of the containing SEQUENCE.
976 for (i = 0; i < nnumbers; i++) {
977 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
978 len += numbers[i].bytes;
981 /* Now add on the SEQUENCE header. */
982 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
985 * Now we know how big outblob needs to be. Allocate it.
987 outblob = snewn(len, unsigned char);
990 * And write the data into it.
993 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
994 for (i = 0; i < nnumbers; i++) {
995 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
996 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
997 pos += numbers[i].bytes;
999 } else if (key->alg == &ssh_ecdsa_nistp256 ||
1000 key->alg == &ssh_ecdsa_nistp384 ||
1001 key->alg == &ssh_ecdsa_nistp521) {
1007 * Structure of asn1:
1010 * OCTET STRING (private key)
1014 * BIT STRING (0x00 public key point)
1016 switch (((struct ec_key *)key->data)->publicKey.curve->fieldBits) {
1018 /* OID: 1.2.840.10045.3.1.7 (ansiX9p256r1) */
1020 oidlen = nistp256_oid_len;
1024 /* OID: 1.3.132.0.34 (secp384r1) */
1026 oidlen = nistp384_oid_len;
1030 /* OID: 1.3.132.0.35 (secp521r1) */
1032 oidlen = nistp521_oid_len;
1039 len = ber_write_id_len(NULL, 2, 1, 0);
1041 len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1043 len += ber_write_id_len(NULL, 0, oidlen +
1044 ber_write_id_len(NULL, 6, oidlen, 0),
1045 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1046 len += ber_write_id_len(NULL, 6, oidlen, 0);
1048 len += ber_write_id_len(NULL, 1, 2 + pointlen +
1049 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1050 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1051 len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1052 len += 2 + pointlen;
1055 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1057 outblob = snewn(len, unsigned char);
1061 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1062 pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1064 pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1065 memcpy(outblob+pos, privblob + 4, privlen - 4);
1067 pos += ber_write_id_len(outblob+pos, 0, oidlen +
1068 ber_write_id_len(NULL, 6, oidlen, 0),
1069 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1070 pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1071 memcpy(outblob+pos, oid, oidlen);
1073 pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1074 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1075 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1076 pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1078 memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1079 pos += 1 + pointlen;
1081 header = "-----BEGIN EC PRIVATE KEY-----\n";
1082 footer = "-----END EC PRIVATE KEY-----\n";
1084 assert(0); /* zoinks! */
1085 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1091 * For the moment, we still encrypt our OpenSSH keys using
1095 struct MD5Context md5c;
1096 unsigned char keybuf[32];
1099 * Round up to the cipher block size, ensuring we have at
1100 * least one byte of padding (see below).
1102 outlen = (len+8) &~ 7;
1104 unsigned char *tmp = snewn(outlen, unsigned char);
1105 memcpy(tmp, outblob, len);
1106 smemclr(outblob, len);
1112 * Padding on OpenSSH keys is deterministic. The number of
1113 * padding bytes is always more than zero, and always at most
1114 * the cipher block length. The value of each padding byte is
1115 * equal to the number of padding bytes. So a plaintext that's
1116 * an exact multiple of the block size will be padded with 08
1117 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1118 * plaintext one byte less than a multiple of the block size
1119 * will be padded with just 01.
1121 * This enables the OpenSSL key decryption function to strip
1122 * off the padding algorithmically and return the unpadded
1123 * plaintext to the next layer: it looks at the final byte, and
1124 * then expects to find that many bytes at the end of the data
1125 * with the same value. Those are all removed and the rest is
1129 while (pos < outlen) {
1130 outblob[pos++] = outlen - len;
1134 * Invent an iv. Then derive encryption key from passphrase
1137 * - let block A equal MD5(passphrase || iv)
1138 * - let block B equal MD5(A || passphrase || iv)
1139 * - block C would be MD5(B || passphrase || iv) and so on
1140 * - encryption key is the first N bytes of A || B
1142 for (i = 0; i < 8; i++) iv[i] = random_byte();
1145 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1146 MD5Update(&md5c, iv, 8);
1147 MD5Final(keybuf, &md5c);
1150 MD5Update(&md5c, keybuf, 16);
1151 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1152 MD5Update(&md5c, iv, 8);
1153 MD5Final(keybuf+16, &md5c);
1156 * Now encrypt the key blob.
1158 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1160 smemclr(&md5c, sizeof(md5c));
1161 smemclr(keybuf, sizeof(keybuf));
1164 * If no encryption, the blob has exactly its original
1171 * And save it. We'll use Unix line endings just in case it's
1172 * subsequently transferred in binary mode.
1174 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1179 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1180 for (i = 0; i < 8; i++)
1181 fprintf(fp, "%02X", iv[i]);
1182 fprintf(fp, "\n\n");
1184 base64_encode(fp, outblob, outlen, 64);
1191 smemclr(outblob, outlen);
1195 smemclr(spareblob, sparelen);
1199 smemclr(privblob, privlen);
1203 smemclr(pubblob, publen);
1209 /* ----------------------------------------------------------------------
1210 * Code to read ssh.com private keys.
1214 * The format of the base64 blob is largely SSH-2-packet-formatted,
1215 * except that mpints are a bit different: they're more like the
1216 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1217 * (N+7)/8 bytes of data.
1219 * So. The blob contains:
1221 * - uint32 0x3f6ff9eb (magic number)
1222 * - uint32 size (total blob size)
1223 * - string key-type (see below)
1224 * - string cipher-type (tells you if key is encrypted)
1225 * - string encrypted-blob
1227 * (The first size field includes the size field itself and the
1228 * magic number before it. All other size fields are ordinary SSH-2
1229 * strings, so the size field indicates how much data is to
1232 * The encrypted blob, once decrypted, contains a single string
1233 * which in turn contains the payload. (This allows padding to be
1234 * added after that string while still making it clear where the
1235 * real payload ends. Also it probably makes for a reasonable
1236 * decryption check.)
1238 * The payload blob, for an RSA key, contains:
1241 * - mpint n (yes, the public and private stuff is intermixed)
1242 * - mpint u (presumably inverse of p mod q)
1243 * - mpint p (p is the smaller prime)
1244 * - mpint q (q is the larger)
1246 * For a DSA key, the payload blob contains:
1254 * Alternatively, if the parameters are `predefined', that
1255 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1256 * containing some predefined parameter specification. *shudder*,
1257 * but I doubt we'll encounter this in real life.
1259 * The key type strings are ghastly. The RSA key I looked at had a
1262 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1264 * and the DSA key wasn't much better:
1266 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1268 * It isn't clear that these will always be the same. I think it
1269 * might be wise just to look at the `if-modn{sign{rsa' and
1270 * `dl-modp{sign{dsa' prefixes.
1272 * Finally, the encryption. The cipher-type string appears to be
1273 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1274 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1275 * from the passphrase by means of yet another hashing faff:
1277 * - first 16 bytes are MD5(passphrase)
1278 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1279 * - if there were more, they'd be MD5(passphrase || first 32),
1283 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1286 char comment[256]; /* allowing any length is overkill */
1287 unsigned char *keyblob;
1288 int keyblob_len, keyblob_size;
1291 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1292 const char **errmsg_p)
1294 struct sshcom_key *ret;
1301 int base64_chars = 0;
1303 ret = snew(struct sshcom_key);
1304 ret->comment[0] = '\0';
1305 ret->keyblob = NULL;
1306 ret->keyblob_len = ret->keyblob_size = 0;
1308 fp = f_open(filename, "r", FALSE);
1310 errmsg = "unable to open key file";
1313 if (!(line = fgetline(fp))) {
1314 errmsg = "unexpected end of file";
1318 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1319 errmsg = "file does not begin with ssh.com key header";
1322 smemclr(line, strlen(line));
1328 if (!(line = fgetline(fp))) {
1329 errmsg = "unexpected end of file";
1333 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1338 if ((p = strchr(line, ':')) != NULL) {
1340 errmsg = "header found in body of key data";
1344 while (*p && isspace((unsigned char)*p)) p++;
1345 hdrstart = p - line;
1348 * Header lines can end in a trailing backslash for
1351 len = hdrstart + strlen(line+hdrstart);
1353 while (line[len-1] == '\\') {
1357 line2 = fgetline(fp);
1359 errmsg = "unexpected end of file";
1364 line2len = strlen(line2);
1365 line = sresize(line, len + line2len + 1, char);
1366 strcpy(line + len - 1, line2);
1367 len += line2len - 1;
1370 smemclr(line2, strlen(line2));
1374 p = line + hdrstart;
1376 if (!strcmp(line, "Comment")) {
1377 /* Strip quotes in comment if present. */
1378 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1380 p[strlen(p)-1] = '\0';
1382 strncpy(ret->comment, p, sizeof(ret->comment));
1383 ret->comment[sizeof(ret->comment)-1] = '\0';
1389 while (isbase64(*p)) {
1390 base64_bit[base64_chars++] = *p;
1391 if (base64_chars == 4) {
1392 unsigned char out[3];
1396 len = base64_decode_atom(base64_bit, out);
1399 errmsg = "invalid base64 encoding";
1403 if (ret->keyblob_len + len > ret->keyblob_size) {
1404 ret->keyblob_size = ret->keyblob_len + len + 256;
1405 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1409 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1410 ret->keyblob_len += len;
1416 smemclr(line, strlen(line));
1421 if (ret->keyblob_len == 0 || !ret->keyblob) {
1422 errmsg = "key body not present";
1427 if (errmsg_p) *errmsg_p = NULL;
1435 smemclr(line, strlen(line));
1441 smemclr(ret->keyblob, ret->keyblob_size);
1442 sfree(ret->keyblob);
1444 smemclr(ret, sizeof(*ret));
1447 if (errmsg_p) *errmsg_p = errmsg;
1451 int sshcom_encrypted(const Filename *filename, char **comment)
1453 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1454 int pos, len, answer;
1463 * Check magic number.
1465 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1466 goto done; /* key is invalid */
1470 * Find the cipher-type string.
1473 if (key->keyblob_len < pos+4)
1474 goto done; /* key is far too short */
1475 len = toint(GET_32BIT(key->keyblob + pos));
1476 if (len < 0 || len > key->keyblob_len - pos - 4)
1477 goto done; /* key is far too short */
1478 pos += 4 + len; /* skip key type */
1479 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1480 if (len < 0 || len > key->keyblob_len - pos - 4)
1481 goto done; /* cipher type string is incomplete */
1482 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1487 *comment = dupstr(key->comment);
1488 smemclr(key->keyblob, key->keyblob_size);
1489 sfree(key->keyblob);
1490 smemclr(key, sizeof(*key));
1493 *comment = dupstr("");
1498 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1500 unsigned bits, bytes;
1501 unsigned char *d = (unsigned char *) data;
1505 bits = GET_32BIT(d);
1507 bytes = (bits + 7) / 8;
1518 return len; /* ensure further calls fail as well */
1521 static int sshcom_put_mpint(void *target, void *data, int len)
1523 unsigned char *d = (unsigned char *)target;
1524 unsigned char *i = (unsigned char *)data;
1525 int bits = len * 8 - 1;
1528 if (*i & (1 << (bits & 7)))
1534 PUT_32BIT(d, bits+1);
1535 memcpy(d+4, i, len);
1539 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1540 const char **errmsg_p)
1542 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1545 const char prefix_rsa[] = "if-modn{sign{rsa";
1546 const char prefix_dsa[] = "dl-modp{sign{dsa";
1547 enum { RSA, DSA } type;
1551 struct ssh2_userkey *ret = NULL, *retkey;
1552 const struct ssh_signkey *alg;
1553 unsigned char *blob = NULL;
1554 int blobsize = 0, publen, privlen;
1560 * Check magic number.
1562 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1563 errmsg = "key does not begin with magic number";
1568 * Determine the key type.
1571 if (key->keyblob_len < pos+4 ||
1572 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1573 len > key->keyblob_len - pos - 4) {
1574 errmsg = "key blob does not contain a key type string";
1577 if (len > sizeof(prefix_rsa) - 1 &&
1578 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1580 } else if (len > sizeof(prefix_dsa) - 1 &&
1581 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1584 errmsg = "key is of unknown type";
1590 * Determine the cipher type.
1592 if (key->keyblob_len < pos+4 ||
1593 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1594 len > key->keyblob_len - pos - 4) {
1595 errmsg = "key blob does not contain a cipher type string";
1598 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1600 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1603 errmsg = "key encryption is of unknown type";
1609 * Get hold of the encrypted part of the key.
1611 if (key->keyblob_len < pos+4 ||
1612 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1613 len > key->keyblob_len - pos - 4) {
1614 errmsg = "key blob does not contain actual key data";
1617 ciphertext = (char *)key->keyblob + pos + 4;
1619 if (cipherlen == 0) {
1620 errmsg = "length of key data is zero";
1625 * Decrypt it if necessary.
1629 * Derive encryption key from passphrase and iv/salt:
1631 * - let block A equal MD5(passphrase)
1632 * - let block B equal MD5(passphrase || A)
1633 * - block C would be MD5(passphrase || A || B) and so on
1634 * - encryption key is the first N bytes of A || B
1636 struct MD5Context md5c;
1637 unsigned char keybuf[32], iv[8];
1639 if (cipherlen % 8 != 0) {
1640 errmsg = "encrypted part of key is not a multiple of cipher block"
1646 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1647 MD5Final(keybuf, &md5c);
1650 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1651 MD5Update(&md5c, keybuf, 16);
1652 MD5Final(keybuf+16, &md5c);
1655 * Now decrypt the key blob.
1657 memset(iv, 0, sizeof(iv));
1658 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1661 smemclr(&md5c, sizeof(md5c));
1662 smemclr(keybuf, sizeof(keybuf));
1665 * Hereafter we return WRONG_PASSPHRASE for any parsing
1666 * error. (But only if we've just tried to decrypt it!
1667 * Returning WRONG_PASSPHRASE for an unencrypted key is
1671 ret = SSH2_WRONG_PASSPHRASE;
1675 * Strip away the containing string to get to the real meat.
1677 len = toint(GET_32BIT(ciphertext));
1678 if (len < 0 || len > cipherlen-4) {
1679 errmsg = "containing string was ill-formed";
1686 * Now we break down into RSA versus DSA. In either case we'll
1687 * construct public and private blobs in our own format, and
1688 * end up feeding them to alg->createkey().
1690 blobsize = cipherlen + 256;
1691 blob = snewn(blobsize, unsigned char);
1694 struct mpint_pos n, e, d, u, p, q;
1696 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1697 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1698 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1699 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1700 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1701 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1703 errmsg = "key data did not contain six integers";
1709 pos += put_string(blob+pos, "ssh-rsa", 7);
1710 pos += put_mp(blob+pos, e.start, e.bytes);
1711 pos += put_mp(blob+pos, n.start, n.bytes);
1713 pos += put_string(blob+pos, d.start, d.bytes);
1714 pos += put_mp(blob+pos, q.start, q.bytes);
1715 pos += put_mp(blob+pos, p.start, p.bytes);
1716 pos += put_mp(blob+pos, u.start, u.bytes);
1717 privlen = pos - publen;
1719 struct mpint_pos p, q, g, x, y;
1722 assert(type == DSA); /* the only other option from the if above */
1724 if (GET_32BIT(ciphertext) != 0) {
1725 errmsg = "predefined DSA parameters not supported";
1728 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1729 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1730 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1731 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1732 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1734 errmsg = "key data did not contain five integers";
1740 pos += put_string(blob+pos, "ssh-dss", 7);
1741 pos += put_mp(blob+pos, p.start, p.bytes);
1742 pos += put_mp(blob+pos, q.start, q.bytes);
1743 pos += put_mp(blob+pos, g.start, g.bytes);
1744 pos += put_mp(blob+pos, y.start, y.bytes);
1746 pos += put_mp(blob+pos, x.start, x.bytes);
1747 privlen = pos - publen;
1750 assert(privlen > 0); /* should have bombed by now if not */
1752 retkey = snew(struct ssh2_userkey);
1754 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1755 if (!retkey->data) {
1757 errmsg = "unable to create key data structure";
1760 retkey->comment = dupstr(key->comment);
1762 errmsg = NULL; /* no error */
1767 smemclr(blob, blobsize);
1770 smemclr(key->keyblob, key->keyblob_size);
1771 sfree(key->keyblob);
1772 smemclr(key, sizeof(*key));
1774 if (errmsg_p) *errmsg_p = errmsg;
1778 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1781 unsigned char *pubblob, *privblob;
1782 int publen, privlen;
1783 unsigned char *outblob;
1785 struct mpint_pos numbers[6];
1786 int nnumbers, initial_zero, pos, lenpos, i;
1794 * Fetch the key blobs.
1796 pubblob = key->alg->public_blob(key->data, &publen);
1797 privblob = key->alg->private_blob(key->data, &privlen);
1801 * Find the sequence of integers to be encoded into the OpenSSH
1802 * key blob, and also decide on the header line.
1804 if (key->alg == &ssh_rsa) {
1806 struct mpint_pos n, e, d, p, q, iqmp;
1809 * These blobs were generated from inside PuTTY, so we needn't
1810 * treat them as untrusted.
1812 pos = 4 + GET_32BIT(pubblob);
1813 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1814 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1816 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1817 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1818 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1819 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1821 assert(e.start && iqmp.start); /* can't go wrong */
1832 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1833 } else if (key->alg == &ssh_dss) {
1835 struct mpint_pos p, q, g, y, x;
1838 * These blobs were generated from inside PuTTY, so we needn't
1839 * treat them as untrusted.
1841 pos = 4 + GET_32BIT(pubblob);
1842 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1843 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1844 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1845 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1847 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1849 assert(y.start && x.start); /* can't go wrong */
1859 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1861 assert(0); /* zoinks! */
1862 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1866 * Total size of key blob will be somewhere under 512 plus
1867 * combined length of integers. We'll calculate the more
1868 * precise size as we construct the blob.
1871 for (i = 0; i < nnumbers; i++)
1872 outlen += 4 + numbers[i].bytes;
1873 outblob = snewn(outlen, unsigned char);
1876 * Create the unencrypted key blob.
1879 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1880 pos += 4; /* length field, fill in later */
1881 pos += put_string(outblob+pos, type, strlen(type));
1883 char *ciphertype = passphrase ? "3des-cbc" : "none";
1884 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1886 lenpos = pos; /* remember this position */
1887 pos += 4; /* encrypted-blob size */
1888 pos += 4; /* encrypted-payload size */
1890 PUT_32BIT(outblob+pos, 0);
1893 for (i = 0; i < nnumbers; i++)
1894 pos += sshcom_put_mpint(outblob+pos,
1895 numbers[i].start, numbers[i].bytes);
1896 /* Now wrap up the encrypted payload. */
1897 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1898 /* Pad encrypted blob to a multiple of cipher block size. */
1900 int padding = -(pos - (lenpos+4)) & 7;
1902 outblob[pos++] = random_byte();
1904 ciphertext = (char *)outblob+lenpos+4;
1905 cipherlen = pos - (lenpos+4);
1906 assert(!passphrase || cipherlen % 8 == 0);
1907 /* Wrap up the encrypted blob string. */
1908 PUT_32BIT(outblob+lenpos, cipherlen);
1909 /* And finally fill in the total length field. */
1910 PUT_32BIT(outblob+4, pos);
1912 assert(pos < outlen);
1919 * Derive encryption key from passphrase and iv/salt:
1921 * - let block A equal MD5(passphrase)
1922 * - let block B equal MD5(passphrase || A)
1923 * - block C would be MD5(passphrase || A || B) and so on
1924 * - encryption key is the first N bytes of A || B
1926 struct MD5Context md5c;
1927 unsigned char keybuf[32], iv[8];
1930 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1931 MD5Final(keybuf, &md5c);
1934 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1935 MD5Update(&md5c, keybuf, 16);
1936 MD5Final(keybuf+16, &md5c);
1939 * Now decrypt the key blob.
1941 memset(iv, 0, sizeof(iv));
1942 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1945 smemclr(&md5c, sizeof(md5c));
1946 smemclr(keybuf, sizeof(keybuf));
1950 * And save it. We'll use Unix line endings just in case it's
1951 * subsequently transferred in binary mode.
1953 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1956 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1957 fprintf(fp, "Comment: \"");
1959 * Comment header is broken with backslash-newline if it goes
1960 * over 70 chars. Although it's surrounded by quotes, it
1961 * _doesn't_ escape backslashes or quotes within the string.
1962 * Don't ask me, I didn't design it.
1965 int slen = 60; /* starts at 60 due to "Comment: " */
1966 char *c = key->comment;
1967 while ((int)strlen(c) > slen) {
1968 fprintf(fp, "%.*s\\\n", slen, c);
1970 slen = 70; /* allow 70 chars on subsequent lines */
1972 fprintf(fp, "%s\"\n", c);
1974 base64_encode(fp, outblob, pos, 70);
1975 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1981 smemclr(outblob, outlen);
1985 smemclr(privblob, privlen);
1989 smemclr(pubblob, publen);