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! */
769 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
773 * Now count up the total size of the ASN.1 encoded integers,
774 * so as to determine the length of the containing SEQUENCE.
777 for (i
= 0; i
< nnumbers
; i
++) {
778 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
779 len
+= numbers
[i
].bytes
;
782 /* Now add on the SEQUENCE header. */
783 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
784 /* Round up to the cipher block size, ensuring we have at least one
785 * byte of padding (see below). */
788 outlen
= (outlen
+8) &~ 7;
791 * Now we know how big outblob needs to be. Allocate it.
793 outblob
= snewn(outlen
, unsigned char);
796 * And write the data into it.
799 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
800 for (i
= 0; i
< nnumbers
; i
++) {
801 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
802 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
803 pos
+= numbers
[i
].bytes
;
807 * Padding on OpenSSH keys is deterministic. The number of
808 * padding bytes is always more than zero, and always at most
809 * the cipher block length. The value of each padding byte is
810 * equal to the number of padding bytes. So a plaintext that's
811 * an exact multiple of the block size will be padded with 08
812 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
813 * plaintext one byte less than a multiple of the block size
814 * will be padded with just 01.
816 * This enables the OpenSSL key decryption function to strip
817 * off the padding algorithmically and return the unpadded
818 * plaintext to the next layer: it looks at the final byte, and
819 * then expects to find that many bytes at the end of the data
820 * with the same value. Those are all removed and the rest is
824 while (pos
< outlen
) {
825 outblob
[pos
++] = outlen
- len
;
833 * Invent an iv. Then derive encryption key from passphrase
836 * - let block A equal MD5(passphrase || iv)
837 * - let block B equal MD5(A || passphrase || iv)
838 * - block C would be MD5(B || passphrase || iv) and so on
839 * - encryption key is the first N bytes of A || B
841 struct MD5Context md5c
;
842 unsigned char keybuf
[32];
844 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
847 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
848 MD5Update(&md5c
, iv
, 8);
849 MD5Final(keybuf
, &md5c
);
852 MD5Update(&md5c
, keybuf
, 16);
853 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
854 MD5Update(&md5c
, iv
, 8);
855 MD5Final(keybuf
+16, &md5c
);
858 * Now encrypt the key blob.
860 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
862 memset(&md5c
, 0, sizeof(md5c
));
863 memset(keybuf
, 0, sizeof(keybuf
));
867 * And save it. We'll use Unix line endings just in case it's
868 * subsequently transferred in binary mode.
870 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
875 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
876 for (i
= 0; i
< 8; i
++)
877 fprintf(fp
, "%02X", iv
[i
]);
880 base64_encode(fp
, outblob
, outlen
, 64);
887 memset(outblob
, 0, outlen
);
891 memset(spareblob
, 0, sparelen
);
895 memset(privblob
, 0, privlen
);
899 memset(pubblob
, 0, publen
);
905 /* ----------------------------------------------------------------------
906 * Code to read ssh.com private keys.
910 * The format of the base64 blob is largely SSH-2-packet-formatted,
911 * except that mpints are a bit different: they're more like the
912 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
913 * (N+7)/8 bytes of data.
915 * So. The blob contains:
917 * - uint32 0x3f6ff9eb (magic number)
918 * - uint32 size (total blob size)
919 * - string key-type (see below)
920 * - string cipher-type (tells you if key is encrypted)
921 * - string encrypted-blob
923 * (The first size field includes the size field itself and the
924 * magic number before it. All other size fields are ordinary SSH-2
925 * strings, so the size field indicates how much data is to
928 * The encrypted blob, once decrypted, contains a single string
929 * which in turn contains the payload. (This allows padding to be
930 * added after that string while still making it clear where the
931 * real payload ends. Also it probably makes for a reasonable
934 * The payload blob, for an RSA key, contains:
937 * - mpint n (yes, the public and private stuff is intermixed)
938 * - mpint u (presumably inverse of p mod q)
939 * - mpint p (p is the smaller prime)
940 * - mpint q (q is the larger)
942 * For a DSA key, the payload blob contains:
950 * Alternatively, if the parameters are `predefined', that
951 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
952 * containing some predefined parameter specification. *shudder*,
953 * but I doubt we'll encounter this in real life.
955 * The key type strings are ghastly. The RSA key I looked at had a
958 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
960 * and the DSA key wasn't much better:
962 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
964 * It isn't clear that these will always be the same. I think it
965 * might be wise just to look at the `if-modn{sign{rsa' and
966 * `dl-modp{sign{dsa' prefixes.
968 * Finally, the encryption. The cipher-type string appears to be
969 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
970 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
971 * from the passphrase by means of yet another hashing faff:
973 * - first 16 bytes are MD5(passphrase)
974 * - next 16 bytes are MD5(passphrase || first 16 bytes)
975 * - if there were more, they'd be MD5(passphrase || first 32),
979 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
982 char comment
[256]; /* allowing any length is overkill */
983 unsigned char *keyblob
;
984 int keyblob_len
, keyblob_size
;
987 static struct sshcom_key
*load_sshcom_key(const Filename
*filename
,
988 const char **errmsg_p
)
990 struct sshcom_key
*ret
;
997 int base64_chars
= 0;
999 ret
= snew(struct sshcom_key
);
1000 ret
->comment
[0] = '\0';
1001 ret
->keyblob
= NULL
;
1002 ret
->keyblob_len
= ret
->keyblob_size
= 0;
1004 fp
= f_open(*filename
, "r");
1006 errmsg
= "unable to open key file";
1009 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
1010 0 != strcmp(buffer
, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1011 errmsg
= "file does not begin with ssh.com key header";
1017 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
1018 errmsg
= "unexpected end of file";
1021 if (!strcmp(buffer
, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1023 if ((p
= strchr(buffer
, ':')) != NULL
) {
1025 errmsg
= "header found in body of key data";
1029 while (*p
&& isspace((unsigned char)*p
)) p
++;
1031 * Header lines can end in a trailing backslash for
1034 while ((len
= strlen(p
)) > (int)(sizeof(buffer
) - (p
-buffer
) -1) ||
1035 p
[len
-1] != '\n' || p
[len
-2] == '\\') {
1036 if (len
> (int)((p
-buffer
) + sizeof(buffer
)-2)) {
1037 errmsg
= "header line too long to deal with";
1040 if (!fgets(p
+len
-2, sizeof(buffer
)-(p
-buffer
)-(len
-2), fp
)) {
1041 errmsg
= "unexpected end of file";
1045 p
[strcspn(p
, "\n")] = '\0';
1046 if (!strcmp(buffer
, "Comment")) {
1047 /* Strip quotes in comment if present. */
1048 if (p
[0] == '"' && p
[strlen(p
)-1] == '"') {
1050 p
[strlen(p
)-1] = '\0';
1052 strncpy(ret
->comment
, p
, sizeof(ret
->comment
));
1053 ret
->comment
[sizeof(ret
->comment
)-1] = '\0';
1059 while (isbase64(*p
)) {
1060 base64_bit
[base64_chars
++] = *p
;
1061 if (base64_chars
== 4) {
1062 unsigned char out
[3];
1066 len
= base64_decode_atom(base64_bit
, out
);
1069 errmsg
= "invalid base64 encoding";
1073 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
1074 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
1075 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
1079 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
1080 ret
->keyblob_len
+= len
;
1088 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
1089 errmsg
= "key body not present";
1093 if (errmsg_p
) *errmsg_p
= NULL
;
1099 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1100 sfree(ret
->keyblob
);
1102 memset(ret
, 0, sizeof(*ret
));
1105 if (errmsg_p
) *errmsg_p
= errmsg
;
1109 int sshcom_encrypted(const Filename
*filename
, char **comment
)
1111 struct sshcom_key
*key
= load_sshcom_key(filename
, NULL
);
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
,
1192 const char **errmsg_p
)
1194 struct sshcom_key
*key
= load_sshcom_key(filename
, errmsg_p
);
1197 const char prefix_rsa
[] = "if-modn{sign{rsa";
1198 const char prefix_dsa
[] = "dl-modp{sign{dsa";
1199 enum { RSA
, DSA
} type
;
1203 struct ssh2_userkey
*ret
= NULL
, *retkey
;
1204 const struct ssh_signkey
*alg
;
1205 unsigned char *blob
= NULL
;
1206 int blobsize
= 0, publen
, privlen
;
1212 * Check magic number.
1214 if (GET_32BIT(key
->keyblob
) != SSHCOM_MAGIC_NUMBER
) {
1215 errmsg
= "key does not begin with magic number";
1220 * Determine the key type.
1223 if (key
->keyblob_len
< pos
+4 ||
1224 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1225 errmsg
= "key blob does not contain a key type string";
1228 if (len
> sizeof(prefix_rsa
) - 1 &&
1229 !memcmp(key
->keyblob
+pos
+4, prefix_rsa
, sizeof(prefix_rsa
) - 1)) {
1231 } else if (len
> sizeof(prefix_dsa
) - 1 &&
1232 !memcmp(key
->keyblob
+pos
+4, prefix_dsa
, sizeof(prefix_dsa
) - 1)) {
1235 errmsg
= "key is of unknown type";
1241 * Determine the cipher type.
1243 if (key
->keyblob_len
< pos
+4 ||
1244 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1245 errmsg
= "key blob does not contain a cipher type string";
1248 if (len
== 4 && !memcmp(key
->keyblob
+pos
+4, "none", 4))
1250 else if (len
== 8 && !memcmp(key
->keyblob
+pos
+4, "3des-cbc", 8))
1253 errmsg
= "key encryption is of unknown type";
1259 * Get hold of the encrypted part of the key.
1261 if (key
->keyblob_len
< pos
+4 ||
1262 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1263 errmsg
= "key blob does not contain actual key data";
1266 ciphertext
= (char *)key
->keyblob
+ pos
+ 4;
1268 if (cipherlen
== 0) {
1269 errmsg
= "length of key data is zero";
1274 * Decrypt it if necessary.
1278 * Derive encryption key from passphrase and iv/salt:
1280 * - let block A equal MD5(passphrase)
1281 * - let block B equal MD5(passphrase || A)
1282 * - block C would be MD5(passphrase || A || B) and so on
1283 * - encryption key is the first N bytes of A || B
1285 struct MD5Context md5c
;
1286 unsigned char keybuf
[32], iv
[8];
1288 if (cipherlen
% 8 != 0) {
1289 errmsg
= "encrypted part of key is not a multiple of cipher block"
1295 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1296 MD5Final(keybuf
, &md5c
);
1299 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1300 MD5Update(&md5c
, keybuf
, 16);
1301 MD5Final(keybuf
+16, &md5c
);
1304 * Now decrypt the key blob.
1306 memset(iv
, 0, sizeof(iv
));
1307 des3_decrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1310 memset(&md5c
, 0, sizeof(md5c
));
1311 memset(keybuf
, 0, sizeof(keybuf
));
1314 * Hereafter we return WRONG_PASSPHRASE for any parsing
1315 * error. (But only if we've just tried to decrypt it!
1316 * Returning WRONG_PASSPHRASE for an unencrypted key is
1320 ret
= SSH2_WRONG_PASSPHRASE
;
1324 * Strip away the containing string to get to the real meat.
1326 len
= GET_32BIT(ciphertext
);
1327 if (len
< 0 || len
> cipherlen
-4) {
1328 errmsg
= "containing string was ill-formed";
1335 * Now we break down into RSA versus DSA. In either case we'll
1336 * construct public and private blobs in our own format, and
1337 * end up feeding them to alg->createkey().
1339 blobsize
= cipherlen
+ 256;
1340 blob
= snewn(blobsize
, unsigned char);
1343 struct mpint_pos n
, e
, d
, u
, p
, q
;
1345 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &e
);
1346 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &d
);
1347 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &n
);
1348 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &u
);
1349 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1350 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1352 errmsg
= "key data did not contain six integers";
1358 pos
+= put_string(blob
+pos
, "ssh-rsa", 7);
1359 pos
+= put_mp(blob
+pos
, e
.start
, e
.bytes
);
1360 pos
+= put_mp(blob
+pos
, n
.start
, n
.bytes
);
1362 pos
+= put_string(blob
+pos
, d
.start
, d
.bytes
);
1363 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1364 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1365 pos
+= put_mp(blob
+pos
, u
.start
, u
.bytes
);
1366 privlen
= pos
- publen
;
1367 } else if (type
== DSA
) {
1368 struct mpint_pos p
, q
, g
, x
, y
;
1370 if (GET_32BIT(ciphertext
) != 0) {
1371 errmsg
= "predefined DSA parameters not supported";
1374 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1375 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &g
);
1376 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1377 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &y
);
1378 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &x
);
1380 errmsg
= "key data did not contain five integers";
1386 pos
+= put_string(blob
+pos
, "ssh-dss", 7);
1387 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1388 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1389 pos
+= put_mp(blob
+pos
, g
.start
, g
.bytes
);
1390 pos
+= put_mp(blob
+pos
, y
.start
, y
.bytes
);
1392 pos
+= put_mp(blob
+pos
, x
.start
, x
.bytes
);
1393 privlen
= pos
- publen
;
1397 assert(privlen
> 0); /* should have bombed by now if not */
1399 retkey
= snew(struct ssh2_userkey
);
1401 retkey
->data
= alg
->createkey(blob
, publen
, blob
+publen
, privlen
);
1402 if (!retkey
->data
) {
1404 errmsg
= "unable to create key data structure";
1407 retkey
->comment
= dupstr(key
->comment
);
1409 errmsg
= NULL
; /* no error */
1414 memset(blob
, 0, blobsize
);
1417 memset(key
->keyblob
, 0, key
->keyblob_size
);
1418 sfree(key
->keyblob
);
1419 memset(key
, 0, sizeof(*key
));
1421 if (errmsg_p
) *errmsg_p
= errmsg
;
1425 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
1428 unsigned char *pubblob
, *privblob
;
1429 int publen
, privlen
;
1430 unsigned char *outblob
;
1432 struct mpint_pos numbers
[6];
1433 int nnumbers
, initial_zero
, pos
, lenpos
, i
;
1441 * Fetch the key blobs.
1443 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
1444 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
1448 * Find the sequence of integers to be encoded into the OpenSSH
1449 * key blob, and also decide on the header line.
1451 if (key
->alg
== &ssh_rsa
) {
1453 struct mpint_pos n
, e
, d
, p
, q
, iqmp
;
1455 pos
= 4 + GET_32BIT(pubblob
);
1456 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
1457 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
1459 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
1460 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
1461 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
1462 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
1464 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
1475 type
= "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1476 } else if (key
->alg
== &ssh_dss
) {
1478 struct mpint_pos p
, q
, g
, y
, x
;
1480 pos
= 4 + GET_32BIT(pubblob
);
1481 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
1482 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
1483 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
1484 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
1486 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
1488 assert(y
.start
&& x
.start
); /* can't go wrong */
1498 type
= "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1500 assert(0); /* zoinks! */
1501 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1505 * Total size of key blob will be somewhere under 512 plus
1506 * combined length of integers. We'll calculate the more
1507 * precise size as we construct the blob.
1510 for (i
= 0; i
< nnumbers
; i
++)
1511 outlen
+= 4 + numbers
[i
].bytes
;
1512 outblob
= snewn(outlen
, unsigned char);
1515 * Create the unencrypted key blob.
1518 PUT_32BIT(outblob
+pos
, SSHCOM_MAGIC_NUMBER
); pos
+= 4;
1519 pos
+= 4; /* length field, fill in later */
1520 pos
+= put_string(outblob
+pos
, type
, strlen(type
));
1522 char *ciphertype
= passphrase ?
"3des-cbc" : "none";
1523 pos
+= put_string(outblob
+pos
, ciphertype
, strlen(ciphertype
));
1525 lenpos
= pos
; /* remember this position */
1526 pos
+= 4; /* encrypted-blob size */
1527 pos
+= 4; /* encrypted-payload size */
1529 PUT_32BIT(outblob
+pos
, 0);
1532 for (i
= 0; i
< nnumbers
; i
++)
1533 pos
+= sshcom_put_mpint(outblob
+pos
,
1534 numbers
[i
].start
, numbers
[i
].bytes
);
1535 /* Now wrap up the encrypted payload. */
1536 PUT_32BIT(outblob
+lenpos
+4, pos
- (lenpos
+8));
1537 /* Pad encrypted blob to a multiple of cipher block size. */
1539 int padding
= -(pos
- (lenpos
+4)) & 7;
1541 outblob
[pos
++] = random_byte();
1543 ciphertext
= (char *)outblob
+lenpos
+4;
1544 cipherlen
= pos
- (lenpos
+4);
1545 assert(!passphrase
|| cipherlen
% 8 == 0);
1546 /* Wrap up the encrypted blob string. */
1547 PUT_32BIT(outblob
+lenpos
, cipherlen
);
1548 /* And finally fill in the total length field. */
1549 PUT_32BIT(outblob
+4, pos
);
1551 assert(pos
< outlen
);
1558 * Derive encryption key from passphrase and iv/salt:
1560 * - let block A equal MD5(passphrase)
1561 * - let block B equal MD5(passphrase || A)
1562 * - block C would be MD5(passphrase || A || B) and so on
1563 * - encryption key is the first N bytes of A || B
1565 struct MD5Context md5c
;
1566 unsigned char keybuf
[32], iv
[8];
1569 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1570 MD5Final(keybuf
, &md5c
);
1573 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1574 MD5Update(&md5c
, keybuf
, 16);
1575 MD5Final(keybuf
+16, &md5c
);
1578 * Now decrypt the key blob.
1580 memset(iv
, 0, sizeof(iv
));
1581 des3_encrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1584 memset(&md5c
, 0, sizeof(md5c
));
1585 memset(keybuf
, 0, sizeof(keybuf
));
1589 * And save it. We'll use Unix line endings just in case it's
1590 * subsequently transferred in binary mode.
1592 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
1595 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1596 fprintf(fp
, "Comment: \"");
1598 * Comment header is broken with backslash-newline if it goes
1599 * over 70 chars. Although it's surrounded by quotes, it
1600 * _doesn't_ escape backslashes or quotes within the string.
1601 * Don't ask me, I didn't design it.
1604 int slen
= 60; /* starts at 60 due to "Comment: " */
1605 char *c
= key
->comment
;
1606 while ((int)strlen(c
) > slen
) {
1607 fprintf(fp
, "%.*s\\\n", slen
, c
);
1609 slen
= 70; /* allow 70 chars on subsequent lines */
1611 fprintf(fp
, "%s\"\n", c
);
1613 base64_encode(fp
, outblob
, pos
, 70);
1614 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1620 memset(outblob
, 0, outlen
);
1624 memset(privblob
, 0, privlen
);
1628 memset(pubblob
, 0, publen
);