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).
312 * The next line says "Encryption: " plus an encryption type.
313 * Currently the only supported encryption types are "aes256-cbc"
316 * The next line says "Comment: " plus the comment string.
318 * Next there is a line saying "Public-Lines: " plus a number N.
319 * The following N lines contain a base64 encoding of the public
320 * part of the key. This is encoded as the standard SSH2 public key
321 * blob (with no initial length): so for RSA, for example, it will
328 * Next, there is a line saying "Private-Lines: " plus a number N,
329 * and then N lines containing the (potentially encrypted) private
330 * part of the key. For the key type "ssh-rsa", this will be
333 * mpint private_exponent
334 * mpint p (the larger of the two primes)
335 * mpint q (the smaller prime)
336 * mpint iqmp (the inverse of q modulo p)
337 * data padding (to reach a multiple of the cipher block size)
339 * And for "ssh-dss", it will be composed of
341 * mpint x (the private key parameter)
342 * string hash (20-byte hash of mpints p || q || g)
344 * Finally, there is a line saying _either_
346 * - "Private-Hash: " plus a hex representation of a SHA-1 hash of
347 * the plaintext version of the private part, including the
352 * - "Private-MAC: " plus a hex representation of a HMAC-SHA-1 of
353 * the plaintext version of the private part, including the
356 * The key to the MAC is itself a SHA-1 hash of:
358 * data "putty-private-key-file-mac-key"
361 * Encrypted keys should have a MAC, whereas unencrypted ones must
364 * If the key is encrypted, the encryption key is derived from the
365 * passphrase by means of a succession of SHA-1 hashes. Each hash
368 * uint32 sequence-number
371 * where the sequence-number increases from zero. As many of these
372 * hashes are used as necessary.
374 * NOTE! It is important that all _public_ data can be verified
375 * with reference to the _private_ data. There exist attacks based
376 * on modifying the public key but leaving the private section
379 * With RSA, this is easy: verify that n = p*q, and also verify
380 * that e*d == 1 modulo (p-1)(q-1). With DSA, we need to store
381 * extra data in the private section other than just x, namely a
382 * hash of p||q||g. (It's then easy to verify that y is equal to
386 static int read_header(FILE * fp
, char *header
)
393 if (c
== '\n' || c
== '\r' || c
== EOF
)
394 return 0; /* failure */
400 return 1; /* success! */
403 return 0; /* failure */
407 return 0; /* failure */
410 static char *read_body(FILE * fp
)
418 text
= smalloc(size
);
424 if (c
== '\r' || c
== '\n') {
426 if (c
!= '\r' && c
!= '\n' && c
!= EOF
)
434 if (len
+ 1 > size
) {
436 text
= srealloc(text
, size
);
443 int base64_decode_atom(char *atom
, unsigned char *out
)
450 for (i
= 0; i
< 4; i
++) {
452 if (c
>= 'A' && c
<= 'Z')
454 else if (c
>= 'a' && c
<= 'z')
456 else if (c
>= '0' && c
<= '9')
465 return 0; /* invalid atom */
469 if (vals
[0] == -1 || vals
[1] == -1)
471 if (vals
[2] == -1 && vals
[3] != -1)
476 else if (vals
[2] != -1)
481 word
= ((vals
[0] << 18) |
482 (vals
[1] << 12) | ((vals
[2] & 0x3F) << 6) | (vals
[3] & 0x3F));
483 out
[0] = (word
>> 16) & 0xFF;
485 out
[1] = (word
>> 8) & 0xFF;
487 out
[2] = word
& 0xFF;
491 static char *read_blob(FILE * fp
, int nlines
, int *bloblen
)
498 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
499 blob
= smalloc(48 * nlines
);
501 for (i
= 0; i
< nlines
; i
++) {
502 line
= read_body(fp
);
507 linelen
= strlen(line
);
508 if (linelen
% 4 != 0 || linelen
> 64) {
513 for (j
= 0; j
< linelen
; j
+= 4) {
514 k
= base64_decode_atom(line
+ j
, blob
+ len
);
529 * Magic error return value for when the passphrase is wrong.
531 struct ssh2_userkey ssh2_wrong_passphrase
= {
535 struct ssh2_userkey
*ssh2_load_userkey(char *filename
, char *passphrase
)
538 char header
[40], *b
, *comment
, *mac
;
539 const struct ssh_signkey
*alg
;
540 struct ssh2_userkey
*ret
;
541 int cipher
, cipherblk
;
542 unsigned char *public_blob
, *private_blob
;
543 int public_blob_len
, private_blob_len
;
545 int passlen
= passphrase ?
strlen(passphrase
) : 0;
547 ret
= NULL
; /* return NULL for most errors */
548 comment
= mac
= NULL
;
549 public_blob
= private_blob
= NULL
;
551 fp
= fopen(filename
, "rb");
555 /* Read the first header line which contains the key type. */
556 if (!read_header(fp
, header
)
557 || 0 != strcmp(header
, "PuTTY-User-Key-File-1"))
559 if ((b
= read_body(fp
)) == NULL
)
561 /* Select key algorithm structure. */
562 if (!strcmp(b
, "ssh-rsa"))
564 else if (!strcmp(b
, "ssh-dss"))
572 /* Read the Encryption header line. */
573 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Encryption"))
575 if ((b
= read_body(fp
)) == NULL
)
577 if (!strcmp(b
, "aes256-cbc")) {
580 } else if (!strcmp(b
, "none")) {
589 /* Read the Comment header line. */
590 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Comment"))
592 if ((comment
= read_body(fp
)) == NULL
)
595 /* Read the Public-Lines header line and the public blob. */
596 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Public-Lines"))
598 if ((b
= read_body(fp
)) == NULL
)
602 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
605 /* Read the Private-Lines header line and the Private blob. */
606 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Private-Lines"))
608 if ((b
= read_body(fp
)) == NULL
)
612 if ((private_blob
= read_blob(fp
, i
, &private_blob_len
)) == NULL
)
615 /* Read the Private-MAC or Private-Hash header line. */
616 if (!read_header(fp
, header
))
618 if (0 == strcmp(header
, "Private-MAC")) {
619 if ((mac
= read_body(fp
)) == NULL
)
622 } else if (0 == strcmp(header
, "Private-Hash")) {
623 if ((mac
= read_body(fp
)) == NULL
)
633 * Decrypt the private blob.
636 unsigned char key
[40];
641 if (private_blob_len
% cipherblk
)
645 SHA_Bytes(&s
, "\0\0\0\0", 4);
646 SHA_Bytes(&s
, passphrase
, passlen
);
647 SHA_Final(&s
, key
+ 0);
649 SHA_Bytes(&s
, "\0\0\0\1", 4);
650 SHA_Bytes(&s
, passphrase
, passlen
);
651 SHA_Final(&s
, key
+ 20);
652 aes256_decrypt_pubkey(key
, private_blob
, private_blob_len
);
656 * Verify the private hash.
660 unsigned char binary
[20];
664 unsigned char mackey
[20];
665 char header
[] = "putty-private-key-file-mac-key";
667 if (!passphrase
) /* can't have MAC in unencrypted key */
671 SHA_Bytes(&s
, header
, sizeof(header
)-1);
672 SHA_Bytes(&s
, passphrase
, passlen
);
673 SHA_Final(&s
, mackey
);
675 hmac_sha1_simple(mackey
, 20, private_blob
, private_blob_len
,
678 memset(mackey
, 0, sizeof(mackey
));
679 memset(&s
, 0, sizeof(s
));
681 SHA_Simple(private_blob
, private_blob_len
, binary
);
683 for (i
= 0; i
< 20; i
++)
684 sprintf(realmac
+ 2 * i
, "%02x", binary
[i
]);
686 if (strcmp(mac
, realmac
)) {
687 /* An incorrect MAC is an unconditional Error if the key is
688 * unencrypted. Otherwise, it means Wrong Passphrase. */
689 ret
= cipher ? SSH2_WRONG_PASSPHRASE
: NULL
;
696 * Create and return the key.
698 ret
= smalloc(sizeof(struct ssh2_userkey
));
700 ret
->comment
= comment
;
701 ret
->data
= alg
->createkey(public_blob
, public_blob_len
,
702 private_blob
, private_blob_len
);
729 char *ssh2_userkey_loadpub(char *filename
, char **algorithm
,
734 const struct ssh_signkey
*alg
;
735 unsigned char *public_blob
;
741 fp
= fopen(filename
, "rb");
745 /* Read the first header line which contains the key type. */
746 if (!read_header(fp
, header
)
747 || 0 != strcmp(header
, "PuTTY-User-Key-File-1"))
749 if ((b
= read_body(fp
)) == NULL
)
751 /* Select key algorithm structure. Currently only ssh-rsa. */
752 if (!strcmp(b
, "ssh-rsa"))
754 else if (!strcmp(b
, "ssh-dss"))
762 /* Read the Encryption header line. */
763 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Encryption"))
765 if ((b
= read_body(fp
)) == NULL
)
767 sfree(b
); /* we don't care */
769 /* Read the Comment header line. */
770 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Comment"))
772 if ((b
= read_body(fp
)) == NULL
)
774 sfree(b
); /* we don't care */
776 /* Read the Public-Lines header line and the public blob. */
777 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Public-Lines"))
779 if ((b
= read_body(fp
)) == NULL
)
783 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
787 *pub_blob_len
= public_blob_len
;
788 *algorithm
= alg
->name
;
802 int ssh2_userkey_encrypted(char *filename
, char **commentptr
)
805 char header
[40], *b
, *comment
;
811 fp
= fopen(filename
, "rb");
814 if (!read_header(fp
, header
)
815 || 0 != strcmp(header
, "PuTTY-User-Key-File-1")) {
819 if ((b
= read_body(fp
)) == NULL
) {
823 sfree(b
); /* we don't care about key type here */
824 /* Read the Encryption header line. */
825 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Encryption")) {
829 if ((b
= read_body(fp
)) == NULL
) {
834 /* Read the Comment header line. */
835 if (!read_header(fp
, header
) || 0 != strcmp(header
, "Comment")) {
840 if ((comment
= read_body(fp
)) == NULL
) {
847 *commentptr
= comment
;
850 if (!strcmp(b
, "aes256-cbc"))
858 int base64_lines(int datalen
)
860 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
861 return (datalen
+ 47) / 48;
864 void base64_encode_atom(unsigned char *data
, int n
, char *out
)
866 static const char base64_chars
[] =
867 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
871 word
= data
[0] << 16;
873 word
|= data
[1] << 8;
876 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
877 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
879 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
883 out
[3] = base64_chars
[word
& 0x3F];
888 void base64_encode(FILE * fp
, unsigned char *data
, int datalen
)
894 while (datalen
> 0) {
899 n
= (datalen
< 3 ? datalen
: 3);
900 base64_encode_atom(data
, n
, out
);
903 fwrite(out
, 1, 4, fp
);
909 int ssh2_save_userkey(char *filename
, struct ssh2_userkey
*key
,
913 unsigned char *pub_blob
, *priv_blob
, *priv_blob_encrypted
;
914 int pub_blob_len
, priv_blob_len
, priv_encrypted_len
;
919 unsigned char priv_mac
[20];
922 * Fetch the key component blobs.
924 pub_blob
= key
->alg
->public_blob(key
->data
, &pub_blob_len
);
925 priv_blob
= key
->alg
->private_blob(key
->data
, &priv_blob_len
);
926 if (!pub_blob
|| !priv_blob
) {
933 * Determine encryption details, and encrypt the private blob.
936 cipherstr
= "aes256-cbc";
942 priv_encrypted_len
= priv_blob_len
+ cipherblk
- 1;
943 priv_encrypted_len
-= priv_encrypted_len
% cipherblk
;
944 priv_blob_encrypted
= smalloc(priv_encrypted_len
);
945 memset(priv_blob_encrypted
, 0, priv_encrypted_len
);
946 memcpy(priv_blob_encrypted
, priv_blob
, priv_blob_len
);
947 /* Create padding based on the SHA hash of the unpadded blob. This prevents
948 * too easy a known-plaintext attack on the last block. */
949 SHA_Simple(priv_blob
, priv_blob_len
, priv_mac
);
950 assert(priv_encrypted_len
- priv_blob_len
< 20);
951 memcpy(priv_blob_encrypted
+ priv_blob_len
, priv_mac
,
952 priv_encrypted_len
- priv_blob_len
);
954 /* Now create the private MAC. */
957 unsigned char mackey
[20];
958 char header
[] = "putty-private-key-file-mac-key";
960 passlen
= strlen(passphrase
);
963 SHA_Bytes(&s
, header
, sizeof(header
)-1);
964 SHA_Bytes(&s
, passphrase
, passlen
);
965 SHA_Final(&s
, mackey
);
967 hmac_sha1_simple(mackey
, 20,
968 priv_blob_encrypted
, priv_encrypted_len
,
972 memset(mackey
, 0, sizeof(mackey
));
973 memset(&s
, 0, sizeof(s
));
975 SHA_Simple(priv_blob_encrypted
, priv_encrypted_len
, priv_mac
);
983 passlen
= strlen(passphrase
);
986 SHA_Bytes(&s
, "\0\0\0\0", 4);
987 SHA_Bytes(&s
, passphrase
, passlen
);
988 SHA_Final(&s
, key
+ 0);
990 SHA_Bytes(&s
, "\0\0\0\1", 4);
991 SHA_Bytes(&s
, passphrase
, passlen
);
992 SHA_Final(&s
, key
+ 20);
993 aes256_encrypt_pubkey(key
, priv_blob_encrypted
,
996 memset(key
, 0, sizeof(key
));
997 memset(&s
, 0, sizeof(s
));
1000 fp
= fopen(filename
, "w");
1003 fprintf(fp
, "PuTTY-User-Key-File-1: %s\n", key
->alg
->name
);
1004 fprintf(fp
, "Encryption: %s\n", cipherstr
);
1005 fprintf(fp
, "Comment: %s\n", key
->comment
);
1006 fprintf(fp
, "Public-Lines: %d\n", base64_lines(pub_blob_len
));
1007 base64_encode(fp
, pub_blob
, pub_blob_len
);
1008 fprintf(fp
, "Private-Lines: %d\n", base64_lines(priv_encrypted_len
));
1009 base64_encode(fp
, priv_blob_encrypted
, priv_encrypted_len
);
1011 fprintf(fp
, "Private-MAC: ");
1013 fprintf(fp
, "Private-Hash: ");
1014 for (i
= 0; i
< 20; i
++)
1015 fprintf(fp
, "%02x", priv_mac
[i
]);
1021 /* ----------------------------------------------------------------------
1022 * A function to determine which version of SSH to try on a private
1023 * key file. Returns 0 on failure, 1 or 2 on success.
1025 int keyfile_version(char *filename
)
1030 fp
= fopen(filename
, "r");
1036 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
1037 if (i
== 'P') /* "PuTTY-User-Key-File" etc */
1039 return 0; /* unrecognised or EOF */