2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 int openssh_encrypted(const Filename *filename);
16 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
17 const char **errmsg_p);
18 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
21 int sshcom_encrypted(const Filename *filename, char **comment);
22 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
23 const char **errmsg_p);
24 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
28 * Given a key type, determine whether we know how to import it.
30 int import_possible(int type)
32 if (type == SSH_KEYTYPE_OPENSSH)
34 if (type == SSH_KEYTYPE_SSHCOM)
40 * Given a key type, determine what native key type
41 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
44 int import_target_type(int type)
47 * There are no known foreign SSH-1 key formats.
49 return SSH_KEYTYPE_SSH2;
53 * Determine whether a foreign key is encrypted.
55 int import_encrypted(const Filename *filename, int type, char **comment)
57 if (type == SSH_KEYTYPE_OPENSSH) {
58 /* OpenSSH doesn't do key comments */
59 *comment = dupstr(filename_to_str(filename));
60 return openssh_encrypted(filename);
62 if (type == SSH_KEYTYPE_SSHCOM) {
63 return sshcom_encrypted(filename, comment);
69 * Import an SSH-1 key.
71 int import_ssh1(const Filename *filename, int type,
72 struct RSAKey *key, char *passphrase, const char **errmsg_p)
78 * Import an SSH-2 key.
80 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
81 char *passphrase, const char **errmsg_p)
83 if (type == SSH_KEYTYPE_OPENSSH)
84 return openssh_read(filename, passphrase, errmsg_p);
85 if (type == SSH_KEYTYPE_SSHCOM)
86 return sshcom_read(filename, passphrase, errmsg_p);
91 * Export an SSH-1 key.
93 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
100 * Export an SSH-2 key.
102 int export_ssh2(const Filename *filename, int type,
103 struct ssh2_userkey *key, char *passphrase)
105 if (type == SSH_KEYTYPE_OPENSSH)
106 return openssh_write(filename, key, passphrase);
107 if (type == SSH_KEYTYPE_SSHCOM)
108 return sshcom_write(filename, key, passphrase);
113 * Strip trailing CRs and LFs at the end of a line of text.
115 void strip_crlf(char *str)
117 char *p = str + strlen(str);
119 while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
123 /* ----------------------------------------------------------------------
124 * Helper routines. (The base64 ones are defined in sshpubk.c.)
127 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
128 ((c) >= 'a' && (c) <= 'z') || \
129 ((c) >= '0' && (c) <= '9') || \
130 (c) == '+' || (c) == '/' || (c) == '=' \
134 * Read an ASN.1/BER identifier and length pair.
136 * Flags are a combination of the #defines listed below.
138 * Returns -1 if unsuccessful; otherwise returns the number of
139 * bytes used out of the source data.
142 /* ASN.1 tag classes. */
143 #define ASN1_CLASS_UNIVERSAL (0 << 6)
144 #define ASN1_CLASS_APPLICATION (1 << 6)
145 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
146 #define ASN1_CLASS_PRIVATE (3 << 6)
147 #define ASN1_CLASS_MASK (3 << 6)
149 /* Primitive versus constructed bit. */
150 #define ASN1_CONSTRUCTED (1 << 5)
152 static int ber_read_id_len(void *source, int sourcelen,
153 int *id, int *length, int *flags)
155 unsigned char *p = (unsigned char *) source;
160 *flags = (*p & 0xE0);
161 if ((*p & 0x1F) == 0x1F) {
167 *id = (*id << 7) | (*p & 0x7F);
185 *length = (*length << 8) | (*p++);
192 return p - (unsigned char *) source;
196 * Write an ASN.1/BER identifier and length pair. Returns the
197 * number of bytes consumed. Assumes dest contains enough space.
198 * Will avoid writing anything if dest is NULL, but still return
199 * amount of space required.
201 static int ber_write_id_len(void *dest, int id, int length, int flags)
203 unsigned char *d = (unsigned char *)dest;
208 * Identifier is one byte.
211 if (d) *d++ = id | flags;
215 * Identifier is multiple bytes: the first byte is 11111
216 * plus the flags, and subsequent bytes encode the value of
217 * the identifier, 7 bits at a time, with the top bit of
218 * each byte 1 except the last one which is 0.
221 if (d) *d++ = 0x1F | flags;
222 for (n = 1; (id >> (7*n)) > 0; n++)
223 continue; /* count the bytes */
226 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
232 * Length is one byte.
235 if (d) *d++ = length;
239 * Length is multiple bytes. The first is 0x80 plus the
240 * number of subsequent bytes, and the subsequent bytes
241 * encode the actual length.
243 for (n = 1; (length >> (8*n)) > 0; n++)
244 continue; /* count the bytes */
246 if (d) *d++ = 0x80 | n;
249 if (d) *d++ = (length >> (8*n)) & 0xFF;
256 static int put_string(void *target, void *data, int len)
258 unsigned char *d = (unsigned char *)target;
261 memcpy(d+4, data, len);
265 static int put_mp(void *target, void *data, int len)
267 unsigned char *d = (unsigned char *)target;
268 unsigned char *i = (unsigned char *)data;
273 memcpy(d+5, data, len);
277 memcpy(d+4, data, len);
282 /* Simple structure to point to an mp-int within a blob. */
283 struct mpint_pos { void *start; int bytes; };
285 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
288 unsigned char *d = (unsigned char *) data;
292 bytes = toint(GET_32BIT(d));
293 if (bytes < 0 || len-4 < bytes)
303 return len; /* ensure further calls fail as well */
306 /* ----------------------------------------------------------------------
307 * Code to read and write OpenSSH private keys.
310 enum { OSSH_DSA, OSSH_RSA };
311 enum { OSSH_ENC_3DES, OSSH_ENC_AES };
314 int encrypted, encryption;
316 unsigned char *keyblob;
317 int keyblob_len, keyblob_size;
320 static struct openssh_key *load_openssh_key(const Filename *filename,
321 const char **errmsg_p)
323 struct openssh_key *ret;
329 int base64_chars = 0;
331 ret = snew(struct openssh_key);
333 ret->keyblob_len = ret->keyblob_size = 0;
335 memset(ret->iv, 0, sizeof(ret->iv));
337 fp = f_open(filename, "r", FALSE);
339 errmsg = "unable to open key file";
343 if (!(line = fgetline(fp))) {
344 errmsg = "unexpected end of file";
348 if (0 != strncmp(line, "-----BEGIN ", 11) ||
349 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
350 errmsg = "file does not begin with OpenSSH key header";
353 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----"))
354 ret->type = OSSH_RSA;
355 else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----"))
356 ret->type = OSSH_DSA;
358 errmsg = "unrecognised key type";
361 smemclr(line, strlen(line));
367 if (!(line = fgetline(fp))) {
368 errmsg = "unexpected end of file";
372 if (0 == strncmp(line, "-----END ", 9) &&
373 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
377 if ((p = strchr(line, ':')) != NULL) {
379 errmsg = "header found in body of key data";
383 while (*p && isspace((unsigned char)*p)) p++;
384 if (!strcmp(line, "Proc-Type")) {
385 if (p[0] != '4' || p[1] != ',') {
386 errmsg = "Proc-Type is not 4 (only 4 is supported)";
390 if (!strcmp(p, "ENCRYPTED"))
392 } else if (!strcmp(line, "DEK-Info")) {
395 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
396 ret->encryption = OSSH_ENC_3DES;
398 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
399 ret->encryption = OSSH_ENC_AES;
402 errmsg = "unsupported cipher";
405 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
406 for (i = 0; i < ivlen; i++) {
407 if (1 != sscanf(p, "%2x", &j)) {
408 errmsg = "expected more iv data in DEK-Info";
415 errmsg = "more iv data than expected in DEK-Info";
423 while (isbase64(*p)) {
424 base64_bit[base64_chars++] = *p;
425 if (base64_chars == 4) {
426 unsigned char out[3];
431 len = base64_decode_atom(base64_bit, out);
434 errmsg = "invalid base64 encoding";
438 if (ret->keyblob_len + len > ret->keyblob_size) {
439 ret->keyblob_size = ret->keyblob_len + len + 256;
440 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
444 memcpy(ret->keyblob + ret->keyblob_len, out, len);
445 ret->keyblob_len += len;
447 smemclr(out, sizeof(out));
453 smemclr(line, strlen(line));
461 if (ret->keyblob_len == 0 || !ret->keyblob) {
462 errmsg = "key body not present";
466 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
467 errmsg = "encrypted key blob is not a multiple of cipher block size";
471 smemclr(base64_bit, sizeof(base64_bit));
472 if (errmsg_p) *errmsg_p = NULL;
477 smemclr(line, strlen(line));
481 smemclr(base64_bit, sizeof(base64_bit));
484 smemclr(ret->keyblob, ret->keyblob_size);
487 smemclr(ret, sizeof(*ret));
490 if (errmsg_p) *errmsg_p = errmsg;
495 int openssh_encrypted(const Filename *filename)
497 struct openssh_key *key = load_openssh_key(filename, NULL);
502 ret = key->encrypted;
503 smemclr(key->keyblob, key->keyblob_size);
505 smemclr(key, sizeof(*key));
510 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
511 const char **errmsg_p)
513 struct openssh_key *key = load_openssh_key(filename, errmsg_p);
514 struct ssh2_userkey *retkey;
516 int ret, id, len, flags;
518 struct ssh2_userkey *retval = NULL;
521 int blobsize = 0, blobptr, privptr;
530 if (key->encrypted) {
532 * Derive encryption key from passphrase and iv/salt:
534 * - let block A equal MD5(passphrase || iv)
535 * - let block B equal MD5(A || passphrase || iv)
536 * - block C would be MD5(B || passphrase || iv) and so on
537 * - encryption key is the first N bytes of A || B
539 * (Note that only 8 bytes of the iv are used for key
540 * derivation, even when the key is encrypted with AES and
541 * hence there are 16 bytes available.)
543 struct MD5Context md5c;
544 unsigned char keybuf[32];
547 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
548 MD5Update(&md5c, (unsigned char *)key->iv, 8);
549 MD5Final(keybuf, &md5c);
552 MD5Update(&md5c, keybuf, 16);
553 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
554 MD5Update(&md5c, (unsigned char *)key->iv, 8);
555 MD5Final(keybuf+16, &md5c);
558 * Now decrypt the key blob.
560 if (key->encryption == OSSH_ENC_3DES)
561 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
562 key->keyblob, key->keyblob_len);
565 assert(key->encryption == OSSH_ENC_AES);
566 ctx = aes_make_context();
567 aes128_key(ctx, keybuf);
568 aes_iv(ctx, (unsigned char *)key->iv);
569 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
570 aes_free_context(ctx);
573 smemclr(&md5c, sizeof(md5c));
574 smemclr(keybuf, sizeof(keybuf));
578 * Now we have a decrypted key blob, which contains an ASN.1
579 * encoded private key. We must now untangle the ASN.1.
581 * We expect the whole key blob to be formatted as a SEQUENCE
582 * (0x30 followed by a length code indicating that the rest of
583 * the blob is part of the sequence). Within that SEQUENCE we
584 * expect to see a bunch of INTEGERs. What those integers mean
585 * depends on the key type:
587 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
588 * dmp1, dmq1, iqmp in that order. (The last three are d mod
589 * (p-1), d mod (q-1), inverse of q mod p respectively.)
591 * - For DSA, we expect them to be 0, p, q, g, y, x in that
597 /* Expect the SEQUENCE header. Take its absence as a failure to
598 * decrypt, if the key was encrypted. */
599 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
601 if (ret < 0 || id != 16) {
602 errmsg = "ASN.1 decoding failure";
603 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
607 /* Expect a load of INTEGERs. */
608 if (key->type == OSSH_RSA)
610 else if (key->type == OSSH_DSA)
613 num_integers = 0; /* placate compiler warnings */
616 * Space to create key blob in.
618 blobsize = 256+key->keyblob_len;
619 blob = snewn(blobsize, unsigned char);
621 if (key->type == OSSH_DSA)
622 memcpy(blob+4, "ssh-dss", 7);
623 else if (key->type == OSSH_RSA)
624 memcpy(blob+4, "ssh-rsa", 7);
628 for (i = 0; i < num_integers; i++) {
629 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
632 if (ret < 0 || id != 2 ||
633 key->keyblob+key->keyblob_len-p < len) {
634 errmsg = "ASN.1 decoding failure";
635 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
641 * The first integer should be zero always (I think
642 * this is some sort of version indication).
644 if (len != 1 || p[0] != 0) {
645 errmsg = "version number mismatch";
648 } else if (key->type == OSSH_RSA) {
650 * Integers 1 and 2 go into the public blob but in the
651 * opposite order; integers 3, 4, 5 and 8 go into the
652 * private blob. The other two (6 and 7) are ignored.
655 /* Save the details for after we deal with number 2. */
658 } else if (i != 6 && i != 7) {
659 PUT_32BIT(blob+blobptr, len);
660 memcpy(blob+blobptr+4, p, len);
663 PUT_32BIT(blob+blobptr, modlen);
664 memcpy(blob+blobptr+4, modptr, modlen);
669 } else if (key->type == OSSH_DSA) {
671 * Integers 1-4 go into the public blob; integer 5 goes
672 * into the private blob.
674 PUT_32BIT(blob+blobptr, len);
675 memcpy(blob+blobptr+4, p, len);
681 /* Skip past the number. */
686 * Now put together the actual key. Simplest way to do this is
687 * to assemble our own key blobs and feed them to the createkey
688 * functions; this is a bit faffy but it does mean we get all
689 * the sanity checks for free.
691 assert(privptr > 0); /* should have bombed by now if not */
692 retkey = snew(struct ssh2_userkey);
693 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
694 retkey->data = retkey->alg->createkey(blob, privptr,
695 blob+privptr, blobptr-privptr);
698 errmsg = "unable to create key data structure";
702 retkey->comment = dupstr("imported-openssh-key");
703 errmsg = NULL; /* no error */
708 smemclr(blob, blobsize);
711 smemclr(key->keyblob, key->keyblob_size);
713 smemclr(key, sizeof(*key));
715 if (errmsg_p) *errmsg_p = errmsg;
719 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
722 unsigned char *pubblob, *privblob, *spareblob;
723 int publen, privlen, sparelen = 0;
724 unsigned char *outblob;
726 struct mpint_pos numbers[9];
727 int nnumbers, pos, len, seqlen, i;
728 char *header, *footer;
735 * Fetch the key blobs.
737 pubblob = key->alg->public_blob(key->data, &publen);
738 privblob = key->alg->private_blob(key->data, &privlen);
739 spareblob = outblob = NULL;
742 * Find the sequence of integers to be encoded into the OpenSSH
743 * key blob, and also decide on the header line.
745 if (key->alg == &ssh_rsa) {
747 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
748 Bignum bd, bp, bq, bdmp1, bdmq1;
751 * These blobs were generated from inside PuTTY, so we needn't
752 * treat them as untrusted.
754 pos = 4 + GET_32BIT(pubblob);
755 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
756 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
758 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
759 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
760 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
761 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
763 assert(e.start && iqmp.start); /* can't go wrong */
765 /* We also need d mod (p-1) and d mod (q-1). */
766 bd = bignum_from_bytes(d.start, d.bytes);
767 bp = bignum_from_bytes(p.start, p.bytes);
768 bq = bignum_from_bytes(q.start, q.bytes);
771 bdmp1 = bigmod(bd, bp);
772 bdmq1 = bigmod(bd, bq);
777 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
778 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
779 sparelen = dmp1.bytes + dmq1.bytes;
780 spareblob = snewn(sparelen, unsigned char);
781 dmp1.start = spareblob;
782 dmq1.start = spareblob + dmp1.bytes;
783 for (i = 0; i < dmp1.bytes; i++)
784 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
785 for (i = 0; i < dmq1.bytes; i++)
786 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
790 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
801 header = "-----BEGIN RSA PRIVATE KEY-----\n";
802 footer = "-----END RSA PRIVATE KEY-----\n";
803 } else if (key->alg == &ssh_dss) {
805 struct mpint_pos p, q, g, y, x;
808 * These blobs were generated from inside PuTTY, so we needn't
809 * treat them as untrusted.
811 pos = 4 + GET_32BIT(pubblob);
812 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
813 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
814 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
815 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
817 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
819 assert(y.start && x.start); /* can't go wrong */
821 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
829 header = "-----BEGIN DSA PRIVATE KEY-----\n";
830 footer = "-----END DSA PRIVATE KEY-----\n";
832 assert(0); /* zoinks! */
833 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
837 * Now count up the total size of the ASN.1 encoded integers,
838 * so as to determine the length of the containing SEQUENCE.
841 for (i = 0; i < nnumbers; i++) {
842 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
843 len += numbers[i].bytes;
846 /* Now add on the SEQUENCE header. */
847 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
848 /* Round up to the cipher block size, ensuring we have at least one
849 * byte of padding (see below). */
852 outlen = (outlen+8) &~ 7;
855 * Now we know how big outblob needs to be. Allocate it.
857 outblob = snewn(outlen, unsigned char);
860 * And write the data into it.
863 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
864 for (i = 0; i < nnumbers; i++) {
865 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
866 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
867 pos += numbers[i].bytes;
871 * Padding on OpenSSH keys is deterministic. The number of
872 * padding bytes is always more than zero, and always at most
873 * the cipher block length. The value of each padding byte is
874 * equal to the number of padding bytes. So a plaintext that's
875 * an exact multiple of the block size will be padded with 08
876 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
877 * plaintext one byte less than a multiple of the block size
878 * will be padded with just 01.
880 * This enables the OpenSSL key decryption function to strip
881 * off the padding algorithmically and return the unpadded
882 * plaintext to the next layer: it looks at the final byte, and
883 * then expects to find that many bytes at the end of the data
884 * with the same value. Those are all removed and the rest is
888 while (pos < outlen) {
889 outblob[pos++] = outlen - len;
895 * For the moment, we still encrypt our OpenSSH keys using
900 * Invent an iv. Then derive encryption key from passphrase
903 * - let block A equal MD5(passphrase || iv)
904 * - let block B equal MD5(A || passphrase || iv)
905 * - block C would be MD5(B || passphrase || iv) and so on
906 * - encryption key is the first N bytes of A || B
908 struct MD5Context md5c;
909 unsigned char keybuf[32];
911 for (i = 0; i < 8; i++) iv[i] = random_byte();
914 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
915 MD5Update(&md5c, iv, 8);
916 MD5Final(keybuf, &md5c);
919 MD5Update(&md5c, keybuf, 16);
920 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
921 MD5Update(&md5c, iv, 8);
922 MD5Final(keybuf+16, &md5c);
925 * Now encrypt the key blob.
927 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
929 smemclr(&md5c, sizeof(md5c));
930 smemclr(keybuf, sizeof(keybuf));
934 * And save it. We'll use Unix line endings just in case it's
935 * subsequently transferred in binary mode.
937 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
942 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
943 for (i = 0; i < 8; i++)
944 fprintf(fp, "%02X", iv[i]);
947 base64_encode(fp, outblob, outlen, 64);
954 smemclr(outblob, outlen);
958 smemclr(spareblob, sparelen);
962 smemclr(privblob, privlen);
966 smemclr(pubblob, publen);
972 /* ----------------------------------------------------------------------
973 * Code to read ssh.com private keys.
977 * The format of the base64 blob is largely SSH-2-packet-formatted,
978 * except that mpints are a bit different: they're more like the
979 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
980 * (N+7)/8 bytes of data.
982 * So. The blob contains:
984 * - uint32 0x3f6ff9eb (magic number)
985 * - uint32 size (total blob size)
986 * - string key-type (see below)
987 * - string cipher-type (tells you if key is encrypted)
988 * - string encrypted-blob
990 * (The first size field includes the size field itself and the
991 * magic number before it. All other size fields are ordinary SSH-2
992 * strings, so the size field indicates how much data is to
995 * The encrypted blob, once decrypted, contains a single string
996 * which in turn contains the payload. (This allows padding to be
997 * added after that string while still making it clear where the
998 * real payload ends. Also it probably makes for a reasonable
1001 * The payload blob, for an RSA key, contains:
1004 * - mpint n (yes, the public and private stuff is intermixed)
1005 * - mpint u (presumably inverse of p mod q)
1006 * - mpint p (p is the smaller prime)
1007 * - mpint q (q is the larger)
1009 * For a DSA key, the payload blob contains:
1017 * Alternatively, if the parameters are `predefined', that
1018 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1019 * containing some predefined parameter specification. *shudder*,
1020 * but I doubt we'll encounter this in real life.
1022 * The key type strings are ghastly. The RSA key I looked at had a
1025 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1027 * and the DSA key wasn't much better:
1029 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1031 * It isn't clear that these will always be the same. I think it
1032 * might be wise just to look at the `if-modn{sign{rsa' and
1033 * `dl-modp{sign{dsa' prefixes.
1035 * Finally, the encryption. The cipher-type string appears to be
1036 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1037 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1038 * from the passphrase by means of yet another hashing faff:
1040 * - first 16 bytes are MD5(passphrase)
1041 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1042 * - if there were more, they'd be MD5(passphrase || first 32),
1046 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1049 char comment[256]; /* allowing any length is overkill */
1050 unsigned char *keyblob;
1051 int keyblob_len, keyblob_size;
1054 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1055 const char **errmsg_p)
1057 struct sshcom_key *ret;
1064 int base64_chars = 0;
1066 ret = snew(struct sshcom_key);
1067 ret->comment[0] = '\0';
1068 ret->keyblob = NULL;
1069 ret->keyblob_len = ret->keyblob_size = 0;
1071 fp = f_open(filename, "r", FALSE);
1073 errmsg = "unable to open key file";
1076 if (!(line = fgetline(fp))) {
1077 errmsg = "unexpected end of file";
1081 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1082 errmsg = "file does not begin with ssh.com key header";
1085 smemclr(line, strlen(line));
1091 if (!(line = fgetline(fp))) {
1092 errmsg = "unexpected end of file";
1096 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1100 if ((p = strchr(line, ':')) != NULL) {
1102 errmsg = "header found in body of key data";
1106 while (*p && isspace((unsigned char)*p)) p++;
1107 hdrstart = p - line;
1110 * Header lines can end in a trailing backslash for
1113 len = hdrstart + strlen(line+hdrstart);
1115 while (line[len-1] == '\\') {
1119 line2 = fgetline(fp);
1121 errmsg = "unexpected end of file";
1126 line2len = strlen(line2);
1127 line = sresize(line, len + line2len + 1, char);
1128 strcpy(line + len - 1, line2);
1129 len += line2len - 1;
1132 smemclr(line2, strlen(line2));
1136 p = line + hdrstart;
1138 if (!strcmp(line, "Comment")) {
1139 /* Strip quotes in comment if present. */
1140 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1142 p[strlen(p)-1] = '\0';
1144 strncpy(ret->comment, p, sizeof(ret->comment));
1145 ret->comment[sizeof(ret->comment)-1] = '\0';
1151 while (isbase64(*p)) {
1152 base64_bit[base64_chars++] = *p;
1153 if (base64_chars == 4) {
1154 unsigned char out[3];
1158 len = base64_decode_atom(base64_bit, out);
1161 errmsg = "invalid base64 encoding";
1165 if (ret->keyblob_len + len > ret->keyblob_size) {
1166 ret->keyblob_size = ret->keyblob_len + len + 256;
1167 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1171 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1172 ret->keyblob_len += len;
1178 smemclr(line, strlen(line));
1183 if (ret->keyblob_len == 0 || !ret->keyblob) {
1184 errmsg = "key body not present";
1189 if (errmsg_p) *errmsg_p = NULL;
1197 smemclr(line, strlen(line));
1203 smemclr(ret->keyblob, ret->keyblob_size);
1204 sfree(ret->keyblob);
1206 smemclr(ret, sizeof(*ret));
1209 if (errmsg_p) *errmsg_p = errmsg;
1213 int sshcom_encrypted(const Filename *filename, char **comment)
1215 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1216 int pos, len, answer;
1225 * Check magic number.
1227 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1228 goto done; /* key is invalid */
1232 * Find the cipher-type string.
1235 if (key->keyblob_len < pos+4)
1236 goto done; /* key is far too short */
1237 len = toint(GET_32BIT(key->keyblob + pos));
1238 if (len < 0 || len > key->keyblob_len - pos - 4)
1239 goto done; /* key is far too short */
1240 pos += 4 + len; /* skip key type */
1241 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1242 if (len < 0 || len > key->keyblob_len - pos - 4)
1243 goto done; /* cipher type string is incomplete */
1244 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1248 *comment = dupstr(key ? key->comment : "");
1249 smemclr(key->keyblob, key->keyblob_size);
1250 sfree(key->keyblob);
1251 smemclr(key, sizeof(*key));
1256 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1258 unsigned bits, bytes;
1259 unsigned char *d = (unsigned char *) data;
1263 bits = GET_32BIT(d);
1265 bytes = (bits + 7) / 8;
1276 return len; /* ensure further calls fail as well */
1279 static int sshcom_put_mpint(void *target, void *data, int len)
1281 unsigned char *d = (unsigned char *)target;
1282 unsigned char *i = (unsigned char *)data;
1283 int bits = len * 8 - 1;
1286 if (*i & (1 << (bits & 7)))
1292 PUT_32BIT(d, bits+1);
1293 memcpy(d+4, i, len);
1297 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1298 const char **errmsg_p)
1300 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1303 const char prefix_rsa[] = "if-modn{sign{rsa";
1304 const char prefix_dsa[] = "dl-modp{sign{dsa";
1305 enum { RSA, DSA } type;
1309 struct ssh2_userkey *ret = NULL, *retkey;
1310 const struct ssh_signkey *alg;
1311 unsigned char *blob = NULL;
1312 int blobsize = 0, publen, privlen;
1318 * Check magic number.
1320 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1321 errmsg = "key does not begin with magic number";
1326 * Determine the key type.
1329 if (key->keyblob_len < pos+4 ||
1330 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1331 len > key->keyblob_len - pos - 4) {
1332 errmsg = "key blob does not contain a key type string";
1335 if (len > sizeof(prefix_rsa) - 1 &&
1336 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1338 } else if (len > sizeof(prefix_dsa) - 1 &&
1339 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1342 errmsg = "key is of unknown type";
1348 * Determine the cipher type.
1350 if (key->keyblob_len < pos+4 ||
1351 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1352 len > key->keyblob_len - pos - 4) {
1353 errmsg = "key blob does not contain a cipher type string";
1356 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1358 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1361 errmsg = "key encryption is of unknown type";
1367 * Get hold of the encrypted part of the key.
1369 if (key->keyblob_len < pos+4 ||
1370 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1371 len > key->keyblob_len - pos - 4) {
1372 errmsg = "key blob does not contain actual key data";
1375 ciphertext = (char *)key->keyblob + pos + 4;
1377 if (cipherlen == 0) {
1378 errmsg = "length of key data is zero";
1383 * Decrypt it if necessary.
1387 * Derive encryption key from passphrase and iv/salt:
1389 * - let block A equal MD5(passphrase)
1390 * - let block B equal MD5(passphrase || A)
1391 * - block C would be MD5(passphrase || A || B) and so on
1392 * - encryption key is the first N bytes of A || B
1394 struct MD5Context md5c;
1395 unsigned char keybuf[32], iv[8];
1397 if (cipherlen % 8 != 0) {
1398 errmsg = "encrypted part of key is not a multiple of cipher block"
1404 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1405 MD5Final(keybuf, &md5c);
1408 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1409 MD5Update(&md5c, keybuf, 16);
1410 MD5Final(keybuf+16, &md5c);
1413 * Now decrypt the key blob.
1415 memset(iv, 0, sizeof(iv));
1416 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1419 smemclr(&md5c, sizeof(md5c));
1420 smemclr(keybuf, sizeof(keybuf));
1423 * Hereafter we return WRONG_PASSPHRASE for any parsing
1424 * error. (But only if we've just tried to decrypt it!
1425 * Returning WRONG_PASSPHRASE for an unencrypted key is
1429 ret = SSH2_WRONG_PASSPHRASE;
1433 * Strip away the containing string to get to the real meat.
1435 len = toint(GET_32BIT(ciphertext));
1436 if (len < 0 || len > cipherlen-4) {
1437 errmsg = "containing string was ill-formed";
1444 * Now we break down into RSA versus DSA. In either case we'll
1445 * construct public and private blobs in our own format, and
1446 * end up feeding them to alg->createkey().
1448 blobsize = cipherlen + 256;
1449 blob = snewn(blobsize, unsigned char);
1452 struct mpint_pos n, e, d, u, p, q;
1454 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1455 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1456 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1457 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1458 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1459 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1461 errmsg = "key data did not contain six integers";
1467 pos += put_string(blob+pos, "ssh-rsa", 7);
1468 pos += put_mp(blob+pos, e.start, e.bytes);
1469 pos += put_mp(blob+pos, n.start, n.bytes);
1471 pos += put_string(blob+pos, d.start, d.bytes);
1472 pos += put_mp(blob+pos, q.start, q.bytes);
1473 pos += put_mp(blob+pos, p.start, p.bytes);
1474 pos += put_mp(blob+pos, u.start, u.bytes);
1475 privlen = pos - publen;
1477 assert(type == DSA); /* the only other option from the if above */
1478 struct mpint_pos p, q, g, x, y;
1480 if (GET_32BIT(ciphertext) != 0) {
1481 errmsg = "predefined DSA parameters not supported";
1484 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1485 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1486 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1487 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1488 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1490 errmsg = "key data did not contain five integers";
1496 pos += put_string(blob+pos, "ssh-dss", 7);
1497 pos += put_mp(blob+pos, p.start, p.bytes);
1498 pos += put_mp(blob+pos, q.start, q.bytes);
1499 pos += put_mp(blob+pos, g.start, g.bytes);
1500 pos += put_mp(blob+pos, y.start, y.bytes);
1502 pos += put_mp(blob+pos, x.start, x.bytes);
1503 privlen = pos - publen;
1506 assert(privlen > 0); /* should have bombed by now if not */
1508 retkey = snew(struct ssh2_userkey);
1510 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1511 if (!retkey->data) {
1513 errmsg = "unable to create key data structure";
1516 retkey->comment = dupstr(key->comment);
1518 errmsg = NULL; /* no error */
1523 smemclr(blob, blobsize);
1526 smemclr(key->keyblob, key->keyblob_size);
1527 sfree(key->keyblob);
1528 smemclr(key, sizeof(*key));
1530 if (errmsg_p) *errmsg_p = errmsg;
1534 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1537 unsigned char *pubblob, *privblob;
1538 int publen, privlen;
1539 unsigned char *outblob;
1541 struct mpint_pos numbers[6];
1542 int nnumbers, initial_zero, pos, lenpos, i;
1550 * Fetch the key blobs.
1552 pubblob = key->alg->public_blob(key->data, &publen);
1553 privblob = key->alg->private_blob(key->data, &privlen);
1557 * Find the sequence of integers to be encoded into the OpenSSH
1558 * key blob, and also decide on the header line.
1560 if (key->alg == &ssh_rsa) {
1562 struct mpint_pos n, e, d, p, q, iqmp;
1565 * These blobs were generated from inside PuTTY, so we needn't
1566 * treat them as untrusted.
1568 pos = 4 + GET_32BIT(pubblob);
1569 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1570 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1572 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1573 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1574 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1575 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1577 assert(e.start && iqmp.start); /* can't go wrong */
1588 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1589 } else if (key->alg == &ssh_dss) {
1591 struct mpint_pos p, q, g, y, x;
1594 * These blobs were generated from inside PuTTY, so we needn't
1595 * treat them as untrusted.
1597 pos = 4 + GET_32BIT(pubblob);
1598 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1599 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1600 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1601 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1603 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1605 assert(y.start && x.start); /* can't go wrong */
1615 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1617 assert(0); /* zoinks! */
1618 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1622 * Total size of key blob will be somewhere under 512 plus
1623 * combined length of integers. We'll calculate the more
1624 * precise size as we construct the blob.
1627 for (i = 0; i < nnumbers; i++)
1628 outlen += 4 + numbers[i].bytes;
1629 outblob = snewn(outlen, unsigned char);
1632 * Create the unencrypted key blob.
1635 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1636 pos += 4; /* length field, fill in later */
1637 pos += put_string(outblob+pos, type, strlen(type));
1639 char *ciphertype = passphrase ? "3des-cbc" : "none";
1640 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1642 lenpos = pos; /* remember this position */
1643 pos += 4; /* encrypted-blob size */
1644 pos += 4; /* encrypted-payload size */
1646 PUT_32BIT(outblob+pos, 0);
1649 for (i = 0; i < nnumbers; i++)
1650 pos += sshcom_put_mpint(outblob+pos,
1651 numbers[i].start, numbers[i].bytes);
1652 /* Now wrap up the encrypted payload. */
1653 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1654 /* Pad encrypted blob to a multiple of cipher block size. */
1656 int padding = -(pos - (lenpos+4)) & 7;
1658 outblob[pos++] = random_byte();
1660 ciphertext = (char *)outblob+lenpos+4;
1661 cipherlen = pos - (lenpos+4);
1662 assert(!passphrase || cipherlen % 8 == 0);
1663 /* Wrap up the encrypted blob string. */
1664 PUT_32BIT(outblob+lenpos, cipherlen);
1665 /* And finally fill in the total length field. */
1666 PUT_32BIT(outblob+4, pos);
1668 assert(pos < outlen);
1675 * Derive encryption key from passphrase and iv/salt:
1677 * - let block A equal MD5(passphrase)
1678 * - let block B equal MD5(passphrase || A)
1679 * - block C would be MD5(passphrase || A || B) and so on
1680 * - encryption key is the first N bytes of A || B
1682 struct MD5Context md5c;
1683 unsigned char keybuf[32], iv[8];
1686 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1687 MD5Final(keybuf, &md5c);
1690 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1691 MD5Update(&md5c, keybuf, 16);
1692 MD5Final(keybuf+16, &md5c);
1695 * Now decrypt the key blob.
1697 memset(iv, 0, sizeof(iv));
1698 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1701 smemclr(&md5c, sizeof(md5c));
1702 smemclr(keybuf, sizeof(keybuf));
1706 * And save it. We'll use Unix line endings just in case it's
1707 * subsequently transferred in binary mode.
1709 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1712 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1713 fprintf(fp, "Comment: \"");
1715 * Comment header is broken with backslash-newline if it goes
1716 * over 70 chars. Although it's surrounded by quotes, it
1717 * _doesn't_ escape backslashes or quotes within the string.
1718 * Don't ask me, I didn't design it.
1721 int slen = 60; /* starts at 60 due to "Comment: " */
1722 char *c = key->comment;
1723 while ((int)strlen(c) > slen) {
1724 fprintf(fp, "%.*s\\\n", slen, c);
1726 slen = 70; /* allow 70 chars on subsequent lines */
1728 fprintf(fp, "%s\"\n", c);
1730 base64_encode(fp, outblob, pos, 70);
1731 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1737 smemclr(outblob, outlen);
1741 smemclr(privblob, privlen);
1745 smemclr(pubblob, publen);