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-----"))
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 smemclr(out, sizeof(out));
451 smemclr(line, strlen(line));
459 if (ret->keyblob_len == 0 || !ret->keyblob) {
460 errmsg = "key body not present";
464 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
465 errmsg = "encrypted key blob is not a multiple of cipher block size";
469 smemclr(base64_bit, sizeof(base64_bit));
470 if (errmsg_p) *errmsg_p = NULL;
475 smemclr(line, strlen(line));
479 smemclr(base64_bit, sizeof(base64_bit));
482 smemclr(ret->keyblob, ret->keyblob_size);
485 smemclr(ret, sizeof(*ret));
488 if (errmsg_p) *errmsg_p = errmsg;
493 int openssh_encrypted(const Filename *filename)
495 struct openssh_key *key = load_openssh_key(filename, NULL);
500 ret = key->encrypted;
501 smemclr(key->keyblob, key->keyblob_size);
503 smemclr(key, sizeof(*key));
508 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
509 const char **errmsg_p)
511 struct openssh_key *key = load_openssh_key(filename, errmsg_p);
512 struct ssh2_userkey *retkey;
514 int ret, id, len, flags;
516 struct ssh2_userkey *retval = NULL;
519 int blobsize = 0, blobptr, privptr;
528 if (key->encrypted) {
530 * Derive encryption key from passphrase and iv/salt:
532 * - let block A equal MD5(passphrase || iv)
533 * - let block B equal MD5(A || passphrase || iv)
534 * - block C would be MD5(B || passphrase || iv) and so on
535 * - encryption key is the first N bytes of A || B
537 * (Note that only 8 bytes of the iv are used for key
538 * derivation, even when the key is encrypted with AES and
539 * hence there are 16 bytes available.)
541 struct MD5Context md5c;
542 unsigned char keybuf[32];
545 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
546 MD5Update(&md5c, (unsigned char *)key->iv, 8);
547 MD5Final(keybuf, &md5c);
550 MD5Update(&md5c, keybuf, 16);
551 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
552 MD5Update(&md5c, (unsigned char *)key->iv, 8);
553 MD5Final(keybuf+16, &md5c);
556 * Now decrypt the key blob.
558 if (key->encryption == OSSH_ENC_3DES)
559 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
560 key->keyblob, key->keyblob_len);
563 assert(key->encryption == OSSH_ENC_AES);
564 ctx = aes_make_context();
565 aes128_key(ctx, keybuf);
566 aes_iv(ctx, (unsigned char *)key->iv);
567 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
568 aes_free_context(ctx);
571 smemclr(&md5c, sizeof(md5c));
572 smemclr(keybuf, sizeof(keybuf));
576 * Now we have a decrypted key blob, which contains an ASN.1
577 * encoded private key. We must now untangle the ASN.1.
579 * We expect the whole key blob to be formatted as a SEQUENCE
580 * (0x30 followed by a length code indicating that the rest of
581 * the blob is part of the sequence). Within that SEQUENCE we
582 * expect to see a bunch of INTEGERs. What those integers mean
583 * depends on the key type:
585 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
586 * dmp1, dmq1, iqmp in that order. (The last three are d mod
587 * (p-1), d mod (q-1), inverse of q mod p respectively.)
589 * - For DSA, we expect them to be 0, p, q, g, y, x in that
595 /* Expect the SEQUENCE header. Take its absence as a failure to
596 * decrypt, if the key was encrypted. */
597 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
599 if (ret < 0 || id != 16) {
600 errmsg = "ASN.1 decoding failure";
601 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
605 /* Expect a load of INTEGERs. */
606 if (key->type == OSSH_RSA)
608 else if (key->type == OSSH_DSA)
611 num_integers = 0; /* placate compiler warnings */
614 * Space to create key blob in.
616 blobsize = 256+key->keyblob_len;
617 blob = snewn(blobsize, unsigned char);
619 if (key->type == OSSH_DSA)
620 memcpy(blob+4, "ssh-dss", 7);
621 else if (key->type == OSSH_RSA)
622 memcpy(blob+4, "ssh-rsa", 7);
626 for (i = 0; i < num_integers; i++) {
627 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
630 if (ret < 0 || id != 2 ||
631 key->keyblob+key->keyblob_len-p < len) {
632 errmsg = "ASN.1 decoding failure";
633 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
639 * The first integer should be zero always (I think
640 * this is some sort of version indication).
642 if (len != 1 || p[0] != 0) {
643 errmsg = "version number mismatch";
646 } else if (key->type == OSSH_RSA) {
648 * Integers 1 and 2 go into the public blob but in the
649 * opposite order; integers 3, 4, 5 and 8 go into the
650 * private blob. The other two (6 and 7) are ignored.
653 /* Save the details for after we deal with number 2. */
656 } else if (i != 6 && i != 7) {
657 PUT_32BIT(blob+blobptr, len);
658 memcpy(blob+blobptr+4, p, len);
661 PUT_32BIT(blob+blobptr, modlen);
662 memcpy(blob+blobptr+4, modptr, modlen);
667 } else if (key->type == OSSH_DSA) {
669 * Integers 1-4 go into the public blob; integer 5 goes
670 * into the private blob.
672 PUT_32BIT(blob+blobptr, len);
673 memcpy(blob+blobptr+4, p, len);
679 /* Skip past the number. */
684 * Now put together the actual key. Simplest way to do this is
685 * to assemble our own key blobs and feed them to the createkey
686 * functions; this is a bit faffy but it does mean we get all
687 * the sanity checks for free.
689 assert(privptr > 0); /* should have bombed by now if not */
690 retkey = snew(struct ssh2_userkey);
691 retkey->alg = (key->type == OSSH_RSA ? &ssh_rsa : &ssh_dss);
692 retkey->data = retkey->alg->createkey(blob, privptr,
693 blob+privptr, blobptr-privptr);
696 errmsg = "unable to create key data structure";
700 retkey->comment = dupstr("imported-openssh-key");
701 errmsg = NULL; /* no error */
706 smemclr(blob, blobsize);
709 smemclr(key->keyblob, key->keyblob_size);
711 smemclr(key, sizeof(*key));
713 if (errmsg_p) *errmsg_p = errmsg;
717 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
720 unsigned char *pubblob, *privblob, *spareblob;
721 int publen, privlen, sparelen = 0;
722 unsigned char *outblob;
724 struct mpint_pos numbers[9];
725 int nnumbers, pos, len, seqlen, i;
726 char *header, *footer;
733 * Fetch the key blobs.
735 pubblob = key->alg->public_blob(key->data, &publen);
736 privblob = key->alg->private_blob(key->data, &privlen);
737 spareblob = outblob = NULL;
740 * Find the sequence of integers to be encoded into the OpenSSH
741 * key blob, and also decide on the header line.
743 if (key->alg == &ssh_rsa) {
745 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
746 Bignum bd, bp, bq, bdmp1, bdmq1;
749 * These blobs were generated from inside PuTTY, so we needn't
750 * treat them as untrusted.
752 pos = 4 + GET_32BIT(pubblob);
753 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
754 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
756 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
757 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
758 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
759 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
761 assert(e.start && iqmp.start); /* can't go wrong */
763 /* We also need d mod (p-1) and d mod (q-1). */
764 bd = bignum_from_bytes(d.start, d.bytes);
765 bp = bignum_from_bytes(p.start, p.bytes);
766 bq = bignum_from_bytes(q.start, q.bytes);
769 bdmp1 = bigmod(bd, bp);
770 bdmq1 = bigmod(bd, bq);
775 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
776 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
777 sparelen = dmp1.bytes + dmq1.bytes;
778 spareblob = snewn(sparelen, unsigned char);
779 dmp1.start = spareblob;
780 dmq1.start = spareblob + dmp1.bytes;
781 for (i = 0; i < dmp1.bytes; i++)
782 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
783 for (i = 0; i < dmq1.bytes; i++)
784 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
788 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
799 header = "-----BEGIN RSA PRIVATE KEY-----\n";
800 footer = "-----END RSA PRIVATE KEY-----\n";
801 } else if (key->alg == &ssh_dss) {
803 struct mpint_pos p, q, g, y, x;
806 * These blobs were generated from inside PuTTY, so we needn't
807 * treat them as untrusted.
809 pos = 4 + GET_32BIT(pubblob);
810 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
811 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
812 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
813 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
815 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
817 assert(y.start && x.start); /* can't go wrong */
819 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
827 header = "-----BEGIN DSA PRIVATE KEY-----\n";
828 footer = "-----END DSA PRIVATE KEY-----\n";
830 assert(0); /* zoinks! */
831 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
835 * Now count up the total size of the ASN.1 encoded integers,
836 * so as to determine the length of the containing SEQUENCE.
839 for (i = 0; i < nnumbers; i++) {
840 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
841 len += numbers[i].bytes;
844 /* Now add on the SEQUENCE header. */
845 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
846 /* Round up to the cipher block size, ensuring we have at least one
847 * byte of padding (see below). */
850 outlen = (outlen+8) &~ 7;
853 * Now we know how big outblob needs to be. Allocate it.
855 outblob = snewn(outlen, unsigned char);
858 * And write the data into it.
861 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
862 for (i = 0; i < nnumbers; i++) {
863 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
864 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
865 pos += numbers[i].bytes;
869 * Padding on OpenSSH keys is deterministic. The number of
870 * padding bytes is always more than zero, and always at most
871 * the cipher block length. The value of each padding byte is
872 * equal to the number of padding bytes. So a plaintext that's
873 * an exact multiple of the block size will be padded with 08
874 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
875 * plaintext one byte less than a multiple of the block size
876 * will be padded with just 01.
878 * This enables the OpenSSL key decryption function to strip
879 * off the padding algorithmically and return the unpadded
880 * plaintext to the next layer: it looks at the final byte, and
881 * then expects to find that many bytes at the end of the data
882 * with the same value. Those are all removed and the rest is
886 while (pos < outlen) {
887 outblob[pos++] = outlen - len;
893 * For the moment, we still encrypt our OpenSSH keys using
898 * Invent an iv. Then derive encryption key from passphrase
901 * - let block A equal MD5(passphrase || iv)
902 * - let block B equal MD5(A || passphrase || iv)
903 * - block C would be MD5(B || passphrase || iv) and so on
904 * - encryption key is the first N bytes of A || B
906 struct MD5Context md5c;
907 unsigned char keybuf[32];
909 for (i = 0; i < 8; i++) iv[i] = random_byte();
912 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
913 MD5Update(&md5c, iv, 8);
914 MD5Final(keybuf, &md5c);
917 MD5Update(&md5c, keybuf, 16);
918 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
919 MD5Update(&md5c, iv, 8);
920 MD5Final(keybuf+16, &md5c);
923 * Now encrypt the key blob.
925 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
927 smemclr(&md5c, sizeof(md5c));
928 smemclr(keybuf, sizeof(keybuf));
932 * And save it. We'll use Unix line endings just in case it's
933 * subsequently transferred in binary mode.
935 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
940 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
941 for (i = 0; i < 8; i++)
942 fprintf(fp, "%02X", iv[i]);
945 base64_encode(fp, outblob, outlen, 64);
952 smemclr(outblob, outlen);
956 smemclr(spareblob, sparelen);
960 smemclr(privblob, privlen);
964 smemclr(pubblob, publen);
970 /* ----------------------------------------------------------------------
971 * Code to read ssh.com private keys.
975 * The format of the base64 blob is largely SSH-2-packet-formatted,
976 * except that mpints are a bit different: they're more like the
977 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
978 * (N+7)/8 bytes of data.
980 * So. The blob contains:
982 * - uint32 0x3f6ff9eb (magic number)
983 * - uint32 size (total blob size)
984 * - string key-type (see below)
985 * - string cipher-type (tells you if key is encrypted)
986 * - string encrypted-blob
988 * (The first size field includes the size field itself and the
989 * magic number before it. All other size fields are ordinary SSH-2
990 * strings, so the size field indicates how much data is to
993 * The encrypted blob, once decrypted, contains a single string
994 * which in turn contains the payload. (This allows padding to be
995 * added after that string while still making it clear where the
996 * real payload ends. Also it probably makes for a reasonable
999 * The payload blob, for an RSA key, contains:
1002 * - mpint n (yes, the public and private stuff is intermixed)
1003 * - mpint u (presumably inverse of p mod q)
1004 * - mpint p (p is the smaller prime)
1005 * - mpint q (q is the larger)
1007 * For a DSA key, the payload blob contains:
1015 * Alternatively, if the parameters are `predefined', that
1016 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1017 * containing some predefined parameter specification. *shudder*,
1018 * but I doubt we'll encounter this in real life.
1020 * The key type strings are ghastly. The RSA key I looked at had a
1023 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1025 * and the DSA key wasn't much better:
1027 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1029 * It isn't clear that these will always be the same. I think it
1030 * might be wise just to look at the `if-modn{sign{rsa' and
1031 * `dl-modp{sign{dsa' prefixes.
1033 * Finally, the encryption. The cipher-type string appears to be
1034 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1035 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1036 * from the passphrase by means of yet another hashing faff:
1038 * - first 16 bytes are MD5(passphrase)
1039 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1040 * - if there were more, they'd be MD5(passphrase || first 32),
1044 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1047 char comment[256]; /* allowing any length is overkill */
1048 unsigned char *keyblob;
1049 int keyblob_len, keyblob_size;
1052 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1053 const char **errmsg_p)
1055 struct sshcom_key *ret;
1062 int base64_chars = 0;
1064 ret = snew(struct sshcom_key);
1065 ret->comment[0] = '\0';
1066 ret->keyblob = NULL;
1067 ret->keyblob_len = ret->keyblob_size = 0;
1069 fp = f_open(filename, "r", FALSE);
1071 errmsg = "unable to open key file";
1074 if (!(line = fgetline(fp))) {
1075 errmsg = "unexpected end of file";
1079 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1080 errmsg = "file does not begin with ssh.com key header";
1083 smemclr(line, strlen(line));
1089 if (!(line = fgetline(fp))) {
1090 errmsg = "unexpected end of file";
1094 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----"))
1096 if ((p = strchr(line, ':')) != NULL) {
1098 errmsg = "header found in body of key data";
1102 while (*p && isspace((unsigned char)*p)) p++;
1103 hdrstart = p - line;
1106 * Header lines can end in a trailing backslash for
1109 len = hdrstart + strlen(line+hdrstart);
1111 while (line[len-1] == '\\') {
1115 line2 = fgetline(fp);
1117 errmsg = "unexpected end of file";
1122 line2len = strlen(line2);
1123 line = sresize(line, len + line2len + 1, char);
1124 strcpy(line + len - 1, line2);
1125 len += line2len - 1;
1128 smemclr(line2, strlen(line2));
1132 p = line + hdrstart;
1134 if (!strcmp(line, "Comment")) {
1135 /* Strip quotes in comment if present. */
1136 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1138 p[strlen(p)-1] = '\0';
1140 strncpy(ret->comment, p, sizeof(ret->comment));
1141 ret->comment[sizeof(ret->comment)-1] = '\0';
1147 while (isbase64(*p)) {
1148 base64_bit[base64_chars++] = *p;
1149 if (base64_chars == 4) {
1150 unsigned char out[3];
1154 len = base64_decode_atom(base64_bit, out);
1157 errmsg = "invalid base64 encoding";
1161 if (ret->keyblob_len + len > ret->keyblob_size) {
1162 ret->keyblob_size = ret->keyblob_len + len + 256;
1163 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1167 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1168 ret->keyblob_len += len;
1174 smemclr(line, strlen(line));
1179 if (ret->keyblob_len == 0 || !ret->keyblob) {
1180 errmsg = "key body not present";
1184 if (errmsg_p) *errmsg_p = NULL;
1189 smemclr(line, strlen(line));
1195 smemclr(ret->keyblob, ret->keyblob_size);
1196 sfree(ret->keyblob);
1198 smemclr(ret, sizeof(*ret));
1201 if (errmsg_p) *errmsg_p = errmsg;
1205 int sshcom_encrypted(const Filename *filename, char **comment)
1207 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1208 int pos, len, answer;
1215 * Check magic number.
1217 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
1218 return 0; /* key is invalid */
1221 * Find the cipher-type string.
1225 if (key->keyblob_len < pos+4)
1226 goto done; /* key is far too short */
1227 len = toint(GET_32BIT(key->keyblob + pos));
1228 if (len < 0 || len > key->keyblob_len - pos - 4)
1229 goto done; /* key is far too short */
1230 pos += 4 + len; /* skip key type */
1231 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1232 if (len < 0 || len > key->keyblob_len - pos - 4)
1233 goto done; /* cipher type string is incomplete */
1234 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1238 *comment = dupstr(key->comment);
1239 smemclr(key->keyblob, key->keyblob_size);
1240 sfree(key->keyblob);
1241 smemclr(key, sizeof(*key));
1246 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1248 unsigned bits, bytes;
1249 unsigned char *d = (unsigned char *) data;
1253 bits = GET_32BIT(d);
1255 bytes = (bits + 7) / 8;
1266 return len; /* ensure further calls fail as well */
1269 static int sshcom_put_mpint(void *target, void *data, int len)
1271 unsigned char *d = (unsigned char *)target;
1272 unsigned char *i = (unsigned char *)data;
1273 int bits = len * 8 - 1;
1276 if (*i & (1 << (bits & 7)))
1282 PUT_32BIT(d, bits+1);
1283 memcpy(d+4, i, len);
1287 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1288 const char **errmsg_p)
1290 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1293 const char prefix_rsa[] = "if-modn{sign{rsa";
1294 const char prefix_dsa[] = "dl-modp{sign{dsa";
1295 enum { RSA, DSA } type;
1299 struct ssh2_userkey *ret = NULL, *retkey;
1300 const struct ssh_signkey *alg;
1301 unsigned char *blob = NULL;
1302 int blobsize = 0, publen, privlen;
1308 * Check magic number.
1310 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1311 errmsg = "key does not begin with magic number";
1316 * Determine the key type.
1319 if (key->keyblob_len < pos+4 ||
1320 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1321 len > key->keyblob_len - pos - 4) {
1322 errmsg = "key blob does not contain a key type string";
1325 if (len > sizeof(prefix_rsa) - 1 &&
1326 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1328 } else if (len > sizeof(prefix_dsa) - 1 &&
1329 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1332 errmsg = "key is of unknown type";
1338 * Determine the cipher type.
1340 if (key->keyblob_len < pos+4 ||
1341 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1342 len > key->keyblob_len - pos - 4) {
1343 errmsg = "key blob does not contain a cipher type string";
1346 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1348 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1351 errmsg = "key encryption is of unknown type";
1357 * Get hold of the encrypted part of the key.
1359 if (key->keyblob_len < pos+4 ||
1360 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1361 len > key->keyblob_len - pos - 4) {
1362 errmsg = "key blob does not contain actual key data";
1365 ciphertext = (char *)key->keyblob + pos + 4;
1367 if (cipherlen == 0) {
1368 errmsg = "length of key data is zero";
1373 * Decrypt it if necessary.
1377 * Derive encryption key from passphrase and iv/salt:
1379 * - let block A equal MD5(passphrase)
1380 * - let block B equal MD5(passphrase || A)
1381 * - block C would be MD5(passphrase || A || B) and so on
1382 * - encryption key is the first N bytes of A || B
1384 struct MD5Context md5c;
1385 unsigned char keybuf[32], iv[8];
1387 if (cipherlen % 8 != 0) {
1388 errmsg = "encrypted part of key is not a multiple of cipher block"
1394 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1395 MD5Final(keybuf, &md5c);
1398 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1399 MD5Update(&md5c, keybuf, 16);
1400 MD5Final(keybuf+16, &md5c);
1403 * Now decrypt the key blob.
1405 memset(iv, 0, sizeof(iv));
1406 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1409 smemclr(&md5c, sizeof(md5c));
1410 smemclr(keybuf, sizeof(keybuf));
1413 * Hereafter we return WRONG_PASSPHRASE for any parsing
1414 * error. (But only if we've just tried to decrypt it!
1415 * Returning WRONG_PASSPHRASE for an unencrypted key is
1419 ret = SSH2_WRONG_PASSPHRASE;
1423 * Strip away the containing string to get to the real meat.
1425 len = toint(GET_32BIT(ciphertext));
1426 if (len < 0 || len > cipherlen-4) {
1427 errmsg = "containing string was ill-formed";
1434 * Now we break down into RSA versus DSA. In either case we'll
1435 * construct public and private blobs in our own format, and
1436 * end up feeding them to alg->createkey().
1438 blobsize = cipherlen + 256;
1439 blob = snewn(blobsize, unsigned char);
1442 struct mpint_pos n, e, d, u, p, q;
1444 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1445 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1446 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1447 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1448 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1449 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1451 errmsg = "key data did not contain six integers";
1457 pos += put_string(blob+pos, "ssh-rsa", 7);
1458 pos += put_mp(blob+pos, e.start, e.bytes);
1459 pos += put_mp(blob+pos, n.start, n.bytes);
1461 pos += put_string(blob+pos, d.start, d.bytes);
1462 pos += put_mp(blob+pos, q.start, q.bytes);
1463 pos += put_mp(blob+pos, p.start, p.bytes);
1464 pos += put_mp(blob+pos, u.start, u.bytes);
1465 privlen = pos - publen;
1466 } else if (type == DSA) {
1467 struct mpint_pos p, q, g, x, y;
1469 if (GET_32BIT(ciphertext) != 0) {
1470 errmsg = "predefined DSA parameters not supported";
1473 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1474 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1475 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1476 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1477 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1479 errmsg = "key data did not contain five integers";
1485 pos += put_string(blob+pos, "ssh-dss", 7);
1486 pos += put_mp(blob+pos, p.start, p.bytes);
1487 pos += put_mp(blob+pos, q.start, q.bytes);
1488 pos += put_mp(blob+pos, g.start, g.bytes);
1489 pos += put_mp(blob+pos, y.start, y.bytes);
1491 pos += put_mp(blob+pos, x.start, x.bytes);
1492 privlen = pos - publen;
1496 assert(privlen > 0); /* should have bombed by now if not */
1498 retkey = snew(struct ssh2_userkey);
1500 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1501 if (!retkey->data) {
1503 errmsg = "unable to create key data structure";
1506 retkey->comment = dupstr(key->comment);
1508 errmsg = NULL; /* no error */
1513 smemclr(blob, blobsize);
1516 smemclr(key->keyblob, key->keyblob_size);
1517 sfree(key->keyblob);
1518 smemclr(key, sizeof(*key));
1520 if (errmsg_p) *errmsg_p = errmsg;
1524 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1527 unsigned char *pubblob, *privblob;
1528 int publen, privlen;
1529 unsigned char *outblob;
1531 struct mpint_pos numbers[6];
1532 int nnumbers, initial_zero, pos, lenpos, i;
1540 * Fetch the key blobs.
1542 pubblob = key->alg->public_blob(key->data, &publen);
1543 privblob = key->alg->private_blob(key->data, &privlen);
1547 * Find the sequence of integers to be encoded into the OpenSSH
1548 * key blob, and also decide on the header line.
1550 if (key->alg == &ssh_rsa) {
1552 struct mpint_pos n, e, d, p, q, iqmp;
1555 * These blobs were generated from inside PuTTY, so we needn't
1556 * treat them as untrusted.
1558 pos = 4 + GET_32BIT(pubblob);
1559 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1560 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1562 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1563 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1564 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1565 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1567 assert(e.start && iqmp.start); /* can't go wrong */
1578 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1579 } else if (key->alg == &ssh_dss) {
1581 struct mpint_pos p, q, g, y, x;
1584 * These blobs were generated from inside PuTTY, so we needn't
1585 * treat them as untrusted.
1587 pos = 4 + GET_32BIT(pubblob);
1588 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1589 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1590 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1591 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1593 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1595 assert(y.start && x.start); /* can't go wrong */
1605 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1607 assert(0); /* zoinks! */
1608 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1612 * Total size of key blob will be somewhere under 512 plus
1613 * combined length of integers. We'll calculate the more
1614 * precise size as we construct the blob.
1617 for (i = 0; i < nnumbers; i++)
1618 outlen += 4 + numbers[i].bytes;
1619 outblob = snewn(outlen, unsigned char);
1622 * Create the unencrypted key blob.
1625 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1626 pos += 4; /* length field, fill in later */
1627 pos += put_string(outblob+pos, type, strlen(type));
1629 char *ciphertype = passphrase ? "3des-cbc" : "none";
1630 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1632 lenpos = pos; /* remember this position */
1633 pos += 4; /* encrypted-blob size */
1634 pos += 4; /* encrypted-payload size */
1636 PUT_32BIT(outblob+pos, 0);
1639 for (i = 0; i < nnumbers; i++)
1640 pos += sshcom_put_mpint(outblob+pos,
1641 numbers[i].start, numbers[i].bytes);
1642 /* Now wrap up the encrypted payload. */
1643 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1644 /* Pad encrypted blob to a multiple of cipher block size. */
1646 int padding = -(pos - (lenpos+4)) & 7;
1648 outblob[pos++] = random_byte();
1650 ciphertext = (char *)outblob+lenpos+4;
1651 cipherlen = pos - (lenpos+4);
1652 assert(!passphrase || cipherlen % 8 == 0);
1653 /* Wrap up the encrypted blob string. */
1654 PUT_32BIT(outblob+lenpos, cipherlen);
1655 /* And finally fill in the total length field. */
1656 PUT_32BIT(outblob+4, pos);
1658 assert(pos < outlen);
1665 * Derive encryption key from passphrase and iv/salt:
1667 * - let block A equal MD5(passphrase)
1668 * - let block B equal MD5(passphrase || A)
1669 * - block C would be MD5(passphrase || A || B) and so on
1670 * - encryption key is the first N bytes of A || B
1672 struct MD5Context md5c;
1673 unsigned char keybuf[32], iv[8];
1676 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1677 MD5Final(keybuf, &md5c);
1680 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1681 MD5Update(&md5c, keybuf, 16);
1682 MD5Final(keybuf+16, &md5c);
1685 * Now decrypt the key blob.
1687 memset(iv, 0, sizeof(iv));
1688 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1691 smemclr(&md5c, sizeof(md5c));
1692 smemclr(keybuf, sizeof(keybuf));
1696 * And save it. We'll use Unix line endings just in case it's
1697 * subsequently transferred in binary mode.
1699 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1702 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1703 fprintf(fp, "Comment: \"");
1705 * Comment header is broken with backslash-newline if it goes
1706 * over 70 chars. Although it's surrounded by quotes, it
1707 * _doesn't_ escape backslashes or quotes within the string.
1708 * Don't ask me, I didn't design it.
1711 int slen = 60; /* starts at 60 due to "Comment: " */
1712 char *c = key->comment;
1713 while ((int)strlen(c) > slen) {
1714 fprintf(fp, "%.*s\\\n", slen, c);
1716 slen = 70; /* allow 70 chars on subsequent lines */
1718 fprintf(fp, "%s\"\n", c);
1720 base64_encode(fp, outblob, pos, 70);
1721 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1727 smemclr(outblob, outlen);
1731 smemclr(privblob, privlen);
1735 smemclr(pubblob, publen);