2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 #define PUT_32BIT(cp, value) do { \
16 (cp)[3] = (unsigned char)(value); \
17 (cp)[2] = (unsigned char)((value) >> 8); \
18 (cp)[1] = (unsigned char)((value) >> 16); \
19 (cp)[0] = (unsigned char)((value) >> 24); } while (0)
21 #define GET_32BIT(cp) \
22 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
23 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
24 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
25 ((unsigned long)(unsigned char)(cp)[3]))
27 int openssh_encrypted(const Filename *filename);
28 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase);
29 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
32 int sshcom_encrypted(const Filename *filename, char **comment);
33 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase);
34 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
38 * Given a key type, determine whether we know how to import it.
40 int import_possible(int type)
42 if (type == SSH_KEYTYPE_OPENSSH)
44 if (type == SSH_KEYTYPE_SSHCOM)
50 * Given a key type, determine what native key type
51 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
54 int import_target_type(int type)
57 * There are no known foreign SSH1 key formats.
59 return SSH_KEYTYPE_SSH2;
63 * Determine whether a foreign key is encrypted.
65 int import_encrypted(const Filename *filename, int type, char **comment)
67 if (type == SSH_KEYTYPE_OPENSSH) {
68 /* OpenSSH doesn't do key comments */
69 *comment = dupstr(filename_to_str(filename));
70 return openssh_encrypted(filename);
72 if (type == SSH_KEYTYPE_SSHCOM) {
73 return sshcom_encrypted(filename, comment);
81 int import_ssh1(const Filename *filename, int type,
82 struct RSAKey *key, char *passphrase)
90 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
93 if (type == SSH_KEYTYPE_OPENSSH)
94 return openssh_read(filename, passphrase);
95 if (type == SSH_KEYTYPE_SSHCOM)
96 return sshcom_read(filename, passphrase);
101 * Export an SSH1 key.
103 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
110 * Export an SSH2 key.
112 int export_ssh2(const Filename *filename, int type,
113 struct ssh2_userkey *key, char *passphrase)
115 if (type == SSH_KEYTYPE_OPENSSH)
116 return openssh_write(filename, key, passphrase);
117 if (type == SSH_KEYTYPE_SSHCOM)
118 return sshcom_write(filename, key, passphrase);
122 /* ----------------------------------------------------------------------
123 * Helper routines. (The base64 ones are defined in sshpubk.c.)
126 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
127 ((c) >= 'a' && (c) <= 'z') || \
128 ((c) >= '0' && (c) <= '9') || \
129 (c) == '+' || (c) == '/' || (c) == '=' \
133 * Read an ASN.1/BER identifier and length pair.
135 * Flags are a combination of the #defines listed below.
137 * Returns -1 if unsuccessful; otherwise returns the number of
138 * bytes used out of the source data.
141 /* ASN.1 tag classes. */
142 #define ASN1_CLASS_UNIVERSAL (0 << 6)
143 #define ASN1_CLASS_APPLICATION (1 << 6)
144 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
145 #define ASN1_CLASS_PRIVATE (3 << 6)
146 #define ASN1_CLASS_MASK (3 << 6)
148 /* Primitive versus constructed bit. */
149 #define ASN1_CONSTRUCTED (1 << 5)
151 static int ber_read_id_len(void *source, int sourcelen,
152 int *id, int *length, int *flags)
154 unsigned char *p = (unsigned char *) source;
159 *flags = (*p & 0xE0);
160 if ((*p & 0x1F) == 0x1F) {
163 *id = (*id << 7) | (*p & 0x7F);
168 *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 = GET_32BIT(d);
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 };
315 unsigned char *keyblob;
316 int keyblob_len, keyblob_size;
319 static struct openssh_key *load_openssh_key(const Filename *filename)
321 struct openssh_key *ret;
327 int base64_chars = 0;
329 ret = snew(struct openssh_key);
331 ret->keyblob_len = ret->keyblob_size = 0;
333 memset(ret->iv, 0, sizeof(ret->iv));
335 fp = f_open(*filename, "r");
337 errmsg = "Unable to open key file";
340 if (!fgets(buffer, sizeof(buffer), fp) ||
341 0 != strncmp(buffer, "-----BEGIN ", 11) ||
342 0 != strcmp(buffer+strlen(buffer)-17, "PRIVATE KEY-----\n")) {
343 errmsg = "File does not begin with OpenSSH key header";
346 if (!strcmp(buffer, "-----BEGIN RSA PRIVATE KEY-----\n"))
347 ret->type = OSSH_RSA;
348 else if (!strcmp(buffer, "-----BEGIN DSA PRIVATE KEY-----\n"))
349 ret->type = OSSH_DSA;
351 errmsg = "Unrecognised key type";
357 if (!fgets(buffer, sizeof(buffer), fp)) {
358 errmsg = "Unexpected end of file";
361 if (0 == strncmp(buffer, "-----END ", 9) &&
362 0 == strcmp(buffer+strlen(buffer)-17, "PRIVATE KEY-----\n"))
364 if ((p = strchr(buffer, ':')) != NULL) {
366 errmsg = "Header found in body of key data";
370 while (*p && isspace((unsigned char)*p)) p++;
371 if (!strcmp(buffer, "Proc-Type")) {
372 if (p[0] != '4' || p[1] != ',') {
373 errmsg = "Proc-Type is not 4 (only 4 is supported)";
377 if (!strcmp(p, "ENCRYPTED\n"))
379 } else if (!strcmp(buffer, "DEK-Info")) {
382 if (strncmp(p, "DES-EDE3-CBC,", 13)) {
383 errmsg = "Ciphers other than DES-EDE3-CBC not supported";
387 for (i = 0; i < 8; i++) {
388 if (1 != sscanf(p, "%2x", &j))
394 errmsg = "Expected 16-digit iv in DEK-Info";
402 while (isbase64(*p)) {
403 base64_bit[base64_chars++] = *p;
404 if (base64_chars == 4) {
405 unsigned char out[3];
410 len = base64_decode_atom(base64_bit, out);
413 errmsg = "Invalid base64 encoding";
417 if (ret->keyblob_len + len > ret->keyblob_size) {
418 ret->keyblob_size = ret->keyblob_len + len + 256;
419 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
423 memcpy(ret->keyblob + ret->keyblob_len, out, len);
424 ret->keyblob_len += len;
426 memset(out, 0, sizeof(out));
434 if (ret->keyblob_len == 0 || !ret->keyblob) {
435 errmsg = "Key body not present";
439 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
440 errmsg = "Encrypted key blob is not a multiple of cipher block size";
444 memset(buffer, 0, sizeof(buffer));
445 memset(base64_bit, 0, sizeof(base64_bit));
449 memset(buffer, 0, sizeof(buffer));
450 memset(base64_bit, 0, sizeof(base64_bit));
453 memset(ret->keyblob, 0, ret->keyblob_size);
456 memset(&ret, 0, sizeof(ret));
462 int openssh_encrypted(const Filename *filename)
464 struct openssh_key *key = load_openssh_key(filename);
469 ret = key->encrypted;
470 memset(key->keyblob, 0, key->keyblob_size);
472 memset(&key, 0, sizeof(key));
477 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase)
479 struct openssh_key *key = load_openssh_key(filename);
480 struct ssh2_userkey *retkey;
482 int ret, id, len, flags;
484 struct ssh2_userkey *retval = NULL;
487 int blobsize, blobptr, privptr;
496 if (key->encrypted) {
498 * Derive encryption key from passphrase and iv/salt:
500 * - let block A equal MD5(passphrase || iv)
501 * - let block B equal MD5(A || passphrase || iv)
502 * - block C would be MD5(B || passphrase || iv) and so on
503 * - encryption key is the first N bytes of A || B
505 struct MD5Context md5c;
506 unsigned char keybuf[32];
509 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
510 MD5Update(&md5c, (unsigned char *)key->iv, 8);
511 MD5Final(keybuf, &md5c);
514 MD5Update(&md5c, keybuf, 16);
515 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
516 MD5Update(&md5c, (unsigned char *)key->iv, 8);
517 MD5Final(keybuf+16, &md5c);
520 * Now decrypt the key blob.
522 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
523 key->keyblob, key->keyblob_len);
525 memset(&md5c, 0, sizeof(md5c));
526 memset(keybuf, 0, sizeof(keybuf));
530 * Now we have a decrypted key blob, which contains an ASN.1
531 * encoded private key. We must now untangle the ASN.1.
533 * We expect the whole key blob to be formatted as a SEQUENCE
534 * (0x30 followed by a length code indicating that the rest of
535 * the blob is part of the sequence). Within that SEQUENCE we
536 * expect to see a bunch of INTEGERs. What those integers mean
537 * depends on the key type:
539 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
540 * dmp1, dmq1, iqmp in that order. (The last three are d mod
541 * (p-1), d mod (q-1), inverse of q mod p respectively.)
543 * - For DSA, we expect them to be 0, p, q, g, y, x in that
549 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
550 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
552 if (ret < 0 || id != 16) {
553 errmsg = "ASN.1 decoding failure";
554 retval = SSH2_WRONG_PASSPHRASE;
558 /* Expect a load of INTEGERs. */
559 if (key->type == OSSH_RSA)
561 else if (key->type == OSSH_DSA)
565 * Space to create key blob in.
567 blobsize = 256+key->keyblob_len;
568 blob = snewn(blobsize, unsigned char);
570 if (key->type == OSSH_DSA)
571 memcpy(blob+4, "ssh-dss", 7);
572 else if (key->type == OSSH_RSA)
573 memcpy(blob+4, "ssh-rsa", 7);
577 for (i = 0; i < num_integers; i++) {
578 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
581 if (ret < 0 || id != 2 ||
582 key->keyblob+key->keyblob_len-p < len) {
583 errmsg = "ASN.1 decoding failure";
589 * The first integer should be zero always (I think
590 * this is some sort of version indication).
592 if (len != 1 || p[0] != 0) {
593 errmsg = "Version number mismatch";
596 } else if (key->type == OSSH_RSA) {
598 * Integers 1 and 2 go into the public blob but in the
599 * opposite order; integers 3, 4, 5 and 8 go into the
600 * private blob. The other two (6 and 7) are ignored.
603 /* Save the details for after we deal with number 2. */
606 } else if (i != 6 && i != 7) {
607 PUT_32BIT(blob+blobptr, len);
608 memcpy(blob+blobptr+4, p, len);
611 PUT_32BIT(blob+blobptr, modlen);
612 memcpy(blob+blobptr+4, modptr, modlen);
617 } else if (key->type == OSSH_DSA) {
619 * Integers 1-4 go into the public blob; integer 5 goes
620 * into the private blob.
622 PUT_32BIT(blob+blobptr, len);
623 memcpy(blob+blobptr+4, p, len);
629 /* Skip past the number. */
634 * Now put together the actual key. Simplest way to do this is
635 * to assemble our own key blobs and feed them to the createkey
636 * functions; this is a bit faffy but it does mean we get all
637 * the sanity checks for free.
639 assert(privptr > 0); /* should have bombed by now if not */
640 retkey = snew(struct ssh2_userkey);
641 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
642 retkey->data = retkey->alg->createkey(blob, privptr,
643 blob+privptr, blobptr-privptr);
646 errmsg = "unable to create key data structure";
650 retkey->comment = dupstr("imported-openssh-key");
651 errmsg = NULL; /* no error */
656 memset(blob, 0, blobsize);
659 memset(key->keyblob, 0, key->keyblob_size);
661 memset(&key, 0, sizeof(key));
666 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
669 unsigned char *pubblob, *privblob, *spareblob;
670 int publen, privlen, sparelen;
671 unsigned char *outblob;
673 struct mpint_pos numbers[9];
674 int nnumbers, pos, len, seqlen, i;
675 char *header, *footer;
682 * Fetch the key blobs.
684 pubblob = key->alg->public_blob(key->data, &publen);
685 privblob = key->alg->private_blob(key->data, &privlen);
686 spareblob = outblob = NULL;
689 * Find the sequence of integers to be encoded into the OpenSSH
690 * key blob, and also decide on the header line.
692 if (key->alg == &ssh_rsa) {
694 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
695 Bignum bd, bp, bq, bdmp1, bdmq1;
697 pos = 4 + GET_32BIT(pubblob);
698 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
699 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
701 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
702 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
703 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
704 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
706 assert(e.start && iqmp.start); /* can't go wrong */
708 /* We also need d mod (p-1) and d mod (q-1). */
709 bd = bignum_from_bytes(d.start, d.bytes);
710 bp = bignum_from_bytes(p.start, p.bytes);
711 bq = bignum_from_bytes(q.start, q.bytes);
714 bdmp1 = bigmod(bd, bp);
715 bdmq1 = bigmod(bd, bq);
720 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
721 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
722 sparelen = dmp1.bytes + dmq1.bytes;
723 spareblob = snewn(sparelen, unsigned char);
724 dmp1.start = spareblob;
725 dmq1.start = spareblob + dmp1.bytes;
726 for (i = 0; i < dmp1.bytes; i++)
727 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
728 for (i = 0; i < dmq1.bytes; i++)
729 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
733 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
744 header = "-----BEGIN RSA PRIVATE KEY-----\n";
745 footer = "-----END RSA PRIVATE KEY-----\n";
746 } else if (key->alg == &ssh_dss) {
748 struct mpint_pos p, q, g, y, x;
750 pos = 4 + GET_32BIT(pubblob);
751 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
752 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
753 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
754 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
756 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
758 assert(y.start && x.start); /* can't go wrong */
760 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
768 header = "-----BEGIN DSA PRIVATE KEY-----\n";
769 footer = "-----END DSA PRIVATE KEY-----\n";
771 assert(0); /* zoinks! */
775 * Now count up the total size of the ASN.1 encoded integers,
776 * so as to determine the length of the containing SEQUENCE.
779 for (i = 0; i < nnumbers; i++) {
780 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
781 len += numbers[i].bytes;
784 /* Now add on the SEQUENCE header. */
785 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
786 /* Round up to the cipher block size, ensuring we have at least one
787 * byte of padding (see below). */
790 outlen = (outlen+8) &~ 7;
793 * Now we know how big outblob needs to be. Allocate it.
795 outblob = snewn(outlen, unsigned char);
798 * And write the data into it.
801 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
802 for (i = 0; i < nnumbers; i++) {
803 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
804 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
805 pos += numbers[i].bytes;
809 * Padding on OpenSSH keys is deterministic. The number of
810 * padding bytes is always more than zero, and always at most
811 * the cipher block length. The value of each padding byte is
812 * equal to the number of padding bytes. So a plaintext that's
813 * an exact multiple of the block size will be padded with 08
814 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
815 * plaintext one byte less than a multiple of the block size
816 * will be padded with just 01.
818 * This enables the OpenSSL key decryption function to strip
819 * off the padding algorithmically and return the unpadded
820 * plaintext to the next layer: it looks at the final byte, and
821 * then expects to find that many bytes at the end of the data
822 * with the same value. Those are all removed and the rest is
826 while (pos < outlen) {
827 outblob[pos++] = outlen - len;
835 * Invent an iv. Then derive encryption key from passphrase
838 * - let block A equal MD5(passphrase || iv)
839 * - let block B equal MD5(A || passphrase || iv)
840 * - block C would be MD5(B || passphrase || iv) and so on
841 * - encryption key is the first N bytes of A || B
843 struct MD5Context md5c;
844 unsigned char keybuf[32];
846 for (i = 0; i < 8; i++) iv[i] = random_byte();
849 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
850 MD5Update(&md5c, iv, 8);
851 MD5Final(keybuf, &md5c);
854 MD5Update(&md5c, keybuf, 16);
855 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
856 MD5Update(&md5c, iv, 8);
857 MD5Final(keybuf+16, &md5c);
860 * Now encrypt the key blob.
862 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
864 memset(&md5c, 0, sizeof(md5c));
865 memset(keybuf, 0, sizeof(keybuf));
869 * And save it. We'll use Unix line endings just in case it's
870 * subsequently transferred in binary mode.
872 fp = f_open(*filename, "wb"); /* ensure Unix line endings */
877 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
878 for (i = 0; i < 8; i++)
879 fprintf(fp, "%02X", iv[i]);
882 base64_encode(fp, outblob, outlen, 64);
889 memset(outblob, 0, outlen);
893 memset(spareblob, 0, sparelen);
897 memset(privblob, 0, privlen);
901 memset(pubblob, 0, publen);
907 /* ----------------------------------------------------------------------
908 * Code to read ssh.com private keys.
912 * The format of the base64 blob is largely ssh2-packet-formatted,
913 * except that mpints are a bit different: they're more like the
914 * old ssh1 mpint. You have a 32-bit bit count N, followed by
915 * (N+7)/8 bytes of data.
917 * So. The blob contains:
919 * - uint32 0x3f6ff9eb (magic number)
920 * - uint32 size (total blob size)
921 * - string key-type (see below)
922 * - string cipher-type (tells you if key is encrypted)
923 * - string encrypted-blob
925 * (The first size field includes the size field itself and the
926 * magic number before it. All other size fields are ordinary ssh2
927 * strings, so the size field indicates how much data is to
930 * The encrypted blob, once decrypted, contains a single string
931 * which in turn contains the payload. (This allows padding to be
932 * added after that string while still making it clear where the
933 * real payload ends. Also it probably makes for a reasonable
936 * The payload blob, for an RSA key, contains:
939 * - mpint n (yes, the public and private stuff is intermixed)
940 * - mpint u (presumably inverse of p mod q)
941 * - mpint p (p is the smaller prime)
942 * - mpint q (q is the larger)
944 * For a DSA key, the payload blob contains:
952 * Alternatively, if the parameters are `predefined', that
953 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
954 * containing some predefined parameter specification. *shudder*,
955 * but I doubt we'll encounter this in real life.
957 * The key type strings are ghastly. The RSA key I looked at had a
960 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
962 * and the DSA key wasn't much better:
964 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
966 * It isn't clear that these will always be the same. I think it
967 * might be wise just to look at the `if-modn{sign{rsa' and
968 * `dl-modp{sign{dsa' prefixes.
970 * Finally, the encryption. The cipher-type string appears to be
971 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
972 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
973 * from the passphrase by means of yet another hashing faff:
975 * - first 16 bytes are MD5(passphrase)
976 * - next 16 bytes are MD5(passphrase || first 16 bytes)
977 * - if there were more, they'd be MD5(passphrase || first 32),
981 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
984 char comment[256]; /* allowing any length is overkill */
985 unsigned char *keyblob;
986 int keyblob_len, keyblob_size;
989 static struct sshcom_key *load_sshcom_key(const Filename *filename)
991 struct sshcom_key *ret;
998 int base64_chars = 0;
1000 ret = snew(struct sshcom_key);
1001 ret->comment[0] = '\0';
1002 ret->keyblob = NULL;
1003 ret->keyblob_len = ret->keyblob_size = 0;
1005 fp = f_open(*filename, "r");
1007 errmsg = "Unable to open key file";
1010 if (!fgets(buffer, sizeof(buffer), fp) ||
1011 0 != strcmp(buffer, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1012 errmsg = "File does not begin with ssh.com key header";
1018 if (!fgets(buffer, sizeof(buffer), fp)) {
1019 errmsg = "Unexpected end of file";
1022 if (!strcmp(buffer, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1024 if ((p = strchr(buffer, ':')) != NULL) {
1026 errmsg = "Header found in body of key data";
1030 while (*p && isspace((unsigned char)*p)) p++;
1032 * Header lines can end in a trailing backslash for
1035 while ((len = strlen(p)) > (int)(sizeof(buffer) - (p-buffer) -1) ||
1036 p[len-1] != '\n' || p[len-2] == '\\') {
1037 if (len > (int)((p-buffer) + sizeof(buffer)-2)) {
1038 errmsg = "Header line too long to deal with";
1041 if (!fgets(p+len-2, sizeof(buffer)-(p-buffer)-(len-2), fp)) {
1042 errmsg = "Unexpected end of file";
1046 p[strcspn(p, "\n")] = '\0';
1047 if (!strcmp(buffer, "Comment")) {
1048 /* Strip quotes in comment if present. */
1049 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1051 p[strlen(p)-1] = '\0';
1053 strncpy(ret->comment, p, sizeof(ret->comment));
1054 ret->comment[sizeof(ret->comment)-1] = '\0';
1060 while (isbase64(*p)) {
1061 base64_bit[base64_chars++] = *p;
1062 if (base64_chars == 4) {
1063 unsigned char out[3];
1067 len = base64_decode_atom(base64_bit, out);
1070 errmsg = "Invalid base64 encoding";
1074 if (ret->keyblob_len + len > ret->keyblob_size) {
1075 ret->keyblob_size = ret->keyblob_len + len + 256;
1076 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1080 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1081 ret->keyblob_len += len;
1089 if (ret->keyblob_len == 0 || !ret->keyblob) {
1090 errmsg = "Key body not present";
1099 memset(ret->keyblob, 0, ret->keyblob_size);
1100 sfree(ret->keyblob);
1102 memset(&ret, 0, sizeof(ret));
1108 int sshcom_encrypted(const Filename *filename, char **comment)
1110 struct sshcom_key *key = load_sshcom_key(filename);
1111 int pos, len, answer;
1118 * Check magic number.
1120 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
1121 return 0; /* key is invalid */
1124 * Find the cipher-type string.
1128 if (key->keyblob_len < pos+4)
1129 goto done; /* key is far too short */
1130 pos += 4 + GET_32BIT(key->keyblob + pos); /* skip key type */
1131 if (key->keyblob_len < pos+4)
1132 goto done; /* key is far too short */
1133 len = GET_32BIT(key->keyblob + pos); /* find cipher-type length */
1134 if (key->keyblob_len < pos+4+len)
1135 goto done; /* cipher type string is incomplete */
1136 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1140 *comment = dupstr(key->comment);
1141 memset(key->keyblob, 0, key->keyblob_size);
1142 sfree(key->keyblob);
1143 memset(&key, 0, sizeof(key));
1148 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1152 unsigned char *d = (unsigned char *) data;
1156 bits = GET_32BIT(d);
1158 bytes = (bits + 7) / 8;
1169 return len; /* ensure further calls fail as well */
1172 static int sshcom_put_mpint(void *target, void *data, int len)
1174 unsigned char *d = (unsigned char *)target;
1175 unsigned char *i = (unsigned char *)data;
1176 int bits = len * 8 - 1;
1179 if (*i & (1 << (bits & 7)))
1185 PUT_32BIT(d, bits+1);
1186 memcpy(d+4, i, len);
1190 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase)
1192 struct sshcom_key *key = load_sshcom_key(filename);
1195 const char prefix_rsa[] = "if-modn{sign{rsa";
1196 const char prefix_dsa[] = "dl-modp{sign{dsa";
1197 enum { RSA, DSA } type;
1201 struct ssh2_userkey *ret = NULL, *retkey;
1202 const struct ssh_signkey *alg;
1203 unsigned char *blob = NULL;
1204 int blobsize, publen, privlen;
1210 * Check magic number.
1212 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1213 errmsg = "Key does not begin with magic number";
1218 * Determine the key type.
1221 if (key->keyblob_len < pos+4 ||
1222 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1223 errmsg = "Key blob does not contain a key type string";
1226 if (len > sizeof(prefix_rsa) - 1 &&
1227 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1229 } else if (len > sizeof(prefix_dsa) - 1 &&
1230 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1233 errmsg = "Key is of unknown type";
1239 * Determine the cipher type.
1241 if (key->keyblob_len < pos+4 ||
1242 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1243 errmsg = "Key blob does not contain a cipher type string";
1246 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1248 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1251 errmsg = "Key encryption is of unknown type";
1257 * Get hold of the encrypted part of the key.
1259 if (key->keyblob_len < pos+4 ||
1260 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1261 errmsg = "Key blob does not contain actual key data";
1264 ciphertext = (char *)key->keyblob + pos + 4;
1266 if (cipherlen == 0) {
1267 errmsg = "Length of key data is zero";
1272 * Decrypt it if necessary.
1276 * Derive encryption key from passphrase and iv/salt:
1278 * - let block A equal MD5(passphrase)
1279 * - let block B equal MD5(passphrase || A)
1280 * - block C would be MD5(passphrase || A || B) and so on
1281 * - encryption key is the first N bytes of A || B
1283 struct MD5Context md5c;
1284 unsigned char keybuf[32], iv[8];
1286 if (cipherlen % 8 != 0) {
1287 errmsg = "Encrypted part of key is not a multiple of cipher block"
1293 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1294 MD5Final(keybuf, &md5c);
1297 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1298 MD5Update(&md5c, keybuf, 16);
1299 MD5Final(keybuf+16, &md5c);
1302 * Now decrypt the key blob.
1304 memset(iv, 0, sizeof(iv));
1305 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1308 memset(&md5c, 0, sizeof(md5c));
1309 memset(keybuf, 0, sizeof(keybuf));
1312 * Hereafter we return WRONG_PASSPHRASE for any parsing
1313 * error. (But only if we've just tried to decrypt it!
1314 * Returning WRONG_PASSPHRASE for an unencrypted key is
1318 ret = SSH2_WRONG_PASSPHRASE;
1322 * Strip away the containing string to get to the real meat.
1324 len = GET_32BIT(ciphertext);
1325 if (len > cipherlen-4) {
1326 errmsg = "containing string was ill-formed";
1333 * Now we break down into RSA versus DSA. In either case we'll
1334 * construct public and private blobs in our own format, and
1335 * end up feeding them to alg->createkey().
1337 blobsize = cipherlen + 256;
1338 blob = snewn(blobsize, unsigned char);
1341 struct mpint_pos n, e, d, u, p, q;
1343 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1344 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1345 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1346 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1347 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1348 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1350 errmsg = "key data did not contain six integers";
1356 pos += put_string(blob+pos, "ssh-rsa", 7);
1357 pos += put_mp(blob+pos, e.start, e.bytes);
1358 pos += put_mp(blob+pos, n.start, n.bytes);
1360 pos += put_string(blob+pos, d.start, d.bytes);
1361 pos += put_mp(blob+pos, q.start, q.bytes);
1362 pos += put_mp(blob+pos, p.start, p.bytes);
1363 pos += put_mp(blob+pos, u.start, u.bytes);
1364 privlen = pos - publen;
1365 } else if (type == DSA) {
1366 struct mpint_pos p, q, g, x, y;
1368 if (GET_32BIT(ciphertext) != 0) {
1369 errmsg = "predefined DSA parameters not supported";
1372 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1373 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1374 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1375 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1376 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1378 errmsg = "key data did not contain five integers";
1384 pos += put_string(blob+pos, "ssh-dss", 7);
1385 pos += put_mp(blob+pos, p.start, p.bytes);
1386 pos += put_mp(blob+pos, q.start, q.bytes);
1387 pos += put_mp(blob+pos, g.start, g.bytes);
1388 pos += put_mp(blob+pos, y.start, y.bytes);
1390 pos += put_mp(blob+pos, x.start, x.bytes);
1391 privlen = pos - publen;
1394 assert(privlen > 0); /* should have bombed by now if not */
1396 retkey = snew(struct ssh2_userkey);
1398 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1399 if (!retkey->data) {
1401 errmsg = "unable to create key data structure";
1404 retkey->comment = dupstr(key->comment);
1406 errmsg = NULL; /* no error */
1411 memset(blob, 0, blobsize);
1414 memset(key->keyblob, 0, key->keyblob_size);
1415 sfree(key->keyblob);
1416 memset(&key, 0, sizeof(key));
1421 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1424 unsigned char *pubblob, *privblob;
1425 int publen, privlen;
1426 unsigned char *outblob;
1428 struct mpint_pos numbers[6];
1429 int nnumbers, initial_zero, pos, lenpos, i;
1437 * Fetch the key blobs.
1439 pubblob = key->alg->public_blob(key->data, &publen);
1440 privblob = key->alg->private_blob(key->data, &privlen);
1444 * Find the sequence of integers to be encoded into the OpenSSH
1445 * key blob, and also decide on the header line.
1447 if (key->alg == &ssh_rsa) {
1449 struct mpint_pos n, e, d, p, q, iqmp;
1451 pos = 4 + GET_32BIT(pubblob);
1452 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1453 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1455 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1456 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1457 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1458 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1460 assert(e.start && iqmp.start); /* can't go wrong */
1471 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1472 } else if (key->alg == &ssh_dss) {
1474 struct mpint_pos p, q, g, y, x;
1476 pos = 4 + GET_32BIT(pubblob);
1477 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1478 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1479 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1480 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1482 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1484 assert(y.start && x.start); /* can't go wrong */
1494 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1496 assert(0); /* zoinks! */
1500 * Total size of key blob will be somewhere under 512 plus
1501 * combined length of integers. We'll calculate the more
1502 * precise size as we construct the blob.
1505 for (i = 0; i < nnumbers; i++)
1506 outlen += 4 + numbers[i].bytes;
1507 outblob = snewn(outlen, unsigned char);
1510 * Create the unencrypted key blob.
1513 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1514 pos += 4; /* length field, fill in later */
1515 pos += put_string(outblob+pos, type, strlen(type));
1517 char *ciphertype = passphrase ? "3des-cbc" : "none";
1518 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1520 lenpos = pos; /* remember this position */
1521 pos += 4; /* encrypted-blob size */
1522 pos += 4; /* encrypted-payload size */
1524 PUT_32BIT(outblob+pos, 0);
1527 for (i = 0; i < nnumbers; i++)
1528 pos += sshcom_put_mpint(outblob+pos,
1529 numbers[i].start, numbers[i].bytes);
1530 /* Now wrap up the encrypted payload. */
1531 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1532 /* Pad encrypted blob to a multiple of cipher block size. */
1534 int padding = -(pos - (lenpos+4)) & 7;
1536 outblob[pos++] = random_byte();
1538 ciphertext = (char *)outblob+lenpos+4;
1539 cipherlen = pos - (lenpos+4);
1540 assert(!passphrase || cipherlen % 8 == 0);
1541 /* Wrap up the encrypted blob string. */
1542 PUT_32BIT(outblob+lenpos, cipherlen);
1543 /* And finally fill in the total length field. */
1544 PUT_32BIT(outblob+4, pos);
1546 assert(pos < outlen);
1553 * Derive encryption key from passphrase and iv/salt:
1555 * - let block A equal MD5(passphrase)
1556 * - let block B equal MD5(passphrase || A)
1557 * - block C would be MD5(passphrase || A || B) and so on
1558 * - encryption key is the first N bytes of A || B
1560 struct MD5Context md5c;
1561 unsigned char keybuf[32], iv[8];
1564 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1565 MD5Final(keybuf, &md5c);
1568 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1569 MD5Update(&md5c, keybuf, 16);
1570 MD5Final(keybuf+16, &md5c);
1573 * Now decrypt the key blob.
1575 memset(iv, 0, sizeof(iv));
1576 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1579 memset(&md5c, 0, sizeof(md5c));
1580 memset(keybuf, 0, sizeof(keybuf));
1584 * And save it. We'll use Unix line endings just in case it's
1585 * subsequently transferred in binary mode.
1587 fp = f_open(*filename, "wb"); /* ensure Unix line endings */
1590 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1591 fprintf(fp, "Comment: \"");
1593 * Comment header is broken with backslash-newline if it goes
1594 * over 70 chars. Although it's surrounded by quotes, it
1595 * _doesn't_ escape backslashes or quotes within the string.
1596 * Don't ask me, I didn't design it.
1599 int slen = 60; /* starts at 60 due to "Comment: " */
1600 char *c = key->comment;
1601 while ((int)strlen(c) > slen) {
1602 fprintf(fp, "%.*s\\\n", slen, c);
1604 slen = 70; /* allow 70 chars on subsequent lines */
1606 fprintf(fp, "%s\"\n", c);
1608 base64_encode(fp, outblob, pos, 70);
1609 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1615 memset(outblob, 0, outlen);
1619 memset(privblob, 0, privlen);
1623 memset(pubblob, 0, publen);