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 = 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 };
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 memset(line, 0, 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-----"))
375 if ((p = strchr(line, ':')) != NULL) {
377 errmsg = "header found in body of key data";
381 while (*p && isspace((unsigned char)*p)) p++;
382 if (!strcmp(line, "Proc-Type")) {
383 if (p[0] != '4' || p[1] != ',') {
384 errmsg = "Proc-Type is not 4 (only 4 is supported)";
388 if (!strcmp(p, "ENCRYPTED"))
390 } else if (!strcmp(line, "DEK-Info")) {
393 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
394 ret->encryption = OSSH_ENC_3DES;
396 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
397 ret->encryption = OSSH_ENC_AES;
400 errmsg = "unsupported cipher";
403 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
404 for (i = 0; i < ivlen; i++) {
405 if (1 != sscanf(p, "%2x", &j)) {
406 errmsg = "expected more iv data in DEK-Info";
413 errmsg = "more iv data than expected in DEK-Info";
421 while (isbase64(*p)) {
422 base64_bit[base64_chars++] = *p;
423 if (base64_chars == 4) {
424 unsigned char out[3];
429 len = base64_decode_atom(base64_bit, out);
432 errmsg = "invalid base64 encoding";
436 if (ret->keyblob_len + len > ret->keyblob_size) {
437 ret->keyblob_size = ret->keyblob_len + len + 256;
438 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
442 memcpy(ret->keyblob + ret->keyblob_len, out, len);
443 ret->keyblob_len += len;
445 memset(out, 0, sizeof(out));
451 memset(line, 0, strlen(line));
456 if (ret->keyblob_len == 0 || !ret->keyblob) {
457 errmsg = "key body not present";
461 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
462 errmsg = "encrypted key blob is not a multiple of cipher block size";
466 memset(base64_bit, 0, sizeof(base64_bit));
467 if (errmsg_p) *errmsg_p = NULL;
472 memset(line, 0, strlen(line));
476 memset(base64_bit, 0, sizeof(base64_bit));
479 memset(ret->keyblob, 0, ret->keyblob_size);
482 memset(ret, 0, sizeof(*ret));
485 if (errmsg_p) *errmsg_p = errmsg;
489 int openssh_encrypted(const Filename *filename)
491 struct openssh_key *key = load_openssh_key(filename, NULL);
496 ret = key->encrypted;
497 memset(key->keyblob, 0, key->keyblob_size);
499 memset(key, 0, sizeof(*key));
504 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
505 const char **errmsg_p)
507 struct openssh_key *key = load_openssh_key(filename, errmsg_p);
508 struct ssh2_userkey *retkey;
510 int ret, id, len, flags;
512 struct ssh2_userkey *retval = NULL;
515 int blobsize = 0, blobptr, privptr;
524 if (key->encrypted) {
526 * Derive encryption key from passphrase and iv/salt:
528 * - let block A equal MD5(passphrase || iv)
529 * - let block B equal MD5(A || passphrase || iv)
530 * - block C would be MD5(B || passphrase || iv) and so on
531 * - encryption key is the first N bytes of A || B
533 struct MD5Context md5c;
534 unsigned char keybuf[32];
537 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
538 MD5Update(&md5c, (unsigned char *)key->iv, 8);
539 MD5Final(keybuf, &md5c);
542 MD5Update(&md5c, keybuf, 16);
543 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
544 MD5Update(&md5c, (unsigned char *)key->iv, 8);
545 MD5Final(keybuf+16, &md5c);
548 * Now decrypt the key blob.
550 if (key->encryption == OSSH_ENC_3DES)
551 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
552 key->keyblob, key->keyblob_len);
555 assert(key->encryption == OSSH_ENC_AES);
556 ctx = aes_make_context();
557 aes128_key(ctx, keybuf);
558 aes_iv(ctx, (unsigned char *)key->iv);
559 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
560 aes_free_context(ctx);
563 memset(&md5c, 0, sizeof(md5c));
564 memset(keybuf, 0, sizeof(keybuf));
568 * Now we have a decrypted key blob, which contains an ASN.1
569 * encoded private key. We must now untangle the ASN.1.
571 * We expect the whole key blob to be formatted as a SEQUENCE
572 * (0x30 followed by a length code indicating that the rest of
573 * the blob is part of the sequence). Within that SEQUENCE we
574 * expect to see a bunch of INTEGERs. What those integers mean
575 * depends on the key type:
577 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
578 * dmp1, dmq1, iqmp in that order. (The last three are d mod
579 * (p-1), d mod (q-1), inverse of q mod p respectively.)
581 * - For DSA, we expect them to be 0, p, q, g, y, x in that
587 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
588 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
590 if (ret < 0 || id != 16) {
591 errmsg = "ASN.1 decoding failure";
592 retval = SSH2_WRONG_PASSPHRASE;
596 /* Expect a load of INTEGERs. */
597 if (key->type == OSSH_RSA)
599 else if (key->type == OSSH_DSA)
602 num_integers = 0; /* placate compiler warnings */
605 * Space to create key blob in.
607 blobsize = 256+key->keyblob_len;
608 blob = snewn(blobsize, unsigned char);
610 if (key->type == OSSH_DSA)
611 memcpy(blob+4, "ssh-dss", 7);
612 else if (key->type == OSSH_RSA)
613 memcpy(blob+4, "ssh-rsa", 7);
617 for (i = 0; i < num_integers; i++) {
618 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
621 if (ret < 0 || id != 2 ||
622 key->keyblob+key->keyblob_len-p < len) {
623 errmsg = "ASN.1 decoding failure";
624 retval = SSH2_WRONG_PASSPHRASE;
630 * The first integer should be zero always (I think
631 * this is some sort of version indication).
633 if (len != 1 || p[0] != 0) {
634 errmsg = "version number mismatch";
637 } else if (key->type == OSSH_RSA) {
639 * Integers 1 and 2 go into the public blob but in the
640 * opposite order; integers 3, 4, 5 and 8 go into the
641 * private blob. The other two (6 and 7) are ignored.
644 /* Save the details for after we deal with number 2. */
647 } else if (i != 6 && i != 7) {
648 PUT_32BIT(blob+blobptr, len);
649 memcpy(blob+blobptr+4, p, len);
652 PUT_32BIT(blob+blobptr, modlen);
653 memcpy(blob+blobptr+4, modptr, modlen);
658 } else if (key->type == OSSH_DSA) {
660 * Integers 1-4 go into the public blob; integer 5 goes
661 * into the private blob.
663 PUT_32BIT(blob+blobptr, len);
664 memcpy(blob+blobptr+4, p, len);
670 /* Skip past the number. */
675 * Now put together the actual key. Simplest way to do this is
676 * to assemble our own key blobs and feed them to the createkey
677 * functions; this is a bit faffy but it does mean we get all
678 * the sanity checks for free.
680 assert(privptr > 0); /* should have bombed by now if not */
681 retkey = snew(struct ssh2_userkey);
682 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
683 retkey->data = retkey->alg->createkey(blob, privptr,
684 blob+privptr, blobptr-privptr);
687 errmsg = "unable to create key data structure";
691 retkey->comment = dupstr("imported-openssh-key");
692 errmsg = NULL; /* no error */
697 memset(blob, 0, blobsize);
700 memset(key->keyblob, 0, key->keyblob_size);
702 memset(key, 0, sizeof(*key));
704 if (errmsg_p) *errmsg_p = errmsg;
708 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
711 unsigned char *pubblob, *privblob, *spareblob;
712 int publen, privlen, sparelen = 0;
713 unsigned char *outblob;
715 struct mpint_pos numbers[9];
716 int nnumbers, pos, len, seqlen, i;
717 char *header, *footer;
724 * Fetch the key blobs.
726 pubblob = key->alg->public_blob(key->data, &publen);
727 privblob = key->alg->private_blob(key->data, &privlen);
728 spareblob = outblob = NULL;
731 * Find the sequence of integers to be encoded into the OpenSSH
732 * key blob, and also decide on the header line.
734 if (key->alg == &ssh_rsa) {
736 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
737 Bignum bd, bp, bq, bdmp1, bdmq1;
739 pos = 4 + GET_32BIT(pubblob);
740 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
741 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
743 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
744 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
745 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
746 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
748 assert(e.start && iqmp.start); /* can't go wrong */
750 /* We also need d mod (p-1) and d mod (q-1). */
751 bd = bignum_from_bytes(d.start, d.bytes);
752 bp = bignum_from_bytes(p.start, p.bytes);
753 bq = bignum_from_bytes(q.start, q.bytes);
756 bdmp1 = bigmod(bd, bp);
757 bdmq1 = bigmod(bd, bq);
762 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
763 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
764 sparelen = dmp1.bytes + dmq1.bytes;
765 spareblob = snewn(sparelen, unsigned char);
766 dmp1.start = spareblob;
767 dmq1.start = spareblob + dmp1.bytes;
768 for (i = 0; i < dmp1.bytes; i++)
769 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
770 for (i = 0; i < dmq1.bytes; i++)
771 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
775 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
786 header = "-----BEGIN RSA PRIVATE KEY-----\n";
787 footer = "-----END RSA PRIVATE KEY-----\n";
788 } else if (key->alg == &ssh_dss) {
790 struct mpint_pos p, q, g, y, x;
792 pos = 4 + GET_32BIT(pubblob);
793 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
794 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
795 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
796 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
798 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
800 assert(y.start && x.start); /* can't go wrong */
802 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
810 header = "-----BEGIN DSA PRIVATE KEY-----\n";
811 footer = "-----END DSA PRIVATE KEY-----\n";
813 assert(0); /* zoinks! */
814 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
818 * Now count up the total size of the ASN.1 encoded integers,
819 * so as to determine the length of the containing SEQUENCE.
822 for (i = 0; i < nnumbers; i++) {
823 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
824 len += numbers[i].bytes;
827 /* Now add on the SEQUENCE header. */
828 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
829 /* Round up to the cipher block size, ensuring we have at least one
830 * byte of padding (see below). */
833 outlen = (outlen+8) &~ 7;
836 * Now we know how big outblob needs to be. Allocate it.
838 outblob = snewn(outlen, unsigned char);
841 * And write the data into it.
844 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
845 for (i = 0; i < nnumbers; i++) {
846 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
847 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
848 pos += numbers[i].bytes;
852 * Padding on OpenSSH keys is deterministic. The number of
853 * padding bytes is always more than zero, and always at most
854 * the cipher block length. The value of each padding byte is
855 * equal to the number of padding bytes. So a plaintext that's
856 * an exact multiple of the block size will be padded with 08
857 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
858 * plaintext one byte less than a multiple of the block size
859 * will be padded with just 01.
861 * This enables the OpenSSL key decryption function to strip
862 * off the padding algorithmically and return the unpadded
863 * plaintext to the next layer: it looks at the final byte, and
864 * then expects to find that many bytes at the end of the data
865 * with the same value. Those are all removed and the rest is
869 while (pos < outlen) {
870 outblob[pos++] = outlen - len;
878 * Invent an iv. Then derive encryption key from passphrase
881 * - let block A equal MD5(passphrase || iv)
882 * - let block B equal MD5(A || passphrase || iv)
883 * - block C would be MD5(B || passphrase || iv) and so on
884 * - encryption key is the first N bytes of A || B
886 struct MD5Context md5c;
887 unsigned char keybuf[32];
889 for (i = 0; i < 8; i++) iv[i] = random_byte();
892 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
893 MD5Update(&md5c, iv, 8);
894 MD5Final(keybuf, &md5c);
897 MD5Update(&md5c, keybuf, 16);
898 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
899 MD5Update(&md5c, iv, 8);
900 MD5Final(keybuf+16, &md5c);
903 * Now encrypt the key blob.
905 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
907 memset(&md5c, 0, sizeof(md5c));
908 memset(keybuf, 0, sizeof(keybuf));
912 * And save it. We'll use Unix line endings just in case it's
913 * subsequently transferred in binary mode.
915 fp = f_open(*filename, "wb", TRUE); /* ensure Unix line endings */
920 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
921 for (i = 0; i < 8; i++)
922 fprintf(fp, "%02X", iv[i]);
925 base64_encode(fp, outblob, outlen, 64);
932 memset(outblob, 0, outlen);
936 memset(spareblob, 0, sparelen);
940 memset(privblob, 0, privlen);
944 memset(pubblob, 0, publen);
950 /* ----------------------------------------------------------------------
951 * Code to read ssh.com private keys.
955 * The format of the base64 blob is largely SSH-2-packet-formatted,
956 * except that mpints are a bit different: they're more like the
957 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
958 * (N+7)/8 bytes of data.
960 * So. The blob contains:
962 * - uint32 0x3f6ff9eb (magic number)
963 * - uint32 size (total blob size)
964 * - string key-type (see below)
965 * - string cipher-type (tells you if key is encrypted)
966 * - string encrypted-blob
968 * (The first size field includes the size field itself and the
969 * magic number before it. All other size fields are ordinary SSH-2
970 * strings, so the size field indicates how much data is to
973 * The encrypted blob, once decrypted, contains a single string
974 * which in turn contains the payload. (This allows padding to be
975 * added after that string while still making it clear where the
976 * real payload ends. Also it probably makes for a reasonable
979 * The payload blob, for an RSA key, contains:
982 * - mpint n (yes, the public and private stuff is intermixed)
983 * - mpint u (presumably inverse of p mod q)
984 * - mpint p (p is the smaller prime)
985 * - mpint q (q is the larger)
987 * For a DSA key, the payload blob contains:
995 * Alternatively, if the parameters are `predefined', that
996 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
997 * containing some predefined parameter specification. *shudder*,
998 * but I doubt we'll encounter this in real life.
1000 * The key type strings are ghastly. The RSA key I looked at had a
1003 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1005 * and the DSA key wasn't much better:
1007 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1009 * It isn't clear that these will always be the same. I think it
1010 * might be wise just to look at the `if-modn{sign{rsa' and
1011 * `dl-modp{sign{dsa' prefixes.
1013 * Finally, the encryption. The cipher-type string appears to be
1014 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1015 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1016 * from the passphrase by means of yet another hashing faff:
1018 * - first 16 bytes are MD5(passphrase)
1019 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1020 * - if there were more, they'd be MD5(passphrase || first 32),
1024 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1027 char comment[256]; /* allowing any length is overkill */
1028 unsigned char *keyblob;
1029 int keyblob_len, keyblob_size;
1032 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1033 const char **errmsg_p)
1035 struct sshcom_key *ret;
1042 int base64_chars = 0;
1044 ret = snew(struct sshcom_key);
1045 ret->comment[0] = '\0';
1046 ret->keyblob = NULL;
1047 ret->keyblob_len = ret->keyblob_size = 0;
1049 fp = f_open(*filename, "r", FALSE);
1051 errmsg = "unable to open key file";
1054 if (!(line = fgetline(fp))) {
1055 errmsg = "unexpected end of file";
1059 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1060 errmsg = "file does not begin with ssh.com key header";
1063 memset(line, 0, strlen(line));
1069 if (!(line = fgetline(fp))) {
1070 errmsg = "unexpected end of file";
1074 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----"))
1076 if ((p = strchr(line, ':')) != NULL) {
1078 errmsg = "header found in body of key data";
1082 while (*p && isspace((unsigned char)*p)) p++;
1083 hdrstart = p - line;
1086 * Header lines can end in a trailing backslash for
1089 len = hdrstart + strlen(line+hdrstart);
1091 while (line[len-1] == '\\') {
1095 line2 = fgetline(fp);
1097 errmsg = "unexpected end of file";
1102 line2len = strlen(line2);
1103 line = sresize(line, len + line2len + 1, char);
1104 strcpy(line + len - 1, line2);
1105 len += line2len - 1;
1108 memset(line2, 0, strlen(line2));
1112 p = line + hdrstart;
1114 if (!strcmp(line, "Comment")) {
1115 /* Strip quotes in comment if present. */
1116 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1118 p[strlen(p)-1] = '\0';
1120 strncpy(ret->comment, p, sizeof(ret->comment));
1121 ret->comment[sizeof(ret->comment)-1] = '\0';
1127 while (isbase64(*p)) {
1128 base64_bit[base64_chars++] = *p;
1129 if (base64_chars == 4) {
1130 unsigned char out[3];
1134 len = base64_decode_atom(base64_bit, out);
1137 errmsg = "invalid base64 encoding";
1141 if (ret->keyblob_len + len > ret->keyblob_size) {
1142 ret->keyblob_size = ret->keyblob_len + len + 256;
1143 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1147 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1148 ret->keyblob_len += len;
1154 memset(line, 0, strlen(line));
1159 if (ret->keyblob_len == 0 || !ret->keyblob) {
1160 errmsg = "key body not present";
1164 if (errmsg_p) *errmsg_p = NULL;
1169 memset(line, 0, strlen(line));
1175 memset(ret->keyblob, 0, ret->keyblob_size);
1176 sfree(ret->keyblob);
1178 memset(ret, 0, sizeof(*ret));
1181 if (errmsg_p) *errmsg_p = errmsg;
1185 int sshcom_encrypted(const Filename *filename, char **comment)
1187 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1188 int pos, len, answer;
1195 * Check magic number.
1197 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
1198 return 0; /* key is invalid */
1201 * Find the cipher-type string.
1205 if (key->keyblob_len < pos+4)
1206 goto done; /* key is far too short */
1207 pos += 4 + GET_32BIT(key->keyblob + pos); /* skip key type */
1208 if (key->keyblob_len < pos+4)
1209 goto done; /* key is far too short */
1210 len = GET_32BIT(key->keyblob + pos); /* find cipher-type length */
1211 if (key->keyblob_len < pos+4+len)
1212 goto done; /* cipher type string is incomplete */
1213 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1217 *comment = dupstr(key->comment);
1218 memset(key->keyblob, 0, key->keyblob_size);
1219 sfree(key->keyblob);
1220 memset(key, 0, sizeof(*key));
1225 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1229 unsigned char *d = (unsigned char *) data;
1233 bits = GET_32BIT(d);
1235 bytes = (bits + 7) / 8;
1246 return len; /* ensure further calls fail as well */
1249 static int sshcom_put_mpint(void *target, void *data, int len)
1251 unsigned char *d = (unsigned char *)target;
1252 unsigned char *i = (unsigned char *)data;
1253 int bits = len * 8 - 1;
1256 if (*i & (1 << (bits & 7)))
1262 PUT_32BIT(d, bits+1);
1263 memcpy(d+4, i, len);
1267 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1268 const char **errmsg_p)
1270 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1273 const char prefix_rsa[] = "if-modn{sign{rsa";
1274 const char prefix_dsa[] = "dl-modp{sign{dsa";
1275 enum { RSA, DSA } type;
1279 struct ssh2_userkey *ret = NULL, *retkey;
1280 const struct ssh_signkey *alg;
1281 unsigned char *blob = NULL;
1282 int blobsize = 0, publen, privlen;
1288 * Check magic number.
1290 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1291 errmsg = "key does not begin with magic number";
1296 * Determine the key type.
1299 if (key->keyblob_len < pos+4 ||
1300 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1301 errmsg = "key blob does not contain a key type string";
1304 if (len > sizeof(prefix_rsa) - 1 &&
1305 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1307 } else if (len > sizeof(prefix_dsa) - 1 &&
1308 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1311 errmsg = "key is of unknown type";
1317 * Determine the cipher type.
1319 if (key->keyblob_len < pos+4 ||
1320 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1321 errmsg = "key blob does not contain a cipher type string";
1324 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1326 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1329 errmsg = "key encryption is of unknown type";
1335 * Get hold of the encrypted part of the key.
1337 if (key->keyblob_len < pos+4 ||
1338 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1339 errmsg = "key blob does not contain actual key data";
1342 ciphertext = (char *)key->keyblob + pos + 4;
1344 if (cipherlen == 0) {
1345 errmsg = "length of key data is zero";
1350 * Decrypt it if necessary.
1354 * Derive encryption key from passphrase and iv/salt:
1356 * - let block A equal MD5(passphrase)
1357 * - let block B equal MD5(passphrase || A)
1358 * - block C would be MD5(passphrase || A || B) and so on
1359 * - encryption key is the first N bytes of A || B
1361 struct MD5Context md5c;
1362 unsigned char keybuf[32], iv[8];
1364 if (cipherlen % 8 != 0) {
1365 errmsg = "encrypted part of key is not a multiple of cipher block"
1371 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1372 MD5Final(keybuf, &md5c);
1375 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1376 MD5Update(&md5c, keybuf, 16);
1377 MD5Final(keybuf+16, &md5c);
1380 * Now decrypt the key blob.
1382 memset(iv, 0, sizeof(iv));
1383 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1386 memset(&md5c, 0, sizeof(md5c));
1387 memset(keybuf, 0, sizeof(keybuf));
1390 * Hereafter we return WRONG_PASSPHRASE for any parsing
1391 * error. (But only if we've just tried to decrypt it!
1392 * Returning WRONG_PASSPHRASE for an unencrypted key is
1396 ret = SSH2_WRONG_PASSPHRASE;
1400 * Strip away the containing string to get to the real meat.
1402 len = GET_32BIT(ciphertext);
1403 if (len < 0 || len > cipherlen-4) {
1404 errmsg = "containing string was ill-formed";
1411 * Now we break down into RSA versus DSA. In either case we'll
1412 * construct public and private blobs in our own format, and
1413 * end up feeding them to alg->createkey().
1415 blobsize = cipherlen + 256;
1416 blob = snewn(blobsize, unsigned char);
1419 struct mpint_pos n, e, d, u, p, q;
1421 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1422 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1423 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1424 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1425 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1426 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1428 errmsg = "key data did not contain six integers";
1434 pos += put_string(blob+pos, "ssh-rsa", 7);
1435 pos += put_mp(blob+pos, e.start, e.bytes);
1436 pos += put_mp(blob+pos, n.start, n.bytes);
1438 pos += put_string(blob+pos, d.start, d.bytes);
1439 pos += put_mp(blob+pos, q.start, q.bytes);
1440 pos += put_mp(blob+pos, p.start, p.bytes);
1441 pos += put_mp(blob+pos, u.start, u.bytes);
1442 privlen = pos - publen;
1443 } else if (type == DSA) {
1444 struct mpint_pos p, q, g, x, y;
1446 if (GET_32BIT(ciphertext) != 0) {
1447 errmsg = "predefined DSA parameters not supported";
1450 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1451 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1452 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1453 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1454 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1456 errmsg = "key data did not contain five integers";
1462 pos += put_string(blob+pos, "ssh-dss", 7);
1463 pos += put_mp(blob+pos, p.start, p.bytes);
1464 pos += put_mp(blob+pos, q.start, q.bytes);
1465 pos += put_mp(blob+pos, g.start, g.bytes);
1466 pos += put_mp(blob+pos, y.start, y.bytes);
1468 pos += put_mp(blob+pos, x.start, x.bytes);
1469 privlen = pos - publen;
1473 assert(privlen > 0); /* should have bombed by now if not */
1475 retkey = snew(struct ssh2_userkey);
1477 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1478 if (!retkey->data) {
1480 errmsg = "unable to create key data structure";
1483 retkey->comment = dupstr(key->comment);
1485 errmsg = NULL; /* no error */
1490 memset(blob, 0, blobsize);
1493 memset(key->keyblob, 0, key->keyblob_size);
1494 sfree(key->keyblob);
1495 memset(key, 0, sizeof(*key));
1497 if (errmsg_p) *errmsg_p = errmsg;
1501 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1504 unsigned char *pubblob, *privblob;
1505 int publen, privlen;
1506 unsigned char *outblob;
1508 struct mpint_pos numbers[6];
1509 int nnumbers, initial_zero, pos, lenpos, i;
1517 * Fetch the key blobs.
1519 pubblob = key->alg->public_blob(key->data, &publen);
1520 privblob = key->alg->private_blob(key->data, &privlen);
1524 * Find the sequence of integers to be encoded into the OpenSSH
1525 * key blob, and also decide on the header line.
1527 if (key->alg == &ssh_rsa) {
1529 struct mpint_pos n, e, d, p, q, iqmp;
1531 pos = 4 + GET_32BIT(pubblob);
1532 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1533 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1535 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1536 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1537 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1538 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1540 assert(e.start && iqmp.start); /* can't go wrong */
1551 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1552 } else if (key->alg == &ssh_dss) {
1554 struct mpint_pos p, q, g, y, x;
1556 pos = 4 + GET_32BIT(pubblob);
1557 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1558 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1559 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1560 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1562 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1564 assert(y.start && x.start); /* can't go wrong */
1574 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1576 assert(0); /* zoinks! */
1577 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1581 * Total size of key blob will be somewhere under 512 plus
1582 * combined length of integers. We'll calculate the more
1583 * precise size as we construct the blob.
1586 for (i = 0; i < nnumbers; i++)
1587 outlen += 4 + numbers[i].bytes;
1588 outblob = snewn(outlen, unsigned char);
1591 * Create the unencrypted key blob.
1594 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1595 pos += 4; /* length field, fill in later */
1596 pos += put_string(outblob+pos, type, strlen(type));
1598 char *ciphertype = passphrase ? "3des-cbc" : "none";
1599 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1601 lenpos = pos; /* remember this position */
1602 pos += 4; /* encrypted-blob size */
1603 pos += 4; /* encrypted-payload size */
1605 PUT_32BIT(outblob+pos, 0);
1608 for (i = 0; i < nnumbers; i++)
1609 pos += sshcom_put_mpint(outblob+pos,
1610 numbers[i].start, numbers[i].bytes);
1611 /* Now wrap up the encrypted payload. */
1612 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1613 /* Pad encrypted blob to a multiple of cipher block size. */
1615 int padding = -(pos - (lenpos+4)) & 7;
1617 outblob[pos++] = random_byte();
1619 ciphertext = (char *)outblob+lenpos+4;
1620 cipherlen = pos - (lenpos+4);
1621 assert(!passphrase || cipherlen % 8 == 0);
1622 /* Wrap up the encrypted blob string. */
1623 PUT_32BIT(outblob+lenpos, cipherlen);
1624 /* And finally fill in the total length field. */
1625 PUT_32BIT(outblob+4, pos);
1627 assert(pos < outlen);
1634 * Derive encryption key from passphrase and iv/salt:
1636 * - let block A equal MD5(passphrase)
1637 * - let block B equal MD5(passphrase || A)
1638 * - block C would be MD5(passphrase || A || B) and so on
1639 * - encryption key is the first N bytes of A || B
1641 struct MD5Context md5c;
1642 unsigned char keybuf[32], iv[8];
1645 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1646 MD5Final(keybuf, &md5c);
1649 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1650 MD5Update(&md5c, keybuf, 16);
1651 MD5Final(keybuf+16, &md5c);
1654 * Now decrypt the key blob.
1656 memset(iv, 0, sizeof(iv));
1657 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1660 memset(&md5c, 0, sizeof(md5c));
1661 memset(keybuf, 0, sizeof(keybuf));
1665 * And save it. We'll use Unix line endings just in case it's
1666 * subsequently transferred in binary mode.
1668 fp = f_open(*filename, "wb", TRUE); /* ensure Unix line endings */
1671 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1672 fprintf(fp, "Comment: \"");
1674 * Comment header is broken with backslash-newline if it goes
1675 * over 70 chars. Although it's surrounded by quotes, it
1676 * _doesn't_ escape backslashes or quotes within the string.
1677 * Don't ask me, I didn't design it.
1680 int slen = 60; /* starts at 60 due to "Comment: " */
1681 char *c = key->comment;
1682 while ((int)strlen(c) > slen) {
1683 fprintf(fp, "%.*s\\\n", slen, c);
1685 slen = 70; /* allow 70 chars on subsequent lines */
1687 fprintf(fp, "%s\"\n", c);
1689 base64_encode(fp, outblob, pos, 70);
1690 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1696 memset(outblob, 0, outlen);
1700 memset(privblob, 0, privlen);
1704 memset(pubblob, 0, publen);