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
) {
36 unsigned char buf
[16384];
37 unsigned char keybuf
[16];
41 struct MD5Context md5c
;
44 /* Slurp the whole file (minus the header) into a buffer. */
45 len
= fread(buf
, 1, sizeof(buf
), fp
);
47 if (len
< 0 || len
== sizeof(buf
))
48 goto end
; /* file too big or not read */
53 * A zero byte. (The signature includes a terminating NUL.)
55 if (len
-i
< 1 || buf
[i
] != 0)
59 /* One byte giving encryption type, and one reserved uint32. */
63 if (ciphertype
!= 0 && ciphertype
!= SSH_CIPHER_3DES
)
67 goto end
; /* reserved field not present */
68 if (buf
[i
] != 0 || buf
[i
+1] != 0 || buf
[i
+2] != 0 || buf
[i
+3] != 0)
69 goto end
; /* reserved field nonzero, panic! */
72 /* Now the serious stuff. An ordinary SSH 1 public key. */
73 i
+= makekey(buf
+i
, key
, NULL
, 1);
75 goto end
; /* overran */
77 /* Next, the comment field. */
80 if (len
-i
< j
) goto end
;
81 comment
= smalloc(j
+1);
83 memcpy(comment
, buf
+i
, j
);
88 *commentptr
= comment
;
90 key
->comment
= comment
;
92 return ciphertype
!= 0;
96 * Decrypt remainder of buffer.
100 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
101 MD5Final(keybuf
, &md5c
);
102 des3_decrypt_pubkey(keybuf
, buf
+i
, (len
-i
+7)&~7);
103 memset(keybuf
, 0, sizeof(keybuf
)); /* burn the evidence */
107 * We are now in the secret part of the key. The first four
108 * bytes should be of the form a, b, a, b.
110 if (len
-i
< 4) goto end
;
111 if (buf
[i
] != buf
[i
+2] || buf
[i
+1] != buf
[i
+3]) { ret
= -1; goto end
; }
115 * After that, we have one further bignum which is our
116 * decryption exponent, and then the three auxiliary values
119 i
+= makeprivate(buf
+i
, key
);
120 if (len
-i
< 0) goto end
;
121 i
+= ssh1_read_bignum(buf
+i
, &key
->iqmp
);
122 if (len
-i
< 0) goto end
;
123 i
+= ssh1_read_bignum(buf
+i
, &key
->q
);
124 if (len
-i
< 0) goto end
;
125 i
+= ssh1_read_bignum(buf
+i
, &key
->p
);
126 if (len
-i
< 0) goto end
;
128 if (!rsa_verify(key
)) {
135 memset(buf
, 0, sizeof(buf
)); /* burn the evidence */
139 int loadrsakey(char *filename
, struct RSAKey
*key
, char *passphrase
) {
141 unsigned char buf
[64];
143 fp
= fopen(filename
, "rb");
145 return 0; /* doesn't even exist */
148 * Read the first line of the file and see if it's a v1 private
151 if (fgets(buf
, sizeof(buf
), fp
) &&
152 !strcmp(buf
, rsa_signature
)) {
153 return loadrsakey_main(fp
, key
, NULL
, passphrase
);
157 * Otherwise, we have nothing. Return empty-handed.
164 * See whether an RSA key is encrypted. Return its comment field as
167 int rsakey_encrypted(char *filename
, char **comment
) {
169 unsigned char buf
[64];
171 fp
= fopen(filename
, "rb");
173 return 0; /* doesn't even exist */
176 * Read the first line of the file and see if it's a v1 private
179 if (fgets(buf
, sizeof(buf
), fp
) &&
180 !strcmp(buf
, rsa_signature
)) {
181 return loadrsakey_main(fp
, NULL
, comment
, NULL
);
184 return 0; /* wasn't the right kind of file */
188 * Save an RSA key file. Return nonzero on success.
190 int saversakey(char *filename
, struct RSAKey
*key
, char *passphrase
) {
191 unsigned char buf
[16384];
192 unsigned char keybuf
[16];
193 struct MD5Context md5c
;
194 unsigned char *p
, *estart
;
198 * Write the initial signature.
201 memcpy(p
, rsa_signature
, sizeof(rsa_signature
));
202 p
+= sizeof(rsa_signature
);
205 * One byte giving encryption type, and one reserved (zero)
208 *p
++ = (passphrase ? SSH_CIPHER_3DES
: 0);
209 PUT_32BIT(p
, 0); p
+= 4;
212 * An ordinary SSH 1 public key consists of: a uint32
213 * containing the bit count, then two bignums containing the
214 * modulus and exponent respectively.
216 PUT_32BIT(p
, bignum_bitcount(key
->modulus
)); p
+= 4;
217 p
+= ssh1_write_bignum(p
, key
->modulus
);
218 p
+= ssh1_write_bignum(p
, key
->exponent
);
221 * A string containing the comment field.
224 PUT_32BIT(p
, strlen(key
->comment
)); p
+= 4;
225 memcpy(p
, key
->comment
, strlen(key
->comment
));
226 p
+= strlen(key
->comment
);
228 PUT_32BIT(p
, 0); p
+= 4;
232 * The encrypted portion starts here.
237 * Two bytes, then the same two bytes repeated.
239 *p
++ = random_byte();
240 *p
++ = random_byte();
241 p
[0] = p
[-2]; p
[1] = p
[-1]; p
+= 2;
244 * Four more bignums: the decryption exponent, then iqmp, then
247 p
+= ssh1_write_bignum(p
, key
->private_exponent
);
248 p
+= ssh1_write_bignum(p
, key
->iqmp
);
249 p
+= ssh1_write_bignum(p
, key
->q
);
250 p
+= ssh1_write_bignum(p
, key
->p
);
253 * Now write zeros until the encrypted portion is a multiple of
256 while ((p
-estart
) % 8)
260 * Now encrypt the encrypted portion.
264 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
265 MD5Final(keybuf
, &md5c
);
266 des3_encrypt_pubkey(keybuf
, estart
, p
-estart
);
267 memset(keybuf
, 0, sizeof(keybuf
)); /* burn the evidence */
271 * Done. Write the result to the file.
273 fp
= fopen(filename
, "wb");
275 int ret
= (fwrite(buf
, 1, p
-buf
, fp
) == (size_t)(p
-buf
));
276 ret
= ret
&& (fclose(fp
) == 0);
282 /* ----------------------------------------------------------------------
283 * SSH2 private key load/store functions.
287 * PuTTY's own format for SSH2 keys is as follows:
289 * The file is text. Lines are terminated by CRLF, although CR-only
290 * and LF-only are tolerated on input.
292 * The first line says "PuTTY-User-Key-File-1: " plus the name of the
293 * algorithm ("ssh-dss", "ssh-rsa" etc. Although, of course, this
294 * being PuTTY, "ssh-dss" is not supported.)
296 * The next line says "Encryption: " plus an encryption type.
297 * Currently the only supported encryption types are "aes256-cbc"
300 * The next line says "Comment: " plus the comment string.
302 * Next there is a line saying "Public-Lines: " plus a number N.
303 * The following N lines contain a base64 encoding of the public
304 * part of the key. This is encoded as the standard SSH2 public key
305 * blob (with no initial length): so for RSA, for example, it will
312 * Next, there is a line saying "Private-Lines: " plus a number N,
313 * and then N lines containing the (potentially encrypted) private
314 * part of the key. For the key type "ssh-rsa", this will be
317 * mpint private_exponent
318 * mpint p (the larger of the two primes)
319 * mpint q (the smaller prime)
320 * mpint iqmp (the inverse of q modulo p)
321 * data padding (to reach a multiple of the cipher block size)
323 * Finally, there is a line saying "Private-Hash: " plus a hex
324 * representation of a SHA-1 hash of the plaintext version of the
325 * private part, including the final padding.
327 * If the key is encrypted, the encryption key is derived from the
328 * passphrase by means of a succession of SHA-1 hashes. Each hash
331 * uint32 sequence-number
334 * where the sequence-number increases from zero. As many of these
335 * hashes are used as necessary.
337 * NOTE! It is important that all _public_ data can be verified
338 * with reference to the _private_ data. There exist attacks based
339 * on modifying the public key but leaving the private section
342 * With RSA, this is easy: verify that n = p*q, and also verify
343 * that e*d == 1 modulo (p-1)(q-1). With DSA (if we were ever to
344 * support it), we would need to store extra data in the private
345 * section other than just x.
348 static int read_header(FILE *fp
, char *header
) {
354 if (c
== '\n' || c
== '\r' || c
== EOF
)
355 return 0; /* failure */
361 return 1; /* success! */
364 return 0; /* failure */
368 return 0; /* failure */
371 static char *read_body(FILE *fp
) {
378 text
= smalloc(size
);
384 if (c
== '\r' || c
== '\n') {
386 if (c
!= '\r' && c
!= '\n' && c
!= EOF
)
394 if (len
+ 1 > size
) {
396 text
= srealloc(text
, size
);
403 int base64_decode_atom(char *atom
, unsigned char *out
) {
409 for (i
= 0; i
< 4; i
++) {
411 if (c
>= 'A' && c
<= 'Z')
413 else if (c
>= 'a' && c
<= 'z')
415 else if (c
>= '0' && c
<= '9')
424 return 0; /* invalid atom */
428 if (vals
[0] == -1 || vals
[1] == -1)
430 if (vals
[2] == -1 && vals
[3] != -1)
435 else if (vals
[2] != -1)
440 word
= ((vals
[0] << 18) |
442 ((vals
[2] & 0x3F) << 6) |
444 out
[0] = (word
>> 16) & 0xFF;
446 out
[1] = (word
>> 8) & 0xFF;
448 out
[2] = word
& 0xFF;
452 static char *read_blob(FILE *fp
, int nlines
, int *bloblen
) {
458 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
459 blob
= smalloc(48 * nlines
);
461 for (i
= 0; i
< nlines
; i
++) {
462 line
= read_body(fp
);
467 linelen
= strlen(line
);
468 if (linelen
% 4 != 0 || linelen
> 64) {
473 for (j
= 0; j
< linelen
; j
+= 4) {
474 k
= base64_decode_atom(line
+j
, blob
+len
);
489 * Magic error return value for when the passphrase is wrong.
491 struct ssh2_userkey ssh2_wrong_passphrase
= {
495 struct ssh2_userkey
*ssh2_load_userkey(char *filename
, char *passphrase
) {
497 char header
[40], *b
, *comment
, *hash
;
498 const struct ssh_signkey
*alg
;
499 struct ssh2_userkey
*ret
;
500 int cipher
, cipherblk
;
501 unsigned char *public_blob
, *private_blob
;
502 int public_blob_len
, private_blob_len
;
505 ret
= NULL
; /* return NULL for most errors */
506 comment
= hash
= NULL
;
507 public_blob
= private_blob
= NULL
;
509 fp
= fopen(filename
, "rb");
513 /* Read the first header line which contains the key type. */
514 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1"))
516 if ((b
= read_body(fp
)) == NULL
)
518 /* Select key algorithm structure. Currently only ssh-rsa. */
519 if (!strcmp(b
, "ssh-rsa"))
527 /* Read the Encryption header line. */
528 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption"))
530 if ((b
= read_body(fp
)) == NULL
)
532 if (!strcmp(b
, "aes256-cbc")) {
533 cipher
= 1; cipherblk
= 16;
534 } else if (!strcmp(b
, "none")) {
535 cipher
= 0; cipherblk
= 1;
542 /* Read the Comment header line. */
543 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment"))
545 if ((comment
= read_body(fp
)) == NULL
)
548 /* Read the Public-Lines header line and the public blob. */
549 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Public-Lines"))
551 if ((b
= read_body(fp
)) == NULL
)
555 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
558 /* Read the Private-Lines header line and the Private blob. */
559 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Private-Lines"))
561 if ((b
= read_body(fp
)) == NULL
)
565 if ((private_blob
= read_blob(fp
, i
, &private_blob_len
)) == NULL
)
568 /* Read the Private-Hash header line. */
569 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Private-Hash"))
571 if ((hash
= read_body(fp
)) == NULL
)
578 * Decrypt the private blob.
581 unsigned char key
[40];
587 if (private_blob_len
% cipherblk
)
590 passlen
= strlen(passphrase
);
593 SHA_Bytes(&s
, "\0\0\0\0", 4);
594 SHA_Bytes(&s
, passphrase
, passlen
);
595 SHA_Final(&s
, key
+0);
597 SHA_Bytes(&s
, "\0\0\0\1", 4);
598 SHA_Bytes(&s
, passphrase
, passlen
);
599 SHA_Final(&s
, key
+20);
600 aes256_decrypt_pubkey(key
, private_blob
, private_blob_len
);
604 * Verify the private hash.
608 unsigned char binary
[20];
610 SHA_Simple(private_blob
, private_blob_len
, binary
);
611 for (i
= 0; i
< 20; i
++)
612 sprintf(realhash
+2*i
, "%02x", binary
[i
]);
614 if (strcmp(hash
, realhash
)) {
615 /* An incorrect hash is an unconditional Error if the key is
616 * unencrypted. Otherwise, it means Wrong Passphrase. */
617 ret
= cipher ? SSH2_WRONG_PASSPHRASE
: NULL
;
624 * Create and return the key.
626 ret
= smalloc(sizeof(struct ssh2_userkey
));
628 ret
->comment
= comment
;
629 ret
->data
= alg
->createkey(public_blob
, public_blob_len
,
630 private_blob
, private_blob_len
);
645 if (comment
) sfree(comment
);
646 if (hash
) sfree(hash
);
647 if (public_blob
) sfree(public_blob
);
648 if (private_blob
) sfree(private_blob
);
652 char *ssh2_userkey_loadpub(char *filename
, char **algorithm
, int *pub_blob_len
) {
655 const struct ssh_signkey
*alg
;
656 unsigned char *public_blob
;
662 fp
= fopen(filename
, "rb");
666 /* Read the first header line which contains the key type. */
667 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1"))
669 if ((b
= read_body(fp
)) == NULL
)
671 /* Select key algorithm structure. Currently only ssh-rsa. */
672 if (!strcmp(b
, "ssh-rsa"))
680 /* Read the Encryption header line. */
681 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption"))
683 if ((b
= read_body(fp
)) == NULL
)
685 sfree(b
); /* we don't care */
687 /* Read the Comment header line. */
688 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment"))
690 if ((b
= read_body(fp
)) == NULL
)
692 sfree(b
); /* we don't care */
694 /* Read the Public-Lines header line and the public blob. */
695 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Public-Lines"))
697 if ((b
= read_body(fp
)) == NULL
)
701 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
705 *pub_blob_len
= public_blob_len
;
706 *algorithm
= alg
->name
;
714 if (public_blob
) sfree(public_blob
);
718 int ssh2_userkey_encrypted(char *filename
, char **commentptr
) {
720 char header
[40], *b
, *comment
;
723 if (commentptr
) *commentptr
= NULL
;
725 fp
= fopen(filename
, "rb");
728 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1")) {
729 fclose(fp
); return 0;
731 if ((b
= read_body(fp
)) == NULL
) {
732 fclose(fp
); return 0;
734 sfree(b
); /* we don't care about key type here */
735 /* Read the Encryption header line. */
736 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption")) {
737 fclose(fp
); return 0;
739 if ((b
= read_body(fp
)) == NULL
) {
740 fclose(fp
); return 0;
743 /* Read the Comment header line. */
744 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment")) {
745 fclose(fp
); sfree(b
); return 1;
747 if ((comment
= read_body(fp
)) == NULL
) {
748 fclose(fp
); sfree(b
); return 1;
751 if (commentptr
) *commentptr
= comment
;
754 if (!strcmp(b
, "aes256-cbc"))
762 int base64_lines(int datalen
) {
763 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
764 return (datalen
+47) / 48;
767 void base64_encode_atom(unsigned char *data
, int n
, char *out
) {
768 static const char base64_chars
[] =
769 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
773 word
= data
[0] << 16;
775 word
|= data
[1] << 8;
778 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
779 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
781 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
785 out
[3] = base64_chars
[word
& 0x3F];
790 void base64_encode(FILE *fp
, unsigned char *data
, int datalen
) {
795 while (datalen
> 0) {
800 n
= (datalen
< 3 ? datalen
: 3);
801 base64_encode_atom(data
, n
, out
);
804 fwrite(out
, 1, 4, fp
);
810 int ssh2_save_userkey(char *filename
, struct ssh2_userkey
*key
, char *passphrase
) {
812 unsigned char *pub_blob
, *priv_blob
, *priv_blob_encrypted
;
813 int pub_blob_len
, priv_blob_len
, priv_encrypted_len
;
818 unsigned char priv_hash
[20];
821 * Fetch the key component blobs.
823 pub_blob
= key
->alg
->public_blob(key
->data
, &pub_blob_len
);
824 priv_blob
= key
->alg
->private_blob(key
->data
, &priv_blob_len
);
825 if (!pub_blob
|| !priv_blob
) {
832 * Determine encryption details, and encrypt the private blob.
835 cipherstr
= "aes256-cbc";
841 priv_encrypted_len
= priv_blob_len
+ cipherblk
- 1;
842 priv_encrypted_len
-= priv_encrypted_len
% cipherblk
;
843 priv_blob_encrypted
= smalloc(priv_encrypted_len
);
844 memset(priv_blob_encrypted
, 0, priv_encrypted_len
);
845 memcpy(priv_blob_encrypted
, priv_blob
, priv_blob_len
);
846 /* Create padding based on the SHA hash of the unpadded blob. This prevents
847 * too easy a known-plaintext attack on the last block. */
848 SHA_Simple(priv_blob
, priv_blob_len
, priv_hash
);
849 assert(priv_encrypted_len
- priv_blob_len
< 20);
850 memcpy(priv_blob_encrypted
+ priv_blob_len
, priv_hash
,
851 priv_encrypted_len
- priv_blob_len
);
853 /* Now create the _real_ private hash. */
854 SHA_Simple(priv_blob_encrypted
, priv_encrypted_len
, priv_hash
);
860 passlen
= strlen(passphrase
);
863 SHA_Bytes(&s
, "\0\0\0\0", 4);
864 SHA_Bytes(&s
, passphrase
, passlen
);
865 SHA_Final(&s
, key
+0);
867 SHA_Bytes(&s
, "\0\0\0\1", 4);
868 SHA_Bytes(&s
, passphrase
, passlen
);
869 SHA_Final(&s
, key
+20);
870 aes256_encrypt_pubkey(key
, priv_blob_encrypted
, priv_encrypted_len
);
873 fp
= fopen(filename
, "w");
876 fprintf(fp
, "PuTTY-User-Key-File-1: %s\n", key
->alg
->name
);
877 fprintf(fp
, "Encryption: %s\n", cipherstr
);
878 fprintf(fp
, "Comment: %s\n", key
->comment
);
879 fprintf(fp
, "Public-Lines: %d\n", base64_lines(pub_blob_len
));
880 base64_encode(fp
, pub_blob
, pub_blob_len
);
881 fprintf(fp
, "Private-Lines: %d\n", base64_lines(priv_encrypted_len
));
882 base64_encode(fp
, priv_blob_encrypted
, priv_encrypted_len
);
883 fprintf(fp
, "Private-Hash: ");
884 for (i
= 0; i
< 20; i
++)
885 fprintf(fp
, "%02x", priv_hash
[i
]);
891 /* ----------------------------------------------------------------------
892 * A function to determine which version of SSH to try on a private
893 * key file. Returns 0 on failure, 1 or 2 on success.
895 int keyfile_version(char *filename
) {
899 fp
= fopen(filename
, "r");
905 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
906 if (i
== 'P') /* "PuTTY-User-Key-File" etc */
908 return 0; /* unrecognised or EOF */