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
;
130 memset(buf
, 0, sizeof(buf
)); /* burn the evidence */
134 int loadrsakey(char *filename
, struct RSAKey
*key
, char *passphrase
) {
136 unsigned char buf
[64];
138 fp
= fopen(filename
, "rb");
140 return 0; /* doesn't even exist */
143 * Read the first line of the file and see if it's a v1 private
146 if (fgets(buf
, sizeof(buf
), fp
) &&
147 !strcmp(buf
, rsa_signature
)) {
148 return loadrsakey_main(fp
, key
, NULL
, passphrase
);
152 * Otherwise, we have nothing. Return empty-handed.
159 * See whether an RSA key is encrypted. Return its comment field as
162 int rsakey_encrypted(char *filename
, char **comment
) {
164 unsigned char buf
[64];
166 fp
= fopen(filename
, "rb");
168 return 0; /* doesn't even exist */
171 * Read the first line of the file and see if it's a v1 private
174 if (fgets(buf
, sizeof(buf
), fp
) &&
175 !strcmp(buf
, rsa_signature
)) {
176 return loadrsakey_main(fp
, NULL
, comment
, NULL
);
179 return 0; /* wasn't the right kind of file */
183 * Save an RSA key file. Return nonzero on success.
185 int saversakey(char *filename
, struct RSAKey
*key
, char *passphrase
) {
186 unsigned char buf
[16384];
187 unsigned char keybuf
[16];
188 struct MD5Context md5c
;
189 unsigned char *p
, *estart
;
193 * Write the initial signature.
196 memcpy(p
, rsa_signature
, sizeof(rsa_signature
));
197 p
+= sizeof(rsa_signature
);
200 * One byte giving encryption type, and one reserved (zero)
203 *p
++ = (passphrase ? SSH_CIPHER_3DES
: 0);
204 PUT_32BIT(p
, 0); p
+= 4;
207 * An ordinary SSH 1 public key consists of: a uint32
208 * containing the bit count, then two bignums containing the
209 * modulus and exponent respectively.
211 PUT_32BIT(p
, ssh1_bignum_bitcount(key
->modulus
)); p
+= 4;
212 p
+= ssh1_write_bignum(p
, key
->modulus
);
213 p
+= ssh1_write_bignum(p
, key
->exponent
);
216 * A string containing the comment field.
219 PUT_32BIT(p
, strlen(key
->comment
)); p
+= 4;
220 memcpy(p
, key
->comment
, strlen(key
->comment
));
221 p
+= strlen(key
->comment
);
223 PUT_32BIT(p
, 0); p
+= 4;
227 * The encrypted portion starts here.
232 * Two bytes, then the same two bytes repeated.
234 *p
++ = random_byte();
235 *p
++ = random_byte();
236 p
[0] = p
[-2]; p
[1] = p
[-1]; p
+= 2;
239 * Four more bignums: the decryption exponent, then iqmp, then
242 p
+= ssh1_write_bignum(p
, key
->private_exponent
);
243 p
+= ssh1_write_bignum(p
, key
->iqmp
);
244 p
+= ssh1_write_bignum(p
, key
->q
);
245 p
+= ssh1_write_bignum(p
, key
->p
);
248 * Now write zeros until the encrypted portion is a multiple of
251 while ((p
-estart
) % 8)
255 * Now encrypt the encrypted portion.
259 MD5Update(&md5c
, passphrase
, strlen(passphrase
));
260 MD5Final(keybuf
, &md5c
);
261 des3_encrypt_pubkey(keybuf
, estart
, p
-estart
);
262 memset(keybuf
, 0, sizeof(keybuf
)); /* burn the evidence */
266 * Done. Write the result to the file.
268 fp
= fopen(filename
, "wb");
270 int ret
= (fwrite(buf
, 1, p
-buf
, fp
) == (size_t)(p
-buf
));
271 ret
= ret
&& (fclose(fp
) == 0);
277 /* ----------------------------------------------------------------------
278 * SSH2 private key load/store functions.
282 * PuTTY's own format for SSH2 keys is as follows:
284 * The file is text. Lines are terminated by CRLF, although CR-only
285 * and LF-only are tolerated on input.
287 * The first line says "PuTTY-User-Key-File-1: " plus the name of the
288 * algorithm ("ssh-dss", "ssh-rsa" etc. Although, of course, this
289 * being PuTTY, "ssh-dss" is not supported.)
291 * The next line says "Encryption: " plus an encryption type.
292 * Currently the only supported encryption types are "aes256-cbc"
295 * The next line says "Comment: " plus the comment string.
297 * Next there is a line saying "Public-Lines: " plus a number N.
298 * The following N lines contain a base64 encoding of the public
299 * part of the key. This is encoded as the standard SSH2 public key
300 * blob (with no initial length): so for RSA, for example, it will
307 * Next, there is a line saying "Private-Lines: " plus a number N,
308 * and then N lines containing the (potentially encrypted) private
309 * part of the key. For the key type "ssh-rsa", this will be
312 * mpint private_exponent
313 * mpint p (the larger of the two primes)
314 * mpint q (the smaller prime)
315 * mpint iqmp (the inverse of q modulo p)
316 * data padding (to reach a multiple of the cipher block size)
318 * Finally, there is a line saying "Private-Hash: " plus a hex
319 * representation of a SHA-1 hash of the plaintext version of the
320 * private part, including the final padding.
322 * If the key is encrypted, the encryption key is derived from the
323 * passphrase by means of a succession of SHA-1 hashes. Each hash
326 * uint32 sequence-number
329 * where the sequence-number increases from zero. As many of these
330 * hashes are used as necessary.
333 static int read_header(FILE *fp
, char *header
) {
339 if (c
== '\n' || c
== '\r' || c
== EOF
)
340 return 0; /* failure */
346 return 1; /* success! */
349 return 0; /* failure */
353 return 0; /* failure */
356 static char *read_body(FILE *fp
) {
363 text
= smalloc(size
);
369 if (c
== '\r' || c
== '\n') {
371 if (c
!= '\r' && c
!= '\n' && c
!= EOF
)
379 if (len
+ 1 > size
) {
381 text
= srealloc(text
, size
);
388 int base64_decode_atom(char *atom
, unsigned char *out
) {
394 for (i
= 0; i
< 4; i
++) {
396 if (c
>= 'A' && c
<= 'Z')
398 else if (c
>= 'a' && c
<= 'z')
400 else if (c
>= '0' && c
<= '9')
409 return 0; /* invalid atom */
413 if (vals
[0] == -1 || vals
[1] == -1)
415 if (vals
[2] == -1 && vals
[3] != -1)
420 else if (vals
[2] != -1)
425 word
= ((vals
[0] << 18) |
427 ((vals
[2] & 0x3F) << 6) |
429 out
[0] = (word
>> 16) & 0xFF;
431 out
[1] = (word
>> 8) & 0xFF;
433 out
[2] = word
& 0xFF;
437 static char *read_blob(FILE *fp
, int nlines
, int *bloblen
) {
443 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
444 blob
= smalloc(48 * nlines
);
446 for (i
= 0; i
< nlines
; i
++) {
447 line
= read_body(fp
);
452 linelen
= strlen(line
);
453 if (linelen
% 4 != 0 || linelen
> 64) {
458 for (j
= 0; j
< linelen
; j
+= 4) {
459 k
= base64_decode_atom(line
+j
, blob
+len
);
474 * Magic error return value for when the passphrase is wrong.
476 struct ssh2_userkey ssh2_wrong_passphrase
= {
480 struct ssh2_userkey
*ssh2_load_userkey(char *filename
, char *passphrase
) {
482 char header
[40], *b
, *comment
, *hash
;
483 const struct ssh_signkey
*alg
;
484 struct ssh2_userkey
*ret
;
485 int cipher
, cipherblk
;
486 unsigned char *public_blob
, *private_blob
;
487 int public_blob_len
, private_blob_len
;
490 ret
= NULL
; /* return NULL for most errors */
491 comment
= hash
= NULL
;
492 public_blob
= private_blob
= NULL
;
494 fp
= fopen(filename
, "rb");
498 /* Read the first header line which contains the key type. */
499 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1"))
501 if ((b
= read_body(fp
)) == NULL
)
503 /* Select key algorithm structure. Currently only ssh-rsa. */
504 if (!strcmp(b
, "ssh-rsa"))
512 /* Read the Encryption header line. */
513 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption"))
515 if ((b
= read_body(fp
)) == NULL
)
517 if (!strcmp(b
, "aes256-cbc")) {
518 cipher
= 1; cipherblk
= 16;
519 } else if (!strcmp(b
, "none")) {
520 cipher
= 0; cipherblk
= 1;
527 /* Read the Comment header line. */
528 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment"))
530 if ((comment
= read_body(fp
)) == NULL
)
533 /* Read the Public-Lines header line and the public blob. */
534 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Public-Lines"))
536 if ((b
= read_body(fp
)) == NULL
)
540 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
543 /* Read the Private-Lines header line and the Private blob. */
544 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Private-Lines"))
546 if ((b
= read_body(fp
)) == NULL
)
550 if ((private_blob
= read_blob(fp
, i
, &private_blob_len
)) == NULL
)
553 /* Read the Private-Hash header line. */
554 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Private-Hash"))
556 if ((hash
= read_body(fp
)) == NULL
)
563 * Decrypt the private blob.
566 unsigned char key
[40];
572 if (private_blob_len
% cipherblk
)
575 passlen
= strlen(passphrase
);
578 SHA_Bytes(&s
, "\0\0\0\0", 4);
579 SHA_Bytes(&s
, passphrase
, passlen
);
580 SHA_Final(&s
, key
+0);
582 SHA_Bytes(&s
, "\0\0\0\1", 4);
583 SHA_Bytes(&s
, passphrase
, passlen
);
584 SHA_Final(&s
, key
+20);
585 aes256_decrypt_pubkey(key
, private_blob
, private_blob_len
);
589 * Verify the private hash.
593 unsigned char binary
[20];
596 SHA_Simple(private_blob
, private_blob_len
, binary
);
597 for (i
= 0; i
< 20; i
++)
598 sprintf(realhash
+2*i
, "%02x", binary
[i
]);
600 if (strcmp(hash
, realhash
)) {
601 /* An incorrect hash is an unconditional Error if the key is
602 * unencrypted. Otherwise, it means Wrong Passphrase. */
603 ret
= cipher ? SSH2_WRONG_PASSPHRASE
: NULL
;
610 * Create and return the key.
612 ret
= smalloc(sizeof(struct ssh2_userkey
));
614 ret
->comment
= comment
;
615 ret
->data
= alg
->createkey(public_blob
, public_blob_len
,
616 private_blob
, private_blob_len
);
626 if (comment
) sfree(comment
);
627 if (hash
) sfree(hash
);
628 if (public_blob
) sfree(public_blob
);
629 if (private_blob
) sfree(private_blob
);
633 char *ssh2_userkey_loadpub(char *filename
, char **algorithm
, int *pub_blob_len
) {
636 const struct ssh_signkey
*alg
;
637 int cipher
, cipherblk
;
638 unsigned char *public_blob
;
644 fp
= fopen(filename
, "rb");
648 /* Read the first header line which contains the key type. */
649 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1"))
651 if ((b
= read_body(fp
)) == NULL
)
653 /* Select key algorithm structure. Currently only ssh-rsa. */
654 if (!strcmp(b
, "ssh-rsa"))
662 /* Read the Encryption header line. */
663 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption"))
665 if ((b
= read_body(fp
)) == NULL
)
667 sfree(b
); /* we don't care */
669 /* Read the Comment header line. */
670 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment"))
672 if ((b
= read_body(fp
)) == NULL
)
674 sfree(b
); /* we don't care */
676 /* Read the Public-Lines header line and the public blob. */
677 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Public-Lines"))
679 if ((b
= read_body(fp
)) == NULL
)
683 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
687 *pub_blob_len
= public_blob_len
;
688 *algorithm
= alg
->name
;
696 if (public_blob
) sfree(public_blob
);
700 int ssh2_userkey_encrypted(char *filename
, char **commentptr
) {
702 char header
[40], *b
, *comment
;
705 if (commentptr
) *commentptr
= NULL
;
707 fp
= fopen(filename
, "rb");
710 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1")) {
711 fclose(fp
); return 0;
713 if ((b
= read_body(fp
)) == NULL
) {
714 fclose(fp
); return 0;
716 sfree(b
); /* we don't care about key type here */
717 /* Read the Encryption header line. */
718 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption")) {
719 fclose(fp
); return 0;
721 if ((b
= read_body(fp
)) == NULL
) {
722 fclose(fp
); return 0;
725 /* Read the Comment header line. */
726 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment")) {
727 fclose(fp
); sfree(b
); return 1;
729 if ((comment
= read_body(fp
)) == NULL
) {
730 fclose(fp
); sfree(b
); return 1;
733 if (commentptr
) *commentptr
= comment
;
736 if (!strcmp(b
, "aes256-cbc"))
744 int base64_lines(int datalen
) {
745 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
746 return (datalen
+47) / 48;
749 void base64_encode_atom(unsigned char *data
, int n
, char *out
) {
750 static const char base64_chars
[] =
751 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
755 word
= data
[0] << 16;
757 word
|= data
[1] << 8;
760 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
761 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
763 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
767 out
[3] = base64_chars
[word
& 0x3F];
772 void base64_encode(FILE *fp
, unsigned char *data
, int datalen
) {
777 while (datalen
> 0) {
782 n
= (datalen
< 3 ? datalen
: 3);
783 base64_encode_atom(data
, n
, out
);
786 fwrite(out
, 1, 4, fp
);
792 int ssh2_save_userkey(char *filename
, struct ssh2_userkey
*key
, char *passphrase
) {
794 unsigned char *pub_blob
, *priv_blob
, *priv_blob_encrypted
;
795 int pub_blob_len
, priv_blob_len
, priv_encrypted_len
;
800 unsigned char priv_hash
[20];
803 * Fetch the key component blobs.
805 pub_blob
= key
->alg
->public_blob(key
->data
, &pub_blob_len
);
806 priv_blob
= key
->alg
->private_blob(key
->data
, &priv_blob_len
);
807 if (!pub_blob
|| !priv_blob
) {
814 * Determine encryption details, and encrypt the private blob.
817 cipherstr
= "aes256-cbc";
823 priv_encrypted_len
= priv_blob_len
+ cipherblk
- 1;
824 priv_encrypted_len
-= priv_encrypted_len
% cipherblk
;
825 priv_blob_encrypted
= smalloc(priv_encrypted_len
);
826 memset(priv_blob_encrypted
, 0, priv_encrypted_len
);
827 memcpy(priv_blob_encrypted
, priv_blob
, priv_blob_len
);
828 /* Create padding based on the SHA hash of the unpadded blob. This prevents
829 * too easy a known-plaintext attack on the last block. */
830 SHA_Simple(priv_blob
, priv_blob_len
, priv_hash
);
831 assert(priv_encrypted_len
- priv_blob_len
< 20);
832 memcpy(priv_blob_encrypted
+ priv_blob_len
, priv_hash
,
833 priv_encrypted_len
- priv_blob_len
);
835 /* Now create the _real_ private hash. */
836 SHA_Simple(priv_blob_encrypted
, priv_encrypted_len
, priv_hash
);
842 passlen
= strlen(passphrase
);
845 SHA_Bytes(&s
, "\0\0\0\0", 4);
846 SHA_Bytes(&s
, passphrase
, passlen
);
847 SHA_Final(&s
, key
+0);
849 SHA_Bytes(&s
, "\0\0\0\1", 4);
850 SHA_Bytes(&s
, passphrase
, passlen
);
851 SHA_Final(&s
, key
+20);
852 aes256_encrypt_pubkey(key
, priv_blob_encrypted
, priv_encrypted_len
);
855 fp
= fopen(filename
, "w");
858 fprintf(fp
, "PuTTY-User-Key-File-1: %s\n", key
->alg
->name
);
859 fprintf(fp
, "Encryption: %s\n", cipherstr
);
860 fprintf(fp
, "Comment: %s\n", key
->comment
);
861 fprintf(fp
, "Public-Lines: %d\n", base64_lines(pub_blob_len
));
862 base64_encode(fp
, pub_blob
, pub_blob_len
);
863 fprintf(fp
, "Private-Lines: %d\n", base64_lines(priv_encrypted_len
));
864 base64_encode(fp
, priv_blob_encrypted
, priv_encrypted_len
);
865 fprintf(fp
, "Private-Hash: ");
866 for (i
= 0; i
< 20; i
++)
867 fprintf(fp
, "%02x", priv_hash
[i
]);
873 /* ----------------------------------------------------------------------
874 * A function to determine which version of SSH to try on a private
875 * key file. Returns 0 on failure, 1 or 2 on success.
877 int keyfile_version(char *filename
) {
881 fp
= fopen(filename
, "r");
887 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
888 if (i
== 'P') /* "PuTTY-User-Key-File" etc */
890 return 0; /* unrecognised or EOF */