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 const char **errmsg_p
);
30 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
33 int sshcom_encrypted(const Filename
*filename
, char **comment
);
34 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
,
35 const char **errmsg_p
);
36 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
40 * Given a key type, determine whether we know how to import it.
42 int import_possible(int type
)
44 if (type
== SSH_KEYTYPE_OPENSSH
)
46 if (type
== SSH_KEYTYPE_SSHCOM
)
52 * Given a key type, determine what native key type
53 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
56 int import_target_type(int type
)
59 * There are no known foreign SSH1 key formats.
61 return SSH_KEYTYPE_SSH2
;
65 * Determine whether a foreign key is encrypted.
67 int import_encrypted(const Filename
*filename
, int type
, char **comment
)
69 if (type
== SSH_KEYTYPE_OPENSSH
) {
70 /* OpenSSH doesn't do key comments */
71 *comment
= dupstr(filename_to_str(filename
));
72 return openssh_encrypted(filename
);
74 if (type
== SSH_KEYTYPE_SSHCOM
) {
75 return sshcom_encrypted(filename
, comment
);
83 int import_ssh1(const Filename
*filename
, int type
,
84 struct RSAKey
*key
, char *passphrase
, const char **errmsg_p
)
92 struct ssh2_userkey
*import_ssh2(const Filename
*filename
, int type
,
93 char *passphrase
, const char **errmsg_p
)
95 if (type
== SSH_KEYTYPE_OPENSSH
)
96 return openssh_read(filename
, passphrase
, errmsg_p
);
97 if (type
== SSH_KEYTYPE_SSHCOM
)
98 return sshcom_read(filename
, passphrase
, errmsg_p
);
103 * Export an SSH1 key.
105 int export_ssh1(const Filename
*filename
, int type
, struct RSAKey
*key
,
112 * Export an SSH2 key.
114 int export_ssh2(const Filename
*filename
, int type
,
115 struct ssh2_userkey
*key
, char *passphrase
)
117 if (type
== SSH_KEYTYPE_OPENSSH
)
118 return openssh_write(filename
, key
, passphrase
);
119 if (type
== SSH_KEYTYPE_SSHCOM
)
120 return sshcom_write(filename
, key
, passphrase
);
124 /* ----------------------------------------------------------------------
125 * Helper routines. (The base64 ones are defined in sshpubk.c.)
128 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
129 ((c) >= 'a' && (c) <= 'z') || \
130 ((c) >= '0' && (c) <= '9') || \
131 (c) == '+' || (c) == '/' || (c) == '=' \
135 * Read an ASN.1/BER identifier and length pair.
137 * Flags are a combination of the #defines listed below.
139 * Returns -1 if unsuccessful; otherwise returns the number of
140 * bytes used out of the source data.
143 /* ASN.1 tag classes. */
144 #define ASN1_CLASS_UNIVERSAL (0 << 6)
145 #define ASN1_CLASS_APPLICATION (1 << 6)
146 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
147 #define ASN1_CLASS_PRIVATE (3 << 6)
148 #define ASN1_CLASS_MASK (3 << 6)
150 /* Primitive versus constructed bit. */
151 #define ASN1_CONSTRUCTED (1 << 5)
153 static int ber_read_id_len(void *source
, int sourcelen
,
154 int *id
, int *length
, int *flags
)
156 unsigned char *p
= (unsigned char *) source
;
161 *flags
= (*p
& 0xE0);
162 if ((*p
& 0x1F) == 0x1F) {
168 *id
= (*id
<< 7) | (*p
& 0x7F);
186 *length
= (*length
<< 8) | (*p
++);
193 return p
- (unsigned char *) source
;
197 * Write an ASN.1/BER identifier and length pair. Returns the
198 * number of bytes consumed. Assumes dest contains enough space.
199 * Will avoid writing anything if dest is NULL, but still return
200 * amount of space required.
202 static int ber_write_id_len(void *dest
, int id
, int length
, int flags
)
204 unsigned char *d
= (unsigned char *)dest
;
209 * Identifier is one byte.
212 if (d
) *d
++ = id
| flags
;
216 * Identifier is multiple bytes: the first byte is 11111
217 * plus the flags, and subsequent bytes encode the value of
218 * the identifier, 7 bits at a time, with the top bit of
219 * each byte 1 except the last one which is 0.
222 if (d
) *d
++ = 0x1F | flags
;
223 for (n
= 1; (id
>> (7*n
)) > 0; n
++)
224 continue; /* count the bytes */
227 if (d
) *d
++ = (n ?
0x80 : 0) | ((id
>> (7*n
)) & 0x7F);
233 * Length is one byte.
236 if (d
) *d
++ = length
;
240 * Length is multiple bytes. The first is 0x80 plus the
241 * number of subsequent bytes, and the subsequent bytes
242 * encode the actual length.
244 for (n
= 1; (length
>> (8*n
)) > 0; n
++)
245 continue; /* count the bytes */
247 if (d
) *d
++ = 0x80 | n
;
250 if (d
) *d
++ = (length
>> (8*n
)) & 0xFF;
257 static int put_string(void *target
, void *data
, int len
)
259 unsigned char *d
= (unsigned char *)target
;
262 memcpy(d
+4, data
, len
);
266 static int put_mp(void *target
, void *data
, int len
)
268 unsigned char *d
= (unsigned char *)target
;
269 unsigned char *i
= (unsigned char *)data
;
274 memcpy(d
+5, data
, len
);
278 memcpy(d
+4, data
, len
);
283 /* Simple structure to point to an mp-int within a blob. */
284 struct mpint_pos
{ void *start
; int bytes
; };
286 static int ssh2_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
289 unsigned char *d
= (unsigned char *) data
;
293 bytes
= GET_32BIT(d
);
304 return len
; /* ensure further calls fail as well */
307 /* ----------------------------------------------------------------------
308 * Code to read and write OpenSSH private keys.
311 enum { OSSH_DSA
, OSSH_RSA
};
316 unsigned char *keyblob
;
317 int keyblob_len
, keyblob_size
;
320 static struct openssh_key
*load_openssh_key(const Filename
*filename
,
321 const char **errmsg_p
)
323 struct openssh_key
*ret
;
329 int base64_chars
= 0;
331 ret
= snew(struct openssh_key
);
333 ret
->keyblob_len
= ret
->keyblob_size
= 0;
335 memset(ret
->iv
, 0, sizeof(ret
->iv
));
337 fp
= f_open(*filename
, "r");
339 errmsg
= "unable to open key file";
342 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
343 0 != strncmp(buffer
, "-----BEGIN ", 11) ||
344 0 != strcmp(buffer
+strlen(buffer
)-17, "PRIVATE KEY-----\n")) {
345 errmsg
= "file does not begin with OpenSSH key header";
348 if (!strcmp(buffer
, "-----BEGIN RSA PRIVATE KEY-----\n"))
349 ret
->type
= OSSH_RSA
;
350 else if (!strcmp(buffer
, "-----BEGIN DSA PRIVATE KEY-----\n"))
351 ret
->type
= OSSH_DSA
;
353 errmsg
= "unrecognised key type";
359 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
360 errmsg
= "unexpected end of file";
363 if (0 == strncmp(buffer
, "-----END ", 9) &&
364 0 == strcmp(buffer
+strlen(buffer
)-17, "PRIVATE KEY-----\n"))
366 if ((p
= strchr(buffer
, ':')) != NULL
) {
368 errmsg
= "header found in body of key data";
372 while (*p
&& isspace((unsigned char)*p
)) p
++;
373 if (!strcmp(buffer
, "Proc-Type")) {
374 if (p
[0] != '4' || p
[1] != ',') {
375 errmsg
= "Proc-Type is not 4 (only 4 is supported)";
379 if (!strcmp(p
, "ENCRYPTED\n"))
381 } else if (!strcmp(buffer
, "DEK-Info")) {
384 if (strncmp(p
, "DES-EDE3-CBC,", 13)) {
385 errmsg
= "ciphers other than DES-EDE3-CBC not supported";
389 for (i
= 0; i
< 8; i
++) {
390 if (1 != sscanf(p
, "%2x", &j
))
396 errmsg
= "expected 16-digit iv in DEK-Info";
404 while (isbase64(*p
)) {
405 base64_bit
[base64_chars
++] = *p
;
406 if (base64_chars
== 4) {
407 unsigned char out
[3];
412 len
= base64_decode_atom(base64_bit
, out
);
415 errmsg
= "invalid base64 encoding";
419 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
420 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
421 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
425 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
426 ret
->keyblob_len
+= len
;
428 memset(out
, 0, sizeof(out
));
436 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
437 errmsg
= "key body not present";
441 if (ret
->encrypted
&& ret
->keyblob_len
% 8 != 0) {
442 errmsg
= "encrypted key blob is not a multiple of cipher block size";
446 memset(buffer
, 0, sizeof(buffer
));
447 memset(base64_bit
, 0, sizeof(base64_bit
));
448 if (errmsg_p
) *errmsg_p
= NULL
;
452 memset(buffer
, 0, sizeof(buffer
));
453 memset(base64_bit
, 0, sizeof(base64_bit
));
456 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
459 memset(&ret
, 0, sizeof(ret
));
462 if (errmsg_p
) *errmsg_p
= errmsg
;
466 int openssh_encrypted(const Filename
*filename
)
468 struct openssh_key
*key
= load_openssh_key(filename
, NULL
);
473 ret
= key
->encrypted
;
474 memset(key
->keyblob
, 0, key
->keyblob_size
);
476 memset(&key
, 0, sizeof(key
));
481 struct ssh2_userkey
*openssh_read(const Filename
*filename
, char *passphrase
,
482 const char **errmsg_p
)
484 struct openssh_key
*key
= load_openssh_key(filename
, errmsg_p
);
485 struct ssh2_userkey
*retkey
;
487 int ret
, id
, len
, flags
;
489 struct ssh2_userkey
*retval
= NULL
;
492 int blobsize
= 0, blobptr
, privptr
;
501 if (key
->encrypted
) {
503 * Derive encryption key from passphrase and iv/salt:
505 * - let block A equal MD5(passphrase || iv)
506 * - let block B equal MD5(A || passphrase || iv)
507 * - block C would be MD5(B || passphrase || iv) and so on
508 * - encryption key is the first N bytes of A || B
510 struct MD5Context md5c
;
511 unsigned char keybuf
[32];
514 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
515 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
516 MD5Final(keybuf
, &md5c
);
519 MD5Update(&md5c
, keybuf
, 16);
520 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
521 MD5Update(&md5c
, (unsigned char *)key
->iv
, 8);
522 MD5Final(keybuf
+16, &md5c
);
525 * Now decrypt the key blob.
527 des3_decrypt_pubkey_ossh(keybuf
, (unsigned char *)key
->iv
,
528 key
->keyblob
, key
->keyblob_len
);
530 memset(&md5c
, 0, sizeof(md5c
));
531 memset(keybuf
, 0, sizeof(keybuf
));
535 * Now we have a decrypted key blob, which contains an ASN.1
536 * encoded private key. We must now untangle the ASN.1.
538 * We expect the whole key blob to be formatted as a SEQUENCE
539 * (0x30 followed by a length code indicating that the rest of
540 * the blob is part of the sequence). Within that SEQUENCE we
541 * expect to see a bunch of INTEGERs. What those integers mean
542 * depends on the key type:
544 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
545 * dmp1, dmq1, iqmp in that order. (The last three are d mod
546 * (p-1), d mod (q-1), inverse of q mod p respectively.)
548 * - For DSA, we expect them to be 0, p, q, g, y, x in that
554 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
555 ret
= ber_read_id_len(p
, key
->keyblob_len
, &id
, &len
, &flags
);
557 if (ret
< 0 || id
!= 16) {
558 errmsg
= "ASN.1 decoding failure";
559 retval
= SSH2_WRONG_PASSPHRASE
;
563 /* Expect a load of INTEGERs. */
564 if (key
->type
== OSSH_RSA
)
566 else if (key
->type
== OSSH_DSA
)
569 num_integers
= 0; /* placate compiler warnings */
572 * Space to create key blob in.
574 blobsize
= 256+key
->keyblob_len
;
575 blob
= snewn(blobsize
, unsigned char);
577 if (key
->type
== OSSH_DSA
)
578 memcpy(blob
+4, "ssh-dss", 7);
579 else if (key
->type
== OSSH_RSA
)
580 memcpy(blob
+4, "ssh-rsa", 7);
584 for (i
= 0; i
< num_integers
; i
++) {
585 ret
= ber_read_id_len(p
, key
->keyblob
+key
->keyblob_len
-p
,
588 if (ret
< 0 || id
!= 2 ||
589 key
->keyblob
+key
->keyblob_len
-p
< len
) {
590 errmsg
= "ASN.1 decoding failure";
591 retval
= SSH2_WRONG_PASSPHRASE
;
597 * The first integer should be zero always (I think
598 * this is some sort of version indication).
600 if (len
!= 1 || p
[0] != 0) {
601 errmsg
= "version number mismatch";
604 } else if (key
->type
== OSSH_RSA
) {
606 * Integers 1 and 2 go into the public blob but in the
607 * opposite order; integers 3, 4, 5 and 8 go into the
608 * private blob. The other two (6 and 7) are ignored.
611 /* Save the details for after we deal with number 2. */
614 } else if (i
!= 6 && i
!= 7) {
615 PUT_32BIT(blob
+blobptr
, len
);
616 memcpy(blob
+blobptr
+4, p
, len
);
619 PUT_32BIT(blob
+blobptr
, modlen
);
620 memcpy(blob
+blobptr
+4, modptr
, modlen
);
625 } else if (key
->type
== OSSH_DSA
) {
627 * Integers 1-4 go into the public blob; integer 5 goes
628 * into the private blob.
630 PUT_32BIT(blob
+blobptr
, len
);
631 memcpy(blob
+blobptr
+4, p
, len
);
637 /* Skip past the number. */
642 * Now put together the actual key. Simplest way to do this is
643 * to assemble our own key blobs and feed them to the createkey
644 * functions; this is a bit faffy but it does mean we get all
645 * the sanity checks for free.
647 assert(privptr
> 0); /* should have bombed by now if not */
648 retkey
= snew(struct ssh2_userkey
);
649 retkey
->alg
= (key
->type
== OSSH_RSA ?
&ssh_rsa
: &ssh_dss
);
650 retkey
->data
= retkey
->alg
->createkey(blob
, privptr
,
651 blob
+privptr
, blobptr
-privptr
);
654 errmsg
= "unable to create key data structure";
658 retkey
->comment
= dupstr("imported-openssh-key");
659 errmsg
= NULL
; /* no error */
664 memset(blob
, 0, blobsize
);
667 memset(key
->keyblob
, 0, key
->keyblob_size
);
669 memset(&key
, 0, sizeof(key
));
671 if (errmsg_p
) *errmsg_p
= errmsg
;
675 int openssh_write(const Filename
*filename
, struct ssh2_userkey
*key
,
678 unsigned char *pubblob
, *privblob
, *spareblob
;
679 int publen
, privlen
, sparelen
= 0;
680 unsigned char *outblob
;
682 struct mpint_pos numbers
[9];
683 int nnumbers
, pos
, len
, seqlen
, i
;
684 char *header
, *footer
;
691 * Fetch the key blobs.
693 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
694 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
695 spareblob
= outblob
= NULL
;
698 * Find the sequence of integers to be encoded into the OpenSSH
699 * key blob, and also decide on the header line.
701 if (key
->alg
== &ssh_rsa
) {
703 struct mpint_pos n
, e
, d
, p
, q
, iqmp
, dmp1
, dmq1
;
704 Bignum bd
, bp
, bq
, bdmp1
, bdmq1
;
706 pos
= 4 + GET_32BIT(pubblob
);
707 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
708 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
710 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
711 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
712 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
713 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
715 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
717 /* We also need d mod (p-1) and d mod (q-1). */
718 bd
= bignum_from_bytes(d
.start
, d
.bytes
);
719 bp
= bignum_from_bytes(p
.start
, p
.bytes
);
720 bq
= bignum_from_bytes(q
.start
, q
.bytes
);
723 bdmp1
= bigmod(bd
, bp
);
724 bdmq1
= bigmod(bd
, bq
);
729 dmp1
.bytes
= (bignum_bitcount(bdmp1
)+8)/8;
730 dmq1
.bytes
= (bignum_bitcount(bdmq1
)+8)/8;
731 sparelen
= dmp1
.bytes
+ dmq1
.bytes
;
732 spareblob
= snewn(sparelen
, unsigned char);
733 dmp1
.start
= spareblob
;
734 dmq1
.start
= spareblob
+ dmp1
.bytes
;
735 for (i
= 0; i
< dmp1
.bytes
; i
++)
736 spareblob
[i
] = bignum_byte(bdmp1
, dmp1
.bytes
-1 - i
);
737 for (i
= 0; i
< dmq1
.bytes
; i
++)
738 spareblob
[i
+dmp1
.bytes
] = bignum_byte(bdmq1
, dmq1
.bytes
-1 - i
);
742 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
753 header
= "-----BEGIN RSA PRIVATE KEY-----\n";
754 footer
= "-----END RSA PRIVATE KEY-----\n";
755 } else if (key
->alg
== &ssh_dss
) {
757 struct mpint_pos p
, q
, g
, y
, x
;
759 pos
= 4 + GET_32BIT(pubblob
);
760 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
761 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
762 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
763 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
765 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
767 assert(y
.start
&& x
.start
); /* can't go wrong */
769 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
777 header
= "-----BEGIN DSA PRIVATE KEY-----\n";
778 footer
= "-----END DSA PRIVATE KEY-----\n";
780 assert(0); /* zoinks! */
784 * Now count up the total size of the ASN.1 encoded integers,
785 * so as to determine the length of the containing SEQUENCE.
788 for (i
= 0; i
< nnumbers
; i
++) {
789 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
790 len
+= numbers
[i
].bytes
;
793 /* Now add on the SEQUENCE header. */
794 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
795 /* Round up to the cipher block size, ensuring we have at least one
796 * byte of padding (see below). */
799 outlen
= (outlen
+8) &~ 7;
802 * Now we know how big outblob needs to be. Allocate it.
804 outblob
= snewn(outlen
, unsigned char);
807 * And write the data into it.
810 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
811 for (i
= 0; i
< nnumbers
; i
++) {
812 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
813 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
814 pos
+= numbers
[i
].bytes
;
818 * Padding on OpenSSH keys is deterministic. The number of
819 * padding bytes is always more than zero, and always at most
820 * the cipher block length. The value of each padding byte is
821 * equal to the number of padding bytes. So a plaintext that's
822 * an exact multiple of the block size will be padded with 08
823 * 08 08 08 08 08 08 08 (assuming a 64-bit block cipher); a
824 * plaintext one byte less than a multiple of the block size
825 * will be padded with just 01.
827 * This enables the OpenSSL key decryption function to strip
828 * off the padding algorithmically and return the unpadded
829 * plaintext to the next layer: it looks at the final byte, and
830 * then expects to find that many bytes at the end of the data
831 * with the same value. Those are all removed and the rest is
835 while (pos
< outlen
) {
836 outblob
[pos
++] = outlen
- len
;
844 * Invent an iv. Then derive encryption key from passphrase
847 * - let block A equal MD5(passphrase || iv)
848 * - let block B equal MD5(A || passphrase || iv)
849 * - block C would be MD5(B || passphrase || iv) and so on
850 * - encryption key is the first N bytes of A || B
852 struct MD5Context md5c
;
853 unsigned char keybuf
[32];
855 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
858 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
859 MD5Update(&md5c
, iv
, 8);
860 MD5Final(keybuf
, &md5c
);
863 MD5Update(&md5c
, keybuf
, 16);
864 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
865 MD5Update(&md5c
, iv
, 8);
866 MD5Final(keybuf
+16, &md5c
);
869 * Now encrypt the key blob.
871 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
873 memset(&md5c
, 0, sizeof(md5c
));
874 memset(keybuf
, 0, sizeof(keybuf
));
878 * And save it. We'll use Unix line endings just in case it's
879 * subsequently transferred in binary mode.
881 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
886 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
887 for (i
= 0; i
< 8; i
++)
888 fprintf(fp
, "%02X", iv
[i
]);
891 base64_encode(fp
, outblob
, outlen
, 64);
898 memset(outblob
, 0, outlen
);
902 memset(spareblob
, 0, sparelen
);
906 memset(privblob
, 0, privlen
);
910 memset(pubblob
, 0, publen
);
916 /* ----------------------------------------------------------------------
917 * Code to read ssh.com private keys.
921 * The format of the base64 blob is largely ssh2-packet-formatted,
922 * except that mpints are a bit different: they're more like the
923 * old ssh1 mpint. You have a 32-bit bit count N, followed by
924 * (N+7)/8 bytes of data.
926 * So. The blob contains:
928 * - uint32 0x3f6ff9eb (magic number)
929 * - uint32 size (total blob size)
930 * - string key-type (see below)
931 * - string cipher-type (tells you if key is encrypted)
932 * - string encrypted-blob
934 * (The first size field includes the size field itself and the
935 * magic number before it. All other size fields are ordinary ssh2
936 * strings, so the size field indicates how much data is to
939 * The encrypted blob, once decrypted, contains a single string
940 * which in turn contains the payload. (This allows padding to be
941 * added after that string while still making it clear where the
942 * real payload ends. Also it probably makes for a reasonable
945 * The payload blob, for an RSA key, contains:
948 * - mpint n (yes, the public and private stuff is intermixed)
949 * - mpint u (presumably inverse of p mod q)
950 * - mpint p (p is the smaller prime)
951 * - mpint q (q is the larger)
953 * For a DSA key, the payload blob contains:
961 * Alternatively, if the parameters are `predefined', that
962 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
963 * containing some predefined parameter specification. *shudder*,
964 * but I doubt we'll encounter this in real life.
966 * The key type strings are ghastly. The RSA key I looked at had a
969 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
971 * and the DSA key wasn't much better:
973 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
975 * It isn't clear that these will always be the same. I think it
976 * might be wise just to look at the `if-modn{sign{rsa' and
977 * `dl-modp{sign{dsa' prefixes.
979 * Finally, the encryption. The cipher-type string appears to be
980 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
981 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
982 * from the passphrase by means of yet another hashing faff:
984 * - first 16 bytes are MD5(passphrase)
985 * - next 16 bytes are MD5(passphrase || first 16 bytes)
986 * - if there were more, they'd be MD5(passphrase || first 32),
990 #define SSHCOM_MAGIC_NUMBER 0x3f6ff9eb
993 char comment
[256]; /* allowing any length is overkill */
994 unsigned char *keyblob
;
995 int keyblob_len
, keyblob_size
;
998 static struct sshcom_key
*load_sshcom_key(const Filename
*filename
,
999 const char **errmsg_p
)
1001 struct sshcom_key
*ret
;
1008 int base64_chars
= 0;
1010 ret
= snew(struct sshcom_key
);
1011 ret
->comment
[0] = '\0';
1012 ret
->keyblob
= NULL
;
1013 ret
->keyblob_len
= ret
->keyblob_size
= 0;
1015 fp
= f_open(*filename
, "r");
1017 errmsg
= "unable to open key file";
1020 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
1021 0 != strcmp(buffer
, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
1022 errmsg
= "file does not begin with ssh.com key header";
1028 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
1029 errmsg
= "unexpected end of file";
1032 if (!strcmp(buffer
, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
1034 if ((p
= strchr(buffer
, ':')) != NULL
) {
1036 errmsg
= "header found in body of key data";
1040 while (*p
&& isspace((unsigned char)*p
)) p
++;
1042 * Header lines can end in a trailing backslash for
1045 while ((len
= strlen(p
)) > (int)(sizeof(buffer
) - (p
-buffer
) -1) ||
1046 p
[len
-1] != '\n' || p
[len
-2] == '\\') {
1047 if (len
> (int)((p
-buffer
) + sizeof(buffer
)-2)) {
1048 errmsg
= "header line too long to deal with";
1051 if (!fgets(p
+len
-2, sizeof(buffer
)-(p
-buffer
)-(len
-2), fp
)) {
1052 errmsg
= "unexpected end of file";
1056 p
[strcspn(p
, "\n")] = '\0';
1057 if (!strcmp(buffer
, "Comment")) {
1058 /* Strip quotes in comment if present. */
1059 if (p
[0] == '"' && p
[strlen(p
)-1] == '"') {
1061 p
[strlen(p
)-1] = '\0';
1063 strncpy(ret
->comment
, p
, sizeof(ret
->comment
));
1064 ret
->comment
[sizeof(ret
->comment
)-1] = '\0';
1070 while (isbase64(*p
)) {
1071 base64_bit
[base64_chars
++] = *p
;
1072 if (base64_chars
== 4) {
1073 unsigned char out
[3];
1077 len
= base64_decode_atom(base64_bit
, out
);
1080 errmsg
= "invalid base64 encoding";
1084 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
1085 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
1086 ret
->keyblob
= sresize(ret
->keyblob
, ret
->keyblob_size
,
1090 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
1091 ret
->keyblob_len
+= len
;
1099 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
1100 errmsg
= "key body not present";
1104 if (errmsg_p
) *errmsg_p
= NULL
;
1110 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1111 sfree(ret
->keyblob
);
1113 memset(&ret
, 0, sizeof(ret
));
1116 if (errmsg_p
) *errmsg_p
= errmsg
;
1120 int sshcom_encrypted(const Filename
*filename
, char **comment
)
1122 struct sshcom_key
*key
= load_sshcom_key(filename
, NULL
);
1123 int pos
, len
, answer
;
1130 * Check magic number.
1132 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb)
1133 return 0; /* key is invalid */
1136 * Find the cipher-type string.
1140 if (key
->keyblob_len
< pos
+4)
1141 goto done
; /* key is far too short */
1142 pos
+= 4 + GET_32BIT(key
->keyblob
+ pos
); /* skip key type */
1143 if (key
->keyblob_len
< pos
+4)
1144 goto done
; /* key is far too short */
1145 len
= GET_32BIT(key
->keyblob
+ pos
); /* find cipher-type length */
1146 if (key
->keyblob_len
< pos
+4+len
)
1147 goto done
; /* cipher type string is incomplete */
1148 if (len
!= 4 || 0 != memcmp(key
->keyblob
+ pos
+ 4, "none", 4))
1152 *comment
= dupstr(key
->comment
);
1153 memset(key
->keyblob
, 0, key
->keyblob_size
);
1154 sfree(key
->keyblob
);
1155 memset(&key
, 0, sizeof(key
));
1160 static int sshcom_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
1164 unsigned char *d
= (unsigned char *) data
;
1168 bits
= GET_32BIT(d
);
1170 bytes
= (bits
+ 7) / 8;
1181 return len
; /* ensure further calls fail as well */
1184 static int sshcom_put_mpint(void *target
, void *data
, int len
)
1186 unsigned char *d
= (unsigned char *)target
;
1187 unsigned char *i
= (unsigned char *)data
;
1188 int bits
= len
* 8 - 1;
1191 if (*i
& (1 << (bits
& 7)))
1197 PUT_32BIT(d
, bits
+1);
1198 memcpy(d
+4, i
, len
);
1202 struct ssh2_userkey
*sshcom_read(const Filename
*filename
, char *passphrase
,
1203 const char **errmsg_p
)
1205 struct sshcom_key
*key
= load_sshcom_key(filename
, errmsg_p
);
1208 const char prefix_rsa
[] = "if-modn{sign{rsa";
1209 const char prefix_dsa
[] = "dl-modp{sign{dsa";
1210 enum { RSA
, DSA
} type
;
1214 struct ssh2_userkey
*ret
= NULL
, *retkey
;
1215 const struct ssh_signkey
*alg
;
1216 unsigned char *blob
= NULL
;
1217 int blobsize
= 0, publen
, privlen
;
1223 * Check magic number.
1225 if (GET_32BIT(key
->keyblob
) != SSHCOM_MAGIC_NUMBER
) {
1226 errmsg
= "key does not begin with magic number";
1231 * Determine the key type.
1234 if (key
->keyblob_len
< pos
+4 ||
1235 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1236 errmsg
= "key blob does not contain a key type string";
1239 if (len
> sizeof(prefix_rsa
) - 1 &&
1240 !memcmp(key
->keyblob
+pos
+4, prefix_rsa
, sizeof(prefix_rsa
) - 1)) {
1242 } else if (len
> sizeof(prefix_dsa
) - 1 &&
1243 !memcmp(key
->keyblob
+pos
+4, prefix_dsa
, sizeof(prefix_dsa
) - 1)) {
1246 errmsg
= "key is of unknown type";
1252 * Determine the cipher type.
1254 if (key
->keyblob_len
< pos
+4 ||
1255 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1256 errmsg
= "key blob does not contain a cipher type string";
1259 if (len
== 4 && !memcmp(key
->keyblob
+pos
+4, "none", 4))
1261 else if (len
== 8 && !memcmp(key
->keyblob
+pos
+4, "3des-cbc", 8))
1264 errmsg
= "key encryption is of unknown type";
1270 * Get hold of the encrypted part of the key.
1272 if (key
->keyblob_len
< pos
+4 ||
1273 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1274 errmsg
= "key blob does not contain actual key data";
1277 ciphertext
= (char *)key
->keyblob
+ pos
+ 4;
1279 if (cipherlen
== 0) {
1280 errmsg
= "length of key data is zero";
1285 * Decrypt it if necessary.
1289 * Derive encryption key from passphrase and iv/salt:
1291 * - let block A equal MD5(passphrase)
1292 * - let block B equal MD5(passphrase || A)
1293 * - block C would be MD5(passphrase || A || B) and so on
1294 * - encryption key is the first N bytes of A || B
1296 struct MD5Context md5c
;
1297 unsigned char keybuf
[32], iv
[8];
1299 if (cipherlen
% 8 != 0) {
1300 errmsg
= "encrypted part of key is not a multiple of cipher block"
1306 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1307 MD5Final(keybuf
, &md5c
);
1310 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1311 MD5Update(&md5c
, keybuf
, 16);
1312 MD5Final(keybuf
+16, &md5c
);
1315 * Now decrypt the key blob.
1317 memset(iv
, 0, sizeof(iv
));
1318 des3_decrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1321 memset(&md5c
, 0, sizeof(md5c
));
1322 memset(keybuf
, 0, sizeof(keybuf
));
1325 * Hereafter we return WRONG_PASSPHRASE for any parsing
1326 * error. (But only if we've just tried to decrypt it!
1327 * Returning WRONG_PASSPHRASE for an unencrypted key is
1331 ret
= SSH2_WRONG_PASSPHRASE
;
1335 * Strip away the containing string to get to the real meat.
1337 len
= GET_32BIT(ciphertext
);
1338 if (len
< 0 || len
> cipherlen
-4) {
1339 errmsg
= "containing string was ill-formed";
1346 * Now we break down into RSA versus DSA. In either case we'll
1347 * construct public and private blobs in our own format, and
1348 * end up feeding them to alg->createkey().
1350 blobsize
= cipherlen
+ 256;
1351 blob
= snewn(blobsize
, unsigned char);
1354 struct mpint_pos n
, e
, d
, u
, p
, q
;
1356 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &e
);
1357 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &d
);
1358 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &n
);
1359 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &u
);
1360 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1361 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1363 errmsg
= "key data did not contain six integers";
1369 pos
+= put_string(blob
+pos
, "ssh-rsa", 7);
1370 pos
+= put_mp(blob
+pos
, e
.start
, e
.bytes
);
1371 pos
+= put_mp(blob
+pos
, n
.start
, n
.bytes
);
1373 pos
+= put_string(blob
+pos
, d
.start
, d
.bytes
);
1374 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1375 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1376 pos
+= put_mp(blob
+pos
, u
.start
, u
.bytes
);
1377 privlen
= pos
- publen
;
1378 } else if (type
== DSA
) {
1379 struct mpint_pos p
, q
, g
, x
, y
;
1381 if (GET_32BIT(ciphertext
) != 0) {
1382 errmsg
= "predefined DSA parameters not supported";
1385 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1386 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &g
);
1387 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1388 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &y
);
1389 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &x
);
1391 errmsg
= "key data did not contain five integers";
1397 pos
+= put_string(blob
+pos
, "ssh-dss", 7);
1398 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1399 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1400 pos
+= put_mp(blob
+pos
, g
.start
, g
.bytes
);
1401 pos
+= put_mp(blob
+pos
, y
.start
, y
.bytes
);
1403 pos
+= put_mp(blob
+pos
, x
.start
, x
.bytes
);
1404 privlen
= pos
- publen
;
1408 assert(privlen
> 0); /* should have bombed by now if not */
1410 retkey
= snew(struct ssh2_userkey
);
1412 retkey
->data
= alg
->createkey(blob
, publen
, blob
+publen
, privlen
);
1413 if (!retkey
->data
) {
1415 errmsg
= "unable to create key data structure";
1418 retkey
->comment
= dupstr(key
->comment
);
1420 errmsg
= NULL
; /* no error */
1425 memset(blob
, 0, blobsize
);
1428 memset(key
->keyblob
, 0, key
->keyblob_size
);
1429 sfree(key
->keyblob
);
1430 memset(&key
, 0, sizeof(key
));
1432 if (errmsg_p
) *errmsg_p
= errmsg
;
1436 int sshcom_write(const Filename
*filename
, struct ssh2_userkey
*key
,
1439 unsigned char *pubblob
, *privblob
;
1440 int publen
, privlen
;
1441 unsigned char *outblob
;
1443 struct mpint_pos numbers
[6];
1444 int nnumbers
, initial_zero
, pos
, lenpos
, i
;
1452 * Fetch the key blobs.
1454 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
1455 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
1459 * Find the sequence of integers to be encoded into the OpenSSH
1460 * key blob, and also decide on the header line.
1462 if (key
->alg
== &ssh_rsa
) {
1464 struct mpint_pos n
, e
, d
, p
, q
, iqmp
;
1466 pos
= 4 + GET_32BIT(pubblob
);
1467 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
1468 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
1470 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
1471 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
1472 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
1473 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
1475 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
1486 type
= "if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}";
1487 } else if (key
->alg
== &ssh_dss
) {
1489 struct mpint_pos p
, q
, g
, y
, x
;
1491 pos
= 4 + GET_32BIT(pubblob
);
1492 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
1493 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
1494 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
1495 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
1497 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
1499 assert(y
.start
&& x
.start
); /* can't go wrong */
1509 type
= "dl-modp{sign{dsa-nist-sha1},dh{plain}}";
1511 assert(0); /* zoinks! */
1515 * Total size of key blob will be somewhere under 512 plus
1516 * combined length of integers. We'll calculate the more
1517 * precise size as we construct the blob.
1520 for (i
= 0; i
< nnumbers
; i
++)
1521 outlen
+= 4 + numbers
[i
].bytes
;
1522 outblob
= snewn(outlen
, unsigned char);
1525 * Create the unencrypted key blob.
1528 PUT_32BIT(outblob
+pos
, SSHCOM_MAGIC_NUMBER
); pos
+= 4;
1529 pos
+= 4; /* length field, fill in later */
1530 pos
+= put_string(outblob
+pos
, type
, strlen(type
));
1532 char *ciphertype
= passphrase ?
"3des-cbc" : "none";
1533 pos
+= put_string(outblob
+pos
, ciphertype
, strlen(ciphertype
));
1535 lenpos
= pos
; /* remember this position */
1536 pos
+= 4; /* encrypted-blob size */
1537 pos
+= 4; /* encrypted-payload size */
1539 PUT_32BIT(outblob
+pos
, 0);
1542 for (i
= 0; i
< nnumbers
; i
++)
1543 pos
+= sshcom_put_mpint(outblob
+pos
,
1544 numbers
[i
].start
, numbers
[i
].bytes
);
1545 /* Now wrap up the encrypted payload. */
1546 PUT_32BIT(outblob
+lenpos
+4, pos
- (lenpos
+8));
1547 /* Pad encrypted blob to a multiple of cipher block size. */
1549 int padding
= -(pos
- (lenpos
+4)) & 7;
1551 outblob
[pos
++] = random_byte();
1553 ciphertext
= (char *)outblob
+lenpos
+4;
1554 cipherlen
= pos
- (lenpos
+4);
1555 assert(!passphrase
|| cipherlen
% 8 == 0);
1556 /* Wrap up the encrypted blob string. */
1557 PUT_32BIT(outblob
+lenpos
, cipherlen
);
1558 /* And finally fill in the total length field. */
1559 PUT_32BIT(outblob
+4, pos
);
1561 assert(pos
< outlen
);
1568 * Derive encryption key from passphrase and iv/salt:
1570 * - let block A equal MD5(passphrase)
1571 * - let block B equal MD5(passphrase || A)
1572 * - block C would be MD5(passphrase || A || B) and so on
1573 * - encryption key is the first N bytes of A || B
1575 struct MD5Context md5c
;
1576 unsigned char keybuf
[32], iv
[8];
1579 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1580 MD5Final(keybuf
, &md5c
);
1583 MD5Update(&md5c
, (unsigned char *)passphrase
, strlen(passphrase
));
1584 MD5Update(&md5c
, keybuf
, 16);
1585 MD5Final(keybuf
+16, &md5c
);
1588 * Now decrypt the key blob.
1590 memset(iv
, 0, sizeof(iv
));
1591 des3_encrypt_pubkey_ossh(keybuf
, iv
, (unsigned char *)ciphertext
,
1594 memset(&md5c
, 0, sizeof(md5c
));
1595 memset(keybuf
, 0, sizeof(keybuf
));
1599 * And save it. We'll use Unix line endings just in case it's
1600 * subsequently transferred in binary mode.
1602 fp
= f_open(*filename
, "wb"); /* ensure Unix line endings */
1605 fputs("---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1606 fprintf(fp
, "Comment: \"");
1608 * Comment header is broken with backslash-newline if it goes
1609 * over 70 chars. Although it's surrounded by quotes, it
1610 * _doesn't_ escape backslashes or quotes within the string.
1611 * Don't ask me, I didn't design it.
1614 int slen
= 60; /* starts at 60 due to "Comment: " */
1615 char *c
= key
->comment
;
1616 while ((int)strlen(c
) > slen
) {
1617 fprintf(fp
, "%.*s\\\n", slen
, c
);
1619 slen
= 70; /* allow 70 chars on subsequent lines */
1621 fprintf(fp
, "%s\"\n", c
);
1623 base64_encode(fp
, outblob
, pos
, 70);
1624 fputs("---- END SSH2 ENCRYPTED PRIVATE KEY ----\n", fp
);
1630 memset(outblob
, 0, outlen
);
1634 memset(privblob
, 0, privlen
);
1638 memset(pubblob
, 0, publen
);