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).
15 #define PUT_32BIT(cp, value) do { \
17 (cp)[2] = (value) >> 8; \
18 (cp)[1] = (value) >> 16; \
19 (cp)[0] = (value) >> 24; } while (0)
21 #define GET_32BIT(cp) \
22 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
23 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
24 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
25 ((unsigned long)(unsigned char)(cp)[3]))
27 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
29 #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
30 (x)-'a'<26 ? (x)-'a'+26 :\
31 (x)-'0'<10 ? (x)-'0'+52 :\
35 static int loadrsakey_main(FILE * fp, struct RSAKey *key,
36 char **commentptr, char *passphrase)
38 unsigned char buf[16384];
39 unsigned char keybuf[16];
43 struct MD5Context md5c;
46 /* Slurp the whole file (minus the header) into a buffer. */
47 len = fread(buf, 1, sizeof(buf), fp);
49 if (len < 0 || len == sizeof(buf))
50 goto end; /* file too big or not read */
55 * A zero byte. (The signature includes a terminating NUL.)
57 if (len - i < 1 || buf[i] != 0)
61 /* One byte giving encryption type, and one reserved uint32. */
65 if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
69 goto end; /* reserved field not present */
70 if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
71 || buf[i + 3] != 0) goto end; /* reserved field nonzero, panic! */
74 /* Now the serious stuff. An ordinary SSH 1 public key. */
75 i += makekey(buf + i, key, NULL, 1);
77 goto end; /* overran */
79 /* Next, the comment field. */
80 j = GET_32BIT(buf + i);
84 comment = smalloc(j + 1);
86 memcpy(comment, buf + i, j);
91 *commentptr = comment;
93 key->comment = comment;
95 return ciphertype != 0;
99 * Decrypt remainder of buffer.
103 MD5Update(&md5c, passphrase, strlen(passphrase));
104 MD5Final(keybuf, &md5c);
105 des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
106 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
110 * We are now in the secret part of the key. The first four
111 * bytes should be of the form a, b, a, b.
115 if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
122 * After that, we have one further bignum which is our
123 * decryption exponent, and then the three auxiliary values
126 i += makeprivate(buf + i, key);
129 i += ssh1_read_bignum(buf + i, &key->iqmp);
132 i += ssh1_read_bignum(buf + i, &key->q);
135 i += ssh1_read_bignum(buf + i, &key->p);
139 if (!rsa_verify(key)) {
146 memset(buf, 0, sizeof(buf)); /* burn the evidence */
150 int loadrsakey(char *filename, struct RSAKey *key, char *passphrase)
153 unsigned char buf[64];
155 fp = fopen(filename, "rb");
157 return 0; /* doesn't even exist */
160 * Read the first line of the file and see if it's a v1 private
163 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
164 return loadrsakey_main(fp, key, NULL, passphrase);
168 * Otherwise, we have nothing. Return empty-handed.
175 * See whether an RSA key is encrypted. Return its comment field as
178 int rsakey_encrypted(char *filename, char **comment)
181 unsigned char buf[64];
183 fp = fopen(filename, "rb");
185 return 0; /* doesn't even exist */
188 * Read the first line of the file and see if it's a v1 private
191 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
192 return loadrsakey_main(fp, NULL, comment, NULL);
195 return 0; /* wasn't the right kind of file */
199 * Save an RSA key file. Return nonzero on success.
201 int saversakey(char *filename, struct RSAKey *key, char *passphrase)
203 unsigned char buf[16384];
204 unsigned char keybuf[16];
205 struct MD5Context md5c;
206 unsigned char *p, *estart;
210 * Write the initial signature.
213 memcpy(p, rsa_signature, sizeof(rsa_signature));
214 p += sizeof(rsa_signature);
217 * One byte giving encryption type, and one reserved (zero)
220 *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
225 * An ordinary SSH 1 public key consists of: a uint32
226 * containing the bit count, then two bignums containing the
227 * modulus and exponent respectively.
229 PUT_32BIT(p, bignum_bitcount(key->modulus));
231 p += ssh1_write_bignum(p, key->modulus);
232 p += ssh1_write_bignum(p, key->exponent);
235 * A string containing the comment field.
238 PUT_32BIT(p, strlen(key->comment));
240 memcpy(p, key->comment, strlen(key->comment));
241 p += strlen(key->comment);
248 * The encrypted portion starts here.
253 * Two bytes, then the same two bytes repeated.
255 *p++ = random_byte();
256 *p++ = random_byte();
262 * Four more bignums: the decryption exponent, then iqmp, then
265 p += ssh1_write_bignum(p, key->private_exponent);
266 p += ssh1_write_bignum(p, key->iqmp);
267 p += ssh1_write_bignum(p, key->q);
268 p += ssh1_write_bignum(p, key->p);
271 * Now write zeros until the encrypted portion is a multiple of
274 while ((p - estart) % 8)
278 * Now encrypt the encrypted portion.
282 MD5Update(&md5c, passphrase, strlen(passphrase));
283 MD5Final(keybuf, &md5c);
284 des3_encrypt_pubkey(keybuf, estart, p - estart);
285 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
289 * Done. Write the result to the file.
291 fp = fopen(filename, "wb");
293 int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
294 ret = ret && (fclose(fp) == 0);
300 /* ----------------------------------------------------------------------
301 * SSH2 private key load/store functions.
305 * PuTTY's own format for SSH2 keys is as follows:
307 * The file is text. Lines are terminated by CRLF, although CR-only
308 * and LF-only are tolerated on input.
310 * The first line says "PuTTY-User-Key-File-2: " plus the name of the
311 * algorithm ("ssh-dss", "ssh-rsa" etc).
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 * And for "ssh-dss", it will be composed of
342 * mpint x (the private key parameter)
343 * [ string hash 20-byte hash of mpints p || q || g only in old format ]
345 * Finally, there is a line saying "Private-MAC: " plus a hex
346 * representation of a HMAC-SHA-1 of:
348 * string name of algorithm ("ssh-dss", "ssh-rsa")
349 * string encryption type
352 * string private-plaintext (the plaintext version of the
353 * private part, including the final
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 * For backwards compatibility with snapshots between 0.51 and
375 * 0.52, we also support the older key file format, which begins
376 * with "PuTTY-User-Key-File-1" (version number differs). In this
377 * format the Private-MAC: field only covers the private-plaintext
378 * field and nothing else (and without the 4-byte string length on
379 * the front too). Moreover, for RSA keys the Private-MAC: field
380 * can be replaced with a Private-Hash: field which is a plain
381 * SHA-1 hash instead of an HMAC. This is not allowable in DSA
382 * keys. (Yes, the old format was a mess. Guess why it changed :-)
385 static int read_header(FILE * fp, char *header)
392 if (c == '\n' || c == '\r' || c == EOF)
393 return 0; /* failure */
399 return 1; /* success! */
402 return 0; /* failure */
406 return 0; /* failure */
409 static char *read_body(FILE * fp)
417 text = smalloc(size);
423 if (c == '\r' || c == '\n') {
425 if (c != '\r' && c != '\n' && c != EOF)
433 if (len + 1 > size) {
435 text = srealloc(text, size);
442 int base64_decode_atom(char *atom, unsigned char *out)
449 for (i = 0; i < 4; i++) {
451 if (c >= 'A' && c <= 'Z')
453 else if (c >= 'a' && c <= 'z')
455 else if (c >= '0' && c <= '9')
464 return 0; /* invalid atom */
468 if (vals[0] == -1 || vals[1] == -1)
470 if (vals[2] == -1 && vals[3] != -1)
475 else if (vals[2] != -1)
480 word = ((vals[0] << 18) |
481 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
482 out[0] = (word >> 16) & 0xFF;
484 out[1] = (word >> 8) & 0xFF;
486 out[2] = word & 0xFF;
490 static char *read_blob(FILE * fp, int nlines, int *bloblen)
497 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
498 blob = smalloc(48 * nlines);
500 for (i = 0; i < nlines; i++) {
501 line = read_body(fp);
506 linelen = strlen(line);
507 if (linelen % 4 != 0 || linelen > 64) {
512 for (j = 0; j < linelen; j += 4) {
513 k = base64_decode_atom(line + j, blob + len);
528 * Magic error return value for when the passphrase is wrong.
530 struct ssh2_userkey ssh2_wrong_passphrase = {
534 struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase)
537 char header[40], *b, *encryption, *comment, *mac;
538 const struct ssh_signkey *alg;
539 struct ssh2_userkey *ret;
540 int cipher, cipherblk;
541 unsigned char *public_blob, *private_blob;
542 int public_blob_len, private_blob_len;
543 int i, is_mac, old_fmt;
544 int passlen = passphrase ? strlen(passphrase) : 0;
546 ret = NULL; /* return NULL for most errors */
547 comment = mac = NULL;
548 public_blob = private_blob = NULL;
550 fp = fopen(filename, "rb");
554 /* Read the first header line which contains the key type. */
555 if (!read_header(fp, header))
557 if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
559 } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
560 /* this is an old key file; warn and then continue */
561 old_keyfile_warning();
565 if ((b = read_body(fp)) == NULL)
567 /* Select key algorithm structure. */
568 if (!strcmp(b, "ssh-rsa"))
570 else if (!strcmp(b, "ssh-dss"))
578 /* Read the Encryption header line. */
579 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
581 if ((encryption = read_body(fp)) == NULL)
583 if (!strcmp(encryption, "aes256-cbc")) {
586 } else if (!strcmp(encryption, "none")) {
594 /* Read the Comment header line. */
595 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
597 if ((comment = read_body(fp)) == NULL)
600 /* Read the Public-Lines header line and the public blob. */
601 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
603 if ((b = read_body(fp)) == NULL)
607 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
610 /* Read the Private-Lines header line and the Private blob. */
611 if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
613 if ((b = read_body(fp)) == NULL)
617 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
620 /* Read the Private-MAC or Private-Hash header line. */
621 if (!read_header(fp, header))
623 if (0 == strcmp(header, "Private-MAC")) {
624 if ((mac = read_body(fp)) == NULL)
627 } else if (0 == strcmp(header, "Private-Hash") &&
628 alg == &ssh_rsa && old_fmt) {
629 if ((mac = read_body(fp)) == NULL)
639 * Decrypt the private blob.
642 unsigned char key[40];
647 if (private_blob_len % cipherblk)
651 SHA_Bytes(&s, "\0\0\0\0", 4);
652 SHA_Bytes(&s, passphrase, passlen);
653 SHA_Final(&s, key + 0);
655 SHA_Bytes(&s, "\0\0\0\1", 4);
656 SHA_Bytes(&s, passphrase, passlen);
657 SHA_Final(&s, key + 20);
658 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
666 unsigned char binary[20];
667 unsigned char *macdata;
672 /* MAC (or hash) only covers the private blob. */
673 macdata = private_blob;
674 maclen = private_blob_len;
678 int namelen = strlen(alg->name);
679 int enclen = strlen(encryption);
680 int commlen = strlen(comment);
681 maclen = (4 + namelen +
684 4 + public_blob_len +
685 4 + private_blob_len);
686 macdata = smalloc(maclen);
688 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
689 DO_STR(alg->name, namelen);
690 DO_STR(encryption, enclen);
691 DO_STR(comment, commlen);
692 DO_STR(public_blob, public_blob_len);
693 DO_STR(private_blob, private_blob_len);
700 unsigned char mackey[20];
701 char header[] = "putty-private-key-file-mac-key";
704 SHA_Bytes(&s, header, sizeof(header)-1);
706 SHA_Bytes(&s, passphrase, passlen);
707 SHA_Final(&s, mackey);
709 hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
711 memset(mackey, 0, sizeof(mackey));
712 memset(&s, 0, sizeof(s));
714 SHA_Simple(macdata, maclen, binary);
718 memset(macdata, 0, maclen);
722 for (i = 0; i < 20; i++)
723 sprintf(realmac + 2 * i, "%02x", binary[i]);
725 if (strcmp(mac, realmac)) {
726 /* An incorrect MAC is an unconditional Error if the key is
727 * unencrypted. Otherwise, it means Wrong Passphrase. */
728 ret = cipher ? SSH2_WRONG_PASSPHRASE : NULL;
735 * Create and return the key.
737 ret = smalloc(sizeof(struct ssh2_userkey));
739 ret->comment = comment;
740 ret->data = alg->createkey(public_blob, public_blob_len,
741 private_blob, private_blob_len);
771 char *ssh2_userkey_loadpub(char *filename, char **algorithm,
776 const struct ssh_signkey *alg;
777 unsigned char *public_blob;
783 fp = fopen(filename, "rb");
787 /* Read the first header line which contains the key type. */
788 if (!read_header(fp, header)
789 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
790 0 != strcmp(header, "PuTTY-User-Key-File-1")))
792 if ((b = read_body(fp)) == NULL)
794 /* Select key algorithm structure. Currently only ssh-rsa. */
795 if (!strcmp(b, "ssh-rsa"))
797 else if (!strcmp(b, "ssh-dss"))
805 /* Read the Encryption header line. */
806 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
808 if ((b = read_body(fp)) == NULL)
810 sfree(b); /* we don't care */
812 /* Read the Comment header line. */
813 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
815 if ((b = read_body(fp)) == NULL)
817 sfree(b); /* we don't care */
819 /* Read the Public-Lines header line and the public blob. */
820 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
822 if ((b = read_body(fp)) == NULL)
826 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
830 *pub_blob_len = public_blob_len;
831 *algorithm = alg->name;
845 int ssh2_userkey_encrypted(char *filename, char **commentptr)
848 char header[40], *b, *comment;
854 fp = fopen(filename, "rb");
857 if (!read_header(fp, header)
858 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
859 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
863 if ((b = read_body(fp)) == NULL) {
867 sfree(b); /* we don't care about key type here */
868 /* Read the Encryption header line. */
869 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
873 if ((b = read_body(fp)) == NULL) {
878 /* Read the Comment header line. */
879 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
884 if ((comment = read_body(fp)) == NULL) {
891 *commentptr = comment;
894 if (!strcmp(b, "aes256-cbc"))
902 int base64_lines(int datalen)
904 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
905 return (datalen + 47) / 48;
908 void base64_encode_atom(unsigned char *data, int n, char *out)
910 static const char base64_chars[] =
911 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
915 word = data[0] << 16;
917 word |= data[1] << 8;
920 out[0] = base64_chars[(word >> 18) & 0x3F];
921 out[1] = base64_chars[(word >> 12) & 0x3F];
923 out[2] = base64_chars[(word >> 6) & 0x3F];
927 out[3] = base64_chars[word & 0x3F];
932 void base64_encode(FILE * fp, unsigned char *data, int datalen)
938 while (datalen > 0) {
943 n = (datalen < 3 ? datalen : 3);
944 base64_encode_atom(data, n, out);
947 fwrite(out, 1, 4, fp);
953 int ssh2_save_userkey(char *filename, struct ssh2_userkey *key,
957 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
958 int pub_blob_len, priv_blob_len, priv_encrypted_len;
963 unsigned char priv_mac[20];
966 * Fetch the key component blobs.
968 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
969 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
970 if (!pub_blob || !priv_blob) {
977 * Determine encryption details, and encrypt the private blob.
980 cipherstr = "aes256-cbc";
986 priv_encrypted_len = priv_blob_len + cipherblk - 1;
987 priv_encrypted_len -= priv_encrypted_len % cipherblk;
988 priv_blob_encrypted = smalloc(priv_encrypted_len);
989 memset(priv_blob_encrypted, 0, priv_encrypted_len);
990 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
991 /* Create padding based on the SHA hash of the unpadded blob. This prevents
992 * too easy a known-plaintext attack on the last block. */
993 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
994 assert(priv_encrypted_len - priv_blob_len < 20);
995 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
996 priv_encrypted_len - priv_blob_len);
998 /* Now create the MAC. */
1000 unsigned char *macdata;
1003 int namelen = strlen(key->alg->name);
1004 int enclen = strlen(cipherstr);
1005 int commlen = strlen(key->comment);
1007 unsigned char mackey[20];
1008 char header[] = "putty-private-key-file-mac-key";
1010 maclen = (4 + namelen +
1014 4 + priv_encrypted_len);
1015 macdata = smalloc(maclen);
1017 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1018 DO_STR(key->alg->name, namelen);
1019 DO_STR(cipherstr, enclen);
1020 DO_STR(key->comment, commlen);
1021 DO_STR(pub_blob, pub_blob_len);
1022 DO_STR(priv_blob_encrypted, priv_encrypted_len);
1025 SHA_Bytes(&s, header, sizeof(header)-1);
1027 SHA_Bytes(&s, passphrase, strlen(passphrase));
1028 SHA_Final(&s, mackey);
1029 hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1030 memset(macdata, 0, maclen);
1032 memset(mackey, 0, sizeof(mackey));
1033 memset(&s, 0, sizeof(s));
1040 passlen = strlen(passphrase);
1043 SHA_Bytes(&s, "\0\0\0\0", 4);
1044 SHA_Bytes(&s, passphrase, passlen);
1045 SHA_Final(&s, key + 0);
1047 SHA_Bytes(&s, "\0\0\0\1", 4);
1048 SHA_Bytes(&s, passphrase, passlen);
1049 SHA_Final(&s, key + 20);
1050 aes256_encrypt_pubkey(key, priv_blob_encrypted,
1051 priv_encrypted_len);
1053 memset(key, 0, sizeof(key));
1054 memset(&s, 0, sizeof(s));
1057 fp = fopen(filename, "w");
1060 fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
1061 fprintf(fp, "Encryption: %s\n", cipherstr);
1062 fprintf(fp, "Comment: %s\n", key->comment);
1063 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1064 base64_encode(fp, pub_blob, pub_blob_len);
1065 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1066 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len);
1067 fprintf(fp, "Private-MAC: ");
1068 for (i = 0; i < 20; i++)
1069 fprintf(fp, "%02x", priv_mac[i]);
1074 memset(priv_blob, 0, priv_blob_len);
1076 sfree(priv_blob_encrypted);
1080 /* ----------------------------------------------------------------------
1081 * A function to determine which version of SSH to try on a private
1082 * key file. Returns 0 on failure, 1 or 2 on success.
1084 int keyfile_version(char *filename)
1089 fp = fopen(filename, "r");
1095 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
1096 if (i == 'P') /* "PuTTY-User-Key-File" etc */
1098 return 0; /* unrecognised or EOF */