2 * Code for PuTTY to import and export private key files in other
3 * SSH clients' formats.
14 #define PUT_32BIT(cp, value) do { \
16 (cp)[2] = (value) >> 8; \
17 (cp)[1] = (value) >> 16; \
18 (cp)[0] = (value) >> 24; } while (0)
20 #define GET_32BIT(cp) \
21 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
22 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
23 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
24 ((unsigned long)(unsigned char)(cp)[3]))
26 int openssh_encrypted(char *filename
);
27 struct ssh2_userkey
*openssh_read(char *filename
, char *passphrase
);
28 int openssh_write(char *filename
, struct ssh2_userkey
*key
, char *passphrase
);
30 int sshcom_encrypted(char *filename
, char **comment
);
31 struct ssh2_userkey
*sshcom_read(char *filename
, char *passphrase
);
34 * Given a key type, determine whether we know how to import it.
36 int import_possible(int type
)
38 if (type
== SSH_KEYTYPE_OPENSSH
)
40 if (type
== SSH_KEYTYPE_SSHCOM
)
46 * Given a key type, determine what native key type
47 * (SSH_KEYTYPE_SSH1 or SSH_KEYTYPE_SSH2) it will come out as once
50 int import_target_type(int type
)
53 * There are no known foreign SSH1 key formats.
55 return SSH_KEYTYPE_SSH2
;
59 * Determine whether a foreign key is encrypted.
61 int import_encrypted(char *filename
, int type
, char **comment
)
63 if (type
== SSH_KEYTYPE_OPENSSH
) {
64 *comment
= filename
; /* OpenSSH doesn't do key comments */
65 return openssh_encrypted(filename
);
67 if (type
== SSH_KEYTYPE_SSHCOM
) {
68 return sshcom_encrypted(filename
, comment
);
76 int import_ssh1(char *filename
, int type
, struct RSAKey
*key
, char *passphrase
)
84 struct ssh2_userkey
*import_ssh2(char *filename
, int type
, char *passphrase
)
86 if (type
== SSH_KEYTYPE_OPENSSH
)
87 return openssh_read(filename
, passphrase
);
88 if (type
== SSH_KEYTYPE_SSHCOM
)
89 return sshcom_read(filename
, passphrase
);
96 int export_ssh1(char *filename
, int type
, struct RSAKey
*key
, char *passphrase
)
102 * Export an SSH2 key.
104 int export_ssh2(char *filename
, int type
,
105 struct ssh2_userkey
*key
, char *passphrase
)
107 if (type
== SSH_KEYTYPE_OPENSSH
)
108 return openssh_write(filename
, key
, passphrase
);
110 if (type
== SSH_KEYTYPE_SSHCOM
)
111 return sshcom_write(filename
, key
, passphrase
);
116 /* ----------------------------------------------------------------------
117 * Helper routines. (The base64 ones are defined in sshpubk.c.)
120 #define isbase64(c) ( ((c) >= 'A' && (c) <= 'Z') || \
121 ((c) >= 'a' && (c) <= 'z') || \
122 ((c) >= '0' && (c) <= '9') || \
123 (c) == '+' || (c) == '/' || (c) == '=' \
126 extern int base64_decode_atom(char *atom
, unsigned char *out
);
127 extern int base64_lines(int datalen
);
128 extern void base64_encode_atom(unsigned char *data
, int n
, char *out
);
129 extern void base64_encode(FILE *fp
, unsigned char *data
, int datalen
);
132 * Read an ASN.1/BER identifier and length pair.
134 * Flags are a combination of the #defines listed below.
136 * Returns -1 if unsuccessful; otherwise returns the number of
137 * bytes used out of the source data.
140 /* ASN.1 tag classes. */
141 #define ASN1_CLASS_UNIVERSAL (0 << 6)
142 #define ASN1_CLASS_APPLICATION (1 << 6)
143 #define ASN1_CLASS_CONTEXT_SPECIFIC (2 << 6)
144 #define ASN1_CLASS_PRIVATE (3 << 6)
145 #define ASN1_CLASS_MASK (3 << 6)
147 /* Primitive versus constructed bit. */
148 #define ASN1_CONSTRUCTED (1 << 5)
150 int ber_read_id_len(void *source
, int sourcelen
,
151 int *id
, int *length
, int *flags
)
153 unsigned char *p
= (unsigned char *) source
;
158 *flags
= (*p
& 0xE0);
159 if ((*p
& 0x1F) == 0x1F) {
162 *id
= (*id
<< 7) | (*p
& 0x7F);
167 *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 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 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 struct openssh_key
*load_openssh_key(char *filename
)
320 struct openssh_key
*ret
;
326 int base64_chars
= 0;
328 ret
= smalloc(sizeof(*ret
));
330 ret
->keyblob_len
= ret
->keyblob_size
= 0;
332 memset(ret
->iv
, 0, sizeof(ret
->iv
));
334 fp
= fopen(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
= srealloc(ret
->keyblob
, ret
->keyblob_size
);
421 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
422 ret
->keyblob_len
+= len
;
424 memset(out
, 0, sizeof(out
));
432 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
433 errmsg
= "Key body not present";
437 if (ret
->encrypted
&& ret
->keyblob_len
% 8 != 0) {
438 errmsg
= "Encrypted key blob is not a multiple of cipher block size";
442 memset(buffer
, 0, sizeof(buffer
));
443 memset(base64_bit
, 0, sizeof(base64_bit
));
447 memset(buffer
, 0, sizeof(buffer
));
448 memset(base64_bit
, 0, sizeof(base64_bit
));
451 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
454 memset(&ret
, 0, sizeof(ret
));
460 int openssh_encrypted(char *filename
)
462 struct openssh_key
*key
= load_openssh_key(filename
);
467 ret
= key
->encrypted
;
468 memset(key
->keyblob
, 0, key
->keyblob_size
);
470 memset(&key
, 0, sizeof(key
));
475 struct ssh2_userkey
*openssh_read(char *filename
, char *passphrase
)
477 struct openssh_key
*key
= load_openssh_key(filename
);
478 struct ssh2_userkey
*retkey
;
480 int ret
, id
, len
, flags
;
482 struct ssh2_userkey
*retval
= NULL
;
485 int blobsize
, blobptr
, privptr
;
492 if (key
->encrypted
) {
494 * Derive encryption key from passphrase and iv/salt:
496 * - let block A equal MD5(passphrase || iv)
497 * - let block B equal MD5(A || passphrase || iv)
498 * - block C would be MD5(B || passphrase || iv) and so on
499 * - encryption key is the first N bytes of A || B
501 struct MD5Context md5c
;
502 unsigned char keybuf
[32];
505 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
506 MD5Update(&md5c
, key
->iv
, 8);
507 MD5Final(keybuf
, &md5c
);
510 MD5Update(&md5c
, keybuf
, 16);
511 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
512 MD5Update(&md5c
, key
->iv
, 8);
513 MD5Final(keybuf
+16, &md5c
);
516 * Now decrypt the key blob.
518 des3_decrypt_pubkey_ossh(keybuf
, key
->iv
,
519 key
->keyblob
, key
->keyblob_len
);
521 memset(&md5c
, 0, sizeof(md5c
));
522 memset(keybuf
, 0, sizeof(keybuf
));
526 * Now we have a decrypted key blob, which contains an ASN.1
527 * encoded private key. We must now untangle the ASN.1.
529 * We expect the whole key blob to be formatted as a SEQUENCE
530 * (0x30 followed by a length code indicating that the rest of
531 * the blob is part of the sequence). Within that SEQUENCE we
532 * expect to see a bunch of INTEGERs. What those integers mean
533 * depends on the key type:
535 * - For RSA, we expect the integers to be 0, n, e, d, p, q,
536 * dmp1, dmq1, iqmp in that order. (The last three are d mod
537 * (p-1), d mod (q-1), inverse of q mod p respectively.)
539 * - For DSA, we expect them to be 0, p, q, g, y, x in that
545 /* Expect the SEQUENCE header. Take its absence as a failure to decrypt. */
546 ret
= ber_read_id_len(p
, key
->keyblob_len
, &id
, &len
, &flags
);
548 if (ret
< 0 || id
!= 16) {
549 errmsg
= "ASN.1 decoding failure";
550 retval
= SSH2_WRONG_PASSPHRASE
;
554 /* Expect a load of INTEGERs. */
555 if (key
->type
== OSSH_RSA
)
557 else if (key
->type
== OSSH_DSA
)
561 * Space to create key blob in.
563 blobsize
= 256+key
->keyblob_len
;
564 blob
= smalloc(blobsize
);
566 if (key
->type
== OSSH_DSA
)
567 memcpy(blob
+4, "ssh-dss", 7);
568 else if (key
->type
== OSSH_RSA
)
569 memcpy(blob
+4, "ssh-rsa", 7);
573 for (i
= 0; i
< num_integers
; i
++) {
574 ret
= ber_read_id_len(p
, key
->keyblob
+key
->keyblob_len
-p
,
577 if (ret
< 0 || id
!= 2 ||
578 key
->keyblob
+key
->keyblob_len
-p
< len
) {
579 errmsg
= "ASN.1 decoding failure";
585 * The first integer should be zero always (I think
586 * this is some sort of version indication).
588 if (len
!= 1 || p
[0] != 0) {
589 errmsg
= "Version number mismatch";
592 } else if (key
->type
== OSSH_RSA
) {
594 * Integers 1 and 2 go into the public blob but in the
595 * opposite order; integers 3, 4, 5 and 8 go into the
596 * private blob. The other two (6 and 7) are ignored.
599 /* Save the details for after we deal with number 2. */
602 } else if (i
!= 6 && i
!= 7) {
603 PUT_32BIT(blob
+blobptr
, len
);
604 memcpy(blob
+blobptr
+4, p
, len
);
607 PUT_32BIT(blob
+blobptr
, modlen
);
608 memcpy(blob
+blobptr
+4, modptr
, modlen
);
613 } else if (key
->type
== OSSH_DSA
) {
615 * Integers 1-4 go into the public blob; integer 5 goes
616 * into the private blob.
618 PUT_32BIT(blob
+blobptr
, len
);
619 memcpy(blob
+blobptr
+4, p
, len
);
625 /* Skip past the number. */
630 * Now put together the actual key. Simplest way to do this is
631 * to assemble our own key blobs and feed them to the createkey
632 * functions; this is a bit faffy but it does mean we get all
633 * the sanity checks for free.
635 assert(privptr
> 0); /* should have bombed by now if not */
636 retkey
= smalloc(sizeof(struct ssh2_userkey
));
637 retkey
->alg
= (key
->type
== OSSH_RSA ?
&ssh_rsa
: &ssh_dss
);
638 retkey
->data
= retkey
->alg
->createkey(blob
, privptr
,
639 blob
+privptr
, blobptr
-privptr
);
642 errmsg
= "unable to create key data structure";
646 retkey
->comment
= dupstr("imported-openssh-key");
647 errmsg
= NULL
; /* no error */
652 memset(blob
, 0, blobsize
);
655 memset(key
->keyblob
, 0, key
->keyblob_size
);
657 memset(&key
, 0, sizeof(key
));
662 int openssh_write(char *filename
, struct ssh2_userkey
*key
, char *passphrase
)
664 unsigned char *pubblob
, *privblob
, *spareblob
;
665 int publen
, privlen
, sparelen
;
666 unsigned char *outblob
;
668 struct mpint_pos numbers
[9];
669 int nnumbers
, pos
, len
, seqlen
, i
;
670 char *header
, *footer
;
677 * Fetch the key blobs.
679 pubblob
= key
->alg
->public_blob(key
->data
, &publen
);
680 privblob
= key
->alg
->private_blob(key
->data
, &privlen
);
681 spareblob
= outblob
= NULL
;
684 * Find the sequence of integers to be encoded into the OpenSSH
685 * key blob, and also decide on the header line.
687 if (key
->alg
== &ssh_rsa
) {
689 struct mpint_pos n
, e
, d
, p
, q
, iqmp
, dmp1
, dmq1
;
690 Bignum bd
, bp
, bq
, bdmp1
, bdmq1
;
692 pos
= 4 + GET_32BIT(pubblob
);
693 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &e
);
694 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &n
);
696 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &d
);
697 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &p
);
698 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &q
);
699 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &iqmp
);
701 assert(e
.start
&& iqmp
.start
); /* can't go wrong */
703 /* We also need d mod (p-1) and d mod (q-1). */
704 bd
= bignum_from_bytes(d
.start
, d
.bytes
);
705 bp
= bignum_from_bytes(p
.start
, p
.bytes
);
706 bq
= bignum_from_bytes(q
.start
, q
.bytes
);
709 bdmp1
= bigmod(bd
, bp
);
710 bdmq1
= bigmod(bd
, bq
);
715 dmp1
.bytes
= (bignum_bitcount(bdmp1
)+8)/8;
716 dmq1
.bytes
= (bignum_bitcount(bdmq1
)+8)/8;
717 sparelen
= dmp1
.bytes
+ dmq1
.bytes
;
718 spareblob
= smalloc(sparelen
);
719 dmp1
.start
= spareblob
;
720 dmq1
.start
= spareblob
+ dmp1
.bytes
;
721 for (i
= 0; i
< dmp1
.bytes
; i
++)
722 spareblob
[i
] = bignum_byte(bdmp1
, dmp1
.bytes
-1 - i
);
723 for (i
= 0; i
< dmq1
.bytes
; i
++)
724 spareblob
[i
+dmp1
.bytes
] = bignum_byte(bdmq1
, dmq1
.bytes
-1 - i
);
728 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
739 header
= "-----BEGIN RSA PRIVATE KEY-----\n";
740 footer
= "-----END RSA PRIVATE KEY-----\n";
741 } else if (key
->alg
== &ssh_dss
) {
743 struct mpint_pos p
, q
, g
, y
, x
;
745 pos
= 4 + GET_32BIT(pubblob
);
746 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &p
);
747 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &q
);
748 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &g
);
749 pos
+= ssh2_read_mpint(pubblob
+pos
, publen
-pos
, &y
);
751 pos
+= ssh2_read_mpint(privblob
+pos
, privlen
-pos
, &x
);
753 assert(y
.start
&& x
.start
); /* can't go wrong */
755 numbers
[0].start
= zero
; numbers
[0].bytes
= 1; zero
[0] = '\0';
763 header
= "-----BEGIN DSA PRIVATE KEY-----\n";
764 footer
= "-----END DSA PRIVATE KEY-----\n";
766 assert(0); /* zoinks! */
770 * Now count up the total size of the ASN.1 encoded integers,
771 * so as to determine the length of the containing SEQUENCE.
774 for (i
= 0; i
< nnumbers
; i
++) {
775 len
+= ber_write_id_len(NULL
, 2, numbers
[i
].bytes
, 0);
776 len
+= numbers
[i
].bytes
;
779 /* Now add on the SEQUENCE header. */
780 len
+= ber_write_id_len(NULL
, 16, seqlen
, ASN1_CONSTRUCTED
);
781 /* And round up to the cipher block size. */
786 * Now we know how big outblob needs to be. Allocate it.
789 outblob
= smalloc(outlen
);
792 * And write the data into it.
795 pos
+= ber_write_id_len(outblob
+pos
, 16, seqlen
, ASN1_CONSTRUCTED
);
796 for (i
= 0; i
< nnumbers
; i
++) {
797 pos
+= ber_write_id_len(outblob
+pos
, 2, numbers
[i
].bytes
, 0);
798 memcpy(outblob
+pos
, numbers
[i
].start
, numbers
[i
].bytes
);
799 pos
+= numbers
[i
].bytes
;
801 while (pos
< outlen
) {
802 outblob
[pos
++] = random_byte();
810 * Invent an iv. Then derive encryption key from passphrase
813 * - let block A equal MD5(passphrase || iv)
814 * - let block B equal MD5(A || passphrase || iv)
815 * - block C would be MD5(B || passphrase || iv) and so on
816 * - encryption key is the first N bytes of A || B
818 struct MD5Context md5c
;
819 unsigned char keybuf
[32];
821 for (i
= 0; i
< 8; i
++) iv
[i
] = random_byte();
824 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
825 MD5Update(&md5c
, iv
, 8);
826 MD5Final(keybuf
, &md5c
);
829 MD5Update(&md5c
, keybuf
, 16);
830 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
831 MD5Update(&md5c
, iv
, 8);
832 MD5Final(keybuf
+16, &md5c
);
835 * Now encrypt the key blob.
837 des3_encrypt_pubkey_ossh(keybuf
, iv
, outblob
, outlen
);
839 memset(&md5c
, 0, sizeof(md5c
));
840 memset(keybuf
, 0, sizeof(keybuf
));
844 * And save it. We'll use Unix line endings just in case it's
845 * subsequently transferred in binary mode.
847 fp
= fopen(filename
, "wb"); /* ensure Unix line endings */
852 fprintf(fp
, "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,");
853 for (i
= 0; i
< 8; i
++)
854 fprintf(fp
, "%02X", iv
[i
]);
857 base64_encode(fp
, outblob
, outlen
);
864 memset(outblob
, 0, outlen
);
868 memset(spareblob
, 0, sparelen
);
872 memset(privblob
, 0, privlen
);
876 memset(pubblob
, 0, publen
);
882 /* ----------------------------------------------------------------------
883 * Code to read ssh.com private keys.
887 * The format of the base64 blob is largely ssh2-packet-formatted,
888 * except that mpints are a bit different: they're more like the
889 * old ssh1 mpint. You have a 32-bit bit count N, followed by
890 * (N+7)/8 bytes of data.
892 * So. The blob contains:
894 * - uint32 0x3f6ff9eb (magic number)
895 * - uint32 size (total blob size)
896 * - string key-type (see below)
897 * - string cipher-type (tells you if key is encrypted)
898 * - string encrypted-blob
900 * (The first size field includes the size field itself and the
901 * magic number before it. All other size fields are ordinary ssh2
902 * strings, so the size field indicates how much data is to
905 * The encrypted blob, once decrypted, contains a single string
906 * which in turn contains the payload. (This allows padding to be
907 * added after that string while still making it clear where the
908 * real payload ends. Also it probably makes for a reasonable
911 * The payload blob, for an RSA key, contains:
914 * - mpint n (yes, the public and private stuff is intermixed)
915 * - mpint u (presumably inverse of p mod q)
916 * - mpint p (p is the smaller prime)
917 * - mpint q (q is the larger)
919 * For a DSA key, the payload blob contains:
927 * Alternatively, if the parameters are `predefined', that
928 * (0,p,g,q) sequence can be replaced by a uint32 1 and a string
929 * containing some predefined parameter specification. *shudder*,
930 * but I doubt we'll encounter this in real life.
932 * The key type strings are ghastly. The RSA key I looked at had a
935 * `if-modn{sign{rsa-pkcs1-sha1},encrypt{rsa-pkcs1v2-oaep}}'
937 * and the DSA key wasn't much better:
939 * `dl-modp{sign{dsa-nist-sha1},dh{plain}}'
941 * It isn't clear that these will always be the same. I think it
942 * might be wise just to look at the `if-modn{sign{rsa' and
943 * `dl-modp{sign{dsa' prefixes.
945 * Finally, the encryption. The cipher-type string appears to be
946 * either `none' or `3des-cbc'. Looks as if this is SSH2-style
947 * 3des-cbc (i.e. outer cbc rather than inner). The key is created
948 * from the passphrase by means of yet another hashing faff:
950 * - first 16 bytes are MD5(passphrase)
951 * - next 16 bytes are MD5(passphrase || first 16 bytes)
952 * - if there were more, they'd be MD5(passphrase || first 32),
957 char comment
[256]; /* allowing any length is overkill */
958 unsigned char *keyblob
;
959 int keyblob_len
, keyblob_size
;
962 struct sshcom_key
*load_sshcom_key(char *filename
)
964 struct sshcom_key
*ret
;
971 int base64_chars
= 0;
973 ret
= smalloc(sizeof(*ret
));
974 ret
->comment
[0] = '\0';
976 ret
->keyblob_len
= ret
->keyblob_size
= 0;
978 fp
= fopen(filename
, "r");
980 errmsg
= "Unable to open key file";
983 if (!fgets(buffer
, sizeof(buffer
), fp
) ||
984 0 != strcmp(buffer
, "---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----\n")) {
985 errmsg
= "File does not begin with ssh.com key header";
991 if (!fgets(buffer
, sizeof(buffer
), fp
)) {
992 errmsg
= "Unexpected end of file";
995 if (!strcmp(buffer
, "---- END SSH2 ENCRYPTED PRIVATE KEY ----\n"))
997 if ((p
= strchr(buffer
, ':')) != NULL
) {
999 errmsg
= "Header found in body of key data";
1003 while (*p
&& isspace((unsigned char)*p
)) p
++;
1005 * Header lines can end in a trailing backslash for
1008 while ((len
= strlen(p
)) > sizeof(buffer
) - (p
-buffer
) -1 ||
1009 p
[len
-1] != '\n' || p
[len
-2] == '\\') {
1010 if (len
> (p
-buffer
) + sizeof(buffer
)-2) {
1011 errmsg
= "Header line too long to deal with";
1014 if (!fgets(p
+len
-2, sizeof(buffer
)-(p
-buffer
)-(len
-2), fp
)) {
1015 errmsg
= "Unexpected end of file";
1019 p
[strcspn(p
, "\n")] = '\0';
1020 if (!strcmp(buffer
, "Comment")) {
1021 /* Strip quotes in comment if present. */
1022 if (p
[0] == '"' && p
[strlen(p
)-1] == '"') {
1024 p
[strlen(p
)-1] = '\0';
1026 strncpy(ret
->comment
, p
, sizeof(ret
->comment
));
1027 ret
->comment
[sizeof(ret
->comment
)-1] = '\0';
1033 while (isbase64(*p
)) {
1034 base64_bit
[base64_chars
++] = *p
;
1035 if (base64_chars
== 4) {
1036 unsigned char out
[3];
1040 len
= base64_decode_atom(base64_bit
, out
);
1043 errmsg
= "Invalid base64 encoding";
1047 if (ret
->keyblob_len
+ len
> ret
->keyblob_size
) {
1048 ret
->keyblob_size
= ret
->keyblob_len
+ len
+ 256;
1049 ret
->keyblob
= srealloc(ret
->keyblob
, ret
->keyblob_size
);
1052 memcpy(ret
->keyblob
+ ret
->keyblob_len
, out
, len
);
1053 ret
->keyblob_len
+= len
;
1061 if (ret
->keyblob_len
== 0 || !ret
->keyblob
) {
1062 errmsg
= "Key body not present";
1071 memset(ret
->keyblob
, 0, ret
->keyblob_size
);
1072 sfree(ret
->keyblob
);
1074 memset(&ret
, 0, sizeof(ret
));
1080 int sshcom_encrypted(char *filename
, char **comment
)
1082 struct sshcom_key
*key
= load_sshcom_key(filename
);
1083 int pos
, len
, answer
;
1090 * Check magic number.
1092 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb)
1093 return 0; /* key is invalid */
1096 * Find the cipher-type string.
1100 if (key
->keyblob_len
< pos
+4)
1101 goto done
; /* key is far too short */
1102 pos
+= 4 + GET_32BIT(key
->keyblob
+ pos
); /* skip key type */
1103 if (key
->keyblob_len
< pos
+4)
1104 goto done
; /* key is far too short */
1105 len
= GET_32BIT(key
->keyblob
+ pos
); /* find cipher-type length */
1106 if (key
->keyblob_len
< pos
+4+len
)
1107 goto done
; /* cipher type string is incomplete */
1108 if (len
!= 4 || 0 != memcmp(key
->keyblob
+ pos
+ 4, "none", 4))
1112 *comment
= dupstr(key
->comment
);
1113 memset(key
->keyblob
, 0, key
->keyblob_size
);
1114 sfree(key
->keyblob
);
1115 memset(&key
, 0, sizeof(key
));
1120 int sshcom_read_mpint(void *data
, int len
, struct mpint_pos
*ret
)
1124 unsigned char *d
= (unsigned char *) data
;
1128 bits
= GET_32BIT(d
);
1130 bytes
= (bits
+ 7) / 8;
1141 return len
; /* ensure further calls fail as well */
1144 struct ssh2_userkey
*sshcom_read(char *filename
, char *passphrase
)
1146 struct sshcom_key
*key
= load_sshcom_key(filename
);
1149 const char prefix_rsa
[] = "if-modn{sign{rsa";
1150 const char prefix_dsa
[] = "dl-modp{sign{dsa";
1151 enum { RSA
, DSA
} type
;
1155 struct ssh2_userkey
*ret
= NULL
, *retkey
;
1156 const struct ssh_signkey
*alg
;
1157 unsigned char *blob
= NULL
;
1158 int blobsize
, publen
, privlen
;
1164 * Check magic number.
1166 if (GET_32BIT(key
->keyblob
) != 0x3f6ff9eb) {
1167 errmsg
= "Key does not begin with magic number";
1172 * Determine the key type.
1175 if (key
->keyblob_len
< pos
+4 ||
1176 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1177 errmsg
= "Key blob does not contain a key type string";
1180 if (len
> sizeof(prefix_rsa
) - 1 &&
1181 !memcmp(key
->keyblob
+pos
+4, prefix_rsa
, sizeof(prefix_rsa
) - 1)) {
1183 } else if (len
> sizeof(prefix_dsa
) - 1 &&
1184 !memcmp(key
->keyblob
+pos
+4, prefix_dsa
, sizeof(prefix_dsa
) - 1)) {
1187 errmsg
= "Key is of unknown type";
1193 * Determine the cipher type.
1195 if (key
->keyblob_len
< pos
+4 ||
1196 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1197 errmsg
= "Key blob does not contain a cipher type string";
1200 if (len
== 4 && !memcmp(key
->keyblob
+pos
+4, "none", 4))
1202 else if (len
== 8 && !memcmp(key
->keyblob
+pos
+4, "3des-cbc", 8))
1205 errmsg
= "Key encryption is of unknown type";
1211 * Get hold of the encrypted part of the key.
1213 if (key
->keyblob_len
< pos
+4 ||
1214 (len
= GET_32BIT(key
->keyblob
+ pos
)) > key
->keyblob_len
- pos
- 4) {
1215 errmsg
= "Key blob does not contain actual key data";
1218 ciphertext
= key
->keyblob
+ pos
+ 4;
1220 if (cipherlen
== 0) {
1221 errmsg
= "Length of key data is zero";
1226 * Decrypt it if necessary.
1230 * Derive encryption key from passphrase and iv/salt:
1232 * - let block A equal MD5(passphrase)
1233 * - let block B equal MD5(passphrase || A)
1234 * - block C would be MD5(passphrase || A || B) and so on
1235 * - encryption key is the first N bytes of A || B
1237 struct MD5Context md5c
;
1238 unsigned char keybuf
[32], iv
[8];
1240 if (cipherlen
% 8 != 0) {
1241 errmsg
= "Encrypted part of key is not a multiple of cipher block"
1247 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
1248 MD5Final(keybuf
, &md5c
);
1251 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
1252 MD5Update(&md5c
, keybuf
, 16);
1253 MD5Final(keybuf
+16, &md5c
);
1256 * Now decrypt the key blob.
1258 memset(iv
, 0, sizeof(iv
));
1259 des3_decrypt_pubkey_ossh(keybuf
, iv
, ciphertext
, cipherlen
);
1261 memset(&md5c
, 0, sizeof(md5c
));
1262 memset(keybuf
, 0, sizeof(keybuf
));
1265 * Hereafter we return WRONG_PASSPHRASE for any parsing
1266 * error. (But only if we've just tried to decrypt it!
1267 * Returning WRONG_PASSPHRASE for an unencrypted key is
1271 ret
= SSH2_WRONG_PASSPHRASE
;
1275 * Strip away the containing string to get to the real meat.
1277 len
= GET_32BIT(ciphertext
);
1278 if (len
> cipherlen
-4) {
1279 errmsg
= "containing string was ill-formed";
1286 * Now we break down into RSA versus DSA. In either case we'll
1287 * construct public and private blobs in our own format, and
1288 * end up feeding them to alg->createkey().
1290 blobsize
= cipherlen
+ 256;
1291 blob
= smalloc(blobsize
);
1294 struct mpint_pos n
, e
, d
, u
, p
, q
;
1296 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &e
);
1297 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &d
);
1298 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &n
);
1299 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &u
);
1300 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1301 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1303 errmsg
= "key data did not contain six integers";
1309 pos
+= put_string(blob
+pos
, "ssh-rsa", 7);
1310 pos
+= put_mp(blob
+pos
, e
.start
, e
.bytes
);
1311 pos
+= put_mp(blob
+pos
, n
.start
, n
.bytes
);
1313 pos
+= put_string(blob
+pos
, d
.start
, d
.bytes
);
1314 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1315 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1316 pos
+= put_mp(blob
+pos
, u
.start
, u
.bytes
);
1317 privlen
= pos
- publen
;
1318 } else if (type
== DSA
) {
1319 struct mpint_pos p
, q
, g
, x
, y
;
1321 if (GET_32BIT(ciphertext
) != 0) {
1322 errmsg
= "predefined DSA parameters not supported";
1325 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &p
);
1326 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &g
);
1327 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &q
);
1328 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &y
);
1329 pos
+= sshcom_read_mpint(ciphertext
+pos
, cipherlen
-pos
, &x
);
1331 errmsg
= "key data did not contain five integers";
1337 pos
+= put_string(blob
+pos
, "ssh-dss", 7);
1338 pos
+= put_mp(blob
+pos
, p
.start
, p
.bytes
);
1339 pos
+= put_mp(blob
+pos
, q
.start
, q
.bytes
);
1340 pos
+= put_mp(blob
+pos
, g
.start
, g
.bytes
);
1341 pos
+= put_mp(blob
+pos
, y
.start
, y
.bytes
);
1343 pos
+= put_mp(blob
+pos
, x
.start
, x
.bytes
);
1344 privlen
= pos
- publen
;
1347 assert(privlen
> 0); /* should have bombed by now if not */
1349 retkey
= smalloc(sizeof(struct ssh2_userkey
));
1351 retkey
->data
= alg
->createkey(blob
, publen
, blob
+publen
, privlen
);
1352 if (!retkey
->data
) {
1354 errmsg
= "unable to create key data structure";
1357 retkey
->comment
= dupstr(key
->comment
);
1359 errmsg
= NULL
; /* no error */
1364 memset(blob
, 0, blobsize
);
1367 memset(key
->keyblob
, 0, key
->keyblob_size
);
1368 sfree(key
->keyblob
);
1369 memset(&key
, 0, sizeof(key
));