2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 #define PUT_32BIT(cp, value) do { \
16 (cp)[3] = (unsigned char)(value); \
17 (cp)[2] = (unsigned char)((value) >> 8); \
18 (cp)[1] = (unsigned char)((value) >> 16); \
19 (cp)[0] = (unsigned char)((value) >> 24); } while (0)
21 #define GET_32BIT(cp) \
22 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
23 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
24 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
25 ((unsigned long)(unsigned char)(cp)[3]))
27 int openssh_encrypted(const Filename
*filename
);
28 struct ssh2_userkey
*openssh_read(const Filename
*filename
, char *passphrase
);
29 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
32 int sshcom_encrypted(const Filename
*filename
, char **comment
);
33 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
);
34 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
38 * Given a key type, determine whether we know how to import it.
40 int import_possible(int type
)
42 if (type
== SSH_KEYTYPE_OPENSSH
)
44 if (type
== SSH_KEYTYPE_SSHCOM
)
50 * Given a key type, determine what native key type
51 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
54 int import_target_type(int type
)
57 * There are no known foreign SSH1 key formats.
59 return SSH_KEYTYPE_SSH2
;
63 * Determine whether a foreign key is encrypted.
65 int import_encrypted(const Filename
*filename
, int type
, char **comment
)
67 if (type
== SSH_KEYTYPE_OPENSSH
) {
68 /* OpenSSH doesn't do key comments */
69 *comment
= dupstr(filename_to_str(filename
));
70 return openssh_encrypted(filename
);
72 if (type
== SSH_KEYTYPE_SSHCOM
) {
73 return sshcom_encrypted(filename
, comment
);
81 int import_ssh1(const Filename
*filename
, int type
,
82 struct RSAKey
*key
, char *passphrase
)
90 struct ssh2_userkey
*import_ssh2(const Filename
*filename
, int type
,
93 if (type
== SSH_KEYTYPE_OPENSSH
)
94 return openssh_read(filename
, passphrase
);
95 if (type
== SSH_KEYTYPE_SSHCOM
)
96 return sshcom_read(filename
, passphrase
);
101 * Export an SSH1 key.
103 int export_ssh1(const Filename
*filename
, int type
, struct RSAKey
*key
,
110 * Export an SSH2 key.
112 int export_ssh2(const Filename
*filename
, int type
,
113 struct ssh2_userkey
*key
, char *passphrase
)
115 if (type
== SSH_KEYTYPE_OPENSSH
)
116 return openssh_write(filename
, key
, passphrase
);
117 if (type
== SSH_KEYTYPE_SSHCOM
)
118 return sshcom_write(filename
, key
, passphrase
);
122 /* ----------------------------------------------------------------------
123 * Helper routines. (The base64 ones are defined in sshpubk.c.)
126 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
127 ((c) >= 'a' && (c) <= 'z') || \
128 ((c) >= '0' && (c) <= '9') || \
129 (c) == '+' || (c) == '/' || (c) == '=' \
133 * Read an ASN.1/BER identifier and length pair.
135 * Flags are a combination of the #defines listed below.
137 * Returns -1 if unsuccessful; otherwise returns the number of
138 * bytes used out of the source data.
141 /* ASN.1 tag classes. */
142 #define ASN1_CLASS_UNIVERSAL (0 << 6)
143 #define ASN1_CLASS_APPLICATION (1 << 6)
144 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
145 #define ASN1_CLASS_PRIVATE (3 << 6)
146 #define ASN1_CLASS_MASK (3 << 6)
148 /* Primitive versus constructed bit. */
149 #define ASN1_CONSTRUCTED (1 << 5)
151 static int ber_read_id_len(void *source
, int sourcelen
,
152 int *id
, int *length
, int *flags
)
154 unsigned char *p
= (unsigned char *) source
;
159 *flags
= (*p
& 0xE0);
160 if ((*p
& 0x1F) == 0x1F) {
166 *id
= (*id
<< 7) | (*p
& 0x7F);
184 *length
= (*length
<< 8) | (*p
++);
191 return p
- (unsigned char *) source
;
195 * Write an ASN.1/BER identifier and length pair. Returns the
196 * number of bytes consumed. Assumes dest contains enough space.
197 * Will avoid writing anything if dest is NULL, but still return
198 * amount of space required.
200 static int ber_write_id_len(void *dest
, int id
, int length
, int flags
)
202 unsigned char *d
= (unsigned char *)dest
;
207 * Identifier is one byte.
210 if (d
) *d
++ = id
| flags
;
214 * Identifier is multiple bytes: the first byte is 11111
215 * plus the flags, and subsequent bytes encode the value of
216 * the identifier, 7 bits at a time, with the top bit of
217 * each byte 1 except the last one which is 0.
220 if (d
) *d
++ = 0x1F | flags
;
221 for (n
= 1; (id
>> (7*n
)) > 0; n
++)
222 continue; /* count the bytes */
225 if (d
) *d
++ = (n ?
0x80 : 0) | ((id
>> (7*n
)) & 0x7F);
231 * Length is one byte.
234 if (d
) *d
++ = length
;
238 * Length is multiple bytes. The first is 0x80 plus the
239 * number of subsequent bytes, and the subsequent bytes
240 * encode the actual length.
242 for (n
= 1; (length
>> (8*n
)) > 0; n
++)
243 continue; /* count the bytes */
245 if (d
) *d
++ = 0x80 | n
;
248 if (d
) *d
++ = (length
>> (8*n
)) & 0xFF;
255 static int put_string(void *target
, void *data
, int len
)
257 unsigned char *d
= (unsigned char *)target
;
260 memcpy(d
+4, data
, len
);
264 static int put_mp(void *target
, void *data
, int len
)
266 unsigned char *d
= (unsigned char *)target
;
267 unsigned char *i
= (unsigned char *)data
;
272 memcpy(d
+5, data
, len
);
276 memcpy(d
+4, data
, len
);
281 /* Simple structure to point to an mp-int within a blob. */
282 struct mpint_pos
{ void *start
; int bytes
; };
284 static int ssh2_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
287 unsigned char *d
= (unsigned char *) data
;
291 bytes
= GET_32BIT(d
);
302 return len
; /* ensure further calls fail as well */
305 /* ----------------------------------------------------------------------
306 * Code to read and write OpenSSH private keys.
309 enum { OSSH_DSA
, OSSH_RSA
};
314 unsigned char *keyblob
;
315 int keyblob_len
, keyblob_size
;
318 static struct openssh_key
*load_openssh_key(const Filename
*filename
)
320 struct openssh_key
*ret
;
326 int base64_chars
= 0;
328 ret
= snew(struct openssh_key
);
330 ret
->keyblob_len
= ret
->keyblob_size
= 0;
332 memset(ret
->iv
, 0, sizeof(ret
->iv
));
334 fp
= f_open(*filename
, "r");
336 errmsg
= "Unable to open key file";
339 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
340 0 != strncmp(buffer
, "-----BEGIN ", 11) ||
341 0 != strcmp(buffer
+strlen(buffer
)-17, "PRIVATE KEY-----\n")) {
342 errmsg
= "File does not begin with OpenSSH key header";
345 if (!strcmp(buffer
, "-----BEGIN RSA PRIVATE KEY-----\n"))
346 ret
->type
= OSSH_RSA
;
347 else if (!strcmp(buffer
, "-----BEGIN DSA PRIVATE KEY-----\n"))
348 ret
->type
= OSSH_DSA
;
350 errmsg
= "Unrecognised key type";
356 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
357 errmsg
= "Unexpected end of file";
360 if (0 == strncmp(buffer
, "-----END ", 9) &&
361 0 == strcmp(buffer
+strlen(buffer
)-17, "PRIVATE KEY-----\n"))
363 if ((p
= strchr(buffer
, ':')) != NULL
) {
365 errmsg
= "Header found in body of key data";
369 while (*p
&& isspace((unsigned char)*p
)) p
++;
370 if (!strcmp(buffer
, "Proc-Type")) {
371 if (p
[0] != '4' || p
[1] != ',') {
372 errmsg
= "Proc-Type is not 4 (only 4 is supported)";
376 if (!strcmp(p
, "ENCRYPTED\n"))
378 } else if (!strcmp(buffer
, "DEK-Info")) {
381 if (strncmp(p
, "DES-EDE3-CBC,", 13)) {
382 errmsg
= "Ciphers other than DES-EDE3-CBC not supported";
386 for (i
= 0; i
< 8; i
++) {
387 if (1 != sscanf(p
, "%2x", &j
))
393 errmsg
= "Expected 16-digit iv in DEK-Info";
401 while (isbase64(*p
)) {
402 base64_bit
[base64_chars
++] = *p
;
403 if (base64_chars
== 4) {
404 unsigned char out
[3];
409 len
= base64_decode_atom(base64_bit
, out
);
412 errmsg
= "Invalid base64 encoding";
416 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
417 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
418 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
422 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
423 ret
->keyblob_len
+= len
;
425 memset(out
, 0, sizeof(out
));
433 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
434 errmsg
= "Key body not present";
438 if (ret
->encrypted
&& ret
->keyblob_len
% 8 != 0) {
439 errmsg
= "Encrypted key blob is not a multiple of cipher block size";
443 memset(buffer
, 0, sizeof(buffer
));
444 memset(base64_bit
, 0, sizeof(base64_bit
));
448 memset(buffer
, 0, sizeof(buffer
));
449 memset(base64_bit
, 0, sizeof(base64_bit
));
452 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
455 memset(&ret
, 0, sizeof(ret
));
461 int openssh_encrypted(const Filename
*filename
)
463 struct openssh_key
*key
= load_openssh_key(filename
);
468 ret
= key
->encrypted
;
469 memset(key
->keyblob
, 0, key
->keyblob_size
);
471 memset(&key
, 0, sizeof(key
));
476 struct ssh2_userkey
*openssh_read(const Filename
*filename
, char *passphrase
)
478 struct openssh_key
*key
= load_openssh_key(filename
);
479 struct ssh2_userkey
*retkey
;
481 int ret
, id
, len
, flags
;
483 struct ssh2_userkey
*retval
= NULL
;
486 int blobsize
= 0, blobptr
, privptr
;
495 if (key
->encrypted
) {
497 * Derive encryption key from passphrase and iv/salt:
499 * - let block A equal MD5(passphrase || iv)
500 * - let block B equal MD5(A || passphrase || iv)
501 * - block C would be MD5(B || passphrase || iv) and so on
502 * - encryption key is the first N bytes of A || B
504 struct MD5Context md5c
;
505 unsigned char keybuf
[32];
508 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
509 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
510 MD5Final(keybuf
, &md5c
);
513 MD5Update(&md5c
, keybuf
, 16);
514 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
515 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
516 MD5Final(keybuf
+16, &md5c
);
519 * Now decrypt the key blob.
521 des3_decrypt_pubkey_ossh(keybuf
, (unsigned char *)key
->iv
,
522 key
->keyblob
, key
->keyblob_len
);
524 memset(&md5c
, 0, sizeof(md5c
));
525 memset(keybuf
, 0, sizeof(keybuf
));
529 * Now we have a decrypted key blob, which contains an ASN.1
530 * encoded private key. We must now untangle the ASN.1.
532 * We expect the whole key blob to be formatted as a SEQUENCE
533 * (0x30 followed by a length code indicating that the rest of
534 * the blob is part of the sequence). Within that SEQUENCE we
535 * expect to see a bunch of INTEGERs. What those integers mean
536 * depends on the key type:
538 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
539 * dmp1, dmq1, iqmp in that order. (The last three are d mod
540 * (p-1), d mod (q-1), inverse of q mod p respectively.)
542 * - For DSA, we expect them to be 0, p, q, g, y, x in that
548 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
549 ret
= ber_read_id_len(p
, key
->keyblob_len
, &id
, &len
, &flags
);
551 if (ret
< 0 || id
!= 16) {
552 errmsg
= "ASN.1 decoding failure";
553 retval
= SSH2_WRONG_PASSPHRASE
;
557 /* Expect a load of INTEGERs. */
558 if (key
->type
== OSSH_RSA
)
560 else if (key
->type
== OSSH_DSA
)
563 num_integers
= 0; /* placate compiler warnings */
566 * Space to create key blob in.
568 blobsize
= 256+key
->keyblob_len
;
569 blob
= snewn(blobsize
, unsigned char);
571 if (key
->type
== OSSH_DSA
)
572 memcpy(blob
+4, "ssh-dss", 7);
573 else if (key
->type
== OSSH_RSA
)
574 memcpy(blob
+4, "ssh-rsa", 7);
578 for (i
= 0; i
< num_integers
; i
++) {
579 ret
= ber_read_id_len(p
, key
->keyblob
+key
->keyblob_len
-p
,
582 if (ret
< 0 || id
!= 2 ||
583 key
->keyblob
+key
->keyblob_len
-p
< len
) {
584 errmsg
= "ASN.1 decoding failure";
590 * The first integer should be zero always (I think
591 * this is some sort of version indication).
593 if (len
!= 1 || p
[0] != 0) {
594 errmsg
= "Version number mismatch";
597 } else if (key
->type
== OSSH_RSA
) {
599 * Integers 1 and 2 go into the public blob but in the
600 * opposite order; integers 3, 4, 5 and 8 go into the
601 * private blob. The other two (6 and 7) are ignored.
604 /* Save the details for after we deal with number 2. */
607 } else if (i
!= 6 && i
!= 7) {
608 PUT_32BIT(blob
+blobptr
, len
);
609 memcpy(blob
+blobptr
+4, p
, len
);
612 PUT_32BIT(blob
+blobptr
, modlen
);
613 memcpy(blob
+blobptr
+4, modptr
, modlen
);
618 } else if (key
->type
== OSSH_DSA
) {
620 * Integers 1-4 go into the public blob; integer 5 goes
621 * into the private blob.
623 PUT_32BIT(blob
+blobptr
, len
);
624 memcpy(blob
+blobptr
+4, p
, len
);
630 /* Skip past the number. */
635 * Now put together the actual key. Simplest way to do this is
636 * to assemble our own key blobs and feed them to the createkey
637 * functions; this is a bit faffy but it does mean we get all
638 * the sanity checks for free.
640 assert(privptr
> 0); /* should have bombed by now if not */
641 retkey
= snew(struct ssh2_userkey
);
642 retkey
->alg
= (key
->type
== OSSH_RSA ?
&ssh_rsa
: &ssh_dss
);
643 retkey
->data
= retkey
->alg
->createkey(blob
, privptr
,
644 blob
+privptr
, blobptr
-privptr
);
647 errmsg
= "unable to create key data structure";
651 retkey
->comment
= dupstr("imported-openssh-key");
652 errmsg
= NULL
; /* no error */
657 memset(blob
, 0, blobsize
);
660 memset(key
->keyblob
, 0, key
->keyblob_size
);
662 memset(&key
, 0, sizeof(key
));
667 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
670 unsigned char *pubblob
, *privblob
, *spareblob
;
671 int publen
, privlen
, sparelen
= 0;
672 unsigned char *outblob
;
674 struct mpint_pos numbers
[9];
675 int nnumbers
, pos
, len
, seqlen
, i
;
676 char *header
, *footer
;
683 * Fetch the key blobs.
685 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
686 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
687 spareblob
= outblob
= NULL
;
690 * Find the sequence of integers to be encoded into the OpenSSH
691 * key blob, and also decide on the header line.
693 if (key
->alg
== &ssh_rsa
) {
695 struct mpint_pos n
, e
, d
, p
, q
, iqmp
, dmp1
, dmq1
;
696 Bignum bd
, bp
, bq
, bdmp1
, bdmq1
;
698 pos
= 4 + GET_32BIT(pubblob
);
699 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
700 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
702 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
703 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
704 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
705 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
707 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
709 /* We also need d mod (p-1) and d mod (q-1). */
710 bd
= bignum_from_bytes(d
.start
, d
.bytes
);
711 bp
= bignum_from_bytes(p
.start
, p
.bytes
);
712 bq
= bignum_from_bytes(q
.start
, q
.bytes
);
715 bdmp1
= bigmod(bd
, bp
);
716 bdmq1
= bigmod(bd
, bq
);
721 dmp1
.bytes
= (bignum_bitcount(bdmp1
)+8)/8;
722 dmq1
.bytes
= (bignum_bitcount(bdmq1
)+8)/8;
723 sparelen
= dmp1
.bytes
+ dmq1
.bytes
;
724 spareblob
= snewn(sparelen
, unsigned char);
725 dmp1
.start
= spareblob
;
726 dmq1
.start
= spareblob
+ dmp1
.bytes
;
727 for (i
= 0; i
< dmp1
.bytes
; i
++)
728 spareblob
[i
] = bignum_byte(bdmp1
, dmp1
.bytes
-1 - i
);
729 for (i
= 0; i
< dmq1
.bytes
; i
++)
730 spareblob
[i
+dmp1
.bytes
] = bignum_byte(bdmq1
, dmq1
.bytes
-1 - i
);
734 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
745 header
= "-----BEGIN RSA PRIVATE KEY-----\n";
746 footer
= "-----END RSA PRIVATE KEY-----\n";
747 } else if (key
->alg
== &ssh_dss
) {
749 struct mpint_pos p
, q
, g
, y
, x
;
751 pos
= 4 + GET_32BIT(pubblob
);
752 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
753 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
754 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
755 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
757 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
759 assert(y
.start
&& x
.start
); /* can't go wrong */
761 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
769 header
= "-----BEGIN DSA PRIVATE KEY-----\n";
770 footer
= "-----END DSA PRIVATE KEY-----\n";
772 assert(0); /* zoinks! */
776 * Now count up the total size of the ASN.1 encoded integers,
777 * so as to determine the length of the containing SEQUENCE.
780 for (i
= 0; i
< nnumbers
; i
++) {
781 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
782 len
+= numbers
[i
].bytes
;
785 /* Now add on the SEQUENCE header. */
786 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
787 /* Round up to the cipher block size, ensuring we have at least one
788 * byte of padding (see below). */
791 outlen
= (outlen
+8) &~ 7;
794 * Now we know how big outblob needs to be. Allocate it.
796 outblob
= snewn(outlen
, unsigned char);
799 * And write the data into it.
802 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
803 for (i
= 0; i
< nnumbers
; i
++) {
804 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
805 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
806 pos
+= numbers
[i
].bytes
;
810 * Padding on OpenSSH keys is deterministic. The number of
811 * padding bytes is always more than zero, and always at most
812 * the cipher block length. The value of each padding byte is
813 * equal to the number of padding bytes. So a plaintext that's
814 * an exact multiple of the block size will be padded with 08
815 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
816 * plaintext one byte less than a multiple of the block size
817 * will be padded with just 01.
819 * This enables the OpenSSL key decryption function to strip
820 * off the padding algorithmically and return the unpadded
821 * plaintext to the next layer: it looks at the final byte, and
822 * then expects to find that many bytes at the end of the data
823 * with the same value. Those are all removed and the rest is
827 while (pos
< outlen
) {
828 outblob
[pos
++] = outlen
- len
;
836 * Invent an iv. Then derive encryption key from passphrase
839 * - let block A equal MD5(passphrase || iv)
840 * - let block B equal MD5(A || passphrase || iv)
841 * - block C would be MD5(B || passphrase || iv) and so on
842 * - encryption key is the first N bytes of A || B
844 struct MD5Context md5c
;
845 unsigned char keybuf
[32];
847 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
850 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
851 MD5Update(&md5c
, iv
, 8);
852 MD5Final(keybuf
, &md5c
);
855 MD5Update(&md5c
, keybuf
, 16);
856 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
857 MD5Update(&md5c
, iv
, 8);
858 MD5Final(keybuf
+16, &md5c
);
861 * Now encrypt the key blob.
863 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
865 memset(&md5c
, 0, sizeof(md5c
));
866 memset(keybuf
, 0, sizeof(keybuf
));
870 * And save it. We'll use Unix line endings just in case it's
871 * subsequently transferred in binary mode.
873 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
878 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
879 for (i
= 0; i
< 8; i
++)
880 fprintf(fp
, "%02X", iv
[i
]);
883 base64_encode(fp
, outblob
, outlen
, 64);
890 memset(outblob
, 0, outlen
);
894 memset(spareblob
, 0, sparelen
);
898 memset(privblob
, 0, privlen
);
902 memset(pubblob
, 0, publen
);
908 /* ----------------------------------------------------------------------
909 * Code to read ssh.com private keys.
913 * The format of the base64 blob is largely ssh2-packet-formatted,
914 * except that mpints are a bit different: they're more like the
915 * old ssh1 mpint. You have a 32-bit bit count N, followed by
916 * (N+7)/8 bytes of data.
918 * So. The blob contains:
920 * - uint32 0x3f6ff9eb (magic number)
921 * - uint32 size (total blob size)
922 * - string key-type (see below)
923 * - string cipher-type (tells you if key is encrypted)
924 * - string encrypted-blob
926 * (The first size field includes the size field itself and the
927 * magic number before it. All other size fields are ordinary ssh2
928 * strings, so the size field indicates how much data is to
931 * The encrypted blob, once decrypted, contains a single string
932 * which in turn contains the payload. (This allows padding to be
933 * added after that string while still making it clear where the
934 * real payload ends. Also it probably makes for a reasonable
937 * The payload blob, for an RSA key, contains:
940 * - mpint n (yes, the public and private stuff is intermixed)
941 * - mpint u (presumably inverse of p mod q)
942 * - mpint p (p is the smaller prime)
943 * - mpint q (q is the larger)
945 * For a DSA key, the payload blob contains:
953 * Alternatively, if the parameters are `predefined', that
954 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
955 * containing some predefined parameter specification. *shudder*,
956 * but I doubt we'll encounter this in real life.
958 * The key type strings are ghastly. The RSA key I looked at had a
961 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
963 * and the DSA key wasn't much better:
965 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
967 * It isn't clear that these will always be the same. I think it
968 * might be wise just to look at the `if-modn{sign{rsa' and
969 * `dl-modp{sign{dsa' prefixes.
971 * Finally, the encryption. The cipher-type string appears to be
972 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
973 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
974 * from the passphrase by means of yet another hashing faff:
976 * - first 16 bytes are MD5(passphrase)
977 * - next 16 bytes are MD5(passphrase || first 16 bytes)
978 * - if there were more, they'd be MD5(passphrase || first 32),
982 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
985 char comment
[256]; /* allowing any length is overkill */
986 unsigned char *keyblob
;
987 int keyblob_len
, keyblob_size
;
990 static struct sshcom_key
*load_sshcom_key(const Filename
*filename
)
992 struct sshcom_key
*ret
;
999 int base64_chars
= 0;
1001 ret
= snew(struct sshcom_key
);
1002 ret
->comment
[0] = '\0';
1003 ret
->keyblob
= NULL
;
1004 ret
->keyblob_len
= ret
->keyblob_size
= 0;
1006 fp
= f_open(*filename
, "r");
1008 errmsg
= "Unable to open key file";
1011 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
1012 0 != strcmp(buffer
, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1013 errmsg
= "File does not begin with ssh.com key header";
1019 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
1020 errmsg
= "Unexpected end of file";
1023 if (!strcmp(buffer
, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1025 if ((p
= strchr(buffer
, ':')) != NULL
) {
1027 errmsg
= "Header found in body of key data";
1031 while (*p
&& isspace((unsigned char)*p
)) p
++;
1033 * Header lines can end in a trailing backslash for
1036 while ((len
= strlen(p
)) > (int)(sizeof(buffer
) - (p
-buffer
) -1) ||
1037 p
[len
-1] != '\n' || p
[len
-2] == '\\') {
1038 if (len
> (int)((p
-buffer
) + sizeof(buffer
)-2)) {
1039 errmsg
= "Header line too long to deal with";
1042 if (!fgets(p
+len
-2, sizeof(buffer
)-(p
-buffer
)-(len
-2), fp
)) {
1043 errmsg
= "Unexpected end of file";
1047 p
[strcspn(p
, "\n")] = '\0';
1048 if (!strcmp(buffer
, "Comment")) {
1049 /* Strip quotes in comment if present. */
1050 if (p
[0] == '"' && p
[strlen(p
)-1] == '"') {
1052 p
[strlen(p
)-1] = '\0';
1054 strncpy(ret
->comment
, p
, sizeof(ret
->comment
));
1055 ret
->comment
[sizeof(ret
->comment
)-1] = '\0';
1061 while (isbase64(*p
)) {
1062 base64_bit
[base64_chars
++] = *p
;
1063 if (base64_chars
== 4) {
1064 unsigned char out
[3];
1068 len
= base64_decode_atom(base64_bit
, out
);
1071 errmsg
= "Invalid base64 encoding";
1075 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
1076 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
1077 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
1081 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
1082 ret
->keyblob_len
+= len
;
1090 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
1091 errmsg
= "Key body not present";
1100 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1101 sfree(ret
->keyblob
);
1103 memset(&ret
, 0, sizeof(ret
));
1109 int sshcom_encrypted(const Filename
*filename
, char **comment
)
1111 struct sshcom_key
*key
= load_sshcom_key(filename
);
1112 int pos
, len
, answer
;
1119 * Check magic number.
1121 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb)
1122 return 0; /* key is invalid */
1125 * Find the cipher-type string.
1129 if (key
->keyblob_len
< pos
+4)
1130 goto done
; /* key is far too short */
1131 pos
+= 4 + GET_32BIT(key
->keyblob
+ pos
); /* skip key type */
1132 if (key
->keyblob_len
< pos
+4)
1133 goto done
; /* key is far too short */
1134 len
= GET_32BIT(key
->keyblob
+ pos
); /* find cipher-type length */
1135 if (key
->keyblob_len
< pos
+4+len
)
1136 goto done
; /* cipher type string is incomplete */
1137 if (len
!= 4 || 0 != memcmp(key
->keyblob
+ pos
+ 4, "none", 4))
1141 *comment
= dupstr(key
->comment
);
1142 memset(key
->keyblob
, 0, key
->keyblob_size
);
1143 sfree(key
->keyblob
);
1144 memset(&key
, 0, sizeof(key
));
1149 static int sshcom_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
1153 unsigned char *d
= (unsigned char *) data
;
1157 bits
= GET_32BIT(d
);
1159 bytes
= (bits
+ 7) / 8;
1170 return len
; /* ensure further calls fail as well */
1173 static int sshcom_put_mpint(void *target
, void *data
, int len
)
1175 unsigned char *d
= (unsigned char *)target
;
1176 unsigned char *i
= (unsigned char *)data
;
1177 int bits
= len
* 8 - 1;
1180 if (*i
& (1 << (bits
& 7)))
1186 PUT_32BIT(d
, bits
+1);
1187 memcpy(d
+4, i
, len
);
1191 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
)
1193 struct sshcom_key
*key
= load_sshcom_key(filename
);
1196 const char prefix_rsa
[] = "if-modn{sign{rsa";
1197 const char prefix_dsa
[] = "dl-modp{sign{dsa";
1198 enum { RSA
, DSA
} type
;
1202 struct ssh2_userkey
*ret
= NULL
, *retkey
;
1203 const struct ssh_signkey
*alg
;
1204 unsigned char *blob
= NULL
;
1205 int blobsize
= 0, publen
, privlen
;
1211 * Check magic number.
1213 if (GET_32BIT(key
->keyblob
) != SSHCOM_MAGIC_NUMBER
) {
1214 errmsg
= "Key does not begin with magic number";
1219 * Determine the key type.
1222 if (key
->keyblob_len
< pos
+4 ||
1223 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1224 errmsg
= "Key blob does not contain a key type string";
1227 if (len
> sizeof(prefix_rsa
) - 1 &&
1228 !memcmp(key
->keyblob
+pos
+4, prefix_rsa
, sizeof(prefix_rsa
) - 1)) {
1230 } else if (len
> sizeof(prefix_dsa
) - 1 &&
1231 !memcmp(key
->keyblob
+pos
+4, prefix_dsa
, sizeof(prefix_dsa
) - 1)) {
1234 errmsg
= "Key is of unknown type";
1240 * Determine the cipher type.
1242 if (key
->keyblob_len
< pos
+4 ||
1243 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1244 errmsg
= "Key blob does not contain a cipher type string";
1247 if (len
== 4 && !memcmp(key
->keyblob
+pos
+4, "none", 4))
1249 else if (len
== 8 && !memcmp(key
->keyblob
+pos
+4, "3des-cbc", 8))
1252 errmsg
= "Key encryption is of unknown type";
1258 * Get hold of the encrypted part of the key.
1260 if (key
->keyblob_len
< pos
+4 ||
1261 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1262 errmsg
= "Key blob does not contain actual key data";
1265 ciphertext
= (char *)key
->keyblob
+ pos
+ 4;
1267 if (cipherlen
== 0) {
1268 errmsg
= "Length of key data is zero";
1273 * Decrypt it if necessary.
1277 * Derive encryption key from passphrase and iv/salt:
1279 * - let block A equal MD5(passphrase)
1280 * - let block B equal MD5(passphrase || A)
1281 * - block C would be MD5(passphrase || A || B) and so on
1282 * - encryption key is the first N bytes of A || B
1284 struct MD5Context md5c
;
1285 unsigned char keybuf
[32], iv
[8];
1287 if (cipherlen
% 8 != 0) {
1288 errmsg
= "Encrypted part of key is not a multiple of cipher block"
1294 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1295 MD5Final(keybuf
, &md5c
);
1298 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1299 MD5Update(&md5c
, keybuf
, 16);
1300 MD5Final(keybuf
+16, &md5c
);
1303 * Now decrypt the key blob.
1305 memset(iv
, 0, sizeof(iv
));
1306 des3_decrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1309 memset(&md5c
, 0, sizeof(md5c
));
1310 memset(keybuf
, 0, sizeof(keybuf
));
1313 * Hereafter we return WRONG_PASSPHRASE for any parsing
1314 * error. (But only if we've just tried to decrypt it!
1315 * Returning WRONG_PASSPHRASE for an unencrypted key is
1319 ret
= SSH2_WRONG_PASSPHRASE
;
1323 * Strip away the containing string to get to the real meat.
1325 len
= GET_32BIT(ciphertext
);
1326 if (len
> cipherlen
-4) {
1327 errmsg
= "containing string was ill-formed";
1334 * Now we break down into RSA versus DSA. In either case we'll
1335 * construct public and private blobs in our own format, and
1336 * end up feeding them to alg->createkey().
1338 blobsize
= cipherlen
+ 256;
1339 blob
= snewn(blobsize
, unsigned char);
1342 struct mpint_pos n
, e
, d
, u
, p
, q
;
1344 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &e
);
1345 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &d
);
1346 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &n
);
1347 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &u
);
1348 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1349 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1351 errmsg
= "key data did not contain six integers";
1357 pos
+= put_string(blob
+pos
, "ssh-rsa", 7);
1358 pos
+= put_mp(blob
+pos
, e
.start
, e
.bytes
);
1359 pos
+= put_mp(blob
+pos
, n
.start
, n
.bytes
);
1361 pos
+= put_string(blob
+pos
, d
.start
, d
.bytes
);
1362 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1363 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1364 pos
+= put_mp(blob
+pos
, u
.start
, u
.bytes
);
1365 privlen
= pos
- publen
;
1366 } else if (type
== DSA
) {
1367 struct mpint_pos p
, q
, g
, x
, y
;
1369 if (GET_32BIT(ciphertext
) != 0) {
1370 errmsg
= "predefined DSA parameters not supported";
1373 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1374 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &g
);
1375 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1376 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &y
);
1377 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &x
);
1379 errmsg
= "key data did not contain five integers";
1385 pos
+= put_string(blob
+pos
, "ssh-dss", 7);
1386 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1387 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1388 pos
+= put_mp(blob
+pos
, g
.start
, g
.bytes
);
1389 pos
+= put_mp(blob
+pos
, y
.start
, y
.bytes
);
1391 pos
+= put_mp(blob
+pos
, x
.start
, x
.bytes
);
1392 privlen
= pos
- publen
;
1396 assert(privlen
> 0); /* should have bombed by now if not */
1398 retkey
= snew(struct ssh2_userkey
);
1400 retkey
->data
= alg
->createkey(blob
, publen
, blob
+publen
, privlen
);
1401 if (!retkey
->data
) {
1403 errmsg
= "unable to create key data structure";
1406 retkey
->comment
= dupstr(key
->comment
);
1408 errmsg
= NULL
; /* no error */
1413 memset(blob
, 0, blobsize
);
1416 memset(key
->keyblob
, 0, key
->keyblob_size
);
1417 sfree(key
->keyblob
);
1418 memset(&key
, 0, sizeof(key
));
1423 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
1426 unsigned char *pubblob
, *privblob
;
1427 int publen
, privlen
;
1428 unsigned char *outblob
;
1430 struct mpint_pos numbers
[6];
1431 int nnumbers
, initial_zero
, pos
, lenpos
, i
;
1439 * Fetch the key blobs.
1441 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
1442 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
1446 * Find the sequence of integers to be encoded into the OpenSSH
1447 * key blob, and also decide on the header line.
1449 if (key
->alg
== &ssh_rsa
) {
1451 struct mpint_pos n
, e
, d
, p
, q
, iqmp
;
1453 pos
= 4 + GET_32BIT(pubblob
);
1454 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
1455 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
1457 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
1458 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
1459 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
1460 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
1462 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
1473 type
= "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1474 } else if (key
->alg
== &ssh_dss
) {
1476 struct mpint_pos p
, q
, g
, y
, x
;
1478 pos
= 4 + GET_32BIT(pubblob
);
1479 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
1480 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
1481 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
1482 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
1484 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
1486 assert(y
.start
&& x
.start
); /* can't go wrong */
1496 type
= "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1498 assert(0); /* zoinks! */
1502 * Total size of key blob will be somewhere under 512 plus
1503 * combined length of integers. We'll calculate the more
1504 * precise size as we construct the blob.
1507 for (i
= 0; i
< nnumbers
; i
++)
1508 outlen
+= 4 + numbers
[i
].bytes
;
1509 outblob
= snewn(outlen
, unsigned char);
1512 * Create the unencrypted key blob.
1515 PUT_32BIT(outblob
+pos
, SSHCOM_MAGIC_NUMBER
); pos
+= 4;
1516 pos
+= 4; /* length field, fill in later */
1517 pos
+= put_string(outblob
+pos
, type
, strlen(type
));
1519 char *ciphertype
= passphrase ?
"3des-cbc" : "none";
1520 pos
+= put_string(outblob
+pos
, ciphertype
, strlen(ciphertype
));
1522 lenpos
= pos
; /* remember this position */
1523 pos
+= 4; /* encrypted-blob size */
1524 pos
+= 4; /* encrypted-payload size */
1526 PUT_32BIT(outblob
+pos
, 0);
1529 for (i
= 0; i
< nnumbers
; i
++)
1530 pos
+= sshcom_put_mpint(outblob
+pos
,
1531 numbers
[i
].start
, numbers
[i
].bytes
);
1532 /* Now wrap up the encrypted payload. */
1533 PUT_32BIT(outblob
+lenpos
+4, pos
- (lenpos
+8));
1534 /* Pad encrypted blob to a multiple of cipher block size. */
1536 int padding
= -(pos
- (lenpos
+4)) & 7;
1538 outblob
[pos
++] = random_byte();
1540 ciphertext
= (char *)outblob
+lenpos
+4;
1541 cipherlen
= pos
- (lenpos
+4);
1542 assert(!passphrase
|| cipherlen
% 8 == 0);
1543 /* Wrap up the encrypted blob string. */
1544 PUT_32BIT(outblob
+lenpos
, cipherlen
);
1545 /* And finally fill in the total length field. */
1546 PUT_32BIT(outblob
+4, pos
);
1548 assert(pos
< outlen
);
1555 * Derive encryption key from passphrase and iv/salt:
1557 * - let block A equal MD5(passphrase)
1558 * - let block B equal MD5(passphrase || A)
1559 * - block C would be MD5(passphrase || A || B) and so on
1560 * - encryption key is the first N bytes of A || B
1562 struct MD5Context md5c
;
1563 unsigned char keybuf
[32], iv
[8];
1566 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1567 MD5Final(keybuf
, &md5c
);
1570 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1571 MD5Update(&md5c
, keybuf
, 16);
1572 MD5Final(keybuf
+16, &md5c
);
1575 * Now decrypt the key blob.
1577 memset(iv
, 0, sizeof(iv
));
1578 des3_encrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1581 memset(&md5c
, 0, sizeof(md5c
));
1582 memset(keybuf
, 0, sizeof(keybuf
));
1586 * And save it. We'll use Unix line endings just in case it's
1587 * subsequently transferred in binary mode.
1589 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
1592 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1593 fprintf(fp
, "Comment: \"");
1595 * Comment header is broken with backslash-newline if it goes
1596 * over 70 chars. Although it's surrounded by quotes, it
1597 * _doesn't_ escape backslashes or quotes within the string.
1598 * Don't ask me, I didn't design it.
1601 int slen
= 60; /* starts at 60 due to "Comment: " */
1602 char *c
= key
->comment
;
1603 while ((int)strlen(c
) > slen
) {
1604 fprintf(fp
, "%.*s\\\n", slen
, c
);
1606 slen
= 70; /* allow 70 chars on subsequent lines */
1608 fprintf(fp
, "%s\"\n", c
);
1610 base64_encode(fp
, outblob
, pos
, 70);
1611 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1617 memset(outblob
, 0, outlen
);
1621 memset(privblob
, 0, privlen
);
1625 memset(pubblob
, 0, publen
);