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_string(void *target, void *data, int len)
275 unsigned char *d = (unsigned char *)target;
278 memcpy(d+4, data, len);
282 static int put_mp(void *target, void *data, int len)
284 unsigned char *d = (unsigned char *)target;
285 unsigned char *i = (unsigned char *)data;
290 memcpy(d+5, data, len);
294 memcpy(d+4, data, len);
299 /* Simple structure to point to an mp-int within a blob. */
300 struct mpint_pos { void *start; int bytes; };
302 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
305 unsigned char *d = (unsigned char *) data;
309 bytes = toint(GET_32BIT(d));
310 if (bytes < 0 || len-4 < bytes)
320 return len; /* ensure further calls fail as well */
323 /* ----------------------------------------------------------------------
324 * Code to read and write OpenSSH private keys, in the old-style PEM
329 OP_DSA, OP_RSA, OP_ECDSA
330 } openssh_pem_keytype;
335 struct openssh_pem_key {
336 openssh_pem_keytype keytype;
338 openssh_pem_enc encryption;
340 unsigned char *keyblob;
341 int keyblob_len, keyblob_size;
344 static struct openssh_pem_key *load_openssh_pem_key(const Filename *filename,
345 const char **errmsg_p)
347 struct openssh_pem_key *ret;
353 int base64_chars = 0;
355 ret = snew(struct openssh_pem_key);
357 ret->keyblob_len = ret->keyblob_size = 0;
359 fp = f_open(filename, "r", FALSE);
361 errmsg = "unable to open key file";
365 if (!(line = fgetline(fp))) {
366 errmsg = "unexpected end of file";
370 if (0 != strncmp(line, "-----BEGIN ", 11) ||
371 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
372 errmsg = "file does not begin with OpenSSH key header";
376 * Parse the BEGIN line. For old-format keys, this tells us the
377 * type of the key; for new-format keys, all it tells us is the
378 * format, and we'll find out the key type once we parse the
381 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) {
382 ret->keytype = OP_RSA;
383 } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) {
384 ret->keytype = OP_DSA;
385 } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) {
386 ret->keytype = OP_ECDSA;
387 } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
388 errmsg = "this is a new-style OpenSSH key";
391 errmsg = "unrecognised key type";
394 smemclr(line, strlen(line));
398 ret->encrypted = FALSE;
399 memset(ret->iv, 0, sizeof(ret->iv));
403 if (!(line = fgetline(fp))) {
404 errmsg = "unexpected end of file";
408 if (0 == strncmp(line, "-----END ", 9) &&
409 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
414 if ((p = strchr(line, ':')) != NULL) {
416 errmsg = "header found in body of key data";
420 while (*p && isspace((unsigned char)*p)) p++;
421 if (!strcmp(line, "Proc-Type")) {
422 if (p[0] != '4' || p[1] != ',') {
423 errmsg = "Proc-Type is not 4 (only 4 is supported)";
427 if (!strcmp(p, "ENCRYPTED"))
428 ret->encrypted = TRUE;
429 } else if (!strcmp(line, "DEK-Info")) {
432 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
433 ret->encryption = OP_E_3DES;
435 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
436 ret->encryption = OP_E_AES;
439 errmsg = "unsupported cipher";
442 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
443 for (i = 0; i < ivlen; i++) {
444 if (1 != sscanf(p, "%2x", &j)) {
445 errmsg = "expected more iv data in DEK-Info";
452 errmsg = "more iv data than expected in DEK-Info";
460 while (isbase64(*p)) {
461 base64_bit[base64_chars++] = *p;
462 if (base64_chars == 4) {
463 unsigned char out[3];
468 len = base64_decode_atom(base64_bit, out);
471 errmsg = "invalid base64 encoding";
475 if (ret->keyblob_len + len > ret->keyblob_size) {
476 ret->keyblob_size = ret->keyblob_len + len + 256;
477 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
481 memcpy(ret->keyblob + ret->keyblob_len, out, len);
482 ret->keyblob_len += len;
484 smemclr(out, sizeof(out));
490 smemclr(line, strlen(line));
498 if (ret->keyblob_len == 0 || !ret->keyblob) {
499 errmsg = "key body not present";
503 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
504 errmsg = "encrypted key blob is not a multiple of "
509 smemclr(base64_bit, sizeof(base64_bit));
510 if (errmsg_p) *errmsg_p = NULL;
515 smemclr(line, strlen(line));
519 smemclr(base64_bit, sizeof(base64_bit));
522 smemclr(ret->keyblob, ret->keyblob_size);
525 smemclr(ret, sizeof(*ret));
528 if (errmsg_p) *errmsg_p = errmsg;
533 int openssh_pem_encrypted(const Filename *filename)
535 struct openssh_pem_key *key = load_openssh_pem_key(filename, NULL);
540 ret = key->encrypted;
541 smemclr(key->keyblob, key->keyblob_size);
543 smemclr(key, sizeof(*key));
548 struct ssh2_userkey *openssh_pem_read(const Filename *filename,
550 const char **errmsg_p)
552 struct openssh_pem_key *key = load_openssh_pem_key(filename, errmsg_p);
553 struct ssh2_userkey *retkey;
555 int ret, id, len, flags;
557 struct ssh2_userkey *retval = NULL;
560 int blobsize = 0, blobptr, privptr;
569 if (key->encrypted) {
571 * Derive encryption key from passphrase and iv/salt:
573 * - let block A equal MD5(passphrase || iv)
574 * - let block B equal MD5(A || passphrase || iv)
575 * - block C would be MD5(B || passphrase || iv) and so on
576 * - encryption key is the first N bytes of A || B
578 * (Note that only 8 bytes of the iv are used for key
579 * derivation, even when the key is encrypted with AES and
580 * hence there are 16 bytes available.)
582 struct MD5Context md5c;
583 unsigned char keybuf[32];
586 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
587 MD5Update(&md5c, (unsigned char *)key->iv, 8);
588 MD5Final(keybuf, &md5c);
591 MD5Update(&md5c, keybuf, 16);
592 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
593 MD5Update(&md5c, (unsigned char *)key->iv, 8);
594 MD5Final(keybuf+16, &md5c);
597 * Now decrypt the key blob.
599 if (key->encryption == OP_E_3DES)
600 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->iv,
601 key->keyblob, key->keyblob_len);
604 assert(key->encryption == OP_E_AES);
605 ctx = aes_make_context();
606 aes128_key(ctx, keybuf);
607 aes_iv(ctx, (unsigned char *)key->iv);
608 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
609 aes_free_context(ctx);
612 smemclr(&md5c, sizeof(md5c));
613 smemclr(keybuf, sizeof(keybuf));
617 * Now we have a decrypted key blob, which contains an ASN.1
618 * encoded private key. We must now untangle the ASN.1.
620 * We expect the whole key blob to be formatted as a SEQUENCE
621 * (0x30 followed by a length code indicating that the rest of
622 * the blob is part of the sequence). Within that SEQUENCE we
623 * expect to see a bunch of INTEGERs. What those integers mean
624 * depends on the key type:
626 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
627 * dmp1, dmq1, iqmp in that order. (The last three are d mod
628 * (p-1), d mod (q-1), inverse of q mod p respectively.)
630 * - For DSA, we expect them to be 0, p, q, g, y, x in that
633 * - In ECDSA the format is totally different: we see the
634 * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
635 * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
640 /* Expect the SEQUENCE header. Take its absence as a failure to
641 * decrypt, if the key was encrypted. */
642 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
644 if (ret < 0 || id != 16) {
645 errmsg = "ASN.1 decoding failure";
646 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
650 /* Expect a load of INTEGERs. */
651 if (key->keytype == OP_RSA)
653 else if (key->keytype == OP_DSA)
656 num_integers = 0; /* placate compiler warnings */
659 if (key->keytype == OP_ECDSA) {
660 /* And now for something completely different */
663 struct ec_curve *curve;
665 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
668 if (ret < 0 || id != 2 || key->keyblob+key->keyblob_len-p < len ||
669 len != 1 || p[0] != 1) {
670 errmsg = "ASN.1 decoding failure";
671 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
675 /* Read private key OCTET STRING */
676 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
679 if (ret < 0 || id != 4 || key->keyblob+key->keyblob_len-p < len) {
680 errmsg = "ASN.1 decoding failure";
681 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
688 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
691 if (ret < 0 || id != 0 || key->keyblob+key->keyblob_len-p < len) {
692 errmsg = "ASN.1 decoding failure";
693 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
696 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
699 if (ret < 0 || id != 6 || key->keyblob+key->keyblob_len-p < len) {
700 errmsg = "ASN.1 decoding failure";
701 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
704 if (len == 8 && !memcmp(p, nistp256_oid, nistp256_oid_len)) {
706 } else if (len == 5 && !memcmp(p, nistp384_oid,
709 } else if (len == 5 && !memcmp(p, nistp521_oid,
713 errmsg = "Unsupported ECDSA curve.";
718 /* Read BIT STRING point */
719 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
722 if (ret < 0 || id != 1 || key->keyblob+key->keyblob_len-p < len) {
723 errmsg = "ASN.1 decoding failure";
724 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
727 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
730 if (ret < 0 || id != 3 || key->keyblob+key->keyblob_len-p < len ||
731 len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
732 errmsg = "ASN.1 decoding failure";
733 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
736 p += 1; len -= 1; /* Skip 0x00 before point */
738 /* Construct the key */
739 retkey = snew(struct ssh2_userkey);
741 errmsg = "out of memory";
744 if (curve->fieldBits == 256) {
745 retkey->alg = &ssh_ecdsa_nistp256;
746 } else if (curve->fieldBits == 384) {
747 retkey->alg = &ssh_ecdsa_nistp384;
749 retkey->alg = &ssh_ecdsa_nistp521;
751 blob = snewn((4+19 + 4+8 + 4+len) + (4+privlen), unsigned char);
754 errmsg = "out of memory";
758 sprintf((char*)blob+4, "ecdsa-sha2-nistp%d", curve->fieldBits);
759 PUT_32BIT(blob+4+19, 8);
760 sprintf((char*)blob+4+19+4, "nistp%d", curve->fieldBits);
761 PUT_32BIT(blob+4+19+4+8, len);
762 memcpy(blob+4+19+4+8+4, p, len);
763 PUT_32BIT(blob+4+19+4+8+4+len, privlen);
764 memcpy(blob+4+19+4+8+4+len+4, priv, privlen);
765 retkey->data = retkey->alg->createkey(blob, 4+19+4+8+4+len,
770 errmsg = "unable to create key data structure";
774 } else if (key->keytype == OP_RSA || key->keytype == OP_DSA) {
777 * Space to create key blob in.
779 blobsize = 256+key->keyblob_len;
780 blob = snewn(blobsize, unsigned char);
782 if (key->keytype == OP_DSA)
783 memcpy(blob+4, "ssh-dss", 7);
784 else if (key->keytype == OP_RSA)
785 memcpy(blob+4, "ssh-rsa", 7);
789 for (i = 0; i < num_integers; i++) {
790 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
793 if (ret < 0 || id != 2 ||
794 key->keyblob+key->keyblob_len-p < len) {
795 errmsg = "ASN.1 decoding failure";
796 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
802 * The first integer should be zero always (I think
803 * this is some sort of version indication).
805 if (len != 1 || p[0] != 0) {
806 errmsg = "version number mismatch";
809 } else if (key->keytype == OP_RSA) {
811 * Integers 1 and 2 go into the public blob but in the
812 * opposite order; integers 3, 4, 5 and 8 go into the
813 * private blob. The other two (6 and 7) are ignored.
816 /* Save the details for after we deal with number 2. */
819 } else if (i != 6 && i != 7) {
820 PUT_32BIT(blob+blobptr, len);
821 memcpy(blob+blobptr+4, p, len);
824 PUT_32BIT(blob+blobptr, modlen);
825 memcpy(blob+blobptr+4, modptr, modlen);
830 } else if (key->keytype == OP_DSA) {
832 * Integers 1-4 go into the public blob; integer 5 goes
833 * into the private blob.
835 PUT_32BIT(blob+blobptr, len);
836 memcpy(blob+blobptr+4, p, len);
842 /* Skip past the number. */
847 * Now put together the actual key. Simplest way to do this is
848 * to assemble our own key blobs and feed them to the createkey
849 * functions; this is a bit faffy but it does mean we get all
850 * the sanity checks for free.
852 assert(privptr > 0); /* should have bombed by now if not */
853 retkey = snew(struct ssh2_userkey);
854 retkey->alg = (key->keytype == OP_RSA ? &ssh_rsa : &ssh_dss);
855 retkey->data = retkey->alg->createkey(blob, privptr,
860 errmsg = "unable to create key data structure";
865 assert(0 && "Bad key type from load_openssh_pem_key");
869 * The old key format doesn't include a comment in the private
872 retkey->comment = dupstr("imported-openssh-key");
874 errmsg = NULL; /* no error */
879 smemclr(blob, blobsize);
882 smemclr(key->keyblob, key->keyblob_size);
884 smemclr(key, sizeof(*key));
886 if (errmsg_p) *errmsg_p = errmsg;
890 int openssh_pem_write(const Filename *filename, struct ssh2_userkey *key,
893 unsigned char *pubblob, *privblob, *spareblob;
894 int publen, privlen, sparelen = 0;
895 unsigned char *outblob;
897 struct mpint_pos numbers[9];
898 int nnumbers, pos, len, seqlen, i;
899 char *header, *footer;
906 * Fetch the key blobs.
908 pubblob = key->alg->public_blob(key->data, &publen);
909 privblob = key->alg->private_blob(key->data, &privlen);
910 spareblob = outblob = NULL;
916 * Encode the OpenSSH key blob, and also decide on the header
919 if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
921 * The RSA and DSS handlers share some code because the two
922 * key types have very similar ASN.1 representations, as a
923 * plain SEQUENCE of big integers. So we set up a list of
924 * bignums per key type and then construct the actual blob in
925 * common code after that.
927 if (key->alg == &ssh_rsa) {
929 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
930 Bignum bd, bp, bq, bdmp1, bdmq1;
933 * These blobs were generated from inside PuTTY, so we needn't
934 * treat them as untrusted.
936 pos = 4 + GET_32BIT(pubblob);
937 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
938 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
940 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
941 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
942 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
943 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
945 assert(e.start && iqmp.start); /* can't go wrong */
947 /* We also need d mod (p-1) and d mod (q-1). */
948 bd = bignum_from_bytes(d.start, d.bytes);
949 bp = bignum_from_bytes(p.start, p.bytes);
950 bq = bignum_from_bytes(q.start, q.bytes);
953 bdmp1 = bigmod(bd, bp);
954 bdmq1 = bigmod(bd, bq);
959 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
960 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
961 sparelen = dmp1.bytes + dmq1.bytes;
962 spareblob = snewn(sparelen, unsigned char);
963 dmp1.start = spareblob;
964 dmq1.start = spareblob + dmp1.bytes;
965 for (i = 0; i < dmp1.bytes; i++)
966 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
967 for (i = 0; i < dmq1.bytes; i++)
968 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
972 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
983 header = "-----BEGIN RSA PRIVATE KEY-----\n";
984 footer = "-----END RSA PRIVATE KEY-----\n";
985 } else { /* ssh-dss */
987 struct mpint_pos p, q, g, y, x;
990 * These blobs were generated from inside PuTTY, so we needn't
991 * treat them as untrusted.
993 pos = 4 + GET_32BIT(pubblob);
994 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
995 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
996 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
997 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
999 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1001 assert(y.start && x.start); /* can't go wrong */
1003 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1011 header = "-----BEGIN DSA PRIVATE KEY-----\n";
1012 footer = "-----END DSA PRIVATE KEY-----\n";
1016 * Now count up the total size of the ASN.1 encoded integers,
1017 * so as to determine the length of the containing SEQUENCE.
1020 for (i = 0; i < nnumbers; i++) {
1021 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
1022 len += numbers[i].bytes;
1025 /* Now add on the SEQUENCE header. */
1026 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1029 * Now we know how big outblob needs to be. Allocate it.
1031 outblob = snewn(len, unsigned char);
1034 * And write the data into it.
1037 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1038 for (i = 0; i < nnumbers; i++) {
1039 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
1040 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
1041 pos += numbers[i].bytes;
1043 } else if (key->alg == &ssh_ecdsa_nistp256 ||
1044 key->alg == &ssh_ecdsa_nistp384 ||
1045 key->alg == &ssh_ecdsa_nistp521) {
1051 * Structure of asn1:
1054 * OCTET STRING (private key)
1058 * BIT STRING (0x00 public key point)
1060 switch (((struct ec_key *)key->data)->publicKey.curve->fieldBits) {
1062 /* OID: 1.2.840.10045.3.1.7 (ansiX9p256r1) */
1064 oidlen = nistp256_oid_len;
1068 /* OID: 1.3.132.0.34 (secp384r1) */
1070 oidlen = nistp384_oid_len;
1074 /* OID: 1.3.132.0.35 (secp521r1) */
1076 oidlen = nistp521_oid_len;
1083 len = ber_write_id_len(NULL, 2, 1, 0);
1085 len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1087 len += ber_write_id_len(NULL, 0, oidlen +
1088 ber_write_id_len(NULL, 6, oidlen, 0),
1089 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1090 len += ber_write_id_len(NULL, 6, oidlen, 0);
1092 len += ber_write_id_len(NULL, 1, 2 + pointlen +
1093 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1094 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1095 len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1096 len += 2 + pointlen;
1099 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1101 outblob = snewn(len, unsigned char);
1105 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1106 pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1108 pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1109 memcpy(outblob+pos, privblob + 4, privlen - 4);
1111 pos += ber_write_id_len(outblob+pos, 0, oidlen +
1112 ber_write_id_len(NULL, 6, oidlen, 0),
1113 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1114 pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1115 memcpy(outblob+pos, oid, oidlen);
1117 pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1118 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1119 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1120 pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1122 memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1123 pos += 1 + pointlen;
1125 header = "-----BEGIN EC PRIVATE KEY-----\n";
1126 footer = "-----END EC PRIVATE KEY-----\n";
1128 assert(0); /* zoinks! */
1129 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1135 * For the moment, we still encrypt our OpenSSH keys using
1139 struct MD5Context md5c;
1140 unsigned char keybuf[32];
1143 * Round up to the cipher block size, ensuring we have at
1144 * least one byte of padding (see below).
1146 outlen = (len+8) &~ 7;
1148 unsigned char *tmp = snewn(outlen, unsigned char);
1149 memcpy(tmp, outblob, len);
1150 smemclr(outblob, len);
1156 * Padding on OpenSSH keys is deterministic. The number of
1157 * padding bytes is always more than zero, and always at most
1158 * the cipher block length. The value of each padding byte is
1159 * equal to the number of padding bytes. So a plaintext that's
1160 * an exact multiple of the block size will be padded with 08
1161 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1162 * plaintext one byte less than a multiple of the block size
1163 * will be padded with just 01.
1165 * This enables the OpenSSL key decryption function to strip
1166 * off the padding algorithmically and return the unpadded
1167 * plaintext to the next layer: it looks at the final byte, and
1168 * then expects to find that many bytes at the end of the data
1169 * with the same value. Those are all removed and the rest is
1173 while (pos < outlen) {
1174 outblob[pos++] = outlen - len;
1178 * Invent an iv. Then derive encryption key from passphrase
1181 * - let block A equal MD5(passphrase || iv)
1182 * - let block B equal MD5(A || passphrase || iv)
1183 * - block C would be MD5(B || passphrase || iv) and so on
1184 * - encryption key is the first N bytes of A || B
1186 for (i = 0; i < 8; i++) iv[i] = random_byte();
1189 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1190 MD5Update(&md5c, iv, 8);
1191 MD5Final(keybuf, &md5c);
1194 MD5Update(&md5c, keybuf, 16);
1195 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1196 MD5Update(&md5c, iv, 8);
1197 MD5Final(keybuf+16, &md5c);
1200 * Now encrypt the key blob.
1202 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1204 smemclr(&md5c, sizeof(md5c));
1205 smemclr(keybuf, sizeof(keybuf));
1208 * If no encryption, the blob has exactly its original
1215 * And save it. We'll use Unix line endings just in case it's
1216 * subsequently transferred in binary mode.
1218 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1223 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1224 for (i = 0; i < 8; i++)
1225 fprintf(fp, "%02X", iv[i]);
1226 fprintf(fp, "\n\n");
1228 base64_encode(fp, outblob, outlen, 64);
1235 smemclr(outblob, outlen);
1239 smemclr(spareblob, sparelen);
1243 smemclr(privblob, privlen);
1247 smemclr(pubblob, publen);
1253 /* ----------------------------------------------------------------------
1254 * Code to read and write OpenSSH private keys in the new-style format.
1258 ON_E_NONE, ON_E_AES256CBC
1259 } openssh_new_cipher;
1261 ON_K_NONE, ON_K_BCRYPT
1264 struct openssh_new_key {
1265 openssh_new_cipher cipher;
1266 openssh_new_kdf kdf;
1270 /* This points to a position within keyblob, not a
1271 * separately allocated thing */
1272 const unsigned char *salt;
1276 int nkeys, key_wanted;
1277 /* This too points to a position within keyblob */
1278 unsigned char *privatestr;
1281 unsigned char *keyblob;
1282 int keyblob_len, keyblob_size;
1285 static struct openssh_new_key *load_openssh_new_key(const Filename *filename,
1286 const char **errmsg_p)
1288 struct openssh_new_key *ret;
1293 int base64_chars = 0;
1294 const void *filedata;
1296 const void *string, *kdfopts, *bcryptsalt, *pubkey;
1297 int stringlen, kdfoptlen, bcryptsaltlen, pubkeylen;
1298 unsigned bcryptrounds, nkeys, key_index;
1300 ret = snew(struct openssh_new_key);
1301 ret->keyblob = NULL;
1302 ret->keyblob_len = ret->keyblob_size = 0;
1304 fp = f_open(filename, "r", FALSE);
1306 errmsg = "unable to open key file";
1310 if (!(line = fgetline(fp))) {
1311 errmsg = "unexpected end of file";
1315 if (0 != strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
1316 errmsg = "file does not begin with OpenSSH new-style key header";
1319 smemclr(line, strlen(line));
1324 if (!(line = fgetline(fp))) {
1325 errmsg = "unexpected end of file";
1329 if (0 == strcmp(line, "-----END OPENSSH PRIVATE KEY-----")) {
1336 while (isbase64(*p)) {
1337 base64_bit[base64_chars++] = *p;
1338 if (base64_chars == 4) {
1339 unsigned char out[3];
1344 len = base64_decode_atom(base64_bit, out);
1347 errmsg = "invalid base64 encoding";
1351 if (ret->keyblob_len + len > ret->keyblob_size) {
1352 ret->keyblob_size = ret->keyblob_len + len + 256;
1353 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1357 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1358 ret->keyblob_len += len;
1360 smemclr(out, sizeof(out));
1365 smemclr(line, strlen(line));
1373 if (ret->keyblob_len == 0 || !ret->keyblob) {
1374 errmsg = "key body not present";
1378 filedata = ret->keyblob;
1379 filelen = ret->keyblob_len;
1381 if (filelen < 15 || 0 != memcmp(filedata, "openssh-key-v1\0", 15)) {
1382 errmsg = "new-style OpenSSH magic number missing\n";
1385 filedata = (const char *)filedata + 15;
1388 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1389 errmsg = "encountered EOF before cipher name\n";
1392 if (match_ssh_id(stringlen, string, "none")) {
1393 ret->cipher = ON_E_NONE;
1394 } else if (match_ssh_id(stringlen, string, "aes256-cbc")) {
1395 ret->cipher = ON_E_AES256CBC;
1397 errmsg = "unrecognised cipher name\n";
1401 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1402 errmsg = "encountered EOF before kdf name\n";
1405 if (match_ssh_id(stringlen, string, "none")) {
1406 ret->kdf = ON_K_NONE;
1407 } else if (match_ssh_id(stringlen, string, "bcrypt")) {
1408 ret->kdf = ON_K_BCRYPT;
1410 errmsg = "unrecognised kdf name\n";
1414 if (!(kdfopts = get_ssh_string(&filelen, &filedata, &kdfoptlen))) {
1415 errmsg = "encountered EOF before kdf options\n";
1420 if (kdfoptlen != 0) {
1421 errmsg = "expected empty options string for 'none' kdf";
1426 if (!(bcryptsalt = get_ssh_string(&kdfoptlen, &kdfopts,
1428 errmsg = "bcrypt options string did not contain salt\n";
1431 if (!get_ssh_uint32(&kdfoptlen, &kdfopts, &bcryptrounds)) {
1432 errmsg = "bcrypt options string did not contain round count\n";
1435 ret->kdfopts.bcrypt.salt = bcryptsalt;
1436 ret->kdfopts.bcrypt.saltlen = bcryptsaltlen;
1437 ret->kdfopts.bcrypt.rounds = bcryptrounds;
1442 * At this point we expect a uint32 saying how many keys are
1443 * stored in this file. OpenSSH new-style key files can
1444 * contain more than one. Currently we don't have any user
1445 * interface to specify which one we're trying to extract, so
1446 * we just bomb out with an error if more than one is found in
1447 * the file. However, I've put in all the mechanism here to
1448 * extract the nth one for a given n, in case we later connect
1449 * up some UI to that mechanism. Just arrange that the
1450 * 'key_wanted' field is set to a value in the range [0,
1451 * nkeys) by some mechanism.
1453 if (!get_ssh_uint32(&filelen, &filedata, &nkeys)) {
1454 errmsg = "encountered EOF before key count\n";
1458 errmsg = "multiple keys in new-style OpenSSH key file "
1463 ret->key_wanted = 0;
1465 for (key_index = 0; key_index < nkeys; key_index++) {
1466 if (!(pubkey = get_ssh_string(&filelen, &filedata, &pubkeylen))) {
1467 errmsg = "encountered EOF before kdf options\n";
1473 * Now we expect a string containing the encrypted part of the
1476 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
1477 errmsg = "encountered EOF before private key container\n";
1480 ret->privatestr = (unsigned char *)string;
1481 ret->privatelen = stringlen;
1484 * And now we're done, until asked to actually decrypt.
1487 smemclr(base64_bit, sizeof(base64_bit));
1488 if (errmsg_p) *errmsg_p = NULL;
1493 smemclr(line, strlen(line));
1497 smemclr(base64_bit, sizeof(base64_bit));
1500 smemclr(ret->keyblob, ret->keyblob_size);
1501 sfree(ret->keyblob);
1503 smemclr(ret, sizeof(*ret));
1506 if (errmsg_p) *errmsg_p = errmsg;
1511 int openssh_new_encrypted(const Filename *filename)
1513 struct openssh_new_key *key = load_openssh_new_key(filename, NULL);
1518 ret = (key->cipher != ON_E_NONE);
1519 smemclr(key->keyblob, key->keyblob_size);
1520 sfree(key->keyblob);
1521 smemclr(key, sizeof(*key));
1526 struct ssh2_userkey *openssh_new_read(const Filename *filename,
1528 const char **errmsg_p)
1530 struct openssh_new_key *key = load_openssh_new_key(filename, errmsg_p);
1531 struct ssh2_userkey *retkey;
1533 struct ssh2_userkey *retval = NULL;
1535 unsigned char *blob;
1537 unsigned checkint0, checkint1;
1538 const void *priv, *string;
1539 int privlen, stringlen, key_index;
1540 const struct ssh_signkey *alg;
1547 if (key->cipher != ON_E_NONE) {
1548 unsigned char keybuf[48];
1552 * Construct the decryption key, and decrypt the string.
1554 switch (key->cipher) {
1558 case ON_E_AES256CBC:
1559 keysize = 48; /* 32 byte key + 16 byte IV */
1562 assert(0 && "Bad cipher enumeration value");
1564 assert(keysize <= sizeof(keybuf));
1567 memset(keybuf, 0, keysize);
1570 openssh_bcrypt(passphrase,
1571 key->kdfopts.bcrypt.salt,
1572 key->kdfopts.bcrypt.saltlen,
1573 key->kdfopts.bcrypt.rounds,
1577 assert(0 && "Bad kdf enumeration value");
1579 switch (key->cipher) {
1582 case ON_E_AES256CBC:
1583 if (key->privatelen % 16 != 0) {
1584 errmsg = "private key container length is not a"
1585 " multiple of AES block size\n";
1589 void *ctx = aes_make_context();
1590 aes256_key(ctx, keybuf);
1591 aes_iv(ctx, keybuf + 32);
1592 aes_ssh2_decrypt_blk(ctx, key->privatestr,
1594 aes_free_context(ctx);
1598 assert(0 && "Bad cipher enumeration value");
1603 * Now parse the entire encrypted section, and extract the key
1604 * identified by key_wanted.
1606 priv = key->privatestr;
1607 privlen = key->privatelen;
1609 if (!get_ssh_uint32(&privlen, &priv, &checkint0) ||
1610 !get_ssh_uint32(&privlen, &priv, &checkint1) ||
1611 checkint0 != checkint1) {
1612 errmsg = "decryption check failed";
1617 for (key_index = 0; key_index < key->nkeys; key_index++) {
1618 unsigned char *thiskey;
1619 int thiskeylen, npieces;
1622 * Read the key type, which will tell us how to scan over
1623 * the key to get to the next one.
1625 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1626 errmsg = "expected key type in private string";
1631 * Preliminary key type identification, and decide how
1632 * many pieces of key we expect to see. Currently
1633 * (conveniently) all key types can be seen as some number
1634 * of strings, so we just need to know how many of them to
1635 * skip over. (The numbers below exclude the key comment.)
1637 if (match_ssh_id(stringlen, string, "ssh-rsa")) {
1639 npieces = 6; /* n,e,d,iqmp,q,p */
1640 } else if (match_ssh_id(stringlen, string, "ssh-dss")) {
1642 npieces = 5; /* p,q,g,y,x */
1643 } else if (match_ssh_id(stringlen, string,
1644 "ecdsa-sha2-nistp256")) {
1645 alg = &ssh_ecdsa_nistp256;
1646 npieces = 3; /* curve name, point, private exponent */
1647 } else if (match_ssh_id(stringlen, string,
1648 "ecdsa-sha2-nistp384")) {
1649 alg = &ssh_ecdsa_nistp384;
1650 npieces = 3; /* curve name, point, private exponent */
1651 } else if (match_ssh_id(stringlen, string,
1652 "ecdsa-sha2-nistp521")) {
1653 alg = &ssh_ecdsa_nistp521;
1654 npieces = 3; /* curve name, point, private exponent */
1656 errmsg = "private key did not start with type string\n";
1660 thiskey = (unsigned char *)priv;
1663 * Skip over the pieces of key.
1665 for (i = 0; i < npieces; i++) {
1666 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1667 errmsg = "ran out of data in mid-private-key";
1672 thiskeylen = (int)((const unsigned char *)priv -
1673 (const unsigned char *)thiskey);
1674 if (key_index == key->key_wanted) {
1675 retkey = snew(struct ssh2_userkey);
1677 retkey->data = alg->openssh_createkey(&thiskey, &thiskeylen);
1678 if (!retkey->data) {
1680 errmsg = "unable to create key data structure";
1686 * Read the key comment.
1688 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1689 errmsg = "ran out of data at key comment";
1692 if (key_index == key->key_wanted) {
1694 retkey->comment = dupprintf("%.*s", stringlen,
1695 (const char *)string);
1700 errmsg = "key index out of range";
1705 * Now we expect nothing left but padding.
1707 for (i = 0; i < privlen; i++) {
1708 if (((const unsigned char *)priv)[i] != (unsigned char)(i+1)) {
1709 errmsg = "padding at end of private string did not match";
1714 errmsg = NULL; /* no error */
1719 smemclr(blob, blobsize);
1722 smemclr(key->keyblob, key->keyblob_size);
1723 sfree(key->keyblob);
1724 smemclr(key, sizeof(*key));
1726 if (errmsg_p) *errmsg_p = errmsg;
1730 int openssh_new_write(const Filename *filename, struct ssh2_userkey *key,
1736 /* ----------------------------------------------------------------------
1737 * Code to read ssh.com private keys.
1741 * The format of the base64 blob is largely SSH-2-packet-formatted,
1742 * except that mpints are a bit different: they're more like the
1743 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1744 * (N+7)/8 bytes of data.
1746 * So. The blob contains:
1748 * - uint32 0x3f6ff9eb (magic number)
1749 * - uint32 size (total blob size)
1750 * - string key-type (see below)
1751 * - string cipher-type (tells you if key is encrypted)
1752 * - string encrypted-blob
1754 * (The first size field includes the size field itself and the
1755 * magic number before it. All other size fields are ordinary SSH-2
1756 * strings, so the size field indicates how much data is to
1759 * The encrypted blob, once decrypted, contains a single string
1760 * which in turn contains the payload. (This allows padding to be
1761 * added after that string while still making it clear where the
1762 * real payload ends. Also it probably makes for a reasonable
1763 * decryption check.)
1765 * The payload blob, for an RSA key, contains:
1768 * - mpint n (yes, the public and private stuff is intermixed)
1769 * - mpint u (presumably inverse of p mod q)
1770 * - mpint p (p is the smaller prime)
1771 * - mpint q (q is the larger)
1773 * For a DSA key, the payload blob contains:
1781 * Alternatively, if the parameters are `predefined', that
1782 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1783 * containing some predefined parameter specification. *shudder*,
1784 * but I doubt we'll encounter this in real life.
1786 * The key type strings are ghastly. The RSA key I looked at had a
1789 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1791 * and the DSA key wasn't much better:
1793 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1795 * It isn't clear that these will always be the same. I think it
1796 * might be wise just to look at the `if-modn{sign{rsa' and
1797 * `dl-modp{sign{dsa' prefixes.
1799 * Finally, the encryption. The cipher-type string appears to be
1800 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1801 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1802 * from the passphrase by means of yet another hashing faff:
1804 * - first 16 bytes are MD5(passphrase)
1805 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1806 * - if there were more, they'd be MD5(passphrase || first 32),
1810 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1813 char comment[256]; /* allowing any length is overkill */
1814 unsigned char *keyblob;
1815 int keyblob_len, keyblob_size;
1818 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1819 const char **errmsg_p)
1821 struct sshcom_key *ret;
1828 int base64_chars = 0;
1830 ret = snew(struct sshcom_key);
1831 ret->comment[0] = '\0';
1832 ret->keyblob = NULL;
1833 ret->keyblob_len = ret->keyblob_size = 0;
1835 fp = f_open(filename, "r", FALSE);
1837 errmsg = "unable to open key file";
1840 if (!(line = fgetline(fp))) {
1841 errmsg = "unexpected end of file";
1845 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1846 errmsg = "file does not begin with ssh.com key header";
1849 smemclr(line, strlen(line));
1855 if (!(line = fgetline(fp))) {
1856 errmsg = "unexpected end of file";
1860 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1865 if ((p = strchr(line, ':')) != NULL) {
1867 errmsg = "header found in body of key data";
1871 while (*p && isspace((unsigned char)*p)) p++;
1872 hdrstart = p - line;
1875 * Header lines can end in a trailing backslash for
1878 len = hdrstart + strlen(line+hdrstart);
1880 while (line[len-1] == '\\') {
1884 line2 = fgetline(fp);
1886 errmsg = "unexpected end of file";
1891 line2len = strlen(line2);
1892 line = sresize(line, len + line2len + 1, char);
1893 strcpy(line + len - 1, line2);
1894 len += line2len - 1;
1897 smemclr(line2, strlen(line2));
1901 p = line + hdrstart;
1903 if (!strcmp(line, "Comment")) {
1904 /* Strip quotes in comment if present. */
1905 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1907 p[strlen(p)-1] = '\0';
1909 strncpy(ret->comment, p, sizeof(ret->comment));
1910 ret->comment[sizeof(ret->comment)-1] = '\0';
1916 while (isbase64(*p)) {
1917 base64_bit[base64_chars++] = *p;
1918 if (base64_chars == 4) {
1919 unsigned char out[3];
1923 len = base64_decode_atom(base64_bit, out);
1926 errmsg = "invalid base64 encoding";
1930 if (ret->keyblob_len + len > ret->keyblob_size) {
1931 ret->keyblob_size = ret->keyblob_len + len + 256;
1932 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1936 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1937 ret->keyblob_len += len;
1943 smemclr(line, strlen(line));
1948 if (ret->keyblob_len == 0 || !ret->keyblob) {
1949 errmsg = "key body not present";
1954 if (errmsg_p) *errmsg_p = NULL;
1962 smemclr(line, strlen(line));
1968 smemclr(ret->keyblob, ret->keyblob_size);
1969 sfree(ret->keyblob);
1971 smemclr(ret, sizeof(*ret));
1974 if (errmsg_p) *errmsg_p = errmsg;
1978 int sshcom_encrypted(const Filename *filename, char **comment)
1980 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1981 int pos, len, answer;
1990 * Check magic number.
1992 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1993 goto done; /* key is invalid */
1997 * Find the cipher-type string.
2000 if (key->keyblob_len < pos+4)
2001 goto done; /* key is far too short */
2002 len = toint(GET_32BIT(key->keyblob + pos));
2003 if (len < 0 || len > key->keyblob_len - pos - 4)
2004 goto done; /* key is far too short */
2005 pos += 4 + len; /* skip key type */
2006 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
2007 if (len < 0 || len > key->keyblob_len - pos - 4)
2008 goto done; /* cipher type string is incomplete */
2009 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
2014 *comment = dupstr(key->comment);
2015 smemclr(key->keyblob, key->keyblob_size);
2016 sfree(key->keyblob);
2017 smemclr(key, sizeof(*key));
2020 *comment = dupstr("");
2025 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
2027 unsigned bits, bytes;
2028 unsigned char *d = (unsigned char *) data;
2032 bits = GET_32BIT(d);
2034 bytes = (bits + 7) / 8;
2045 return len; /* ensure further calls fail as well */
2048 static int sshcom_put_mpint(void *target, void *data, int len)
2050 unsigned char *d = (unsigned char *)target;
2051 unsigned char *i = (unsigned char *)data;
2052 int bits = len * 8 - 1;
2055 if (*i & (1 << (bits & 7)))
2061 PUT_32BIT(d, bits+1);
2062 memcpy(d+4, i, len);
2066 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
2067 const char **errmsg_p)
2069 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
2072 const char prefix_rsa[] = "if-modn{sign{rsa";
2073 const char prefix_dsa[] = "dl-modp{sign{dsa";
2074 enum { RSA, DSA } type;
2078 struct ssh2_userkey *ret = NULL, *retkey;
2079 const struct ssh_signkey *alg;
2080 unsigned char *blob = NULL;
2081 int blobsize = 0, publen, privlen;
2087 * Check magic number.
2089 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
2090 errmsg = "key does not begin with magic number";
2095 * Determine the key type.
2098 if (key->keyblob_len < pos+4 ||
2099 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2100 len > key->keyblob_len - pos - 4) {
2101 errmsg = "key blob does not contain a key type string";
2104 if (len > sizeof(prefix_rsa) - 1 &&
2105 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
2107 } else if (len > sizeof(prefix_dsa) - 1 &&
2108 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
2111 errmsg = "key is of unknown type";
2117 * Determine the cipher type.
2119 if (key->keyblob_len < pos+4 ||
2120 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2121 len > key->keyblob_len - pos - 4) {
2122 errmsg = "key blob does not contain a cipher type string";
2125 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
2127 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
2130 errmsg = "key encryption is of unknown type";
2136 * Get hold of the encrypted part of the key.
2138 if (key->keyblob_len < pos+4 ||
2139 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2140 len > key->keyblob_len - pos - 4) {
2141 errmsg = "key blob does not contain actual key data";
2144 ciphertext = (char *)key->keyblob + pos + 4;
2146 if (cipherlen == 0) {
2147 errmsg = "length of key data is zero";
2152 * Decrypt it if necessary.
2156 * Derive encryption key from passphrase and iv/salt:
2158 * - let block A equal MD5(passphrase)
2159 * - let block B equal MD5(passphrase || A)
2160 * - block C would be MD5(passphrase || A || B) and so on
2161 * - encryption key is the first N bytes of A || B
2163 struct MD5Context md5c;
2164 unsigned char keybuf[32], iv[8];
2166 if (cipherlen % 8 != 0) {
2167 errmsg = "encrypted part of key is not a multiple of cipher block"
2173 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2174 MD5Final(keybuf, &md5c);
2177 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2178 MD5Update(&md5c, keybuf, 16);
2179 MD5Final(keybuf+16, &md5c);
2182 * Now decrypt the key blob.
2184 memset(iv, 0, sizeof(iv));
2185 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2188 smemclr(&md5c, sizeof(md5c));
2189 smemclr(keybuf, sizeof(keybuf));
2192 * Hereafter we return WRONG_PASSPHRASE for any parsing
2193 * error. (But only if we've just tried to decrypt it!
2194 * Returning WRONG_PASSPHRASE for an unencrypted key is
2198 ret = SSH2_WRONG_PASSPHRASE;
2202 * Strip away the containing string to get to the real meat.
2204 len = toint(GET_32BIT(ciphertext));
2205 if (len < 0 || len > cipherlen-4) {
2206 errmsg = "containing string was ill-formed";
2213 * Now we break down into RSA versus DSA. In either case we'll
2214 * construct public and private blobs in our own format, and
2215 * end up feeding them to alg->createkey().
2217 blobsize = cipherlen + 256;
2218 blob = snewn(blobsize, unsigned char);
2221 struct mpint_pos n, e, d, u, p, q;
2223 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
2224 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
2225 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
2226 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
2227 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2228 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2230 errmsg = "key data did not contain six integers";
2236 pos += put_string(blob+pos, "ssh-rsa", 7);
2237 pos += put_mp(blob+pos, e.start, e.bytes);
2238 pos += put_mp(blob+pos, n.start, n.bytes);
2240 pos += put_string(blob+pos, d.start, d.bytes);
2241 pos += put_mp(blob+pos, q.start, q.bytes);
2242 pos += put_mp(blob+pos, p.start, p.bytes);
2243 pos += put_mp(blob+pos, u.start, u.bytes);
2244 privlen = pos - publen;
2246 struct mpint_pos p, q, g, x, y;
2249 assert(type == DSA); /* the only other option from the if above */
2251 if (GET_32BIT(ciphertext) != 0) {
2252 errmsg = "predefined DSA parameters not supported";
2255 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2256 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
2257 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2258 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
2259 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
2261 errmsg = "key data did not contain five integers";
2267 pos += put_string(blob+pos, "ssh-dss", 7);
2268 pos += put_mp(blob+pos, p.start, p.bytes);
2269 pos += put_mp(blob+pos, q.start, q.bytes);
2270 pos += put_mp(blob+pos, g.start, g.bytes);
2271 pos += put_mp(blob+pos, y.start, y.bytes);
2273 pos += put_mp(blob+pos, x.start, x.bytes);
2274 privlen = pos - publen;
2277 assert(privlen > 0); /* should have bombed by now if not */
2279 retkey = snew(struct ssh2_userkey);
2281 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
2282 if (!retkey->data) {
2284 errmsg = "unable to create key data structure";
2287 retkey->comment = dupstr(key->comment);
2289 errmsg = NULL; /* no error */
2294 smemclr(blob, blobsize);
2297 smemclr(key->keyblob, key->keyblob_size);
2298 sfree(key->keyblob);
2299 smemclr(key, sizeof(*key));
2301 if (errmsg_p) *errmsg_p = errmsg;
2305 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
2308 unsigned char *pubblob, *privblob;
2309 int publen, privlen;
2310 unsigned char *outblob;
2312 struct mpint_pos numbers[6];
2313 int nnumbers, initial_zero, pos, lenpos, i;
2321 * Fetch the key blobs.
2323 pubblob = key->alg->public_blob(key->data, &publen);
2324 privblob = key->alg->private_blob(key->data, &privlen);
2328 * Find the sequence of integers to be encoded into the OpenSSH
2329 * key blob, and also decide on the header line.
2331 if (key->alg == &ssh_rsa) {
2333 struct mpint_pos n, e, d, p, q, iqmp;
2336 * These blobs were generated from inside PuTTY, so we needn't
2337 * treat them as untrusted.
2339 pos = 4 + GET_32BIT(pubblob);
2340 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
2341 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
2343 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
2344 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
2345 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
2346 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
2348 assert(e.start && iqmp.start); /* can't go wrong */
2359 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
2360 } else if (key->alg == &ssh_dss) {
2362 struct mpint_pos p, q, g, y, x;
2365 * These blobs were generated from inside PuTTY, so we needn't
2366 * treat them as untrusted.
2368 pos = 4 + GET_32BIT(pubblob);
2369 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
2370 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
2371 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
2372 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
2374 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
2376 assert(y.start && x.start); /* can't go wrong */
2386 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
2388 assert(0); /* zoinks! */
2389 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
2393 * Total size of key blob will be somewhere under 512 plus
2394 * combined length of integers. We'll calculate the more
2395 * precise size as we construct the blob.
2398 for (i = 0; i < nnumbers; i++)
2399 outlen += 4 + numbers[i].bytes;
2400 outblob = snewn(outlen, unsigned char);
2403 * Create the unencrypted key blob.
2406 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
2407 pos += 4; /* length field, fill in later */
2408 pos += put_string(outblob+pos, type, strlen(type));
2410 char *ciphertype = passphrase ? "3des-cbc" : "none";
2411 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
2413 lenpos = pos; /* remember this position */
2414 pos += 4; /* encrypted-blob size */
2415 pos += 4; /* encrypted-payload size */
2417 PUT_32BIT(outblob+pos, 0);
2420 for (i = 0; i < nnumbers; i++)
2421 pos += sshcom_put_mpint(outblob+pos,
2422 numbers[i].start, numbers[i].bytes);
2423 /* Now wrap up the encrypted payload. */
2424 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
2425 /* Pad encrypted blob to a multiple of cipher block size. */
2427 int padding = -(pos - (lenpos+4)) & 7;
2429 outblob[pos++] = random_byte();
2431 ciphertext = (char *)outblob+lenpos+4;
2432 cipherlen = pos - (lenpos+4);
2433 assert(!passphrase || cipherlen % 8 == 0);
2434 /* Wrap up the encrypted blob string. */
2435 PUT_32BIT(outblob+lenpos, cipherlen);
2436 /* And finally fill in the total length field. */
2437 PUT_32BIT(outblob+4, pos);
2439 assert(pos < outlen);
2446 * Derive encryption key from passphrase and iv/salt:
2448 * - let block A equal MD5(passphrase)
2449 * - let block B equal MD5(passphrase || A)
2450 * - block C would be MD5(passphrase || A || B) and so on
2451 * - encryption key is the first N bytes of A || B
2453 struct MD5Context md5c;
2454 unsigned char keybuf[32], iv[8];
2457 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2458 MD5Final(keybuf, &md5c);
2461 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2462 MD5Update(&md5c, keybuf, 16);
2463 MD5Final(keybuf+16, &md5c);
2466 * Now decrypt the key blob.
2468 memset(iv, 0, sizeof(iv));
2469 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2472 smemclr(&md5c, sizeof(md5c));
2473 smemclr(keybuf, sizeof(keybuf));
2477 * And save it. We'll use Unix line endings just in case it's
2478 * subsequently transferred in binary mode.
2480 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
2483 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2484 fprintf(fp, "Comment: \"");
2486 * Comment header is broken with backslash-newline if it goes
2487 * over 70 chars. Although it's surrounded by quotes, it
2488 * _doesn't_ escape backslashes or quotes within the string.
2489 * Don't ask me, I didn't design it.
2492 int slen = 60; /* starts at 60 due to "Comment: " */
2493 char *c = key->comment;
2494 while ((int)strlen(c) > slen) {
2495 fprintf(fp, "%.*s\\\n", slen, c);
2497 slen = 70; /* allow 70 chars on subsequent lines */
2499 fprintf(fp, "%s\"\n", c);
2501 base64_encode(fp, outblob, pos, 70);
2502 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2508 smemclr(outblob, outlen);
2512 smemclr(privblob, privlen);
2516 smemclr(pubblob, publen);