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 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;
748 pos = 4 + GET_32BIT(pubblob);
749 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
750 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
752 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
753 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
754 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
755 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
757 assert(e.start && iqmp.start); /* can't go wrong */
759 /* We also need d mod (p-1) and d mod (q-1). */
760 bd = bignum_from_bytes(d.start, d.bytes);
761 bp = bignum_from_bytes(p.start, p.bytes);
762 bq = bignum_from_bytes(q.start, q.bytes);
765 bdmp1 = bigmod(bd, bp);
766 bdmq1 = bigmod(bd, bq);
771 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
772 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
773 sparelen = dmp1.bytes + dmq1.bytes;
774 spareblob = snewn(sparelen, unsigned char);
775 dmp1.start = spareblob;
776 dmq1.start = spareblob + dmp1.bytes;
777 for (i = 0; i < dmp1.bytes; i++)
778 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
779 for (i = 0; i < dmq1.bytes; i++)
780 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
784 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
795 header = "-----BEGIN RSA PRIVATE KEY-----\n";
796 footer = "-----END RSA PRIVATE KEY-----\n";
797 } else if (key->alg == &ssh_dss) {
799 struct mpint_pos p, q, g, y, x;
801 pos = 4 + GET_32BIT(pubblob);
802 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
803 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
804 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
805 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
807 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
809 assert(y.start && x.start); /* can't go wrong */
811 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
819 header = "-----BEGIN DSA PRIVATE KEY-----\n";
820 footer = "-----END DSA PRIVATE KEY-----\n";
822 assert(0); /* zoinks! */
823 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
827 * Now count up the total size of the ASN.1 encoded integers,
828 * so as to determine the length of the containing SEQUENCE.
831 for (i = 0; i < nnumbers; i++) {
832 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
833 len += numbers[i].bytes;
836 /* Now add on the SEQUENCE header. */
837 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
838 /* Round up to the cipher block size, ensuring we have at least one
839 * byte of padding (see below). */
842 outlen = (outlen+8) &~ 7;
845 * Now we know how big outblob needs to be. Allocate it.
847 outblob = snewn(outlen, unsigned char);
850 * And write the data into it.
853 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
854 for (i = 0; i < nnumbers; i++) {
855 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
856 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
857 pos += numbers[i].bytes;
861 * Padding on OpenSSH keys is deterministic. The number of
862 * padding bytes is always more than zero, and always at most
863 * the cipher block length. The value of each padding byte is
864 * equal to the number of padding bytes. So a plaintext that's
865 * an exact multiple of the block size will be padded with 08
866 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
867 * plaintext one byte less than a multiple of the block size
868 * will be padded with just 01.
870 * This enables the OpenSSL key decryption function to strip
871 * off the padding algorithmically and return the unpadded
872 * plaintext to the next layer: it looks at the final byte, and
873 * then expects to find that many bytes at the end of the data
874 * with the same value. Those are all removed and the rest is
878 while (pos < outlen) {
879 outblob[pos++] = outlen - len;
885 * For the moment, we still encrypt our OpenSSH keys using
890 * Invent an iv. Then derive encryption key from passphrase
893 * - let block A equal MD5(passphrase || iv)
894 * - let block B equal MD5(A || passphrase || iv)
895 * - block C would be MD5(B || passphrase || iv) and so on
896 * - encryption key is the first N bytes of A || B
898 struct MD5Context md5c;
899 unsigned char keybuf[32];
901 for (i = 0; i < 8; i++) iv[i] = random_byte();
904 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
905 MD5Update(&md5c, iv, 8);
906 MD5Final(keybuf, &md5c);
909 MD5Update(&md5c, keybuf, 16);
910 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
911 MD5Update(&md5c, iv, 8);
912 MD5Final(keybuf+16, &md5c);
915 * Now encrypt the key blob.
917 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
919 smemclr(&md5c, sizeof(md5c));
920 smemclr(keybuf, sizeof(keybuf));
924 * And save it. We'll use Unix line endings just in case it's
925 * subsequently transferred in binary mode.
927 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
932 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
933 for (i = 0; i < 8; i++)
934 fprintf(fp, "%02X", iv[i]);
937 base64_encode(fp, outblob, outlen, 64);
944 smemclr(outblob, outlen);
948 smemclr(spareblob, sparelen);
952 smemclr(privblob, privlen);
956 smemclr(pubblob, publen);
962 /* ----------------------------------------------------------------------
963 * Code to read ssh.com private keys.
967 * The format of the base64 blob is largely SSH-2-packet-formatted,
968 * except that mpints are a bit different: they're more like the
969 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
970 * (N+7)/8 bytes of data.
972 * So. The blob contains:
974 * - uint32 0x3f6ff9eb (magic number)
975 * - uint32 size (total blob size)
976 * - string key-type (see below)
977 * - string cipher-type (tells you if key is encrypted)
978 * - string encrypted-blob
980 * (The first size field includes the size field itself and the
981 * magic number before it. All other size fields are ordinary SSH-2
982 * strings, so the size field indicates how much data is to
985 * The encrypted blob, once decrypted, contains a single string
986 * which in turn contains the payload. (This allows padding to be
987 * added after that string while still making it clear where the
988 * real payload ends. Also it probably makes for a reasonable
991 * The payload blob, for an RSA key, contains:
994 * - mpint n (yes, the public and private stuff is intermixed)
995 * - mpint u (presumably inverse of p mod q)
996 * - mpint p (p is the smaller prime)
997 * - mpint q (q is the larger)
999 * For a DSA key, the payload blob contains:
1007 * Alternatively, if the parameters are `predefined', that
1008 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1009 * containing some predefined parameter specification. *shudder*,
1010 * but I doubt we'll encounter this in real life.
1012 * The key type strings are ghastly. The RSA key I looked at had a
1015 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1017 * and the DSA key wasn't much better:
1019 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1021 * It isn't clear that these will always be the same. I think it
1022 * might be wise just to look at the `if-modn{sign{rsa' and
1023 * `dl-modp{sign{dsa' prefixes.
1025 * Finally, the encryption. The cipher-type string appears to be
1026 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1027 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1028 * from the passphrase by means of yet another hashing faff:
1030 * - first 16 bytes are MD5(passphrase)
1031 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1032 * - if there were more, they'd be MD5(passphrase || first 32),
1036 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1039 char comment[256]; /* allowing any length is overkill */
1040 unsigned char *keyblob;
1041 int keyblob_len, keyblob_size;
1044 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1045 const char **errmsg_p)
1047 struct sshcom_key *ret;
1054 int base64_chars = 0;
1056 ret = snew(struct sshcom_key);
1057 ret->comment[0] = '\0';
1058 ret->keyblob = NULL;
1059 ret->keyblob_len = ret->keyblob_size = 0;
1061 fp = f_open(filename, "r", FALSE);
1063 errmsg = "unable to open key file";
1066 if (!(line = fgetline(fp))) {
1067 errmsg = "unexpected end of file";
1071 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1072 errmsg = "file does not begin with ssh.com key header";
1075 smemclr(line, strlen(line));
1081 if (!(line = fgetline(fp))) {
1082 errmsg = "unexpected end of file";
1086 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----"))
1088 if ((p = strchr(line, ':')) != NULL) {
1090 errmsg = "header found in body of key data";
1094 while (*p && isspace((unsigned char)*p)) p++;
1095 hdrstart = p - line;
1098 * Header lines can end in a trailing backslash for
1101 len = hdrstart + strlen(line+hdrstart);
1103 while (line[len-1] == '\\') {
1107 line2 = fgetline(fp);
1109 errmsg = "unexpected end of file";
1114 line2len = strlen(line2);
1115 line = sresize(line, len + line2len + 1, char);
1116 strcpy(line + len - 1, line2);
1117 len += line2len - 1;
1120 smemclr(line2, strlen(line2));
1124 p = line + hdrstart;
1126 if (!strcmp(line, "Comment")) {
1127 /* Strip quotes in comment if present. */
1128 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1130 p[strlen(p)-1] = '\0';
1132 strncpy(ret->comment, p, sizeof(ret->comment));
1133 ret->comment[sizeof(ret->comment)-1] = '\0';
1139 while (isbase64(*p)) {
1140 base64_bit[base64_chars++] = *p;
1141 if (base64_chars == 4) {
1142 unsigned char out[3];
1146 len = base64_decode_atom(base64_bit, out);
1149 errmsg = "invalid base64 encoding";
1153 if (ret->keyblob_len + len > ret->keyblob_size) {
1154 ret->keyblob_size = ret->keyblob_len + len + 256;
1155 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1159 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1160 ret->keyblob_len += len;
1166 smemclr(line, strlen(line));
1171 if (ret->keyblob_len == 0 || !ret->keyblob) {
1172 errmsg = "key body not present";
1176 if (errmsg_p) *errmsg_p = NULL;
1181 smemclr(line, strlen(line));
1187 smemclr(ret->keyblob, ret->keyblob_size);
1188 sfree(ret->keyblob);
1190 smemclr(ret, sizeof(*ret));
1193 if (errmsg_p) *errmsg_p = errmsg;
1197 int sshcom_encrypted(const Filename *filename, char **comment)
1199 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1200 int pos, len, answer;
1207 * Check magic number.
1209 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb)
1210 return 0; /* key is invalid */
1213 * Find the cipher-type string.
1217 if (key->keyblob_len < pos+4)
1218 goto done; /* key is far too short */
1219 pos += 4 + GET_32BIT(key->keyblob + pos); /* skip key type */
1220 if (key->keyblob_len < pos+4)
1221 goto done; /* key is far too short */
1222 len = GET_32BIT(key->keyblob + pos); /* find cipher-type length */
1223 if (key->keyblob_len < pos+4+len)
1224 goto done; /* cipher type string is incomplete */
1225 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1229 *comment = dupstr(key->comment);
1230 smemclr(key->keyblob, key->keyblob_size);
1231 sfree(key->keyblob);
1232 smemclr(key, sizeof(*key));
1237 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1241 unsigned char *d = (unsigned char *) data;
1245 bits = GET_32BIT(d);
1247 bytes = (bits + 7) / 8;
1258 return len; /* ensure further calls fail as well */
1261 static int sshcom_put_mpint(void *target, void *data, int len)
1263 unsigned char *d = (unsigned char *)target;
1264 unsigned char *i = (unsigned char *)data;
1265 int bits = len * 8 - 1;
1268 if (*i & (1 << (bits & 7)))
1274 PUT_32BIT(d, bits+1);
1275 memcpy(d+4, i, len);
1279 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1280 const char **errmsg_p)
1282 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1285 const char prefix_rsa[] = "if-modn{sign{rsa";
1286 const char prefix_dsa[] = "dl-modp{sign{dsa";
1287 enum { RSA, DSA } type;
1291 struct ssh2_userkey *ret = NULL, *retkey;
1292 const struct ssh_signkey *alg;
1293 unsigned char *blob = NULL;
1294 int blobsize = 0, publen, privlen;
1300 * Check magic number.
1302 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1303 errmsg = "key does not begin with magic number";
1308 * Determine the key type.
1311 if (key->keyblob_len < pos+4 ||
1312 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1313 errmsg = "key blob does not contain a key type string";
1316 if (len > sizeof(prefix_rsa) - 1 &&
1317 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
1319 } else if (len > sizeof(prefix_dsa) - 1 &&
1320 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
1323 errmsg = "key is of unknown type";
1329 * Determine the cipher type.
1331 if (key->keyblob_len < pos+4 ||
1332 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1333 errmsg = "key blob does not contain a cipher type string";
1336 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
1338 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
1341 errmsg = "key encryption is of unknown type";
1347 * Get hold of the encrypted part of the key.
1349 if (key->keyblob_len < pos+4 ||
1350 (len = GET_32BIT(key->keyblob + pos)) > key->keyblob_len - pos - 4) {
1351 errmsg = "key blob does not contain actual key data";
1354 ciphertext = (char *)key->keyblob + pos + 4;
1356 if (cipherlen == 0) {
1357 errmsg = "length of key data is zero";
1362 * Decrypt it if necessary.
1366 * Derive encryption key from passphrase and iv/salt:
1368 * - let block A equal MD5(passphrase)
1369 * - let block B equal MD5(passphrase || A)
1370 * - block C would be MD5(passphrase || A || B) and so on
1371 * - encryption key is the first N bytes of A || B
1373 struct MD5Context md5c;
1374 unsigned char keybuf[32], iv[8];
1376 if (cipherlen % 8 != 0) {
1377 errmsg = "encrypted part of key is not a multiple of cipher block"
1383 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1384 MD5Final(keybuf, &md5c);
1387 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1388 MD5Update(&md5c, keybuf, 16);
1389 MD5Final(keybuf+16, &md5c);
1392 * Now decrypt the key blob.
1394 memset(iv, 0, sizeof(iv));
1395 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1398 smemclr(&md5c, sizeof(md5c));
1399 smemclr(keybuf, sizeof(keybuf));
1402 * Hereafter we return WRONG_PASSPHRASE for any parsing
1403 * error. (But only if we've just tried to decrypt it!
1404 * Returning WRONG_PASSPHRASE for an unencrypted key is
1408 ret = SSH2_WRONG_PASSPHRASE;
1412 * Strip away the containing string to get to the real meat.
1414 len = GET_32BIT(ciphertext);
1415 if (len < 0 || len > cipherlen-4) {
1416 errmsg = "containing string was ill-formed";
1423 * Now we break down into RSA versus DSA. In either case we'll
1424 * construct public and private blobs in our own format, and
1425 * end up feeding them to alg->createkey().
1427 blobsize = cipherlen + 256;
1428 blob = snewn(blobsize, unsigned char);
1431 struct mpint_pos n, e, d, u, p, q;
1433 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
1434 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
1435 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
1436 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
1437 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1438 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1440 errmsg = "key data did not contain six integers";
1446 pos += put_string(blob+pos, "ssh-rsa", 7);
1447 pos += put_mp(blob+pos, e.start, e.bytes);
1448 pos += put_mp(blob+pos, n.start, n.bytes);
1450 pos += put_string(blob+pos, d.start, d.bytes);
1451 pos += put_mp(blob+pos, q.start, q.bytes);
1452 pos += put_mp(blob+pos, p.start, p.bytes);
1453 pos += put_mp(blob+pos, u.start, u.bytes);
1454 privlen = pos - publen;
1455 } else if (type == DSA) {
1456 struct mpint_pos p, q, g, x, y;
1458 if (GET_32BIT(ciphertext) != 0) {
1459 errmsg = "predefined DSA parameters not supported";
1462 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
1463 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
1464 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
1465 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
1466 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
1468 errmsg = "key data did not contain five integers";
1474 pos += put_string(blob+pos, "ssh-dss", 7);
1475 pos += put_mp(blob+pos, p.start, p.bytes);
1476 pos += put_mp(blob+pos, q.start, q.bytes);
1477 pos += put_mp(blob+pos, g.start, g.bytes);
1478 pos += put_mp(blob+pos, y.start, y.bytes);
1480 pos += put_mp(blob+pos, x.start, x.bytes);
1481 privlen = pos - publen;
1485 assert(privlen > 0); /* should have bombed by now if not */
1487 retkey = snew(struct ssh2_userkey);
1489 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
1490 if (!retkey->data) {
1492 errmsg = "unable to create key data structure";
1495 retkey->comment = dupstr(key->comment);
1497 errmsg = NULL; /* no error */
1502 smemclr(blob, blobsize);
1505 smemclr(key->keyblob, key->keyblob_size);
1506 sfree(key->keyblob);
1507 smemclr(key, sizeof(*key));
1509 if (errmsg_p) *errmsg_p = errmsg;
1513 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
1516 unsigned char *pubblob, *privblob;
1517 int publen, privlen;
1518 unsigned char *outblob;
1520 struct mpint_pos numbers[6];
1521 int nnumbers, initial_zero, pos, lenpos, i;
1529 * Fetch the key blobs.
1531 pubblob = key->alg->public_blob(key->data, &publen);
1532 privblob = key->alg->private_blob(key->data, &privlen);
1536 * Find the sequence of integers to be encoded into the OpenSSH
1537 * key blob, and also decide on the header line.
1539 if (key->alg == &ssh_rsa) {
1541 struct mpint_pos n, e, d, p, q, iqmp;
1543 pos = 4 + GET_32BIT(pubblob);
1544 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1545 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1547 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1548 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1549 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1550 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1552 assert(e.start && iqmp.start); /* can't go wrong */
1563 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1564 } else if (key->alg == &ssh_dss) {
1566 struct mpint_pos p, q, g, y, x;
1568 pos = 4 + GET_32BIT(pubblob);
1569 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1570 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1571 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1572 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1574 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1576 assert(y.start && x.start); /* can't go wrong */
1586 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1588 assert(0); /* zoinks! */
1589 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1593 * Total size of key blob will be somewhere under 512 plus
1594 * combined length of integers. We'll calculate the more
1595 * precise size as we construct the blob.
1598 for (i = 0; i < nnumbers; i++)
1599 outlen += 4 + numbers[i].bytes;
1600 outblob = snewn(outlen, unsigned char);
1603 * Create the unencrypted key blob.
1606 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
1607 pos += 4; /* length field, fill in later */
1608 pos += put_string(outblob+pos, type, strlen(type));
1610 char *ciphertype = passphrase ? "3des-cbc" : "none";
1611 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
1613 lenpos = pos; /* remember this position */
1614 pos += 4; /* encrypted-blob size */
1615 pos += 4; /* encrypted-payload size */
1617 PUT_32BIT(outblob+pos, 0);
1620 for (i = 0; i < nnumbers; i++)
1621 pos += sshcom_put_mpint(outblob+pos,
1622 numbers[i].start, numbers[i].bytes);
1623 /* Now wrap up the encrypted payload. */
1624 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
1625 /* Pad encrypted blob to a multiple of cipher block size. */
1627 int padding = -(pos - (lenpos+4)) & 7;
1629 outblob[pos++] = random_byte();
1631 ciphertext = (char *)outblob+lenpos+4;
1632 cipherlen = pos - (lenpos+4);
1633 assert(!passphrase || cipherlen % 8 == 0);
1634 /* Wrap up the encrypted blob string. */
1635 PUT_32BIT(outblob+lenpos, cipherlen);
1636 /* And finally fill in the total length field. */
1637 PUT_32BIT(outblob+4, pos);
1639 assert(pos < outlen);
1646 * Derive encryption key from passphrase and iv/salt:
1648 * - let block A equal MD5(passphrase)
1649 * - let block B equal MD5(passphrase || A)
1650 * - block C would be MD5(passphrase || A || B) and so on
1651 * - encryption key is the first N bytes of A || B
1653 struct MD5Context md5c;
1654 unsigned char keybuf[32], iv[8];
1657 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1658 MD5Final(keybuf, &md5c);
1661 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1662 MD5Update(&md5c, keybuf, 16);
1663 MD5Final(keybuf+16, &md5c);
1666 * Now decrypt the key blob.
1668 memset(iv, 0, sizeof(iv));
1669 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
1672 smemclr(&md5c, sizeof(md5c));
1673 smemclr(keybuf, sizeof(keybuf));
1677 * And save it. We'll use Unix line endings just in case it's
1678 * subsequently transferred in binary mode.
1680 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1683 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1684 fprintf(fp, "Comment: \"");
1686 * Comment header is broken with backslash-newline if it goes
1687 * over 70 chars. Although it's surrounded by quotes, it
1688 * _doesn't_ escape backslashes or quotes within the string.
1689 * Don't ask me, I didn't design it.
1692 int slen = 60; /* starts at 60 due to "Comment: " */
1693 char *c = key->comment;
1694 while ((int)strlen(c) > slen) {
1695 fprintf(fp, "%.*s\\\n", slen, c);
1697 slen = 70; /* allow 70 chars on subsequent lines */
1699 fprintf(fp, "%s\"\n", c);
1701 base64_encode(fp, outblob, pos, 70);
1702 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
1708 smemclr(outblob, outlen);
1712 smemclr(privblob, privlen);
1716 smemclr(pubblob, publen);