2 * Generic SSH public-key handling operations. In particular,
3 * reading of SSH public-key files, and also the generic `sign'
4 * operation for ssh2 (which checks the type of the key and
5 * dispatches to the appropriate key-type specific function).
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 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
28 #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
29 (x)-'a'<26 ? (x)-'a'+26 :\
30 (x)-'0'<10 ? (x)-'0'+52 :\
34 static int loadrsakey_main(FILE * fp
, struct RSAKey
*key
,
35 char **commentptr
, char *passphrase
)
37 unsigned char buf
[16384];
38 unsigned char keybuf
[16];
42 struct MD5Context md5c
;
45 /* Slurp the whole file (minus the header) into a buffer. */
46 len
= fread(buf
, 1, sizeof(buf
), fp
);
48 if (len
< 0 || len
== sizeof(buf
))
49 goto end
; /* file too big or not read */
54 * A zero byte. (The signature includes a terminating NUL.)
56 if (len
- i
< 1 || buf
[i
] != 0)
60 /* One byte giving encryption type, and one reserved uint32. */
64 if (ciphertype
!= 0 && ciphertype
!= SSH_CIPHER_3DES
)
68 goto end
; /* reserved field not present */
69 if (buf
[i
] != 0 || buf
[i
+ 1] != 0 || buf
[i
+ 2] != 0
70 || buf
[i
+ 3] != 0) goto end
; /* reserved field nonzero, panic! */
73 /* Now the serious stuff. An ordinary SSH 1 public key. */
74 i
+= makekey(buf
+ i
, key
, NULL
, 1);
76 goto end
; /* overran */
78 /* Next, the comment field. */
79 j
= GET_32BIT(buf
+ i
);
83 comment
= smalloc(j
+ 1);
85 memcpy(comment
, buf
+ i
, j
);
90 *commentptr
= comment
;
92 key
->comment
= comment
;
94 return ciphertype
!= 0;
98 * Decrypt remainder of buffer.
102 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
103 MD5Final(keybuf
, &md5c
);
104 des3_decrypt_pubkey(keybuf
, buf
+ i
, (len
- i
+ 7) & ~7);
105 memset(keybuf
, 0, sizeof(keybuf
)); /* burn the evidence */
109 * We are now in the secret part of the key. The first four
110 * bytes should be of the form a, b, a, b.
114 if (buf
[i
] != buf
[i
+ 2] || buf
[i
+ 1] != buf
[i
+ 3]) {
121 * After that, we have one further bignum which is our
122 * decryption exponent, and then the three auxiliary values
125 i
+= makeprivate(buf
+ i
, key
);
128 i
+= ssh1_read_bignum(buf
+ i
, &key
->iqmp
);
131 i
+= ssh1_read_bignum(buf
+ i
, &key
->q
);
134 i
+= ssh1_read_bignum(buf
+ i
, &key
->p
);
138 if (!rsa_verify(key
)) {
145 memset(buf
, 0, sizeof(buf
)); /* burn the evidence */
149 int loadrsakey(char *filename
, struct RSAKey
*key
, char *passphrase
)
152 unsigned char buf
[64];
154 fp
= fopen(filename
, "rb");
156 return 0; /* doesn't even exist */
159 * Read the first line of the file and see if it's a v1 private
162 if (fgets(buf
, sizeof(buf
), fp
) && !strcmp(buf
, rsa_signature
)) {
163 return loadrsakey_main(fp
, key
, NULL
, passphrase
);
167 * Otherwise, we have nothing. Return empty-handed.
174 * See whether an RSA key is encrypted. Return its comment field as
177 int rsakey_encrypted(char *filename
, char **comment
)
180 unsigned char buf
[64];
182 fp
= fopen(filename
, "rb");
184 return 0; /* doesn't even exist */
187 * Read the first line of the file and see if it's a v1 private
190 if (fgets(buf
, sizeof(buf
), fp
) && !strcmp(buf
, rsa_signature
)) {
191 return loadrsakey_main(fp
, NULL
, comment
, NULL
);
194 return 0; /* wasn't the right kind of file */
198 * Save an RSA key file. Return nonzero on success.
200 int saversakey(char *filename
, struct RSAKey
*key
, char *passphrase
)
202 unsigned char buf
[16384];
203 unsigned char keybuf
[16];
204 struct MD5Context md5c
;
205 unsigned char *p
, *estart
;
209 * Write the initial signature.
212 memcpy(p
, rsa_signature
, sizeof(rsa_signature
));
213 p
+= sizeof(rsa_signature
);
216 * One byte giving encryption type, and one reserved (zero)
219 *p
++ = (passphrase ? SSH_CIPHER_3DES
: 0);
224 * An ordinary SSH 1 public key consists of: a uint32
225 * containing the bit count, then two bignums containing the
226 * modulus and exponent respectively.
228 PUT_32BIT(p
, bignum_bitcount(key
->modulus
));
230 p
+= ssh1_write_bignum(p
, key
->modulus
);
231 p
+= ssh1_write_bignum(p
, key
->exponent
);
234 * A string containing the comment field.
237 PUT_32BIT(p
, strlen(key
->comment
));
239 memcpy(p
, key
->comment
, strlen(key
->comment
));
240 p
+= strlen(key
->comment
);
247 * The encrypted portion starts here.
252 * Two bytes, then the same two bytes repeated.
254 *p
++ = random_byte();
255 *p
++ = random_byte();
261 * Four more bignums: the decryption exponent, then iqmp, then
264 p
+= ssh1_write_bignum(p
, key
->private_exponent
);
265 p
+= ssh1_write_bignum(p
, key
->iqmp
);
266 p
+= ssh1_write_bignum(p
, key
->q
);
267 p
+= ssh1_write_bignum(p
, key
->p
);
270 * Now write zeros until the encrypted portion is a multiple of
273 while ((p
- estart
) % 8)
277 * Now encrypt the encrypted portion.
281 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
282 MD5Final(keybuf
, &md5c
);
283 des3_encrypt_pubkey(keybuf
, estart
, p
- estart
);
284 memset(keybuf
, 0, sizeof(keybuf
)); /* burn the evidence */
288 * Done. Write the result to the file.
290 fp
= fopen(filename
, "wb");
292 int ret
= (fwrite(buf
, 1, p
- buf
, fp
) == (size_t) (p
- buf
));
293 ret
= ret
&& (fclose(fp
) == 0);
299 /* ----------------------------------------------------------------------
300 * SSH2 private key load/store functions.
304 * PuTTY's own format for SSH2 keys is as follows:
306 * The file is text. Lines are terminated by CRLF, although CR-only
307 * and LF-only are tolerated on input.
309 * The first line says "PuTTY-User-Key-File-1: " plus the name of the
310 * algorithm ("ssh-dss", "ssh-rsa" etc. Although, of course, this
311 * being PuTTY, "ssh-dss" is not supported.)
313 * The next line says "Encryption: " plus an encryption type.
314 * Currently the only supported encryption types are "aes256-cbc"
317 * The next line says "Comment: " plus the comment string.
319 * Next there is a line saying "Public-Lines: " plus a number N.
320 * The following N lines contain a base64 encoding of the public
321 * part of the key. This is encoded as the standard SSH2 public key
322 * blob (with no initial length): so for RSA, for example, it will
329 * Next, there is a line saying "Private-Lines: " plus a number N,
330 * and then N lines containing the (potentially encrypted) private
331 * part of the key. For the key type "ssh-rsa", this will be
334 * mpint private_exponent
335 * mpint p (the larger of the two primes)
336 * mpint q (the smaller prime)
337 * mpint iqmp (the inverse of q modulo p)
338 * data padding (to reach a multiple of the cipher block size)
340 * Finally, there is a line saying "Private-Hash: " plus a hex
341 * representation of a SHA-1 hash of the plaintext version of the
342 * private part, including the final padding.
344 * If the key is encrypted, the encryption key is derived from the
345 * passphrase by means of a succession of SHA-1 hashes. Each hash
348 * uint32 sequence-number
351 * where the sequence-number increases from zero. As many of these
352 * hashes are used as necessary.
354 * NOTE! It is important that all _public_ data can be verified
355 * with reference to the _private_ data. There exist attacks based
356 * on modifying the public key but leaving the private section
359 * With RSA, this is easy: verify that n = p*q, and also verify
360 * that e*d == 1 modulo (p-1)(q-1). With DSA (if we were ever to
361 * support it), we would need to store extra data in the private
362 * section other than just x.
365 static int read_header(FILE * fp
, char *header
)
372 if (c
== '\n' || c
== '\r' || c
== EOF
)
373 return 0; /* failure */
379 return 1; /* success! */
382 return 0; /* failure */
386 return 0; /* failure */
389 static char *read_body(FILE * fp
)
397 text
= smalloc(size
);
403 if (c
== '\r' || c
== '\n') {
405 if (c
!= '\r' && c
!= '\n' && c
!= EOF
)
413 if (len
+ 1 > size
) {
415 text
= srealloc(text
, size
);
422 int base64_decode_atom(char *atom
, unsigned char *out
)
429 for (i
= 0; i
< 4; i
++) {
431 if (c
>= 'A' && c
<= 'Z')
433 else if (c
>= 'a' && c
<= 'z')
435 else if (c
>= '0' && c
<= '9')
444 return 0; /* invalid atom */
448 if (vals
[0] == -1 || vals
[1] == -1)
450 if (vals
[2] == -1 && vals
[3] != -1)
455 else if (vals
[2] != -1)
460 word
= ((vals
[0] << 18) |
461 (vals
[1] << 12) | ((vals
[2] & 0x3F) << 6) | (vals
[3] & 0x3F));
462 out
[0] = (word
>> 16) & 0xFF;
464 out
[1] = (word
>> 8) & 0xFF;
466 out
[2] = word
& 0xFF;
470 static char *read_blob(FILE * fp
, int nlines
, int *bloblen
)
477 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
478 blob
= smalloc(48 * nlines
);
480 for (i
= 0; i
< nlines
; i
++) {
481 line
= read_body(fp
);
486 linelen
= strlen(line
);
487 if (linelen
% 4 != 0 || linelen
> 64) {
492 for (j
= 0; j
< linelen
; j
+= 4) {
493 k
= base64_decode_atom(line
+ j
, blob
+ len
);
508 * Magic error return value for when the passphrase is wrong.
510 struct ssh2_userkey ssh2_wrong_passphrase
= {
514 struct ssh2_userkey
*ssh2_load_userkey(char *filename
, char *passphrase
)
517 char header
[40], *b
, *comment
, *hash
;
518 const struct ssh_signkey
*alg
;
519 struct ssh2_userkey
*ret
;
520 int cipher
, cipherblk
;
521 unsigned char *public_blob
, *private_blob
;
522 int public_blob_len
, private_blob_len
;
525 ret
= NULL
; /* return NULL for most errors */
526 comment
= hash
= NULL
;
527 public_blob
= private_blob
= NULL
;
529 fp
= fopen(filename
, "rb");
533 /* Read the first header line which contains the key type. */
534 if (!read_header(fp
, header
)
535 || 0 != strcmp(header
, "PuTTY-User-Key-File-1"))
537 if ((b
= read_body(fp
)) == NULL
)
539 /* Select key algorithm structure. Currently only ssh-rsa. */
540 if (!strcmp(b
, "ssh-rsa"))
548 /* Read the Encryption header line. */
549 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Encryption"))
551 if ((b
= read_body(fp
)) == NULL
)
553 if (!strcmp(b
, "aes256-cbc")) {
556 } else if (!strcmp(b
, "none")) {
565 /* Read the Comment header line. */
566 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Comment"))
568 if ((comment
= read_body(fp
)) == NULL
)
571 /* Read the Public-Lines header line and the public blob. */
572 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Public-Lines"))
574 if ((b
= read_body(fp
)) == NULL
)
578 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
581 /* Read the Private-Lines header line and the Private blob. */
582 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Private-Lines"))
584 if ((b
= read_body(fp
)) == NULL
)
588 if ((private_blob
= read_blob(fp
, i
, &private_blob_len
)) == NULL
)
591 /* Read the Private-Hash header line. */
592 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Private-Hash"))
594 if ((hash
= read_body(fp
)) == NULL
)
601 * Decrypt the private blob.
604 unsigned char key
[40];
610 if (private_blob_len
% cipherblk
)
613 passlen
= strlen(passphrase
);
616 SHA_Bytes(&s
, "\0\0\0\0", 4);
617 SHA_Bytes(&s
, passphrase
, passlen
);
618 SHA_Final(&s
, key
+ 0);
620 SHA_Bytes(&s
, "\0\0\0\1", 4);
621 SHA_Bytes(&s
, passphrase
, passlen
);
622 SHA_Final(&s
, key
+ 20);
623 aes256_decrypt_pubkey(key
, private_blob
, private_blob_len
);
627 * Verify the private hash.
631 unsigned char binary
[20];
633 SHA_Simple(private_blob
, private_blob_len
, binary
);
634 for (i
= 0; i
< 20; i
++)
635 sprintf(realhash
+ 2 * i
, "%02x", binary
[i
]);
637 if (strcmp(hash
, realhash
)) {
638 /* An incorrect hash is an unconditional Error if the key is
639 * unencrypted. Otherwise, it means Wrong Passphrase. */
640 ret
= cipher ? SSH2_WRONG_PASSPHRASE
: NULL
;
647 * Create and return the key.
649 ret
= smalloc(sizeof(struct ssh2_userkey
));
651 ret
->comment
= comment
;
652 ret
->data
= alg
->createkey(public_blob
, public_blob_len
,
653 private_blob
, private_blob_len
);
680 char *ssh2_userkey_loadpub(char *filename
, char **algorithm
,
685 const struct ssh_signkey
*alg
;
686 unsigned char *public_blob
;
692 fp
= fopen(filename
, "rb");
696 /* Read the first header line which contains the key type. */
697 if (!read_header(fp
, header
)
698 || 0 != strcmp(header
, "PuTTY-User-Key-File-1"))
700 if ((b
= read_body(fp
)) == NULL
)
702 /* Select key algorithm structure. Currently only ssh-rsa. */
703 if (!strcmp(b
, "ssh-rsa"))
711 /* Read the Encryption header line. */
712 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Encryption"))
714 if ((b
= read_body(fp
)) == NULL
)
716 sfree(b
); /* we don't care */
718 /* Read the Comment header line. */
719 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Comment"))
721 if ((b
= read_body(fp
)) == NULL
)
723 sfree(b
); /* we don't care */
725 /* Read the Public-Lines header line and the public blob. */
726 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Public-Lines"))
728 if ((b
= read_body(fp
)) == NULL
)
732 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
736 *pub_blob_len
= public_blob_len
;
737 *algorithm
= alg
->name
;
751 int ssh2_userkey_encrypted(char *filename
, char **commentptr
)
754 char header
[40], *b
, *comment
;
760 fp
= fopen(filename
, "rb");
763 if (!read_header(fp
, header
)
764 || 0 != strcmp(header
, "PuTTY-User-Key-File-1")) {
768 if ((b
= read_body(fp
)) == NULL
) {
772 sfree(b
); /* we don't care about key type here */
773 /* Read the Encryption header line. */
774 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Encryption")) {
778 if ((b
= read_body(fp
)) == NULL
) {
783 /* Read the Comment header line. */
784 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Comment")) {
789 if ((comment
= read_body(fp
)) == NULL
) {
796 *commentptr
= comment
;
799 if (!strcmp(b
, "aes256-cbc"))
807 int base64_lines(int datalen
)
809 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
810 return (datalen
+ 47) / 48;
813 void base64_encode_atom(unsigned char *data
, int n
, char *out
)
815 static const char base64_chars
[] =
816 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
820 word
= data
[0] << 16;
822 word
|= data
[1] << 8;
825 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
826 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
828 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
832 out
[3] = base64_chars
[word
& 0x3F];
837 void base64_encode(FILE * fp
, unsigned char *data
, int datalen
)
843 while (datalen
> 0) {
848 n
= (datalen
< 3 ? datalen
: 3);
849 base64_encode_atom(data
, n
, out
);
852 fwrite(out
, 1, 4, fp
);
858 int ssh2_save_userkey(char *filename
, struct ssh2_userkey
*key
,
862 unsigned char *pub_blob
, *priv_blob
, *priv_blob_encrypted
;
863 int pub_blob_len
, priv_blob_len
, priv_encrypted_len
;
868 unsigned char priv_hash
[20];
871 * Fetch the key component blobs.
873 pub_blob
= key
->alg
->public_blob(key
->data
, &pub_blob_len
);
874 priv_blob
= key
->alg
->private_blob(key
->data
, &priv_blob_len
);
875 if (!pub_blob
|| !priv_blob
) {
882 * Determine encryption details, and encrypt the private blob.
885 cipherstr
= "aes256-cbc";
891 priv_encrypted_len
= priv_blob_len
+ cipherblk
- 1;
892 priv_encrypted_len
-= priv_encrypted_len
% cipherblk
;
893 priv_blob_encrypted
= smalloc(priv_encrypted_len
);
894 memset(priv_blob_encrypted
, 0, priv_encrypted_len
);
895 memcpy(priv_blob_encrypted
, priv_blob
, priv_blob_len
);
896 /* Create padding based on the SHA hash of the unpadded blob. This prevents
897 * too easy a known-plaintext attack on the last block. */
898 SHA_Simple(priv_blob
, priv_blob_len
, priv_hash
);
899 assert(priv_encrypted_len
- priv_blob_len
< 20);
900 memcpy(priv_blob_encrypted
+ priv_blob_len
, priv_hash
,
901 priv_encrypted_len
- priv_blob_len
);
903 /* Now create the _real_ private hash. */
904 SHA_Simple(priv_blob_encrypted
, priv_encrypted_len
, priv_hash
);
910 passlen
= strlen(passphrase
);
913 SHA_Bytes(&s
, "\0\0\0\0", 4);
914 SHA_Bytes(&s
, passphrase
, passlen
);
915 SHA_Final(&s
, key
+ 0);
917 SHA_Bytes(&s
, "\0\0\0\1", 4);
918 SHA_Bytes(&s
, passphrase
, passlen
);
919 SHA_Final(&s
, key
+ 20);
920 aes256_encrypt_pubkey(key
, priv_blob_encrypted
,
924 fp
= fopen(filename
, "w");
927 fprintf(fp
, "PuTTY-User-Key-File-1: %s\n", key
->alg
->name
);
928 fprintf(fp
, "Encryption: %s\n", cipherstr
);
929 fprintf(fp
, "Comment: %s\n", key
->comment
);
930 fprintf(fp
, "Public-Lines: %d\n", base64_lines(pub_blob_len
));
931 base64_encode(fp
, pub_blob
, pub_blob_len
);
932 fprintf(fp
, "Private-Lines: %d\n", base64_lines(priv_encrypted_len
));
933 base64_encode(fp
, priv_blob_encrypted
, priv_encrypted_len
);
934 fprintf(fp
, "Private-Hash: ");
935 for (i
= 0; i
< 20; i
++)
936 fprintf(fp
, "%02x", priv_hash
[i
]);
942 /* ----------------------------------------------------------------------
943 * A function to determine which version of SSH to try on a private
944 * key file. Returns 0 on failure, 1 or 2 on success.
946 int keyfile_version(char *filename
)
951 fp
= fopen(filename
, "r");
957 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
958 if (i
== 'P') /* "PuTTY-User-Key-File" etc */
960 return 0; /* unrecognised or EOF */