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];
595 SHA_Simple(private_blob
, private_blob_len
, binary
);
596 for (i
= 0; i
< 20; i
++)
597 sprintf(realhash
+2*i
, "%02x", binary
[i
]);
599 if (strcmp(hash
, realhash
)) {
600 /* An incorrect hash is an unconditional Error if the key is
601 * unencrypted. Otherwise, it means Wrong Passphrase. */
602 ret
= cipher ? SSH2_WRONG_PASSPHRASE
: NULL
;
609 * Create and return the key.
611 ret
= smalloc(sizeof(struct ssh2_userkey
));
613 ret
->comment
= comment
;
614 ret
->data
= alg
->createkey(public_blob
, public_blob_len
,
615 private_blob
, private_blob_len
);
625 if (comment
) sfree(comment
);
626 if (hash
) sfree(hash
);
627 if (public_blob
) sfree(public_blob
);
628 if (private_blob
) sfree(private_blob
);
632 char *ssh2_userkey_loadpub(char *filename
, char **algorithm
, int *pub_blob_len
) {
635 const struct ssh_signkey
*alg
;
636 unsigned char *public_blob
;
642 fp
= fopen(filename
, "rb");
646 /* Read the first header line which contains the key type. */
647 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1"))
649 if ((b
= read_body(fp
)) == NULL
)
651 /* Select key algorithm structure. Currently only ssh-rsa. */
652 if (!strcmp(b
, "ssh-rsa"))
660 /* Read the Encryption header line. */
661 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption"))
663 if ((b
= read_body(fp
)) == NULL
)
665 sfree(b
); /* we don't care */
667 /* Read the Comment header line. */
668 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment"))
670 if ((b
= read_body(fp
)) == NULL
)
672 sfree(b
); /* we don't care */
674 /* Read the Public-Lines header line and the public blob. */
675 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Public-Lines"))
677 if ((b
= read_body(fp
)) == NULL
)
681 if ((public_blob
= read_blob(fp
, i
, &public_blob_len
)) == NULL
)
685 *pub_blob_len
= public_blob_len
;
686 *algorithm
= alg
->name
;
694 if (public_blob
) sfree(public_blob
);
698 int ssh2_userkey_encrypted(char *filename
, char **commentptr
) {
700 char header
[40], *b
, *comment
;
703 if (commentptr
) *commentptr
= NULL
;
705 fp
= fopen(filename
, "rb");
708 if (!read_header(fp
, header
) || 0!=strcmp(header
, "PuTTY-User-Key-File-1")) {
709 fclose(fp
); return 0;
711 if ((b
= read_body(fp
)) == NULL
) {
712 fclose(fp
); return 0;
714 sfree(b
); /* we don't care about key type here */
715 /* Read the Encryption header line. */
716 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Encryption")) {
717 fclose(fp
); return 0;
719 if ((b
= read_body(fp
)) == NULL
) {
720 fclose(fp
); return 0;
723 /* Read the Comment header line. */
724 if (!read_header(fp
, header
) || 0!=strcmp(header
, "Comment")) {
725 fclose(fp
); sfree(b
); return 1;
727 if ((comment
= read_body(fp
)) == NULL
) {
728 fclose(fp
); sfree(b
); return 1;
731 if (commentptr
) *commentptr
= comment
;
734 if (!strcmp(b
, "aes256-cbc"))
742 int base64_lines(int datalen
) {
743 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
744 return (datalen
+47) / 48;
747 void base64_encode_atom(unsigned char *data
, int n
, char *out
) {
748 static const char base64_chars
[] =
749 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
753 word
= data
[0] << 16;
755 word
|= data
[1] << 8;
758 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
759 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
761 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
765 out
[3] = base64_chars
[word
& 0x3F];
770 void base64_encode(FILE *fp
, unsigned char *data
, int datalen
) {
775 while (datalen
> 0) {
780 n
= (datalen
< 3 ? datalen
: 3);
781 base64_encode_atom(data
, n
, out
);
784 fwrite(out
, 1, 4, fp
);
790 int ssh2_save_userkey(char *filename
, struct ssh2_userkey
*key
, char *passphrase
) {
792 unsigned char *pub_blob
, *priv_blob
, *priv_blob_encrypted
;
793 int pub_blob_len
, priv_blob_len
, priv_encrypted_len
;
798 unsigned char priv_hash
[20];
801 * Fetch the key component blobs.
803 pub_blob
= key
->alg
->public_blob(key
->data
, &pub_blob_len
);
804 priv_blob
= key
->alg
->private_blob(key
->data
, &priv_blob_len
);
805 if (!pub_blob
|| !priv_blob
) {
812 * Determine encryption details, and encrypt the private blob.
815 cipherstr
= "aes256-cbc";
821 priv_encrypted_len
= priv_blob_len
+ cipherblk
- 1;
822 priv_encrypted_len
-= priv_encrypted_len
% cipherblk
;
823 priv_blob_encrypted
= smalloc(priv_encrypted_len
);
824 memset(priv_blob_encrypted
, 0, priv_encrypted_len
);
825 memcpy(priv_blob_encrypted
, priv_blob
, priv_blob_len
);
826 /* Create padding based on the SHA hash of the unpadded blob. This prevents
827 * too easy a known-plaintext attack on the last block. */
828 SHA_Simple(priv_blob
, priv_blob_len
, priv_hash
);
829 assert(priv_encrypted_len
- priv_blob_len
< 20);
830 memcpy(priv_blob_encrypted
+ priv_blob_len
, priv_hash
,
831 priv_encrypted_len
- priv_blob_len
);
833 /* Now create the _real_ private hash. */
834 SHA_Simple(priv_blob_encrypted
, priv_encrypted_len
, priv_hash
);
840 passlen
= strlen(passphrase
);
843 SHA_Bytes(&s
, "\0\0\0\0", 4);
844 SHA_Bytes(&s
, passphrase
, passlen
);
845 SHA_Final(&s
, key
+0);
847 SHA_Bytes(&s
, "\0\0\0\1", 4);
848 SHA_Bytes(&s
, passphrase
, passlen
);
849 SHA_Final(&s
, key
+20);
850 aes256_encrypt_pubkey(key
, priv_blob_encrypted
, priv_encrypted_len
);
853 fp
= fopen(filename
, "w");
856 fprintf(fp
, "PuTTY-User-Key-File-1: %s\n", key
->alg
->name
);
857 fprintf(fp
, "Encryption: %s\n", cipherstr
);
858 fprintf(fp
, "Comment: %s\n", key
->comment
);
859 fprintf(fp
, "Public-Lines: %d\n", base64_lines(pub_blob_len
));
860 base64_encode(fp
, pub_blob
, pub_blob_len
);
861 fprintf(fp
, "Private-Lines: %d\n", base64_lines(priv_encrypted_len
));
862 base64_encode(fp
, priv_blob_encrypted
, priv_encrypted_len
);
863 fprintf(fp
, "Private-Hash: ");
864 for (i
= 0; i
< 20; i
++)
865 fprintf(fp
, "%02x", priv_hash
[i
]);
871 /* ----------------------------------------------------------------------
872 * A function to determine which version of SSH to try on a private
873 * key file. Returns 0 on failure, 1 or 2 on success.
875 int keyfile_version(char *filename
) {
879 fp
= fopen(filename
, "r");
885 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
886 if (i
== 'P') /* "PuTTY-User-Key-File" etc */
888 return 0; /* unrecognised or EOF */