2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 int openssh_encrypted(const Filename *filename);
16 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
17 const char **errmsg_p);
18 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
21 int sshcom_encrypted(const Filename *filename, char **comment);
22 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
23 const char **errmsg_p);
24 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
28 * Given a key type, determine whether we know how to import it.
30 int import_possible(int type)
32 if (type == SSH_KEYTYPE_OPENSSH)
34 if (type == SSH_KEYTYPE_SSHCOM)
40 * Given a key type, determine what native key type
41 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
44 int import_target_type(int type)
47 * There are no known foreign SSH-1 key formats.
49 return SSH_KEYTYPE_SSH2;
53 * Determine whether a foreign key is encrypted.
55 int import_encrypted(const Filename *filename, int type, char **comment)
57 if (type == SSH_KEYTYPE_OPENSSH) {
58 /* OpenSSH doesn't do key comments */
59 *comment = dupstr(filename_to_str(filename));
60 return openssh_encrypted(filename);
62 if (type == SSH_KEYTYPE_SSHCOM) {
63 return sshcom_encrypted(filename, comment);
69 * Import an SSH-1 key.
71 int import_ssh1(const Filename *filename, int type,
72 struct RSAKey *key, char *passphrase, const char **errmsg_p)
78 * Import an SSH-2 key.
80 struct ssh2_userkey *import_ssh2(const Filename *filename, int type,
81 char *passphrase, const char **errmsg_p)
83 if (type == SSH_KEYTYPE_OPENSSH)
84 return openssh_read(filename, passphrase, errmsg_p);
85 if (type == SSH_KEYTYPE_SSHCOM)
86 return sshcom_read(filename, passphrase, errmsg_p);
91 * Export an SSH-1 key.
93 int export_ssh1(const Filename *filename, int type, struct RSAKey *key,
100 * Export an SSH-2 key.
102 int export_ssh2(const Filename *filename, int type,
103 struct ssh2_userkey *key, char *passphrase)
105 if (type == SSH_KEYTYPE_OPENSSH)
106 return openssh_write(filename, key, passphrase);
107 if (type == SSH_KEYTYPE_SSHCOM)
108 return sshcom_write(filename, key, passphrase);
113 * Strip trailing CRs and LFs at the end of a line of text.
115 void strip_crlf(char *str)
117 char *p = str + strlen(str);
119 while (p > str && (p[-1] == '\r' || p[-1] == '\n'))
123 /* ----------------------------------------------------------------------
124 * Helper routines. (The base64 ones are defined in sshpubk.c.)
127 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
128 ((c) >= 'a' && (c) <= 'z') || \
129 ((c) >= '0' && (c) <= '9') || \
130 (c) == '+' || (c) == '/' || (c) == '=' \
134 * Read an ASN.1/BER identifier and length pair.
136 * Flags are a combination of the #defines listed below.
138 * Returns -1 if unsuccessful; otherwise returns the number of
139 * bytes used out of the source data.
142 /* ASN.1 tag classes. */
143 #define ASN1_CLASS_UNIVERSAL (0 << 6)
144 #define ASN1_CLASS_APPLICATION (1 << 6)
145 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
146 #define ASN1_CLASS_PRIVATE (3 << 6)
147 #define ASN1_CLASS_MASK (3 << 6)
149 /* Primitive versus constructed bit. */
150 #define ASN1_CONSTRUCTED (1 << 5)
152 static int ber_read_id_len(void *source, int sourcelen,
153 int *id, int *length, int *flags)
155 unsigned char *p = (unsigned char *) source;
160 *flags = (*p & 0xE0);
161 if ((*p & 0x1F) == 0x1F) {
167 *id = (*id << 7) | (*p & 0x7F);
185 *length = (*length << 8) | (*p++);
192 return p - (unsigned char *) source;
196 * Write an ASN.1/BER identifier and length pair. Returns the
197 * number of bytes consumed. Assumes dest contains enough space.
198 * Will avoid writing anything if dest is NULL, but still return
199 * amount of space required.
201 static int ber_write_id_len(void *dest, int id, int length, int flags)
203 unsigned char *d = (unsigned char *)dest;
208 * Identifier is one byte.
211 if (d) *d++ = id | flags;
215 * Identifier is multiple bytes: the first byte is 11111
216 * plus the flags, and subsequent bytes encode the value of
217 * the identifier, 7 bits at a time, with the top bit of
218 * each byte 1 except the last one which is 0.
221 if (d) *d++ = 0x1F | flags;
222 for (n = 1; (id >> (7*n)) > 0; n++)
223 continue; /* count the bytes */
226 if (d) *d++ = (n ? 0x80 : 0) | ((id >> (7*n)) & 0x7F);
232 * Length is one byte.
235 if (d) *d++ = length;
239 * Length is multiple bytes. The first is 0x80 plus the
240 * number of subsequent bytes, and the subsequent bytes
241 * encode the actual length.
243 for (n = 1; (length >> (8*n)) > 0; n++)
244 continue; /* count the bytes */
246 if (d) *d++ = 0x80 | n;
249 if (d) *d++ = (length >> (8*n)) & 0xFF;
256 static int put_string(void *target, void *data, int len)
258 unsigned char *d = (unsigned char *)target;
261 memcpy(d+4, data, len);
265 static int put_mp(void *target, void *data, int len)
267 unsigned char *d = (unsigned char *)target;
268 unsigned char *i = (unsigned char *)data;
273 memcpy(d+5, data, len);
277 memcpy(d+4, data, len);
282 /* Simple structure to point to an mp-int within a blob. */
283 struct mpint_pos { void *start; int bytes; };
285 static int ssh2_read_mpint(void *data, int len, struct mpint_pos *ret)
288 unsigned char *d = (unsigned char *) data;
292 bytes = toint(GET_32BIT(d));
293 if (bytes < 0 || len-4 < bytes)
303 return len; /* ensure further calls fail as well */
306 /* ----------------------------------------------------------------------
307 * Code to read and write OpenSSH private keys.
311 OSSH_DSA, OSSH_RSA, OSSH_ECDSA, OSSH_DUNNO_YET
314 OSSH_FMT_OLD, OSSH_FMT_NEW
317 OSSH_ENC_3DES, OSSH_ENC_AES
320 OSSH_E_NONE, OSSH_E_AES256CBC
321 } openssh_new_cipher;
323 OSSH_K_NONE, OSSH_K_BCRYPT
327 openssh_keytype keytype;
328 openssh_keyfmt keyfmt;
332 openssh_old_enc encryption;
336 openssh_new_cipher cipher;
341 /* This points to a position within keyblob, not a
342 * separately allocated thing */
343 const unsigned char *salt;
347 int nkeys, key_wanted;
348 /* This too points to a position within keyblob */
349 unsigned char *privatestr;
353 unsigned char *keyblob;
354 int keyblob_len, keyblob_size;
357 static int decrypt_openssh_key(struct openssh_key *key,
358 const char *passphrase,
361 assert(key->encrypted);
362 if (key->keyfmt == OSSH_FMT_OLD) {
364 * Derive encryption key from passphrase and iv/salt:
366 * - let block A equal MD5(passphrase || iv)
367 * - let block B equal MD5(A || passphrase || iv)
368 * - block C would be MD5(B || passphrase || iv) and so on
369 * - encryption key is the first N bytes of A || B
371 * (Note that only 8 bytes of the iv are used for key
372 * derivation, even when the key is encrypted with AES and
373 * hence there are 16 bytes available.)
375 struct MD5Context md5c;
376 unsigned char keybuf[32];
379 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
380 MD5Update(&md5c, (unsigned char *)key->u.old.iv, 8);
381 MD5Final(keybuf, &md5c);
384 MD5Update(&md5c, keybuf, 16);
385 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
386 MD5Update(&md5c, (unsigned char *)key->u.old.iv, 8);
387 MD5Final(keybuf+16, &md5c);
390 * Now decrypt the key blob.
392 if (key->u.old.encryption == OSSH_ENC_3DES)
393 des3_decrypt_pubkey_ossh(keybuf, (unsigned char *)key->u.old.iv,
394 key->keyblob, key->keyblob_len);
397 assert(key->u.old.encryption == OSSH_ENC_AES);
398 ctx = aes_make_context();
399 aes128_key(ctx, keybuf);
400 aes_iv(ctx, (unsigned char *)key->u.old.iv);
401 aes_ssh2_decrypt_blk(ctx, key->keyblob, key->keyblob_len);
402 aes_free_context(ctx);
405 smemclr(&md5c, sizeof(md5c));
406 smemclr(keybuf, sizeof(keybuf));
411 if (key->keyfmt == OSSH_FMT_NEW) {
412 unsigned char keybuf[48];
416 * Construct the decryption key, and decrypt the string.
418 switch (key->u.new.cipher) {
422 case OSSH_E_AES256CBC:
423 keysize = 48; /* 32 byte key + 16 byte IV */
426 assert(0 && "Bad cipher enumeration value");
428 assert(keysize <= sizeof(keybuf));
429 switch (key->u.new.kdf) {
431 memset(keybuf, 0, keysize);
434 openssh_bcrypt(passphrase,
435 key->u.new.kdfopts.bcrypt.salt,
436 key->u.new.kdfopts.bcrypt.saltlen,
437 key->u.new.kdfopts.bcrypt.rounds,
441 assert(0 && "Bad kdf enumeration value");
443 switch (key->u.new.cipher) {
446 case OSSH_E_AES256CBC:
447 if (key->u.new.privatelen % 16 != 0) {
448 *errmsg = "private key container length is not a"
449 " multiple of AES block size\n";
453 void *ctx = aes_make_context();
454 aes256_key(ctx, keybuf);
455 aes_iv(ctx, keybuf + 32);
456 aes_ssh2_decrypt_blk(ctx, key->u.new.privatestr,
457 key->u.new.privatelen);
458 aes_free_context(ctx);
462 assert(0 && "Bad cipher enumeration value");
467 assert(0 && "Bad key format in decrypt_openssh_key");
470 static struct openssh_key *load_openssh_key(const Filename *filename,
471 const char **errmsg_p)
473 struct openssh_key *ret;
479 int base64_chars = 0;
481 ret = snew(struct openssh_key);
483 ret->keyblob_len = ret->keyblob_size = 0;
485 fp = f_open(filename, "r", FALSE);
487 errmsg = "unable to open key file";
491 if (!(line = fgetline(fp))) {
492 errmsg = "unexpected end of file";
496 if (0 != strncmp(line, "-----BEGIN ", 11) ||
497 0 != strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
498 errmsg = "file does not begin with OpenSSH key header";
502 * Parse the BEGIN line. For old-format keys, this tells us the
503 * type of the key; for new-format keys, all it tells us is the
504 * format, and we'll find out the key type once we parse the
507 if (!strcmp(line, "-----BEGIN RSA PRIVATE KEY-----")) {
508 ret->keyfmt = OSSH_FMT_OLD;
509 ret->keytype = OSSH_RSA;
510 } else if (!strcmp(line, "-----BEGIN DSA PRIVATE KEY-----")) {
511 ret->keyfmt = OSSH_FMT_OLD;
512 ret->keytype = OSSH_DSA;
513 } else if (!strcmp(line, "-----BEGIN EC PRIVATE KEY-----")) {
514 ret->keyfmt = OSSH_FMT_OLD;
515 ret->keytype = OSSH_ECDSA;
516 } else if (!strcmp(line, "-----BEGIN OPENSSH PRIVATE KEY-----")) {
517 ret->keyfmt = OSSH_FMT_NEW;
518 ret->keytype = OSSH_DUNNO_YET;
520 errmsg = "unrecognised key type";
523 smemclr(line, strlen(line));
527 if (ret->keyfmt == OSSH_FMT_OLD) {
528 ret->encrypted = FALSE;
529 memset(ret->u.old.iv, 0, sizeof(ret->u.old.iv));
534 if (!(line = fgetline(fp))) {
535 errmsg = "unexpected end of file";
539 if (0 == strncmp(line, "-----END ", 9) &&
540 0 == strcmp(line+strlen(line)-16, "PRIVATE KEY-----")) {
545 if ((p = strchr(line, ':')) != NULL) {
546 if (ret->keyfmt != OSSH_FMT_OLD) {
547 errmsg = "expected no headers in new-style OpenSSH key format";
551 errmsg = "header found in body of key data";
555 while (*p && isspace((unsigned char)*p)) p++;
556 if (!strcmp(line, "Proc-Type")) {
557 if (p[0] != '4' || p[1] != ',') {
558 errmsg = "Proc-Type is not 4 (only 4 is supported)";
562 if (!strcmp(p, "ENCRYPTED"))
563 ret->encrypted = TRUE;
564 } else if (!strcmp(line, "DEK-Info")) {
567 if (!strncmp(p, "DES-EDE3-CBC,", 13)) {
568 ret->u.old.encryption = OSSH_ENC_3DES;
570 } else if (!strncmp(p, "AES-128-CBC,", 12)) {
571 ret->u.old.encryption = OSSH_ENC_AES;
574 errmsg = "unsupported cipher";
577 p = strchr(p, ',') + 1;/* always non-NULL, by above checks */
578 for (i = 0; i < ivlen; i++) {
579 if (1 != sscanf(p, "%2x", &j)) {
580 errmsg = "expected more iv data in DEK-Info";
583 ret->u.old.iv[i] = j;
587 errmsg = "more iv data than expected in DEK-Info";
595 while (isbase64(*p)) {
596 base64_bit[base64_chars++] = *p;
597 if (base64_chars == 4) {
598 unsigned char out[3];
603 len = base64_decode_atom(base64_bit, out);
606 errmsg = "invalid base64 encoding";
610 if (ret->keyblob_len + len > ret->keyblob_size) {
611 ret->keyblob_size = ret->keyblob_len + len + 256;
612 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
616 memcpy(ret->keyblob + ret->keyblob_len, out, len);
617 ret->keyblob_len += len;
619 smemclr(out, sizeof(out));
625 smemclr(line, strlen(line));
633 if (ret->keyblob_len == 0 || !ret->keyblob) {
634 errmsg = "key body not present";
638 if (ret->keyfmt == OSSH_FMT_NEW) {
640 * If we get here, then we haven't boiled down to a private
641 * key blob after all; we've merely stripped the base64
642 * wrapping from a new-style OpenSSH private key file. Now we
643 * have to parse that in turn, or at least get as far as the
646 const void *filedata = ret->keyblob;
647 int filelen = ret->keyblob_len;
648 const void *string, *kdfopts, *bcryptsalt, *pubkey;
649 int stringlen, kdfoptlen, bcryptsaltlen, pubkeylen;
650 unsigned bcryptrounds, nkeys, key_index;
652 if (filelen < 15 || 0 != memcmp(filedata, "openssh-key-v1\0", 15)) {
653 errmsg = "new-style OpenSSH magic number missing\n";
656 filedata = (const char *)filedata + 15;
659 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
660 errmsg = "encountered EOF before cipher name\n";
663 if (match_ssh_id(stringlen, string, "none")) {
664 ret->u.new.cipher = OSSH_E_NONE;
665 } else if (match_ssh_id(stringlen, string, "aes256-cbc")) {
666 ret->u.new.cipher = OSSH_E_AES256CBC;
668 errmsg = "unrecognised cipher name\n";
672 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
673 errmsg = "encountered EOF before kdf name\n";
676 if (match_ssh_id(stringlen, string, "none")) {
677 ret->u.new.kdf = OSSH_K_NONE;
678 } else if (match_ssh_id(stringlen, string, "bcrypt")) {
679 ret->u.new.kdf = OSSH_K_BCRYPT;
681 errmsg = "unrecognised kdf name\n";
685 if (!(kdfopts = get_ssh_string(&filelen, &filedata, &kdfoptlen))) {
686 errmsg = "encountered EOF before kdf options\n";
689 switch (ret->u.new.kdf) {
691 if (kdfoptlen != 0) {
692 errmsg = "expected empty options string for 'none' kdf";
697 if (!(bcryptsalt = get_ssh_string(&kdfoptlen, &kdfopts,
699 errmsg = "bcrypt options string did not contain salt\n";
702 if (!get_ssh_uint32(&kdfoptlen, &kdfopts, &bcryptrounds)) {
703 errmsg = "bcrypt options string did not contain round count\n";
706 ret->u.new.kdfopts.bcrypt.salt = bcryptsalt;
707 ret->u.new.kdfopts.bcrypt.saltlen = bcryptsaltlen;
708 ret->u.new.kdfopts.bcrypt.rounds = bcryptrounds;
712 ret->encrypted = (ret->u.new.cipher != OSSH_E_NONE);
715 * At this point we expect a uint32 saying how many keys are
716 * stored in this file. OpenSSH new-style key files can
717 * contain more than one. Currently we don't have any user
718 * interface to specify which one we're trying to extract, so
719 * we just bomb out with an error if more than one is found in
720 * the file. However, I've put in all the mechanism here to
721 * extract the nth one for a given n, in case we later connect
722 * up some UI to that mechanism. Just arrange that the
723 * 'key_wanted' field is set to a value in the range [0,
724 * nkeys) by some mechanism.
726 if (!get_ssh_uint32(&filelen, &filedata, &nkeys)) {
727 errmsg = "encountered EOF before key count\n";
731 errmsg = "multiple keys in new-style OpenSSH key file "
735 ret->u.new.nkeys = nkeys;
736 ret->u.new.key_wanted = 0;
738 for (key_index = 0; key_index < nkeys; key_index++) {
740 if (!(pubkey = get_ssh_string(&filelen, &filedata, &pubkeylen))) {
741 errmsg = "encountered EOF before kdf options\n";
745 * Check the key type, and make sure it's something we
748 if (!(string = get_ssh_string(&pubkeylen, &pubkey,
750 errmsg = "public key did not start with type string\n";
753 if (match_ssh_id(stringlen, string, "ssh-rsa")) {
754 this_keytype = OSSH_RSA;
755 } else if (match_ssh_id(stringlen, string, "ssh-dss")) {
756 this_keytype = OSSH_DSA;
757 } else if (match_ssh_id(stringlen, string,
758 "ecdsa-sha2-nistp256") ||
759 match_ssh_id(stringlen, string,
760 "ecdsa-sha2-nistp384") ||
761 match_ssh_id(stringlen, string,
762 "ecdsa-sha2-nistp521")) {
763 this_keytype = OSSH_ECDSA;
765 errmsg = "public key did not start with type string\n";
768 if (key_index == ret->u.new.key_wanted)
769 ret->keytype = this_keytype;
773 * Now we expect a string containing the encrypted part of the
776 if (!(string = get_ssh_string(&filelen, &filedata, &stringlen))) {
777 errmsg = "encountered EOF before private key container\n";
780 ret->u.new.privatestr = (unsigned char *)string;
781 ret->u.new.privatelen = stringlen;
784 * And now we're done, until asked to actually decrypt.
788 if (ret->keyfmt == OSSH_FMT_OLD) {
789 if (ret->encrypted && ret->keyblob_len % 8 != 0) {
790 errmsg = "encrypted key blob is not a multiple of "
796 smemclr(base64_bit, sizeof(base64_bit));
797 if (errmsg_p) *errmsg_p = NULL;
802 smemclr(line, strlen(line));
806 smemclr(base64_bit, sizeof(base64_bit));
809 smemclr(ret->keyblob, ret->keyblob_size);
812 smemclr(ret, sizeof(*ret));
815 if (errmsg_p) *errmsg_p = errmsg;
820 int openssh_encrypted(const Filename *filename)
822 struct openssh_key *key = load_openssh_key(filename, NULL);
827 ret = key->encrypted;
828 smemclr(key->keyblob, key->keyblob_size);
830 smemclr(key, sizeof(*key));
835 struct ssh2_userkey *openssh_read(const Filename *filename, char *passphrase,
836 const char **errmsg_p)
838 struct openssh_key *key = load_openssh_key(filename, errmsg_p);
839 struct ssh2_userkey *retkey;
841 int ret, id, len, flags;
843 struct ssh2_userkey *retval = NULL;
846 int blobsize = 0, blobptr, privptr;
855 if (key->encrypted) {
856 if (!decrypt_openssh_key(key, passphrase, &errmsg))
860 if (key->keyfmt == OSSH_FMT_OLD) {
862 * Now we have a decrypted key blob, which contains an ASN.1
863 * encoded private key. We must now untangle the ASN.1.
865 * We expect the whole key blob to be formatted as a SEQUENCE
866 * (0x30 followed by a length code indicating that the rest of
867 * the blob is part of the sequence). Within that SEQUENCE we
868 * expect to see a bunch of INTEGERs. What those integers mean
869 * depends on the key type:
871 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
872 * dmp1, dmq1, iqmp in that order. (The last three are d mod
873 * (p-1), d mod (q-1), inverse of q mod p respectively.)
875 * - For DSA, we expect them to be 0, p, q, g, y, x in that
878 * - In ECDSA the format is totally different: we see the
879 * SEQUENCE, but beneath is an INTEGER 1, OCTET STRING priv
880 * EXPLICIT [0] OID curve, EXPLICIT [1] BIT STRING pubPoint
885 /* Expect the SEQUENCE header. Take its absence as a failure to
886 * decrypt, if the key was encrypted. */
887 ret = ber_read_id_len(p, key->keyblob_len, &id, &len, &flags);
889 if (ret < 0 || id != 16) {
890 errmsg = "ASN.1 decoding failure";
891 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
895 /* Expect a load of INTEGERs. */
896 if (key->keytype == OSSH_RSA)
898 else if (key->keytype == OSSH_DSA)
901 num_integers = 0; /* placate compiler warnings */
904 if (key->keytype == OSSH_ECDSA) {
905 /* And now for something completely different */
908 struct ec_curve *curve;
910 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
913 if (ret < 0 || id != 2 || key->keyblob+key->keyblob_len-p < len ||
914 len != 1 || p[0] != 1) {
915 errmsg = "ASN.1 decoding failure";
916 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
920 /* Read private key OCTET STRING */
921 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
924 if (ret < 0 || id != 4 || key->keyblob+key->keyblob_len-p < len) {
925 errmsg = "ASN.1 decoding failure";
926 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
933 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
936 if (ret < 0 || id != 0 || key->keyblob+key->keyblob_len-p < len) {
937 errmsg = "ASN.1 decoding failure";
938 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
941 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
944 if (ret < 0 || id != 6 || key->keyblob+key->keyblob_len-p < len) {
945 errmsg = "ASN.1 decoding failure";
946 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
949 if (len == 8 && !memcmp(p, nistp256_oid, nistp256_oid_len)) {
951 } else if (len == 5 && !memcmp(p, nistp384_oid,
954 } else if (len == 5 && !memcmp(p, nistp521_oid,
958 errmsg = "Unsupported ECDSA curve.";
963 /* Read BIT STRING point */
964 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
967 if (ret < 0 || id != 1 || key->keyblob+key->keyblob_len-p < len) {
968 errmsg = "ASN.1 decoding failure";
969 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
972 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
975 if (ret < 0 || id != 3 || key->keyblob+key->keyblob_len-p < len ||
976 len != ((((curve->fieldBits + 7) / 8) * 2) + 2)) {
977 errmsg = "ASN.1 decoding failure";
978 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
981 p += 1; len -= 1; /* Skip 0x00 before point */
983 /* Construct the key */
984 retkey = snew(struct ssh2_userkey);
986 errmsg = "out of memory";
989 if (curve->fieldBits == 256) {
990 retkey->alg = &ssh_ecdsa_nistp256;
991 } else if (curve->fieldBits == 384) {
992 retkey->alg = &ssh_ecdsa_nistp384;
994 retkey->alg = &ssh_ecdsa_nistp521;
996 blob = snewn((4+19 + 4+8 + 4+len) + (4+privlen), unsigned char);
999 errmsg = "out of memory";
1002 PUT_32BIT(blob, 19);
1003 sprintf((char*)blob+4, "ecdsa-sha2-nistp%d", curve->fieldBits);
1004 PUT_32BIT(blob+4+19, 8);
1005 sprintf((char*)blob+4+19+4, "nistp%d", curve->fieldBits);
1006 PUT_32BIT(blob+4+19+4+8, len);
1007 memcpy(blob+4+19+4+8+4, p, len);
1008 PUT_32BIT(blob+4+19+4+8+4+len, privlen);
1009 memcpy(blob+4+19+4+8+4+len+4, priv, privlen);
1010 retkey->data = retkey->alg->createkey(blob, 4+19+4+8+4+len,
1011 blob+4+19+4+8+4+len,
1013 if (!retkey->data) {
1015 errmsg = "unable to create key data structure";
1019 } else if (key->keytype == OSSH_RSA || key->keytype == OSSH_DSA) {
1022 * Space to create key blob in.
1024 blobsize = 256+key->keyblob_len;
1025 blob = snewn(blobsize, unsigned char);
1027 if (key->keytype == OSSH_DSA)
1028 memcpy(blob+4, "ssh-dss", 7);
1029 else if (key->keytype == OSSH_RSA)
1030 memcpy(blob+4, "ssh-rsa", 7);
1034 for (i = 0; i < num_integers; i++) {
1035 ret = ber_read_id_len(p, key->keyblob+key->keyblob_len-p,
1038 if (ret < 0 || id != 2 ||
1039 key->keyblob+key->keyblob_len-p < len) {
1040 errmsg = "ASN.1 decoding failure";
1041 retval = key->encrypted ? SSH2_WRONG_PASSPHRASE : NULL;
1047 * The first integer should be zero always (I think
1048 * this is some sort of version indication).
1050 if (len != 1 || p[0] != 0) {
1051 errmsg = "version number mismatch";
1054 } else if (key->keytype == OSSH_RSA) {
1056 * Integers 1 and 2 go into the public blob but in the
1057 * opposite order; integers 3, 4, 5 and 8 go into the
1058 * private blob. The other two (6 and 7) are ignored.
1061 /* Save the details for after we deal with number 2. */
1064 } else if (i != 6 && i != 7) {
1065 PUT_32BIT(blob+blobptr, len);
1066 memcpy(blob+blobptr+4, p, len);
1069 PUT_32BIT(blob+blobptr, modlen);
1070 memcpy(blob+blobptr+4, modptr, modlen);
1071 blobptr += 4+modlen;
1075 } else if (key->keytype == OSSH_DSA) {
1077 * Integers 1-4 go into the public blob; integer 5 goes
1078 * into the private blob.
1080 PUT_32BIT(blob+blobptr, len);
1081 memcpy(blob+blobptr+4, p, len);
1087 /* Skip past the number. */
1092 * Now put together the actual key. Simplest way to do this is
1093 * to assemble our own key blobs and feed them to the createkey
1094 * functions; this is a bit faffy but it does mean we get all
1095 * the sanity checks for free.
1097 assert(privptr > 0); /* should have bombed by now if not */
1098 retkey = snew(struct ssh2_userkey);
1099 retkey->alg = (key->keytype == OSSH_RSA ? &ssh_rsa : &ssh_dss);
1100 retkey->data = retkey->alg->createkey(blob, privptr,
1103 if (!retkey->data) {
1105 errmsg = "unable to create key data structure";
1110 assert(0 && "Bad key type from load_openssh_key");
1114 * The old key format doesn't include a comment in the private
1117 retkey->comment = dupstr("imported-openssh-key");
1118 } else if (key->keyfmt == OSSH_FMT_NEW) {
1119 unsigned checkint0, checkint1;
1120 const void *priv, *string;
1121 int privlen, stringlen, key_index;
1122 const struct ssh_signkey *alg;
1125 * OpenSSH's new key format. Here we must parse the entire
1126 * encrypted section, and extract the key identified by
1129 priv = key->u.new.privatestr;
1130 privlen = key->u.new.privatelen;
1132 if (!get_ssh_uint32(&privlen, &priv, &checkint0) ||
1133 !get_ssh_uint32(&privlen, &priv, &checkint1) ||
1134 checkint0 != checkint1) {
1135 errmsg = "decryption check failed";
1140 for (key_index = 0; key_index < key->u.new.nkeys; key_index++) {
1141 unsigned char *thiskey;
1142 openssh_keytype this_keytype;
1143 int thiskeylen, npieces;
1146 * Read the key type, which will tell us how to scan over
1147 * the key to get to the next one.
1149 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1150 errmsg = "expected key type in private string";
1155 * Preliminary key type identification, and decide how
1156 * many pieces of key we expect to see. Currently
1157 * (conveniently) all key types can be seen as some number
1158 * of strings, so we just need to know how many of them to
1159 * skip over. (The numbers below exclude the key comment.)
1161 if (match_ssh_id(stringlen, string, "ssh-rsa")) {
1162 this_keytype = OSSH_RSA;
1164 npieces = 6; /* n,e,d,iqmp,q,p */
1165 } else if (match_ssh_id(stringlen, string, "ssh-dss")) {
1166 this_keytype = OSSH_DSA;
1168 npieces = 5; /* p,q,g,y,x */
1169 } else if (match_ssh_id(stringlen, string,
1170 "ecdsa-sha2-nistp256")) {
1171 this_keytype = OSSH_ECDSA;
1172 alg = &ssh_ecdsa_nistp256;
1173 npieces = 3; /* curve name, point, private exponent */
1174 } else if (match_ssh_id(stringlen, string,
1175 "ecdsa-sha2-nistp384")) {
1176 this_keytype = OSSH_ECDSA;
1177 alg = &ssh_ecdsa_nistp384;
1178 npieces = 3; /* curve name, point, private exponent */
1179 } else if (match_ssh_id(stringlen, string,
1180 "ecdsa-sha2-nistp521")) {
1181 this_keytype = OSSH_ECDSA;
1182 alg = &ssh_ecdsa_nistp521;
1183 npieces = 3; /* curve name, point, private exponent */
1185 errmsg = "private key did not start with type string\n";
1189 thiskey = (unsigned char *)priv;
1192 * Skip over the pieces of key.
1194 for (i = 0; i < npieces; i++) {
1195 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1196 errmsg = "ran out of data in mid-private-key";
1201 thiskeylen = (int)((const unsigned char *)priv -
1202 (const unsigned char *)thiskey);
1203 if (key_index == key->u.new.key_wanted) {
1204 if (this_keytype != key->keytype) {
1205 errmsg = "public and private key types did not match";
1208 retkey = snew(struct ssh2_userkey);
1210 retkey->data = alg->openssh_createkey(&thiskey, &thiskeylen);
1211 if (!retkey->data) {
1213 errmsg = "unable to create key data structure";
1219 * Read the key comment.
1221 if (!(string = get_ssh_string(&privlen, &priv, &stringlen))) {
1222 errmsg = "ran out of data at key comment";
1225 if (key_index == key->u.new.key_wanted) {
1227 retkey->comment = dupprintf("%.*s", stringlen,
1228 (const char *)string);
1233 errmsg = "key index out of range";
1238 * Now we expect nothing left but padding.
1240 for (i = 0; i < privlen; i++) {
1241 if (((const unsigned char *)priv)[i] != (unsigned char)(i+1)) {
1242 errmsg = "padding at end of private string did not match";
1247 assert(0 && "Bad key format from load_openssh_key");
1250 errmsg = NULL; /* no error */
1255 smemclr(blob, blobsize);
1258 smemclr(key->keyblob, key->keyblob_size);
1259 sfree(key->keyblob);
1260 smemclr(key, sizeof(*key));
1262 if (errmsg_p) *errmsg_p = errmsg;
1266 int openssh_write(const Filename *filename, struct ssh2_userkey *key,
1269 unsigned char *pubblob, *privblob, *spareblob;
1270 int publen, privlen, sparelen = 0;
1271 unsigned char *outblob;
1273 struct mpint_pos numbers[9];
1274 int nnumbers, pos, len, seqlen, i;
1275 char *header, *footer;
1277 unsigned char iv[8];
1282 * Fetch the key blobs.
1284 pubblob = key->alg->public_blob(key->data, &publen);
1285 privblob = key->alg->private_blob(key->data, &privlen);
1286 spareblob = outblob = NULL;
1292 * Encode the OpenSSH key blob, and also decide on the header
1295 if (key->alg == &ssh_rsa || key->alg == &ssh_dss) {
1297 * The RSA and DSS handlers share some code because the two
1298 * key types have very similar ASN.1 representations, as a
1299 * plain SEQUENCE of big integers. So we set up a list of
1300 * bignums per key type and then construct the actual blob in
1301 * common code after that.
1303 if (key->alg == &ssh_rsa) {
1305 struct mpint_pos n, e, d, p, q, iqmp, dmp1, dmq1;
1306 Bignum bd, bp, bq, bdmp1, bdmq1;
1309 * These blobs were generated from inside PuTTY, so we needn't
1310 * treat them as untrusted.
1312 pos = 4 + GET_32BIT(pubblob);
1313 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
1314 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
1316 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
1317 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
1318 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
1319 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
1321 assert(e.start && iqmp.start); /* can't go wrong */
1323 /* We also need d mod (p-1) and d mod (q-1). */
1324 bd = bignum_from_bytes(d.start, d.bytes);
1325 bp = bignum_from_bytes(p.start, p.bytes);
1326 bq = bignum_from_bytes(q.start, q.bytes);
1329 bdmp1 = bigmod(bd, bp);
1330 bdmq1 = bigmod(bd, bq);
1335 dmp1.bytes = (bignum_bitcount(bdmp1)+8)/8;
1336 dmq1.bytes = (bignum_bitcount(bdmq1)+8)/8;
1337 sparelen = dmp1.bytes + dmq1.bytes;
1338 spareblob = snewn(sparelen, unsigned char);
1339 dmp1.start = spareblob;
1340 dmq1.start = spareblob + dmp1.bytes;
1341 for (i = 0; i < dmp1.bytes; i++)
1342 spareblob[i] = bignum_byte(bdmp1, dmp1.bytes-1 - i);
1343 for (i = 0; i < dmq1.bytes; i++)
1344 spareblob[i+dmp1.bytes] = bignum_byte(bdmq1, dmq1.bytes-1 - i);
1348 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1359 header = "-----BEGIN RSA PRIVATE KEY-----\n";
1360 footer = "-----END RSA PRIVATE KEY-----\n";
1361 } else { /* ssh-dss */
1363 struct mpint_pos p, q, g, y, x;
1366 * These blobs were generated from inside PuTTY, so we needn't
1367 * treat them as untrusted.
1369 pos = 4 + GET_32BIT(pubblob);
1370 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
1371 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
1372 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
1373 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
1375 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
1377 assert(y.start && x.start); /* can't go wrong */
1379 numbers[0].start = zero; numbers[0].bytes = 1; zero[0] = '\0';
1387 header = "-----BEGIN DSA PRIVATE KEY-----\n";
1388 footer = "-----END DSA PRIVATE KEY-----\n";
1392 * Now count up the total size of the ASN.1 encoded integers,
1393 * so as to determine the length of the containing SEQUENCE.
1396 for (i = 0; i < nnumbers; i++) {
1397 len += ber_write_id_len(NULL, 2, numbers[i].bytes, 0);
1398 len += numbers[i].bytes;
1401 /* Now add on the SEQUENCE header. */
1402 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1405 * Now we know how big outblob needs to be. Allocate it.
1407 outblob = snewn(len, unsigned char);
1410 * And write the data into it.
1413 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1414 for (i = 0; i < nnumbers; i++) {
1415 pos += ber_write_id_len(outblob+pos, 2, numbers[i].bytes, 0);
1416 memcpy(outblob+pos, numbers[i].start, numbers[i].bytes);
1417 pos += numbers[i].bytes;
1419 } else if (key->alg == &ssh_ecdsa_nistp256 ||
1420 key->alg == &ssh_ecdsa_nistp384 ||
1421 key->alg == &ssh_ecdsa_nistp521) {
1427 * Structure of asn1:
1430 * OCTET STRING (private key)
1434 * BIT STRING (0x00 public key point)
1436 switch (((struct ec_key *)key->data)->publicKey.curve->fieldBits) {
1438 /* OID: 1.2.840.10045.3.1.7 (ansiX9p256r1) */
1440 oidlen = nistp256_oid_len;
1444 /* OID: 1.3.132.0.34 (secp384r1) */
1446 oidlen = nistp384_oid_len;
1450 /* OID: 1.3.132.0.35 (secp521r1) */
1452 oidlen = nistp521_oid_len;
1459 len = ber_write_id_len(NULL, 2, 1, 0);
1461 len += ber_write_id_len(NULL, 4, privlen - 4, 0);
1463 len += ber_write_id_len(NULL, 0, oidlen +
1464 ber_write_id_len(NULL, 6, oidlen, 0),
1465 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1466 len += ber_write_id_len(NULL, 6, oidlen, 0);
1468 len += ber_write_id_len(NULL, 1, 2 + pointlen +
1469 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1470 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1471 len += ber_write_id_len(NULL, 3, 2 + pointlen, 0);
1472 len += 2 + pointlen;
1475 len += ber_write_id_len(NULL, 16, seqlen, ASN1_CONSTRUCTED);
1477 outblob = snewn(len, unsigned char);
1481 pos += ber_write_id_len(outblob+pos, 16, seqlen, ASN1_CONSTRUCTED);
1482 pos += ber_write_id_len(outblob+pos, 2, 1, 0);
1484 pos += ber_write_id_len(outblob+pos, 4, privlen - 4, 0);
1485 memcpy(outblob+pos, privblob + 4, privlen - 4);
1487 pos += ber_write_id_len(outblob+pos, 0, oidlen +
1488 ber_write_id_len(NULL, 6, oidlen, 0),
1489 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1490 pos += ber_write_id_len(outblob+pos, 6, oidlen, 0);
1491 memcpy(outblob+pos, oid, oidlen);
1493 pos += ber_write_id_len(outblob+pos, 1, 2 + pointlen +
1494 ber_write_id_len(NULL, 3, 2 + pointlen, 0),
1495 ASN1_CLASS_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED);
1496 pos += ber_write_id_len(outblob+pos, 3, 2 + pointlen, 0);
1498 memcpy(outblob+pos, pubblob+39, 1 + pointlen);
1499 pos += 1 + pointlen;
1501 header = "-----BEGIN EC PRIVATE KEY-----\n";
1502 footer = "-----END EC PRIVATE KEY-----\n";
1504 assert(0); /* zoinks! */
1505 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1511 * For the moment, we still encrypt our OpenSSH keys using
1515 struct MD5Context md5c;
1516 unsigned char keybuf[32];
1519 * Round up to the cipher block size, ensuring we have at
1520 * least one byte of padding (see below).
1522 outlen = (len+8) &~ 7;
1524 unsigned char *tmp = snewn(outlen, unsigned char);
1525 memcpy(tmp, outblob, len);
1526 smemclr(outblob, len);
1532 * Padding on OpenSSH keys is deterministic. The number of
1533 * padding bytes is always more than zero, and always at most
1534 * the cipher block length. The value of each padding byte is
1535 * equal to the number of padding bytes. So a plaintext that's
1536 * an exact multiple of the block size will be padded with 08
1537 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
1538 * plaintext one byte less than a multiple of the block size
1539 * will be padded with just 01.
1541 * This enables the OpenSSL key decryption function to strip
1542 * off the padding algorithmically and return the unpadded
1543 * plaintext to the next layer: it looks at the final byte, and
1544 * then expects to find that many bytes at the end of the data
1545 * with the same value. Those are all removed and the rest is
1549 while (pos < outlen) {
1550 outblob[pos++] = outlen - len;
1554 * Invent an iv. Then derive encryption key from passphrase
1557 * - let block A equal MD5(passphrase || iv)
1558 * - let block B equal MD5(A || passphrase || iv)
1559 * - block C would be MD5(B || passphrase || iv) and so on
1560 * - encryption key is the first N bytes of A || B
1562 for (i = 0; i < 8; i++) iv[i] = random_byte();
1565 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1566 MD5Update(&md5c, iv, 8);
1567 MD5Final(keybuf, &md5c);
1570 MD5Update(&md5c, keybuf, 16);
1571 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
1572 MD5Update(&md5c, iv, 8);
1573 MD5Final(keybuf+16, &md5c);
1576 * Now encrypt the key blob.
1578 des3_encrypt_pubkey_ossh(keybuf, iv, outblob, outlen);
1580 smemclr(&md5c, sizeof(md5c));
1581 smemclr(keybuf, sizeof(keybuf));
1584 * If no encryption, the blob has exactly its original
1591 * And save it. We'll use Unix line endings just in case it's
1592 * subsequently transferred in binary mode.
1594 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
1599 fprintf(fp, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
1600 for (i = 0; i < 8; i++)
1601 fprintf(fp, "%02X", iv[i]);
1602 fprintf(fp, "\n\n");
1604 base64_encode(fp, outblob, outlen, 64);
1611 smemclr(outblob, outlen);
1615 smemclr(spareblob, sparelen);
1619 smemclr(privblob, privlen);
1623 smemclr(pubblob, publen);
1629 /* ----------------------------------------------------------------------
1630 * Code to read ssh.com private keys.
1634 * The format of the base64 blob is largely SSH-2-packet-formatted,
1635 * except that mpints are a bit different: they're more like the
1636 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
1637 * (N+7)/8 bytes of data.
1639 * So. The blob contains:
1641 * - uint32 0x3f6ff9eb (magic number)
1642 * - uint32 size (total blob size)
1643 * - string key-type (see below)
1644 * - string cipher-type (tells you if key is encrypted)
1645 * - string encrypted-blob
1647 * (The first size field includes the size field itself and the
1648 * magic number before it. All other size fields are ordinary SSH-2
1649 * strings, so the size field indicates how much data is to
1652 * The encrypted blob, once decrypted, contains a single string
1653 * which in turn contains the payload. (This allows padding to be
1654 * added after that string while still making it clear where the
1655 * real payload ends. Also it probably makes for a reasonable
1656 * decryption check.)
1658 * The payload blob, for an RSA key, contains:
1661 * - mpint n (yes, the public and private stuff is intermixed)
1662 * - mpint u (presumably inverse of p mod q)
1663 * - mpint p (p is the smaller prime)
1664 * - mpint q (q is the larger)
1666 * For a DSA key, the payload blob contains:
1674 * Alternatively, if the parameters are `predefined', that
1675 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
1676 * containing some predefined parameter specification. *shudder*,
1677 * but I doubt we'll encounter this in real life.
1679 * The key type strings are ghastly. The RSA key I looked at had a
1682 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
1684 * and the DSA key wasn't much better:
1686 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
1688 * It isn't clear that these will always be the same. I think it
1689 * might be wise just to look at the `if-modn{sign{rsa' and
1690 * `dl-modp{sign{dsa' prefixes.
1692 * Finally, the encryption. The cipher-type string appears to be
1693 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
1694 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
1695 * from the passphrase by means of yet another hashing faff:
1697 * - first 16 bytes are MD5(passphrase)
1698 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1699 * - if there were more, they'd be MD5(passphrase || first 32),
1703 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1706 char comment[256]; /* allowing any length is overkill */
1707 unsigned char *keyblob;
1708 int keyblob_len, keyblob_size;
1711 static struct sshcom_key *load_sshcom_key(const Filename *filename,
1712 const char **errmsg_p)
1714 struct sshcom_key *ret;
1721 int base64_chars = 0;
1723 ret = snew(struct sshcom_key);
1724 ret->comment[0] = '\0';
1725 ret->keyblob = NULL;
1726 ret->keyblob_len = ret->keyblob_size = 0;
1728 fp = f_open(filename, "r", FALSE);
1730 errmsg = "unable to open key file";
1733 if (!(line = fgetline(fp))) {
1734 errmsg = "unexpected end of file";
1738 if (0 != strcmp(line, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1739 errmsg = "file does not begin with ssh.com key header";
1742 smemclr(line, strlen(line));
1748 if (!(line = fgetline(fp))) {
1749 errmsg = "unexpected end of file";
1753 if (!strcmp(line, "---- END SSH2 ENCRYPTED PRIVATE KEY ----")) {
1758 if ((p = strchr(line, ':')) != NULL) {
1760 errmsg = "header found in body of key data";
1764 while (*p && isspace((unsigned char)*p)) p++;
1765 hdrstart = p - line;
1768 * Header lines can end in a trailing backslash for
1771 len = hdrstart + strlen(line+hdrstart);
1773 while (line[len-1] == '\\') {
1777 line2 = fgetline(fp);
1779 errmsg = "unexpected end of file";
1784 line2len = strlen(line2);
1785 line = sresize(line, len + line2len + 1, char);
1786 strcpy(line + len - 1, line2);
1787 len += line2len - 1;
1790 smemclr(line2, strlen(line2));
1794 p = line + hdrstart;
1796 if (!strcmp(line, "Comment")) {
1797 /* Strip quotes in comment if present. */
1798 if (p[0] == '"' && p[strlen(p)-1] == '"') {
1800 p[strlen(p)-1] = '\0';
1802 strncpy(ret->comment, p, sizeof(ret->comment));
1803 ret->comment[sizeof(ret->comment)-1] = '\0';
1809 while (isbase64(*p)) {
1810 base64_bit[base64_chars++] = *p;
1811 if (base64_chars == 4) {
1812 unsigned char out[3];
1816 len = base64_decode_atom(base64_bit, out);
1819 errmsg = "invalid base64 encoding";
1823 if (ret->keyblob_len + len > ret->keyblob_size) {
1824 ret->keyblob_size = ret->keyblob_len + len + 256;
1825 ret->keyblob = sresize(ret->keyblob, ret->keyblob_size,
1829 memcpy(ret->keyblob + ret->keyblob_len, out, len);
1830 ret->keyblob_len += len;
1836 smemclr(line, strlen(line));
1841 if (ret->keyblob_len == 0 || !ret->keyblob) {
1842 errmsg = "key body not present";
1847 if (errmsg_p) *errmsg_p = NULL;
1855 smemclr(line, strlen(line));
1861 smemclr(ret->keyblob, ret->keyblob_size);
1862 sfree(ret->keyblob);
1864 smemclr(ret, sizeof(*ret));
1867 if (errmsg_p) *errmsg_p = errmsg;
1871 int sshcom_encrypted(const Filename *filename, char **comment)
1873 struct sshcom_key *key = load_sshcom_key(filename, NULL);
1874 int pos, len, answer;
1883 * Check magic number.
1885 if (GET_32BIT(key->keyblob) != 0x3f6ff9eb) {
1886 goto done; /* key is invalid */
1890 * Find the cipher-type string.
1893 if (key->keyblob_len < pos+4)
1894 goto done; /* key is far too short */
1895 len = toint(GET_32BIT(key->keyblob + pos));
1896 if (len < 0 || len > key->keyblob_len - pos - 4)
1897 goto done; /* key is far too short */
1898 pos += 4 + len; /* skip key type */
1899 len = toint(GET_32BIT(key->keyblob + pos)); /* find cipher-type length */
1900 if (len < 0 || len > key->keyblob_len - pos - 4)
1901 goto done; /* cipher type string is incomplete */
1902 if (len != 4 || 0 != memcmp(key->keyblob + pos + 4, "none", 4))
1907 *comment = dupstr(key->comment);
1908 smemclr(key->keyblob, key->keyblob_size);
1909 sfree(key->keyblob);
1910 smemclr(key, sizeof(*key));
1913 *comment = dupstr("");
1918 static int sshcom_read_mpint(void *data, int len, struct mpint_pos *ret)
1920 unsigned bits, bytes;
1921 unsigned char *d = (unsigned char *) data;
1925 bits = GET_32BIT(d);
1927 bytes = (bits + 7) / 8;
1938 return len; /* ensure further calls fail as well */
1941 static int sshcom_put_mpint(void *target, void *data, int len)
1943 unsigned char *d = (unsigned char *)target;
1944 unsigned char *i = (unsigned char *)data;
1945 int bits = len * 8 - 1;
1948 if (*i & (1 << (bits & 7)))
1954 PUT_32BIT(d, bits+1);
1955 memcpy(d+4, i, len);
1959 struct ssh2_userkey *sshcom_read(const Filename *filename, char *passphrase,
1960 const char **errmsg_p)
1962 struct sshcom_key *key = load_sshcom_key(filename, errmsg_p);
1965 const char prefix_rsa[] = "if-modn{sign{rsa";
1966 const char prefix_dsa[] = "dl-modp{sign{dsa";
1967 enum { RSA, DSA } type;
1971 struct ssh2_userkey *ret = NULL, *retkey;
1972 const struct ssh_signkey *alg;
1973 unsigned char *blob = NULL;
1974 int blobsize = 0, publen, privlen;
1980 * Check magic number.
1982 if (GET_32BIT(key->keyblob) != SSHCOM_MAGIC_NUMBER) {
1983 errmsg = "key does not begin with magic number";
1988 * Determine the key type.
1991 if (key->keyblob_len < pos+4 ||
1992 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
1993 len > key->keyblob_len - pos - 4) {
1994 errmsg = "key blob does not contain a key type string";
1997 if (len > sizeof(prefix_rsa) - 1 &&
1998 !memcmp(key->keyblob+pos+4, prefix_rsa, sizeof(prefix_rsa) - 1)) {
2000 } else if (len > sizeof(prefix_dsa) - 1 &&
2001 !memcmp(key->keyblob+pos+4, prefix_dsa, sizeof(prefix_dsa) - 1)) {
2004 errmsg = "key is of unknown type";
2010 * Determine the cipher type.
2012 if (key->keyblob_len < pos+4 ||
2013 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2014 len > key->keyblob_len - pos - 4) {
2015 errmsg = "key blob does not contain a cipher type string";
2018 if (len == 4 && !memcmp(key->keyblob+pos+4, "none", 4))
2020 else if (len == 8 && !memcmp(key->keyblob+pos+4, "3des-cbc", 8))
2023 errmsg = "key encryption is of unknown type";
2029 * Get hold of the encrypted part of the key.
2031 if (key->keyblob_len < pos+4 ||
2032 (len = toint(GET_32BIT(key->keyblob + pos))) < 0 ||
2033 len > key->keyblob_len - pos - 4) {
2034 errmsg = "key blob does not contain actual key data";
2037 ciphertext = (char *)key->keyblob + pos + 4;
2039 if (cipherlen == 0) {
2040 errmsg = "length of key data is zero";
2045 * Decrypt it if necessary.
2049 * Derive encryption key from passphrase and iv/salt:
2051 * - let block A equal MD5(passphrase)
2052 * - let block B equal MD5(passphrase || A)
2053 * - block C would be MD5(passphrase || A || B) and so on
2054 * - encryption key is the first N bytes of A || B
2056 struct MD5Context md5c;
2057 unsigned char keybuf[32], iv[8];
2059 if (cipherlen % 8 != 0) {
2060 errmsg = "encrypted part of key is not a multiple of cipher block"
2066 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2067 MD5Final(keybuf, &md5c);
2070 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2071 MD5Update(&md5c, keybuf, 16);
2072 MD5Final(keybuf+16, &md5c);
2075 * Now decrypt the key blob.
2077 memset(iv, 0, sizeof(iv));
2078 des3_decrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2081 smemclr(&md5c, sizeof(md5c));
2082 smemclr(keybuf, sizeof(keybuf));
2085 * Hereafter we return WRONG_PASSPHRASE for any parsing
2086 * error. (But only if we've just tried to decrypt it!
2087 * Returning WRONG_PASSPHRASE for an unencrypted key is
2091 ret = SSH2_WRONG_PASSPHRASE;
2095 * Strip away the containing string to get to the real meat.
2097 len = toint(GET_32BIT(ciphertext));
2098 if (len < 0 || len > cipherlen-4) {
2099 errmsg = "containing string was ill-formed";
2106 * Now we break down into RSA versus DSA. In either case we'll
2107 * construct public and private blobs in our own format, and
2108 * end up feeding them to alg->createkey().
2110 blobsize = cipherlen + 256;
2111 blob = snewn(blobsize, unsigned char);
2114 struct mpint_pos n, e, d, u, p, q;
2116 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &e);
2117 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &d);
2118 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &n);
2119 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &u);
2120 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2121 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2123 errmsg = "key data did not contain six integers";
2129 pos += put_string(blob+pos, "ssh-rsa", 7);
2130 pos += put_mp(blob+pos, e.start, e.bytes);
2131 pos += put_mp(blob+pos, n.start, n.bytes);
2133 pos += put_string(blob+pos, d.start, d.bytes);
2134 pos += put_mp(blob+pos, q.start, q.bytes);
2135 pos += put_mp(blob+pos, p.start, p.bytes);
2136 pos += put_mp(blob+pos, u.start, u.bytes);
2137 privlen = pos - publen;
2139 struct mpint_pos p, q, g, x, y;
2142 assert(type == DSA); /* the only other option from the if above */
2144 if (GET_32BIT(ciphertext) != 0) {
2145 errmsg = "predefined DSA parameters not supported";
2148 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &p);
2149 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &g);
2150 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &q);
2151 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &y);
2152 pos += sshcom_read_mpint(ciphertext+pos, cipherlen-pos, &x);
2154 errmsg = "key data did not contain five integers";
2160 pos += put_string(blob+pos, "ssh-dss", 7);
2161 pos += put_mp(blob+pos, p.start, p.bytes);
2162 pos += put_mp(blob+pos, q.start, q.bytes);
2163 pos += put_mp(blob+pos, g.start, g.bytes);
2164 pos += put_mp(blob+pos, y.start, y.bytes);
2166 pos += put_mp(blob+pos, x.start, x.bytes);
2167 privlen = pos - publen;
2170 assert(privlen > 0); /* should have bombed by now if not */
2172 retkey = snew(struct ssh2_userkey);
2174 retkey->data = alg->createkey(blob, publen, blob+publen, privlen);
2175 if (!retkey->data) {
2177 errmsg = "unable to create key data structure";
2180 retkey->comment = dupstr(key->comment);
2182 errmsg = NULL; /* no error */
2187 smemclr(blob, blobsize);
2190 smemclr(key->keyblob, key->keyblob_size);
2191 sfree(key->keyblob);
2192 smemclr(key, sizeof(*key));
2194 if (errmsg_p) *errmsg_p = errmsg;
2198 int sshcom_write(const Filename *filename, struct ssh2_userkey *key,
2201 unsigned char *pubblob, *privblob;
2202 int publen, privlen;
2203 unsigned char *outblob;
2205 struct mpint_pos numbers[6];
2206 int nnumbers, initial_zero, pos, lenpos, i;
2214 * Fetch the key blobs.
2216 pubblob = key->alg->public_blob(key->data, &publen);
2217 privblob = key->alg->private_blob(key->data, &privlen);
2221 * Find the sequence of integers to be encoded into the OpenSSH
2222 * key blob, and also decide on the header line.
2224 if (key->alg == &ssh_rsa) {
2226 struct mpint_pos n, e, d, p, q, iqmp;
2229 * These blobs were generated from inside PuTTY, so we needn't
2230 * treat them as untrusted.
2232 pos = 4 + GET_32BIT(pubblob);
2233 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &e);
2234 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &n);
2236 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &d);
2237 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &p);
2238 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &q);
2239 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &iqmp);
2241 assert(e.start && iqmp.start); /* can't go wrong */
2252 type = "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
2253 } else if (key->alg == &ssh_dss) {
2255 struct mpint_pos p, q, g, y, x;
2258 * These blobs were generated from inside PuTTY, so we needn't
2259 * treat them as untrusted.
2261 pos = 4 + GET_32BIT(pubblob);
2262 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &p);
2263 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &q);
2264 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &g);
2265 pos += ssh2_read_mpint(pubblob+pos, publen-pos, &y);
2267 pos += ssh2_read_mpint(privblob+pos, privlen-pos, &x);
2269 assert(y.start && x.start); /* can't go wrong */
2279 type = "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
2281 assert(0); /* zoinks! */
2282 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
2286 * Total size of key blob will be somewhere under 512 plus
2287 * combined length of integers. We'll calculate the more
2288 * precise size as we construct the blob.
2291 for (i = 0; i < nnumbers; i++)
2292 outlen += 4 + numbers[i].bytes;
2293 outblob = snewn(outlen, unsigned char);
2296 * Create the unencrypted key blob.
2299 PUT_32BIT(outblob+pos, SSHCOM_MAGIC_NUMBER); pos += 4;
2300 pos += 4; /* length field, fill in later */
2301 pos += put_string(outblob+pos, type, strlen(type));
2303 char *ciphertype = passphrase ? "3des-cbc" : "none";
2304 pos += put_string(outblob+pos, ciphertype, strlen(ciphertype));
2306 lenpos = pos; /* remember this position */
2307 pos += 4; /* encrypted-blob size */
2308 pos += 4; /* encrypted-payload size */
2310 PUT_32BIT(outblob+pos, 0);
2313 for (i = 0; i < nnumbers; i++)
2314 pos += sshcom_put_mpint(outblob+pos,
2315 numbers[i].start, numbers[i].bytes);
2316 /* Now wrap up the encrypted payload. */
2317 PUT_32BIT(outblob+lenpos+4, pos - (lenpos+8));
2318 /* Pad encrypted blob to a multiple of cipher block size. */
2320 int padding = -(pos - (lenpos+4)) & 7;
2322 outblob[pos++] = random_byte();
2324 ciphertext = (char *)outblob+lenpos+4;
2325 cipherlen = pos - (lenpos+4);
2326 assert(!passphrase || cipherlen % 8 == 0);
2327 /* Wrap up the encrypted blob string. */
2328 PUT_32BIT(outblob+lenpos, cipherlen);
2329 /* And finally fill in the total length field. */
2330 PUT_32BIT(outblob+4, pos);
2332 assert(pos < outlen);
2339 * Derive encryption key from passphrase and iv/salt:
2341 * - let block A equal MD5(passphrase)
2342 * - let block B equal MD5(passphrase || A)
2343 * - block C would be MD5(passphrase || A || B) and so on
2344 * - encryption key is the first N bytes of A || B
2346 struct MD5Context md5c;
2347 unsigned char keybuf[32], iv[8];
2350 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2351 MD5Final(keybuf, &md5c);
2354 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
2355 MD5Update(&md5c, keybuf, 16);
2356 MD5Final(keybuf+16, &md5c);
2359 * Now decrypt the key blob.
2361 memset(iv, 0, sizeof(iv));
2362 des3_encrypt_pubkey_ossh(keybuf, iv, (unsigned char *)ciphertext,
2365 smemclr(&md5c, sizeof(md5c));
2366 smemclr(keybuf, sizeof(keybuf));
2370 * And save it. We'll use Unix line endings just in case it's
2371 * subsequently transferred in binary mode.
2373 fp = f_open(filename, "wb", TRUE); /* ensure Unix line endings */
2376 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2377 fprintf(fp, "Comment: \"");
2379 * Comment header is broken with backslash-newline if it goes
2380 * over 70 chars. Although it's surrounded by quotes, it
2381 * _doesn't_ escape backslashes or quotes within the string.
2382 * Don't ask me, I didn't design it.
2385 int slen = 60; /* starts at 60 due to "Comment: " */
2386 char *c = key->comment;
2387 while ((int)strlen(c) > slen) {
2388 fprintf(fp, "%.*s\\\n", slen, c);
2390 slen = 70; /* allow 70 chars on subsequent lines */
2392 fprintf(fp, "%s\"\n", c);
2394 base64_encode(fp, outblob, pos, 70);
2395 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp);
2401 smemclr(outblob, outlen);
2405 smemclr(privblob, privlen);
2409 smemclr(pubblob, publen);