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) {
166 *id = (*id << 7) | (*p & 0x7F);
184 *length = (*length << 8) | (*p++);
191 return p - (unsigned char *) source;
195 * Write an ASN.1/BER identifier and length pair. Returns the
196 * number of bytes consumed. Assumes dest contains enough space.
197 * Will avoid writing anything if dest is NULL, but still return
198 * amount of space required.
200 static int ber_write_id_len(void *dest, int id, int length, int flags)
202 unsigned char *d = (unsigned char *)dest;
207 * Identifier is one byte.
210 if (d) *d++ = id | flags;
214 * Identifier is multiple bytes: the first byte is 11111
215 * plus the flags, and subsequent bytes encode the value of
216 * the identifier, 7 bits at a time, with the top bit of
217 * each byte 1 except the last one which is 0.
220 if (d) *d++ = 0x1F | flags;
221 for (n = 1; (id >> (7*n)) > 0; n++)
222 continue; /* count the bytes */
225 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
231 * Length is one byte.
234 if (d) *d++ = length;
238 * Length is multiple bytes. The first is 0x80 plus the
239 * number of subsequent bytes, and the subsequent bytes
240 * encode the actual length.
242 for (n = 1; (length >> (8*n)) > 0; n++)
243 continue; /* count the bytes */
245 if (d) *d++ = 0x80 | n;
248 if (d) *d++ = (length >> (8*n)) & 0xFF;
255 static int put_string(void *target, void *data, int len)
257 unsigned char *d = (unsigned char *)target;
260 memcpy(d+4, data, len);
264 static int put_mp(void *target, void *data, int len)
266 unsigned char *d = (unsigned char *)target;
267 unsigned char *i = (unsigned char *)data;
272 memcpy(d+5, data, len);
276 memcpy(d+4, data, len);
281 /* Simple structure to point to an mp-int within a blob. */
282 struct mpint_pos { void *start; int bytes; };
284 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
287 unsigned char *d = (unsigned char *) data;
291 bytes = GET_32BIT(d);
302 return len; /* ensure further calls fail as well */
305 /* ----------------------------------------------------------------------
306 * Code to read and write OpenSSH private keys.
309 enum { OSSH_DSA, OSSH_RSA };
314 unsigned char *keyblob;
315 int keyblob_len, keyblob_size;
318 static struct openssh_key *load_openssh_key(const Filename *filename)
320 struct openssh_key *ret;
326 int base64_chars = 0;
328 ret = snew(struct openssh_key);
330 ret->keyblob_len = ret->keyblob_size = 0;
332 memset(ret->iv, 0, sizeof(ret->iv));
334 fp = f_open(*filename, "r");
336 errmsg = "Unable to open key file";
339 if (!fgets(buffer, sizeof(buffer), fp) ||
340 0 != strncmp(buffer, "-----BEGIN ", 11) ||
341 0 != strcmp(buffer+strlen(buffer)-17, "PRIVATE KEY-----\n")) {
342 errmsg = "File does not begin with OpenSSH key header";
345 if (!strcmp(buffer, "-----BEGIN RSA PRIVATE KEY-----\n"))
346 ret->type = OSSH_RSA;
347 else if (!strcmp(buffer, "-----BEGIN DSA PRIVATE KEY-----\n"))
348 ret->type = OSSH_DSA;
350 errmsg = "Unrecognised key type";
356 if (!fgets(buffer, sizeof(buffer), fp)) {
357 errmsg = "Unexpected end of file";
360 if (0 == strncmp(buffer, "-----END ", 9) &&
361 0 == strcmp(buffer+strlen(buffer)-17, "PRIVATE KEY-----\n"))
363 if ((p = strchr(buffer, ':')) != NULL) {
365 errmsg = "Header found in body of key data";
369 while (*p && isspace((unsigned char)*p)) p++;
370 if (!strcmp(buffer, "Proc-Type")) {
371 if (p[0] != '4' || p[1] != ',') {
372 errmsg = "Proc-Type is not 4 (only 4 is supported)";
376 if (!strcmp(p, "ENCRYPTED\n"))
378 } else if (!strcmp(buffer, "DEK-Info")) {
381 if (strncmp(p, "DES-EDE3-CBC,", 13)) {
382 errmsg = "Ciphers other than DES-EDE3-CBC not supported";
386 for (i = 0; i < 8; i++) {
387 if (1 != sscanf(p, "%2x", &j))
393 errmsg = "Expected 16-digit iv in DEK-Info";
401 while (isbase64(*p)) {
402 base64_bit[base64_chars++] = *p;
403 if (base64_chars == 4) {
404 unsigned char out[3];
409 len = base64_decode_atom(base64_bit, out);
412 errmsg = "Invalid base64 encoding";
416 if (ret->keyblob_len + len > ret->keyblob_size) {
417 ret->keyblob_size = ret->keyblob_len + len + 256;
418 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
422 memcpy(ret->keyblob + ret->keyblob_len, out, len);
423 ret->keyblob_len += len;
425 memset(out, 0, sizeof(out));
433 if (ret->keyblob_len == 0 || !ret->keyblob) {
434 errmsg = "Key body not present";
438 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
439 errmsg = "Encrypted key blob is not a multiple of cipher block size";
443 memset(buffer, 0, sizeof(buffer));
444 memset(base64_bit, 0, sizeof(base64_bit));
448 memset(buffer, 0, sizeof(buffer));
449 memset(base64_bit, 0, sizeof(base64_bit));
452 memset(ret->keyblob, 0, ret->keyblob_size);
455 memset(&ret, 0, sizeof(ret));
461 int openssh_encrypted(const Filename *filename)
463 struct openssh_key *key = load_openssh_key(filename);
468 ret = key->encrypted;
469 memset(key->keyblob, 0, key->keyblob_size);
471 memset(&key, 0, sizeof(key));
476 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase)
478 struct openssh_key *key = load_openssh_key(filename);
479 struct ssh2_userkey *retkey;
481 int ret, id, len, flags;
483 struct ssh2_userkey *retval = NULL;
486 int blobsize = 0, blobptr, privptr;
495 if (key->encrypted) {
497 * Derive encryption key from passphrase and iv/salt:
499 * - let block A equal MD5(passphrase || iv)
500 * - let block B equal MD5(A || passphrase || iv)
501 * - block C would be MD5(B || passphrase || iv) and so on
502 * - encryption key is the first N bytes of A || B
504 struct MD5Context md5c;
505 unsigned char keybuf[32];
508 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
509 MD5Update(&md5c, (unsigned char *)key->iv, 8);
510 MD5Final(keybuf, &md5c);
513 MD5Update(&md5c, keybuf, 16);
514 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
515 MD5Update(&md5c, (unsigned char *)key->iv, 8);
516 MD5Final(keybuf+16, &md5c);
519 * Now decrypt the key blob.
521 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
522 key->keyblob, key->keyblob_len);
524 memset(&md5c, 0, sizeof(md5c));
525 memset(keybuf, 0, sizeof(keybuf));
529 * Now we have a decrypted key blob, which contains an ASN.1
530 * encoded private key. We must now untangle the ASN.1.
532 * We expect the whole key blob to be formatted as a SEQUENCE
533 * (0x30 followed by a length code indicating that the rest of
534 * the blob is part of the sequence). Within that SEQUENCE we
535 * expect to see a bunch of INTEGERs. What those integers mean
536 * depends on the key type:
538 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
539 * dmp1, dmq1, iqmp in that order. (The last three are d mod
540 * (p-1), d mod (q-1), inverse of q mod p respectively.)
542 * - For DSA, we expect them to be 0, p, q, g, y, x in that
548 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
549 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
551 if (ret < 0 || id != 16) {
552 errmsg = "ASN.1 decoding failure";
553 retval = SSH2_WRONG_PASSPHRASE;
557 /* Expect a load of INTEGERs. */
558 if (key->type == OSSH_RSA)
560 else if (key->type == OSSH_DSA)
563 num_integers = 0; /* placate compiler warnings */
566 * Space to create key blob in.
568 blobsize = 256+key->keyblob_len;
569 blob = snewn(blobsize, unsigned char);
571 if (key->type == OSSH_DSA)
572 memcpy(blob+4, "ssh-dss", 7);
573 else if (key->type == OSSH_RSA)
574 memcpy(blob+4, "ssh-rsa", 7);
578 for (i = 0; i < num_integers; i++) {
579 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
582 if (ret < 0 || id != 2 ||
583 key->keyblob+key->keyblob_len-p < len) {
584 errmsg = "ASN.1 decoding failure";
585 retval = SSH2_WRONG_PASSPHRASE;
591 * The first integer should be zero always (I think
592 * this is some sort of version indication).
594 if (len != 1 || p[0] != 0) {
595 errmsg = "Version number mismatch";
598 } else if (key->type == OSSH_RSA) {
600 * Integers 1 and 2 go into the public blob but in the
601 * opposite order; integers 3, 4, 5 and 8 go into the
602 * private blob. The other two (6 and 7) are ignored.
605 /* Save the details for after we deal with number 2. */
608 } else if (i != 6 && i != 7) {
609 PUT_32BIT(blob+blobptr, len);
610 memcpy(blob+blobptr+4, p, len);
613 PUT_32BIT(blob+blobptr, modlen);
614 memcpy(blob+blobptr+4, modptr, modlen);
619 } else if (key->type == OSSH_DSA) {
621 * Integers 1-4 go into the public blob; integer 5 goes
622 * into the private blob.
624 PUT_32BIT(blob+blobptr, len);
625 memcpy(blob+blobptr+4, p, len);
631 /* Skip past the number. */
636 * Now put together the actual key. Simplest way to do this is
637 * to assemble our own key blobs and feed them to the createkey
638 * functions; this is a bit faffy but it does mean we get all
639 * the sanity checks for free.
641 assert(privptr > 0); /* should have bombed by now if not */
642 retkey = snew(struct ssh2_userkey);
643 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
644 retkey->data = retkey->alg->createkey(blob, privptr,
645 blob+privptr, blobptr-privptr);
648 errmsg = "unable to create key data structure";
652 retkey->comment = dupstr("imported-openssh-key");
653 errmsg = NULL; /* no error */
658 memset(blob, 0, blobsize);
661 memset(key->keyblob, 0, key->keyblob_size);
663 memset(&key, 0, sizeof(key));
668 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
671 unsigned char *pubblob, *privblob, *spareblob;
672 int publen, privlen, sparelen = 0;
673 unsigned char *outblob;
675 struct mpint_pos numbers[9];
676 int nnumbers, pos, len, seqlen, i;
677 char *header, *footer;
684 * Fetch the key blobs.
686 pubblob = key->alg->public_blob(key->data, &publen);
687 privblob = key->alg->private_blob(key->data, &privlen);
688 spareblob = outblob = NULL;
691 * Find the sequence of integers to be encoded into the OpenSSH
692 * key blob, and also decide on the header line.
694 if (key->alg == &ssh_rsa) {
696 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
697 Bignum bd, bp, bq, bdmp1, bdmq1;
699 pos = 4 + GET_32BIT(pubblob);
700 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
701 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
703 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
704 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
705 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
706 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
708 assert(e.start && iqmp.start); /* can't go wrong */
710 /* We also need d mod (p-1) and d mod (q-1). */
711 bd = bignum_from_bytes(d.start, d.bytes);
712 bp = bignum_from_bytes(p.start, p.bytes);
713 bq = bignum_from_bytes(q.start, q.bytes);
716 bdmp1 = bigmod(bd, bp);
717 bdmq1 = bigmod(bd, bq);
722 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
723 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
724 sparelen = dmp1.bytes + dmq1.bytes;
725 spareblob = snewn(sparelen, unsigned char);
726 dmp1.start = spareblob;
727 dmq1.start = spareblob + dmp1.bytes;
728 for (i = 0; i < dmp1.bytes; i++)
729 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
730 for (i = 0; i < dmq1.bytes; i++)
731 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
735 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
746 header = "-----BEGIN RSA PRIVATE KEY-----\n";
747 footer = "-----END RSA PRIVATE KEY-----\n";
748 } else if (key->alg == &ssh_dss) {
750 struct mpint_pos p, q, g, y, x;
752 pos = 4 + GET_32BIT(pubblob);
753 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
754 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
755 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
756 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
758 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
760 assert(y.start && x.start); /* can't go wrong */
762 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
770 header = "-----BEGIN DSA PRIVATE KEY-----\n";
771 footer = "-----END DSA PRIVATE KEY-----\n";
773 assert(0); /* zoinks! */
777 * Now count up the total size of the ASN.1 encoded integers,
778 * so as to determine the length of the containing SEQUENCE.
781 for (i = 0; i < nnumbers; i++) {
782 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
783 len += numbers[i].bytes;
786 /* Now add on the SEQUENCE header. */
787 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
788 /* Round up to the cipher block size, ensuring we have at least one
789 * byte of padding (see below). */
792 outlen = (outlen+8) &~ 7;
795 * Now we know how big outblob needs to be. Allocate it.
797 outblob = snewn(outlen, unsigned char);
800 * And write the data into it.
803 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
804 for (i = 0; i < nnumbers; i++) {
805 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
806 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
807 pos += numbers[i].bytes;
811 * Padding on OpenSSH keys is deterministic. The number of
812 * padding bytes is always more than zero, and always at most
813 * the cipher block length. The value of each padding byte is
814 * equal to the number of padding bytes. So a plaintext that's
815 * an exact multiple of the block size will be padded with 08
816 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
817 * plaintext one byte less than a multiple of the block size
818 * will be padded with just 01.
820 * This enables the OpenSSL key decryption function to strip
821 * off the padding algorithmically and return the unpadded
822 * plaintext to the next layer: it looks at the final byte, and
823 * then expects to find that many bytes at the end of the data
824 * with the same value. Those are all removed and the rest is
828 while (pos < outlen) {
829 outblob[pos++] = outlen - len;
837 * Invent an iv. Then derive encryption key from passphrase
840 * - let block A equal MD5(passphrase || iv)
841 * - let block B equal MD5(A || passphrase || iv)
842 * - block C would be MD5(B || passphrase || iv) and so on
843 * - encryption key is the first N bytes of A || B
845 struct MD5Context md5c;
846 unsigned char keybuf[32];
848 for (i = 0; i < 8; i++) iv[i] = random_byte();
851 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
852 MD5Update(&md5c, iv, 8);
853 MD5Final(keybuf, &md5c);
856 MD5Update(&md5c, keybuf, 16);
857 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
858 MD5Update(&md5c, iv, 8);
859 MD5Final(keybuf+16, &md5c);
862 * Now encrypt the key blob.
864 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
866 memset(&md5c, 0, sizeof(md5c));
867 memset(keybuf, 0, sizeof(keybuf));
871 * And save it. We'll use Unix line endings just in case it's
872 * subsequently transferred in binary mode.
874 fp = f_open(*filename, "wb"); /* ensure Unix line endings */
879 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
880 for (i = 0; i < 8; i++)
881 fprintf(fp, "%02X", iv[i]);
884 base64_encode(fp, outblob, outlen, 64);
891 memset(outblob, 0, outlen);
895 memset(spareblob, 0, sparelen);
899 memset(privblob, 0, privlen);
903 memset(pubblob, 0, publen);
909 /* ----------------------------------------------------------------------
910 * Code to read ssh.com private keys.
914 * The format of the base64 blob is largely ssh2-packet-formatted,
915 * except that mpints are a bit different: they're more like the
916 * old ssh1 mpint. You have a 32-bit bit count N, followed by
917 * (N+7)/8 bytes of data.
919 * So. The blob contains:
921 * - uint32 0x3f6ff9eb (magic number)
922 * - uint32 size (total blob size)
923 * - string key-type (see below)
924 * - string cipher-type (tells you if key is encrypted)
925 * - string encrypted-blob
927 * (The first size field includes the size field itself and the
928 * magic number before it. All other size fields are ordinary ssh2
929 * strings, so the size field indicates how much data is to
932 * The encrypted blob, once decrypted, contains a single string
933 * which in turn contains the payload. (This allows padding to be
934 * added after that string while still making it clear where the
935 * real payload ends. Also it probably makes for a reasonable
938 * The payload blob, for an RSA key, contains:
941 * - mpint n (yes, the public and private stuff is intermixed)
942 * - mpint u (presumably inverse of p mod q)
943 * - mpint p (p is the smaller prime)
944 * - mpint q (q is the larger)
946 * For a DSA key, the payload blob contains:
954 * Alternatively, if the parameters are `predefined', that
955 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
956 * containing some predefined parameter specification. *shudder*,
957 * but I doubt we'll encounter this in real life.
959 * The key type strings are ghastly. The RSA key I looked at had a
962 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
964 * and the DSA key wasn't much better:
966 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
968 * It isn't clear that these will always be the same. I think it
969 * might be wise just to look at the `if-modn{sign{rsa' and
970 * `dl-modp{sign{dsa' prefixes.
972 * Finally, the encryption. The cipher-type string appears to be
973 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
974 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
975 * from the passphrase by means of yet another hashing faff:
977 * - first 16 bytes are MD5(passphrase)
978 * - next 16 bytes are MD5(passphrase || first 16 bytes)
979 * - if there were more, they'd be MD5(passphrase || first 32),
983 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
986 char comment[256]; /* allowing any length is overkill */
987 unsigned char *keyblob;
988 int keyblob_len, keyblob_size;
991 static struct sshcom_key *load_sshcom_key(const Filename *filename)
993 struct sshcom_key *ret;
1000 int base64_chars = 0;
1002 ret = snew(struct sshcom_key);
1003 ret->comment[0] = '\0';
1004 ret->keyblob = NULL;
1005 ret->keyblob_len = ret->keyblob_size = 0;
1007 fp = f_open(*filename, "r");
1009 errmsg = "Unable to open key file";
1012 if (!fgets(buffer, sizeof(buffer), fp) ||
1013 0 != strcmp(buffer, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1014 errmsg = "File does not begin with ssh.com key header";
1020 if (!fgets(buffer, sizeof(buffer), fp)) {
1021 errmsg = "Unexpected end of file";
1024 if (!strcmp(buffer, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1026 if ((p = strchr(buffer, ':')) != NULL) {
1028 errmsg = "Header found in body of key data";
1032 while (*p && isspace((unsigned char)*p)) p++;
1034 * Header lines can end in a trailing backslash for
1037 while ((len = strlen(p)) > (int)(sizeof(buffer) - (p-buffer) -1) ||
1038 p[len-1] != '\n' || p[len-2] == '\\') {
1039 if (len > (int)((p-buffer) + sizeof(buffer)-2)) {
1040 errmsg = "Header line too long to deal with";
1043 if (!fgets(p+len-2, sizeof(buffer)-(p-buffer)-(len-2), fp)) {
1044 errmsg = "Unexpected end of file";
1048 p[strcspn(p, "\n")] = '\0';
1049 if (!strcmp(buffer, "Comment")) {
1050 /* Strip quotes in comment if present. */
1051 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1053 p[strlen(p)-1] = '\0';
1055 strncpy(ret->comment, p, sizeof(ret->comment));
1056 ret->comment[sizeof(ret->comment)-1] = '\0';
1062 while (isbase64(*p)) {
1063 base64_bit[base64_chars++] = *p;
1064 if (base64_chars == 4) {
1065 unsigned char out[3];
1069 len = base64_decode_atom(base64_bit, out);
1072 errmsg = "Invalid base64 encoding";
1076 if (ret->keyblob_len + len > ret->keyblob_size) {
1077 ret->keyblob_size = ret->keyblob_len + len + 256;
1078 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1082 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1083 ret->keyblob_len += len;
1091 if (ret->keyblob_len == 0 || !ret->keyblob) {
1092 errmsg = "Key body not present";
1101 memset(ret->keyblob, 0, ret->keyblob_size);
1102 sfree(ret->keyblob);
1104 memset(&ret, 0, sizeof(ret));
1110 int sshcom_encrypted(const Filename *filename, char **comment)
1112 struct sshcom_key *key = load_sshcom_key(filename);
1113 int pos, len, answer;
1120 * Check magic number.
1122 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
1123 return 0; /* key is invalid */
1126 * Find the cipher-type string.
1130 if (key->keyblob_len < pos+4)
1131 goto done; /* key is far too short */
1132 pos += 4 + GET_32BIT(key->keyblob + pos); /* skip key type */
1133 if (key->keyblob_len < pos+4)
1134 goto done; /* key is far too short */
1135 len = GET_32BIT(key->keyblob + pos); /* find cipher-type length */
1136 if (key->keyblob_len < pos+4+len)
1137 goto done; /* cipher type string is incomplete */
1138 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1142 *comment = dupstr(key->comment);
1143 memset(key->keyblob, 0, key->keyblob_size);
1144 sfree(key->keyblob);
1145 memset(&key, 0, sizeof(key));
1150 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1154 unsigned char *d = (unsigned char *) data;
1158 bits = GET_32BIT(d);
1160 bytes = (bits + 7) / 8;
1171 return len; /* ensure further calls fail as well */
1174 static int sshcom_put_mpint(void *target, void *data, int len)
1176 unsigned char *d = (unsigned char *)target;
1177 unsigned char *i = (unsigned char *)data;
1178 int bits = len * 8 - 1;
1181 if (*i & (1 << (bits & 7)))
1187 PUT_32BIT(d, bits+1);
1188 memcpy(d+4, i, len);
1192 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase)
1194 struct sshcom_key *key = load_sshcom_key(filename);
1197 const char prefix_rsa[] = "if-modn{sign{rsa";
1198 const char prefix_dsa[] = "dl-modp{sign{dsa";
1199 enum { RSA, DSA } type;
1203 struct ssh2_userkey *ret = NULL, *retkey;
1204 const struct ssh_signkey *alg;
1205 unsigned char *blob = NULL;
1206 int blobsize = 0, publen, privlen;
1212 * Check magic number.
1214 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1215 errmsg = "Key does not begin with magic number";
1220 * Determine the key type.
1223 if (key->keyblob_len < pos+4 ||
1224 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1225 errmsg = "Key blob does not contain a key type string";
1228 if (len > sizeof(prefix_rsa) - 1 &&
1229 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1231 } else if (len > sizeof(prefix_dsa) - 1 &&
1232 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1235 errmsg = "Key is of unknown type";
1241 * Determine the cipher type.
1243 if (key->keyblob_len < pos+4 ||
1244 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1245 errmsg = "Key blob does not contain a cipher type string";
1248 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1250 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1253 errmsg = "Key encryption is of unknown type";
1259 * Get hold of the encrypted part of the key.
1261 if (key->keyblob_len < pos+4 ||
1262 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1263 errmsg = "Key blob does not contain actual key data";
1266 ciphertext = (char *)key->keyblob + pos + 4;
1268 if (cipherlen == 0) {
1269 errmsg = "Length of key data is zero";
1274 * Decrypt it if necessary.
1278 * Derive encryption key from passphrase and iv/salt:
1280 * - let block A equal MD5(passphrase)
1281 * - let block B equal MD5(passphrase || A)
1282 * - block C would be MD5(passphrase || A || B) and so on
1283 * - encryption key is the first N bytes of A || B
1285 struct MD5Context md5c;
1286 unsigned char keybuf[32], iv[8];
1288 if (cipherlen % 8 != 0) {
1289 errmsg = "Encrypted part of key is not a multiple of cipher block"
1295 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1296 MD5Final(keybuf, &md5c);
1299 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1300 MD5Update(&md5c, keybuf, 16);
1301 MD5Final(keybuf+16, &md5c);
1304 * Now decrypt the key blob.
1306 memset(iv, 0, sizeof(iv));
1307 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1310 memset(&md5c, 0, sizeof(md5c));
1311 memset(keybuf, 0, sizeof(keybuf));
1314 * Hereafter we return WRONG_PASSPHRASE for any parsing
1315 * error. (But only if we've just tried to decrypt it!
1316 * Returning WRONG_PASSPHRASE for an unencrypted key is
1320 ret = SSH2_WRONG_PASSPHRASE;
1324 * Strip away the containing string to get to the real meat.
1326 len = GET_32BIT(ciphertext);
1327 if (len < 0 || len > cipherlen-4) {
1328 errmsg = "containing string was ill-formed";
1335 * Now we break down into RSA versus DSA. In either case we'll
1336 * construct public and private blobs in our own format, and
1337 * end up feeding them to alg->createkey().
1339 blobsize = cipherlen + 256;
1340 blob = snewn(blobsize, unsigned char);
1343 struct mpint_pos n, e, d, u, p, q;
1345 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1346 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1347 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1348 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1349 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1350 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1352 errmsg = "key data did not contain six integers";
1358 pos += put_string(blob+pos, "ssh-rsa", 7);
1359 pos += put_mp(blob+pos, e.start, e.bytes);
1360 pos += put_mp(blob+pos, n.start, n.bytes);
1362 pos += put_string(blob+pos, d.start, d.bytes);
1363 pos += put_mp(blob+pos, q.start, q.bytes);
1364 pos += put_mp(blob+pos, p.start, p.bytes);
1365 pos += put_mp(blob+pos, u.start, u.bytes);
1366 privlen = pos - publen;
1367 } else if (type == DSA) {
1368 struct mpint_pos p, q, g, x, y;
1370 if (GET_32BIT(ciphertext) != 0) {
1371 errmsg = "predefined DSA parameters not supported";
1374 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1375 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1376 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1377 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1378 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1380 errmsg = "key data did not contain five integers";
1386 pos += put_string(blob+pos, "ssh-dss", 7);
1387 pos += put_mp(blob+pos, p.start, p.bytes);
1388 pos += put_mp(blob+pos, q.start, q.bytes);
1389 pos += put_mp(blob+pos, g.start, g.bytes);
1390 pos += put_mp(blob+pos, y.start, y.bytes);
1392 pos += put_mp(blob+pos, x.start, x.bytes);
1393 privlen = pos - publen;
1397 assert(privlen > 0); /* should have bombed by now if not */
1399 retkey = snew(struct ssh2_userkey);
1401 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1402 if (!retkey->data) {
1404 errmsg = "unable to create key data structure";
1407 retkey->comment = dupstr(key->comment);
1409 errmsg = NULL; /* no error */
1414 memset(blob, 0, blobsize);
1417 memset(key->keyblob, 0, key->keyblob_size);
1418 sfree(key->keyblob);
1419 memset(&key, 0, sizeof(key));
1424 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1427 unsigned char *pubblob, *privblob;
1428 int publen, privlen;
1429 unsigned char *outblob;
1431 struct mpint_pos numbers[6];
1432 int nnumbers, initial_zero, pos, lenpos, i;
1440 * Fetch the key blobs.
1442 pubblob = key->alg->public_blob(key->data, &publen);
1443 privblob = key->alg->private_blob(key->data, &privlen);
1447 * Find the sequence of integers to be encoded into the OpenSSH
1448 * key blob, and also decide on the header line.
1450 if (key->alg == &ssh_rsa) {
1452 struct mpint_pos n, e, d, p, q, iqmp;
1454 pos = 4 + GET_32BIT(pubblob);
1455 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1456 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1458 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1459 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1460 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1461 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1463 assert(e.start && iqmp.start); /* can't go wrong */
1474 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1475 } else if (key->alg == &ssh_dss) {
1477 struct mpint_pos p, q, g, y, x;
1479 pos = 4 + GET_32BIT(pubblob);
1480 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1481 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1482 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1483 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1485 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1487 assert(y.start && x.start); /* can't go wrong */
1497 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1499 assert(0); /* zoinks! */
1503 * Total size of key blob will be somewhere under 512 plus
1504 * combined length of integers. We'll calculate the more
1505 * precise size as we construct the blob.
1508 for (i = 0; i < nnumbers; i++)
1509 outlen += 4 + numbers[i].bytes;
1510 outblob = snewn(outlen, unsigned char);
1513 * Create the unencrypted key blob.
1516 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1517 pos += 4; /* length field, fill in later */
1518 pos += put_string(outblob+pos, type, strlen(type));
1520 char *ciphertype = passphrase ? "3des-cbc" : "none";
1521 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1523 lenpos = pos; /* remember this position */
1524 pos += 4; /* encrypted-blob size */
1525 pos += 4; /* encrypted-payload size */
1527 PUT_32BIT(outblob+pos, 0);
1530 for (i = 0; i < nnumbers; i++)
1531 pos += sshcom_put_mpint(outblob+pos,
1532 numbers[i].start, numbers[i].bytes);
1533 /* Now wrap up the encrypted payload. */
1534 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1535 /* Pad encrypted blob to a multiple of cipher block size. */
1537 int padding = -(pos - (lenpos+4)) & 7;
1539 outblob[pos++] = random_byte();
1541 ciphertext = (char *)outblob+lenpos+4;
1542 cipherlen = pos - (lenpos+4);
1543 assert(!passphrase || cipherlen % 8 == 0);
1544 /* Wrap up the encrypted blob string. */
1545 PUT_32BIT(outblob+lenpos, cipherlen);
1546 /* And finally fill in the total length field. */
1547 PUT_32BIT(outblob+4, pos);
1549 assert(pos < outlen);
1556 * Derive encryption key from passphrase and iv/salt:
1558 * - let block A equal MD5(passphrase)
1559 * - let block B equal MD5(passphrase || A)
1560 * - block C would be MD5(passphrase || A || B) and so on
1561 * - encryption key is the first N bytes of A || B
1563 struct MD5Context md5c;
1564 unsigned char keybuf[32], iv[8];
1567 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1568 MD5Final(keybuf, &md5c);
1571 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1572 MD5Update(&md5c, keybuf, 16);
1573 MD5Final(keybuf+16, &md5c);
1576 * Now decrypt the key blob.
1578 memset(iv, 0, sizeof(iv));
1579 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1582 memset(&md5c, 0, sizeof(md5c));
1583 memset(keybuf, 0, sizeof(keybuf));
1587 * And save it. We'll use Unix line endings just in case it's
1588 * subsequently transferred in binary mode.
1590 fp = f_open(*filename, "wb"); /* ensure Unix line endings */
1593 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1594 fprintf(fp, "Comment: \"");
1596 * Comment header is broken with backslash-newline if it goes
1597 * over 70 chars. Although it's surrounded by quotes, it
1598 * _doesn't_ escape backslashes or quotes within the string.
1599 * Don't ask me, I didn't design it.
1602 int slen = 60; /* starts at 60 due to "Comment: " */
1603 char *c = key->comment;
1604 while ((int)strlen(c) > slen) {
1605 fprintf(fp, "%.*s\\\n", slen, c);
1607 slen = 70; /* allow 70 chars on subsequent lines */
1609 fprintf(fp, "%s\"\n", c);
1611 base64_encode(fp, outblob, pos, 70);
1612 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1618 memset(outblob, 0, outlen);
1622 memset(privblob, 0, privlen);
1626 memset(pubblob, 0, publen);