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
);
112 /* ----------------------------------------------------------------------
113 * Helper routines. (The base64 ones are defined in sshpubk.c.)
116 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
117 ((c) >= 'a' && (c) <= 'z') || \
118 ((c) >= '0' && (c) <= '9') || \
119 (c) == '+' || (c) == '/' || (c) == '=' \
123 * Read an ASN.1/BER identifier and length pair.
125 * Flags are a combination of the #defines listed below.
127 * Returns -1 if unsuccessful; otherwise returns the number of
128 * bytes used out of the source data.
131 /* ASN.1 tag classes. */
132 #define ASN1_CLASS_UNIVERSAL (0 << 6)
133 #define ASN1_CLASS_APPLICATION (1 << 6)
134 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
135 #define ASN1_CLASS_PRIVATE (3 << 6)
136 #define ASN1_CLASS_MASK (3 << 6)
138 /* Primitive versus constructed bit. */
139 #define ASN1_CONSTRUCTED (1 << 5)
141 static int ber_read_id_len(void *source
, int sourcelen
,
142 int *id
, int *length
, int *flags
)
144 unsigned char *p
= (unsigned char *) source
;
149 *flags
= (*p
& 0xE0);
150 if ((*p
& 0x1F) == 0x1F) {
156 *id
= (*id
<< 7) | (*p
& 0x7F);
174 *length
= (*length
<< 8) | (*p
++);
181 return p
- (unsigned char *) source
;
185 * Write an ASN.1/BER identifier and length pair. Returns the
186 * number of bytes consumed. Assumes dest contains enough space.
187 * Will avoid writing anything if dest is NULL, but still return
188 * amount of space required.
190 static int ber_write_id_len(void *dest
, int id
, int length
, int flags
)
192 unsigned char *d
= (unsigned char *)dest
;
197 * Identifier is one byte.
200 if (d
) *d
++ = id
| flags
;
204 * Identifier is multiple bytes: the first byte is 11111
205 * plus the flags, and subsequent bytes encode the value of
206 * the identifier, 7 bits at a time, with the top bit of
207 * each byte 1 except the last one which is 0.
210 if (d
) *d
++ = 0x1F | flags
;
211 for (n
= 1; (id
>> (7*n
)) > 0; n
++)
212 continue; /* count the bytes */
215 if (d
) *d
++ = (n ?
0x80 : 0) | ((id
>> (7*n
)) & 0x7F);
221 * Length is one byte.
224 if (d
) *d
++ = length
;
228 * Length is multiple bytes. The first is 0x80 plus the
229 * number of subsequent bytes, and the subsequent bytes
230 * encode the actual length.
232 for (n
= 1; (length
>> (8*n
)) > 0; n
++)
233 continue; /* count the bytes */
235 if (d
) *d
++ = 0x80 | n
;
238 if (d
) *d
++ = (length
>> (8*n
)) & 0xFF;
245 static int put_string(void *target
, void *data
, int len
)
247 unsigned char *d
= (unsigned char *)target
;
250 memcpy(d
+4, data
, len
);
254 static int put_mp(void *target
, void *data
, int len
)
256 unsigned char *d
= (unsigned char *)target
;
257 unsigned char *i
= (unsigned char *)data
;
262 memcpy(d
+5, data
, len
);
266 memcpy(d
+4, data
, len
);
271 /* Simple structure to point to an mp-int within a blob. */
272 struct mpint_pos
{ void *start
; int bytes
; };
274 static int ssh2_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
277 unsigned char *d
= (unsigned char *) data
;
281 bytes
= GET_32BIT(d
);
292 return len
; /* ensure further calls fail as well */
295 /* ----------------------------------------------------------------------
296 * Code to read and write OpenSSH private keys.
299 enum { OSSH_DSA
, OSSH_RSA
};
304 unsigned char *keyblob
;
305 int keyblob_len
, keyblob_size
;
308 static struct openssh_key
*load_openssh_key(const Filename
*filename
,
309 const char **errmsg_p
)
311 struct openssh_key
*ret
;
317 int base64_chars
= 0;
319 ret
= snew(struct openssh_key
);
321 ret
->keyblob_len
= ret
->keyblob_size
= 0;
323 memset(ret
->iv
, 0, sizeof(ret
->iv
));
325 fp
= f_open(*filename
, "r");
327 errmsg
= "unable to open key file";
330 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
331 0 != strncmp(buffer
, "-----BEGIN ", 11) ||
332 0 != strcmp(buffer
+strlen(buffer
)-17, "PRIVATE KEY-----\n")) {
333 errmsg
= "file does not begin with OpenSSH key header";
336 if (!strcmp(buffer
, "-----BEGIN RSA PRIVATE KEY-----\n"))
337 ret
->type
= OSSH_RSA
;
338 else if (!strcmp(buffer
, "-----BEGIN DSA PRIVATE KEY-----\n"))
339 ret
->type
= OSSH_DSA
;
341 errmsg
= "unrecognised key type";
347 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
348 errmsg
= "unexpected end of file";
351 if (0 == strncmp(buffer
, "-----END ", 9) &&
352 0 == strcmp(buffer
+strlen(buffer
)-17, "PRIVATE KEY-----\n"))
354 if ((p
= strchr(buffer
, ':')) != NULL
) {
356 errmsg
= "header found in body of key data";
360 while (*p
&& isspace((unsigned char)*p
)) p
++;
361 if (!strcmp(buffer
, "Proc-Type")) {
362 if (p
[0] != '4' || p
[1] != ',') {
363 errmsg
= "Proc-Type is not 4 (only 4 is supported)";
367 if (!strcmp(p
, "ENCRYPTED\n"))
369 } else if (!strcmp(buffer
, "DEK-Info")) {
372 if (strncmp(p
, "DES-EDE3-CBC,", 13)) {
373 errmsg
= "ciphers other than DES-EDE3-CBC not supported";
377 for (i
= 0; i
< 8; i
++) {
378 if (1 != sscanf(p
, "%2x", &j
))
384 errmsg
= "expected 16-digit iv in DEK-Info";
392 while (isbase64(*p
)) {
393 base64_bit
[base64_chars
++] = *p
;
394 if (base64_chars
== 4) {
395 unsigned char out
[3];
400 len
= base64_decode_atom(base64_bit
, out
);
403 errmsg
= "invalid base64 encoding";
407 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
408 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
409 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
413 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
414 ret
->keyblob_len
+= len
;
416 memset(out
, 0, sizeof(out
));
424 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
425 errmsg
= "key body not present";
429 if (ret
->encrypted
&& ret
->keyblob_len
% 8 != 0) {
430 errmsg
= "encrypted key blob is not a multiple of cipher block size";
434 memset(buffer
, 0, sizeof(buffer
));
435 memset(base64_bit
, 0, sizeof(base64_bit
));
436 if (errmsg_p
) *errmsg_p
= NULL
;
440 memset(buffer
, 0, sizeof(buffer
));
441 memset(base64_bit
, 0, sizeof(base64_bit
));
444 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
447 memset(&ret
, 0, sizeof(ret
));
450 if (errmsg_p
) *errmsg_p
= errmsg
;
454 int openssh_encrypted(const Filename
*filename
)
456 struct openssh_key
*key
= load_openssh_key(filename
, NULL
);
461 ret
= key
->encrypted
;
462 memset(key
->keyblob
, 0, key
->keyblob_size
);
464 memset(&key
, 0, sizeof(key
));
469 struct ssh2_userkey
*openssh_read(const Filename
*filename
, char *passphrase
,
470 const char **errmsg_p
)
472 struct openssh_key
*key
= load_openssh_key(filename
, errmsg_p
);
473 struct ssh2_userkey
*retkey
;
475 int ret
, id
, len
, flags
;
477 struct ssh2_userkey
*retval
= NULL
;
480 int blobsize
= 0, blobptr
, privptr
;
489 if (key
->encrypted
) {
491 * Derive encryption key from passphrase and iv/salt:
493 * - let block A equal MD5(passphrase || iv)
494 * - let block B equal MD5(A || passphrase || iv)
495 * - block C would be MD5(B || passphrase || iv) and so on
496 * - encryption key is the first N bytes of A || B
498 struct MD5Context md5c
;
499 unsigned char keybuf
[32];
502 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
503 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
504 MD5Final(keybuf
, &md5c
);
507 MD5Update(&md5c
, keybuf
, 16);
508 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
509 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
510 MD5Final(keybuf
+16, &md5c
);
513 * Now decrypt the key blob.
515 des3_decrypt_pubkey_ossh(keybuf
, (unsigned char *)key
->iv
,
516 key
->keyblob
, key
->keyblob_len
);
518 memset(&md5c
, 0, sizeof(md5c
));
519 memset(keybuf
, 0, sizeof(keybuf
));
523 * Now we have a decrypted key blob, which contains an ASN.1
524 * encoded private key. We must now untangle the ASN.1.
526 * We expect the whole key blob to be formatted as a SEQUENCE
527 * (0x30 followed by a length code indicating that the rest of
528 * the blob is part of the sequence). Within that SEQUENCE we
529 * expect to see a bunch of INTEGERs. What those integers mean
530 * depends on the key type:
532 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
533 * dmp1, dmq1, iqmp in that order. (The last three are d mod
534 * (p-1), d mod (q-1), inverse of q mod p respectively.)
536 * - For DSA, we expect them to be 0, p, q, g, y, x in that
542 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
543 ret
= ber_read_id_len(p
, key
->keyblob_len
, &id
, &len
, &flags
);
545 if (ret
< 0 || id
!= 16) {
546 errmsg
= "ASN.1 decoding failure";
547 retval
= SSH2_WRONG_PASSPHRASE
;
551 /* Expect a load of INTEGERs. */
552 if (key
->type
== OSSH_RSA
)
554 else if (key
->type
== OSSH_DSA
)
557 num_integers
= 0; /* placate compiler warnings */
560 * Space to create key blob in.
562 blobsize
= 256+key
->keyblob_len
;
563 blob
= snewn(blobsize
, unsigned char);
565 if (key
->type
== OSSH_DSA
)
566 memcpy(blob
+4, "ssh-dss", 7);
567 else if (key
->type
== OSSH_RSA
)
568 memcpy(blob
+4, "ssh-rsa", 7);
572 for (i
= 0; i
< num_integers
; i
++) {
573 ret
= ber_read_id_len(p
, key
->keyblob
+key
->keyblob_len
-p
,
576 if (ret
< 0 || id
!= 2 ||
577 key
->keyblob
+key
->keyblob_len
-p
< len
) {
578 errmsg
= "ASN.1 decoding failure";
579 retval
= SSH2_WRONG_PASSPHRASE
;
585 * The first integer should be zero always (I think
586 * this is some sort of version indication).
588 if (len
!= 1 || p
[0] != 0) {
589 errmsg
= "version number mismatch";
592 } else if (key
->type
== OSSH_RSA
) {
594 * Integers 1 and 2 go into the public blob but in the
595 * opposite order; integers 3, 4, 5 and 8 go into the
596 * private blob. The other two (6 and 7) are ignored.
599 /* Save the details for after we deal with number 2. */
602 } else if (i
!= 6 && i
!= 7) {
603 PUT_32BIT(blob
+blobptr
, len
);
604 memcpy(blob
+blobptr
+4, p
, len
);
607 PUT_32BIT(blob
+blobptr
, modlen
);
608 memcpy(blob
+blobptr
+4, modptr
, modlen
);
613 } else if (key
->type
== OSSH_DSA
) {
615 * Integers 1-4 go into the public blob; integer 5 goes
616 * into the private blob.
618 PUT_32BIT(blob
+blobptr
, len
);
619 memcpy(blob
+blobptr
+4, p
, len
);
625 /* Skip past the number. */
630 * Now put together the actual key. Simplest way to do this is
631 * to assemble our own key blobs and feed them to the createkey
632 * functions; this is a bit faffy but it does mean we get all
633 * the sanity checks for free.
635 assert(privptr
> 0); /* should have bombed by now if not */
636 retkey
= snew(struct ssh2_userkey
);
637 retkey
->alg
= (key
->type
== OSSH_RSA ?
&ssh_rsa
: &ssh_dss
);
638 retkey
->data
= retkey
->alg
->createkey(blob
, privptr
,
639 blob
+privptr
, blobptr
-privptr
);
642 errmsg
= "unable to create key data structure";
646 retkey
->comment
= dupstr("imported-openssh-key");
647 errmsg
= NULL
; /* no error */
652 memset(blob
, 0, blobsize
);
655 memset(key
->keyblob
, 0, key
->keyblob_size
);
657 memset(&key
, 0, sizeof(key
));
659 if (errmsg_p
) *errmsg_p
= errmsg
;
663 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
666 unsigned char *pubblob
, *privblob
, *spareblob
;
667 int publen
, privlen
, sparelen
= 0;
668 unsigned char *outblob
;
670 struct mpint_pos numbers
[9];
671 int nnumbers
, pos
, len
, seqlen
, i
;
672 char *header
, *footer
;
679 * Fetch the key blobs.
681 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
682 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
683 spareblob
= outblob
= NULL
;
686 * Find the sequence of integers to be encoded into the OpenSSH
687 * key blob, and also decide on the header line.
689 if (key
->alg
== &ssh_rsa
) {
691 struct mpint_pos n
, e
, d
, p
, q
, iqmp
, dmp1
, dmq1
;
692 Bignum bd
, bp
, bq
, bdmp1
, bdmq1
;
694 pos
= 4 + GET_32BIT(pubblob
);
695 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
696 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
698 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
699 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
700 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
701 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
703 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
705 /* We also need d mod (p-1) and d mod (q-1). */
706 bd
= bignum_from_bytes(d
.start
, d
.bytes
);
707 bp
= bignum_from_bytes(p
.start
, p
.bytes
);
708 bq
= bignum_from_bytes(q
.start
, q
.bytes
);
711 bdmp1
= bigmod(bd
, bp
);
712 bdmq1
= bigmod(bd
, bq
);
717 dmp1
.bytes
= (bignum_bitcount(bdmp1
)+8)/8;
718 dmq1
.bytes
= (bignum_bitcount(bdmq1
)+8)/8;
719 sparelen
= dmp1
.bytes
+ dmq1
.bytes
;
720 spareblob
= snewn(sparelen
, unsigned char);
721 dmp1
.start
= spareblob
;
722 dmq1
.start
= spareblob
+ dmp1
.bytes
;
723 for (i
= 0; i
< dmp1
.bytes
; i
++)
724 spareblob
[i
] = bignum_byte(bdmp1
, dmp1
.bytes
-1 - i
);
725 for (i
= 0; i
< dmq1
.bytes
; i
++)
726 spareblob
[i
+dmp1
.bytes
] = bignum_byte(bdmq1
, dmq1
.bytes
-1 - i
);
730 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
741 header
= "-----BEGIN RSA PRIVATE KEY-----\n";
742 footer
= "-----END RSA PRIVATE KEY-----\n";
743 } else if (key
->alg
== &ssh_dss
) {
745 struct mpint_pos p
, q
, g
, y
, x
;
747 pos
= 4 + GET_32BIT(pubblob
);
748 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
749 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
750 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
751 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
753 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
755 assert(y
.start
&& x
.start
); /* can't go wrong */
757 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
765 header
= "-----BEGIN DSA PRIVATE KEY-----\n";
766 footer
= "-----END DSA PRIVATE KEY-----\n";
768 assert(0); /* zoinks! */
772 * Now count up the total size of the ASN.1 encoded integers,
773 * so as to determine the length of the containing SEQUENCE.
776 for (i
= 0; i
< nnumbers
; i
++) {
777 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
778 len
+= numbers
[i
].bytes
;
781 /* Now add on the SEQUENCE header. */
782 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
783 /* Round up to the cipher block size, ensuring we have at least one
784 * byte of padding (see below). */
787 outlen
= (outlen
+8) &~ 7;
790 * Now we know how big outblob needs to be. Allocate it.
792 outblob
= snewn(outlen
, unsigned char);
795 * And write the data into it.
798 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
799 for (i
= 0; i
< nnumbers
; i
++) {
800 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
801 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
802 pos
+= numbers
[i
].bytes
;
806 * Padding on OpenSSH keys is deterministic. The number of
807 * padding bytes is always more than zero, and always at most
808 * the cipher block length. The value of each padding byte is
809 * equal to the number of padding bytes. So a plaintext that's
810 * an exact multiple of the block size will be padded with 08
811 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
812 * plaintext one byte less than a multiple of the block size
813 * will be padded with just 01.
815 * This enables the OpenSSL key decryption function to strip
816 * off the padding algorithmically and return the unpadded
817 * plaintext to the next layer: it looks at the final byte, and
818 * then expects to find that many bytes at the end of the data
819 * with the same value. Those are all removed and the rest is
823 while (pos
< outlen
) {
824 outblob
[pos
++] = outlen
- len
;
832 * Invent an iv. Then derive encryption key from passphrase
835 * - let block A equal MD5(passphrase || iv)
836 * - let block B equal MD5(A || passphrase || iv)
837 * - block C would be MD5(B || passphrase || iv) and so on
838 * - encryption key is the first N bytes of A || B
840 struct MD5Context md5c
;
841 unsigned char keybuf
[32];
843 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
846 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
847 MD5Update(&md5c
, iv
, 8);
848 MD5Final(keybuf
, &md5c
);
851 MD5Update(&md5c
, keybuf
, 16);
852 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
853 MD5Update(&md5c
, iv
, 8);
854 MD5Final(keybuf
+16, &md5c
);
857 * Now encrypt the key blob.
859 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
861 memset(&md5c
, 0, sizeof(md5c
));
862 memset(keybuf
, 0, sizeof(keybuf
));
866 * And save it. We'll use Unix line endings just in case it's
867 * subsequently transferred in binary mode.
869 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
874 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
875 for (i
= 0; i
< 8; i
++)
876 fprintf(fp
, "%02X", iv
[i
]);
879 base64_encode(fp
, outblob
, outlen
, 64);
886 memset(outblob
, 0, outlen
);
890 memset(spareblob
, 0, sparelen
);
894 memset(privblob
, 0, privlen
);
898 memset(pubblob
, 0, publen
);
904 /* ----------------------------------------------------------------------
905 * Code to read ssh.com private keys.
909 * The format of the base64 blob is largely SSH-2-packet-formatted,
910 * except that mpints are a bit different: they're more like the
911 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
912 * (N+7)/8 bytes of data.
914 * So. The blob contains:
916 * - uint32 0x3f6ff9eb (magic number)
917 * - uint32 size (total blob size)
918 * - string key-type (see below)
919 * - string cipher-type (tells you if key is encrypted)
920 * - string encrypted-blob
922 * (The first size field includes the size field itself and the
923 * magic number before it. All other size fields are ordinary SSH-2
924 * strings, so the size field indicates how much data is to
927 * The encrypted blob, once decrypted, contains a single string
928 * which in turn contains the payload. (This allows padding to be
929 * added after that string while still making it clear where the
930 * real payload ends. Also it probably makes for a reasonable
933 * The payload blob, for an RSA key, contains:
936 * - mpint n (yes, the public and private stuff is intermixed)
937 * - mpint u (presumably inverse of p mod q)
938 * - mpint p (p is the smaller prime)
939 * - mpint q (q is the larger)
941 * For a DSA key, the payload blob contains:
949 * Alternatively, if the parameters are `predefined', that
950 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
951 * containing some predefined parameter specification. *shudder*,
952 * but I doubt we'll encounter this in real life.
954 * The key type strings are ghastly. The RSA key I looked at had a
957 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
959 * and the DSA key wasn't much better:
961 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
963 * It isn't clear that these will always be the same. I think it
964 * might be wise just to look at the `if-modn{sign{rsa' and
965 * `dl-modp{sign{dsa' prefixes.
967 * Finally, the encryption. The cipher-type string appears to be
968 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
969 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
970 * from the passphrase by means of yet another hashing faff:
972 * - first 16 bytes are MD5(passphrase)
973 * - next 16 bytes are MD5(passphrase || first 16 bytes)
974 * - if there were more, they'd be MD5(passphrase || first 32),
978 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
981 char comment
[256]; /* allowing any length is overkill */
982 unsigned char *keyblob
;
983 int keyblob_len
, keyblob_size
;
986 static struct sshcom_key
*load_sshcom_key(const Filename
*filename
,
987 const char **errmsg_p
)
989 struct sshcom_key
*ret
;
996 int base64_chars
= 0;
998 ret
= snew(struct sshcom_key
);
999 ret
->comment
[0] = '\0';
1000 ret
->keyblob
= NULL
;
1001 ret
->keyblob_len
= ret
->keyblob_size
= 0;
1003 fp
= f_open(*filename
, "r");
1005 errmsg
= "unable to open key file";
1008 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
1009 0 != strcmp(buffer
, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1010 errmsg
= "file does not begin with ssh.com key header";
1016 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
1017 errmsg
= "unexpected end of file";
1020 if (!strcmp(buffer
, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1022 if ((p
= strchr(buffer
, ':')) != NULL
) {
1024 errmsg
= "header found in body of key data";
1028 while (*p
&& isspace((unsigned char)*p
)) p
++;
1030 * Header lines can end in a trailing backslash for
1033 while ((len
= strlen(p
)) > (int)(sizeof(buffer
) - (p
-buffer
) -1) ||
1034 p
[len
-1] != '\n' || p
[len
-2] == '\\') {
1035 if (len
> (int)((p
-buffer
) + sizeof(buffer
)-2)) {
1036 errmsg
= "header line too long to deal with";
1039 if (!fgets(p
+len
-2, sizeof(buffer
)-(p
-buffer
)-(len
-2), fp
)) {
1040 errmsg
= "unexpected end of file";
1044 p
[strcspn(p
, "\n")] = '\0';
1045 if (!strcmp(buffer
, "Comment")) {
1046 /* Strip quotes in comment if present. */
1047 if (p
[0] == '"' && p
[strlen(p
)-1] == '"') {
1049 p
[strlen(p
)-1] = '\0';
1051 strncpy(ret
->comment
, p
, sizeof(ret
->comment
));
1052 ret
->comment
[sizeof(ret
->comment
)-1] = '\0';
1058 while (isbase64(*p
)) {
1059 base64_bit
[base64_chars
++] = *p
;
1060 if (base64_chars
== 4) {
1061 unsigned char out
[3];
1065 len
= base64_decode_atom(base64_bit
, out
);
1068 errmsg
= "invalid base64 encoding";
1072 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
1073 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
1074 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
1078 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
1079 ret
->keyblob_len
+= len
;
1087 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
1088 errmsg
= "key body not present";
1092 if (errmsg_p
) *errmsg_p
= NULL
;
1098 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1099 sfree(ret
->keyblob
);
1101 memset(&ret
, 0, sizeof(ret
));
1104 if (errmsg_p
) *errmsg_p
= errmsg
;
1108 int sshcom_encrypted(const Filename
*filename
, char **comment
)
1110 struct sshcom_key
*key
= load_sshcom_key(filename
, NULL
);
1111 int pos
, len
, answer
;
1118 * Check magic number.
1120 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb)
1121 return 0; /* key is invalid */
1124 * Find the cipher-type string.
1128 if (key
->keyblob_len
< pos
+4)
1129 goto done
; /* key is far too short */
1130 pos
+= 4 + GET_32BIT(key
->keyblob
+ pos
); /* skip key type */
1131 if (key
->keyblob_len
< pos
+4)
1132 goto done
; /* key is far too short */
1133 len
= GET_32BIT(key
->keyblob
+ pos
); /* find cipher-type length */
1134 if (key
->keyblob_len
< pos
+4+len
)
1135 goto done
; /* cipher type string is incomplete */
1136 if (len
!= 4 || 0 != memcmp(key
->keyblob
+ pos
+ 4, "none", 4))
1140 *comment
= dupstr(key
->comment
);
1141 memset(key
->keyblob
, 0, key
->keyblob_size
);
1142 sfree(key
->keyblob
);
1143 memset(&key
, 0, sizeof(key
));
1148 static int sshcom_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
1152 unsigned char *d
= (unsigned char *) data
;
1156 bits
= GET_32BIT(d
);
1158 bytes
= (bits
+ 7) / 8;
1169 return len
; /* ensure further calls fail as well */
1172 static int sshcom_put_mpint(void *target
, void *data
, int len
)
1174 unsigned char *d
= (unsigned char *)target
;
1175 unsigned char *i
= (unsigned char *)data
;
1176 int bits
= len
* 8 - 1;
1179 if (*i
& (1 << (bits
& 7)))
1185 PUT_32BIT(d
, bits
+1);
1186 memcpy(d
+4, i
, len
);
1190 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
,
1191 const char **errmsg_p
)
1193 struct sshcom_key
*key
= load_sshcom_key(filename
, errmsg_p
);
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
< 0 || 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
));
1420 if (errmsg_p
) *errmsg_p
= errmsg
;
1424 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
1427 unsigned char *pubblob
, *privblob
;
1428 int publen
, privlen
;
1429 unsigned char *outblob
;
1431 struct mpint_pos numbers
[6];
1432 int nnumbers
, initial_zero
, pos
, lenpos
, i
;
1440 * Fetch the key blobs.
1442 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
1443 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
1447 * Find the sequence of integers to be encoded into the OpenSSH
1448 * key blob, and also decide on the header line.
1450 if (key
->alg
== &ssh_rsa
) {
1452 struct mpint_pos n
, e
, d
, p
, q
, iqmp
;
1454 pos
= 4 + GET_32BIT(pubblob
);
1455 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
1456 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
1458 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
1459 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
1460 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
1461 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
1463 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
1474 type
= "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1475 } else if (key
->alg
== &ssh_dss
) {
1477 struct mpint_pos p
, q
, g
, y
, x
;
1479 pos
= 4 + GET_32BIT(pubblob
);
1480 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
1481 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
1482 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
1483 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
1485 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
1487 assert(y
.start
&& x
.start
); /* can't go wrong */
1497 type
= "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1499 assert(0); /* zoinks! */
1503 * Total size of key blob will be somewhere under 512 plus
1504 * combined length of integers. We'll calculate the more
1505 * precise size as we construct the blob.
1508 for (i
= 0; i
< nnumbers
; i
++)
1509 outlen
+= 4 + numbers
[i
].bytes
;
1510 outblob
= snewn(outlen
, unsigned char);
1513 * Create the unencrypted key blob.
1516 PUT_32BIT(outblob
+pos
, SSHCOM_MAGIC_NUMBER
); pos
+= 4;
1517 pos
+= 4; /* length field, fill in later */
1518 pos
+= put_string(outblob
+pos
, type
, strlen(type
));
1520 char *ciphertype
= passphrase ?
"3des-cbc" : "none";
1521 pos
+= put_string(outblob
+pos
, ciphertype
, strlen(ciphertype
));
1523 lenpos
= pos
; /* remember this position */
1524 pos
+= 4; /* encrypted-blob size */
1525 pos
+= 4; /* encrypted-payload size */
1527 PUT_32BIT(outblob
+pos
, 0);
1530 for (i
= 0; i
< nnumbers
; i
++)
1531 pos
+= sshcom_put_mpint(outblob
+pos
,
1532 numbers
[i
].start
, numbers
[i
].bytes
);
1533 /* Now wrap up the encrypted payload. */
1534 PUT_32BIT(outblob
+lenpos
+4, pos
- (lenpos
+8));
1535 /* Pad encrypted blob to a multiple of cipher block size. */
1537 int padding
= -(pos
- (lenpos
+4)) & 7;
1539 outblob
[pos
++] = random_byte();
1541 ciphertext
= (char *)outblob
+lenpos
+4;
1542 cipherlen
= pos
- (lenpos
+4);
1543 assert(!passphrase
|| cipherlen
% 8 == 0);
1544 /* Wrap up the encrypted blob string. */
1545 PUT_32BIT(outblob
+lenpos
, cipherlen
);
1546 /* And finally fill in the total length field. */
1547 PUT_32BIT(outblob
+4, pos
);
1549 assert(pos
< outlen
);
1556 * Derive encryption key from passphrase and iv/salt:
1558 * - let block A equal MD5(passphrase)
1559 * - let block B equal MD5(passphrase || A)
1560 * - block C would be MD5(passphrase || A || B) and so on
1561 * - encryption key is the first N bytes of A || B
1563 struct MD5Context md5c
;
1564 unsigned char keybuf
[32], iv
[8];
1567 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1568 MD5Final(keybuf
, &md5c
);
1571 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1572 MD5Update(&md5c
, keybuf
, 16);
1573 MD5Final(keybuf
+16, &md5c
);
1576 * Now decrypt the key blob.
1578 memset(iv
, 0, sizeof(iv
));
1579 des3_encrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1582 memset(&md5c
, 0, sizeof(md5c
));
1583 memset(keybuf
, 0, sizeof(keybuf
));
1587 * And save it. We'll use Unix line endings just in case it's
1588 * subsequently transferred in binary mode.
1590 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
1593 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1594 fprintf(fp
, "Comment: \"");
1596 * Comment header is broken with backslash-newline if it goes
1597 * over 70 chars. Although it's surrounded by quotes, it
1598 * _doesn't_ escape backslashes or quotes within the string.
1599 * Don't ask me, I didn't design it.
1602 int slen
= 60; /* starts at 60 due to "Comment: " */
1603 char *c
= key
->comment
;
1604 while ((int)strlen(c
) > slen
) {
1605 fprintf(fp
, "%.*s\\\n", slen
, c
);
1607 slen
= 70; /* allow 70 chars on subsequent lines */
1609 fprintf(fp
, "%s\"\n", c
);
1611 base64_encode(fp
, outblob
, pos
, 70);
1612 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1618 memset(outblob
, 0, outlen
);
1622 memset(privblob
, 0, privlen
);
1626 memset(pubblob
, 0, publen
);