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);
186 len = (len << 8) | (*p++);
188 *length = toint(len);
194 return p - (unsigned char *) source;
198 * Write an ASN.1/BER identifier and length pair. Returns the
199 * number of bytes consumed. Assumes dest contains enough space.
200 * Will avoid writing anything if dest is NULL, but still return
201 * amount of space required.
203 static int ber_write_id_len(void *dest, int id, int length, int flags)
205 unsigned char *d = (unsigned char *)dest;
210 * Identifier is one byte.
213 if (d) *d++ = id | flags;
217 * Identifier is multiple bytes: the first byte is 11111
218 * plus the flags, and subsequent bytes encode the value of
219 * the identifier, 7 bits at a time, with the top bit of
220 * each byte 1 except the last one which is 0.
223 if (d) *d++ = 0x1F | flags;
224 for (n = 1; (id >> (7*n)) > 0; n++)
225 continue; /* count the bytes */
228 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
234 * Length is one byte.
237 if (d) *d++ = length;
241 * Length is multiple bytes. The first is 0x80 plus the
242 * number of subsequent bytes, and the subsequent bytes
243 * encode the actual length.
245 for (n = 1; (length >> (8*n)) > 0; n++)
246 continue; /* count the bytes */
248 if (d) *d++ = 0x80 | n;
251 if (d) *d++ = (length >> (8*n)) & 0xFF;
258 static int put_string(void *target, void *data, int len)
260 unsigned char *d = (unsigned char *)target;
263 memcpy(d+4, data, len);
267 static int put_mp(void *target, void *data, int len)
269 unsigned char *d = (unsigned char *)target;
270 unsigned char *i = (unsigned char *)data;
275 memcpy(d+5, data, len);
279 memcpy(d+4, data, len);
284 /* Simple structure to point to an mp-int within a blob. */
285 struct mpint_pos { void *start; int bytes; };
287 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
290 unsigned char *d = (unsigned char *) data;
294 bytes = toint(GET_32BIT(d));
295 if (bytes < 0 || len-4 < bytes)
305 return len; /* ensure further calls fail as well */
308 /* ----------------------------------------------------------------------
309 * Code to read and write OpenSSH private keys.
312 enum { OSSH_DSA, OSSH_RSA };
313 enum { OSSH_ENC_3DES, OSSH_ENC_AES };
316 int encrypted, encryption;
318 unsigned char *keyblob;
319 int keyblob_len, keyblob_size;
322 static struct openssh_key *load_openssh_key(const Filename *filename,
323 const char **errmsg_p)
325 struct openssh_key *ret;
331 int base64_chars = 0;
333 ret = snew(struct openssh_key);
335 ret->keyblob_len = ret->keyblob_size = 0;
337 memset(ret->iv, 0, sizeof(ret->iv));
339 fp = f_open(filename, "r", FALSE);
341 errmsg = "unable to open key file";
345 if (!(line = fgetline(fp))) {
346 errmsg = "unexpected end of file";
350 if (!strstartswith(line, "-----BEGIN ") ||
351 !strendswith(line, "PRIVATE KEY-----")) {
352 errmsg = "file does not begin with OpenSSH key header";
355 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----"))
356 ret->type = OSSH_RSA;
357 else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----"))
358 ret->type = OSSH_DSA;
360 errmsg = "unrecognised key type";
363 smemclr(line, strlen(line));
369 if (!(line = fgetline(fp))) {
370 errmsg = "unexpected end of file";
374 if (strstartswith(line, "-----END ") &&
375 strendswith(line, "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
600 /* Expect the SEQUENCE header. Take its absence as a failure to
601 * decrypt, if the key was encrypted. */
602 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
604 if (ret < 0 || id != 16 || len < 0 ||
605 key->keyblob+key->keyblob_len-p < len) {
606 errmsg = "ASN.1 decoding failure";
607 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
611 /* Expect a load of INTEGERs. */
612 if (key->type == OSSH_RSA)
614 else if (key->type == OSSH_DSA)
617 num_integers = 0; /* placate compiler warnings */
620 * Space to create key blob in.
622 blobsize = 256+key->keyblob_len;
623 blob = snewn(blobsize, unsigned char);
625 if (key->type == OSSH_DSA)
626 memcpy(blob+4, "ssh-dss", 7);
627 else if (key->type == OSSH_RSA)
628 memcpy(blob+4, "ssh-rsa", 7);
632 for (i = 0; i < num_integers; i++) {
633 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
636 if (ret < 0 || id != 2 || len < 0 ||
637 key->keyblob+key->keyblob_len-p < len) {
638 errmsg = "ASN.1 decoding failure";
639 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
645 * The first integer should be zero always (I think
646 * this is some sort of version indication).
648 if (len != 1 || p[0] != 0) {
649 errmsg = "version number mismatch";
652 } else if (key->type == OSSH_RSA) {
654 * Integers 1 and 2 go into the public blob but in the
655 * opposite order; integers 3, 4, 5 and 8 go into the
656 * private blob. The other two (6 and 7) are ignored.
659 /* Save the details for after we deal with number 2. */
662 } else if (i != 6 && i != 7) {
663 PUT_32BIT(blob+blobptr, len);
664 memcpy(blob+blobptr+4, p, len);
667 PUT_32BIT(blob+blobptr, modlen);
668 memcpy(blob+blobptr+4, modptr, modlen);
673 } else if (key->type == OSSH_DSA) {
675 * Integers 1-4 go into the public blob; integer 5 goes
676 * into the private blob.
678 PUT_32BIT(blob+blobptr, len);
679 memcpy(blob+blobptr+4, p, len);
685 /* Skip past the number. */
690 * Now put together the actual key. Simplest way to do this is
691 * to assemble our own key blobs and feed them to the createkey
692 * functions; this is a bit faffy but it does mean we get all
693 * the sanity checks for free.
695 assert(privptr > 0); /* should have bombed by now if not */
696 retkey = snew(struct ssh2_userkey);
697 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
698 retkey->data = retkey->alg->createkey(blob, privptr,
699 blob+privptr, blobptr-privptr);
702 errmsg = "unable to create key data structure";
706 retkey->comment = dupstr("imported-openssh-key");
707 errmsg = NULL; /* no error */
712 smemclr(blob, blobsize);
715 smemclr(key->keyblob, key->keyblob_size);
717 smemclr(key, sizeof(*key));
719 if (errmsg_p) *errmsg_p = errmsg;
723 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
726 unsigned char *pubblob, *privblob, *spareblob;
727 int publen, privlen, sparelen = 0;
728 unsigned char *outblob;
730 struct mpint_pos numbers[9];
731 int nnumbers, pos, len, seqlen, i;
732 char *header, *footer;
739 * Fetch the key blobs.
741 pubblob = key->alg->public_blob(key->data, &publen);
742 privblob = key->alg->private_blob(key->data, &privlen);
743 spareblob = outblob = NULL;
746 * Find the sequence of integers to be encoded into the OpenSSH
747 * key blob, and also decide on the header line.
749 if (key->alg == &ssh_rsa) {
751 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
752 Bignum bd, bp, bq, bdmp1, bdmq1;
755 * These blobs were generated from inside PuTTY, so we needn't
756 * treat them as untrusted.
758 pos = 4 + GET_32BIT(pubblob);
759 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
760 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
762 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
763 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
764 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
765 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
767 assert(e.start && iqmp.start); /* can't go wrong */
769 /* We also need d mod (p-1) and d mod (q-1). */
770 bd = bignum_from_bytes(d.start, d.bytes);
771 bp = bignum_from_bytes(p.start, p.bytes);
772 bq = bignum_from_bytes(q.start, q.bytes);
775 bdmp1 = bigmod(bd, bp);
776 bdmq1 = bigmod(bd, bq);
781 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
782 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
783 sparelen = dmp1.bytes + dmq1.bytes;
784 spareblob = snewn(sparelen, unsigned char);
785 dmp1.start = spareblob;
786 dmq1.start = spareblob + dmp1.bytes;
787 for (i = 0; i < dmp1.bytes; i++)
788 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
789 for (i = 0; i < dmq1.bytes; i++)
790 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
794 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
805 header = "-----BEGIN RSA PRIVATE KEY-----\n";
806 footer = "-----END RSA PRIVATE KEY-----\n";
807 } else if (key->alg == &ssh_dss) {
809 struct mpint_pos p, q, g, y, x;
812 * These blobs were generated from inside PuTTY, so we needn't
813 * treat them as untrusted.
815 pos = 4 + GET_32BIT(pubblob);
816 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
817 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
818 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
819 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
821 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
823 assert(y.start && x.start); /* can't go wrong */
825 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
833 header = "-----BEGIN DSA PRIVATE KEY-----\n";
834 footer = "-----END DSA PRIVATE KEY-----\n";
836 assert(0); /* zoinks! */
837 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
841 * Now count up the total size of the ASN.1 encoded integers,
842 * so as to determine the length of the containing SEQUENCE.
845 for (i = 0; i < nnumbers; i++) {
846 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
847 len += numbers[i].bytes;
850 /* Now add on the SEQUENCE header. */
851 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
852 /* Round up to the cipher block size, ensuring we have at least one
853 * byte of padding (see below). */
856 outlen = (outlen+8) &~ 7;
859 * Now we know how big outblob needs to be. Allocate it.
861 outblob = snewn(outlen, unsigned char);
864 * And write the data into it.
867 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
868 for (i = 0; i < nnumbers; i++) {
869 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
870 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
871 pos += numbers[i].bytes;
875 * Padding on OpenSSH keys is deterministic. The number of
876 * padding bytes is always more than zero, and always at most
877 * the cipher block length. The value of each padding byte is
878 * equal to the number of padding bytes. So a plaintext that's
879 * an exact multiple of the block size will be padded with 08
880 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
881 * plaintext one byte less than a multiple of the block size
882 * will be padded with just 01.
884 * This enables the OpenSSL key decryption function to strip
885 * off the padding algorithmically and return the unpadded
886 * plaintext to the next layer: it looks at the final byte, and
887 * then expects to find that many bytes at the end of the data
888 * with the same value. Those are all removed and the rest is
892 while (pos < outlen) {
893 outblob[pos++] = outlen - len;
899 * For the moment, we still encrypt our OpenSSH keys using
904 * Invent an iv. Then derive encryption key from passphrase
907 * - let block A equal MD5(passphrase || iv)
908 * - let block B equal MD5(A || passphrase || iv)
909 * - block C would be MD5(B || passphrase || iv) and so on
910 * - encryption key is the first N bytes of A || B
912 struct MD5Context md5c;
913 unsigned char keybuf[32];
915 for (i = 0; i < 8; i++) iv[i] = random_byte();
918 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
919 MD5Update(&md5c, iv, 8);
920 MD5Final(keybuf, &md5c);
923 MD5Update(&md5c, keybuf, 16);
924 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
925 MD5Update(&md5c, iv, 8);
926 MD5Final(keybuf+16, &md5c);
929 * Now encrypt the key blob.
931 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
933 smemclr(&md5c, sizeof(md5c));
934 smemclr(keybuf, sizeof(keybuf));
938 * And save it. We'll use Unix line endings just in case it's
939 * subsequently transferred in binary mode.
941 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
946 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
947 for (i = 0; i < 8; i++)
948 fprintf(fp, "%02X", iv[i]);
951 base64_encode(fp, outblob, outlen, 64);
958 smemclr(outblob, outlen);
962 smemclr(spareblob, sparelen);
966 smemclr(privblob, privlen);
970 smemclr(pubblob, publen);
976 /* ----------------------------------------------------------------------
977 * Code to read ssh.com private keys.
981 * The format of the base64 blob is largely SSH-2-packet-formatted,
982 * except that mpints are a bit different: they're more like the
983 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
984 * (N+7)/8 bytes of data.
986 * So. The blob contains:
988 * - uint32 0x3f6ff9eb (magic number)
989 * - uint32 size (total blob size)
990 * - string key-type (see below)
991 * - string cipher-type (tells you if key is encrypted)
992 * - string encrypted-blob
994 * (The first size field includes the size field itself and the
995 * magic number before it. All other size fields are ordinary SSH-2
996 * strings, so the size field indicates how much data is to
999 * The encrypted blob, once decrypted, contains a single string
1000 * which in turn contains the payload. (This allows padding to be
1001 * added after that string while still making it clear where the
1002 * real payload ends. Also it probably makes for a reasonable
1003 * decryption check.)
1005 * The payload blob, for an RSA key, contains:
1008 * - mpint n (yes, the public and private stuff is intermixed)
1009 * - mpint u (presumably inverse of p mod q)
1010 * - mpint p (p is the smaller prime)
1011 * - mpint q (q is the larger)
1013 * For a DSA key, the payload blob contains:
1021 * Alternatively, if the parameters are `predefined', that
1022 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1023 * containing some predefined parameter specification. *shudder*,
1024 * but I doubt we'll encounter this in real life.
1026 * The key type strings are ghastly. The RSA key I looked at had a
1029 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1031 * and the DSA key wasn't much better:
1033 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1035 * It isn't clear that these will always be the same. I think it
1036 * might be wise just to look at the `if-modn{sign{rsa' and
1037 * `dl-modp{sign{dsa' prefixes.
1039 * Finally, the encryption. The cipher-type string appears to be
1040 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1041 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1042 * from the passphrase by means of yet another hashing faff:
1044 * - first 16 bytes are MD5(passphrase)
1045 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1046 * - if there were more, they'd be MD5(passphrase || first 32),
1050 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1053 char comment[256]; /* allowing any length is overkill */
1054 unsigned char *keyblob;
1055 int keyblob_len, keyblob_size;
1058 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1059 const char **errmsg_p)
1061 struct sshcom_key *ret;
1068 int base64_chars = 0;
1070 ret = snew(struct sshcom_key);
1071 ret->comment[0] = '\0';
1072 ret->keyblob = NULL;
1073 ret->keyblob_len = ret->keyblob_size = 0;
1075 fp = f_open(filename, "r", FALSE);
1077 errmsg = "unable to open key file";
1080 if (!(line = fgetline(fp))) {
1081 errmsg = "unexpected end of file";
1085 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1086 errmsg = "file does not begin with ssh.com key header";
1089 smemclr(line, strlen(line));
1095 if (!(line = fgetline(fp))) {
1096 errmsg = "unexpected end of file";
1100 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1105 if ((p = strchr(line, ':')) != NULL) {
1107 errmsg = "header found in body of key data";
1111 while (*p && isspace((unsigned char)*p)) p++;
1112 hdrstart = p - line;
1115 * Header lines can end in a trailing backslash for
1118 len = hdrstart + strlen(line+hdrstart);
1120 while (line[len-1] == '\\') {
1124 line2 = fgetline(fp);
1126 errmsg = "unexpected end of file";
1131 line2len = strlen(line2);
1132 line = sresize(line, len + line2len + 1, char);
1133 strcpy(line + len - 1, line2);
1134 len += line2len - 1;
1137 smemclr(line2, strlen(line2));
1141 p = line + hdrstart;
1143 if (!strcmp(line, "Comment")) {
1144 /* Strip quotes in comment if present. */
1145 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1147 p[strlen(p)-1] = '\0';
1149 strncpy(ret->comment, p, sizeof(ret->comment));
1150 ret->comment[sizeof(ret->comment)-1] = '\0';
1156 while (isbase64(*p)) {
1157 base64_bit[base64_chars++] = *p;
1158 if (base64_chars == 4) {
1159 unsigned char out[3];
1163 len = base64_decode_atom(base64_bit, out);
1166 errmsg = "invalid base64 encoding";
1170 if (ret->keyblob_len + len > ret->keyblob_size) {
1171 ret->keyblob_size = ret->keyblob_len + len + 256;
1172 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1176 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1177 ret->keyblob_len += len;
1183 smemclr(line, strlen(line));
1188 if (ret->keyblob_len == 0 || !ret->keyblob) {
1189 errmsg = "key body not present";
1194 if (errmsg_p) *errmsg_p = NULL;
1202 smemclr(line, strlen(line));
1208 smemclr(ret->keyblob, ret->keyblob_size);
1209 sfree(ret->keyblob);
1211 smemclr(ret, sizeof(*ret));
1214 if (errmsg_p) *errmsg_p = errmsg;
1218 int sshcom_encrypted(const Filename *filename, char **comment)
1220 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1221 int pos, len, answer;
1230 * Check magic number.
1232 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1233 goto done; /* key is invalid */
1237 * Find the cipher-type string.
1240 if (key->keyblob_len < pos+4)
1241 goto done; /* key is far too short */
1242 len = toint(GET_32BIT(key->keyblob + pos));
1243 if (len < 0 || len > key->keyblob_len - pos - 4)
1244 goto done; /* key is far too short */
1245 pos += 4 + len; /* skip key type */
1246 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1247 if (len < 0 || len > key->keyblob_len - pos - 4)
1248 goto done; /* cipher type string is incomplete */
1249 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1254 *comment = dupstr(key->comment);
1255 smemclr(key->keyblob, key->keyblob_size);
1256 sfree(key->keyblob);
1257 smemclr(key, sizeof(*key));
1260 *comment = dupstr("");
1265 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1267 unsigned bits, bytes;
1268 unsigned char *d = (unsigned char *) data;
1272 bits = GET_32BIT(d);
1274 bytes = (bits + 7) / 8;
1285 return len; /* ensure further calls fail as well */
1288 static int sshcom_put_mpint(void *target, void *data, int len)
1290 unsigned char *d = (unsigned char *)target;
1291 unsigned char *i = (unsigned char *)data;
1292 int bits = len * 8 - 1;
1295 if (*i & (1 << (bits & 7)))
1301 PUT_32BIT(d, bits+1);
1302 memcpy(d+4, i, len);
1306 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1307 const char **errmsg_p)
1309 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1312 const char prefix_rsa[] = "if-modn{sign{rsa";
1313 const char prefix_dsa[] = "dl-modp{sign{dsa";
1314 enum { RSA, DSA } type;
1318 struct ssh2_userkey *ret = NULL, *retkey;
1319 const struct ssh_signkey *alg;
1320 unsigned char *blob = NULL;
1321 int blobsize = 0, publen, privlen;
1327 * Check magic number.
1329 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1330 errmsg = "key does not begin with magic number";
1335 * Determine the key type.
1338 if (key->keyblob_len < pos+4 ||
1339 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1340 len > key->keyblob_len - pos - 4) {
1341 errmsg = "key blob does not contain a key type string";
1344 if (len > sizeof(prefix_rsa) - 1 &&
1345 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1347 } else if (len > sizeof(prefix_dsa) - 1 &&
1348 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1351 errmsg = "key is of unknown type";
1357 * Determine the cipher type.
1359 if (key->keyblob_len < pos+4 ||
1360 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1361 len > key->keyblob_len - pos - 4) {
1362 errmsg = "key blob does not contain a cipher type string";
1365 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1367 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1370 errmsg = "key encryption is of unknown type";
1376 * Get hold of the encrypted part of the key.
1378 if (key->keyblob_len < pos+4 ||
1379 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1380 len > key->keyblob_len - pos - 4) {
1381 errmsg = "key blob does not contain actual key data";
1384 ciphertext = (char *)key->keyblob + pos + 4;
1386 if (cipherlen == 0) {
1387 errmsg = "length of key data is zero";
1392 * Decrypt it if necessary.
1396 * Derive encryption key from passphrase and iv/salt:
1398 * - let block A equal MD5(passphrase)
1399 * - let block B equal MD5(passphrase || A)
1400 * - block C would be MD5(passphrase || A || B) and so on
1401 * - encryption key is the first N bytes of A || B
1403 struct MD5Context md5c;
1404 unsigned char keybuf[32], iv[8];
1406 if (cipherlen % 8 != 0) {
1407 errmsg = "encrypted part of key is not a multiple of cipher block"
1413 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1414 MD5Final(keybuf, &md5c);
1417 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1418 MD5Update(&md5c, keybuf, 16);
1419 MD5Final(keybuf+16, &md5c);
1422 * Now decrypt the key blob.
1424 memset(iv, 0, sizeof(iv));
1425 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1428 smemclr(&md5c, sizeof(md5c));
1429 smemclr(keybuf, sizeof(keybuf));
1432 * Hereafter we return WRONG_PASSPHRASE for any parsing
1433 * error. (But only if we've just tried to decrypt it!
1434 * Returning WRONG_PASSPHRASE for an unencrypted key is
1438 ret = SSH2_WRONG_PASSPHRASE;
1442 * Strip away the containing string to get to the real meat.
1444 len = toint(GET_32BIT(ciphertext));
1445 if (len < 0 || len > cipherlen-4) {
1446 errmsg = "containing string was ill-formed";
1453 * Now we break down into RSA versus DSA. In either case we'll
1454 * construct public and private blobs in our own format, and
1455 * end up feeding them to alg->createkey().
1457 blobsize = cipherlen + 256;
1458 blob = snewn(blobsize, unsigned char);
1461 struct mpint_pos n, e, d, u, p, q;
1463 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1464 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1465 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1466 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1467 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1468 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1470 errmsg = "key data did not contain six integers";
1476 pos += put_string(blob+pos, "ssh-rsa", 7);
1477 pos += put_mp(blob+pos, e.start, e.bytes);
1478 pos += put_mp(blob+pos, n.start, n.bytes);
1480 pos += put_string(blob+pos, d.start, d.bytes);
1481 pos += put_mp(blob+pos, q.start, q.bytes);
1482 pos += put_mp(blob+pos, p.start, p.bytes);
1483 pos += put_mp(blob+pos, u.start, u.bytes);
1484 privlen = pos - publen;
1486 struct mpint_pos p, q, g, x, y;
1489 assert(type == DSA); /* the only other option from the if above */
1491 if (GET_32BIT(ciphertext) != 0) {
1492 errmsg = "predefined DSA parameters not supported";
1495 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1496 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1497 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1498 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1499 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1501 errmsg = "key data did not contain five integers";
1507 pos += put_string(blob+pos, "ssh-dss", 7);
1508 pos += put_mp(blob+pos, p.start, p.bytes);
1509 pos += put_mp(blob+pos, q.start, q.bytes);
1510 pos += put_mp(blob+pos, g.start, g.bytes);
1511 pos += put_mp(blob+pos, y.start, y.bytes);
1513 pos += put_mp(blob+pos, x.start, x.bytes);
1514 privlen = pos - publen;
1517 assert(privlen > 0); /* should have bombed by now if not */
1519 retkey = snew(struct ssh2_userkey);
1521 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1522 if (!retkey->data) {
1524 errmsg = "unable to create key data structure";
1527 retkey->comment = dupstr(key->comment);
1529 errmsg = NULL; /* no error */
1534 smemclr(blob, blobsize);
1537 smemclr(key->keyblob, key->keyblob_size);
1538 sfree(key->keyblob);
1539 smemclr(key, sizeof(*key));
1541 if (errmsg_p) *errmsg_p = errmsg;
1545 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1548 unsigned char *pubblob, *privblob;
1549 int publen, privlen;
1550 unsigned char *outblob;
1552 struct mpint_pos numbers[6];
1553 int nnumbers, initial_zero, pos, lenpos, i;
1561 * Fetch the key blobs.
1563 pubblob = key->alg->public_blob(key->data, &publen);
1564 privblob = key->alg->private_blob(key->data, &privlen);
1568 * Find the sequence of integers to be encoded into the OpenSSH
1569 * key blob, and also decide on the header line.
1571 if (key->alg == &ssh_rsa) {
1573 struct mpint_pos n, e, d, p, q, iqmp;
1576 * These blobs were generated from inside PuTTY, so we needn't
1577 * treat them as untrusted.
1579 pos = 4 + GET_32BIT(pubblob);
1580 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1581 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1583 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1584 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1585 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1586 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1588 assert(e.start && iqmp.start); /* can't go wrong */
1599 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1600 } else if (key->alg == &ssh_dss) {
1602 struct mpint_pos p, q, g, y, x;
1605 * These blobs were generated from inside PuTTY, so we needn't
1606 * treat them as untrusted.
1608 pos = 4 + GET_32BIT(pubblob);
1609 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1610 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1611 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1612 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1614 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1616 assert(y.start && x.start); /* can't go wrong */
1626 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1628 assert(0); /* zoinks! */
1629 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1633 * Total size of key blob will be somewhere under 512 plus
1634 * combined length of integers. We'll calculate the more
1635 * precise size as we construct the blob.
1638 for (i = 0; i < nnumbers; i++)
1639 outlen += 4 + numbers[i].bytes;
1640 outblob = snewn(outlen, unsigned char);
1643 * Create the unencrypted key blob.
1646 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1647 pos += 4; /* length field, fill in later */
1648 pos += put_string(outblob+pos, type, strlen(type));
1650 char *ciphertype = passphrase ? "3des-cbc" : "none";
1651 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1653 lenpos = pos; /* remember this position */
1654 pos += 4; /* encrypted-blob size */
1655 pos += 4; /* encrypted-payload size */
1657 PUT_32BIT(outblob+pos, 0);
1660 for (i = 0; i < nnumbers; i++)
1661 pos += sshcom_put_mpint(outblob+pos,
1662 numbers[i].start, numbers[i].bytes);
1663 /* Now wrap up the encrypted payload. */
1664 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1665 /* Pad encrypted blob to a multiple of cipher block size. */
1667 int padding = -(pos - (lenpos+4)) & 7;
1669 outblob[pos++] = random_byte();
1671 ciphertext = (char *)outblob+lenpos+4;
1672 cipherlen = pos - (lenpos+4);
1673 assert(!passphrase || cipherlen % 8 == 0);
1674 /* Wrap up the encrypted blob string. */
1675 PUT_32BIT(outblob+lenpos, cipherlen);
1676 /* And finally fill in the total length field. */
1677 PUT_32BIT(outblob+4, pos);
1679 assert(pos < outlen);
1686 * Derive encryption key from passphrase and iv/salt:
1688 * - let block A equal MD5(passphrase)
1689 * - let block B equal MD5(passphrase || A)
1690 * - block C would be MD5(passphrase || A || B) and so on
1691 * - encryption key is the first N bytes of A || B
1693 struct MD5Context md5c;
1694 unsigned char keybuf[32], iv[8];
1697 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1698 MD5Final(keybuf, &md5c);
1701 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1702 MD5Update(&md5c, keybuf, 16);
1703 MD5Final(keybuf+16, &md5c);
1706 * Now decrypt the key blob.
1708 memset(iv, 0, sizeof(iv));
1709 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1712 smemclr(&md5c, sizeof(md5c));
1713 smemclr(keybuf, sizeof(keybuf));
1717 * And save it. We'll use Unix line endings just in case it's
1718 * subsequently transferred in binary mode.
1720 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1723 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1724 fprintf(fp, "Comment: \"");
1726 * Comment header is broken with backslash-newline if it goes
1727 * over 70 chars. Although it's surrounded by quotes, it
1728 * _doesn't_ escape backslashes or quotes within the string.
1729 * Don't ask me, I didn't design it.
1732 int slen = 60; /* starts at 60 due to "Comment: " */
1733 char *c = key->comment;
1734 while ((int)strlen(c) > slen) {
1735 fprintf(fp, "%.*s\\\n", slen, c);
1737 slen = 70; /* allow 70 chars on subsequent lines */
1739 fprintf(fp, "%s\"\n", c);
1741 base64_encode(fp, outblob, pos, 70);
1742 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1748 smemclr(outblob, outlen);
1752 smemclr(privblob, privlen);
1756 smemclr(pubblob, publen);