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_pem_write(const Filename *filename, struct ssh2_userkey *key,
25 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
28 int sshcom_encrypted(const Filename *filename, char **comment);
29 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
30 const char **errmsg_p);
31 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
35 * Given a key type, determine whether we know how to import it.
37 int import_possible(int type)
39 if (type == SSH_KEYTYPE_OPENSSH_PEM)
41 if (type == SSH_KEYTYPE_OPENSSH_NEW)
43 if (type == SSH_KEYTYPE_SSHCOM)
49 * Given a key type, determine what native key type
50 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
53 int import_target_type(int type)
56 * There are no known foreign SSH-1 key formats.
58 return SSH_KEYTYPE_SSH2;
62 * Determine whether a foreign key is encrypted.
64 int import_encrypted(const Filename *filename, int type, char **comment)
66 if (type == SSH_KEYTYPE_OPENSSH_PEM) {
67 /* OpenSSH PEM format doesn't contain a key comment at all */
68 *comment = dupstr(filename_to_str(filename));
69 return openssh_pem_encrypted(filename);
70 } else if (type == SSH_KEYTYPE_OPENSSH_NEW) {
71 /* OpenSSH new format does, but it's inside the encrypted
72 * section for some reason */
73 *comment = dupstr(filename_to_str(filename));
74 return openssh_new_encrypted(filename);
75 } else if (type == SSH_KEYTYPE_SSHCOM) {
76 return sshcom_encrypted(filename, comment);
82 * Import an SSH-1 key.
84 int import_ssh1(const Filename *filename, int type,
85 struct RSAKey *key, char *passphrase, const char **errmsg_p)
91 * Import an SSH-2 key.
93 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
94 char *passphrase, const char **errmsg_p)
96 if (type == SSH_KEYTYPE_OPENSSH_PEM)
97 return openssh_pem_read(filename, passphrase, errmsg_p);
98 else if (type == SSH_KEYTYPE_OPENSSH_NEW)
99 return openssh_new_read(filename, passphrase, errmsg_p);
100 if (type == SSH_KEYTYPE_SSHCOM)
101 return sshcom_read(filename, passphrase, errmsg_p);
106 * Export an SSH-1 key.
108 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
115 * Export an SSH-2 key.
117 int export_ssh2(const Filename *filename, int type,
118 struct ssh2_userkey *key, char *passphrase)
120 if (type == SSH_KEYTYPE_OPENSSH_PEM)
121 return openssh_pem_write(filename, key, passphrase);
122 if (type == SSH_KEYTYPE_OPENSSH_NEW)
123 return openssh_new_write(filename, key, passphrase);
124 if (type == SSH_KEYTYPE_SSHCOM)
125 return sshcom_write(filename, key, passphrase);
130 * Strip trailing CRs and LFs at the end of a line of text.
132 void strip_crlf(char *str)
134 char *p = str + strlen(str);
136 while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
140 /* ----------------------------------------------------------------------
141 * Helper routines. (The base64 ones are defined in sshpubk.c.)
144 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
145 ((c) >= 'a' && (c) <= 'z') || \
146 ((c) >= '0' && (c) <= '9') || \
147 (c) == '+' || (c) == '/' || (c) == '=' \
151 * Read an ASN.1/BER identifier and length pair.
153 * Flags are a combination of the #defines listed below.
155 * Returns -1 if unsuccessful; otherwise returns the number of
156 * bytes used out of the source data.
159 /* ASN.1 tag classes. */
160 #define ASN1_CLASS_UNIVERSAL (0 << 6)
161 #define ASN1_CLASS_APPLICATION (1 << 6)
162 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
163 #define ASN1_CLASS_PRIVATE (3 << 6)
164 #define ASN1_CLASS_MASK (3 << 6)
166 /* Primitive versus constructed bit. */
167 #define ASN1_CONSTRUCTED (1 << 5)
169 static int ber_read_id_len(void *source, int sourcelen,
170 int *id, int *length, int *flags)
172 unsigned char *p = (unsigned char *) source;
177 *flags = (*p & 0xE0);
178 if ((*p & 0x1F) == 0x1F) {
184 *id = (*id << 7) | (*p & 0x7F);
202 *length = (*length << 8) | (*p++);
209 return p - (unsigned char *) source;
213 * Write an ASN.1/BER identifier and length pair. Returns the
214 * number of bytes consumed. Assumes dest contains enough space.
215 * Will avoid writing anything if dest is NULL, but still return
216 * amount of space required.
218 static int ber_write_id_len(void *dest, int id, int length, int flags)
220 unsigned char *d = (unsigned char *)dest;
225 * Identifier is one byte.
228 if (d) *d++ = id | flags;
232 * Identifier is multiple bytes: the first byte is 11111
233 * plus the flags, and subsequent bytes encode the value of
234 * the identifier, 7 bits at a time, with the top bit of
235 * each byte 1 except the last one which is 0.
238 if (d) *d++ = 0x1F | flags;
239 for (n = 1; (id >> (7*n)) > 0; n++)
240 continue; /* count the bytes */
243 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
249 * Length is one byte.
252 if (d) *d++ = length;
256 * Length is multiple bytes. The first is 0x80 plus the
257 * number of subsequent bytes, and the subsequent bytes
258 * encode the actual length.
260 for (n = 1; (length >> (8*n)) > 0; n++)
261 continue; /* count the bytes */
263 if (d) *d++ = 0x80 | n;
266 if (d) *d++ = (length >> (8*n)) & 0xFF;
273 static int put_uint32(void *target, unsigned val)
275 unsigned char *d = (unsigned char *)target;
281 static int put_string(void *target, const void *data, int len)
283 unsigned char *d = (unsigned char *)target;
286 memcpy(d+4, data, len);
290 static int put_string_z(void *target, const char *string)
292 return put_string(target, string, strlen(string));
295 static int put_mp(void *target, void *data, int len)
297 unsigned char *d = (unsigned char *)target;
298 unsigned char *i = (unsigned char *)data;
303 memcpy(d+5, data, len);
307 memcpy(d+4, data, len);
312 /* Simple structure to point to an mp-int within a blob. */
313 struct mpint_pos { void *start; int bytes; };
315 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
318 unsigned char *d = (unsigned char *) data;
322 bytes = toint(GET_32BIT(d));
323 if (bytes < 0 || len-4 < bytes)
333 return len; /* ensure further calls fail as well */
336 /* ----------------------------------------------------------------------
337 * Code to read and write OpenSSH private keys, in the old-style PEM
342 OP_DSA, OP_RSA, OP_ECDSA
343 } openssh_pem_keytype;
348 struct openssh_pem_key {
349 openssh_pem_keytype keytype;
351 openssh_pem_enc encryption;
353 unsigned char *keyblob;
354 int keyblob_len, keyblob_size;
357 static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename,
358 const char **errmsg_p)
360 struct openssh_pem_key *ret;
366 int base64_chars = 0;
368 ret = snew(struct openssh_pem_key);
370 ret->keyblob_len = ret->keyblob_size = 0;
372 fp = f_open(filename, "r", FALSE);
374 errmsg = "unable to open key file";
378 if (!(line = fgetline(fp))) {
379 errmsg = "unexpected end of file";
383 if (0 != strncmp(line, "-----BEGIN ", 11) ||
384 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
385 errmsg = "file does not begin with OpenSSH key header";
389 * Parse the BEGIN line. For old-format keys, this tells us the
390 * type of the key; for new-format keys, all it tells us is the
391 * format, and we'll find out the key type once we parse the
394 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) {
395 ret->keytype = OP_RSA;
396 } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) {
397 ret->keytype = OP_DSA;
398 } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) {
399 ret->keytype = OP_ECDSA;
400 } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
401 errmsg = "this is a new-style OpenSSH key";
404 errmsg = "unrecognised key type";
407 smemclr(line, strlen(line));
411 ret->encrypted = FALSE;
412 memset(ret->iv, 0, sizeof(ret->iv));
416 if (!(line = fgetline(fp))) {
417 errmsg = "unexpected end of file";
421 if (0 == strncmp(line, "-----END ", 9) &&
422 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
427 if ((p = strchr(line, ':')) != NULL) {
429 errmsg = "header found in body of key data";
433 while (*p && isspace((unsigned char)*p)) p++;
434 if (!strcmp(line, "Proc-Type")) {
435 if (p[0] != '4' || p[1] != ',') {
436 errmsg = "Proc-Type is not 4 (only 4 is supported)";
440 if (!strcmp(p, "ENCRYPTED"))
441 ret->encrypted = TRUE;
442 } else if (!strcmp(line, "DEK-Info")) {
445 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
446 ret->encryption = OP_E_3DES;
448 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
449 ret->encryption = OP_E_AES;
452 errmsg = "unsupported cipher";
455 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
456 for (i = 0; i < ivlen; i++) {
457 if (1 != sscanf(p, "%2x", &j)) {
458 errmsg = "expected more iv data in DEK-Info";
465 errmsg = "more iv data than expected in DEK-Info";
473 while (isbase64(*p)) {
474 base64_bit[base64_chars++] = *p;
475 if (base64_chars == 4) {
476 unsigned char out[3];
481 len = base64_decode_atom(base64_bit, out);
484 errmsg = "invalid base64 encoding";
488 if (ret->keyblob_len + len > ret->keyblob_size) {
489 ret->keyblob_size = ret->keyblob_len + len + 256;
490 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
494 memcpy(ret->keyblob + ret->keyblob_len, out, len);
495 ret->keyblob_len += len;
497 smemclr(out, sizeof(out));
503 smemclr(line, strlen(line));
511 if (ret->keyblob_len == 0 || !ret->keyblob) {
512 errmsg = "key body not present";
516 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
517 errmsg = "encrypted key blob is not a multiple of "
522 smemclr(base64_bit, sizeof(base64_bit));
523 if (errmsg_p) *errmsg_p = NULL;
528 smemclr(line, strlen(line));
532 smemclr(base64_bit, sizeof(base64_bit));
535 smemclr(ret->keyblob, ret->keyblob_size);
538 smemclr(ret, sizeof(*ret));
541 if (errmsg_p) *errmsg_p = errmsg;
546 int openssh_pem_encrypted(const Filename *filename)
548 struct openssh_pem_key *key = load_openssh_pem_key(filename, NULL);
553 ret = key->encrypted;
554 smemclr(key->keyblob, key->keyblob_size);
556 smemclr(key, sizeof(*key));
561 struct ssh2_userkey *openssh_pem_read(const Filename *filename,
563 const char **errmsg_p)
565 struct openssh_pem_key *key = load_openssh_pem_key(filename, errmsg_p);
566 struct ssh2_userkey *retkey;
568 int ret, id, len, flags;
570 struct ssh2_userkey *retval = NULL;
573 int blobsize = 0, blobptr, privptr;
582 if (key->encrypted) {
584 * Derive encryption key from passphrase and iv/salt:
586 * - let block A equal MD5(passphrase || iv)
587 * - let block B equal MD5(A || passphrase || iv)
588 * - block C would be MD5(B || passphrase || iv) and so on
589 * - encryption key is the first N bytes of A || B
591 * (Note that only 8 bytes of the iv are used for key
592 * derivation, even when the key is encrypted with AES and
593 * hence there are 16 bytes available.)
595 struct MD5Context md5c;
596 unsigned char keybuf[32];
599 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
600 MD5Update(&md5c, (unsigned char *)key->iv, 8);
601 MD5Final(keybuf, &md5c);
604 MD5Update(&md5c, keybuf, 16);
605 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
606 MD5Update(&md5c, (unsigned char *)key->iv, 8);
607 MD5Final(keybuf+16, &md5c);
610 * Now decrypt the key blob.
612 if (key->encryption == OP_E_3DES)
613 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
614 key->keyblob, key->keyblob_len);
617 assert(key->encryption == OP_E_AES);
618 ctx = aes_make_context();
619 aes128_key(ctx, keybuf);
620 aes_iv(ctx, (unsigned char *)key->iv);
621 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
622 aes_free_context(ctx);
625 smemclr(&md5c, sizeof(md5c));
626 smemclr(keybuf, sizeof(keybuf));
630 * Now we have a decrypted key blob, which contains an ASN.1
631 * encoded private key. We must now untangle the ASN.1.
633 * We expect the whole key blob to be formatted as a SEQUENCE
634 * (0x30 followed by a length code indicating that the rest of
635 * the blob is part of the sequence). Within that SEQUENCE we
636 * expect to see a bunch of INTEGERs. What those integers mean
637 * depends on the key type:
639 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
640 * dmp1, dmq1, iqmp in that order. (The last three are d mod
641 * (p-1), d mod (q-1), inverse of q mod p respectively.)
643 * - For DSA, we expect them to be 0, p, q, g, y, x in that
646 * - In ECDSA the format is totally different: we see the
647 * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
648 * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
653 /* Expect the SEQUENCE header. Take its absence as a failure to
654 * decrypt, if the key was encrypted. */
655 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
657 if (ret < 0 || id != 16) {
658 errmsg = "ASN.1 decoding failure";
659 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
663 /* Expect a load of INTEGERs. */
664 if (key->keytype == OP_RSA)
666 else if (key->keytype == OP_DSA)
669 num_integers = 0; /* placate compiler warnings */
672 if (key->keytype == OP_ECDSA) {
673 /* And now for something completely different */
676 struct ec_curve *curve;
678 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
681 if (ret < 0 || id != 2 || key->keyblob+key->keyblob_len-p < len ||
682 len != 1 || p[0] != 1) {
683 errmsg = "ASN.1 decoding failure";
684 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
688 /* Read private key OCTET STRING */
689 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
692 if (ret < 0 || id != 4 || key->keyblob+key->keyblob_len-p < len) {
693 errmsg = "ASN.1 decoding failure";
694 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
701 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
704 if (ret < 0 || id != 0 || key->keyblob+key->keyblob_len-p < len) {
705 errmsg = "ASN.1 decoding failure";
706 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
709 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
712 if (ret < 0 || id != 6 || key->keyblob+key->keyblob_len-p < len) {
713 errmsg = "ASN.1 decoding failure";
714 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
717 if (len == 8 && !memcmp(p, nistp256_oid, nistp256_oid_len)) {
719 } else if (len == 5 && !memcmp(p, nistp384_oid,
722 } else if (len == 5 && !memcmp(p, nistp521_oid,
726 errmsg = "Unsupported ECDSA curve.";
731 /* Read BIT STRING point */
732 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
735 if (ret < 0 || id != 1 || key->keyblob+key->keyblob_len-p < len) {
736 errmsg = "ASN.1 decoding failure";
737 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
740 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
743 if (ret < 0 || id != 3 || key->keyblob+key->keyblob_len-p < len ||
744 len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
745 errmsg = "ASN.1 decoding failure";
746 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
749 p += 1; len -= 1; /* Skip 0x00 before point */
751 /* Construct the key */
752 retkey = snew(struct ssh2_userkey);
754 errmsg = "out of memory";
757 if (curve->fieldBits == 256) {
758 retkey->alg = &ssh_ecdsa_nistp256;
759 } else if (curve->fieldBits == 384) {
760 retkey->alg = &ssh_ecdsa_nistp384;
762 retkey->alg = &ssh_ecdsa_nistp521;
764 blob = snewn((4+19 + 4+8 + 4+len) + (4+privlen), unsigned char);
767 errmsg = "out of memory";
771 sprintf((char*)blob+4, "ecdsa-sha2-nistp%d", curve->fieldBits);
772 PUT_32BIT(blob+4+19, 8);
773 sprintf((char*)blob+4+19+4, "nistp%d", curve->fieldBits);
774 PUT_32BIT(blob+4+19+4+8, len);
775 memcpy(blob+4+19+4+8+4, p, len);
776 PUT_32BIT(blob+4+19+4+8+4+len, privlen);
777 memcpy(blob+4+19+4+8+4+len+4, priv, privlen);
778 retkey->data = retkey->alg->createkey(blob, 4+19+4+8+4+len,
783 errmsg = "unable to create key data structure";
787 } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
790 * Space to create key blob in.
792 blobsize = 256+key->keyblob_len;
793 blob = snewn(blobsize, unsigned char);
795 if (key->keytype == OP_DSA)
796 memcpy(blob+4, "ssh-dss", 7);
797 else if (key->keytype == OP_RSA)
798 memcpy(blob+4, "ssh-rsa", 7);
802 for (i = 0; i < num_integers; i++) {
803 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
806 if (ret < 0 || id != 2 ||
807 key->keyblob+key->keyblob_len-p < len) {
808 errmsg = "ASN.1 decoding failure";
809 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
815 * The first integer should be zero always (I think
816 * this is some sort of version indication).
818 if (len != 1 || p[0] != 0) {
819 errmsg = "version number mismatch";
822 } else if (key->keytype == OP_RSA) {
824 * Integers 1 and 2 go into the public blob but in the
825 * opposite order; integers 3, 4, 5 and 8 go into the
826 * private blob. The other two (6 and 7) are ignored.
829 /* Save the details for after we deal with number 2. */
832 } else if (i != 6 && i != 7) {
833 PUT_32BIT(blob+blobptr, len);
834 memcpy(blob+blobptr+4, p, len);
837 PUT_32BIT(blob+blobptr, modlen);
838 memcpy(blob+blobptr+4, modptr, modlen);
843 } else if (key->keytype == OP_DSA) {
845 * Integers 1-4 go into the public blob; integer 5 goes
846 * into the private blob.
848 PUT_32BIT(blob+blobptr, len);
849 memcpy(blob+blobptr+4, p, len);
855 /* Skip past the number. */
860 * Now put together the actual key. Simplest way to do this is
861 * to assemble our own key blobs and feed them to the createkey
862 * functions; this is a bit faffy but it does mean we get all
863 * the sanity checks for free.
865 assert(privptr > 0); /* should have bombed by now if not */
866 retkey = snew(struct ssh2_userkey);
867 retkey->alg = (key->keytype == OP_RSA ? &ssh_rsa : &ssh_dss);
868 retkey->data = retkey->alg->createkey(blob, privptr,
873 errmsg = "unable to create key data structure";
878 assert(0 && "Bad key type from load_openssh_pem_key");
882 * The old key format doesn't include a comment in the private
885 retkey->comment = dupstr("imported-openssh-key");
887 errmsg = NULL; /* no error */
892 smemclr(blob, blobsize);
895 smemclr(key->keyblob, key->keyblob_size);
897 smemclr(key, sizeof(*key));
899 if (errmsg_p) *errmsg_p = errmsg;
903 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
906 unsigned char *pubblob, *privblob, *spareblob;
907 int publen, privlen, sparelen = 0;
908 unsigned char *outblob;
910 struct mpint_pos numbers[9];
911 int nnumbers, pos, len, seqlen, i;
912 char *header, *footer;
919 * Fetch the key blobs.
921 pubblob = key->alg->public_blob(key->data, &publen);
922 privblob = key->alg->private_blob(key->data, &privlen);
923 spareblob = outblob = NULL;
929 * Encode the OpenSSH key blob, and also decide on the header
932 if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
934 * The RSA and DSS handlers share some code because the two
935 * key types have very similar ASN.1 representations, as a
936 * plain SEQUENCE of big integers. So we set up a list of
937 * bignums per key type and then construct the actual blob in
938 * common code after that.
940 if (key->alg == &ssh_rsa) {
942 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
943 Bignum bd, bp, bq, bdmp1, bdmq1;
946 * These blobs were generated from inside PuTTY, so we needn't
947 * treat them as untrusted.
949 pos = 4 + GET_32BIT(pubblob);
950 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
951 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
953 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
954 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
955 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
956 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
958 assert(e.start && iqmp.start); /* can't go wrong */
960 /* We also need d mod (p-1) and d mod (q-1). */
961 bd = bignum_from_bytes(d.start, d.bytes);
962 bp = bignum_from_bytes(p.start, p.bytes);
963 bq = bignum_from_bytes(q.start, q.bytes);
966 bdmp1 = bigmod(bd, bp);
967 bdmq1 = bigmod(bd, bq);
972 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
973 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
974 sparelen = dmp1.bytes + dmq1.bytes;
975 spareblob = snewn(sparelen, unsigned char);
976 dmp1.start = spareblob;
977 dmq1.start = spareblob + dmp1.bytes;
978 for (i = 0; i < dmp1.bytes; i++)
979 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
980 for (i = 0; i < dmq1.bytes; i++)
981 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
985 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
996 header = "-----BEGIN RSA PRIVATE KEY-----\n";
997 footer = "-----END RSA PRIVATE KEY-----\n";
998 } else { /* ssh-dss */
1000 struct mpint_pos p, q, g, y, x;
1003 * These blobs were generated from inside PuTTY, so we needn't
1004 * treat them as untrusted.
1006 pos = 4 + GET_32BIT(pubblob);
1007 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1008 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1009 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1010 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1012 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1014 assert(y.start && x.start); /* can't go wrong */
1016 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1024 header = "-----BEGIN DSA PRIVATE KEY-----\n";
1025 footer = "-----END DSA PRIVATE KEY-----\n";
1029 * Now count up the total size of the ASN.1 encoded integers,
1030 * so as to determine the length of the containing SEQUENCE.
1033 for (i = 0; i < nnumbers; i++) {
1034 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
1035 len += numbers[i].bytes;
1038 /* Now add on the SEQUENCE header. */
1039 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1042 * Now we know how big outblob needs to be. Allocate it.
1044 outblob = snewn(len, unsigned char);
1047 * And write the data into it.
1050 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1051 for (i = 0; i < nnumbers; i++) {
1052 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
1053 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
1054 pos += numbers[i].bytes;
1056 } else if (key->alg == &ssh_ecdsa_nistp256 ||
1057 key->alg == &ssh_ecdsa_nistp384 ||
1058 key->alg == &ssh_ecdsa_nistp521) {
1064 * Structure of asn1:
1067 * OCTET STRING (private key)
1071 * BIT STRING (0x00 public key point)
1073 switch (((struct ec_key *)key->data)->publicKey.curve->fieldBits) {
1075 /* OID: 1.2.840.10045.3.1.7 (ansiX9p256r1) */
1077 oidlen = nistp256_oid_len;
1081 /* OID: 1.3.132.0.34 (secp384r1) */
1083 oidlen = nistp384_oid_len;
1087 /* OID: 1.3.132.0.35 (secp521r1) */
1089 oidlen = nistp521_oid_len;
1096 len = ber_write_id_len(NULL, 2, 1, 0);
1098 len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1100 len += ber_write_id_len(NULL, 0, oidlen +
1101 ber_write_id_len(NULL, 6, oidlen, 0),
1102 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1103 len += ber_write_id_len(NULL, 6, oidlen, 0);
1105 len += ber_write_id_len(NULL, 1, 2 + pointlen +
1106 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1107 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1108 len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1109 len += 2 + pointlen;
1112 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1114 outblob = snewn(len, unsigned char);
1118 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1119 pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1121 pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1122 memcpy(outblob+pos, privblob + 4, privlen - 4);
1124 pos += ber_write_id_len(outblob+pos, 0, oidlen +
1125 ber_write_id_len(NULL, 6, oidlen, 0),
1126 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1127 pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1128 memcpy(outblob+pos, oid, oidlen);
1130 pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1131 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1132 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1133 pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1135 memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1136 pos += 1 + pointlen;
1138 header = "-----BEGIN EC PRIVATE KEY-----\n";
1139 footer = "-----END EC PRIVATE KEY-----\n";
1141 assert(0); /* zoinks! */
1142 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1148 * For the moment, we still encrypt our OpenSSH keys using
1152 struct MD5Context md5c;
1153 unsigned char keybuf[32];
1156 * Round up to the cipher block size, ensuring we have at
1157 * least one byte of padding (see below).
1159 outlen = (len+8) &~ 7;
1161 unsigned char *tmp = snewn(outlen, unsigned char);
1162 memcpy(tmp, outblob, len);
1163 smemclr(outblob, len);
1169 * Padding on OpenSSH keys is deterministic. The number of
1170 * padding bytes is always more than zero, and always at most
1171 * the cipher block length. The value of each padding byte is
1172 * equal to the number of padding bytes. So a plaintext that's
1173 * an exact multiple of the block size will be padded with 08
1174 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1175 * plaintext one byte less than a multiple of the block size
1176 * will be padded with just 01.
1178 * This enables the OpenSSL key decryption function to strip
1179 * off the padding algorithmically and return the unpadded
1180 * plaintext to the next layer: it looks at the final byte, and
1181 * then expects to find that many bytes at the end of the data
1182 * with the same value. Those are all removed and the rest is
1186 while (pos < outlen) {
1187 outblob[pos++] = outlen - len;
1191 * Invent an iv. Then derive encryption key from passphrase
1194 * - let block A equal MD5(passphrase || iv)
1195 * - let block B equal MD5(A || passphrase || iv)
1196 * - block C would be MD5(B || passphrase || iv) and so on
1197 * - encryption key is the first N bytes of A || B
1199 for (i = 0; i < 8; i++) iv[i] = random_byte();
1202 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1203 MD5Update(&md5c, iv, 8);
1204 MD5Final(keybuf, &md5c);
1207 MD5Update(&md5c, keybuf, 16);
1208 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1209 MD5Update(&md5c, iv, 8);
1210 MD5Final(keybuf+16, &md5c);
1213 * Now encrypt the key blob.
1215 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1217 smemclr(&md5c, sizeof(md5c));
1218 smemclr(keybuf, sizeof(keybuf));
1221 * If no encryption, the blob has exactly its original
1228 * And save it. We'll use Unix line endings just in case it's
1229 * subsequently transferred in binary mode.
1231 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1236 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1237 for (i = 0; i < 8; i++)
1238 fprintf(fp, "%02X", iv[i]);
1239 fprintf(fp, "\n\n");
1241 base64_encode(fp, outblob, outlen, 64);
1248 smemclr(outblob, outlen);
1252 smemclr(spareblob, sparelen);
1256 smemclr(privblob, privlen);
1260 smemclr(pubblob, publen);
1266 /* ----------------------------------------------------------------------
1267 * Code to read and write OpenSSH private keys in the new-style format.
1271 ON_E_NONE, ON_E_AES256CBC
1272 } openssh_new_cipher;
1274 ON_K_NONE, ON_K_BCRYPT
1277 struct openssh_new_key {
1278 openssh_new_cipher cipher;
1279 openssh_new_kdf kdf;
1283 /* This points to a position within keyblob, not a
1284 * separately allocated thing */
1285 const unsigned char *salt;
1289 int nkeys, key_wanted;
1290 /* This too points to a position within keyblob */
1291 unsigned char *privatestr;
1294 unsigned char *keyblob;
1295 int keyblob_len, keyblob_size;
1298 static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
1299 const char **errmsg_p)
1301 struct openssh_new_key *ret;
1306 int base64_chars = 0;
1307 const void *filedata;
1309 const void *string, *kdfopts, *bcryptsalt, *pubkey;
1310 int stringlen, kdfoptlen, bcryptsaltlen, pubkeylen;
1311 unsigned bcryptrounds, nkeys, key_index;
1313 ret = snew(struct openssh_new_key);
1314 ret->keyblob = NULL;
1315 ret->keyblob_len = ret->keyblob_size = 0;
1317 fp = f_open(filename, "r", FALSE);
1319 errmsg = "unable to open key file";
1323 if (!(line = fgetline(fp))) {
1324 errmsg = "unexpected end of file";
1328 if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
1329 errmsg = "file does not begin with OpenSSH new-style key header";
1332 smemclr(line, strlen(line));
1337 if (!(line = fgetline(fp))) {
1338 errmsg = "unexpected end of file";
1342 if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
1349 while (isbase64(*p)) {
1350 base64_bit[base64_chars++] = *p;
1351 if (base64_chars == 4) {
1352 unsigned char out[3];
1357 len = base64_decode_atom(base64_bit, out);
1360 errmsg = "invalid base64 encoding";
1364 if (ret->keyblob_len + len > ret->keyblob_size) {
1365 ret->keyblob_size = ret->keyblob_len + len + 256;
1366 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1370 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1371 ret->keyblob_len += len;
1373 smemclr(out, sizeof(out));
1378 smemclr(line, strlen(line));
1386 if (ret->keyblob_len == 0 || !ret->keyblob) {
1387 errmsg = "key body not present";
1391 filedata = ret->keyblob;
1392 filelen = ret->keyblob_len;
1394 if (filelen < 15 || 0 != memcmp(filedata, "openssh-key-v1\0", 15)) {
1395 errmsg = "new-style OpenSSH magic number missing\n";
1398 filedata = (const char *)filedata + 15;
1401 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1402 errmsg = "encountered EOF before cipher name\n";
1405 if (match_ssh_id(stringlen, string, "none")) {
1406 ret->cipher = ON_E_NONE;
1407 } else if (match_ssh_id(stringlen, string, "aes256-cbc")) {
1408 ret->cipher = ON_E_AES256CBC;
1410 errmsg = "unrecognised cipher name\n";
1414 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1415 errmsg = "encountered EOF before kdf name\n";
1418 if (match_ssh_id(stringlen, string, "none")) {
1419 ret->kdf = ON_K_NONE;
1420 } else if (match_ssh_id(stringlen, string, "bcrypt")) {
1421 ret->kdf = ON_K_BCRYPT;
1423 errmsg = "unrecognised kdf name\n";
1427 if (!(kdfopts = get_ssh_string(&filelen, &filedata, &kdfoptlen))) {
1428 errmsg = "encountered EOF before kdf options\n";
1433 if (kdfoptlen != 0) {
1434 errmsg = "expected empty options string for 'none' kdf";
1439 if (!(bcryptsalt = get_ssh_string(&kdfoptlen, &kdfopts,
1441 errmsg = "bcrypt options string did not contain salt\n";
1444 if (!get_ssh_uint32(&kdfoptlen, &kdfopts, &bcryptrounds)) {
1445 errmsg = "bcrypt options string did not contain round count\n";
1448 ret->kdfopts.bcrypt.salt = bcryptsalt;
1449 ret->kdfopts.bcrypt.saltlen = bcryptsaltlen;
1450 ret->kdfopts.bcrypt.rounds = bcryptrounds;
1455 * At this point we expect a uint32 saying how many keys are
1456 * stored in this file. OpenSSH new-style key files can
1457 * contain more than one. Currently we don't have any user
1458 * interface to specify which one we're trying to extract, so
1459 * we just bomb out with an error if more than one is found in
1460 * the file. However, I've put in all the mechanism here to
1461 * extract the nth one for a given n, in case we later connect
1462 * up some UI to that mechanism. Just arrange that the
1463 * 'key_wanted' field is set to a value in the range [0,
1464 * nkeys) by some mechanism.
1466 if (!get_ssh_uint32(&filelen, &filedata, &nkeys)) {
1467 errmsg = "encountered EOF before key count\n";
1471 errmsg = "multiple keys in new-style OpenSSH key file "
1476 ret->key_wanted = 0;
1478 for (key_index = 0; key_index < nkeys; key_index++) {
1479 if (!(pubkey = get_ssh_string(&filelen, &filedata, &pubkeylen))) {
1480 errmsg = "encountered EOF before kdf options\n";
1486 * Now we expect a string containing the encrypted part of the
1489 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1490 errmsg = "encountered EOF before private key container\n";
1493 ret->privatestr = (unsigned char *)string;
1494 ret->privatelen = stringlen;
1497 * And now we're done, until asked to actually decrypt.
1500 smemclr(base64_bit, sizeof(base64_bit));
1501 if (errmsg_p) *errmsg_p = NULL;
1506 smemclr(line, strlen(line));
1510 smemclr(base64_bit, sizeof(base64_bit));
1513 smemclr(ret->keyblob, ret->keyblob_size);
1514 sfree(ret->keyblob);
1516 smemclr(ret, sizeof(*ret));
1519 if (errmsg_p) *errmsg_p = errmsg;
1524 int openssh_new_encrypted(const Filename *filename)
1526 struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
1531 ret = (key->cipher != ON_E_NONE);
1532 smemclr(key->keyblob, key->keyblob_size);
1533 sfree(key->keyblob);
1534 smemclr(key, sizeof(*key));
1539 struct ssh2_userkey *openssh_new_read(const Filename *filename,
1541 const char **errmsg_p)
1543 struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
1544 struct ssh2_userkey *retkey;
1546 struct ssh2_userkey *retval = NULL;
1548 unsigned char *blob;
1550 unsigned checkint0, checkint1;
1551 const void *priv, *string;
1552 int privlen, stringlen, key_index;
1553 const struct ssh_signkey *alg;
1560 if (key->cipher != ON_E_NONE) {
1561 unsigned char keybuf[48];
1565 * Construct the decryption key, and decrypt the string.
1567 switch (key->cipher) {
1571 case ON_E_AES256CBC:
1572 keysize = 48; /* 32 byte key + 16 byte IV */
1575 assert(0 && "Bad cipher enumeration value");
1577 assert(keysize <= sizeof(keybuf));
1580 memset(keybuf, 0, keysize);
1583 openssh_bcrypt(passphrase,
1584 key->kdfopts.bcrypt.salt,
1585 key->kdfopts.bcrypt.saltlen,
1586 key->kdfopts.bcrypt.rounds,
1590 assert(0 && "Bad kdf enumeration value");
1592 switch (key->cipher) {
1595 case ON_E_AES256CBC:
1596 if (key->privatelen % 16 != 0) {
1597 errmsg = "private key container length is not a"
1598 " multiple of AES block size\n";
1602 void *ctx = aes_make_context();
1603 aes256_key(ctx, keybuf);
1604 aes_iv(ctx, keybuf + 32);
1605 aes_ssh2_decrypt_blk(ctx, key->privatestr,
1607 aes_free_context(ctx);
1611 assert(0 && "Bad cipher enumeration value");
1616 * Now parse the entire encrypted section, and extract the key
1617 * identified by key_wanted.
1619 priv = key->privatestr;
1620 privlen = key->privatelen;
1622 if (!get_ssh_uint32(&privlen, &priv, &checkint0) ||
1623 !get_ssh_uint32(&privlen, &priv, &checkint1) ||
1624 checkint0 != checkint1) {
1625 errmsg = "decryption check failed";
1630 for (key_index = 0; key_index < key->nkeys; key_index++) {
1631 const unsigned char *thiskey;
1635 * Read the key type, which will tell us how to scan over
1636 * the key to get to the next one.
1638 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1639 errmsg = "expected key type in private string";
1644 * Preliminary key type identification, and decide how
1645 * many pieces of key we expect to see. Currently
1646 * (conveniently) all key types can be seen as some number
1647 * of strings, so we just need to know how many of them to
1648 * skip over. (The numbers below exclude the key comment.)
1651 /* find_pubkey_alg needs a zero-terminated copy of the
1653 char *name_zt = dupprintf("%.*s", stringlen, (char *)string);
1654 alg = find_pubkey_alg(name_zt);
1659 errmsg = "private key type not recognised\n";
1666 * Skip over the pieces of key.
1668 for (i = 0; i < alg->openssh_private_npieces; i++) {
1669 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1670 errmsg = "ran out of data in mid-private-key";
1675 thiskeylen = (int)((const unsigned char *)priv -
1676 (const unsigned char *)thiskey);
1677 if (key_index == key->key_wanted) {
1678 retkey = snew(struct ssh2_userkey);
1680 retkey->data = alg->openssh_createkey(&thiskey, &thiskeylen);
1681 if (!retkey->data) {
1683 errmsg = "unable to create key data structure";
1689 * Read the key comment.
1691 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1692 errmsg = "ran out of data at key comment";
1695 if (key_index == key->key_wanted) {
1697 retkey->comment = dupprintf("%.*s", stringlen,
1698 (const char *)string);
1703 errmsg = "key index out of range";
1708 * Now we expect nothing left but padding.
1710 for (i = 0; i < privlen; i++) {
1711 if (((const unsigned char *)priv)[i] != (unsigned char)(i+1)) {
1712 errmsg = "padding at end of private string did not match";
1717 errmsg = NULL; /* no error */
1722 smemclr(blob, blobsize);
1725 smemclr(key->keyblob, key->keyblob_size);
1726 sfree(key->keyblob);
1727 smemclr(key, sizeof(*key));
1729 if (errmsg_p) *errmsg_p = errmsg;
1733 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
1736 unsigned char *pubblob, *privblob, *outblob, *p;
1737 unsigned char *private_section_start, *private_section_length_field;
1738 int publen, privlen, commentlen, maxsize, padvalue, i;
1741 unsigned char bcrypt_salt[16];
1742 const int bcrypt_rounds = 16;
1746 * Fetch the key blobs and find out the lengths of things.
1748 pubblob = key->alg->public_blob(key->data, &publen);
1749 i = key->alg->openssh_fmtkey(key->data, NULL, 0);
1750 privblob = snewn(i, unsigned char);
1751 privlen = key->alg->openssh_fmtkey(key->data, privblob, i);
1752 assert(privlen == i);
1753 commentlen = strlen(key->comment);
1756 * Allocate enough space for the full binary key format. No need
1757 * to be absolutely precise here.
1759 maxsize = (16 + /* magic number */
1760 32 + /* cipher name string */
1761 32 + /* kdf name string */
1762 64 + /* kdf options string */
1764 4+publen + /* public key string */
1765 4 + /* string header for private section */
1766 8 + /* checkint x 2 */
1767 4+strlen(key->alg->name) + /* key type string */
1768 privlen + /* private blob */
1769 4+commentlen + /* comment string */
1770 16); /* padding at end of private section */
1771 outblob = snewn(maxsize, unsigned char);
1774 * Construct the cleartext version of the blob.
1779 memcpy(p, "openssh-key-v1\0", 15);
1782 /* Cipher and kdf names, and kdf options. */
1784 memset(bcrypt_salt, 0, sizeof(bcrypt_salt)); /* prevent warnings */
1785 p += put_string_z(p, "none");
1786 p += put_string_z(p, "none");
1787 p += put_string_z(p, "");
1790 for (i = 0; i < (int)sizeof(bcrypt_salt); i++)
1791 bcrypt_salt[i] = random_byte();
1792 p += put_string_z(p, "aes256-cbc");
1793 p += put_string_z(p, "bcrypt");
1796 p += put_string(p, bcrypt_salt, sizeof(bcrypt_salt));
1797 p += put_uint32(p, bcrypt_rounds);
1798 PUT_32BIT_MSB_FIRST(q, (unsigned)(p - (q+4)));
1801 /* Number of keys. */
1802 p += put_uint32(p, 1);
1805 p += put_string(p, pubblob, publen);
1807 /* Begin private section. */
1808 private_section_length_field = p;
1810 private_section_start = p;
1814 for (i = 0; i < 4; i++)
1815 checkint = (checkint << 8) + random_byte();
1816 p += put_uint32(p, checkint);
1817 p += put_uint32(p, checkint);
1819 /* Private key. The main private blob goes inline, with no string
1821 p += put_string_z(p, key->alg->name);
1822 memcpy(p, privblob, privlen);
1826 p += put_string_z(p, key->comment);
1828 /* Pad out the encrypted section. */
1832 } while ((p - private_section_start) & 15);
1834 assert(p - outblob < maxsize);
1836 /* Go back and fill in the length field for the private section. */
1837 PUT_32BIT_MSB_FIRST(private_section_length_field,
1838 p - private_section_start);
1842 * Encrypt the private section. We need 48 bytes of key
1843 * material: 32 bytes AES key + 16 bytes iv.
1845 unsigned char keybuf[48];
1848 openssh_bcrypt(passphrase,
1849 bcrypt_salt, sizeof(bcrypt_salt), bcrypt_rounds,
1850 keybuf, sizeof(keybuf));
1852 ctx = aes_make_context();
1853 aes256_key(ctx, keybuf);
1854 aes_iv(ctx, keybuf + 32);
1855 aes_ssh2_encrypt_blk(ctx, private_section_start,
1856 p - private_section_start);
1857 aes_free_context(ctx);
1859 smemclr(keybuf, sizeof(keybuf));
1863 * And save it. We'll use Unix line endings just in case it's
1864 * subsequently transferred in binary mode.
1866 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1869 fputs("-----BEGIN OPENSSH PRIVATE KEY-----\n", fp);
1870 base64_encode(fp, outblob, p - outblob, 64);
1871 fputs("-----END OPENSSH PRIVATE KEY-----\n", fp);
1877 smemclr(outblob, maxsize);
1881 smemclr(privblob, privlen);
1885 smemclr(pubblob, publen);
1891 /* ----------------------------------------------------------------------
1892 * Code to read ssh.com private keys.
1896 * The format of the base64 blob is largely SSH-2-packet-formatted,
1897 * except that mpints are a bit different: they're more like the
1898 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1899 * (N+7)/8 bytes of data.
1901 * So. The blob contains:
1903 * - uint32 0x3f6ff9eb (magic number)
1904 * - uint32 size (total blob size)
1905 * - string key-type (see below)
1906 * - string cipher-type (tells you if key is encrypted)
1907 * - string encrypted-blob
1909 * (The first size field includes the size field itself and the
1910 * magic number before it. All other size fields are ordinary SSH-2
1911 * strings, so the size field indicates how much data is to
1914 * The encrypted blob, once decrypted, contains a single string
1915 * which in turn contains the payload. (This allows padding to be
1916 * added after that string while still making it clear where the
1917 * real payload ends. Also it probably makes for a reasonable
1918 * decryption check.)
1920 * The payload blob, for an RSA key, contains:
1923 * - mpint n (yes, the public and private stuff is intermixed)
1924 * - mpint u (presumably inverse of p mod q)
1925 * - mpint p (p is the smaller prime)
1926 * - mpint q (q is the larger)
1928 * For a DSA key, the payload blob contains:
1936 * Alternatively, if the parameters are `predefined', that
1937 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1938 * containing some predefined parameter specification. *shudder*,
1939 * but I doubt we'll encounter this in real life.
1941 * The key type strings are ghastly. The RSA key I looked at had a
1944 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1946 * and the DSA key wasn't much better:
1948 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1950 * It isn't clear that these will always be the same. I think it
1951 * might be wise just to look at the `if-modn{sign{rsa' and
1952 * `dl-modp{sign{dsa' prefixes.
1954 * Finally, the encryption. The cipher-type string appears to be
1955 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1956 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1957 * from the passphrase by means of yet another hashing faff:
1959 * - first 16 bytes are MD5(passphrase)
1960 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1961 * - if there were more, they'd be MD5(passphrase || first 32),
1965 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1968 char comment[256]; /* allowing any length is overkill */
1969 unsigned char *keyblob;
1970 int keyblob_len, keyblob_size;
1973 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1974 const char **errmsg_p)
1976 struct sshcom_key *ret;
1983 int base64_chars = 0;
1985 ret = snew(struct sshcom_key);
1986 ret->comment[0] = '\0';
1987 ret->keyblob = NULL;
1988 ret->keyblob_len = ret->keyblob_size = 0;
1990 fp = f_open(filename, "r", FALSE);
1992 errmsg = "unable to open key file";
1995 if (!(line = fgetline(fp))) {
1996 errmsg = "unexpected end of file";
2000 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
2001 errmsg = "file does not begin with ssh.com key header";
2004 smemclr(line, strlen(line));
2010 if (!(line = fgetline(fp))) {
2011 errmsg = "unexpected end of file";
2015 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
2020 if ((p = strchr(line, ':')) != NULL) {
2022 errmsg = "header found in body of key data";
2026 while (*p && isspace((unsigned char)*p)) p++;
2027 hdrstart = p - line;
2030 * Header lines can end in a trailing backslash for
2033 len = hdrstart + strlen(line+hdrstart);
2035 while (line[len-1] == '\\') {
2039 line2 = fgetline(fp);
2041 errmsg = "unexpected end of file";
2046 line2len = strlen(line2);
2047 line = sresize(line, len + line2len + 1, char);
2048 strcpy(line + len - 1, line2);
2049 len += line2len - 1;
2052 smemclr(line2, strlen(line2));
2056 p = line + hdrstart;
2058 if (!strcmp(line, "Comment")) {
2059 /* Strip quotes in comment if present. */
2060 if (p[0] == '"' && p[strlen(p)-1] == '"') {
2062 p[strlen(p)-1] = '\0';
2064 strncpy(ret->comment, p, sizeof(ret->comment));
2065 ret->comment[sizeof(ret->comment)-1] = '\0';
2071 while (isbase64(*p)) {
2072 base64_bit[base64_chars++] = *p;
2073 if (base64_chars == 4) {
2074 unsigned char out[3];
2078 len = base64_decode_atom(base64_bit, out);
2081 errmsg = "invalid base64 encoding";
2085 if (ret->keyblob_len + len > ret->keyblob_size) {
2086 ret->keyblob_size = ret->keyblob_len + len + 256;
2087 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
2091 memcpy(ret->keyblob + ret->keyblob_len, out, len);
2092 ret->keyblob_len += len;
2098 smemclr(line, strlen(line));
2103 if (ret->keyblob_len == 0 || !ret->keyblob) {
2104 errmsg = "key body not present";
2109 if (errmsg_p) *errmsg_p = NULL;
2117 smemclr(line, strlen(line));
2123 smemclr(ret->keyblob, ret->keyblob_size);
2124 sfree(ret->keyblob);
2126 smemclr(ret, sizeof(*ret));
2129 if (errmsg_p) *errmsg_p = errmsg;
2133 int sshcom_encrypted(const Filename *filename, char **comment)
2135 struct sshcom_key *key = load_sshcom_key(filename, NULL);
2136 int pos, len, answer;
2145 * Check magic number.
2147 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
2148 goto done; /* key is invalid */
2152 * Find the cipher-type string.
2155 if (key->keyblob_len < pos+4)
2156 goto done; /* key is far too short */
2157 len = toint(GET_32BIT(key->keyblob + pos));
2158 if (len < 0 || len > key->keyblob_len - pos - 4)
2159 goto done; /* key is far too short */
2160 pos += 4 + len; /* skip key type */
2161 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
2162 if (len < 0 || len > key->keyblob_len - pos - 4)
2163 goto done; /* cipher type string is incomplete */
2164 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
2169 *comment = dupstr(key->comment);
2170 smemclr(key->keyblob, key->keyblob_size);
2171 sfree(key->keyblob);
2172 smemclr(key, sizeof(*key));
2175 *comment = dupstr("");
2180 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
2182 unsigned bits, bytes;
2183 unsigned char *d = (unsigned char *) data;
2187 bits = GET_32BIT(d);
2189 bytes = (bits + 7) / 8;
2200 return len; /* ensure further calls fail as well */
2203 static int sshcom_put_mpint(void *target, void *data, int len)
2205 unsigned char *d = (unsigned char *)target;
2206 unsigned char *i = (unsigned char *)data;
2207 int bits = len * 8 - 1;
2210 if (*i & (1 << (bits & 7)))
2216 PUT_32BIT(d, bits+1);
2217 memcpy(d+4, i, len);
2221 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
2222 const char **errmsg_p)
2224 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
2227 const char prefix_rsa[] = "if-modn{sign{rsa";
2228 const char prefix_dsa[] = "dl-modp{sign{dsa";
2229 enum { RSA, DSA } type;
2233 struct ssh2_userkey *ret = NULL, *retkey;
2234 const struct ssh_signkey *alg;
2235 unsigned char *blob = NULL;
2236 int blobsize = 0, publen, privlen;
2242 * Check magic number.
2244 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
2245 errmsg = "key does not begin with magic number";
2250 * Determine the key type.
2253 if (key->keyblob_len < pos+4 ||
2254 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2255 len > key->keyblob_len - pos - 4) {
2256 errmsg = "key blob does not contain a key type string";
2259 if (len > sizeof(prefix_rsa) - 1 &&
2260 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
2262 } else if (len > sizeof(prefix_dsa) - 1 &&
2263 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
2266 errmsg = "key is of unknown type";
2272 * Determine the cipher type.
2274 if (key->keyblob_len < pos+4 ||
2275 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2276 len > key->keyblob_len - pos - 4) {
2277 errmsg = "key blob does not contain a cipher type string";
2280 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
2282 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
2285 errmsg = "key encryption is of unknown type";
2291 * Get hold of the encrypted part of the key.
2293 if (key->keyblob_len < pos+4 ||
2294 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2295 len > key->keyblob_len - pos - 4) {
2296 errmsg = "key blob does not contain actual key data";
2299 ciphertext = (char *)key->keyblob + pos + 4;
2301 if (cipherlen == 0) {
2302 errmsg = "length of key data is zero";
2307 * Decrypt it if necessary.
2311 * Derive encryption key from passphrase and iv/salt:
2313 * - let block A equal MD5(passphrase)
2314 * - let block B equal MD5(passphrase || A)
2315 * - block C would be MD5(passphrase || A || B) and so on
2316 * - encryption key is the first N bytes of A || B
2318 struct MD5Context md5c;
2319 unsigned char keybuf[32], iv[8];
2321 if (cipherlen % 8 != 0) {
2322 errmsg = "encrypted part of key is not a multiple of cipher block"
2328 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2329 MD5Final(keybuf, &md5c);
2332 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2333 MD5Update(&md5c, keybuf, 16);
2334 MD5Final(keybuf+16, &md5c);
2337 * Now decrypt the key blob.
2339 memset(iv, 0, sizeof(iv));
2340 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2343 smemclr(&md5c, sizeof(md5c));
2344 smemclr(keybuf, sizeof(keybuf));
2347 * Hereafter we return WRONG_PASSPHRASE for any parsing
2348 * error. (But only if we've just tried to decrypt it!
2349 * Returning WRONG_PASSPHRASE for an unencrypted key is
2353 ret = SSH2_WRONG_PASSPHRASE;
2357 * Strip away the containing string to get to the real meat.
2359 len = toint(GET_32BIT(ciphertext));
2360 if (len < 0 || len > cipherlen-4) {
2361 errmsg = "containing string was ill-formed";
2368 * Now we break down into RSA versus DSA. In either case we'll
2369 * construct public and private blobs in our own format, and
2370 * end up feeding them to alg->createkey().
2372 blobsize = cipherlen + 256;
2373 blob = snewn(blobsize, unsigned char);
2376 struct mpint_pos n, e, d, u, p, q;
2378 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
2379 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
2380 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
2381 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
2382 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2383 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2385 errmsg = "key data did not contain six integers";
2391 pos += put_string(blob+pos, "ssh-rsa", 7);
2392 pos += put_mp(blob+pos, e.start, e.bytes);
2393 pos += put_mp(blob+pos, n.start, n.bytes);
2395 pos += put_string(blob+pos, d.start, d.bytes);
2396 pos += put_mp(blob+pos, q.start, q.bytes);
2397 pos += put_mp(blob+pos, p.start, p.bytes);
2398 pos += put_mp(blob+pos, u.start, u.bytes);
2399 privlen = pos - publen;
2401 struct mpint_pos p, q, g, x, y;
2404 assert(type == DSA); /* the only other option from the if above */
2406 if (GET_32BIT(ciphertext) != 0) {
2407 errmsg = "predefined DSA parameters not supported";
2410 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2411 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
2412 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2413 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
2414 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
2416 errmsg = "key data did not contain five integers";
2422 pos += put_string(blob+pos, "ssh-dss", 7);
2423 pos += put_mp(blob+pos, p.start, p.bytes);
2424 pos += put_mp(blob+pos, q.start, q.bytes);
2425 pos += put_mp(blob+pos, g.start, g.bytes);
2426 pos += put_mp(blob+pos, y.start, y.bytes);
2428 pos += put_mp(blob+pos, x.start, x.bytes);
2429 privlen = pos - publen;
2432 assert(privlen > 0); /* should have bombed by now if not */
2434 retkey = snew(struct ssh2_userkey);
2436 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
2437 if (!retkey->data) {
2439 errmsg = "unable to create key data structure";
2442 retkey->comment = dupstr(key->comment);
2444 errmsg = NULL; /* no error */
2449 smemclr(blob, blobsize);
2452 smemclr(key->keyblob, key->keyblob_size);
2453 sfree(key->keyblob);
2454 smemclr(key, sizeof(*key));
2456 if (errmsg_p) *errmsg_p = errmsg;
2460 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
2463 unsigned char *pubblob, *privblob;
2464 int publen, privlen;
2465 unsigned char *outblob;
2467 struct mpint_pos numbers[6];
2468 int nnumbers, initial_zero, pos, lenpos, i;
2476 * Fetch the key blobs.
2478 pubblob = key->alg->public_blob(key->data, &publen);
2479 privblob = key->alg->private_blob(key->data, &privlen);
2483 * Find the sequence of integers to be encoded into the OpenSSH
2484 * key blob, and also decide on the header line.
2486 if (key->alg == &ssh_rsa) {
2488 struct mpint_pos n, e, d, p, q, iqmp;
2491 * These blobs were generated from inside PuTTY, so we needn't
2492 * treat them as untrusted.
2494 pos = 4 + GET_32BIT(pubblob);
2495 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
2496 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
2498 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
2499 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
2500 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
2501 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
2503 assert(e.start && iqmp.start); /* can't go wrong */
2514 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
2515 } else if (key->alg == &ssh_dss) {
2517 struct mpint_pos p, q, g, y, x;
2520 * These blobs were generated from inside PuTTY, so we needn't
2521 * treat them as untrusted.
2523 pos = 4 + GET_32BIT(pubblob);
2524 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
2525 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
2526 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
2527 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
2529 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
2531 assert(y.start && x.start); /* can't go wrong */
2541 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
2543 assert(0); /* zoinks! */
2544 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
2548 * Total size of key blob will be somewhere under 512 plus
2549 * combined length of integers. We'll calculate the more
2550 * precise size as we construct the blob.
2553 for (i = 0; i < nnumbers; i++)
2554 outlen += 4 + numbers[i].bytes;
2555 outblob = snewn(outlen, unsigned char);
2558 * Create the unencrypted key blob.
2561 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
2562 pos += 4; /* length field, fill in later */
2563 pos += put_string(outblob+pos, type, strlen(type));
2565 char *ciphertype = passphrase ? "3des-cbc" : "none";
2566 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
2568 lenpos = pos; /* remember this position */
2569 pos += 4; /* encrypted-blob size */
2570 pos += 4; /* encrypted-payload size */
2572 PUT_32BIT(outblob+pos, 0);
2575 for (i = 0; i < nnumbers; i++)
2576 pos += sshcom_put_mpint(outblob+pos,
2577 numbers[i].start, numbers[i].bytes);
2578 /* Now wrap up the encrypted payload. */
2579 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
2580 /* Pad encrypted blob to a multiple of cipher block size. */
2582 int padding = -(pos - (lenpos+4)) & 7;
2584 outblob[pos++] = random_byte();
2586 ciphertext = (char *)outblob+lenpos+4;
2587 cipherlen = pos - (lenpos+4);
2588 assert(!passphrase || cipherlen % 8 == 0);
2589 /* Wrap up the encrypted blob string. */
2590 PUT_32BIT(outblob+lenpos, cipherlen);
2591 /* And finally fill in the total length field. */
2592 PUT_32BIT(outblob+4, pos);
2594 assert(pos < outlen);
2601 * Derive encryption key from passphrase and iv/salt:
2603 * - let block A equal MD5(passphrase)
2604 * - let block B equal MD5(passphrase || A)
2605 * - block C would be MD5(passphrase || A || B) and so on
2606 * - encryption key is the first N bytes of A || B
2608 struct MD5Context md5c;
2609 unsigned char keybuf[32], iv[8];
2612 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2613 MD5Final(keybuf, &md5c);
2616 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2617 MD5Update(&md5c, keybuf, 16);
2618 MD5Final(keybuf+16, &md5c);
2621 * Now decrypt the key blob.
2623 memset(iv, 0, sizeof(iv));
2624 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2627 smemclr(&md5c, sizeof(md5c));
2628 smemclr(keybuf, sizeof(keybuf));
2632 * And save it. We'll use Unix line endings just in case it's
2633 * subsequently transferred in binary mode.
2635 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
2638 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2639 fprintf(fp, "Comment: \"");
2641 * Comment header is broken with backslash-newline if it goes
2642 * over 70 chars. Although it's surrounded by quotes, it
2643 * _doesn't_ escape backslashes or quotes within the string.
2644 * Don't ask me, I didn't design it.
2647 int slen = 60; /* starts at 60 due to "Comment: " */
2648 char *c = key->comment;
2649 while ((int)strlen(c) > slen) {
2650 fprintf(fp, "%.*s\\\n", slen, c);
2652 slen = 70; /* allow 70 chars on subsequent lines */
2654 fprintf(fp, "%s\"\n", c);
2656 base64_encode(fp, outblob, pos, 70);
2657 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2663 smemclr(outblob, outlen);
2667 smemclr(privblob, privlen);
2671 smemclr(pubblob, publen);