2 * Generic SSH public-key handling operations. In particular,
3 * reading of SSH public-key files, and also the generic `sign'
4 * operation for SSH-2 (which checks the type of the key and
5 * dispatches to the appropriate key-type specific function).
16 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
18 #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
19 (x)-'a'<26 ? (x)-'a'+26 :\
20 (x)-'0'<10 ? (x)-'0'+52 :\
24 static int key_type_fp(FILE *fp);
26 static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only,
27 char **commentptr, const char *passphrase,
30 unsigned char buf[16384];
31 unsigned char keybuf[16];
35 struct MD5Context md5c;
40 /* Slurp the whole file (minus the header) into a buffer. */
41 len = fread(buf, 1, sizeof(buf), fp);
43 if (len < 0 || len == sizeof(buf)) {
44 *error = "error reading file";
45 goto end; /* file too big or not read */
49 *error = "file format error";
52 * A zero byte. (The signature includes a terminating NUL.)
54 if (len - i < 1 || buf[i] != 0)
58 /* One byte giving encryption type, and one reserved uint32. */
62 if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
66 goto end; /* reserved field not present */
67 if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
68 || buf[i + 3] != 0) goto end; /* reserved field nonzero, panic! */
71 /* Now the serious stuff. An ordinary SSH-1 public key. */
72 j = makekey(buf + i, len - i, key, NULL, 1);
74 goto end; /* overran */
77 /* Next, the comment field. */
78 j = toint(GET_32BIT(buf + i));
80 if (j < 0 || len - i < j)
82 comment = snewn(j + 1, char);
84 memcpy(comment, buf + i, j);
89 *commentptr = dupstr(comment);
91 key->comment = comment;
101 ret = ciphertype != 0;
107 * Decrypt remainder of buffer.
111 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
112 MD5Final(keybuf, &md5c);
113 des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
114 smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
118 * We are now in the secret part of the key. The first four
119 * bytes should be of the form a, b, a, b.
123 if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
124 *error = "wrong passphrase";
131 * After that, we have one further bignum which is our
132 * decryption exponent, and then the three auxiliary values
135 j = makeprivate(buf + i, len - i, key);
138 j = ssh1_read_bignum(buf + i, len - i, &key->iqmp);
141 j = ssh1_read_bignum(buf + i, len - i, &key->q);
144 j = ssh1_read_bignum(buf + i, len - i, &key->p);
148 if (!rsa_verify(key)) {
149 *error = "rsa_verify failed";
156 smemclr(buf, sizeof(buf)); /* burn the evidence */
160 int loadrsakey(const Filename *filename, struct RSAKey *key,
161 const char *passphrase, const char **errorstr)
166 const char *error = NULL;
168 fp = f_open(filename, "rb", FALSE);
170 error = "can't open file";
175 * Read the first line of the file and see if it's a v1 private
178 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
180 * This routine will take care of calling fclose() for us.
182 ret = loadrsakey_main(fp, key, FALSE, NULL, passphrase, &error);
188 * Otherwise, we have nothing. Return empty-handed.
190 error = "not an SSH-1 RSA file";
195 if ((ret != 1) && errorstr)
201 * See whether an RSA key is encrypted. Return its comment field as
204 int rsakey_encrypted(const Filename *filename, char **comment)
209 fp = f_open(filename, "rb", FALSE);
211 return 0; /* doesn't even exist */
214 * Read the first line of the file and see if it's a v1 private
217 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
220 * This routine will take care of calling fclose() for us.
222 return loadrsakey_main(fp, NULL, FALSE, comment, NULL, &dummy);
225 return 0; /* wasn't the right kind of file */
229 * Return a malloc'ed chunk of memory containing the public blob of
230 * an RSA key, as given in the agent protocol (modulus bits,
231 * exponent, modulus).
233 int rsakey_pubblob(const Filename *filename, void **blob, int *bloblen,
234 char **commentptr, const char **errorstr)
240 const char *error = NULL;
242 /* Default return if we fail. */
247 fp = f_open(filename, "rb", FALSE);
249 error = "can't open file";
254 * Read the first line of the file and see if it's a v1 private
257 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
258 memset(&key, 0, sizeof(key));
259 if (loadrsakey_main(fp, &key, TRUE, commentptr, NULL, &error)) {
260 *blob = rsa_public_blob(&key, bloblen);
264 fp = NULL; /* loadrsakey_main unconditionally closes fp */
267 * Try interpreting the file as an SSH-1 public key.
269 char *line, *p, *bitsp, *expp, *modp, *commentp;
272 line = chomp(fgetline(fp));
276 p += strspn(p, "0123456789");
278 goto not_public_either;
282 p += strspn(p, "0123456789");
284 goto not_public_either;
288 p += strspn(p, "0123456789");
291 goto not_public_either;
298 memset(&key, 0, sizeof(key));
299 key.exponent = bignum_from_decimal(expp);
300 key.modulus = bignum_from_decimal(modp);
301 if (atoi(bitsp) != bignum_bitcount(key.modulus)) {
302 freebn(key.exponent);
305 error = "key bit count does not match in SSH-1 public key file";
309 *commentptr = commentp ? dupstr(commentp) : NULL;
310 *blob = rsa_public_blob(&key, bloblen);
317 error = "not an SSH-1 RSA file";
323 if ((ret != 1) && errorstr)
329 * Save an RSA key file. Return nonzero on success.
331 int saversakey(const Filename *filename, struct RSAKey *key, char *passphrase)
333 unsigned char buf[16384];
334 unsigned char keybuf[16];
335 struct MD5Context md5c;
336 unsigned char *p, *estart;
340 * Write the initial signature.
343 memcpy(p, rsa_signature, sizeof(rsa_signature));
344 p += sizeof(rsa_signature);
347 * One byte giving encryption type, and one reserved (zero)
350 *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
355 * An ordinary SSH-1 public key consists of: a uint32
356 * containing the bit count, then two bignums containing the
357 * modulus and exponent respectively.
359 PUT_32BIT(p, bignum_bitcount(key->modulus));
361 p += ssh1_write_bignum(p, key->modulus);
362 p += ssh1_write_bignum(p, key->exponent);
365 * A string containing the comment field.
368 PUT_32BIT(p, strlen(key->comment));
370 memcpy(p, key->comment, strlen(key->comment));
371 p += strlen(key->comment);
378 * The encrypted portion starts here.
383 * Two bytes, then the same two bytes repeated.
385 *p++ = random_byte();
386 *p++ = random_byte();
392 * Four more bignums: the decryption exponent, then iqmp, then
395 p += ssh1_write_bignum(p, key->private_exponent);
396 p += ssh1_write_bignum(p, key->iqmp);
397 p += ssh1_write_bignum(p, key->q);
398 p += ssh1_write_bignum(p, key->p);
401 * Now write zeros until the encrypted portion is a multiple of
404 while ((p - estart) % 8)
408 * Now encrypt the encrypted portion.
412 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
413 MD5Final(keybuf, &md5c);
414 des3_encrypt_pubkey(keybuf, estart, p - estart);
415 smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
419 * Done. Write the result to the file.
421 fp = f_open(filename, "wb", TRUE);
423 int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
431 /* ----------------------------------------------------------------------
432 * SSH-2 private key load/store functions.
436 * PuTTY's own format for SSH-2 keys is as follows:
438 * The file is text. Lines are terminated by CRLF, although CR-only
439 * and LF-only are tolerated on input.
441 * The first line says "PuTTY-User-Key-File-2: " plus the name of the
442 * algorithm ("ssh-dss", "ssh-rsa" etc).
444 * The next line says "Encryption: " plus an encryption type.
445 * Currently the only supported encryption types are "aes256-cbc"
448 * The next line says "Comment: " plus the comment string.
450 * Next there is a line saying "Public-Lines: " plus a number N.
451 * The following N lines contain a base64 encoding of the public
452 * part of the key. This is encoded as the standard SSH-2 public key
453 * blob (with no initial length): so for RSA, for example, it will
460 * Next, there is a line saying "Private-Lines: " plus a number N,
461 * and then N lines containing the (potentially encrypted) private
462 * part of the key. For the key type "ssh-rsa", this will be
465 * mpint private_exponent
466 * mpint p (the larger of the two primes)
467 * mpint q (the smaller prime)
468 * mpint iqmp (the inverse of q modulo p)
469 * data padding (to reach a multiple of the cipher block size)
471 * And for "ssh-dss", it will be composed of
473 * mpint x (the private key parameter)
474 * [ string hash 20-byte hash of mpints p || q || g only in old format ]
476 * Finally, there is a line saying "Private-MAC: " plus a hex
477 * representation of a HMAC-SHA-1 of:
479 * string name of algorithm ("ssh-dss", "ssh-rsa")
480 * string encryption type
483 * string private-plaintext (the plaintext version of the
484 * private part, including the final
487 * The key to the MAC is itself a SHA-1 hash of:
489 * data "putty-private-key-file-mac-key"
492 * (An empty passphrase is used for unencrypted keys.)
494 * If the key is encrypted, the encryption key is derived from the
495 * passphrase by means of a succession of SHA-1 hashes. Each hash
498 * uint32 sequence-number
501 * where the sequence-number increases from zero. As many of these
502 * hashes are used as necessary.
504 * For backwards compatibility with snapshots between 0.51 and
505 * 0.52, we also support the older key file format, which begins
506 * with "PuTTY-User-Key-File-1" (version number differs). In this
507 * format the Private-MAC: field only covers the private-plaintext
508 * field and nothing else (and without the 4-byte string length on
509 * the front too). Moreover, the Private-MAC: field can be replaced
510 * with a Private-Hash: field which is a plain SHA-1 hash instead of
511 * an HMAC (this was generated for unencrypted keys).
514 static int read_header(FILE * fp, char *header)
521 if (c == '\n' || c == '\r' || c == EOF)
522 return 0; /* failure */
528 return 1; /* success! */
531 return 0; /* failure */
535 return 0; /* failure */
538 static char *read_body(FILE * fp)
546 text = snewn(size, char);
552 if (c == '\r' || c == '\n' || c == EOF) {
555 if (c != '\r' && c != '\n')
560 if (len + 1 >= size) {
562 text = sresize(text, size, char);
569 static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)
576 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
577 blob = snewn(48 * nlines, unsigned char);
579 for (i = 0; i < nlines; i++) {
580 line = read_body(fp);
585 linelen = strlen(line);
586 if (linelen % 4 != 0 || linelen > 64) {
591 for (j = 0; j < linelen; j += 4) {
592 k = base64_decode_atom(line + j, blob + len);
607 * Magic error return value for when the passphrase is wrong.
609 struct ssh2_userkey ssh2_wrong_passphrase = {
613 const struct ssh_signkey *find_pubkey_alg_len(int namelen, const char *name)
615 if (match_ssh_id(namelen, name, "ssh-rsa"))
617 else if (match_ssh_id(namelen, name, "ssh-dss"))
619 else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp256"))
620 return &ssh_ecdsa_nistp256;
621 else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp384"))
622 return &ssh_ecdsa_nistp384;
623 else if (match_ssh_id(namelen, name, "ecdsa-sha2-nistp521"))
624 return &ssh_ecdsa_nistp521;
625 else if (match_ssh_id(namelen, name, "ssh-ed25519"))
626 return &ssh_ecdsa_ed25519;
631 const struct ssh_signkey *find_pubkey_alg(const char *name)
633 return find_pubkey_alg_len(strlen(name), name);
636 struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,
637 const char *passphrase,
638 const char **errorstr)
641 char header[40], *b, *encryption, *comment, *mac;
642 const struct ssh_signkey *alg;
643 struct ssh2_userkey *ret;
644 int cipher, cipherblk;
645 unsigned char *public_blob, *private_blob;
646 int public_blob_len, private_blob_len;
647 int i, is_mac, old_fmt;
648 int passlen = passphrase ? strlen(passphrase) : 0;
649 const char *error = NULL;
651 ret = NULL; /* return NULL for most errors */
652 encryption = comment = mac = NULL;
653 public_blob = private_blob = NULL;
655 fp = f_open(filename, "rb", FALSE);
657 error = "can't open file";
661 /* Read the first header line which contains the key type. */
662 if (!read_header(fp, header))
664 if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
666 } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
667 /* this is an old key file; warn and then continue */
668 old_keyfile_warning();
670 } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
671 /* this is a key file FROM THE FUTURE; refuse it, but with a
672 * more specific error message than the generic one below */
673 error = "PuTTY key format too new";
676 error = "not a PuTTY SSH-2 private key";
679 error = "file format error";
680 if ((b = read_body(fp)) == NULL)
682 /* Select key algorithm structure. */
683 alg = find_pubkey_alg(b);
690 /* Read the Encryption header line. */
691 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
693 if ((encryption = read_body(fp)) == NULL)
695 if (!strcmp(encryption, "aes256-cbc")) {
698 } else if (!strcmp(encryption, "none")) {
705 /* Read the Comment header line. */
706 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
708 if ((comment = read_body(fp)) == NULL)
711 /* Read the Public-Lines header line and the public blob. */
712 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
714 if ((b = read_body(fp)) == NULL)
718 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
721 /* Read the Private-Lines header line and the Private blob. */
722 if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
724 if ((b = read_body(fp)) == NULL)
728 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
731 /* Read the Private-MAC or Private-Hash header line. */
732 if (!read_header(fp, header))
734 if (0 == strcmp(header, "Private-MAC")) {
735 if ((mac = read_body(fp)) == NULL)
738 } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {
739 if ((mac = read_body(fp)) == NULL)
749 * Decrypt the private blob.
752 unsigned char key[40];
757 if (private_blob_len % cipherblk)
761 SHA_Bytes(&s, "\0\0\0\0", 4);
762 SHA_Bytes(&s, passphrase, passlen);
763 SHA_Final(&s, key + 0);
765 SHA_Bytes(&s, "\0\0\0\1", 4);
766 SHA_Bytes(&s, passphrase, passlen);
767 SHA_Final(&s, key + 20);
768 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
776 unsigned char binary[20];
777 unsigned char *macdata;
782 /* MAC (or hash) only covers the private blob. */
783 macdata = private_blob;
784 maclen = private_blob_len;
788 int namelen = strlen(alg->name);
789 int enclen = strlen(encryption);
790 int commlen = strlen(comment);
791 maclen = (4 + namelen +
794 4 + public_blob_len +
795 4 + private_blob_len);
796 macdata = snewn(maclen, unsigned char);
798 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
799 DO_STR(alg->name, namelen);
800 DO_STR(encryption, enclen);
801 DO_STR(comment, commlen);
802 DO_STR(public_blob, public_blob_len);
803 DO_STR(private_blob, private_blob_len);
810 unsigned char mackey[20];
811 char header[] = "putty-private-key-file-mac-key";
814 SHA_Bytes(&s, header, sizeof(header)-1);
815 if (cipher && passphrase)
816 SHA_Bytes(&s, passphrase, passlen);
817 SHA_Final(&s, mackey);
819 hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
821 smemclr(mackey, sizeof(mackey));
822 smemclr(&s, sizeof(s));
824 SHA_Simple(macdata, maclen, binary);
828 smemclr(macdata, maclen);
832 for (i = 0; i < 20; i++)
833 sprintf(realmac + 2 * i, "%02x", binary[i]);
835 if (strcmp(mac, realmac)) {
836 /* An incorrect MAC is an unconditional Error if the key is
837 * unencrypted. Otherwise, it means Wrong Passphrase. */
839 error = "wrong passphrase";
840 ret = SSH2_WRONG_PASSPHRASE;
842 error = "MAC failed";
852 * Create and return the key.
854 ret = snew(struct ssh2_userkey);
856 ret->comment = comment;
857 ret->data = alg->createkey(alg, public_blob, public_blob_len,
858 private_blob, private_blob_len);
862 error = "createkey failed";
866 smemclr(private_blob, private_blob_len);
888 smemclr(private_blob, private_blob_len);
896 unsigned char *rfc4716_loadpub(FILE *fp, char **algorithm,
897 int *pub_blob_len, char **commentptr,
898 const char **errorstr)
901 char *line, *colon, *value;
902 char *comment = NULL;
903 unsigned char *pubblob = NULL;
904 int pubbloblen, pubblobsize;
906 unsigned char base64out[3];
910 line = chomp(fgetline(fp));
911 if (!line || 0 != strcmp(line, "---- BEGIN SSH2 PUBLIC KEY ----")) {
912 error = "invalid begin line in SSH-2 public key file";
915 sfree(line); line = NULL;
918 line = chomp(fgetline(fp));
920 error = "truncated SSH-2 public key file";
923 colon = strstr(line, ": ");
929 if (!strcmp(line, "Comment")) {
932 /* Remove containing double quotes, if present */
934 if (*p == '"' && p[strlen(p)-1] == '"') {
935 p[strlen(p)-1] = '\0';
939 /* Remove \-escaping, not in RFC4716 but seen in the wild
941 for (q = line; *p; p++) {
942 if (*p == '\\' && p[1])
948 comment = dupstr(line);
949 } else if (!strcmp(line, "Subject") ||
950 !strncmp(line, "x-", 2)) {
951 /* Headers we recognise and ignore. Do nothing. */
953 error = "unrecognised header in SSH-2 public key file";
957 sfree(line); line = NULL;
961 * Now line contains the initial line of base64 data. Loop round
962 * while it still does contain base64.
965 pubblob = snewn(pubblobsize, unsigned char);
968 while (line && line[0] != '-') {
970 for (p = line; *p; p++) {
971 base64in[base64bytes++] = *p;
972 if (base64bytes == 4) {
973 int n = base64_decode_atom(base64in, base64out);
974 if (pubbloblen + n > pubblobsize) {
975 pubblobsize = (pubbloblen + n) * 5 / 4 + 1024;
976 pubblob = sresize(pubblob, pubblobsize, unsigned char);
978 memcpy(pubblob + pubbloblen, base64out, n);
983 sfree(line); line = NULL;
984 line = chomp(fgetline(fp));
988 * Finally, check the END line makes sense.
990 if (!line || 0 != strcmp(line, "---- END SSH2 PUBLIC KEY ----")) {
991 error = "invalid end line in SSH-2 public key file";
994 sfree(line); line = NULL;
997 * OK, we now have a public blob and optionally a comment. We must
998 * return the key algorithm string too, so look for that at the
999 * start of the public blob.
1001 if (pubbloblen < 4) {
1002 error = "not enough data in SSH-2 public key file";
1005 alglen = toint(GET_32BIT(pubblob));
1006 if (alglen < 0 || alglen > pubbloblen-4) {
1007 error = "invalid algorithm prefix in SSH-2 public key file";
1011 *algorithm = dupprintf("%.*s", alglen, pubblob+4);
1013 *pub_blob_len = pubbloblen;
1015 *commentptr = comment;
1029 unsigned char *openssh_loadpub(FILE *fp, char **algorithm,
1030 int *pub_blob_len, char **commentptr,
1031 const char **errorstr)
1034 char *line, *base64;
1035 char *comment = NULL;
1036 unsigned char *pubblob = NULL;
1037 int pubbloblen, pubblobsize;
1040 line = chomp(fgetline(fp));
1042 base64 = strchr(line, ' ');
1044 error = "no key blob in OpenSSH public key file";
1049 comment = strchr(base64, ' ');
1052 comment = dupstr(comment);
1055 pubblobsize = strlen(base64) / 4 * 3;
1056 pubblob = snewn(pubblobsize, unsigned char);
1059 while (!memchr(base64, '\0', 4)) {
1060 assert(pubbloblen + 3 <= pubblobsize);
1061 pubbloblen += base64_decode_atom(base64, pubblob + pubbloblen);
1065 error = "invalid length for base64 data in OpenSSH public key file";
1070 * Sanity check: the first word on the line should be the key
1071 * algorithm, and should match the encoded string at the start of
1074 alglen = strlen(line);
1075 if (pubbloblen < alglen + 4 ||
1076 GET_32BIT(pubblob) != alglen ||
1077 0 != memcmp(pubblob + 4, line, alglen)) {
1078 error = "key algorithms do not match in OpenSSH public key file";
1086 *algorithm = dupstr(line);
1088 *pub_blob_len = pubbloblen;
1090 *commentptr = comment;
1104 unsigned char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
1105 int *pub_blob_len, char **commentptr,
1106 const char **errorstr)
1109 char header[40], *b;
1110 const struct ssh_signkey *alg;
1111 unsigned char *public_blob;
1112 int public_blob_len;
1114 const char *error = NULL;
1115 char *comment = NULL;
1119 fp = f_open(filename, "rb", FALSE);
1121 error = "can't open file";
1125 /* Initially, check if this is a public-only key file. Sometimes
1126 * we'll be asked to read a public blob from one of those. */
1127 type = key_type_fp(fp);
1128 if (type == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
1129 unsigned char *ret = rfc4716_loadpub(fp, algorithm, pub_blob_len,
1130 commentptr, errorstr);
1133 } else if (type == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
1134 unsigned char *ret = openssh_loadpub(fp, algorithm, pub_blob_len,
1135 commentptr, errorstr);
1138 } else if (type != SSH_KEYTYPE_SSH2) {
1139 error = "not a PuTTY SSH-2 private key";
1143 /* Read the first header line which contains the key type. */
1144 if (!read_header(fp, header)
1145 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
1146 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
1147 if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
1148 error = "PuTTY key format too new";
1150 error = "not a PuTTY SSH-2 private key";
1153 error = "file format error";
1154 if ((b = read_body(fp)) == NULL)
1156 /* Select key algorithm structure. */
1157 alg = find_pubkey_alg(b);
1163 /* Read the Encryption header line. */
1164 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
1166 if ((b = read_body(fp)) == NULL)
1168 sfree(b); /* we don't care */
1170 /* Read the Comment header line. */
1171 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
1173 if ((comment = read_body(fp)) == NULL)
1177 *commentptr = comment;
1181 /* Read the Public-Lines header line and the public blob. */
1182 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
1184 if ((b = read_body(fp)) == NULL)
1188 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
1193 *pub_blob_len = public_blob_len;
1195 *algorithm = dupstr(alg->name);
1208 if (comment && commentptr) {
1215 int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
1218 char header[40], *b, *comment;
1224 fp = f_open(filename, "rb", FALSE);
1227 if (!read_header(fp, header)
1228 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
1229 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
1233 if ((b = read_body(fp)) == NULL) {
1237 sfree(b); /* we don't care about key type here */
1238 /* Read the Encryption header line. */
1239 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
1243 if ((b = read_body(fp)) == NULL) {
1248 /* Read the Comment header line. */
1249 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
1254 if ((comment = read_body(fp)) == NULL) {
1261 *commentptr = comment;
1266 if (!strcmp(b, "aes256-cbc"))
1274 int base64_lines(int datalen)
1276 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
1277 return (datalen + 47) / 48;
1280 void base64_encode(FILE *fp, const unsigned char *data, int datalen, int cpl)
1286 while (datalen > 0) {
1287 n = (datalen < 3 ? datalen : 3);
1288 base64_encode_atom(data, n, out);
1291 for (i = 0; i < 4; i++) {
1292 if (linelen >= cpl) {
1303 int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
1307 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1308 int pub_blob_len, priv_blob_len, priv_encrypted_len;
1312 const char *cipherstr;
1313 unsigned char priv_mac[20];
1316 * Fetch the key component blobs.
1318 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1319 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1320 if (!pub_blob || !priv_blob) {
1327 * Determine encryption details, and encrypt the private blob.
1330 cipherstr = "aes256-cbc";
1336 priv_encrypted_len = priv_blob_len + cipherblk - 1;
1337 priv_encrypted_len -= priv_encrypted_len % cipherblk;
1338 priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
1339 memset(priv_blob_encrypted, 0, priv_encrypted_len);
1340 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1341 /* Create padding based on the SHA hash of the unpadded blob. This prevents
1342 * too easy a known-plaintext attack on the last block. */
1343 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
1344 assert(priv_encrypted_len - priv_blob_len < 20);
1345 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
1346 priv_encrypted_len - priv_blob_len);
1348 /* Now create the MAC. */
1350 unsigned char *macdata;
1353 int namelen = strlen(key->alg->name);
1354 int enclen = strlen(cipherstr);
1355 int commlen = strlen(key->comment);
1357 unsigned char mackey[20];
1358 char header[] = "putty-private-key-file-mac-key";
1360 maclen = (4 + namelen +
1364 4 + priv_encrypted_len);
1365 macdata = snewn(maclen, unsigned char);
1367 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1368 DO_STR(key->alg->name, namelen);
1369 DO_STR(cipherstr, enclen);
1370 DO_STR(key->comment, commlen);
1371 DO_STR(pub_blob, pub_blob_len);
1372 DO_STR(priv_blob_encrypted, priv_encrypted_len);
1375 SHA_Bytes(&s, header, sizeof(header)-1);
1377 SHA_Bytes(&s, passphrase, strlen(passphrase));
1378 SHA_Final(&s, mackey);
1379 hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1380 smemclr(macdata, maclen);
1382 smemclr(mackey, sizeof(mackey));
1383 smemclr(&s, sizeof(s));
1387 unsigned char key[40];
1390 passlen = strlen(passphrase);
1393 SHA_Bytes(&s, "\0\0\0\0", 4);
1394 SHA_Bytes(&s, passphrase, passlen);
1395 SHA_Final(&s, key + 0);
1397 SHA_Bytes(&s, "\0\0\0\1", 4);
1398 SHA_Bytes(&s, passphrase, passlen);
1399 SHA_Final(&s, key + 20);
1400 aes256_encrypt_pubkey(key, priv_blob_encrypted,
1401 priv_encrypted_len);
1403 smemclr(key, sizeof(key));
1404 smemclr(&s, sizeof(s));
1407 fp = f_open(filename, "w", TRUE);
1410 smemclr(priv_blob, priv_blob_len);
1412 smemclr(priv_blob_encrypted, priv_blob_len);
1413 sfree(priv_blob_encrypted);
1416 fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
1417 fprintf(fp, "Encryption: %s\n", cipherstr);
1418 fprintf(fp, "Comment: %s\n", key->comment);
1419 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1420 base64_encode(fp, pub_blob, pub_blob_len, 64);
1421 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1422 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
1423 fprintf(fp, "Private-MAC: ");
1424 for (i = 0; i < 20; i++)
1425 fprintf(fp, "%02x", priv_mac[i]);
1430 smemclr(priv_blob, priv_blob_len);
1432 smemclr(priv_blob_encrypted, priv_blob_len);
1433 sfree(priv_blob_encrypted);
1437 /* ----------------------------------------------------------------------
1438 * Output public keys.
1440 char *ssh1_pubkey_str(struct RSAKey *key)
1445 dec1 = bignum_decimal(key->exponent);
1446 dec2 = bignum_decimal(key->modulus);
1447 buffer = dupprintf("%d %s %s%s%s", bignum_bitcount(key->modulus),
1449 key->comment ? " " : "",
1450 key->comment ? key->comment : "");
1456 void ssh1_write_pubkey(FILE *fp, struct RSAKey *key)
1458 char *buffer = ssh1_pubkey_str(key);
1459 fprintf(fp, "%s\n", buffer);
1463 static char *ssh2_pubkey_openssh_str_internal(const char *comment,
1464 const void *v_pub_blob,
1467 const unsigned char *ssh2blob = (const unsigned char *)v_pub_blob;
1476 alglen = GET_32BIT(ssh2blob);
1477 if (alglen > 0 && alglen < pub_len - 4) {
1478 alg = (const char *)ssh2blob + 4;
1485 alg = "INVALID-ALGORITHM";
1486 alglen = strlen(alg);
1489 buffer = snewn(alglen +
1490 4 * ((pub_len+2) / 3) +
1491 (comment ? strlen(comment) : 0) + 3, char);
1492 p = buffer + sprintf(buffer, "%.*s ", alglen, alg);
1494 while (i < pub_len) {
1495 int n = (pub_len - i < 3 ? pub_len - i : 3);
1496 base64_encode_atom(ssh2blob + i, n, p);
1509 char *ssh2_pubkey_openssh_str(struct ssh2_userkey *key)
1512 unsigned char *blob;
1515 blob = key->alg->public_blob(key->data, &bloblen);
1516 ret = ssh2_pubkey_openssh_str_internal(key->comment, blob, bloblen);
1522 void ssh2_write_pubkey(FILE *fp, const char *comment,
1523 const void *v_pub_blob, int pub_len,
1526 unsigned char *pub_blob = (unsigned char *)v_pub_blob;
1528 if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716) {
1532 fprintf(fp, "---- BEGIN SSH2 PUBLIC KEY ----\n");
1535 fprintf(fp, "Comment: \"");
1536 for (p = comment; *p; p++) {
1537 if (*p == '\\' || *p == '\"')
1541 fprintf(fp, "\"\n");
1546 while (i < pub_len) {
1548 int n = (pub_len - i < 3 ? pub_len - i : 3);
1549 base64_encode_atom(pub_blob + i, n, buf);
1553 if (++column >= 16) {
1561 fprintf(fp, "---- END SSH2 PUBLIC KEY ----\n");
1562 } else if (keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
1563 char *buffer = ssh2_pubkey_openssh_str_internal(comment,
1564 v_pub_blob, pub_len);
1565 fprintf(fp, "%s\n", buffer);
1568 assert(0 && "Bad key type in ssh2_write_pubkey");
1572 /* ----------------------------------------------------------------------
1573 * Utility functions to compute SSH-2 fingerprints in a uniform way.
1575 char *ssh2_fingerprint_blob(const void *blob, int bloblen)
1577 unsigned char digest[16];
1578 char fingerprint_str[16*3];
1581 const struct ssh_signkey *alg;
1585 * The fingerprint hash itself is always just the MD5 of the blob.
1587 MD5Simple(blob, bloblen, digest);
1588 for (i = 0; i < 16; i++)
1589 sprintf(fingerprint_str + i*3, "%02x%s", digest[i], i==15 ? "" : ":");
1592 * Identify the key algorithm, if possible.
1594 alglen = toint(GET_32BIT((const unsigned char *)blob));
1595 if (alglen > 0 && alglen < bloblen-4) {
1596 algstr = (const char *)blob + 4;
1599 * If we can actually identify the algorithm as one we know
1600 * about, get hold of the key's bit count too.
1602 alg = find_pubkey_alg_len(alglen, algstr);
1604 int bits = alg->pubkey_bits(alg, blob, bloblen);
1605 return dupprintf("%.*s %d %s", alglen, algstr,
1606 bits, fingerprint_str);
1608 return dupprintf("%.*s %s", alglen, algstr, fingerprint_str);
1612 * No algorithm available (which means a seriously confused
1613 * key blob, but there we go). Return only the hash.
1615 return dupstr(fingerprint_str);
1619 char *ssh2_fingerprint(const struct ssh_signkey *alg, void *data)
1622 unsigned char *blob = alg->public_blob(data, &len);
1623 char *ret = ssh2_fingerprint_blob(blob, len);
1628 /* ----------------------------------------------------------------------
1629 * Determine the type of a private key file.
1631 static int key_type_fp(FILE *fp)
1634 const char public_std_sig[] = "---- BEGIN SSH2 PUBLIC KEY";
1635 const char putty2_sig[] = "PuTTY-User-Key-File-";
1636 const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1637 const char openssh_new_sig[] = "-----BEGIN OPENSSH PRIVATE KEY";
1638 const char openssh_sig[] = "-----BEGIN ";
1642 i = fread(buf, 1, sizeof(buf)-1, fp);
1646 return SSH_KEYTYPE_UNOPENABLE;
1648 return SSH_KEYTYPE_UNKNOWN;
1649 assert(i > 0 && i < sizeof(buf));
1651 if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1652 return SSH_KEYTYPE_SSH1;
1653 if (!memcmp(buf, public_std_sig, sizeof(public_std_sig)-1))
1654 return SSH_KEYTYPE_SSH2_PUBLIC_RFC4716;
1655 if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1656 return SSH_KEYTYPE_SSH2;
1657 if (!memcmp(buf, openssh_new_sig, sizeof(openssh_new_sig)-1))
1658 return SSH_KEYTYPE_OPENSSH_NEW;
1659 if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1660 return SSH_KEYTYPE_OPENSSH_PEM;
1661 if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1662 return SSH_KEYTYPE_SSHCOM;
1663 if ((p = buf + strspn(buf, "0123456789"), *p == ' ') &&
1664 (p = p+1 + strspn(p+1, "0123456789"), *p == ' ') &&
1665 (p = p+1 + strspn(p+1, "0123456789"), *p == ' ' || *p == '\n' || !*p))
1666 return SSH_KEYTYPE_SSH1_PUBLIC;
1667 if ((p = buf + strcspn(buf, " "), find_pubkey_alg_len(p-buf, buf)) &&
1668 (p = p+1 + strspn(p+1, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij"
1669 "klmnopqrstuvwxyz+/="),
1670 *p == ' ' || *p == '\n' || !*p))
1671 return SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH;
1672 return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
1675 int key_type(const Filename *filename)
1680 fp = f_open(filename, "r", FALSE);
1682 return SSH_KEYTYPE_UNOPENABLE;
1683 ret = key_type_fp(fp);
1689 * Convert the type word to a string, for `wrong type' error
1692 const char *key_type_to_str(int type)
1695 case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1696 case SSH_KEYTYPE_UNKNOWN: return "not a recognised key file format"; break;
1697 case SSH_KEYTYPE_SSH1_PUBLIC: return "SSH-1 public key"; break;
1698 case SSH_KEYTYPE_SSH2_PUBLIC_RFC4716: return "SSH-2 public key (RFC 4716 format)"; break;
1699 case SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH: return "SSH-2 public key (OpenSSH format)"; break;
1700 case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
1701 case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
1702 case SSH_KEYTYPE_OPENSSH_PEM: return "OpenSSH SSH-2 private key (old PEM format)"; break;
1703 case SSH_KEYTYPE_OPENSSH_NEW: return "OpenSSH SSH-2 private key (new format)"; break;
1704 case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
1706 * This function is called with a key type derived from
1707 * looking at an actual key file, so the output-only type
1708 * OPENSSH_AUTO should never get here, and is much an INTERNAL
1709 * ERROR as a code we don't even understand.
1711 case SSH_KEYTYPE_OPENSSH_AUTO: return "INTERNAL ERROR (OPENSSH_AUTO)"; break;
1712 default: return "INTERNAL ERROR"; break;