2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
15 int openssh_encrypted(const Filename
*filename
);
16 struct ssh2_userkey
*openssh_read(const Filename
*filename
, char *passphrase
,
17 const char **errmsg_p
);
18 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
21 int sshcom_encrypted(const Filename
*filename
, char **comment
);
22 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
,
23 const char **errmsg_p
);
24 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
28 * Given a key type, determine whether we know how to import it.
30 int import_possible(int type
)
32 if (type
== SSH_KEYTYPE_OPENSSH
)
34 if (type
== SSH_KEYTYPE_SSHCOM
)
40 * Given a key type, determine what native key type
41 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
44 int import_target_type(int type
)
47 * There are no known foreign SSH-1 key formats.
49 return SSH_KEYTYPE_SSH2
;
53 * Determine whether a foreign key is encrypted.
55 int import_encrypted(const Filename
*filename
, int type
, char **comment
)
57 if (type
== SSH_KEYTYPE_OPENSSH
) {
58 /* OpenSSH doesn't do key comments */
59 *comment
= dupstr(filename_to_str(filename
));
60 return openssh_encrypted(filename
);
62 if (type
== SSH_KEYTYPE_SSHCOM
) {
63 return sshcom_encrypted(filename
, comment
);
69 * Import an SSH-1 key.
71 int import_ssh1(const Filename
*filename
, int type
,
72 struct RSAKey
*key
, char *passphrase
, const char **errmsg_p
)
78 * Import an SSH-2 key.
80 struct ssh2_userkey
*import_ssh2(const Filename
*filename
, int type
,
81 char *passphrase
, const char **errmsg_p
)
83 if (type
== SSH_KEYTYPE_OPENSSH
)
84 return openssh_read(filename
, passphrase
, errmsg_p
);
85 if (type
== SSH_KEYTYPE_SSHCOM
)
86 return sshcom_read(filename
, passphrase
, errmsg_p
);
91 * Export an SSH-1 key.
93 int export_ssh1(const Filename
*filename
, int type
, struct RSAKey
*key
,
100 * Export an SSH-2 key.
102 int export_ssh2(const Filename
*filename
, int type
,
103 struct ssh2_userkey
*key
, char *passphrase
)
105 if (type
== SSH_KEYTYPE_OPENSSH
)
106 return openssh_write(filename
, key
, passphrase
);
107 if (type
== SSH_KEYTYPE_SSHCOM
)
108 return sshcom_write(filename
, key
, passphrase
);
113 * Strip trailing CRs and LFs at the end of a line of text.
115 void strip_crlf(char *str
)
117 char *p
= str
+ strlen(str
);
119 while (p
> str
&& (p
[-1] == '\r' || p
[-1] == '\n'))
123 /* ----------------------------------------------------------------------
124 * Helper routines. (The base64 ones are defined in sshpubk.c.)
127 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
128 ((c) >= 'a' && (c) <= 'z') || \
129 ((c) >= '0' && (c) <= '9') || \
130 (c) == '+' || (c) == '/' || (c) == '=' \
134 * Read an ASN.1/BER identifier and length pair.
136 * Flags are a combination of the #defines listed below.
138 * Returns -1 if unsuccessful; otherwise returns the number of
139 * bytes used out of the source data.
142 /* ASN.1 tag classes. */
143 #define ASN1_CLASS_UNIVERSAL (0 << 6)
144 #define ASN1_CLASS_APPLICATION (1 << 6)
145 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
146 #define ASN1_CLASS_PRIVATE (3 << 6)
147 #define ASN1_CLASS_MASK (3 << 6)
149 /* Primitive versus constructed bit. */
150 #define ASN1_CONSTRUCTED (1 << 5)
152 static int ber_read_id_len(void *source
, int sourcelen
,
153 int *id
, int *length
, int *flags
)
155 unsigned char *p
= (unsigned char *) source
;
160 *flags
= (*p
& 0xE0);
161 if ((*p
& 0x1F) == 0x1F) {
167 *id
= (*id
<< 7) | (*p
& 0x7F);
185 *length
= (*length
<< 8) | (*p
++);
192 return p
- (unsigned char *) source
;
196 * Write an ASN.1/BER identifier and length pair. Returns the
197 * number of bytes consumed. Assumes dest contains enough space.
198 * Will avoid writing anything if dest is NULL, but still return
199 * amount of space required.
201 static int ber_write_id_len(void *dest
, int id
, int length
, int flags
)
203 unsigned char *d
= (unsigned char *)dest
;
208 * Identifier is one byte.
211 if (d
) *d
++ = id
| flags
;
215 * Identifier is multiple bytes: the first byte is 11111
216 * plus the flags, and subsequent bytes encode the value of
217 * the identifier, 7 bits at a time, with the top bit of
218 * each byte 1 except the last one which is 0.
221 if (d
) *d
++ = 0x1F | flags
;
222 for (n
= 1; (id
>> (7*n
)) > 0; n
++)
223 continue; /* count the bytes */
226 if (d
) *d
++ = (n ?
0x80 : 0) | ((id
>> (7*n
)) & 0x7F);
232 * Length is one byte.
235 if (d
) *d
++ = length
;
239 * Length is multiple bytes. The first is 0x80 plus the
240 * number of subsequent bytes, and the subsequent bytes
241 * encode the actual length.
243 for (n
= 1; (length
>> (8*n
)) > 0; n
++)
244 continue; /* count the bytes */
246 if (d
) *d
++ = 0x80 | n
;
249 if (d
) *d
++ = (length
>> (8*n
)) & 0xFF;
256 static int put_string(void *target
, void *data
, int len
)
258 unsigned char *d
= (unsigned char *)target
;
261 memcpy(d
+4, data
, len
);
265 static int put_mp(void *target
, void *data
, int len
)
267 unsigned char *d
= (unsigned char *)target
;
268 unsigned char *i
= (unsigned char *)data
;
273 memcpy(d
+5, data
, len
);
277 memcpy(d
+4, data
, len
);
282 /* Simple structure to point to an mp-int within a blob. */
283 struct mpint_pos
{ void *start
; int bytes
; };
285 static int ssh2_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
288 unsigned char *d
= (unsigned char *) data
;
292 bytes
= GET_32BIT(d
);
303 return len
; /* ensure further calls fail as well */
306 /* ----------------------------------------------------------------------
307 * Code to read and write OpenSSH private keys.
310 enum { OSSH_DSA
, OSSH_RSA
};
315 unsigned char *keyblob
;
316 int keyblob_len
, keyblob_size
;
319 static struct openssh_key
*load_openssh_key(const Filename
*filename
,
320 const char **errmsg_p
)
322 struct openssh_key
*ret
;
328 int base64_chars
= 0;
330 ret
= snew(struct openssh_key
);
332 ret
->keyblob_len
= ret
->keyblob_size
= 0;
334 memset(ret
->iv
, 0, sizeof(ret
->iv
));
336 fp
= f_open(*filename
, "r", FALSE
);
338 errmsg
= "unable to open key file";
342 if (!(line
= fgetline(fp
))) {
343 errmsg
= "unexpected end of file";
347 if (0 != strncmp(line
, "-----BEGIN ", 11) ||
348 0 != strcmp(line
+strlen(line
)-16, "PRIVATE KEY-----")) {
349 errmsg
= "file does not begin with OpenSSH key header";
352 if (!strcmp(line
, "-----BEGIN RSA PRIVATE KEY-----"))
353 ret
->type
= OSSH_RSA
;
354 else if (!strcmp(line
, "-----BEGIN DSA PRIVATE KEY-----"))
355 ret
->type
= OSSH_DSA
;
357 errmsg
= "unrecognised key type";
360 memset(line
, 0, strlen(line
));
366 if (!(line
= fgetline(fp
))) {
367 errmsg
= "unexpected end of file";
371 if (0 == strncmp(line
, "-----END ", 9) &&
372 0 == strcmp(line
+strlen(line
)-16, "PRIVATE KEY-----"))
374 if ((p
= strchr(line
, ':')) != NULL
) {
376 errmsg
= "header found in body of key data";
380 while (*p
&& isspace((unsigned char)*p
)) p
++;
381 if (!strcmp(line
, "Proc-Type")) {
382 if (p
[0] != '4' || p
[1] != ',') {
383 errmsg
= "Proc-Type is not 4 (only 4 is supported)";
387 if (!strcmp(p
, "ENCRYPTED"))
389 } else if (!strcmp(line
, "DEK-Info")) {
392 if (strncmp(p
, "DES-EDE3-CBC,", 13)) {
393 errmsg
= "ciphers other than DES-EDE3-CBC not supported";
397 for (i
= 0; i
< 8; i
++) {
398 if (1 != sscanf(p
, "%2x", &j
))
404 errmsg
= "expected 16-digit iv in DEK-Info";
412 while (isbase64(*p
)) {
413 base64_bit
[base64_chars
++] = *p
;
414 if (base64_chars
== 4) {
415 unsigned char out
[3];
420 len
= base64_decode_atom(base64_bit
, out
);
423 errmsg
= "invalid base64 encoding";
427 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
428 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
429 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
433 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
434 ret
->keyblob_len
+= len
;
436 memset(out
, 0, sizeof(out
));
442 memset(line
, 0, strlen(line
));
447 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
448 errmsg
= "key body not present";
452 if (ret
->encrypted
&& ret
->keyblob_len
% 8 != 0) {
453 errmsg
= "encrypted key blob is not a multiple of cipher block size";
457 memset(base64_bit
, 0, sizeof(base64_bit
));
458 if (errmsg_p
) *errmsg_p
= NULL
;
463 memset(line
, 0, strlen(line
));
467 memset(base64_bit
, 0, sizeof(base64_bit
));
470 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
473 memset(ret
, 0, sizeof(*ret
));
476 if (errmsg_p
) *errmsg_p
= errmsg
;
480 int openssh_encrypted(const Filename
*filename
)
482 struct openssh_key
*key
= load_openssh_key(filename
, NULL
);
487 ret
= key
->encrypted
;
488 memset(key
->keyblob
, 0, key
->keyblob_size
);
490 memset(key
, 0, sizeof(*key
));
495 struct ssh2_userkey
*openssh_read(const Filename
*filename
, char *passphrase
,
496 const char **errmsg_p
)
498 struct openssh_key
*key
= load_openssh_key(filename
, errmsg_p
);
499 struct ssh2_userkey
*retkey
;
501 int ret
, id
, len
, flags
;
503 struct ssh2_userkey
*retval
= NULL
;
506 int blobsize
= 0, blobptr
, privptr
;
515 if (key
->encrypted
) {
517 * Derive encryption key from passphrase and iv/salt:
519 * - let block A equal MD5(passphrase || iv)
520 * - let block B equal MD5(A || passphrase || iv)
521 * - block C would be MD5(B || passphrase || iv) and so on
522 * - encryption key is the first N bytes of A || B
524 struct MD5Context md5c
;
525 unsigned char keybuf
[32];
528 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
529 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
530 MD5Final(keybuf
, &md5c
);
533 MD5Update(&md5c
, keybuf
, 16);
534 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
535 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
536 MD5Final(keybuf
+16, &md5c
);
539 * Now decrypt the key blob.
541 des3_decrypt_pubkey_ossh(keybuf
, (unsigned char *)key
->iv
,
542 key
->keyblob
, key
->keyblob_len
);
544 memset(&md5c
, 0, sizeof(md5c
));
545 memset(keybuf
, 0, sizeof(keybuf
));
549 * Now we have a decrypted key blob, which contains an ASN.1
550 * encoded private key. We must now untangle the ASN.1.
552 * We expect the whole key blob to be formatted as a SEQUENCE
553 * (0x30 followed by a length code indicating that the rest of
554 * the blob is part of the sequence). Within that SEQUENCE we
555 * expect to see a bunch of INTEGERs. What those integers mean
556 * depends on the key type:
558 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
559 * dmp1, dmq1, iqmp in that order. (The last three are d mod
560 * (p-1), d mod (q-1), inverse of q mod p respectively.)
562 * - For DSA, we expect them to be 0, p, q, g, y, x in that
568 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
569 ret
= ber_read_id_len(p
, key
->keyblob_len
, &id
, &len
, &flags
);
571 if (ret
< 0 || id
!= 16) {
572 errmsg
= "ASN.1 decoding failure";
573 retval
= SSH2_WRONG_PASSPHRASE
;
577 /* Expect a load of INTEGERs. */
578 if (key
->type
== OSSH_RSA
)
580 else if (key
->type
== OSSH_DSA
)
583 num_integers
= 0; /* placate compiler warnings */
586 * Space to create key blob in.
588 blobsize
= 256+key
->keyblob_len
;
589 blob
= snewn(blobsize
, unsigned char);
591 if (key
->type
== OSSH_DSA
)
592 memcpy(blob
+4, "ssh-dss", 7);
593 else if (key
->type
== OSSH_RSA
)
594 memcpy(blob
+4, "ssh-rsa", 7);
598 for (i
= 0; i
< num_integers
; i
++) {
599 ret
= ber_read_id_len(p
, key
->keyblob
+key
->keyblob_len
-p
,
602 if (ret
< 0 || id
!= 2 ||
603 key
->keyblob
+key
->keyblob_len
-p
< len
) {
604 errmsg
= "ASN.1 decoding failure";
605 retval
= SSH2_WRONG_PASSPHRASE
;
611 * The first integer should be zero always (I think
612 * this is some sort of version indication).
614 if (len
!= 1 || p
[0] != 0) {
615 errmsg
= "version number mismatch";
618 } else if (key
->type
== OSSH_RSA
) {
620 * Integers 1 and 2 go into the public blob but in the
621 * opposite order; integers 3, 4, 5 and 8 go into the
622 * private blob. The other two (6 and 7) are ignored.
625 /* Save the details for after we deal with number 2. */
628 } else if (i
!= 6 && i
!= 7) {
629 PUT_32BIT(blob
+blobptr
, len
);
630 memcpy(blob
+blobptr
+4, p
, len
);
633 PUT_32BIT(blob
+blobptr
, modlen
);
634 memcpy(blob
+blobptr
+4, modptr
, modlen
);
639 } else if (key
->type
== OSSH_DSA
) {
641 * Integers 1-4 go into the public blob; integer 5 goes
642 * into the private blob.
644 PUT_32BIT(blob
+blobptr
, len
);
645 memcpy(blob
+blobptr
+4, p
, len
);
651 /* Skip past the number. */
656 * Now put together the actual key. Simplest way to do this is
657 * to assemble our own key blobs and feed them to the createkey
658 * functions; this is a bit faffy but it does mean we get all
659 * the sanity checks for free.
661 assert(privptr
> 0); /* should have bombed by now if not */
662 retkey
= snew(struct ssh2_userkey
);
663 retkey
->alg
= (key
->type
== OSSH_RSA ?
&ssh_rsa
: &ssh_dss
);
664 retkey
->data
= retkey
->alg
->createkey(blob
, privptr
,
665 blob
+privptr
, blobptr
-privptr
);
668 errmsg
= "unable to create key data structure";
672 retkey
->comment
= dupstr("imported-openssh-key");
673 errmsg
= NULL
; /* no error */
678 memset(blob
, 0, blobsize
);
681 memset(key
->keyblob
, 0, key
->keyblob_size
);
683 memset(key
, 0, sizeof(*key
));
685 if (errmsg_p
) *errmsg_p
= errmsg
;
689 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
692 unsigned char *pubblob
, *privblob
, *spareblob
;
693 int publen
, privlen
, sparelen
= 0;
694 unsigned char *outblob
;
696 struct mpint_pos numbers
[9];
697 int nnumbers
, pos
, len
, seqlen
, i
;
698 char *header
, *footer
;
705 * Fetch the key blobs.
707 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
708 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
709 spareblob
= outblob
= NULL
;
712 * Find the sequence of integers to be encoded into the OpenSSH
713 * key blob, and also decide on the header line.
715 if (key
->alg
== &ssh_rsa
) {
717 struct mpint_pos n
, e
, d
, p
, q
, iqmp
, dmp1
, dmq1
;
718 Bignum bd
, bp
, bq
, bdmp1
, bdmq1
;
720 pos
= 4 + GET_32BIT(pubblob
);
721 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
722 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
724 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
725 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
726 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
727 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
729 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
731 /* We also need d mod (p-1) and d mod (q-1). */
732 bd
= bignum_from_bytes(d
.start
, d
.bytes
);
733 bp
= bignum_from_bytes(p
.start
, p
.bytes
);
734 bq
= bignum_from_bytes(q
.start
, q
.bytes
);
737 bdmp1
= bigmod(bd
, bp
);
738 bdmq1
= bigmod(bd
, bq
);
743 dmp1
.bytes
= (bignum_bitcount(bdmp1
)+8)/8;
744 dmq1
.bytes
= (bignum_bitcount(bdmq1
)+8)/8;
745 sparelen
= dmp1
.bytes
+ dmq1
.bytes
;
746 spareblob
= snewn(sparelen
, unsigned char);
747 dmp1
.start
= spareblob
;
748 dmq1
.start
= spareblob
+ dmp1
.bytes
;
749 for (i
= 0; i
< dmp1
.bytes
; i
++)
750 spareblob
[i
] = bignum_byte(bdmp1
, dmp1
.bytes
-1 - i
);
751 for (i
= 0; i
< dmq1
.bytes
; i
++)
752 spareblob
[i
+dmp1
.bytes
] = bignum_byte(bdmq1
, dmq1
.bytes
-1 - i
);
756 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
767 header
= "-----BEGIN RSA PRIVATE KEY-----\n";
768 footer
= "-----END RSA PRIVATE KEY-----\n";
769 } else if (key
->alg
== &ssh_dss
) {
771 struct mpint_pos p
, q
, g
, y
, x
;
773 pos
= 4 + GET_32BIT(pubblob
);
774 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
775 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
776 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
777 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
779 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
781 assert(y
.start
&& x
.start
); /* can't go wrong */
783 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
791 header
= "-----BEGIN DSA PRIVATE KEY-----\n";
792 footer
= "-----END DSA PRIVATE KEY-----\n";
794 assert(0); /* zoinks! */
795 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
799 * Now count up the total size of the ASN.1 encoded integers,
800 * so as to determine the length of the containing SEQUENCE.
803 for (i
= 0; i
< nnumbers
; i
++) {
804 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
805 len
+= numbers
[i
].bytes
;
808 /* Now add on the SEQUENCE header. */
809 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
810 /* Round up to the cipher block size, ensuring we have at least one
811 * byte of padding (see below). */
814 outlen
= (outlen
+8) &~ 7;
817 * Now we know how big outblob needs to be. Allocate it.
819 outblob
= snewn(outlen
, unsigned char);
822 * And write the data into it.
825 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
826 for (i
= 0; i
< nnumbers
; i
++) {
827 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
828 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
829 pos
+= numbers
[i
].bytes
;
833 * Padding on OpenSSH keys is deterministic. The number of
834 * padding bytes is always more than zero, and always at most
835 * the cipher block length. The value of each padding byte is
836 * equal to the number of padding bytes. So a plaintext that's
837 * an exact multiple of the block size will be padded with 08
838 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
839 * plaintext one byte less than a multiple of the block size
840 * will be padded with just 01.
842 * This enables the OpenSSL key decryption function to strip
843 * off the padding algorithmically and return the unpadded
844 * plaintext to the next layer: it looks at the final byte, and
845 * then expects to find that many bytes at the end of the data
846 * with the same value. Those are all removed and the rest is
850 while (pos
< outlen
) {
851 outblob
[pos
++] = outlen
- len
;
859 * Invent an iv. Then derive encryption key from passphrase
862 * - let block A equal MD5(passphrase || iv)
863 * - let block B equal MD5(A || passphrase || iv)
864 * - block C would be MD5(B || passphrase || iv) and so on
865 * - encryption key is the first N bytes of A || B
867 struct MD5Context md5c
;
868 unsigned char keybuf
[32];
870 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
873 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
874 MD5Update(&md5c
, iv
, 8);
875 MD5Final(keybuf
, &md5c
);
878 MD5Update(&md5c
, keybuf
, 16);
879 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
880 MD5Update(&md5c
, iv
, 8);
881 MD5Final(keybuf
+16, &md5c
);
884 * Now encrypt the key blob.
886 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
888 memset(&md5c
, 0, sizeof(md5c
));
889 memset(keybuf
, 0, sizeof(keybuf
));
893 * And save it. We'll use Unix line endings just in case it's
894 * subsequently transferred in binary mode.
896 fp
= f_open(*filename
, "wb", TRUE
); /* ensure Unix line endings */
901 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
902 for (i
= 0; i
< 8; i
++)
903 fprintf(fp
, "%02X", iv
[i
]);
906 base64_encode(fp
, outblob
, outlen
, 64);
913 memset(outblob
, 0, outlen
);
917 memset(spareblob
, 0, sparelen
);
921 memset(privblob
, 0, privlen
);
925 memset(pubblob
, 0, publen
);
931 /* ----------------------------------------------------------------------
932 * Code to read ssh.com private keys.
936 * The format of the base64 blob is largely SSH-2-packet-formatted,
937 * except that mpints are a bit different: they're more like the
938 * old SSH-1 mpint. You have a 32-bit bit count N, followed by
939 * (N+7)/8 bytes of data.
941 * So. The blob contains:
943 * - uint32 0x3f6ff9eb (magic number)
944 * - uint32 size (total blob size)
945 * - string key-type (see below)
946 * - string cipher-type (tells you if key is encrypted)
947 * - string encrypted-blob
949 * (The first size field includes the size field itself and the
950 * magic number before it. All other size fields are ordinary SSH-2
951 * strings, so the size field indicates how much data is to
954 * The encrypted blob, once decrypted, contains a single string
955 * which in turn contains the payload. (This allows padding to be
956 * added after that string while still making it clear where the
957 * real payload ends. Also it probably makes for a reasonable
960 * The payload blob, for an RSA key, contains:
963 * - mpint n (yes, the public and private stuff is intermixed)
964 * - mpint u (presumably inverse of p mod q)
965 * - mpint p (p is the smaller prime)
966 * - mpint q (q is the larger)
968 * For a DSA key, the payload blob contains:
976 * Alternatively, if the parameters are `predefined', that
977 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
978 * containing some predefined parameter specification. *shudder*,
979 * but I doubt we'll encounter this in real life.
981 * The key type strings are ghastly. The RSA key I looked at had a
984 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
986 * and the DSA key wasn't much better:
988 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
990 * It isn't clear that these will always be the same. I think it
991 * might be wise just to look at the `if-modn{sign{rsa' and
992 * `dl-modp{sign{dsa' prefixes.
994 * Finally, the encryption. The cipher-type string appears to be
995 * either `none' or `3des-cbc'. Looks as if this is SSH-2-style
996 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
997 * from the passphrase by means of yet another hashing faff:
999 * - first 16 bytes are MD5(passphrase)
1000 * - next 16 bytes are MD5(passphrase || first 16 bytes)
1001 * - if there were more, they'd be MD5(passphrase || first 32),
1005 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
1008 char comment
[256]; /* allowing any length is overkill */
1009 unsigned char *keyblob
;
1010 int keyblob_len
, keyblob_size
;
1013 static struct sshcom_key
*load_sshcom_key(const Filename
*filename
,
1014 const char **errmsg_p
)
1016 struct sshcom_key
*ret
;
1023 int base64_chars
= 0;
1025 ret
= snew(struct sshcom_key
);
1026 ret
->comment
[0] = '\0';
1027 ret
->keyblob
= NULL
;
1028 ret
->keyblob_len
= ret
->keyblob_size
= 0;
1030 fp
= f_open(*filename
, "r", FALSE
);
1032 errmsg
= "unable to open key file";
1035 if (!(line
= fgetline(fp
))) {
1036 errmsg
= "unexpected end of file";
1040 if (0 != strcmp(line
, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----")) {
1041 errmsg
= "file does not begin with ssh.com key header";
1044 memset(line
, 0, strlen(line
));
1050 if (!(line
= fgetline(fp
))) {
1051 errmsg
= "unexpected end of file";
1055 if (!strcmp(line
, "---- END SSH2 ENCRYPTED PRIVATE KEY ----"))
1057 if ((p
= strchr(line
, ':')) != NULL
) {
1059 errmsg
= "header found in body of key data";
1063 while (*p
&& isspace((unsigned char)*p
)) p
++;
1064 hdrstart
= p
- line
;
1067 * Header lines can end in a trailing backslash for
1070 len
= hdrstart
+ strlen(line
+hdrstart
);
1072 while (line
[len
-1] == '\\') {
1076 line2
= fgetline(fp
);
1078 errmsg
= "unexpected end of file";
1083 line2len
= strlen(line2
);
1084 line
= sresize(line
, len
+ line2len
+ 1, char);
1085 strcpy(line
+ len
- 1, line2
);
1086 len
+= line2len
- 1;
1089 memset(line2
, 0, strlen(line2
));
1093 p
= line
+ hdrstart
;
1095 if (!strcmp(line
, "Comment")) {
1096 /* Strip quotes in comment if present. */
1097 if (p
[0] == '"' && p
[strlen(p
)-1] == '"') {
1099 p
[strlen(p
)-1] = '\0';
1101 strncpy(ret
->comment
, p
, sizeof(ret
->comment
));
1102 ret
->comment
[sizeof(ret
->comment
)-1] = '\0';
1108 while (isbase64(*p
)) {
1109 base64_bit
[base64_chars
++] = *p
;
1110 if (base64_chars
== 4) {
1111 unsigned char out
[3];
1115 len
= base64_decode_atom(base64_bit
, out
);
1118 errmsg
= "invalid base64 encoding";
1122 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
1123 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
1124 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
1128 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
1129 ret
->keyblob_len
+= len
;
1135 memset(line
, 0, strlen(line
));
1140 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
1141 errmsg
= "key body not present";
1145 if (errmsg_p
) *errmsg_p
= NULL
;
1150 memset(line
, 0, strlen(line
));
1156 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1157 sfree(ret
->keyblob
);
1159 memset(ret
, 0, sizeof(*ret
));
1162 if (errmsg_p
) *errmsg_p
= errmsg
;
1166 int sshcom_encrypted(const Filename
*filename
, char **comment
)
1168 struct sshcom_key
*key
= load_sshcom_key(filename
, NULL
);
1169 int pos
, len
, answer
;
1176 * Check magic number.
1178 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb)
1179 return 0; /* key is invalid */
1182 * Find the cipher-type string.
1186 if (key
->keyblob_len
< pos
+4)
1187 goto done
; /* key is far too short */
1188 pos
+= 4 + GET_32BIT(key
->keyblob
+ pos
); /* skip key type */
1189 if (key
->keyblob_len
< pos
+4)
1190 goto done
; /* key is far too short */
1191 len
= GET_32BIT(key
->keyblob
+ pos
); /* find cipher-type length */
1192 if (key
->keyblob_len
< pos
+4+len
)
1193 goto done
; /* cipher type string is incomplete */
1194 if (len
!= 4 || 0 != memcmp(key
->keyblob
+ pos
+ 4, "none", 4))
1198 *comment
= dupstr(key
->comment
);
1199 memset(key
->keyblob
, 0, key
->keyblob_size
);
1200 sfree(key
->keyblob
);
1201 memset(key
, 0, sizeof(*key
));
1206 static int sshcom_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
1210 unsigned char *d
= (unsigned char *) data
;
1214 bits
= GET_32BIT(d
);
1216 bytes
= (bits
+ 7) / 8;
1227 return len
; /* ensure further calls fail as well */
1230 static int sshcom_put_mpint(void *target
, void *data
, int len
)
1232 unsigned char *d
= (unsigned char *)target
;
1233 unsigned char *i
= (unsigned char *)data
;
1234 int bits
= len
* 8 - 1;
1237 if (*i
& (1 << (bits
& 7)))
1243 PUT_32BIT(d
, bits
+1);
1244 memcpy(d
+4, i
, len
);
1248 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
,
1249 const char **errmsg_p
)
1251 struct sshcom_key
*key
= load_sshcom_key(filename
, errmsg_p
);
1254 const char prefix_rsa
[] = "if-modn{sign{rsa";
1255 const char prefix_dsa
[] = "dl-modp{sign{dsa";
1256 enum { RSA
, DSA
} type
;
1260 struct ssh2_userkey
*ret
= NULL
, *retkey
;
1261 const struct ssh_signkey
*alg
;
1262 unsigned char *blob
= NULL
;
1263 int blobsize
= 0, publen
, privlen
;
1269 * Check magic number.
1271 if (GET_32BIT(key
->keyblob
) != SSHCOM_MAGIC_NUMBER
) {
1272 errmsg
= "key does not begin with magic number";
1277 * Determine the key type.
1280 if (key
->keyblob_len
< pos
+4 ||
1281 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1282 errmsg
= "key blob does not contain a key type string";
1285 if (len
> sizeof(prefix_rsa
) - 1 &&
1286 !memcmp(key
->keyblob
+pos
+4, prefix_rsa
, sizeof(prefix_rsa
) - 1)) {
1288 } else if (len
> sizeof(prefix_dsa
) - 1 &&
1289 !memcmp(key
->keyblob
+pos
+4, prefix_dsa
, sizeof(prefix_dsa
) - 1)) {
1292 errmsg
= "key is of unknown type";
1298 * Determine the cipher type.
1300 if (key
->keyblob_len
< pos
+4 ||
1301 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1302 errmsg
= "key blob does not contain a cipher type string";
1305 if (len
== 4 && !memcmp(key
->keyblob
+pos
+4, "none", 4))
1307 else if (len
== 8 && !memcmp(key
->keyblob
+pos
+4, "3des-cbc", 8))
1310 errmsg
= "key encryption is of unknown type";
1316 * Get hold of the encrypted part of the key.
1318 if (key
->keyblob_len
< pos
+4 ||
1319 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1320 errmsg
= "key blob does not contain actual key data";
1323 ciphertext
= (char *)key
->keyblob
+ pos
+ 4;
1325 if (cipherlen
== 0) {
1326 errmsg
= "length of key data is zero";
1331 * Decrypt it if necessary.
1335 * Derive encryption key from passphrase and iv/salt:
1337 * - let block A equal MD5(passphrase)
1338 * - let block B equal MD5(passphrase || A)
1339 * - block C would be MD5(passphrase || A || B) and so on
1340 * - encryption key is the first N bytes of A || B
1342 struct MD5Context md5c
;
1343 unsigned char keybuf
[32], iv
[8];
1345 if (cipherlen
% 8 != 0) {
1346 errmsg
= "encrypted part of key is not a multiple of cipher block"
1352 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1353 MD5Final(keybuf
, &md5c
);
1356 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1357 MD5Update(&md5c
, keybuf
, 16);
1358 MD5Final(keybuf
+16, &md5c
);
1361 * Now decrypt the key blob.
1363 memset(iv
, 0, sizeof(iv
));
1364 des3_decrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1367 memset(&md5c
, 0, sizeof(md5c
));
1368 memset(keybuf
, 0, sizeof(keybuf
));
1371 * Hereafter we return WRONG_PASSPHRASE for any parsing
1372 * error. (But only if we've just tried to decrypt it!
1373 * Returning WRONG_PASSPHRASE for an unencrypted key is
1377 ret
= SSH2_WRONG_PASSPHRASE
;
1381 * Strip away the containing string to get to the real meat.
1383 len
= GET_32BIT(ciphertext
);
1384 if (len
< 0 || len
> cipherlen
-4) {
1385 errmsg
= "containing string was ill-formed";
1392 * Now we break down into RSA versus DSA. In either case we'll
1393 * construct public and private blobs in our own format, and
1394 * end up feeding them to alg->createkey().
1396 blobsize
= cipherlen
+ 256;
1397 blob
= snewn(blobsize
, unsigned char);
1400 struct mpint_pos n
, e
, d
, u
, p
, q
;
1402 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &e
);
1403 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &d
);
1404 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &n
);
1405 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &u
);
1406 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1407 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1409 errmsg
= "key data did not contain six integers";
1415 pos
+= put_string(blob
+pos
, "ssh-rsa", 7);
1416 pos
+= put_mp(blob
+pos
, e
.start
, e
.bytes
);
1417 pos
+= put_mp(blob
+pos
, n
.start
, n
.bytes
);
1419 pos
+= put_string(blob
+pos
, d
.start
, d
.bytes
);
1420 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1421 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1422 pos
+= put_mp(blob
+pos
, u
.start
, u
.bytes
);
1423 privlen
= pos
- publen
;
1424 } else if (type
== DSA
) {
1425 struct mpint_pos p
, q
, g
, x
, y
;
1427 if (GET_32BIT(ciphertext
) != 0) {
1428 errmsg
= "predefined DSA parameters not supported";
1431 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1432 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &g
);
1433 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1434 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &y
);
1435 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &x
);
1437 errmsg
= "key data did not contain five integers";
1443 pos
+= put_string(blob
+pos
, "ssh-dss", 7);
1444 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1445 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1446 pos
+= put_mp(blob
+pos
, g
.start
, g
.bytes
);
1447 pos
+= put_mp(blob
+pos
, y
.start
, y
.bytes
);
1449 pos
+= put_mp(blob
+pos
, x
.start
, x
.bytes
);
1450 privlen
= pos
- publen
;
1454 assert(privlen
> 0); /* should have bombed by now if not */
1456 retkey
= snew(struct ssh2_userkey
);
1458 retkey
->data
= alg
->createkey(blob
, publen
, blob
+publen
, privlen
);
1459 if (!retkey
->data
) {
1461 errmsg
= "unable to create key data structure";
1464 retkey
->comment
= dupstr(key
->comment
);
1466 errmsg
= NULL
; /* no error */
1471 memset(blob
, 0, blobsize
);
1474 memset(key
->keyblob
, 0, key
->keyblob_size
);
1475 sfree(key
->keyblob
);
1476 memset(key
, 0, sizeof(*key
));
1478 if (errmsg_p
) *errmsg_p
= errmsg
;
1482 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
1485 unsigned char *pubblob
, *privblob
;
1486 int publen
, privlen
;
1487 unsigned char *outblob
;
1489 struct mpint_pos numbers
[6];
1490 int nnumbers
, initial_zero
, pos
, lenpos
, i
;
1498 * Fetch the key blobs.
1500 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
1501 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
1505 * Find the sequence of integers to be encoded into the OpenSSH
1506 * key blob, and also decide on the header line.
1508 if (key
->alg
== &ssh_rsa
) {
1510 struct mpint_pos n
, e
, d
, p
, q
, iqmp
;
1512 pos
= 4 + GET_32BIT(pubblob
);
1513 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
1514 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
1516 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
1517 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
1518 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
1519 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
1521 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
1532 type
= "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1533 } else if (key
->alg
== &ssh_dss
) {
1535 struct mpint_pos p
, q
, g
, y
, x
;
1537 pos
= 4 + GET_32BIT(pubblob
);
1538 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
1539 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
1540 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
1541 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
1543 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
1545 assert(y
.start
&& x
.start
); /* can't go wrong */
1555 type
= "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1557 assert(0); /* zoinks! */
1558 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
1562 * Total size of key blob will be somewhere under 512 plus
1563 * combined length of integers. We'll calculate the more
1564 * precise size as we construct the blob.
1567 for (i
= 0; i
< nnumbers
; i
++)
1568 outlen
+= 4 + numbers
[i
].bytes
;
1569 outblob
= snewn(outlen
, unsigned char);
1572 * Create the unencrypted key blob.
1575 PUT_32BIT(outblob
+pos
, SSHCOM_MAGIC_NUMBER
); pos
+= 4;
1576 pos
+= 4; /* length field, fill in later */
1577 pos
+= put_string(outblob
+pos
, type
, strlen(type
));
1579 char *ciphertype
= passphrase ?
"3des-cbc" : "none";
1580 pos
+= put_string(outblob
+pos
, ciphertype
, strlen(ciphertype
));
1582 lenpos
= pos
; /* remember this position */
1583 pos
+= 4; /* encrypted-blob size */
1584 pos
+= 4; /* encrypted-payload size */
1586 PUT_32BIT(outblob
+pos
, 0);
1589 for (i
= 0; i
< nnumbers
; i
++)
1590 pos
+= sshcom_put_mpint(outblob
+pos
,
1591 numbers
[i
].start
, numbers
[i
].bytes
);
1592 /* Now wrap up the encrypted payload. */
1593 PUT_32BIT(outblob
+lenpos
+4, pos
- (lenpos
+8));
1594 /* Pad encrypted blob to a multiple of cipher block size. */
1596 int padding
= -(pos
- (lenpos
+4)) & 7;
1598 outblob
[pos
++] = random_byte();
1600 ciphertext
= (char *)outblob
+lenpos
+4;
1601 cipherlen
= pos
- (lenpos
+4);
1602 assert(!passphrase
|| cipherlen
% 8 == 0);
1603 /* Wrap up the encrypted blob string. */
1604 PUT_32BIT(outblob
+lenpos
, cipherlen
);
1605 /* And finally fill in the total length field. */
1606 PUT_32BIT(outblob
+4, pos
);
1608 assert(pos
< outlen
);
1615 * Derive encryption key from passphrase and iv/salt:
1617 * - let block A equal MD5(passphrase)
1618 * - let block B equal MD5(passphrase || A)
1619 * - block C would be MD5(passphrase || A || B) and so on
1620 * - encryption key is the first N bytes of A || B
1622 struct MD5Context md5c
;
1623 unsigned char keybuf
[32], iv
[8];
1626 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1627 MD5Final(keybuf
, &md5c
);
1630 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1631 MD5Update(&md5c
, keybuf
, 16);
1632 MD5Final(keybuf
+16, &md5c
);
1635 * Now decrypt the key blob.
1637 memset(iv
, 0, sizeof(iv
));
1638 des3_encrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1641 memset(&md5c
, 0, sizeof(md5c
));
1642 memset(keybuf
, 0, sizeof(keybuf
));
1646 * And save it. We'll use Unix line endings just in case it's
1647 * subsequently transferred in binary mode.
1649 fp
= f_open(*filename
, "wb", TRUE
); /* ensure Unix line endings */
1652 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1653 fprintf(fp
, "Comment: \"");
1655 * Comment header is broken with backslash-newline if it goes
1656 * over 70 chars. Although it's surrounded by quotes, it
1657 * _doesn't_ escape backslashes or quotes within the string.
1658 * Don't ask me, I didn't design it.
1661 int slen
= 60; /* starts at 60 due to "Comment: " */
1662 char *c
= key
->comment
;
1663 while ((int)strlen(c
) > slen
) {
1664 fprintf(fp
, "%.*s\\\n", slen
, c
);
1666 slen
= 70; /* allow 70 chars on subsequent lines */
1668 fprintf(fp
, "%s\"\n", c
);
1670 base64_encode(fp
, outblob
, pos
, 70);
1671 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1677 memset(outblob
, 0, outlen
);
1681 memset(privblob
, 0, privlen
);
1685 memset(pubblob
, 0, publen
);