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
, 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
)
564 * Space to create key blob in.
566 blobsize
= 256+key
->keyblob_len
;
567 blob
= snewn(blobsize
, unsigned char);
569 if (key
->type
== OSSH_DSA
)
570 memcpy(blob
+4, "ssh-dss", 7);
571 else if (key
->type
== OSSH_RSA
)
572 memcpy(blob
+4, "ssh-rsa", 7);
576 for (i
= 0; i
< num_integers
; i
++) {
577 ret
= ber_read_id_len(p
, key
->keyblob
+key
->keyblob_len
-p
,
580 if (ret
< 0 || id
!= 2 ||
581 key
->keyblob
+key
->keyblob_len
-p
< len
) {
582 errmsg
= "ASN.1 decoding failure";
588 * The first integer should be zero always (I think
589 * this is some sort of version indication).
591 if (len
!= 1 || p
[0] != 0) {
592 errmsg
= "Version number mismatch";
595 } else if (key
->type
== OSSH_RSA
) {
597 * Integers 1 and 2 go into the public blob but in the
598 * opposite order; integers 3, 4, 5 and 8 go into the
599 * private blob. The other two (6 and 7) are ignored.
602 /* Save the details for after we deal with number 2. */
605 } else if (i
!= 6 && i
!= 7) {
606 PUT_32BIT(blob
+blobptr
, len
);
607 memcpy(blob
+blobptr
+4, p
, len
);
610 PUT_32BIT(blob
+blobptr
, modlen
);
611 memcpy(blob
+blobptr
+4, modptr
, modlen
);
616 } else if (key
->type
== OSSH_DSA
) {
618 * Integers 1-4 go into the public blob; integer 5 goes
619 * into the private blob.
621 PUT_32BIT(blob
+blobptr
, len
);
622 memcpy(blob
+blobptr
+4, p
, len
);
628 /* Skip past the number. */
633 * Now put together the actual key. Simplest way to do this is
634 * to assemble our own key blobs and feed them to the createkey
635 * functions; this is a bit faffy but it does mean we get all
636 * the sanity checks for free.
638 assert(privptr
> 0); /* should have bombed by now if not */
639 retkey
= snew(struct ssh2_userkey
);
640 retkey
->alg
= (key
->type
== OSSH_RSA ?
&ssh_rsa
: &ssh_dss
);
641 retkey
->data
= retkey
->alg
->createkey(blob
, privptr
,
642 blob
+privptr
, blobptr
-privptr
);
645 errmsg
= "unable to create key data structure";
649 retkey
->comment
= dupstr("imported-openssh-key");
650 errmsg
= NULL
; /* no error */
655 memset(blob
, 0, blobsize
);
658 memset(key
->keyblob
, 0, key
->keyblob_size
);
660 memset(&key
, 0, sizeof(key
));
665 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
668 unsigned char *pubblob
, *privblob
, *spareblob
;
669 int publen
, privlen
, sparelen
;
670 unsigned char *outblob
;
672 struct mpint_pos numbers
[9];
673 int nnumbers
, pos
, len
, seqlen
, i
;
674 char *header
, *footer
;
681 * Fetch the key blobs.
683 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
684 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
685 spareblob
= outblob
= NULL
;
688 * Find the sequence of integers to be encoded into the OpenSSH
689 * key blob, and also decide on the header line.
691 if (key
->alg
== &ssh_rsa
) {
693 struct mpint_pos n
, e
, d
, p
, q
, iqmp
, dmp1
, dmq1
;
694 Bignum bd
, bp
, bq
, bdmp1
, bdmq1
;
696 pos
= 4 + GET_32BIT(pubblob
);
697 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
698 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
700 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
701 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
702 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
703 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
705 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
707 /* We also need d mod (p-1) and d mod (q-1). */
708 bd
= bignum_from_bytes(d
.start
, d
.bytes
);
709 bp
= bignum_from_bytes(p
.start
, p
.bytes
);
710 bq
= bignum_from_bytes(q
.start
, q
.bytes
);
713 bdmp1
= bigmod(bd
, bp
);
714 bdmq1
= bigmod(bd
, bq
);
719 dmp1
.bytes
= (bignum_bitcount(bdmp1
)+8)/8;
720 dmq1
.bytes
= (bignum_bitcount(bdmq1
)+8)/8;
721 sparelen
= dmp1
.bytes
+ dmq1
.bytes
;
722 spareblob
= snewn(sparelen
, unsigned char);
723 dmp1
.start
= spareblob
;
724 dmq1
.start
= spareblob
+ dmp1
.bytes
;
725 for (i
= 0; i
< dmp1
.bytes
; i
++)
726 spareblob
[i
] = bignum_byte(bdmp1
, dmp1
.bytes
-1 - i
);
727 for (i
= 0; i
< dmq1
.bytes
; i
++)
728 spareblob
[i
+dmp1
.bytes
] = bignum_byte(bdmq1
, dmq1
.bytes
-1 - i
);
732 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
743 header
= "-----BEGIN RSA PRIVATE KEY-----\n";
744 footer
= "-----END RSA PRIVATE KEY-----\n";
745 } else if (key
->alg
== &ssh_dss
) {
747 struct mpint_pos p
, q
, g
, y
, x
;
749 pos
= 4 + GET_32BIT(pubblob
);
750 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
751 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
752 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
753 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
755 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
757 assert(y
.start
&& x
.start
); /* can't go wrong */
759 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
767 header
= "-----BEGIN DSA PRIVATE KEY-----\n";
768 footer
= "-----END DSA PRIVATE KEY-----\n";
770 assert(0); /* zoinks! */
774 * Now count up the total size of the ASN.1 encoded integers,
775 * so as to determine the length of the containing SEQUENCE.
778 for (i
= 0; i
< nnumbers
; i
++) {
779 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
780 len
+= numbers
[i
].bytes
;
783 /* Now add on the SEQUENCE header. */
784 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
785 /* Round up to the cipher block size, ensuring we have at least one
786 * byte of padding (see below). */
789 outlen
= (outlen
+8) &~ 7;
792 * Now we know how big outblob needs to be. Allocate it.
794 outblob
= snewn(outlen
, unsigned char);
797 * And write the data into it.
800 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
801 for (i
= 0; i
< nnumbers
; i
++) {
802 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
803 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
804 pos
+= numbers
[i
].bytes
;
808 * Padding on OpenSSH keys is deterministic. The number of
809 * padding bytes is always more than zero, and always at most
810 * the cipher block length. The value of each padding byte is
811 * equal to the number of padding bytes. So a plaintext that's
812 * an exact multiple of the block size will be padded with 08
813 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
814 * plaintext one byte less than a multiple of the block size
815 * will be padded with just 01.
817 * This enables the OpenSSL key decryption function to strip
818 * off the padding algorithmically and return the unpadded
819 * plaintext to the next layer: it looks at the final byte, and
820 * then expects to find that many bytes at the end of the data
821 * with the same value. Those are all removed and the rest is
825 while (pos
< outlen
) {
826 outblob
[pos
++] = outlen
- len
;
834 * Invent an iv. Then derive encryption key from passphrase
837 * - let block A equal MD5(passphrase || iv)
838 * - let block B equal MD5(A || passphrase || iv)
839 * - block C would be MD5(B || passphrase || iv) and so on
840 * - encryption key is the first N bytes of A || B
842 struct MD5Context md5c
;
843 unsigned char keybuf
[32];
845 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
848 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
849 MD5Update(&md5c
, iv
, 8);
850 MD5Final(keybuf
, &md5c
);
853 MD5Update(&md5c
, keybuf
, 16);
854 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
855 MD5Update(&md5c
, iv
, 8);
856 MD5Final(keybuf
+16, &md5c
);
859 * Now encrypt the key blob.
861 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
863 memset(&md5c
, 0, sizeof(md5c
));
864 memset(keybuf
, 0, sizeof(keybuf
));
868 * And save it. We'll use Unix line endings just in case it's
869 * subsequently transferred in binary mode.
871 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
876 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
877 for (i
= 0; i
< 8; i
++)
878 fprintf(fp
, "%02X", iv
[i
]);
881 base64_encode(fp
, outblob
, outlen
, 64);
888 memset(outblob
, 0, outlen
);
892 memset(spareblob
, 0, sparelen
);
896 memset(privblob
, 0, privlen
);
900 memset(pubblob
, 0, publen
);
906 /* ----------------------------------------------------------------------
907 * Code to read ssh.com private keys.
911 * The format of the base64 blob is largely ssh2-packet-formatted,
912 * except that mpints are a bit different: they're more like the
913 * old ssh1 mpint. You have a 32-bit bit count N, followed by
914 * (N+7)/8 bytes of data.
916 * So. The blob contains:
918 * - uint32 0x3f6ff9eb (magic number)
919 * - uint32 size (total blob size)
920 * - string key-type (see below)
921 * - string cipher-type (tells you if key is encrypted)
922 * - string encrypted-blob
924 * (The first size field includes the size field itself and the
925 * magic number before it. All other size fields are ordinary ssh2
926 * strings, so the size field indicates how much data is to
929 * The encrypted blob, once decrypted, contains a single string
930 * which in turn contains the payload. (This allows padding to be
931 * added after that string while still making it clear where the
932 * real payload ends. Also it probably makes for a reasonable
935 * The payload blob, for an RSA key, contains:
938 * - mpint n (yes, the public and private stuff is intermixed)
939 * - mpint u (presumably inverse of p mod q)
940 * - mpint p (p is the smaller prime)
941 * - mpint q (q is the larger)
943 * For a DSA key, the payload blob contains:
951 * Alternatively, if the parameters are `predefined', that
952 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
953 * containing some predefined parameter specification. *shudder*,
954 * but I doubt we'll encounter this in real life.
956 * The key type strings are ghastly. The RSA key I looked at had a
959 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
961 * and the DSA key wasn't much better:
963 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
965 * It isn't clear that these will always be the same. I think it
966 * might be wise just to look at the `if-modn{sign{rsa' and
967 * `dl-modp{sign{dsa' prefixes.
969 * Finally, the encryption. The cipher-type string appears to be
970 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
971 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
972 * from the passphrase by means of yet another hashing faff:
974 * - first 16 bytes are MD5(passphrase)
975 * - next 16 bytes are MD5(passphrase || first 16 bytes)
976 * - if there were more, they'd be MD5(passphrase || first 32),
980 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
983 char comment
[256]; /* allowing any length is overkill */
984 unsigned char *keyblob
;
985 int keyblob_len
, keyblob_size
;
988 static struct sshcom_key
*load_sshcom_key(const Filename
*filename
)
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";
1098 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1099 sfree(ret
->keyblob
);
1101 memset(&ret
, 0, sizeof(ret
));
1107 int sshcom_encrypted(const Filename
*filename
, char **comment
)
1109 struct sshcom_key
*key
= load_sshcom_key(filename
);
1110 int pos
, len
, answer
;
1117 * Check magic number.
1119 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb)
1120 return 0; /* key is invalid */
1123 * Find the cipher-type string.
1127 if (key
->keyblob_len
< pos
+4)
1128 goto done
; /* key is far too short */
1129 pos
+= 4 + GET_32BIT(key
->keyblob
+ pos
); /* skip key type */
1130 if (key
->keyblob_len
< pos
+4)
1131 goto done
; /* key is far too short */
1132 len
= GET_32BIT(key
->keyblob
+ pos
); /* find cipher-type length */
1133 if (key
->keyblob_len
< pos
+4+len
)
1134 goto done
; /* cipher type string is incomplete */
1135 if (len
!= 4 || 0 != memcmp(key
->keyblob
+ pos
+ 4, "none", 4))
1139 *comment
= dupstr(key
->comment
);
1140 memset(key
->keyblob
, 0, key
->keyblob_size
);
1141 sfree(key
->keyblob
);
1142 memset(&key
, 0, sizeof(key
));
1147 static int sshcom_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
1151 unsigned char *d
= (unsigned char *) data
;
1155 bits
= GET_32BIT(d
);
1157 bytes
= (bits
+ 7) / 8;
1168 return len
; /* ensure further calls fail as well */
1171 static int sshcom_put_mpint(void *target
, void *data
, int len
)
1173 unsigned char *d
= (unsigned char *)target
;
1174 unsigned char *i
= (unsigned char *)data
;
1175 int bits
= len
* 8 - 1;
1178 if (*i
& (1 << (bits
& 7)))
1184 PUT_32BIT(d
, bits
+1);
1185 memcpy(d
+4, i
, len
);
1189 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
)
1191 struct sshcom_key
*key
= load_sshcom_key(filename
);
1194 const char prefix_rsa
[] = "if-modn{sign{rsa";
1195 const char prefix_dsa
[] = "dl-modp{sign{dsa";
1196 enum { RSA
, DSA
} type
;
1200 struct ssh2_userkey
*ret
= NULL
, *retkey
;
1201 const struct ssh_signkey
*alg
;
1202 unsigned char *blob
= NULL
;
1203 int blobsize
, publen
, privlen
;
1209 * Check magic number.
1211 if (GET_32BIT(key
->keyblob
) != SSHCOM_MAGIC_NUMBER
) {
1212 errmsg
= "Key does not begin with magic number";
1217 * Determine the key type.
1220 if (key
->keyblob_len
< pos
+4 ||
1221 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1222 errmsg
= "Key blob does not contain a key type string";
1225 if (len
> sizeof(prefix_rsa
) - 1 &&
1226 !memcmp(key
->keyblob
+pos
+4, prefix_rsa
, sizeof(prefix_rsa
) - 1)) {
1228 } else if (len
> sizeof(prefix_dsa
) - 1 &&
1229 !memcmp(key
->keyblob
+pos
+4, prefix_dsa
, sizeof(prefix_dsa
) - 1)) {
1232 errmsg
= "Key is of unknown type";
1238 * Determine the cipher type.
1240 if (key
->keyblob_len
< pos
+4 ||
1241 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1242 errmsg
= "Key blob does not contain a cipher type string";
1245 if (len
== 4 && !memcmp(key
->keyblob
+pos
+4, "none", 4))
1247 else if (len
== 8 && !memcmp(key
->keyblob
+pos
+4, "3des-cbc", 8))
1250 errmsg
= "Key encryption is of unknown type";
1256 * Get hold of the encrypted part of the key.
1258 if (key
->keyblob_len
< pos
+4 ||
1259 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1260 errmsg
= "Key blob does not contain actual key data";
1263 ciphertext
= (char *)key
->keyblob
+ pos
+ 4;
1265 if (cipherlen
== 0) {
1266 errmsg
= "Length of key data is zero";
1271 * Decrypt it if necessary.
1275 * Derive encryption key from passphrase and iv/salt:
1277 * - let block A equal MD5(passphrase)
1278 * - let block B equal MD5(passphrase || A)
1279 * - block C would be MD5(passphrase || A || B) and so on
1280 * - encryption key is the first N bytes of A || B
1282 struct MD5Context md5c
;
1283 unsigned char keybuf
[32], iv
[8];
1285 if (cipherlen
% 8 != 0) {
1286 errmsg
= "Encrypted part of key is not a multiple of cipher block"
1292 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1293 MD5Final(keybuf
, &md5c
);
1296 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1297 MD5Update(&md5c
, keybuf
, 16);
1298 MD5Final(keybuf
+16, &md5c
);
1301 * Now decrypt the key blob.
1303 memset(iv
, 0, sizeof(iv
));
1304 des3_decrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1307 memset(&md5c
, 0, sizeof(md5c
));
1308 memset(keybuf
, 0, sizeof(keybuf
));
1311 * Hereafter we return WRONG_PASSPHRASE for any parsing
1312 * error. (But only if we've just tried to decrypt it!
1313 * Returning WRONG_PASSPHRASE for an unencrypted key is
1317 ret
= SSH2_WRONG_PASSPHRASE
;
1321 * Strip away the containing string to get to the real meat.
1323 len
= GET_32BIT(ciphertext
);
1324 if (len
> cipherlen
-4) {
1325 errmsg
= "containing string was ill-formed";
1332 * Now we break down into RSA versus DSA. In either case we'll
1333 * construct public and private blobs in our own format, and
1334 * end up feeding them to alg->createkey().
1336 blobsize
= cipherlen
+ 256;
1337 blob
= snewn(blobsize
, unsigned char);
1340 struct mpint_pos n
, e
, d
, u
, p
, q
;
1342 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &e
);
1343 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &d
);
1344 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &n
);
1345 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &u
);
1346 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1347 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1349 errmsg
= "key data did not contain six integers";
1355 pos
+= put_string(blob
+pos
, "ssh-rsa", 7);
1356 pos
+= put_mp(blob
+pos
, e
.start
, e
.bytes
);
1357 pos
+= put_mp(blob
+pos
, n
.start
, n
.bytes
);
1359 pos
+= put_string(blob
+pos
, d
.start
, d
.bytes
);
1360 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1361 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1362 pos
+= put_mp(blob
+pos
, u
.start
, u
.bytes
);
1363 privlen
= pos
- publen
;
1364 } else if (type
== DSA
) {
1365 struct mpint_pos p
, q
, g
, x
, y
;
1367 if (GET_32BIT(ciphertext
) != 0) {
1368 errmsg
= "predefined DSA parameters not supported";
1371 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1372 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &g
);
1373 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1374 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &y
);
1375 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &x
);
1377 errmsg
= "key data did not contain five integers";
1383 pos
+= put_string(blob
+pos
, "ssh-dss", 7);
1384 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1385 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1386 pos
+= put_mp(blob
+pos
, g
.start
, g
.bytes
);
1387 pos
+= put_mp(blob
+pos
, y
.start
, y
.bytes
);
1389 pos
+= put_mp(blob
+pos
, x
.start
, x
.bytes
);
1390 privlen
= pos
- publen
;
1393 assert(privlen
> 0); /* should have bombed by now if not */
1395 retkey
= snew(struct ssh2_userkey
);
1397 retkey
->data
= alg
->createkey(blob
, publen
, blob
+publen
, privlen
);
1398 if (!retkey
->data
) {
1400 errmsg
= "unable to create key data structure";
1403 retkey
->comment
= dupstr(key
->comment
);
1405 errmsg
= NULL
; /* no error */
1410 memset(blob
, 0, blobsize
);
1413 memset(key
->keyblob
, 0, key
->keyblob_size
);
1414 sfree(key
->keyblob
);
1415 memset(&key
, 0, sizeof(key
));
1420 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
1423 unsigned char *pubblob
, *privblob
;
1424 int publen
, privlen
;
1425 unsigned char *outblob
;
1427 struct mpint_pos numbers
[6];
1428 int nnumbers
, initial_zero
, pos
, lenpos
, i
;
1436 * Fetch the key blobs.
1438 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
1439 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
1443 * Find the sequence of integers to be encoded into the OpenSSH
1444 * key blob, and also decide on the header line.
1446 if (key
->alg
== &ssh_rsa
) {
1448 struct mpint_pos n
, e
, d
, p
, q
, iqmp
;
1450 pos
= 4 + GET_32BIT(pubblob
);
1451 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
1452 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
1454 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
1455 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
1456 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
1457 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
1459 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
1470 type
= "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1471 } else if (key
->alg
== &ssh_dss
) {
1473 struct mpint_pos p
, q
, g
, y
, x
;
1475 pos
= 4 + GET_32BIT(pubblob
);
1476 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
1477 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
1478 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
1479 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
1481 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
1483 assert(y
.start
&& x
.start
); /* can't go wrong */
1493 type
= "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1495 assert(0); /* zoinks! */
1499 * Total size of key blob will be somewhere under 512 plus
1500 * combined length of integers. We'll calculate the more
1501 * precise size as we construct the blob.
1504 for (i
= 0; i
< nnumbers
; i
++)
1505 outlen
+= 4 + numbers
[i
].bytes
;
1506 outblob
= snewn(outlen
, unsigned char);
1509 * Create the unencrypted key blob.
1512 PUT_32BIT(outblob
+pos
, SSHCOM_MAGIC_NUMBER
); pos
+= 4;
1513 pos
+= 4; /* length field, fill in later */
1514 pos
+= put_string(outblob
+pos
, type
, strlen(type
));
1516 char *ciphertype
= passphrase ?
"3des-cbc" : "none";
1517 pos
+= put_string(outblob
+pos
, ciphertype
, strlen(ciphertype
));
1519 lenpos
= pos
; /* remember this position */
1520 pos
+= 4; /* encrypted-blob size */
1521 pos
+= 4; /* encrypted-payload size */
1523 PUT_32BIT(outblob
+pos
, 0);
1526 for (i
= 0; i
< nnumbers
; i
++)
1527 pos
+= sshcom_put_mpint(outblob
+pos
,
1528 numbers
[i
].start
, numbers
[i
].bytes
);
1529 /* Now wrap up the encrypted payload. */
1530 PUT_32BIT(outblob
+lenpos
+4, pos
- (lenpos
+8));
1531 /* Pad encrypted blob to a multiple of cipher block size. */
1533 int padding
= -(pos
- (lenpos
+4)) & 7;
1535 outblob
[pos
++] = random_byte();
1537 ciphertext
= (char *)outblob
+lenpos
+4;
1538 cipherlen
= pos
- (lenpos
+4);
1539 assert(!passphrase
|| cipherlen
% 8 == 0);
1540 /* Wrap up the encrypted blob string. */
1541 PUT_32BIT(outblob
+lenpos
, cipherlen
);
1542 /* And finally fill in the total length field. */
1543 PUT_32BIT(outblob
+4, pos
);
1545 assert(pos
< outlen
);
1552 * Derive encryption key from passphrase and iv/salt:
1554 * - let block A equal MD5(passphrase)
1555 * - let block B equal MD5(passphrase || A)
1556 * - block C would be MD5(passphrase || A || B) and so on
1557 * - encryption key is the first N bytes of A || B
1559 struct MD5Context md5c
;
1560 unsigned char keybuf
[32], iv
[8];
1563 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1564 MD5Final(keybuf
, &md5c
);
1567 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1568 MD5Update(&md5c
, keybuf
, 16);
1569 MD5Final(keybuf
+16, &md5c
);
1572 * Now decrypt the key blob.
1574 memset(iv
, 0, sizeof(iv
));
1575 des3_encrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1578 memset(&md5c
, 0, sizeof(md5c
));
1579 memset(keybuf
, 0, sizeof(keybuf
));
1583 * And save it. We'll use Unix line endings just in case it's
1584 * subsequently transferred in binary mode.
1586 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
1589 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1590 fprintf(fp
, "Comment: \"");
1592 * Comment header is broken with backslash-newline if it goes
1593 * over 70 chars. Although it's surrounded by quotes, it
1594 * _doesn't_ escape backslashes or quotes within the string.
1595 * Don't ask me, I didn't design it.
1598 int slen
= 60; /* starts at 60 due to "Comment: " */
1599 char *c
= key
->comment
;
1600 while ((int)strlen(c
) > slen
) {
1601 fprintf(fp
, "%.*s\\\n", slen
, c
);
1603 slen
= 70; /* allow 70 chars on subsequent lines */
1605 fprintf(fp
, "%s\"\n", c
);
1607 base64_encode(fp
, outblob
, pos
, 70);
1608 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1614 memset(outblob
, 0, outlen
);
1618 memset(privblob
, 0, privlen
);
1622 memset(pubblob
, 0, publen
);