2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 int openssh_pem_encrypted(const Filename *filename);
16 int openssh_new_encrypted(const Filename *filename);
17 struct ssh2_userkey *openssh_pem_read(const Filename *filename,
19 const char **errmsg_p);
20 struct ssh2_userkey *openssh_new_read(const Filename *filename,
22 const char **errmsg_p);
23 int openssh_auto_write(const Filename *filename, struct ssh2_userkey *key,
25 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
27 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
30 int sshcom_encrypted(const Filename *filename, char **comment);
31 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
32 const char **errmsg_p);
33 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
37 * Given a key type, determine whether we know how to import it.
39 int import_possible(int type)
41 if (type == SSH_KEYTYPE_OPENSSH_PEM)
43 if (type == SSH_KEYTYPE_OPENSSH_NEW)
45 if (type == SSH_KEYTYPE_SSHCOM)
51 * Given a key type, determine what native key type
52 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
55 int import_target_type(int type)
58 * There are no known foreign SSH-1 key formats.
60 return SSH_KEYTYPE_SSH2;
64 * Determine whether a foreign key is encrypted.
66 int import_encrypted(const Filename *filename, int type, char **comment)
68 if (type == SSH_KEYTYPE_OPENSSH_PEM) {
69 /* OpenSSH PEM format doesn't contain a key comment at all */
70 *comment = dupstr(filename_to_str(filename));
71 return openssh_pem_encrypted(filename);
72 } else if (type == SSH_KEYTYPE_OPENSSH_NEW) {
73 /* OpenSSH new format does, but it's inside the encrypted
74 * section for some reason */
75 *comment = dupstr(filename_to_str(filename));
76 return openssh_new_encrypted(filename);
77 } else if (type == SSH_KEYTYPE_SSHCOM) {
78 return sshcom_encrypted(filename, comment);
84 * Import an SSH-1 key.
86 int import_ssh1(const Filename *filename, int type,
87 struct RSAKey *key, char *passphrase, const char **errmsg_p)
93 * Import an SSH-2 key.
95 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
96 char *passphrase, const char **errmsg_p)
98 if (type == SSH_KEYTYPE_OPENSSH_PEM)
99 return openssh_pem_read(filename, passphrase, errmsg_p);
100 else if (type == SSH_KEYTYPE_OPENSSH_NEW)
101 return openssh_new_read(filename, passphrase, errmsg_p);
102 if (type == SSH_KEYTYPE_SSHCOM)
103 return sshcom_read(filename, passphrase, errmsg_p);
108 * Export an SSH-1 key.
110 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
117 * Export an SSH-2 key.
119 int export_ssh2(const Filename *filename, int type,
120 struct ssh2_userkey *key, char *passphrase)
122 if (type == SSH_KEYTYPE_OPENSSH_AUTO)
123 return openssh_auto_write(filename, key, passphrase);
124 if (type == SSH_KEYTYPE_OPENSSH_NEW)
125 return openssh_new_write(filename, key, passphrase);
126 if (type == SSH_KEYTYPE_SSHCOM)
127 return sshcom_write(filename, key, passphrase);
132 * Strip trailing CRs and LFs at the end of a line of text.
134 void strip_crlf(char *str)
136 char *p = str + strlen(str);
138 while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
142 /* ----------------------------------------------------------------------
143 * Helper routines. (The base64 ones are defined in sshpubk.c.)
146 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
147 ((c) >= 'a' && (c) <= 'z') || \
148 ((c) >= '0' && (c) <= '9') || \
149 (c) == '+' || (c) == '/' || (c) == '=' \
153 * Read an ASN.1/BER identifier and length pair.
155 * Flags are a combination of the #defines listed below.
157 * Returns -1 if unsuccessful; otherwise returns the number of
158 * bytes used out of the source data.
161 /* ASN.1 tag classes. */
162 #define ASN1_CLASS_UNIVERSAL (0 << 6)
163 #define ASN1_CLASS_APPLICATION (1 << 6)
164 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
165 #define ASN1_CLASS_PRIVATE (3 << 6)
166 #define ASN1_CLASS_MASK (3 << 6)
168 /* Primitive versus constructed bit. */
169 #define ASN1_CONSTRUCTED (1 << 5)
171 static int ber_read_id_len(void *source, int sourcelen,
172 int *id, int *length, int *flags)
174 unsigned char *p = (unsigned char *) source;
179 *flags = (*p & 0xE0);
180 if ((*p & 0x1F) == 0x1F) {
186 *id = (*id << 7) | (*p & 0x7F);
204 *length = (*length << 8) | (*p++);
211 return p - (unsigned char *) source;
215 * Write an ASN.1/BER identifier and length pair. Returns the
216 * number of bytes consumed. Assumes dest contains enough space.
217 * Will avoid writing anything if dest is NULL, but still return
218 * amount of space required.
220 static int ber_write_id_len(void *dest, int id, int length, int flags)
222 unsigned char *d = (unsigned char *)dest;
227 * Identifier is one byte.
230 if (d) *d++ = id | flags;
234 * Identifier is multiple bytes: the first byte is 11111
235 * plus the flags, and subsequent bytes encode the value of
236 * the identifier, 7 bits at a time, with the top bit of
237 * each byte 1 except the last one which is 0.
240 if (d) *d++ = 0x1F | flags;
241 for (n = 1; (id >> (7*n)) > 0; n++)
242 continue; /* count the bytes */
245 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
251 * Length is one byte.
254 if (d) *d++ = length;
258 * Length is multiple bytes. The first is 0x80 plus the
259 * number of subsequent bytes, and the subsequent bytes
260 * encode the actual length.
262 for (n = 1; (length >> (8*n)) > 0; n++)
263 continue; /* count the bytes */
265 if (d) *d++ = 0x80 | n;
268 if (d) *d++ = (length >> (8*n)) & 0xFF;
275 static int put_uint32(void *target, unsigned val)
277 unsigned char *d = (unsigned char *)target;
283 static int put_string(void *target, const void *data, int len)
285 unsigned char *d = (unsigned char *)target;
288 memcpy(d+4, data, len);
292 static int put_string_z(void *target, const char *string)
294 return put_string(target, string, strlen(string));
297 static int put_mp(void *target, void *data, int len)
299 unsigned char *d = (unsigned char *)target;
300 unsigned char *i = (unsigned char *)data;
305 memcpy(d+5, data, len);
309 memcpy(d+4, data, len);
314 /* Simple structure to point to an mp-int within a blob. */
315 struct mpint_pos { void *start; int bytes; };
317 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
320 unsigned char *d = (unsigned char *) data;
324 bytes = toint(GET_32BIT(d));
325 if (bytes < 0 || len-4 < bytes)
335 return len; /* ensure further calls fail as well */
338 /* ----------------------------------------------------------------------
339 * Code to read and write OpenSSH private keys, in the old-style PEM
344 OP_DSA, OP_RSA, OP_ECDSA
345 } openssh_pem_keytype;
350 struct openssh_pem_key {
351 openssh_pem_keytype keytype;
353 openssh_pem_enc encryption;
355 unsigned char *keyblob;
356 int keyblob_len, keyblob_size;
359 static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename,
360 const char **errmsg_p)
362 struct openssh_pem_key *ret;
369 int base64_chars = 0;
371 ret = snew(struct openssh_pem_key);
373 ret->keyblob_len = ret->keyblob_size = 0;
375 fp = f_open(filename, "r", FALSE);
377 errmsg = "unable to open key file";
381 if (!(line = fgetline(fp))) {
382 errmsg = "unexpected end of file";
386 if (0 != strncmp(line, "-----BEGIN ", 11) ||
387 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
388 errmsg = "file does not begin with OpenSSH key header";
392 * Parse the BEGIN line. For old-format keys, this tells us the
393 * type of the key; for new-format keys, all it tells us is the
394 * format, and we'll find out the key type once we parse the
397 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) {
398 ret->keytype = OP_RSA;
399 } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) {
400 ret->keytype = OP_DSA;
401 } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) {
402 ret->keytype = OP_ECDSA;
403 } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
404 errmsg = "this is a new-style OpenSSH key";
407 errmsg = "unrecognised key type";
410 smemclr(line, strlen(line));
414 ret->encrypted = FALSE;
415 memset(ret->iv, 0, sizeof(ret->iv));
419 if (!(line = fgetline(fp))) {
420 errmsg = "unexpected end of file";
424 if (0 == strncmp(line, "-----END ", 9) &&
425 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
430 if ((p = strchr(line, ':')) != NULL) {
432 errmsg = "header found in body of key data";
436 while (*p && isspace((unsigned char)*p)) p++;
437 if (!strcmp(line, "Proc-Type")) {
438 if (p[0] != '4' || p[1] != ',') {
439 errmsg = "Proc-Type is not 4 (only 4 is supported)";
443 if (!strcmp(p, "ENCRYPTED"))
444 ret->encrypted = TRUE;
445 } else if (!strcmp(line, "DEK-Info")) {
448 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
449 ret->encryption = OP_E_3DES;
451 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
452 ret->encryption = OP_E_AES;
455 errmsg = "unsupported cipher";
458 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
459 for (i = 0; i < ivlen; i++) {
460 if (1 != sscanf(p, "%2x", &j)) {
461 errmsg = "expected more iv data in DEK-Info";
468 errmsg = "more iv data than expected in DEK-Info";
476 while (isbase64(*p)) {
477 base64_bit[base64_chars++] = *p;
478 if (base64_chars == 4) {
479 unsigned char out[3];
484 len = base64_decode_atom(base64_bit, out);
487 errmsg = "invalid base64 encoding";
491 if (ret->keyblob_len + len > ret->keyblob_size) {
492 ret->keyblob_size = ret->keyblob_len + len + 256;
493 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
497 memcpy(ret->keyblob + ret->keyblob_len, out, len);
498 ret->keyblob_len += len;
500 smemclr(out, sizeof(out));
506 smemclr(line, strlen(line));
514 if (ret->keyblob_len == 0 || !ret->keyblob) {
515 errmsg = "key body not present";
519 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
520 errmsg = "encrypted key blob is not a multiple of "
525 smemclr(base64_bit, sizeof(base64_bit));
526 if (errmsg_p) *errmsg_p = NULL;
531 smemclr(line, strlen(line));
535 smemclr(base64_bit, sizeof(base64_bit));
538 smemclr(ret->keyblob, ret->keyblob_size);
541 smemclr(ret, sizeof(*ret));
544 if (errmsg_p) *errmsg_p = errmsg;
549 int openssh_pem_encrypted(const Filename *filename)
551 struct openssh_pem_key *key = load_openssh_pem_key(filename, NULL);
556 ret = key->encrypted;
557 smemclr(key->keyblob, key->keyblob_size);
559 smemclr(key, sizeof(*key));
564 struct ssh2_userkey *openssh_pem_read(const Filename *filename,
566 const char **errmsg_p)
568 struct openssh_pem_key *key = load_openssh_pem_key(filename, errmsg_p);
569 struct ssh2_userkey *retkey;
570 unsigned char *p, *q;
571 int ret, id, len, flags;
573 struct ssh2_userkey *retval = NULL;
576 int blobsize = 0, blobptr, privptr;
585 if (key->encrypted) {
587 * Derive encryption key from passphrase and iv/salt:
589 * - let block A equal MD5(passphrase || iv)
590 * - let block B equal MD5(A || passphrase || iv)
591 * - block C would be MD5(B || passphrase || iv) and so on
592 * - encryption key is the first N bytes of A || B
594 * (Note that only 8 bytes of the iv are used for key
595 * derivation, even when the key is encrypted with AES and
596 * hence there are 16 bytes available.)
598 struct MD5Context md5c;
599 unsigned char keybuf[32];
602 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
603 MD5Update(&md5c, (unsigned char *)key->iv, 8);
604 MD5Final(keybuf, &md5c);
607 MD5Update(&md5c, keybuf, 16);
608 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
609 MD5Update(&md5c, (unsigned char *)key->iv, 8);
610 MD5Final(keybuf+16, &md5c);
613 * Now decrypt the key blob.
615 if (key->encryption == OP_E_3DES)
616 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
617 key->keyblob, key->keyblob_len);
620 assert(key->encryption == OP_E_AES);
621 ctx = aes_make_context();
622 aes128_key(ctx, keybuf);
623 aes_iv(ctx, (unsigned char *)key->iv);
624 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
625 aes_free_context(ctx);
628 smemclr(&md5c, sizeof(md5c));
629 smemclr(keybuf, sizeof(keybuf));
633 * Now we have a decrypted key blob, which contains an ASN.1
634 * encoded private key. We must now untangle the ASN.1.
636 * We expect the whole key blob to be formatted as a SEQUENCE
637 * (0x30 followed by a length code indicating that the rest of
638 * the blob is part of the sequence). Within that SEQUENCE we
639 * expect to see a bunch of INTEGERs. What those integers mean
640 * depends on the key type:
642 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
643 * dmp1, dmq1, iqmp in that order. (The last three are d mod
644 * (p-1), d mod (q-1), inverse of q mod p respectively.)
646 * - For DSA, we expect them to be 0, p, q, g, y, x in that
649 * - In ECDSA the format is totally different: we see the
650 * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
651 * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
656 /* Expect the SEQUENCE header. Take its absence as a failure to
657 * decrypt, if the key was encrypted. */
658 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
660 if (ret < 0 || id != 16) {
661 errmsg = "ASN.1 decoding failure";
662 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
666 /* Expect a load of INTEGERs. */
667 if (key->keytype == OP_RSA)
669 else if (key->keytype == OP_DSA)
672 num_integers = 0; /* placate compiler warnings */
675 if (key->keytype == OP_ECDSA) {
676 /* And now for something completely different */
679 const struct ssh_signkey *alg;
680 const struct ec_curve *curve;
681 int algnamelen, curvenamelen;
683 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
686 if (ret < 0 || id != 2 || key->keyblob+key->keyblob_len-p < len ||
687 len != 1 || p[0] != 1) {
688 errmsg = "ASN.1 decoding failure";
689 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
693 /* Read private key OCTET STRING */
694 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
697 if (ret < 0 || id != 4 || key->keyblob+key->keyblob_len-p < len) {
698 errmsg = "ASN.1 decoding failure";
699 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
706 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
709 if (ret < 0 || id != 0 || key->keyblob+key->keyblob_len-p < len) {
710 errmsg = "ASN.1 decoding failure";
711 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
714 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
717 if (ret < 0 || id != 6 || key->keyblob+key->keyblob_len-p < len) {
718 errmsg = "ASN.1 decoding failure";
719 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
722 alg = ec_alg_by_oid(len, p, &curve);
724 errmsg = "Unsupported ECDSA curve.";
729 /* Read BIT STRING point */
730 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
733 if (ret < 0 || id != 1 || key->keyblob+key->keyblob_len-p < len) {
734 errmsg = "ASN.1 decoding failure";
735 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
738 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
741 if (ret < 0 || id != 3 || key->keyblob+key->keyblob_len-p < len ||
742 len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
743 errmsg = "ASN.1 decoding failure";
744 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
747 p += 1; len -= 1; /* Skip 0x00 before point */
749 /* Construct the key */
750 retkey = snew(struct ssh2_userkey);
752 errmsg = "out of memory";
756 blob = snewn((4+19 + 4+8 + 4+len) + (4+1+privlen), unsigned char);
759 errmsg = "out of memory";
765 algnamelen = strlen(alg->name);
766 PUT_32BIT(q, algnamelen); q += 4;
767 memcpy(q, alg->name, algnamelen); q += algnamelen;
769 curvenamelen = strlen(curve->name);
770 PUT_32BIT(q, curvenamelen); q += 4;
771 memcpy(q, curve->name, curvenamelen); q += curvenamelen;
773 PUT_32BIT(q, len); q += 4;
774 memcpy(q, p, len); q += len;
777 * To be acceptable to our createkey(), the private blob must
778 * contain a valid mpint, i.e. without the top bit set. But
779 * the input private string may have the top bit set, so we
780 * prefix a zero byte to ensure createkey() doesn't fail for
783 PUT_32BIT(q, privlen+1);
785 memcpy(q+5, priv, privlen);
787 retkey->data = retkey->alg->createkey(retkey->alg,
793 errmsg = "unable to create key data structure";
797 } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
800 * Space to create key blob in.
802 blobsize = 256+key->keyblob_len;
803 blob = snewn(blobsize, unsigned char);
805 if (key->keytype == OP_DSA)
806 memcpy(blob+4, "ssh-dss", 7);
807 else if (key->keytype == OP_RSA)
808 memcpy(blob+4, "ssh-rsa", 7);
812 for (i = 0; i < num_integers; i++) {
813 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
816 if (ret < 0 || id != 2 ||
817 key->keyblob+key->keyblob_len-p < len) {
818 errmsg = "ASN.1 decoding failure";
819 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
825 * The first integer should be zero always (I think
826 * this is some sort of version indication).
828 if (len != 1 || p[0] != 0) {
829 errmsg = "version number mismatch";
832 } else if (key->keytype == OP_RSA) {
834 * Integers 1 and 2 go into the public blob but in the
835 * opposite order; integers 3, 4, 5 and 8 go into the
836 * private blob. The other two (6 and 7) are ignored.
839 /* Save the details for after we deal with number 2. */
842 } else if (i != 6 && i != 7) {
843 PUT_32BIT(blob+blobptr, len);
844 memcpy(blob+blobptr+4, p, len);
847 PUT_32BIT(blob+blobptr, modlen);
848 memcpy(blob+blobptr+4, modptr, modlen);
853 } else if (key->keytype == OP_DSA) {
855 * Integers 1-4 go into the public blob; integer 5 goes
856 * into the private blob.
858 PUT_32BIT(blob+blobptr, len);
859 memcpy(blob+blobptr+4, p, len);
865 /* Skip past the number. */
870 * Now put together the actual key. Simplest way to do this is
871 * to assemble our own key blobs and feed them to the createkey
872 * functions; this is a bit faffy but it does mean we get all
873 * the sanity checks for free.
875 assert(privptr > 0); /* should have bombed by now if not */
876 retkey = snew(struct ssh2_userkey);
877 retkey->alg = (key->keytype == OP_RSA ? &ssh_rsa : &ssh_dss);
878 retkey->data = retkey->alg->createkey(retkey->alg, blob, privptr,
883 errmsg = "unable to create key data structure";
888 assert(0 && "Bad key type from load_openssh_pem_key");
892 * The old key format doesn't include a comment in the private
895 retkey->comment = dupstr("imported-openssh-key");
897 errmsg = NULL; /* no error */
902 smemclr(blob, blobsize);
905 smemclr(key->keyblob, key->keyblob_size);
907 smemclr(key, sizeof(*key));
909 if (errmsg_p) *errmsg_p = errmsg;
913 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
916 unsigned char *pubblob, *privblob, *spareblob;
917 int publen, privlen, sparelen = 0;
918 unsigned char *outblob;
920 struct mpint_pos numbers[9];
921 int nnumbers, pos, len, seqlen, i;
922 const char *header, *footer;
929 * Fetch the key blobs.
931 pubblob = key->alg->public_blob(key->data, &publen);
932 privblob = key->alg->private_blob(key->data, &privlen);
933 spareblob = outblob = NULL;
939 * Encode the OpenSSH key blob, and also decide on the header
942 if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
944 * The RSA and DSS handlers share some code because the two
945 * key types have very similar ASN.1 representations, as a
946 * plain SEQUENCE of big integers. So we set up a list of
947 * bignums per key type and then construct the actual blob in
948 * common code after that.
950 if (key->alg == &ssh_rsa) {
952 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
953 Bignum bd, bp, bq, bdmp1, bdmq1;
956 * These blobs were generated from inside PuTTY, so we needn't
957 * treat them as untrusted.
959 pos = 4 + GET_32BIT(pubblob);
960 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
961 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
963 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
964 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
965 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
966 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
968 assert(e.start && iqmp.start); /* can't go wrong */
970 /* We also need d mod (p-1) and d mod (q-1). */
971 bd = bignum_from_bytes(d.start, d.bytes);
972 bp = bignum_from_bytes(p.start, p.bytes);
973 bq = bignum_from_bytes(q.start, q.bytes);
976 bdmp1 = bigmod(bd, bp);
977 bdmq1 = bigmod(bd, bq);
982 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
983 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
984 sparelen = dmp1.bytes + dmq1.bytes;
985 spareblob = snewn(sparelen, unsigned char);
986 dmp1.start = spareblob;
987 dmq1.start = spareblob + dmp1.bytes;
988 for (i = 0; i < dmp1.bytes; i++)
989 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
990 for (i = 0; i < dmq1.bytes; i++)
991 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
995 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1006 header = "-----BEGIN RSA PRIVATE KEY-----\n";
1007 footer = "-----END RSA PRIVATE KEY-----\n";
1008 } else { /* ssh-dss */
1010 struct mpint_pos p, q, g, y, x;
1013 * These blobs were generated from inside PuTTY, so we needn't
1014 * treat them as untrusted.
1016 pos = 4 + GET_32BIT(pubblob);
1017 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1018 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1019 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1020 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1022 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1024 assert(y.start && x.start); /* can't go wrong */
1026 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1034 header = "-----BEGIN DSA PRIVATE KEY-----\n";
1035 footer = "-----END DSA PRIVATE KEY-----\n";
1039 * Now count up the total size of the ASN.1 encoded integers,
1040 * so as to determine the length of the containing SEQUENCE.
1043 for (i = 0; i < nnumbers; i++) {
1044 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
1045 len += numbers[i].bytes;
1048 /* Now add on the SEQUENCE header. */
1049 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1052 * Now we know how big outblob needs to be. Allocate it.
1054 outblob = snewn(len, unsigned char);
1057 * And write the data into it.
1060 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1061 for (i = 0; i < nnumbers; i++) {
1062 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
1063 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
1064 pos += numbers[i].bytes;
1066 } else if (key->alg == &ssh_ecdsa_nistp256 ||
1067 key->alg == &ssh_ecdsa_nistp384 ||
1068 key->alg == &ssh_ecdsa_nistp521) {
1069 const unsigned char *oid;
1074 * Structure of asn1:
1077 * OCTET STRING (private key)
1081 * BIT STRING (0x00 public key point)
1083 oid = ec_alg_oid(key->alg, &oidlen);
1084 pointlen = (((struct ec_key *)key->data)->publicKey.curve->fieldBits
1087 len = ber_write_id_len(NULL, 2, 1, 0);
1089 len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1091 len += ber_write_id_len(NULL, 0, oidlen +
1092 ber_write_id_len(NULL, 6, oidlen, 0),
1093 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1094 len += ber_write_id_len(NULL, 6, oidlen, 0);
1096 len += ber_write_id_len(NULL, 1, 2 + pointlen +
1097 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1098 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1099 len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1100 len += 2 + pointlen;
1103 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1105 outblob = snewn(len, unsigned char);
1109 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1110 pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1112 pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1113 memcpy(outblob+pos, privblob + 4, privlen - 4);
1115 pos += ber_write_id_len(outblob+pos, 0, oidlen +
1116 ber_write_id_len(NULL, 6, oidlen, 0),
1117 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1118 pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1119 memcpy(outblob+pos, oid, oidlen);
1121 pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1122 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1123 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1124 pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1126 memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1127 pos += 1 + pointlen;
1129 header = "-----BEGIN EC PRIVATE KEY-----\n";
1130 footer = "-----END EC PRIVATE KEY-----\n";
1132 assert(0); /* zoinks! */
1133 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1139 * For the moment, we still encrypt our OpenSSH keys using
1143 struct MD5Context md5c;
1144 unsigned char keybuf[32];
1147 * Round up to the cipher block size, ensuring we have at
1148 * least one byte of padding (see below).
1150 outlen = (len+8) &~ 7;
1152 unsigned char *tmp = snewn(outlen, unsigned char);
1153 memcpy(tmp, outblob, len);
1154 smemclr(outblob, len);
1160 * Padding on OpenSSH keys is deterministic. The number of
1161 * padding bytes is always more than zero, and always at most
1162 * the cipher block length. The value of each padding byte is
1163 * equal to the number of padding bytes. So a plaintext that's
1164 * an exact multiple of the block size will be padded with 08
1165 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1166 * plaintext one byte less than a multiple of the block size
1167 * will be padded with just 01.
1169 * This enables the OpenSSL key decryption function to strip
1170 * off the padding algorithmically and return the unpadded
1171 * plaintext to the next layer: it looks at the final byte, and
1172 * then expects to find that many bytes at the end of the data
1173 * with the same value. Those are all removed and the rest is
1177 while (pos < outlen) {
1178 outblob[pos++] = outlen - len;
1182 * Invent an iv. Then derive encryption key from passphrase
1185 * - let block A equal MD5(passphrase || iv)
1186 * - let block B equal MD5(A || passphrase || iv)
1187 * - block C would be MD5(B || passphrase || iv) and so on
1188 * - encryption key is the first N bytes of A || B
1190 for (i = 0; i < 8; i++) iv[i] = random_byte();
1193 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1194 MD5Update(&md5c, iv, 8);
1195 MD5Final(keybuf, &md5c);
1198 MD5Update(&md5c, keybuf, 16);
1199 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1200 MD5Update(&md5c, iv, 8);
1201 MD5Final(keybuf+16, &md5c);
1204 * Now encrypt the key blob.
1206 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1208 smemclr(&md5c, sizeof(md5c));
1209 smemclr(keybuf, sizeof(keybuf));
1212 * If no encryption, the blob has exactly its original
1219 * And save it. We'll use Unix line endings just in case it's
1220 * subsequently transferred in binary mode.
1222 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1227 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1228 for (i = 0; i < 8; i++)
1229 fprintf(fp, "%02X", iv[i]);
1230 fprintf(fp, "\n\n");
1232 base64_encode(fp, outblob, outlen, 64);
1239 smemclr(outblob, outlen);
1243 smemclr(spareblob, sparelen);
1247 smemclr(privblob, privlen);
1251 smemclr(pubblob, publen);
1257 /* ----------------------------------------------------------------------
1258 * Code to read and write OpenSSH private keys in the new-style format.
1262 ON_E_NONE, ON_E_AES256CBC
1263 } openssh_new_cipher;
1265 ON_K_NONE, ON_K_BCRYPT
1268 struct openssh_new_key {
1269 openssh_new_cipher cipher;
1270 openssh_new_kdf kdf;
1274 /* This points to a position within keyblob, not a
1275 * separately allocated thing */
1276 const unsigned char *salt;
1280 int nkeys, key_wanted;
1281 /* This too points to a position within keyblob */
1282 unsigned char *privatestr;
1285 unsigned char *keyblob;
1286 int keyblob_len, keyblob_size;
1289 static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
1290 const char **errmsg_p)
1292 struct openssh_new_key *ret;
1298 int base64_chars = 0;
1299 const void *filedata;
1301 const void *string, *kdfopts, *bcryptsalt, *pubkey;
1302 int stringlen, kdfoptlen, bcryptsaltlen, pubkeylen;
1303 unsigned bcryptrounds, nkeys, key_index;
1305 ret = snew(struct openssh_new_key);
1306 ret->keyblob = NULL;
1307 ret->keyblob_len = ret->keyblob_size = 0;
1309 fp = f_open(filename, "r", FALSE);
1311 errmsg = "unable to open key file";
1315 if (!(line = fgetline(fp))) {
1316 errmsg = "unexpected end of file";
1320 if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
1321 errmsg = "file does not begin with OpenSSH new-style key header";
1324 smemclr(line, strlen(line));
1329 if (!(line = fgetline(fp))) {
1330 errmsg = "unexpected end of file";
1334 if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
1341 while (isbase64(*p)) {
1342 base64_bit[base64_chars++] = *p;
1343 if (base64_chars == 4) {
1344 unsigned char out[3];
1349 len = base64_decode_atom(base64_bit, out);
1352 errmsg = "invalid base64 encoding";
1356 if (ret->keyblob_len + len > ret->keyblob_size) {
1357 ret->keyblob_size = ret->keyblob_len + len + 256;
1358 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1362 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1363 ret->keyblob_len += len;
1365 smemclr(out, sizeof(out));
1370 smemclr(line, strlen(line));
1378 if (ret->keyblob_len == 0 || !ret->keyblob) {
1379 errmsg = "key body not present";
1383 filedata = ret->keyblob;
1384 filelen = ret->keyblob_len;
1386 if (filelen < 15 || 0 != memcmp(filedata, "openssh-key-v1\0", 15)) {
1387 errmsg = "new-style OpenSSH magic number missing\n";
1390 filedata = (const char *)filedata + 15;
1393 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1394 errmsg = "encountered EOF before cipher name\n";
1397 if (match_ssh_id(stringlen, string, "none")) {
1398 ret->cipher = ON_E_NONE;
1399 } else if (match_ssh_id(stringlen, string, "aes256-cbc")) {
1400 ret->cipher = ON_E_AES256CBC;
1402 errmsg = "unrecognised cipher name\n";
1406 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1407 errmsg = "encountered EOF before kdf name\n";
1410 if (match_ssh_id(stringlen, string, "none")) {
1411 ret->kdf = ON_K_NONE;
1412 } else if (match_ssh_id(stringlen, string, "bcrypt")) {
1413 ret->kdf = ON_K_BCRYPT;
1415 errmsg = "unrecognised kdf name\n";
1419 if (!(kdfopts = get_ssh_string(&filelen, &filedata, &kdfoptlen))) {
1420 errmsg = "encountered EOF before kdf options\n";
1425 if (kdfoptlen != 0) {
1426 errmsg = "expected empty options string for 'none' kdf";
1431 if (!(bcryptsalt = get_ssh_string(&kdfoptlen, &kdfopts,
1433 errmsg = "bcrypt options string did not contain salt\n";
1436 if (!get_ssh_uint32(&kdfoptlen, &kdfopts, &bcryptrounds)) {
1437 errmsg = "bcrypt options string did not contain round count\n";
1440 ret->kdfopts.bcrypt.salt = bcryptsalt;
1441 ret->kdfopts.bcrypt.saltlen = bcryptsaltlen;
1442 ret->kdfopts.bcrypt.rounds = bcryptrounds;
1447 * At this point we expect a uint32 saying how many keys are
1448 * stored in this file. OpenSSH new-style key files can
1449 * contain more than one. Currently we don't have any user
1450 * interface to specify which one we're trying to extract, so
1451 * we just bomb out with an error if more than one is found in
1452 * the file. However, I've put in all the mechanism here to
1453 * extract the nth one for a given n, in case we later connect
1454 * up some UI to that mechanism. Just arrange that the
1455 * 'key_wanted' field is set to a value in the range [0,
1456 * nkeys) by some mechanism.
1458 if (!get_ssh_uint32(&filelen, &filedata, &nkeys)) {
1459 errmsg = "encountered EOF before key count\n";
1463 errmsg = "multiple keys in new-style OpenSSH key file "
1468 ret->key_wanted = 0;
1470 for (key_index = 0; key_index < nkeys; key_index++) {
1471 if (!(pubkey = get_ssh_string(&filelen, &filedata, &pubkeylen))) {
1472 errmsg = "encountered EOF before kdf options\n";
1478 * Now we expect a string containing the encrypted part of the
1481 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1482 errmsg = "encountered EOF before private key container\n";
1485 ret->privatestr = (unsigned char *)string;
1486 ret->privatelen = stringlen;
1489 * And now we're done, until asked to actually decrypt.
1492 smemclr(base64_bit, sizeof(base64_bit));
1493 if (errmsg_p) *errmsg_p = NULL;
1498 smemclr(line, strlen(line));
1502 smemclr(base64_bit, sizeof(base64_bit));
1505 smemclr(ret->keyblob, ret->keyblob_size);
1506 sfree(ret->keyblob);
1508 smemclr(ret, sizeof(*ret));
1511 if (errmsg_p) *errmsg_p = errmsg;
1516 int openssh_new_encrypted(const Filename *filename)
1518 struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
1523 ret = (key->cipher != ON_E_NONE);
1524 smemclr(key->keyblob, key->keyblob_size);
1525 sfree(key->keyblob);
1526 smemclr(key, sizeof(*key));
1531 struct ssh2_userkey *openssh_new_read(const Filename *filename,
1533 const char **errmsg_p)
1535 struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
1536 struct ssh2_userkey *retkey;
1538 struct ssh2_userkey *retval = NULL;
1540 unsigned char *blob;
1542 unsigned checkint0, checkint1;
1543 const void *priv, *string;
1544 int privlen, stringlen, key_index;
1545 const struct ssh_signkey *alg;
1552 if (key->cipher != ON_E_NONE) {
1553 unsigned char keybuf[48];
1557 * Construct the decryption key, and decrypt the string.
1559 switch (key->cipher) {
1563 case ON_E_AES256CBC:
1564 keysize = 48; /* 32 byte key + 16 byte IV */
1567 assert(0 && "Bad cipher enumeration value");
1569 assert(keysize <= sizeof(keybuf));
1572 memset(keybuf, 0, keysize);
1575 openssh_bcrypt(passphrase,
1576 key->kdfopts.bcrypt.salt,
1577 key->kdfopts.bcrypt.saltlen,
1578 key->kdfopts.bcrypt.rounds,
1582 assert(0 && "Bad kdf enumeration value");
1584 switch (key->cipher) {
1587 case ON_E_AES256CBC:
1588 if (key->privatelen % 16 != 0) {
1589 errmsg = "private key container length is not a"
1590 " multiple of AES block size\n";
1594 void *ctx = aes_make_context();
1595 aes256_key(ctx, keybuf);
1596 aes_iv(ctx, keybuf + 32);
1597 aes_ssh2_decrypt_blk(ctx, key->privatestr,
1599 aes_free_context(ctx);
1603 assert(0 && "Bad cipher enumeration value");
1608 * Now parse the entire encrypted section, and extract the key
1609 * identified by key_wanted.
1611 priv = key->privatestr;
1612 privlen = key->privatelen;
1614 if (!get_ssh_uint32(&privlen, &priv, &checkint0) ||
1615 !get_ssh_uint32(&privlen, &priv, &checkint1) ||
1616 checkint0 != checkint1) {
1617 errmsg = "decryption check failed";
1622 for (key_index = 0; key_index < key->nkeys; key_index++) {
1623 const unsigned char *thiskey;
1627 * Read the key type, which will tell us how to scan over
1628 * the key to get to the next one.
1630 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1631 errmsg = "expected key type in private string";
1636 * Preliminary key type identification, and decide how
1637 * many pieces of key we expect to see. Currently
1638 * (conveniently) all key types can be seen as some number
1639 * of strings, so we just need to know how many of them to
1640 * skip over. (The numbers below exclude the key comment.)
1643 /* find_pubkey_alg needs a zero-terminated copy of the
1645 char *name_zt = dupprintf("%.*s", stringlen, (char *)string);
1646 alg = find_pubkey_alg(name_zt);
1651 errmsg = "private key type not recognised\n";
1658 * Skip over the pieces of key.
1660 for (i = 0; i < alg->openssh_private_npieces; i++) {
1661 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1662 errmsg = "ran out of data in mid-private-key";
1667 thiskeylen = (int)((const unsigned char *)priv -
1668 (const unsigned char *)thiskey);
1669 if (key_index == key->key_wanted) {
1670 retkey = snew(struct ssh2_userkey);
1672 retkey->data = alg->openssh_createkey(alg, &thiskey, &thiskeylen);
1673 if (!retkey->data) {
1675 errmsg = "unable to create key data structure";
1681 * Read the key comment.
1683 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1684 errmsg = "ran out of data at key comment";
1687 if (key_index == key->key_wanted) {
1689 retkey->comment = dupprintf("%.*s", stringlen,
1690 (const char *)string);
1695 errmsg = "key index out of range";
1700 * Now we expect nothing left but padding.
1702 for (i = 0; i < privlen; i++) {
1703 if (((const unsigned char *)priv)[i] != (unsigned char)(i+1)) {
1704 errmsg = "padding at end of private string did not match";
1709 errmsg = NULL; /* no error */
1714 smemclr(blob, blobsize);
1717 smemclr(key->keyblob, key->keyblob_size);
1718 sfree(key->keyblob);
1719 smemclr(key, sizeof(*key));
1721 if (errmsg_p) *errmsg_p = errmsg;
1725 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
1728 unsigned char *pubblob, *privblob, *outblob, *p;
1729 unsigned char *private_section_start, *private_section_length_field;
1730 int publen, privlen, commentlen, maxsize, padvalue, i;
1733 unsigned char bcrypt_salt[16];
1734 const int bcrypt_rounds = 16;
1738 * Fetch the key blobs and find out the lengths of things.
1740 pubblob = key->alg->public_blob(key->data, &publen);
1741 i = key->alg->openssh_fmtkey(key->data, NULL, 0);
1742 privblob = snewn(i, unsigned char);
1743 privlen = key->alg->openssh_fmtkey(key->data, privblob, i);
1744 assert(privlen == i);
1745 commentlen = strlen(key->comment);
1748 * Allocate enough space for the full binary key format. No need
1749 * to be absolutely precise here.
1751 maxsize = (16 + /* magic number */
1752 32 + /* cipher name string */
1753 32 + /* kdf name string */
1754 64 + /* kdf options string */
1756 4+publen + /* public key string */
1757 4 + /* string header for private section */
1758 8 + /* checkint x 2 */
1759 4+strlen(key->alg->name) + /* key type string */
1760 privlen + /* private blob */
1761 4+commentlen + /* comment string */
1762 16); /* padding at end of private section */
1763 outblob = snewn(maxsize, unsigned char);
1766 * Construct the cleartext version of the blob.
1771 memcpy(p, "openssh-key-v1\0", 15);
1774 /* Cipher and kdf names, and kdf options. */
1776 memset(bcrypt_salt, 0, sizeof(bcrypt_salt)); /* prevent warnings */
1777 p += put_string_z(p, "none");
1778 p += put_string_z(p, "none");
1779 p += put_string_z(p, "");
1782 for (i = 0; i < (int)sizeof(bcrypt_salt); i++)
1783 bcrypt_salt[i] = random_byte();
1784 p += put_string_z(p, "aes256-cbc");
1785 p += put_string_z(p, "bcrypt");
1788 p += put_string(p, bcrypt_salt, sizeof(bcrypt_salt));
1789 p += put_uint32(p, bcrypt_rounds);
1790 PUT_32BIT_MSB_FIRST(q, (unsigned)(p - (q+4)));
1793 /* Number of keys. */
1794 p += put_uint32(p, 1);
1797 p += put_string(p, pubblob, publen);
1799 /* Begin private section. */
1800 private_section_length_field = p;
1802 private_section_start = p;
1806 for (i = 0; i < 4; i++)
1807 checkint = (checkint << 8) + random_byte();
1808 p += put_uint32(p, checkint);
1809 p += put_uint32(p, checkint);
1811 /* Private key. The main private blob goes inline, with no string
1813 p += put_string_z(p, key->alg->name);
1814 memcpy(p, privblob, privlen);
1818 p += put_string_z(p, key->comment);
1820 /* Pad out the encrypted section. */
1824 } while ((p - private_section_start) & 15);
1826 assert(p - outblob < maxsize);
1828 /* Go back and fill in the length field for the private section. */
1829 PUT_32BIT_MSB_FIRST(private_section_length_field,
1830 p - private_section_start);
1834 * Encrypt the private section. We need 48 bytes of key
1835 * material: 32 bytes AES key + 16 bytes iv.
1837 unsigned char keybuf[48];
1840 openssh_bcrypt(passphrase,
1841 bcrypt_salt, sizeof(bcrypt_salt), bcrypt_rounds,
1842 keybuf, sizeof(keybuf));
1844 ctx = aes_make_context();
1845 aes256_key(ctx, keybuf);
1846 aes_iv(ctx, keybuf + 32);
1847 aes_ssh2_encrypt_blk(ctx, private_section_start,
1848 p - private_section_start);
1849 aes_free_context(ctx);
1851 smemclr(keybuf, sizeof(keybuf));
1855 * And save it. We'll use Unix line endings just in case it's
1856 * subsequently transferred in binary mode.
1858 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1861 fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp);
1862 base64_encode(fp, outblob, p - outblob, 64);
1863 fputs("-----END OPENSSH PRIVATE KEY-----\n", fp);
1869 smemclr(outblob, maxsize);
1873 smemclr(privblob, privlen);
1877 smemclr(pubblob, publen);
1883 /* ----------------------------------------------------------------------
1884 * The switch function openssh_auto_write(), which chooses one of the
1885 * concrete OpenSSH output formats based on the key type.
1887 int openssh_auto_write(const Filename *filename, struct ssh2_userkey *key,
1891 * The old OpenSSH format supports a fixed list of key types. We
1892 * assume that anything not in that fixed list is newer, and hence
1893 * will use the new format.
1895 if (key->alg == &ssh_dss ||
1896 key->alg == &ssh_rsa ||
1897 key->alg == &ssh_ecdsa_nistp256 ||
1898 key->alg == &ssh_ecdsa_nistp384 ||
1899 key->alg == &ssh_ecdsa_nistp521)
1900 return openssh_pem_write(filename, key, passphrase);
1902 return openssh_new_write(filename, key, passphrase);
1905 /* ----------------------------------------------------------------------
1906 * Code to read ssh.com private keys.
1910 * The format of the base64 blob is largely SSH-2-packet-formatted,
1911 * except that mpints are a bit different: they're more like the
1912 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1913 * (N+7)/8 bytes of data.
1915 * So. The blob contains:
1917 * - uint32 0x3f6ff9eb (magic number)
1918 * - uint32 size (total blob size)
1919 * - string key-type (see below)
1920 * - string cipher-type (tells you if key is encrypted)
1921 * - string encrypted-blob
1923 * (The first size field includes the size field itself and the
1924 * magic number before it. All other size fields are ordinary SSH-2
1925 * strings, so the size field indicates how much data is to
1928 * The encrypted blob, once decrypted, contains a single string
1929 * which in turn contains the payload. (This allows padding to be
1930 * added after that string while still making it clear where the
1931 * real payload ends. Also it probably makes for a reasonable
1932 * decryption check.)
1934 * The payload blob, for an RSA key, contains:
1937 * - mpint n (yes, the public and private stuff is intermixed)
1938 * - mpint u (presumably inverse of p mod q)
1939 * - mpint p (p is the smaller prime)
1940 * - mpint q (q is the larger)
1942 * For a DSA key, the payload blob contains:
1950 * Alternatively, if the parameters are `predefined', that
1951 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1952 * containing some predefined parameter specification. *shudder*,
1953 * but I doubt we'll encounter this in real life.
1955 * The key type strings are ghastly. The RSA key I looked at had a
1958 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1960 * and the DSA key wasn't much better:
1962 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1964 * It isn't clear that these will always be the same. I think it
1965 * might be wise just to look at the `if-modn{sign{rsa' and
1966 * `dl-modp{sign{dsa' prefixes.
1968 * Finally, the encryption. The cipher-type string appears to be
1969 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1970 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1971 * from the passphrase by means of yet another hashing faff:
1973 * - first 16 bytes are MD5(passphrase)
1974 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1975 * - if there were more, they'd be MD5(passphrase || first 32),
1979 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1982 char comment[256]; /* allowing any length is overkill */
1983 unsigned char *keyblob;
1984 int keyblob_len, keyblob_size;
1987 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1988 const char **errmsg_p)
1990 struct sshcom_key *ret;
1998 int base64_chars = 0;
2000 ret = snew(struct sshcom_key);
2001 ret->comment[0] = '\0';
2002 ret->keyblob = NULL;
2003 ret->keyblob_len = ret->keyblob_size = 0;
2005 fp = f_open(filename, "r", FALSE);
2007 errmsg = "unable to open key file";
2010 if (!(line = fgetline(fp))) {
2011 errmsg = "unexpected end of file";
2015 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
2016 errmsg = "file does not begin with ssh.com key header";
2019 smemclr(line, strlen(line));
2025 if (!(line = fgetline(fp))) {
2026 errmsg = "unexpected end of file";
2030 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
2035 if ((p = strchr(line, ':')) != NULL) {
2037 errmsg = "header found in body of key data";
2041 while (*p && isspace((unsigned char)*p)) p++;
2042 hdrstart = p - line;
2045 * Header lines can end in a trailing backslash for
2048 len = hdrstart + strlen(line+hdrstart);
2050 while (line[len-1] == '\\') {
2054 line2 = fgetline(fp);
2056 errmsg = "unexpected end of file";
2061 line2len = strlen(line2);
2062 line = sresize(line, len + line2len + 1, char);
2063 strcpy(line + len - 1, line2);
2064 len += line2len - 1;
2067 smemclr(line2, strlen(line2));
2071 p = line + hdrstart;
2073 if (!strcmp(line, "Comment")) {
2074 /* Strip quotes in comment if present. */
2075 if (p[0] == '"' && p[strlen(p)-1] == '"') {
2077 p[strlen(p)-1] = '\0';
2079 strncpy(ret->comment, p, sizeof(ret->comment));
2080 ret->comment[sizeof(ret->comment)-1] = '\0';
2086 while (isbase64(*p)) {
2087 base64_bit[base64_chars++] = *p;
2088 if (base64_chars == 4) {
2089 unsigned char out[3];
2093 len = base64_decode_atom(base64_bit, out);
2096 errmsg = "invalid base64 encoding";
2100 if (ret->keyblob_len + len > ret->keyblob_size) {
2101 ret->keyblob_size = ret->keyblob_len + len + 256;
2102 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
2106 memcpy(ret->keyblob + ret->keyblob_len, out, len);
2107 ret->keyblob_len += len;
2113 smemclr(line, strlen(line));
2118 if (ret->keyblob_len == 0 || !ret->keyblob) {
2119 errmsg = "key body not present";
2124 if (errmsg_p) *errmsg_p = NULL;
2132 smemclr(line, strlen(line));
2138 smemclr(ret->keyblob, ret->keyblob_size);
2139 sfree(ret->keyblob);
2141 smemclr(ret, sizeof(*ret));
2144 if (errmsg_p) *errmsg_p = errmsg;
2148 int sshcom_encrypted(const Filename *filename, char **comment)
2150 struct sshcom_key *key = load_sshcom_key(filename, NULL);
2151 int pos, len, answer;
2160 * Check magic number.
2162 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
2163 goto done; /* key is invalid */
2167 * Find the cipher-type string.
2170 if (key->keyblob_len < pos+4)
2171 goto done; /* key is far too short */
2172 len = toint(GET_32BIT(key->keyblob + pos));
2173 if (len < 0 || len > key->keyblob_len - pos - 4)
2174 goto done; /* key is far too short */
2175 pos += 4 + len; /* skip key type */
2176 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
2177 if (len < 0 || len > key->keyblob_len - pos - 4)
2178 goto done; /* cipher type string is incomplete */
2179 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
2184 *comment = dupstr(key->comment);
2185 smemclr(key->keyblob, key->keyblob_size);
2186 sfree(key->keyblob);
2187 smemclr(key, sizeof(*key));
2190 *comment = dupstr("");
2195 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
2197 unsigned bits, bytes;
2198 unsigned char *d = (unsigned char *) data;
2202 bits = GET_32BIT(d);
2204 bytes = (bits + 7) / 8;
2215 return len; /* ensure further calls fail as well */
2218 static int sshcom_put_mpint(void *target, void *data, int len)
2220 unsigned char *d = (unsigned char *)target;
2221 unsigned char *i = (unsigned char *)data;
2222 int bits = len * 8 - 1;
2225 if (*i & (1 << (bits & 7)))
2231 PUT_32BIT(d, bits+1);
2232 memcpy(d+4, i, len);
2236 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
2237 const char **errmsg_p)
2239 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
2242 const char prefix_rsa[] = "if-modn{sign{rsa";
2243 const char prefix_dsa[] = "dl-modp{sign{dsa";
2244 enum { RSA, DSA } type;
2248 struct ssh2_userkey *ret = NULL, *retkey;
2249 const struct ssh_signkey *alg;
2250 unsigned char *blob = NULL;
2251 int blobsize = 0, publen, privlen;
2257 * Check magic number.
2259 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
2260 errmsg = "key does not begin with magic number";
2265 * Determine the key type.
2268 if (key->keyblob_len < pos+4 ||
2269 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2270 len > key->keyblob_len - pos - 4) {
2271 errmsg = "key blob does not contain a key type string";
2274 if (len > sizeof(prefix_rsa) - 1 &&
2275 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
2277 } else if (len > sizeof(prefix_dsa) - 1 &&
2278 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
2281 errmsg = "key is of unknown type";
2287 * Determine the cipher type.
2289 if (key->keyblob_len < pos+4 ||
2290 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2291 len > key->keyblob_len - pos - 4) {
2292 errmsg = "key blob does not contain a cipher type string";
2295 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
2297 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
2300 errmsg = "key encryption is of unknown type";
2306 * Get hold of the encrypted part of the key.
2308 if (key->keyblob_len < pos+4 ||
2309 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2310 len > key->keyblob_len - pos - 4) {
2311 errmsg = "key blob does not contain actual key data";
2314 ciphertext = (char *)key->keyblob + pos + 4;
2316 if (cipherlen == 0) {
2317 errmsg = "length of key data is zero";
2322 * Decrypt it if necessary.
2326 * Derive encryption key from passphrase and iv/salt:
2328 * - let block A equal MD5(passphrase)
2329 * - let block B equal MD5(passphrase || A)
2330 * - block C would be MD5(passphrase || A || B) and so on
2331 * - encryption key is the first N bytes of A || B
2333 struct MD5Context md5c;
2334 unsigned char keybuf[32], iv[8];
2336 if (cipherlen % 8 != 0) {
2337 errmsg = "encrypted part of key is not a multiple of cipher block"
2343 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2344 MD5Final(keybuf, &md5c);
2347 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2348 MD5Update(&md5c, keybuf, 16);
2349 MD5Final(keybuf+16, &md5c);
2352 * Now decrypt the key blob.
2354 memset(iv, 0, sizeof(iv));
2355 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2358 smemclr(&md5c, sizeof(md5c));
2359 smemclr(keybuf, sizeof(keybuf));
2362 * Hereafter we return WRONG_PASSPHRASE for any parsing
2363 * error. (But only if we've just tried to decrypt it!
2364 * Returning WRONG_PASSPHRASE for an unencrypted key is
2368 ret = SSH2_WRONG_PASSPHRASE;
2372 * Strip away the containing string to get to the real meat.
2374 len = toint(GET_32BIT(ciphertext));
2375 if (len < 0 || len > cipherlen-4) {
2376 errmsg = "containing string was ill-formed";
2383 * Now we break down into RSA versus DSA. In either case we'll
2384 * construct public and private blobs in our own format, and
2385 * end up feeding them to alg->createkey().
2387 blobsize = cipherlen + 256;
2388 blob = snewn(blobsize, unsigned char);
2391 struct mpint_pos n, e, d, u, p, q;
2393 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
2394 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
2395 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
2396 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
2397 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2398 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2400 errmsg = "key data did not contain six integers";
2406 pos += put_string(blob+pos, "ssh-rsa", 7);
2407 pos += put_mp(blob+pos, e.start, e.bytes);
2408 pos += put_mp(blob+pos, n.start, n.bytes);
2410 pos += put_string(blob+pos, d.start, d.bytes);
2411 pos += put_mp(blob+pos, q.start, q.bytes);
2412 pos += put_mp(blob+pos, p.start, p.bytes);
2413 pos += put_mp(blob+pos, u.start, u.bytes);
2414 privlen = pos - publen;
2416 struct mpint_pos p, q, g, x, y;
2419 assert(type == DSA); /* the only other option from the if above */
2421 if (GET_32BIT(ciphertext) != 0) {
2422 errmsg = "predefined DSA parameters not supported";
2425 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2426 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
2427 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2428 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
2429 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
2431 errmsg = "key data did not contain five integers";
2437 pos += put_string(blob+pos, "ssh-dss", 7);
2438 pos += put_mp(blob+pos, p.start, p.bytes);
2439 pos += put_mp(blob+pos, q.start, q.bytes);
2440 pos += put_mp(blob+pos, g.start, g.bytes);
2441 pos += put_mp(blob+pos, y.start, y.bytes);
2443 pos += put_mp(blob+pos, x.start, x.bytes);
2444 privlen = pos - publen;
2447 assert(privlen > 0); /* should have bombed by now if not */
2449 retkey = snew(struct ssh2_userkey);
2451 retkey->data = alg->createkey(alg, blob, publen, blob+publen, privlen);
2452 if (!retkey->data) {
2454 errmsg = "unable to create key data structure";
2457 retkey->comment = dupstr(key->comment);
2459 errmsg = NULL; /* no error */
2464 smemclr(blob, blobsize);
2467 smemclr(key->keyblob, key->keyblob_size);
2468 sfree(key->keyblob);
2469 smemclr(key, sizeof(*key));
2471 if (errmsg_p) *errmsg_p = errmsg;
2475 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
2478 unsigned char *pubblob, *privblob;
2479 int publen, privlen;
2480 unsigned char *outblob;
2482 struct mpint_pos numbers[6];
2483 int nnumbers, initial_zero, pos, lenpos, i;
2491 * Fetch the key blobs.
2493 pubblob = key->alg->public_blob(key->data, &publen);
2494 privblob = key->alg->private_blob(key->data, &privlen);
2498 * Find the sequence of integers to be encoded into the OpenSSH
2499 * key blob, and also decide on the header line.
2501 if (key->alg == &ssh_rsa) {
2503 struct mpint_pos n, e, d, p, q, iqmp;
2506 * These blobs were generated from inside PuTTY, so we needn't
2507 * treat them as untrusted.
2509 pos = 4 + GET_32BIT(pubblob);
2510 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
2511 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
2513 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
2514 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
2515 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
2516 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
2518 assert(e.start && iqmp.start); /* can't go wrong */
2529 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
2530 } else if (key->alg == &ssh_dss) {
2532 struct mpint_pos p, q, g, y, x;
2535 * These blobs were generated from inside PuTTY, so we needn't
2536 * treat them as untrusted.
2538 pos = 4 + GET_32BIT(pubblob);
2539 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
2540 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
2541 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
2542 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
2544 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
2546 assert(y.start && x.start); /* can't go wrong */
2556 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
2558 assert(0); /* zoinks! */
2559 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
2563 * Total size of key blob will be somewhere under 512 plus
2564 * combined length of integers. We'll calculate the more
2565 * precise size as we construct the blob.
2568 for (i = 0; i < nnumbers; i++)
2569 outlen += 4 + numbers[i].bytes;
2570 outblob = snewn(outlen, unsigned char);
2573 * Create the unencrypted key blob.
2576 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
2577 pos += 4; /* length field, fill in later */
2578 pos += put_string(outblob+pos, type, strlen(type));
2580 const char *ciphertype = passphrase ? "3des-cbc" : "none";
2581 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
2583 lenpos = pos; /* remember this position */
2584 pos += 4; /* encrypted-blob size */
2585 pos += 4; /* encrypted-payload size */
2587 PUT_32BIT(outblob+pos, 0);
2590 for (i = 0; i < nnumbers; i++)
2591 pos += sshcom_put_mpint(outblob+pos,
2592 numbers[i].start, numbers[i].bytes);
2593 /* Now wrap up the encrypted payload. */
2594 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
2595 /* Pad encrypted blob to a multiple of cipher block size. */
2597 int padding = -(pos - (lenpos+4)) & 7;
2599 outblob[pos++] = random_byte();
2601 ciphertext = (char *)outblob+lenpos+4;
2602 cipherlen = pos - (lenpos+4);
2603 assert(!passphrase || cipherlen % 8 == 0);
2604 /* Wrap up the encrypted blob string. */
2605 PUT_32BIT(outblob+lenpos, cipherlen);
2606 /* And finally fill in the total length field. */
2607 PUT_32BIT(outblob+4, pos);
2609 assert(pos < outlen);
2616 * Derive encryption key from passphrase and iv/salt:
2618 * - let block A equal MD5(passphrase)
2619 * - let block B equal MD5(passphrase || A)
2620 * - block C would be MD5(passphrase || A || B) and so on
2621 * - encryption key is the first N bytes of A || B
2623 struct MD5Context md5c;
2624 unsigned char keybuf[32], iv[8];
2627 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2628 MD5Final(keybuf, &md5c);
2631 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2632 MD5Update(&md5c, keybuf, 16);
2633 MD5Final(keybuf+16, &md5c);
2636 * Now decrypt the key blob.
2638 memset(iv, 0, sizeof(iv));
2639 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2642 smemclr(&md5c, sizeof(md5c));
2643 smemclr(keybuf, sizeof(keybuf));
2647 * And save it. We'll use Unix line endings just in case it's
2648 * subsequently transferred in binary mode.
2650 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
2653 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2654 fprintf(fp, "Comment: \"");
2656 * Comment header is broken with backslash-newline if it goes
2657 * over 70 chars. Although it's surrounded by quotes, it
2658 * _doesn't_ escape backslashes or quotes within the string.
2659 * Don't ask me, I didn't design it.
2662 int slen = 60; /* starts at 60 due to "Comment: " */
2663 char *c = key->comment;
2664 while ((int)strlen(c) > slen) {
2665 fprintf(fp, "%.*s\\\n", slen, c);
2667 slen = 70; /* allow 70 chars on subsequent lines */
2669 fprintf(fp, "%s\"\n", c);
2671 base64_encode(fp, outblob, pos, 70);
2672 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2678 smemclr(outblob, outlen);
2682 smemclr(privblob, privlen);
2686 smemclr(pubblob, publen);