tor-commits
Threads by month
- ----- 2025 -----
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
September 2018
- 17 participants
- 3231 discussions
[tor/master] Extract openssl RSA functionality into its own file.
by nickm@torproject.org 05 Sep '18
by nickm@torproject.org 05 Sep '18
05 Sep '18
commit 752ffa21973c67a789c34511e13d079d8bec3858
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Jul 19 08:53:40 2018 -0400
Extract openssl RSA functionality into its own file.
---
src/lib/crypt_ops/crypto_rsa.c | 795 --------------------------------
src/lib/crypt_ops/crypto_rsa_openssl.c | 815 +++++++++++++++++++++++++++++++++
src/lib/crypt_ops/include.am | 1 +
3 files changed, 816 insertions(+), 795 deletions(-)
diff --git a/src/lib/crypt_ops/crypto_rsa.c b/src/lib/crypt_ops/crypto_rsa.c
index ffe2bd2ce..328fd732d 100644
--- a/src/lib/crypt_ops/crypto_rsa.c
+++ b/src/lib/crypt_ops/crypto_rsa.c
@@ -21,33 +21,11 @@
#include "lib/log/util_bug.h"
#include "lib/fs/files.h"
-DISABLE_GCC_WARNING(redundant-decls)
-
-#include <openssl/err.h>
-#include <openssl/rsa.h>
-#include <openssl/pem.h>
-#include <openssl/evp.h>
-#include <openssl/engine.h>
-#include <openssl/rand.h>
-#include <openssl/bn.h>
-#include <openssl/dh.h>
-#include <openssl/conf.h>
-#include <openssl/hmac.h>
-
-ENABLE_GCC_WARNING(redundant-decls)
-
#include "lib/log/log.h"
#include "lib/encoding/binascii.h"
#include <string.h>
-/** Declaration for crypto_pk_t structure. */
-struct crypto_pk_t
-{
- int refs; /**< reference count, so we don't have to copy keys */
- RSA *key; /**< The key itself */
-};
-
/** Return the number of bytes added by padding method <b>padding</b>.
*/
int
@@ -72,442 +50,6 @@ crypto_get_rsa_padding(int padding)
}
}
-/** used internally: quicly validate a crypto_pk_t object as a private key.
- * Return 1 iff the public key is valid, 0 if obviously invalid.
- */
-static int
-crypto_pk_private_ok(const crypto_pk_t *k)
-{
-#ifdef OPENSSL_1_1_API
- if (!k || !k->key)
- return 0;
-
- const BIGNUM *p, *q;
- RSA_get0_factors(k->key, &p, &q);
- return p != NULL; /* XXX/yawning: Should we check q? */
-#else /* !(defined(OPENSSL_1_1_API)) */
- return k && k->key && k->key->p;
-#endif /* defined(OPENSSL_1_1_API) */
-}
-
-/** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
-crypto_pk_t *
-crypto_new_pk_from_rsa_(RSA *rsa)
-{
- crypto_pk_t *env;
- tor_assert(rsa);
- env = tor_malloc(sizeof(crypto_pk_t));
- env->refs = 1;
- env->key = rsa;
- return env;
-}
-
-/** Helper, used by tor-gencert.c. Return the RSA from a
- * crypto_pk_t. */
-RSA *
-crypto_pk_get_rsa_(crypto_pk_t *env)
-{
- return env->key;
-}
-
-/** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
- * private is set, include the private-key portion of the key. Return a valid
- * pointer on success, and NULL on failure. */
-MOCK_IMPL(EVP_PKEY *,
-crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
-{
- RSA *key = NULL;
- EVP_PKEY *pkey = NULL;
- tor_assert(env->key);
- if (private) {
- if (!(key = RSAPrivateKey_dup(env->key)))
- goto error;
- } else {
- if (!(key = RSAPublicKey_dup(env->key)))
- goto error;
- }
- if (!(pkey = EVP_PKEY_new()))
- goto error;
- if (!(EVP_PKEY_assign_RSA(pkey, key)))
- goto error;
- return pkey;
- error:
- if (pkey)
- EVP_PKEY_free(pkey);
- if (key)
- RSA_free(key);
- return NULL;
-}
-
-/** Allocate and return storage for a public key. The key itself will not yet
- * be set.
- */
-MOCK_IMPL(crypto_pk_t *,
-crypto_pk_new,(void))
-{
- RSA *rsa;
-
- rsa = RSA_new();
- tor_assert(rsa);
- return crypto_new_pk_from_rsa_(rsa);
-}
-
-/** Release a reference to an asymmetric key; when all the references
- * are released, free the key.
- */
-void
-crypto_pk_free_(crypto_pk_t *env)
-{
- if (!env)
- return;
-
- if (--env->refs > 0)
- return;
- tor_assert(env->refs == 0);
-
- if (env->key)
- RSA_free(env->key);
-
- tor_free(env);
-}
-
-/** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
- * Return 0 on success, -1 on failure.
- */
-MOCK_IMPL(int,
-crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
-{
- tor_assert(env);
-
- if (env->key) {
- RSA_free(env->key);
- env->key = NULL;
- }
-
- {
- BIGNUM *e = BN_new();
- RSA *r = NULL;
- if (!e)
- goto done;
- if (! BN_set_word(e, 65537))
- goto done;
- r = RSA_new();
- if (!r)
- goto done;
- if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
- goto done;
-
- env->key = r;
- r = NULL;
- done:
- if (e)
- BN_clear_free(e);
- if (r)
- RSA_free(r);
- }
-
- if (!env->key) {
- crypto_openssl_log_errors(LOG_WARN, "generating RSA key");
- return -1;
- }
-
- return 0;
-}
-
-/** A PEM callback that always reports a failure to get a password */
-static int
-pem_no_password_cb(char *buf, int size, int rwflag, void *u)
-{
- (void)buf;
- (void)size;
- (void)rwflag;
- (void)u;
- return -1;
-}
-
-/** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
- * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
- * the string is nul-terminated.
- */
-int
-crypto_pk_read_private_key_from_string(crypto_pk_t *env,
- const char *s, ssize_t len)
-{
- BIO *b;
-
- tor_assert(env);
- tor_assert(s);
- tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
-
- /* Create a read-only memory BIO, backed by the string 's' */
- b = BIO_new_mem_buf((char*)s, (int)len);
- if (!b)
- return -1;
-
- if (env->key)
- RSA_free(env->key);
-
- env->key = PEM_read_bio_RSAPrivateKey(b,NULL,pem_no_password_cb,NULL);
-
- BIO_free(b);
-
- if (!env->key) {
- crypto_openssl_log_errors(LOG_WARN, "Error parsing private key");
- return -1;
- }
- return 0;
-}
-
-/** Read a PEM-encoded private key from the file named by
- * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
- */
-int
-crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
- const char *keyfile)
-{
- char *contents;
- int r;
-
- /* Read the file into a string. */
- contents = read_file_to_str(keyfile, 0, NULL);
- if (!contents) {
- log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
- return -1;
- }
-
- /* Try to parse it. */
- r = crypto_pk_read_private_key_from_string(env, contents, -1);
- memwipe(contents, 0, strlen(contents));
- tor_free(contents);
- if (r)
- return -1; /* read_private_key_from_string already warned, so we don't.*/
-
- /* Make sure it's valid. */
- if (crypto_pk_check_key(env) <= 0)
- return -1;
-
- return 0;
-}
-
-/** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
- * success, -1 on failure. */
-static int
-crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
- size_t *len, int is_public)
-{
- BUF_MEM *buf;
- BIO *b;
- int r;
-
- tor_assert(env);
- tor_assert(env->key);
- tor_assert(dest);
-
- b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
- if (!b)
- return -1;
-
- /* Now you can treat b as if it were a file. Just use the
- * PEM_*_bio_* functions instead of the non-bio variants.
- */
- if (is_public)
- r = PEM_write_bio_RSAPublicKey(b, env->key);
- else
- r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
-
- if (!r) {
- crypto_openssl_log_errors(LOG_WARN, "writing RSA key to string");
- BIO_free(b);
- return -1;
- }
-
- BIO_get_mem_ptr(b, &buf);
-
- *dest = tor_malloc(buf->length+1);
- memcpy(*dest, buf->data, buf->length);
- (*dest)[buf->length] = 0; /* nul terminate it */
- *len = buf->length;
-
- BIO_free(b);
-
- return 0;
-}
-
-/** PEM-encode the public key portion of <b>env</b> and write it to a
- * newly allocated string. On success, set *<b>dest</b> to the new
- * string, *<b>len</b> to the string's length, and return 0. On
- * failure, return -1.
- */
-int
-crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
- size_t *len)
-{
- return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
-}
-
-/** PEM-encode the private key portion of <b>env</b> and write it to a
- * newly allocated string. On success, set *<b>dest</b> to the new
- * string, *<b>len</b> to the string's length, and return 0. On
- * failure, return -1.
- */
-int
-crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
- size_t *len)
-{
- return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
-}
-
-/** Read a PEM-encoded public key from the first <b>len</b> characters of
- * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
- * failure.
- */
-int
-crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
- size_t len)
-{
- BIO *b;
-
- tor_assert(env);
- tor_assert(src);
- tor_assert(len<INT_MAX);
-
- b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
- if (!b)
- return -1;
-
- BIO_write(b, src, (int)len);
-
- if (env->key)
- RSA_free(env->key);
- env->key = PEM_read_bio_RSAPublicKey(b, NULL, pem_no_password_cb, NULL);
- BIO_free(b);
- if (!env->key) {
- crypto_openssl_log_errors(LOG_WARN, "reading public key from string");
- return -1;
- }
-
- return 0;
-}
-
-/** Write the private key from <b>env</b> into the file named by <b>fname</b>,
- * PEM-encoded. Return 0 on success, -1 on failure.
- */
-int
-crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
- const char *fname)
-{
- BIO *bio;
- char *cp;
- long len;
- char *s;
- int r;
-
- tor_assert(crypto_pk_private_ok(env));
-
- if (!(bio = BIO_new(BIO_s_mem())))
- return -1;
- if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
- == 0) {
- crypto_openssl_log_errors(LOG_WARN, "writing private key");
- BIO_free(bio);
- return -1;
- }
- len = BIO_get_mem_data(bio, &cp);
- tor_assert(len >= 0);
- s = tor_malloc(len+1);
- memcpy(s, cp, len);
- s[len]='\0';
- r = write_str_to_file(fname, s, 0);
- BIO_free(bio);
- memwipe(s, 0, strlen(s));
- tor_free(s);
- return r;
-}
-
-/** Return true iff <b>env</b> has a valid key.
- */
-int
-crypto_pk_check_key(crypto_pk_t *env)
-{
- int r;
- tor_assert(env);
-
- r = RSA_check_key(env->key);
- if (r <= 0)
- crypto_openssl_log_errors(LOG_WARN,"checking RSA key");
- return r;
-}
-
-/** Return true iff <b>key</b> contains the private-key portion of the RSA
- * key. */
-int
-crypto_pk_key_is_private(const crypto_pk_t *key)
-{
- tor_assert(key);
- return crypto_pk_private_ok(key);
-}
-
-/** Return true iff <b>env</b> contains a public key whose public exponent
- * equals 65537.
- */
-int
-crypto_pk_public_exponent_ok(crypto_pk_t *env)
-{
- tor_assert(env);
- tor_assert(env->key);
-
- const BIGNUM *e;
-
-#ifdef OPENSSL_1_1_API
- const BIGNUM *n, *d;
- RSA_get0_key(env->key, &n, &e, &d);
-#else
- e = env->key->e;
-#endif /* defined(OPENSSL_1_1_API) */
- return BN_is_word(e, 65537);
-}
-
-/** Compare the public-key components of a and b. Return less than 0
- * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
- * considered to be less than all non-NULL keys, and equal to itself.
- *
- * Note that this may leak information about the keys through timing.
- */
-int
-crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
-{
- int result;
- char a_is_non_null = (a != NULL) && (a->key != NULL);
- char b_is_non_null = (b != NULL) && (b->key != NULL);
- char an_argument_is_null = !a_is_non_null | !b_is_non_null;
-
- result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
- if (an_argument_is_null)
- return result;
-
- const BIGNUM *a_n, *a_e;
- const BIGNUM *b_n, *b_e;
-
-#ifdef OPENSSL_1_1_API
- const BIGNUM *a_d, *b_d;
- RSA_get0_key(a->key, &a_n, &a_e, &a_d);
- RSA_get0_key(b->key, &b_n, &b_e, &b_d);
-#else
- a_n = a->key->n;
- a_e = a->key->e;
- b_n = b->key->n;
- b_e = b->key->e;
-#endif /* defined(OPENSSL_1_1_API) */
-
- tor_assert(a_n != NULL && a_e != NULL);
- tor_assert(b_n != NULL && b_e != NULL);
-
- result = BN_cmp(a_n, b_n);
- if (result)
- return result;
- return BN_cmp(a_e, b_e);
-}
-
/** Compare the public-key components of a and b. Return non-zero iff
* a==b. A NULL key is considered to be distinct from all non-NULL
* keys, and equal to itself.
@@ -520,98 +62,6 @@ crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
return (crypto_pk_cmp_keys(a, b) == 0);
}
-/** Return the size of the public key modulus in <b>env</b>, in bytes. */
-size_t
-crypto_pk_keysize(const crypto_pk_t *env)
-{
- tor_assert(env);
- tor_assert(env->key);
-
- return (size_t) RSA_size((RSA*)env->key);
-}
-
-/** Return the size of the public key modulus of <b>env</b>, in bits. */
-int
-crypto_pk_num_bits(crypto_pk_t *env)
-{
- tor_assert(env);
- tor_assert(env->key);
-
-#ifdef OPENSSL_1_1_API
- /* It's so stupid that there's no other way to check that n is valid
- * before calling RSA_bits().
- */
- const BIGNUM *n, *e, *d;
- RSA_get0_key(env->key, &n, &e, &d);
- tor_assert(n != NULL);
-
- return RSA_bits(env->key);
-#else /* !(defined(OPENSSL_1_1_API)) */
- tor_assert(env->key->n);
- return BN_num_bits(env->key->n);
-#endif /* defined(OPENSSL_1_1_API) */
-}
-
-/** Increase the reference count of <b>env</b>, and return it.
- */
-crypto_pk_t *
-crypto_pk_dup_key(crypto_pk_t *env)
-{
- tor_assert(env);
- tor_assert(env->key);
-
- env->refs++;
- return env;
-}
-
-#ifdef TOR_UNIT_TESTS
-/** For testing: replace dest with src. (Dest must have a refcount
- * of 1) */
-void
-crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
-{
- tor_assert(dest);
- tor_assert(dest->refs == 1);
- tor_assert(src);
- RSA_free(dest->key);
- dest->key = RSAPrivateKey_dup(src->key);
-}
-#endif /* defined(TOR_UNIT_TESTS) */
-
-/** Make a real honest-to-goodness copy of <b>env</b>, and return it.
- * Returns NULL on failure. */
-crypto_pk_t *
-crypto_pk_copy_full(crypto_pk_t *env)
-{
- RSA *new_key;
- int privatekey = 0;
- tor_assert(env);
- tor_assert(env->key);
-
- if (crypto_pk_private_ok(env)) {
- new_key = RSAPrivateKey_dup(env->key);
- privatekey = 1;
- } else {
- new_key = RSAPublicKey_dup(env->key);
- }
- if (!new_key) {
- /* LCOV_EXCL_START
- *
- * We can't cause RSA*Key_dup() to fail, so we can't really test this.
- */
- log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
- privatekey?"private":"public");
- crypto_openssl_log_errors(LOG_ERR,
- privatekey ? "Duplicating a private key" :
- "Duplicating a public key");
- tor_fragile_assert();
- return NULL;
- /* LCOV_EXCL_STOP */
- }
-
- return crypto_new_pk_from_rsa_(new_key);
-}
-
/** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
* bytes of data from <b>from</b>, with padding type 'padding',
* storing the results on <b>to</b>.
@@ -754,179 +204,6 @@ crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env,
return -1;
}
-/** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
- * in <b>env</b>, using the padding method <b>padding</b>. On success,
- * write the result to <b>to</b>, and return the number of bytes
- * written. On failure, return -1.
- *
- * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
- * at least the length of the modulus of <b>env</b>.
- */
-int
-crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
- const char *from, size_t fromlen, int padding)
-{
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen<INT_MAX);
- tor_assert(tolen >= crypto_pk_keysize(env));
-
- r = RSA_public_encrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, crypto_get_rsa_padding(padding));
- if (r<0) {
- crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
- return -1;
- }
- return r;
-}
-
-/** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
- * in <b>env</b>, using the padding method <b>padding</b>. On success,
- * write the result to <b>to</b>, and return the number of bytes
- * written. On failure, return -1.
- *
- * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
- * at least the length of the modulus of <b>env</b>.
- */
-int
-crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
- size_t tolen,
- const char *from, size_t fromlen,
- int padding, int warnOnFailure)
-{
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(env->key);
- tor_assert(fromlen<INT_MAX);
- tor_assert(tolen >= crypto_pk_keysize(env));
- if (!crypto_pk_key_is_private(env))
- /* Not a private key */
- return -1;
-
- r = RSA_private_decrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, crypto_get_rsa_padding(padding));
-
- if (r<0) {
- crypto_openssl_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
- "performing RSA decryption");
- return -1;
- }
- return r;
-}
-
-/** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
- * public key in <b>env</b>, using PKCS1 padding. On success, write the
- * signed data to <b>to</b>, and return the number of bytes written.
- * On failure, return -1.
- *
- * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
- * at least the length of the modulus of <b>env</b>.
- */
-MOCK_IMPL(int,
-crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
- size_t tolen,
- const char *from, size_t fromlen))
-{
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen < INT_MAX);
- tor_assert(tolen >= crypto_pk_keysize(env));
- r = RSA_public_decrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- env->key, RSA_PKCS1_PADDING);
-
- if (r<0) {
- crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
- return -1;
- }
- return r;
-}
-
-/** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
- * <b>env</b>, using PKCS1 padding. On success, write the signature to
- * <b>to</b>, and return the number of bytes written. On failure, return
- * -1.
- *
- * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
- * at least the length of the modulus of <b>env</b>.
- */
-int
-crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
- const char *from, size_t fromlen)
-{
- int r;
- tor_assert(env);
- tor_assert(from);
- tor_assert(to);
- tor_assert(fromlen < INT_MAX);
- tor_assert(tolen >= crypto_pk_keysize(env));
- if (!crypto_pk_key_is_private(env))
- /* Not a private key */
- return -1;
-
- r = RSA_private_encrypt((int)fromlen,
- (unsigned char*)from, (unsigned char*)to,
- (RSA*)env->key, RSA_PKCS1_PADDING);
- if (r<0) {
- crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
- return -1;
- }
- return r;
-}
-
-/** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
- * Return -1 on error, or the number of characters used on success.
- */
-int
-crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
-{
- int len;
- unsigned char *buf = NULL;
-
- len = i2d_RSAPublicKey(pk->key, &buf);
- if (len < 0 || buf == NULL)
- return -1;
-
- if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
- OPENSSL_free(buf);
- return -1;
- }
- /* We don't encode directly into 'dest', because that would be illegal
- * type-punning. (C99 is smarter than me, C99 is smarter than me...)
- */
- memcpy(dest,buf,len);
- OPENSSL_free(buf);
- return len;
-}
-
-/** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
- * success and NULL on failure.
- */
-crypto_pk_t *
-crypto_pk_asn1_decode(const char *str, size_t len)
-{
- RSA *rsa;
- unsigned char *buf;
- const unsigned char *cp;
- cp = buf = tor_malloc(len);
- memcpy(buf,str,len);
- rsa = d2i_RSAPublicKey(NULL, &cp, len);
- tor_free(buf);
- if (!rsa) {
- crypto_openssl_log_errors(LOG_WARN,"decoding public key");
- return NULL;
- }
- return crypto_new_pk_from_rsa_(rsa);
-}
-
/** Given a private or public key <b>pk</b>, put a fingerprint of the
* public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
* space). Return 0 on success, -1 on failure.
@@ -1111,75 +388,3 @@ crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
tor_free(buf);
return rv;
}
-
-/** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
- * Base64 encoding of the DER representation of the private key as a NUL
- * terminated string, and return it via <b>priv_out</b>. Return 0 on
- * success, -1 on failure.
- *
- * It is the caller's responsibility to sanitize and free the resulting buffer.
- */
-int
-crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
-{
- unsigned char *der = NULL;
- int der_len;
- int ret = -1;
-
- *priv_out = NULL;
-
- der_len = i2d_RSAPrivateKey(pk->key, &der);
- if (der_len < 0 || der == NULL)
- return ret;
-
- size_t priv_len = base64_encode_size(der_len, 0) + 1;
- char *priv = tor_malloc_zero(priv_len);
- if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
- *priv_out = priv;
- ret = 0;
- } else {
- tor_free(priv);
- }
-
- memwipe(der, 0, der_len);
- OPENSSL_free(der);
- return ret;
-}
-
-/** Given a string containing the Base64 encoded DER representation of the
- * private key <b>str</b>, decode and return the result on success, or NULL
- * on failure.
- */
-crypto_pk_t *
-crypto_pk_base64_decode(const char *str, size_t len)
-{
- crypto_pk_t *pk = NULL;
-
- char *der = tor_malloc_zero(len + 1);
- int der_len = base64_decode(der, len, str, len);
- if (der_len <= 0) {
- log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
- goto out;
- }
-
- const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
- RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
- if (!rsa) {
- crypto_openssl_log_errors(LOG_WARN, "decoding private key");
- goto out;
- }
-
- pk = crypto_new_pk_from_rsa_(rsa);
-
- /* Make sure it's valid. */
- if (crypto_pk_check_key(pk) <= 0) {
- crypto_pk_free(pk);
- pk = NULL;
- goto out;
- }
-
- out:
- memwipe(der, 0, len + 1);
- tor_free(der);
- return pk;
-}
diff --git a/src/lib/crypt_ops/crypto_rsa_openssl.c b/src/lib/crypt_ops/crypto_rsa_openssl.c
new file mode 100644
index 000000000..c57a2e39e
--- /dev/null
+++ b/src/lib/crypt_ops/crypto_rsa_openssl.c
@@ -0,0 +1,815 @@
+/* Copyright (c) 2001, Matej Pfajfar.
+ * Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file crypto_rsa.c
+ * \brief OpenSSL implementations of our RSA code.
+ **/
+
+#include "lib/crypt_ops/compat_openssl.h"
+#include "lib/crypt_ops/crypto_rsa.h"
+#include "lib/crypt_ops/crypto_util.h"
+#include "lib/ctime/di_ops.h"
+#include "lib/log/util_bug.h"
+#include "lib/fs/files.h"
+
+DISABLE_GCC_WARNING(redundant-decls)
+
+#include <openssl/err.h>
+#include <openssl/rsa.h>
+#include <openssl/pem.h>
+#include <openssl/evp.h>
+#include <openssl/engine.h>
+#include <openssl/rand.h>
+#include <openssl/bn.h>
+#include <openssl/conf.h>
+
+ENABLE_GCC_WARNING(redundant-decls)
+
+#include "lib/log/log.h"
+#include "lib/encoding/binascii.h"
+
+#include <string.h>
+
+/** Declaration for crypto_pk_t structure. */
+struct crypto_pk_t
+{
+ int refs; /**< reference count, so we don't have to copy keys */
+ RSA *key; /**< The key itself */
+};
+
+/** used internally: quicly validate a crypto_pk_t object as a private key.
+ * Return 1 iff the public key is valid, 0 if obviously invalid.
+ */
+static int
+crypto_pk_private_ok(const crypto_pk_t *k)
+{
+#ifdef OPENSSL_1_1_API
+ if (!k || !k->key)
+ return 0;
+
+ const BIGNUM *p, *q;
+ RSA_get0_factors(k->key, &p, &q);
+ return p != NULL; /* XXX/yawning: Should we check q? */
+#else /* !(defined(OPENSSL_1_1_API)) */
+ return k && k->key && k->key->p;
+#endif /* defined(OPENSSL_1_1_API) */
+}
+
+/** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
+crypto_pk_t *
+crypto_new_pk_from_rsa_(RSA *rsa)
+{
+ crypto_pk_t *env;
+ tor_assert(rsa);
+ env = tor_malloc(sizeof(crypto_pk_t));
+ env->refs = 1;
+ env->key = rsa;
+ return env;
+}
+
+/** Helper, used by tor-gencert.c. Return the RSA from a
+ * crypto_pk_t. */
+RSA *
+crypto_pk_get_rsa_(crypto_pk_t *env)
+{
+ return env->key;
+}
+
+/** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
+ * private is set, include the private-key portion of the key. Return a valid
+ * pointer on success, and NULL on failure. */
+MOCK_IMPL(EVP_PKEY *,
+crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
+{
+ RSA *key = NULL;
+ EVP_PKEY *pkey = NULL;
+ tor_assert(env->key);
+ if (private) {
+ if (!(key = RSAPrivateKey_dup(env->key)))
+ goto error;
+ } else {
+ if (!(key = RSAPublicKey_dup(env->key)))
+ goto error;
+ }
+ if (!(pkey = EVP_PKEY_new()))
+ goto error;
+ if (!(EVP_PKEY_assign_RSA(pkey, key)))
+ goto error;
+ return pkey;
+ error:
+ if (pkey)
+ EVP_PKEY_free(pkey);
+ if (key)
+ RSA_free(key);
+ return NULL;
+}
+
+/** Allocate and return storage for a public key. The key itself will not yet
+ * be set.
+ */
+MOCK_IMPL(crypto_pk_t *,
+crypto_pk_new,(void))
+{
+ RSA *rsa;
+
+ rsa = RSA_new();
+ tor_assert(rsa);
+ return crypto_new_pk_from_rsa_(rsa);
+}
+
+/** Release a reference to an asymmetric key; when all the references
+ * are released, free the key.
+ */
+void
+crypto_pk_free_(crypto_pk_t *env)
+{
+ if (!env)
+ return;
+
+ if (--env->refs > 0)
+ return;
+ tor_assert(env->refs == 0);
+
+ if (env->key)
+ RSA_free(env->key);
+
+ tor_free(env);
+}
+
+/** Generate a <b>bits</b>-bit new public/private keypair in <b>env</b>.
+ * Return 0 on success, -1 on failure.
+ */
+MOCK_IMPL(int,
+crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
+{
+ tor_assert(env);
+
+ if (env->key) {
+ RSA_free(env->key);
+ env->key = NULL;
+ }
+
+ {
+ BIGNUM *e = BN_new();
+ RSA *r = NULL;
+ if (!e)
+ goto done;
+ if (! BN_set_word(e, 65537))
+ goto done;
+ r = RSA_new();
+ if (!r)
+ goto done;
+ if (RSA_generate_key_ex(r, bits, e, NULL) == -1)
+ goto done;
+
+ env->key = r;
+ r = NULL;
+ done:
+ if (e)
+ BN_clear_free(e);
+ if (r)
+ RSA_free(r);
+ }
+
+ if (!env->key) {
+ crypto_openssl_log_errors(LOG_WARN, "generating RSA key");
+ return -1;
+ }
+
+ return 0;
+}
+
+/** A PEM callback that always reports a failure to get a password */
+static int
+pem_no_password_cb(char *buf, int size, int rwflag, void *u)
+{
+ (void)buf;
+ (void)size;
+ (void)rwflag;
+ (void)u;
+ return -1;
+}
+
+/** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
+ * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
+ * the string is nul-terminated.
+ */
+int
+crypto_pk_read_private_key_from_string(crypto_pk_t *env,
+ const char *s, ssize_t len)
+{
+ BIO *b;
+
+ tor_assert(env);
+ tor_assert(s);
+ tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
+
+ /* Create a read-only memory BIO, backed by the string 's' */
+ b = BIO_new_mem_buf((char*)s, (int)len);
+ if (!b)
+ return -1;
+
+ if (env->key)
+ RSA_free(env->key);
+
+ env->key = PEM_read_bio_RSAPrivateKey(b,NULL,pem_no_password_cb,NULL);
+
+ BIO_free(b);
+
+ if (!env->key) {
+ crypto_openssl_log_errors(LOG_WARN, "Error parsing private key");
+ return -1;
+ }
+ return 0;
+}
+
+/** Read a PEM-encoded private key from the file named by
+ * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
+ */
+int
+crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
+ const char *keyfile)
+{
+ char *contents;
+ int r;
+
+ /* Read the file into a string. */
+ contents = read_file_to_str(keyfile, 0, NULL);
+ if (!contents) {
+ log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
+ return -1;
+ }
+
+ /* Try to parse it. */
+ r = crypto_pk_read_private_key_from_string(env, contents, -1);
+ memwipe(contents, 0, strlen(contents));
+ tor_free(contents);
+ if (r)
+ return -1; /* read_private_key_from_string already warned, so we don't.*/
+
+ /* Make sure it's valid. */
+ if (crypto_pk_check_key(env) <= 0)
+ return -1;
+
+ return 0;
+}
+
+/** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
+ * success, -1 on failure. */
+static int
+crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
+ size_t *len, int is_public)
+{
+ BUF_MEM *buf;
+ BIO *b;
+ int r;
+
+ tor_assert(env);
+ tor_assert(env->key);
+ tor_assert(dest);
+
+ b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
+ if (!b)
+ return -1;
+
+ /* Now you can treat b as if it were a file. Just use the
+ * PEM_*_bio_* functions instead of the non-bio variants.
+ */
+ if (is_public)
+ r = PEM_write_bio_RSAPublicKey(b, env->key);
+ else
+ r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
+
+ if (!r) {
+ crypto_openssl_log_errors(LOG_WARN, "writing RSA key to string");
+ BIO_free(b);
+ return -1;
+ }
+
+ BIO_get_mem_ptr(b, &buf);
+
+ *dest = tor_malloc(buf->length+1);
+ memcpy(*dest, buf->data, buf->length);
+ (*dest)[buf->length] = 0; /* nul terminate it */
+ *len = buf->length;
+
+ BIO_free(b);
+
+ return 0;
+}
+
+/** PEM-encode the public key portion of <b>env</b> and write it to a
+ * newly allocated string. On success, set *<b>dest</b> to the new
+ * string, *<b>len</b> to the string's length, and return 0. On
+ * failure, return -1.
+ */
+int
+crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
+ size_t *len)
+{
+ return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
+}
+
+/** PEM-encode the private key portion of <b>env</b> and write it to a
+ * newly allocated string. On success, set *<b>dest</b> to the new
+ * string, *<b>len</b> to the string's length, and return 0. On
+ * failure, return -1.
+ */
+int
+crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
+ size_t *len)
+{
+ return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
+}
+
+/** Read a PEM-encoded public key from the first <b>len</b> characters of
+ * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
+ * failure.
+ */
+int
+crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
+ size_t len)
+{
+ BIO *b;
+
+ tor_assert(env);
+ tor_assert(src);
+ tor_assert(len<INT_MAX);
+
+ b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
+ if (!b)
+ return -1;
+
+ BIO_write(b, src, (int)len);
+
+ if (env->key)
+ RSA_free(env->key);
+ env->key = PEM_read_bio_RSAPublicKey(b, NULL, pem_no_password_cb, NULL);
+ BIO_free(b);
+ if (!env->key) {
+ crypto_openssl_log_errors(LOG_WARN, "reading public key from string");
+ return -1;
+ }
+
+ return 0;
+}
+
+/** Write the private key from <b>env</b> into the file named by <b>fname</b>,
+ * PEM-encoded. Return 0 on success, -1 on failure.
+ */
+int
+crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
+ const char *fname)
+{
+ BIO *bio;
+ char *cp;
+ long len;
+ char *s;
+ int r;
+
+ tor_assert(crypto_pk_private_ok(env));
+
+ if (!(bio = BIO_new(BIO_s_mem())))
+ return -1;
+ if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
+ == 0) {
+ crypto_openssl_log_errors(LOG_WARN, "writing private key");
+ BIO_free(bio);
+ return -1;
+ }
+ len = BIO_get_mem_data(bio, &cp);
+ tor_assert(len >= 0);
+ s = tor_malloc(len+1);
+ memcpy(s, cp, len);
+ s[len]='\0';
+ r = write_str_to_file(fname, s, 0);
+ BIO_free(bio);
+ memwipe(s, 0, strlen(s));
+ tor_free(s);
+ return r;
+}
+
+/** Return true iff <b>env</b> has a valid key.
+ */
+int
+crypto_pk_check_key(crypto_pk_t *env)
+{
+ int r;
+ tor_assert(env);
+
+ r = RSA_check_key(env->key);
+ if (r <= 0)
+ crypto_openssl_log_errors(LOG_WARN,"checking RSA key");
+ return r;
+}
+
+/** Return true iff <b>key</b> contains the private-key portion of the RSA
+ * key. */
+int
+crypto_pk_key_is_private(const crypto_pk_t *key)
+{
+ tor_assert(key);
+ return crypto_pk_private_ok(key);
+}
+
+/** Return true iff <b>env</b> contains a public key whose public exponent
+ * equals 65537.
+ */
+int
+crypto_pk_public_exponent_ok(crypto_pk_t *env)
+{
+ tor_assert(env);
+ tor_assert(env->key);
+
+ const BIGNUM *e;
+
+#ifdef OPENSSL_1_1_API
+ const BIGNUM *n, *d;
+ RSA_get0_key(env->key, &n, &e, &d);
+#else
+ e = env->key->e;
+#endif /* defined(OPENSSL_1_1_API) */
+ return BN_is_word(e, 65537);
+}
+
+/** Compare the public-key components of a and b. Return less than 0
+ * if a\<b, 0 if a==b, and greater than 0 if a\>b. A NULL key is
+ * considered to be less than all non-NULL keys, and equal to itself.
+ *
+ * Note that this may leak information about the keys through timing.
+ */
+int
+crypto_pk_cmp_keys(const crypto_pk_t *a, const crypto_pk_t *b)
+{
+ int result;
+ char a_is_non_null = (a != NULL) && (a->key != NULL);
+ char b_is_non_null = (b != NULL) && (b->key != NULL);
+ char an_argument_is_null = !a_is_non_null | !b_is_non_null;
+
+ result = tor_memcmp(&a_is_non_null, &b_is_non_null, sizeof(a_is_non_null));
+ if (an_argument_is_null)
+ return result;
+
+ const BIGNUM *a_n, *a_e;
+ const BIGNUM *b_n, *b_e;
+
+#ifdef OPENSSL_1_1_API
+ const BIGNUM *a_d, *b_d;
+ RSA_get0_key(a->key, &a_n, &a_e, &a_d);
+ RSA_get0_key(b->key, &b_n, &b_e, &b_d);
+#else
+ a_n = a->key->n;
+ a_e = a->key->e;
+ b_n = b->key->n;
+ b_e = b->key->e;
+#endif /* defined(OPENSSL_1_1_API) */
+
+ tor_assert(a_n != NULL && a_e != NULL);
+ tor_assert(b_n != NULL && b_e != NULL);
+
+ result = BN_cmp(a_n, b_n);
+ if (result)
+ return result;
+ return BN_cmp(a_e, b_e);
+}
+
+/** Return the size of the public key modulus in <b>env</b>, in bytes. */
+size_t
+crypto_pk_keysize(const crypto_pk_t *env)
+{
+ tor_assert(env);
+ tor_assert(env->key);
+
+ return (size_t) RSA_size((RSA*)env->key);
+}
+
+/** Return the size of the public key modulus of <b>env</b>, in bits. */
+int
+crypto_pk_num_bits(crypto_pk_t *env)
+{
+ tor_assert(env);
+ tor_assert(env->key);
+
+#ifdef OPENSSL_1_1_API
+ /* It's so stupid that there's no other way to check that n is valid
+ * before calling RSA_bits().
+ */
+ const BIGNUM *n, *e, *d;
+ RSA_get0_key(env->key, &n, &e, &d);
+ tor_assert(n != NULL);
+
+ return RSA_bits(env->key);
+#else /* !(defined(OPENSSL_1_1_API)) */
+ tor_assert(env->key->n);
+ return BN_num_bits(env->key->n);
+#endif /* defined(OPENSSL_1_1_API) */
+}
+
+/** Increase the reference count of <b>env</b>, and return it.
+ */
+crypto_pk_t *
+crypto_pk_dup_key(crypto_pk_t *env)
+{
+ tor_assert(env);
+ tor_assert(env->key);
+
+ env->refs++;
+ return env;
+}
+
+#ifdef TOR_UNIT_TESTS
+/** For testing: replace dest with src. (Dest must have a refcount
+ * of 1) */
+void
+crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
+{
+ tor_assert(dest);
+ tor_assert(dest->refs == 1);
+ tor_assert(src);
+ RSA_free(dest->key);
+ dest->key = RSAPrivateKey_dup(src->key);
+}
+#endif /* defined(TOR_UNIT_TESTS) */
+
+/** Make a real honest-to-goodness copy of <b>env</b>, and return it.
+ * Returns NULL on failure. */
+crypto_pk_t *
+crypto_pk_copy_full(crypto_pk_t *env)
+{
+ RSA *new_key;
+ int privatekey = 0;
+ tor_assert(env);
+ tor_assert(env->key);
+
+ if (crypto_pk_private_ok(env)) {
+ new_key = RSAPrivateKey_dup(env->key);
+ privatekey = 1;
+ } else {
+ new_key = RSAPublicKey_dup(env->key);
+ }
+ if (!new_key) {
+ /* LCOV_EXCL_START
+ *
+ * We can't cause RSA*Key_dup() to fail, so we can't really test this.
+ */
+ log_err(LD_CRYPTO, "Unable to duplicate a %s key: openssl failed.",
+ privatekey?"private":"public");
+ crypto_openssl_log_errors(LOG_ERR,
+ privatekey ? "Duplicating a private key" :
+ "Duplicating a public key");
+ tor_fragile_assert();
+ return NULL;
+ /* LCOV_EXCL_STOP */
+ }
+
+ return crypto_new_pk_from_rsa_(new_key);
+}
+
+/** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
+ * in <b>env</b>, using the padding method <b>padding</b>. On success,
+ * write the result to <b>to</b>, and return the number of bytes
+ * written. On failure, return -1.
+ *
+ * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
+ * at least the length of the modulus of <b>env</b>.
+ */
+int
+crypto_pk_public_encrypt(crypto_pk_t *env, char *to, size_t tolen,
+ const char *from, size_t fromlen, int padding)
+{
+ int r;
+ tor_assert(env);
+ tor_assert(from);
+ tor_assert(to);
+ tor_assert(fromlen<INT_MAX);
+ tor_assert(tolen >= crypto_pk_keysize(env));
+
+ r = RSA_public_encrypt((int)fromlen,
+ (unsigned char*)from, (unsigned char*)to,
+ env->key, crypto_get_rsa_padding(padding));
+ if (r<0) {
+ crypto_openssl_log_errors(LOG_WARN, "performing RSA encryption");
+ return -1;
+ }
+ return r;
+}
+
+/** Decrypt <b>fromlen</b> bytes from <b>from</b> with the private key
+ * in <b>env</b>, using the padding method <b>padding</b>. On success,
+ * write the result to <b>to</b>, and return the number of bytes
+ * written. On failure, return -1.
+ *
+ * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
+ * at least the length of the modulus of <b>env</b>.
+ */
+int
+crypto_pk_private_decrypt(crypto_pk_t *env, char *to,
+ size_t tolen,
+ const char *from, size_t fromlen,
+ int padding, int warnOnFailure)
+{
+ int r;
+ tor_assert(env);
+ tor_assert(from);
+ tor_assert(to);
+ tor_assert(env->key);
+ tor_assert(fromlen<INT_MAX);
+ tor_assert(tolen >= crypto_pk_keysize(env));
+ if (!crypto_pk_key_is_private(env))
+ /* Not a private key */
+ return -1;
+
+ r = RSA_private_decrypt((int)fromlen,
+ (unsigned char*)from, (unsigned char*)to,
+ env->key, crypto_get_rsa_padding(padding));
+
+ if (r<0) {
+ crypto_openssl_log_errors(warnOnFailure?LOG_WARN:LOG_DEBUG,
+ "performing RSA decryption");
+ return -1;
+ }
+ return r;
+}
+
+/** Check the signature in <b>from</b> (<b>fromlen</b> bytes long) with the
+ * public key in <b>env</b>, using PKCS1 padding. On success, write the
+ * signed data to <b>to</b>, and return the number of bytes written.
+ * On failure, return -1.
+ *
+ * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
+ * at least the length of the modulus of <b>env</b>.
+ */
+MOCK_IMPL(int,
+crypto_pk_public_checksig,(const crypto_pk_t *env, char *to,
+ size_t tolen,
+ const char *from, size_t fromlen))
+{
+ int r;
+ tor_assert(env);
+ tor_assert(from);
+ tor_assert(to);
+ tor_assert(fromlen < INT_MAX);
+ tor_assert(tolen >= crypto_pk_keysize(env));
+ r = RSA_public_decrypt((int)fromlen,
+ (unsigned char*)from, (unsigned char*)to,
+ env->key, RSA_PKCS1_PADDING);
+
+ if (r<0) {
+ crypto_openssl_log_errors(LOG_INFO, "checking RSA signature");
+ return -1;
+ }
+ return r;
+}
+
+/** Sign <b>fromlen</b> bytes of data from <b>from</b> with the private key in
+ * <b>env</b>, using PKCS1 padding. On success, write the signature to
+ * <b>to</b>, and return the number of bytes written. On failure, return
+ * -1.
+ *
+ * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
+ * at least the length of the modulus of <b>env</b>.
+ */
+int
+crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
+ const char *from, size_t fromlen)
+{
+ int r;
+ tor_assert(env);
+ tor_assert(from);
+ tor_assert(to);
+ tor_assert(fromlen < INT_MAX);
+ tor_assert(tolen >= crypto_pk_keysize(env));
+ if (!crypto_pk_key_is_private(env))
+ /* Not a private key */
+ return -1;
+
+ r = RSA_private_encrypt((int)fromlen,
+ (unsigned char*)from, (unsigned char*)to,
+ (RSA*)env->key, RSA_PKCS1_PADDING);
+ if (r<0) {
+ crypto_openssl_log_errors(LOG_WARN, "generating RSA signature");
+ return -1;
+ }
+ return r;
+}
+
+/** ASN.1-encode the public portion of <b>pk</b> into <b>dest</b>.
+ * Return -1 on error, or the number of characters used on success.
+ */
+int
+crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
+{
+ int len;
+ unsigned char *buf = NULL;
+
+ len = i2d_RSAPublicKey(pk->key, &buf);
+ if (len < 0 || buf == NULL)
+ return -1;
+
+ if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
+ OPENSSL_free(buf);
+ return -1;
+ }
+ /* We don't encode directly into 'dest', because that would be illegal
+ * type-punning. (C99 is smarter than me, C99 is smarter than me...)
+ */
+ memcpy(dest,buf,len);
+ OPENSSL_free(buf);
+ return len;
+}
+
+/** Decode an ASN.1-encoded public key from <b>str</b>; return the result on
+ * success and NULL on failure.
+ */
+crypto_pk_t *
+crypto_pk_asn1_decode(const char *str, size_t len)
+{
+ RSA *rsa;
+ unsigned char *buf;
+ const unsigned char *cp;
+ cp = buf = tor_malloc(len);
+ memcpy(buf,str,len);
+ rsa = d2i_RSAPublicKey(NULL, &cp, len);
+ tor_free(buf);
+ if (!rsa) {
+ crypto_openssl_log_errors(LOG_WARN,"decoding public key");
+ return NULL;
+ }
+ return crypto_new_pk_from_rsa_(rsa);
+}
+
+/** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
+ * Base64 encoding of the DER representation of the private key as a NUL
+ * terminated string, and return it via <b>priv_out</b>. Return 0 on
+ * success, -1 on failure.
+ *
+ * It is the caller's responsibility to sanitize and free the resulting buffer.
+ */
+int
+crypto_pk_base64_encode(const crypto_pk_t *pk, char **priv_out)
+{
+ unsigned char *der = NULL;
+ int der_len;
+ int ret = -1;
+
+ *priv_out = NULL;
+
+ der_len = i2d_RSAPrivateKey(pk->key, &der);
+ if (der_len < 0 || der == NULL)
+ return ret;
+
+ size_t priv_len = base64_encode_size(der_len, 0) + 1;
+ char *priv = tor_malloc_zero(priv_len);
+ if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
+ *priv_out = priv;
+ ret = 0;
+ } else {
+ tor_free(priv);
+ }
+
+ memwipe(der, 0, der_len);
+ OPENSSL_free(der);
+ return ret;
+}
+
+/** Given a string containing the Base64 encoded DER representation of the
+ * private key <b>str</b>, decode and return the result on success, or NULL
+ * on failure.
+ */
+crypto_pk_t *
+crypto_pk_base64_decode(const char *str, size_t len)
+{
+ crypto_pk_t *pk = NULL;
+
+ char *der = tor_malloc_zero(len + 1);
+ int der_len = base64_decode(der, len, str, len);
+ if (der_len <= 0) {
+ log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
+ goto out;
+ }
+
+ const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
+ RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
+ if (!rsa) {
+ crypto_openssl_log_errors(LOG_WARN, "decoding private key");
+ goto out;
+ }
+
+ pk = crypto_new_pk_from_rsa_(rsa);
+
+ /* Make sure it's valid. */
+ if (crypto_pk_check_key(pk) <= 0) {
+ crypto_pk_free(pk);
+ pk = NULL;
+ goto out;
+ }
+
+ out:
+ memwipe(der, 0, len + 1);
+ tor_free(der);
+ return pk;
+}
diff --git a/src/lib/crypt_ops/include.am b/src/lib/crypt_ops/include.am
index f6164dd21..69bd7c2db 100644
--- a/src/lib/crypt_ops/include.am
+++ b/src/lib/crypt_ops/include.am
@@ -19,6 +19,7 @@ src_lib_libtor_crypt_ops_a_SOURCES = \
src/lib/crypt_ops/crypto_pwbox.c \
src/lib/crypt_ops/crypto_rand.c \
src/lib/crypt_ops/crypto_rsa.c \
+ src/lib/crypt_ops/crypto_rsa_openssl.c \
src/lib/crypt_ops/crypto_s2k.c \
src/lib/crypt_ops/crypto_util.c \
src/lib/crypt_ops/digestset.c
1
0
commit 38212d2e40a1eae9f65c1a695e478854177c0783
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Jul 19 09:00:12 2018 -0400
Remove a redundant function.
---
src/lib/crypt_ops/crypto_rsa_openssl.c | 22 ++++++----------------
1 file changed, 6 insertions(+), 16 deletions(-)
diff --git a/src/lib/crypt_ops/crypto_rsa_openssl.c b/src/lib/crypt_ops/crypto_rsa_openssl.c
index a342c1e7d..cd9fb5266 100644
--- a/src/lib/crypt_ops/crypto_rsa_openssl.c
+++ b/src/lib/crypt_ops/crypto_rsa_openssl.c
@@ -41,11 +41,10 @@ struct crypto_pk_t
RSA *key; /**< The key itself */
};
-/** used internally: quicly validate a crypto_pk_t object as a private key.
- * Return 1 iff the public key is valid, 0 if obviously invalid.
- */
-static int
-crypto_pk_private_ok(const crypto_pk_t *k)
+/** Return true iff <b>key</b> contains the private-key portion of the RSA
+ * key. */
+int
+crypto_pk_key_is_private(const crypto_pk_t *k)
{
#ifdef OPENSSL_1_1_API
if (!k || !k->key)
@@ -371,7 +370,7 @@ crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
char *s;
int r;
- tor_assert(crypto_pk_private_ok(env));
+ tor_assert(crypto_pk_key_is_private(env));
if (!(bio = BIO_new(BIO_s_mem())))
return -1;
@@ -407,15 +406,6 @@ crypto_pk_check_key(crypto_pk_t *env)
return r;
}
-/** Return true iff <b>key</b> contains the private-key portion of the RSA
- * key. */
-int
-crypto_pk_key_is_private(const crypto_pk_t *key)
-{
- tor_assert(key);
- return crypto_pk_private_ok(key);
-}
-
/** Return true iff <b>env</b> contains a public key whose public exponent
* equals 65537.
*/
@@ -545,7 +535,7 @@ crypto_pk_copy_full(crypto_pk_t *env)
tor_assert(env);
tor_assert(env->key);
- if (crypto_pk_private_ok(env)) {
+ if (crypto_pk_key_is_private(env)) {
new_key = RSAPrivateKey_dup(env->key);
privatekey = 1;
} else {
1
0
commit 0812f1cbc2f528f0acb785e2fea416b9f2113c7c
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Jul 19 09:23:30 2018 -0400
Use a constant for "65537"
---
src/lib/crypt_ops/crypto_rsa.h | 3 +++
src/lib/crypt_ops/crypto_rsa_openssl.c | 6 +++---
2 files changed, 6 insertions(+), 3 deletions(-)
diff --git a/src/lib/crypt_ops/crypto_rsa.h b/src/lib/crypt_ops/crypto_rsa.h
index 88978bf37..4a5d92c6b 100644
--- a/src/lib/crypt_ops/crypto_rsa.h
+++ b/src/lib/crypt_ops/crypto_rsa.h
@@ -33,6 +33,9 @@
* including terminating NUL. */
#define FINGERPRINT_LEN 49
+/** Value of 'e' to use in our public keys */
+#define TOR_RSA_EXPONENT 65537
+
/** A public key, or a public/private key-pair. */
typedef struct crypto_pk_t crypto_pk_t;
diff --git a/src/lib/crypt_ops/crypto_rsa_openssl.c b/src/lib/crypt_ops/crypto_rsa_openssl.c
index 20be34cbd..d1b56c3b6 100644
--- a/src/lib/crypt_ops/crypto_rsa_openssl.c
+++ b/src/lib/crypt_ops/crypto_rsa_openssl.c
@@ -158,7 +158,7 @@ crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
RSA *r = NULL;
if (!e)
goto done;
- if (! BN_set_word(e, 65537))
+ if (! BN_set_word(e, TOR_RSA_EXPONENT))
goto done;
r = RSA_new();
if (!r)
@@ -408,7 +408,7 @@ crypto_pk_check_key(crypto_pk_t *env)
}
/** Return true iff <b>env</b> contains a public key whose public exponent
- * equals 65537.
+ * equals TOR_RSA_EXPONENT.
*/
int
crypto_pk_public_exponent_ok(crypto_pk_t *env)
@@ -424,7 +424,7 @@ crypto_pk_public_exponent_ok(crypto_pk_t *env)
#else
e = env->key->e;
#endif /* defined(OPENSSL_1_1_API) */
- return BN_is_word(e, 65537);
+ return BN_is_word(e, TOR_RSA_EXPONENT);
}
/** Compare the public-key components of a and b. Return less than 0
1
0
05 Sep '18
commit 824009cde52d40c937c23670b71e9c5b28d2e1f3
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Jul 19 09:07:08 2018 -0400
Rename openssl-bridging functions in crypto_rsa
These functions exist only to expose RSA keys to other places in Tor
that use OpenSSL; let's be specific about their purpose.
---
src/lib/crypt_ops/crypto_rsa.h | 10 ++++++----
src/lib/crypt_ops/crypto_rsa_openssl.c | 21 +++++++++++----------
src/lib/tls/tortls.c | 14 +++++++-------
src/test/test_tortls.c | 6 +++---
src/tools/tor-gencert.c | 7 +++----
5 files changed, 30 insertions(+), 28 deletions(-)
diff --git a/src/lib/crypt_ops/crypto_rsa.h b/src/lib/crypt_ops/crypto_rsa.h
index d1f9d57aa..88978bf37 100644
--- a/src/lib/crypt_ops/crypto_rsa.h
+++ b/src/lib/crypt_ops/crypto_rsa.h
@@ -104,14 +104,16 @@ int crypto_pk_get_common_digests(crypto_pk_t *pk,
int crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out);
crypto_pk_t *crypto_pk_base64_decode_private(const char *str, size_t len);
+#ifdef ENABLE_OPENSSL
/* Prototypes for private functions only used by tortls.c, crypto.c, and the
* unit tests. */
struct rsa_st;
-struct rsa_st *crypto_pk_get_rsa_(crypto_pk_t *env);
-crypto_pk_t *crypto_new_pk_from_rsa_(struct rsa_st *rsa);
-MOCK_DECL(struct evp_pkey_st *, crypto_pk_get_evp_pkey_,(crypto_pk_t *env,
- int private));
struct evp_pkey_st;
+struct rsa_st *crypto_pk_get_openssl_rsa_(crypto_pk_t *env);
+crypto_pk_t *crypto_new_pk_from_openssl_rsa_(struct rsa_st *rsa);
+MOCK_DECL(struct evp_pkey_st *, crypto_pk_get_openssl_evp_pkey_,(
+ crypto_pk_t *env,int private));
+#endif
#ifdef TOR_UNIT_TESTS
void crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src);
diff --git a/src/lib/crypt_ops/crypto_rsa_openssl.c b/src/lib/crypt_ops/crypto_rsa_openssl.c
index cd9fb5266..20be34cbd 100644
--- a/src/lib/crypt_ops/crypto_rsa_openssl.c
+++ b/src/lib/crypt_ops/crypto_rsa_openssl.c
@@ -58,9 +58,10 @@ crypto_pk_key_is_private(const crypto_pk_t *k)
#endif /* defined(OPENSSL_1_1_API) */
}
-/** used by tortls.c: wrap an RSA* in a crypto_pk_t. */
+/** used by tortls.c: wrap an RSA* in a crypto_pk_t. Takes ownership of
+ * its argument. */
crypto_pk_t *
-crypto_new_pk_from_rsa_(RSA *rsa)
+crypto_new_pk_from_openssl_rsa_(RSA *rsa)
{
crypto_pk_t *env;
tor_assert(rsa);
@@ -70,19 +71,19 @@ crypto_new_pk_from_rsa_(RSA *rsa)
return env;
}
-/** Helper, used by tor-gencert.c. Return the RSA from a
+/** Helper, used by tor-gencert.c. Return a copy of the private RSA from a
* crypto_pk_t. */
RSA *
-crypto_pk_get_rsa_(crypto_pk_t *env)
+crypto_pk_get_openssl_rsa_(crypto_pk_t *env)
{
- return env->key;
+ return RSA_PrivateKeyDup(env->key);
}
/** used by tortls.c: get an equivalent EVP_PKEY* for a crypto_pk_t. Iff
* private is set, include the private-key portion of the key. Return a valid
* pointer on success, and NULL on failure. */
MOCK_IMPL(EVP_PKEY *,
-crypto_pk_get_evp_pkey_,(crypto_pk_t *env, int private))
+crypto_pk_get_openssl_evp_pkey_,(crypto_pk_t *env, int private))
{
RSA *key = NULL;
EVP_PKEY *pkey = NULL;
@@ -117,7 +118,7 @@ crypto_pk_new,(void))
rsa = RSA_new();
tor_assert(rsa);
- return crypto_new_pk_from_rsa_(rsa);
+ return crypto_new_pk_from_openssl_rsa_(rsa);
}
/** Release a reference to an asymmetric key; when all the references
@@ -556,7 +557,7 @@ crypto_pk_copy_full(crypto_pk_t *env)
/* LCOV_EXCL_STOP */
}
- return crypto_new_pk_from_rsa_(new_key);
+ return crypto_new_pk_from_openssl_rsa_(new_key);
}
/** Encrypt <b>fromlen</b> bytes from <b>from</b> with the public key
@@ -729,7 +730,7 @@ crypto_pk_asn1_decode(const char *str, size_t len)
crypto_openssl_log_errors(LOG_WARN,"decoding public key");
return NULL;
}
- return crypto_new_pk_from_rsa_(rsa);
+ return crypto_new_pk_from_openssl_rsa_(rsa);
}
/** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
@@ -789,7 +790,7 @@ crypto_pk_base64_decode_private(const char *str, size_t len)
goto out;
}
- pk = crypto_new_pk_from_rsa_(rsa);
+ pk = crypto_new_pk_from_openssl_rsa_(rsa);
/* Make sure it's valid. */
if (crypto_pk_check_key(pk) <= 0) {
diff --git a/src/lib/tls/tortls.c b/src/lib/tls/tortls.c
index 875ed95f8..466df8966 100644
--- a/src/lib/tls/tortls.c
+++ b/src/lib/tls/tortls.c
@@ -539,9 +539,9 @@ tor_tls_create_certificate,(crypto_pk_t *rsa,
tor_assert(cname);
tor_assert(rsa_sign);
tor_assert(cname_sign);
- if (!(sign_pkey = crypto_pk_get_evp_pkey_(rsa_sign,1)))
+ if (!(sign_pkey = crypto_pk_get_openssl_evp_pkey_(rsa_sign,1)))
goto error;
- if (!(pkey = crypto_pk_get_evp_pkey_(rsa,0)))
+ if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,0)))
goto error;
if (!(x509 = X509_new()))
goto error;
@@ -746,7 +746,7 @@ tor_x509_cert_new,(X509 *x509_cert))
if ((pkey = X509_get_pubkey(x509_cert)) &&
(rsa = EVP_PKEY_get1_RSA(pkey))) {
- crypto_pk_t *pk = crypto_new_pk_from_rsa_(rsa);
+ crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(rsa);
if (crypto_pk_get_common_digests(pk, &cert->pkey_digests) < 0) {
crypto_pk_free(pk);
EVP_PKEY_free(pkey);
@@ -915,7 +915,7 @@ tor_tls_cert_get_key(tor_x509_cert_t *cert)
EVP_PKEY_free(pkey);
return NULL;
}
- result = crypto_new_pk_from_rsa_(rsa);
+ result = crypto_new_pk_from_openssl_rsa_(rsa);
EVP_PKEY_free(pkey);
return result;
}
@@ -1270,7 +1270,7 @@ tor_tls_context_new(crypto_pk_t *identity, unsigned int key_lifetime,
SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
if (!is_client) {
tor_assert(rsa);
- if (!(pkey = crypto_pk_get_evp_pkey_(rsa,1)))
+ if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,1)))
goto error;
if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
goto error;
@@ -2277,7 +2277,7 @@ tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity_key)
rsa = EVP_PKEY_get1_RSA(id_pkey);
if (!rsa)
goto done;
- *identity_key = crypto_new_pk_from_rsa_(rsa);
+ *identity_key = crypto_new_pk_from_openssl_rsa_(rsa);
r = 0;
@@ -2362,7 +2362,7 @@ tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
{
X509 *newc = X509_dup(inp->cert);
X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
- EVP_PKEY *pk = crypto_pk_get_evp_pkey_(signing_key, 1);
+ EVP_PKEY *pk = crypto_pk_get_openssl_evp_pkey_(signing_key, 1);
tor_assert(X509_sign(newc, pk, EVP_sha256()));
EVP_PKEY_free(pk);
return tor_x509_cert_new(newc);
diff --git a/src/test/test_tortls.c b/src/test/test_tortls.c
index 54e5eca4f..49a39e264 100644
--- a/src/test/test_tortls.c
+++ b/src/test/test_tortls.c
@@ -690,7 +690,7 @@ test_tortls_get_my_client_auth_key(void *ignored)
RSA *k = RSA_new();
ctx = tor_malloc_zero(sizeof(tor_tls_context_t));
- expected = crypto_new_pk_from_rsa_(k);
+ expected = crypto_new_pk_from_openssl_rsa_(k);
ctx->auth_key = expected;
client_tls_context = NULL;
@@ -2609,7 +2609,7 @@ test_tortls_create_certificate(void *ignored)
pk1 = crypto_pk_new();
pk2 = crypto_pk_new();
- MOCK(crypto_pk_get_evp_pkey_, fixed_crypto_pk_get_evp_pkey_);
+ MOCK(crypto_pk_get_openssl_evp_pkey_, fixed_crypto_pk_get_evp_pkey_);
fixed_crypto_pk_get_evp_pkey_result_index = 0;
fixed_crypto_pk_get_evp_pkey_result[0] = NULL;
ret = tor_tls_create_certificate(pk1, pk2, "hello", "hello2", 1);
@@ -2628,7 +2628,7 @@ test_tortls_create_certificate(void *ignored)
tt_assert(!ret);
done:
- UNMOCK(crypto_pk_get_evp_pkey_);
+ UNMOCK(crypto_pk_get_openssl_evp_pkey_);
crypto_pk_free(pk1);
crypto_pk_free(pk2);
}
diff --git a/src/tools/tor-gencert.c b/src/tools/tor-gencert.c
index 63e24d922..e0ac3dec8 100644
--- a/src/tools/tor-gencert.c
+++ b/src/tools/tor-gencert.c
@@ -239,8 +239,7 @@ generate_key(int bits)
crypto_pk_t *env = crypto_pk_new();
if (crypto_pk_generate_key_with_bits(env,bits)<0)
goto done;
- rsa = crypto_pk_get_rsa_(env);
- rsa = RSAPrivateKey_dup(rsa);
+ rsa = crypto_pk_get_openssl_rsa_(env);
done:
crypto_pk_free(env);
return rsa;
@@ -416,7 +415,7 @@ static int
get_fingerprint(EVP_PKEY *pkey, char *out)
{
int r = -1;
- crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
+ crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(EVP_PKEY_get1_RSA(pkey));
if (pk) {
r = crypto_pk_get_fingerprint(pk, out, 0);
crypto_pk_free(pk);
@@ -429,7 +428,7 @@ static int
get_digest(EVP_PKEY *pkey, char *out)
{
int r = -1;
- crypto_pk_t *pk = crypto_new_pk_from_rsa_(EVP_PKEY_get1_RSA(pkey));
+ crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(EVP_PKEY_get1_RSA(pkey));
if (pk) {
r = crypto_pk_get_digest(pk, out);
crypto_pk_free(pk);
1
0
[tor/master] Add rudimentary support for PEM-encoding, since NSS doesn't do that.
by nickm@torproject.org 05 Sep '18
by nickm@torproject.org 05 Sep '18
05 Sep '18
commit 9566ed6fd9e4aab2ce6b84afc2f7112550cf0483
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Jul 19 15:47:48 2018 -0400
Add rudimentary support for PEM-encoding, since NSS doesn't do that.
---
src/lib/encoding/.may_include | 1 +
src/lib/encoding/include.am | 2 +
src/lib/encoding/pem.c | 106 ++++++++++++++++++++++++++++++++++++
src/lib/encoding/pem.h | 26 +++++++++
src/test/include.am | 1 +
src/test/test.c | 1 +
src/test/test.h | 1 +
src/test/test_pem.c | 122 ++++++++++++++++++++++++++++++++++++++++++
8 files changed, 260 insertions(+)
diff --git a/src/lib/encoding/.may_include b/src/lib/encoding/.may_include
index 92231b513..7c2ef3692 100644
--- a/src/lib/encoding/.may_include
+++ b/src/lib/encoding/.may_include
@@ -1,5 +1,6 @@
orconfig.h
lib/cc/*.h
+lib/ctime/*.h
lib/encoding/*.h
lib/intmath/*.h
lib/log/*.h
diff --git a/src/lib/encoding/include.am b/src/lib/encoding/include.am
index 868e531b6..2d2aa3988 100644
--- a/src/lib/encoding/include.am
+++ b/src/lib/encoding/include.am
@@ -9,6 +9,7 @@ src_lib_libtor_encoding_a_SOURCES = \
src/lib/encoding/confline.c \
src/lib/encoding/cstring.c \
src/lib/encoding/keyval.c \
+ src/lib/encoding/pem.c \
src/lib/encoding/time_fmt.c
src_lib_libtor_encoding_testing_a_SOURCES = \
@@ -21,4 +22,5 @@ noinst_HEADERS += \
src/lib/encoding/confline.h \
src/lib/encoding/cstring.h \
src/lib/encoding/keyval.h \
+ src/lib/encoding/pem.h \
src/lib/encoding/time_fmt.h
diff --git a/src/lib/encoding/pem.c b/src/lib/encoding/pem.c
new file mode 100644
index 000000000..0d4a814f6
--- /dev/null
+++ b/src/lib/encoding/pem.c
@@ -0,0 +1,106 @@
+/* Copyright (c) 2001, Matej Pfajfar.
+ * Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file pem.c
+ *
+ * \brief Implement a trivial version of PEM encoding, for use with NSS.
+ *
+ * We deliberately do not support any encryption here.
+ **/
+
+#include "orconfig.h"
+
+#include "lib/encoding/pem.h"
+
+#include "lib/ctime/di_ops.h"
+#include "lib/encoding/binascii.h"
+#include "lib/log/util_bug.h"
+#include "lib/malloc/malloc.h"
+#include "lib/string/printf.h"
+#include "lib/string/util_string.h"
+
+#include <string.h>
+
+/**
+ * Return the length of a <b>src_len</b>-byte object when tagged with
+ * <b>objtype</b> and PEM-encoded. Includes terminating NUL.
+ */
+size_t
+pem_encoded_size(size_t src_len, const char *objtype)
+{
+ return
+ strlen("-----BEGIN -----\n") +
+ strlen("-----END -----\n") +
+ strlen(objtype) * 2 +
+ base64_encode_size(src_len, BASE64_ENCODE_MULTILINE)
+ + 1;
+}
+
+/**
+ * PEM-encode the <b>srclen</b>-byte object at <b>src</b> into the
+ * <b>destlen<\b>-byte buffer at <b>dest</b>, tagging it with <b>objtype</b>.
+ * Return 0 on success and -1 on failure.
+ */
+int
+pem_encode(char *dest, size_t destlen, const uint8_t *src, size_t srclen,
+ const char *objtype)
+{
+ if (tor_snprintf(dest, destlen, "-----BEGIN %s-----\n", objtype) < 0)
+ return -1;
+
+ size_t offset = strlen(dest);
+
+ int n = base64_encode(dest + offset, destlen - offset,
+ (const char *)src, srclen, BASE64_ENCODE_MULTILINE);
+ if (n < 0)
+ return -1;
+ offset += n;
+ if (BUG(offset > destlen))
+ return -1;
+
+ if (tor_snprintf(dest + offset, destlen - offset,
+ "-----END %s-----\n", objtype) < 0)
+ return -1;
+
+ tor_assert(strlen(dest) + 1 <= pem_encoded_size(srclen, objtype));
+ return 0;
+}
+
+/**
+ * Given a PEM-encoded block of size <b>srclen</b> in <b>src</b>, if it has
+ * object type <b>objtype</b>, decode it into the <b>destlen</b>-byte buffer
+ * at <b>dest</b>. Return the number of characters decoded on success, or -1
+ * on failure.
+ */
+int
+pem_decode(uint8_t *dest, size_t destlen, const char *src, size_t srclen,
+ const char *objtype)
+{
+ const char *eos = src + srclen;
+
+ src = eat_whitespace_eos(src, eos);
+
+ char *tag = NULL;
+ tor_asprintf(&tag, "-----BEGIN %s-----\n", objtype);
+ if ((size_t)(eos-src) < strlen(tag) || fast_memneq(src, tag, strlen(tag))) {
+ tor_free(tag);
+ return -1;
+ }
+ src += strlen(tag);
+ tor_free(tag);
+
+ // NOTE lack of trailing \n. We do not enforce its presence.
+ tor_asprintf(&tag, "\n-----END %s-----", objtype);
+ const char *end_of_base64 = tor_memstr(src, eos-src, tag);
+ tor_free(tag);
+ if (end_of_base64 == NULL)
+ return -1;
+
+ /* Should we actually allow extra stuff at the end? */
+
+ return base64_decode((char*)dest, destlen, src, end_of_base64-src);
+}
diff --git a/src/lib/encoding/pem.h b/src/lib/encoding/pem.h
new file mode 100644
index 000000000..ba2122884
--- /dev/null
+++ b/src/lib/encoding/pem.h
@@ -0,0 +1,26 @@
+/* Copyright (c) 2001, Matej Pfajfar.
+ * Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file pem.h
+ *
+ * \brief Header for pem.c
+ **/
+
+#ifndef TOR_PEM_H
+#define TOR_PEM_H
+
+#include "orconfig.h"
+#include <stddef.h>
+#include "lib/cc/torint.h"
+
+size_t pem_encoded_size(size_t src_len, const char *objtype);
+int pem_encode(char *dest, size_t destlen, const uint8_t *src, size_t srclen,
+ const char *objtype);
+int pem_decode(uint8_t *dest, size_t destlen, const char *src, size_t srclen,
+ const char *objtype);
+
+#endif
diff --git a/src/test/include.am b/src/test/include.am
index 46990597f..68372adc7 100644
--- a/src/test/include.am
+++ b/src/test/include.am
@@ -151,6 +151,7 @@ src_test_test_SOURCES += \
src/test/test_oom.c \
src/test/test_oos.c \
src/test/test_options.c \
+ src/test/test_pem.c \
src/test/test_periodic_event.c \
src/test/test_policy.c \
src/test/test_procmon.c \
diff --git a/src/test/test.c b/src/test/test.c
index 745aa987a..94eae5a4f 100644
--- a/src/test/test.c
+++ b/src/test/test.c
@@ -867,6 +867,7 @@ struct testgroup_t testgroups[] = {
{ "crypto/", crypto_tests },
{ "crypto/ope/", crypto_ope_tests },
{ "crypto/openssl/", crypto_openssl_tests },
+ { "crypto/pem/", pem_tests },
{ "dir/", dir_tests },
{ "dir_handle_get/", dir_handle_get_tests },
{ "dir/md/", microdesc_tests },
diff --git a/src/test/test.h b/src/test/test.h
index bfe50cbb8..b3a73271e 100644
--- a/src/test/test.h
+++ b/src/test/test.h
@@ -234,6 +234,7 @@ extern struct testcase_t nodelist_tests[];
extern struct testcase_t oom_tests[];
extern struct testcase_t oos_tests[];
extern struct testcase_t options_tests[];
+extern struct testcase_t pem_tests[];
extern struct testcase_t periodic_event_tests[];
extern struct testcase_t policy_tests[];
extern struct testcase_t procmon_tests[];
diff --git a/src/test/test_pem.c b/src/test/test_pem.c
new file mode 100644
index 000000000..2bae286e2
--- /dev/null
+++ b/src/test/test_pem.c
@@ -0,0 +1,122 @@
+/* Copyright (c) 2001-2004, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#include "orconfig.h"
+
+#include "lib/encoding/pem.h"
+#include "lib/cc/compat_compiler.h"
+#include "lib/malloc/malloc.h"
+
+#include "test/test.h"
+
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static const char example_pre[] =
+ "Lest you get the wrong impression, we wombats "
+ "are not in the habit of tunneling madly about, without any supplies "
+ "or even a map."; /* -- Ursula Vernon, _Digger_ */
+static const char expected[] =
+ "-----BEGIN WOMBAT QUOTE-----\n"
+ "TGVzdCB5b3UgZ2V0IHRoZSB3cm9uZyBpbXByZXNzaW9uLCB3ZSB3b21iYXRzIGFy\n"
+ "ZSBub3QgaW4gdGhlIGhhYml0IG9mIHR1bm5lbGluZyBtYWRseSBhYm91dCwgd2l0\n"
+ "aG91dCBhbnkgc3VwcGxpZXMgb3IgZXZlbiBhIG1hcC4=\n"
+ "-----END WOMBAT QUOTE-----\n";
+
+static void
+test_crypto_pem_encode(void *arg)
+{
+ (void)arg;
+
+ char buf[4096];
+
+ int n = (int) pem_encoded_size(strlen(example_pre), "WOMBAT QUOTE");
+
+ int n2 = pem_encode(buf, sizeof(buf),
+ (const unsigned char *)example_pre, strlen(example_pre),
+ "WOMBAT QUOTE");
+ tt_int_op(strlen(buf)+1, OP_EQ, n);
+ tt_int_op(n2, OP_EQ, 0);
+ tt_str_op(buf, OP_EQ, expected);
+
+ /* Now make sure it succeeds if the buffer is exactly the length we want. */
+ memset(buf, 0, sizeof(buf));
+ n2 = pem_encode(buf, n, (const unsigned char *)example_pre,
+ strlen(example_pre), "WOMBAT QUOTE");
+ tt_int_op(n2, OP_EQ, 0);
+ tt_str_op(buf, OP_EQ, expected);
+
+ /* Make sure it fails if the buffer is too short. */
+ memset(buf, 0, sizeof(buf));
+ n2 = pem_encode(buf, n - 1, (const unsigned char *)example_pre,
+ strlen(example_pre), "WOMBAT QUOTE");
+ tt_int_op(n2, OP_EQ, -1);
+
+ done:
+ ;
+}
+
+static void
+test_crypto_pem_decode(void *arg)
+{
+ (void)arg;
+
+ unsigned char buf[4096];
+
+ /* Try a straightforward decoding. */
+ int n = pem_decode(buf, sizeof(buf),
+ expected, strlen(expected),
+ "WOMBAT QUOTE");
+ tt_int_op(n, OP_EQ, strlen(example_pre));
+ tt_mem_op(buf, OP_EQ, example_pre, n);
+
+ /* Succeed if the buffer is exactly the right size. */
+ memset(buf, 0xff, sizeof(buf));
+ n = pem_decode(buf, strlen(example_pre),
+ expected, strlen(expected),
+ "WOMBAT QUOTE");
+ tt_int_op(n, OP_EQ, strlen(example_pre));
+ tt_mem_op(buf, OP_EQ, example_pre, n);
+ tt_int_op(buf[n], OP_EQ, 0xff);
+
+ /* Verify that it fails if the buffer is too small. */
+ memset(buf, 0xff, sizeof(buf));
+ n = pem_decode(buf, strlen(example_pre) - 1,
+ expected, strlen(expected),
+ "WOMBAT QUOTE");
+ tt_int_op(n, OP_EQ, -1);
+
+ /* Verify that it fails with an incorrect tag. */
+ memset(buf, 0xff, sizeof(buf));
+ n = pem_decode(buf, sizeof(buf),
+ expected, strlen(expected),
+ "QUOKKA VOTE");
+ tt_int_op(n, OP_EQ, -1);
+
+ /* Try truncated buffers of different sizes. */
+ size_t i;
+ for (i = 0; i <= strlen(expected); ++i) {
+ char *truncated = tor_memdup(expected, i);
+ n = pem_decode(buf, sizeof(buf),
+ truncated, i,
+ "WOMBAT QUOTE");
+ tor_free(truncated);
+ if (i < strlen(expected) - 1) {
+ tt_int_op(n, OP_EQ, -1);
+ } else {
+ tt_int_op(n, OP_EQ, strlen(example_pre));
+ }
+ }
+
+ done:
+ ;
+}
+
+struct testcase_t pem_tests[] = {
+ { "encode", test_crypto_pem_encode, 0, NULL, NULL },
+ { "decode", test_crypto_pem_decode, 0, NULL, NULL },
+ END_OF_TESTCASES
+};
1
0
commit b94e7de7dbf31a9b9bfe2d376013e279f15500f8
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Thu Jul 19 17:09:23 2018 -0400
Refactor crypto_rsa to use pem module.
This cleans up a lot of junk from crypto_rsa_openssl, and will
save us duplicated code in crypto_rsa_nss (when it exists).
(Actually, it already exists, but I am going to use git rebase so
that this commit precedes the creation of crypto_rsa_nss.)
---
src/lib/crypt_ops/crypto_rsa.c | 253 ++++++++++++++++++++++++++
src/lib/crypt_ops/crypto_rsa.h | 16 +-
src/lib/crypt_ops/crypto_rsa_openssl.c | 320 +++++----------------------------
src/test/test_crypto.c | 3 +-
src/test/testing_rsakeys.c | 3 +-
5 files changed, 317 insertions(+), 278 deletions(-)
diff --git a/src/lib/crypt_ops/crypto_rsa.c b/src/lib/crypt_ops/crypto_rsa.c
index 328fd732d..0f80bc967 100644
--- a/src/lib/crypt_ops/crypto_rsa.c
+++ b/src/lib/crypt_ops/crypto_rsa.c
@@ -23,8 +23,12 @@
#include "lib/log/log.h"
#include "lib/encoding/binascii.h"
+#include "lib/encoding/pem.h"
#include <string.h>
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
/** Return the number of bytes added by padding method <b>padding</b>.
*/
@@ -388,3 +392,252 @@ crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
tor_free(buf);
return rv;
}
+
+static const char RSA_PUBLIC_TAG[] = "RSA PUBLIC KEY";
+static const char RSA_PRIVATE_TAG[] = "RSA PRIVATE KEY";
+
+/** PEM-encode the public key portion of <b>env</b> and write it to a
+ * newly allocated string. On success, set *<b>dest</b> to the new
+ * string, *<b>len</b> to the string's length, and return 0. On
+ * failure, return -1.
+ */
+int
+crypto_pk_write_public_key_to_string(crypto_pk_t *env,
+ char **dest, size_t *len)
+{
+ size_t buflen = crypto_pk_keysize(env) * 3;
+ char *buf = tor_malloc(buflen);
+ char *result = NULL;
+ size_t resultlen = 0;
+ int rv = -1;
+
+ int n = crypto_pk_asn1_encode(env, buf, buflen);
+ if (n < 0)
+ goto done;
+
+ resultlen = pem_encoded_size(n, RSA_PUBLIC_TAG);
+ result = tor_malloc(resultlen);
+ if (pem_encode(result, resultlen,
+ (const unsigned char *)buf, n, RSA_PUBLIC_TAG) < 0) {
+ goto done;
+ }
+
+ *dest = result;
+ *len = resultlen;
+ rv = 0;
+
+ done:
+ if (rv < 0 && result) {
+ memwipe(result, 0, resultlen);
+ tor_free(result);
+ }
+ memwipe(buf, 0, buflen);
+ tor_free(buf);
+ return rv;
+}
+
+/** PEM-encode the private key portion of <b>env</b> and write it to a
+ * newly allocated string. On success, set *<b>dest</b> to the new
+ * string, *<b>len</b> to the string's length, and return 0. On
+ * failure, return -1.
+ */
+int
+crypto_pk_write_private_key_to_string(crypto_pk_t *env,
+ char **dest, size_t *len)
+{
+ size_t buflen = crypto_pk_keysize(env) * 16;
+ char *buf = tor_malloc(buflen);
+ char *result = NULL;
+ size_t resultlen = 0;
+ int rv = -1;
+
+ int n = crypto_pk_asn1_encode_private(env, buf, buflen);
+ if (n < 0)
+ goto done;
+
+ resultlen = pem_encoded_size(n, RSA_PRIVATE_TAG);
+ result = tor_malloc(resultlen);
+ if (pem_encode(result, resultlen,
+ (const unsigned char *)buf, n, RSA_PRIVATE_TAG) < 0)
+ goto done;
+
+ *dest = result;
+ *len = resultlen;
+ rv = 0;
+ done:
+ if (rv < 0 && result) {
+ memwipe(result, 0, resultlen);
+ tor_free(result);
+ }
+ memwipe(buf, 0, buflen);
+ tor_free(buf);
+ return rv;
+}
+
+/** Read a PEM-encoded public key from the first <b>len</b> characters of
+ * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
+ * failure.
+ */
+int
+crypto_pk_read_public_key_from_string(crypto_pk_t *env,
+ const char *src, size_t len)
+{
+ if (len == (size_t)-1)
+ len = strlen(src);
+
+ size_t buflen = len;
+ uint8_t *buf = tor_malloc(buflen);
+ int rv = -1;
+
+ int n = pem_decode(buf, buflen, src, len, RSA_PUBLIC_TAG);
+ if (n < 0)
+ goto done;
+
+ crypto_pk_t *pk = crypto_pk_asn1_decode((const char*)buf, n);
+ if (! pk)
+ goto done;
+
+ crypto_pk_assign_public(env, pk);
+ crypto_pk_free(pk);
+ rv = 0;
+
+ done:
+ memwipe(buf, 0, buflen);
+ tor_free(buf);
+ return rv;
+}
+
+/** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
+ * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
+ * the string is nul-terminated.
+ */
+int
+crypto_pk_read_private_key_from_string(crypto_pk_t *env,
+ const char *s, ssize_t len)
+{
+ if (len == -1)
+ len = strlen(s);
+
+ size_t buflen = len;
+ uint8_t *buf = tor_malloc(buflen);
+ int rv = -1;
+
+ int n = pem_decode(buf, buflen, s, len, RSA_PRIVATE_TAG);
+ if (n < 0) {
+ goto done;
+ }
+
+ crypto_pk_t *pk = crypto_pk_asn1_decode_private((const char *)buf, n);
+ if (! pk)
+ goto done;
+
+ crypto_pk_assign_private(env, pk);
+ crypto_pk_free(pk);
+ rv = 0;
+
+ done:
+ memwipe(buf, 0, buflen);
+ tor_free(buf);
+ return rv;
+}
+
+/** Read a PEM-encoded private key from the file named by
+ * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
+ */
+int
+crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
+ const char *keyfile)
+{
+ struct stat st;
+ char *buf = read_file_to_str(keyfile, 0, &st);
+ if (!buf)
+ return -1;
+
+ int rv = crypto_pk_read_private_key_from_string(env, buf, st.st_size);
+ memwipe(buf, 0, st.st_size);
+ tor_free(buf);
+ return rv;
+}
+
+/** Write the private key from <b>env</b> into the file named by <b>fname</b>,
+ * PEM-encoded. Return 0 on success, -1 on failure.
+ */
+int
+crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
+ const char *fname)
+{
+ char *s = NULL;
+ size_t n = 0;
+
+ if (crypto_pk_write_private_key_to_string(env, &s, &n) < 0)
+ return -1;
+
+ int rv = write_bytes_to_file(fname, s, n, 0);
+ memwipe(s, 0, n);
+ tor_free(s);
+ return rv;
+}
+
+/** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
+ * Base64 encoding of the DER representation of the private key as a NUL
+ * terminated string, and return it via <b>priv_out</b>. Return 0 on
+ * success, -1 on failure.
+ *
+ * It is the caller's responsibility to sanitize and free the resulting buffer.
+ */
+int
+crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out)
+{
+ size_t buflen = crypto_pk_keysize(pk)*16;
+ char *buf = tor_malloc(buflen);
+ char *result = NULL;
+ size_t reslen = 0;
+ bool ok = false;
+
+ int n = crypto_pk_asn1_encode_private(pk, buf, buflen);
+
+ if (n < 0)
+ goto done;
+
+ reslen = base64_encode_size(n, 0)+1;
+ result = tor_malloc(reslen);
+ if (base64_encode(result, reslen, buf, n, 0) < 0)
+ goto done;
+
+ ok = true;
+
+ done:
+ memwipe(buf, 0, buflen);
+ tor_free(buf);
+ if (result && ! ok) {
+ memwipe(result, 0, reslen);
+ tor_free(result);
+ }
+ *priv_out = result;
+ return ok ? 0 : -1;
+}
+
+/** Given a string containing the Base64 encoded DER representation of the
+ * private key <b>str</b>, decode and return the result on success, or NULL
+ * on failure.
+ */
+crypto_pk_t *
+crypto_pk_base64_decode_private(const char *str, size_t len)
+{
+ crypto_pk_t *pk = NULL;
+
+ char *der = tor_malloc_zero(len + 1);
+ int der_len = base64_decode(der, len, str, len);
+ if (der_len <= 0) {
+ log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
+ goto out;
+ }
+
+ pk = crypto_pk_asn1_decode_private(der, der_len);
+
+ out:
+ memwipe(der, 0, len+1);
+ tor_free(der);
+
+ return pk;
+}
diff --git a/src/lib/crypt_ops/crypto_rsa.h b/src/lib/crypt_ops/crypto_rsa.h
index 4a5d92c6b..bcb2b51dd 100644
--- a/src/lib/crypt_ops/crypto_rsa.h
+++ b/src/lib/crypt_ops/crypto_rsa.h
@@ -93,6 +93,9 @@ int crypto_pk_private_sign(const crypto_pk_t *env, char *to, size_t tolen,
const char *from, size_t fromlen);
int crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len);
crypto_pk_t *crypto_pk_asn1_decode(const char *str, size_t len);
+int crypto_pk_asn1_encode_private(const crypto_pk_t *pk,
+ char *dest, size_t dest_len);
+crypto_pk_t *crypto_pk_asn1_decode_private(const char *str, size_t len);
int crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out,int add_space);
int crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out);
void crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in);
@@ -107,6 +110,14 @@ int crypto_pk_get_common_digests(crypto_pk_t *pk,
int crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out);
crypto_pk_t *crypto_pk_base64_decode_private(const char *str, size_t len);
+#ifdef TOR_UNIT_TESTS
+#ifdef ENABLE_NSS
+struct SECItemStr;
+STATIC int secitem_uint_cmp(const struct SECItemStr *a,
+ const struct SECItemStr *b);
+#endif
+#endif
+
#ifdef ENABLE_OPENSSL
/* Prototypes for private functions only used by tortls.c, crypto.c, and the
* unit tests. */
@@ -118,8 +129,7 @@ MOCK_DECL(struct evp_pkey_st *, crypto_pk_get_openssl_evp_pkey_,(
crypto_pk_t *env,int private));
#endif
-#ifdef TOR_UNIT_TESTS
-void crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src);
-#endif
+void crypto_pk_assign_public(crypto_pk_t *dest, const crypto_pk_t *src);
+void crypto_pk_assign_private(crypto_pk_t *dest, const crypto_pk_t *src);
#endif
diff --git a/src/lib/crypt_ops/crypto_rsa_openssl.c b/src/lib/crypt_ops/crypto_rsa_openssl.c
index d1b56c3b6..9a3729a87 100644
--- a/src/lib/crypt_ops/crypto_rsa_openssl.c
+++ b/src/lib/crypt_ops/crypto_rsa_openssl.c
@@ -183,216 +183,6 @@ crypto_pk_generate_key_with_bits,(crypto_pk_t *env, int bits))
return 0;
}
-/** A PEM callback that always reports a failure to get a password */
-static int
-pem_no_password_cb(char *buf, int size, int rwflag, void *u)
-{
- (void)buf;
- (void)size;
- (void)rwflag;
- (void)u;
- return -1;
-}
-
-/** Read a PEM-encoded private key from the <b>len</b>-byte string <b>s</b>
- * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
- * the string is nul-terminated.
- */
-int
-crypto_pk_read_private_key_from_string(crypto_pk_t *env,
- const char *s, ssize_t len)
-{
- BIO *b;
-
- tor_assert(env);
- tor_assert(s);
- tor_assert(len < INT_MAX && len < SSIZE_T_CEILING);
-
- /* Create a read-only memory BIO, backed by the string 's' */
- b = BIO_new_mem_buf((char*)s, (int)len);
- if (!b)
- return -1;
-
- if (env->key)
- RSA_free(env->key);
-
- env->key = PEM_read_bio_RSAPrivateKey(b,NULL,pem_no_password_cb,NULL);
-
- BIO_free(b);
-
- if (!env->key) {
- crypto_openssl_log_errors(LOG_WARN, "Error parsing private key");
- return -1;
- }
- return 0;
-}
-
-/** Read a PEM-encoded private key from the file named by
- * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
- */
-int
-crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
- const char *keyfile)
-{
- char *contents;
- int r;
-
- /* Read the file into a string. */
- contents = read_file_to_str(keyfile, 0, NULL);
- if (!contents) {
- log_warn(LD_CRYPTO, "Error reading private key from \"%s\"", keyfile);
- return -1;
- }
-
- /* Try to parse it. */
- r = crypto_pk_read_private_key_from_string(env, contents, -1);
- memwipe(contents, 0, strlen(contents));
- tor_free(contents);
- if (r)
- return -1; /* read_private_key_from_string already warned, so we don't.*/
-
- /* Make sure it's valid. */
- if (crypto_pk_check_key(env) <= 0)
- return -1;
-
- return 0;
-}
-
-/** Helper function to implement crypto_pk_write_*_key_to_string. Return 0 on
- * success, -1 on failure. */
-static int
-crypto_pk_write_key_to_string_impl(crypto_pk_t *env, char **dest,
- size_t *len, int is_public)
-{
- BUF_MEM *buf;
- BIO *b;
- int r;
-
- tor_assert(env);
- tor_assert(env->key);
- tor_assert(dest);
-
- b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
- if (!b)
- return -1;
-
- /* Now you can treat b as if it were a file. Just use the
- * PEM_*_bio_* functions instead of the non-bio variants.
- */
- if (is_public)
- r = PEM_write_bio_RSAPublicKey(b, env->key);
- else
- r = PEM_write_bio_RSAPrivateKey(b, env->key, NULL,NULL,0,NULL,NULL);
-
- if (!r) {
- crypto_openssl_log_errors(LOG_WARN, "writing RSA key to string");
- BIO_free(b);
- return -1;
- }
-
- BIO_get_mem_ptr(b, &buf);
-
- *dest = tor_malloc(buf->length+1);
- memcpy(*dest, buf->data, buf->length);
- (*dest)[buf->length] = 0; /* nul terminate it */
- *len = buf->length;
-
- BIO_free(b);
-
- return 0;
-}
-
-/** PEM-encode the public key portion of <b>env</b> and write it to a
- * newly allocated string. On success, set *<b>dest</b> to the new
- * string, *<b>len</b> to the string's length, and return 0. On
- * failure, return -1.
- */
-int
-crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest,
- size_t *len)
-{
- return crypto_pk_write_key_to_string_impl(env, dest, len, 1);
-}
-
-/** PEM-encode the private key portion of <b>env</b> and write it to a
- * newly allocated string. On success, set *<b>dest</b> to the new
- * string, *<b>len</b> to the string's length, and return 0. On
- * failure, return -1.
- */
-int
-crypto_pk_write_private_key_to_string(crypto_pk_t *env, char **dest,
- size_t *len)
-{
- return crypto_pk_write_key_to_string_impl(env, dest, len, 0);
-}
-
-/** Read a PEM-encoded public key from the first <b>len</b> characters of
- * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
- * failure.
- */
-int
-crypto_pk_read_public_key_from_string(crypto_pk_t *env, const char *src,
- size_t len)
-{
- BIO *b;
-
- tor_assert(env);
- tor_assert(src);
- tor_assert(len<INT_MAX);
-
- b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
- if (!b)
- return -1;
-
- BIO_write(b, src, (int)len);
-
- if (env->key)
- RSA_free(env->key);
- env->key = PEM_read_bio_RSAPublicKey(b, NULL, pem_no_password_cb, NULL);
- BIO_free(b);
- if (!env->key) {
- crypto_openssl_log_errors(LOG_WARN, "reading public key from string");
- return -1;
- }
-
- return 0;
-}
-
-/** Write the private key from <b>env</b> into the file named by <b>fname</b>,
- * PEM-encoded. Return 0 on success, -1 on failure.
- */
-int
-crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
- const char *fname)
-{
- BIO *bio;
- char *cp;
- long len;
- char *s;
- int r;
-
- tor_assert(crypto_pk_key_is_private(env));
-
- if (!(bio = BIO_new(BIO_s_mem())))
- return -1;
- if (PEM_write_bio_RSAPrivateKey(bio, env->key, NULL,NULL,0,NULL,NULL)
- == 0) {
- crypto_openssl_log_errors(LOG_WARN, "writing private key");
- BIO_free(bio);
- return -1;
- }
- len = BIO_get_mem_data(bio, &cp);
- tor_assert(len >= 0);
- s = tor_malloc(len+1);
- memcpy(s, cp, len);
- s[len]='\0';
- r = write_str_to_file(fname, s, 0);
- BIO_free(bio);
- memwipe(s, 0, strlen(s));
- tor_free(s);
- return r;
-}
-
/** Return true iff <b>env</b> has a valid key.
*/
int
@@ -512,11 +302,11 @@ crypto_pk_dup_key(crypto_pk_t *env)
return env;
}
-#ifdef TOR_UNIT_TESTS
-/** For testing: replace dest with src. (Dest must have a refcount
- * of 1) */
+/** Replace dest with src (private key only). (Dest must have a refcount
+ * of 1)
+ */
void
-crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
+crypto_pk_assign_private(crypto_pk_t *dest, const crypto_pk_t *src)
{
tor_assert(dest);
tor_assert(dest->refs == 1);
@@ -524,7 +314,19 @@ crypto_pk_assign_(crypto_pk_t *dest, const crypto_pk_t *src)
RSA_free(dest->key);
dest->key = RSAPrivateKey_dup(src->key);
}
-#endif /* defined(TOR_UNIT_TESTS) */
+
+/** Replace dest with src (public key only). (Dest must have a refcount
+ * of 1)
+ */
+void
+crypto_pk_assign_public(crypto_pk_t *dest, const crypto_pk_t *src)
+{
+ tor_assert(dest);
+ tor_assert(dest->refs == 1);
+ tor_assert(src);
+ RSA_free(dest->key);
+ dest->key = RSAPublicKey_dup(src->key);
+}
/** Make a real honest-to-goodness copy of <b>env</b>, and return it.
* Returns NULL on failure. */
@@ -733,74 +535,48 @@ crypto_pk_asn1_decode(const char *str, size_t len)
return crypto_new_pk_from_openssl_rsa_(rsa);
}
-/** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
- * Base64 encoding of the DER representation of the private key as a NUL
- * terminated string, and return it via <b>priv_out</b>. Return 0 on
- * success, -1 on failure.
- *
- * It is the caller's responsibility to sanitize and free the resulting buffer.
+/** ASN.1-encode the private portion of <b>pk</b> into <b>dest</b>.
+ * Return -1 on error, or the number of characters used on success.
*/
int
-crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out)
+crypto_pk_asn1_encode_private(const crypto_pk_t *pk, char *dest,
+ size_t dest_len)
{
- unsigned char *der = NULL;
- int der_len;
- int ret = -1;
-
- *priv_out = NULL;
+ int len;
+ unsigned char *buf = NULL;
- der_len = i2d_RSAPrivateKey(pk->key, &der);
- if (der_len < 0 || der == NULL)
- return ret;
+ len = i2d_RSAPrivateKey(pk->key, &buf);
+ if (len < 0 || buf == NULL)
+ return -1;
- size_t priv_len = base64_encode_size(der_len, 0) + 1;
- char *priv = tor_malloc_zero(priv_len);
- if (base64_encode(priv, priv_len, (char *)der, der_len, 0) >= 0) {
- *priv_out = priv;
- ret = 0;
- } else {
- tor_free(priv);
+ if ((size_t)len > dest_len || dest_len > SIZE_T_CEILING) {
+ OPENSSL_free(buf);
+ return -1;
}
-
- memwipe(der, 0, der_len);
- OPENSSL_free(der);
- return ret;
+ /* We don't encode directly into 'dest', because that would be illegal
+ * type-punning. (C99 is smarter than me, C99 is smarter than me...)
+ */
+ memcpy(dest,buf,len);
+ OPENSSL_free(buf);
+ return len;
}
-/** Given a string containing the Base64 encoded DER representation of the
- * private key <b>str</b>, decode and return the result on success, or NULL
- * on failure.
+/** Decode an ASN.1-encoded private key from <b>str</b>; return the result on
+ * success and NULL on failure.
*/
crypto_pk_t *
-crypto_pk_base64_decode_private(const char *str, size_t len)
+crypto_pk_asn1_decode_private(const char *str, size_t len)
{
- crypto_pk_t *pk = NULL;
-
- char *der = tor_malloc_zero(len + 1);
- int der_len = base64_decode(der, len, str, len);
- if (der_len <= 0) {
- log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
- goto out;
- }
-
- const unsigned char *dp = (unsigned char*)der; /* Shut the compiler up. */
- RSA *rsa = d2i_RSAPrivateKey(NULL, &dp, der_len);
+ RSA *rsa;
+ unsigned char *buf;
+ const unsigned char *cp;
+ cp = buf = tor_malloc(len);
+ memcpy(buf,str,len);
+ rsa = d2i_RSAPrivateKey(NULL, &cp, len);
+ tor_free(buf);
if (!rsa) {
- crypto_openssl_log_errors(LOG_WARN, "decoding private key");
- goto out;
- }
-
- pk = crypto_new_pk_from_openssl_rsa_(rsa);
-
- /* Make sure it's valid. */
- if (crypto_pk_check_key(pk) <= 0) {
- crypto_pk_free(pk);
- pk = NULL;
- goto out;
+ crypto_openssl_log_errors(LOG_WARN,"decoding public key");
+ return NULL;
}
-
- out:
- memwipe(der, 0, len + 1);
- tor_free(der);
- return pk;
+ return crypto_new_pk_from_openssl_rsa_(rsa);
}
diff --git a/src/test/test_crypto.c b/src/test/test_crypto.c
index 81d43ff13..90fb8d468 100644
--- a/src/test/test_crypto.c
+++ b/src/test/test_crypto.c
@@ -1519,7 +1519,8 @@ test_crypto_digests(void *arg)
(void)arg;
k = crypto_pk_new();
tt_assert(k);
- r = crypto_pk_read_private_key_from_string(k, AUTHORITY_SIGNKEY_3, -1);
+ r = crypto_pk_read_private_key_from_string(k, AUTHORITY_SIGNKEY_3,
+ strlen(AUTHORITY_SIGNKEY_3));
tt_assert(!r);
r = crypto_pk_get_digest(k, digest);
diff --git a/src/test/testing_rsakeys.c b/src/test/testing_rsakeys.c
index a8c9ce4ce..c8062b82d 100644
--- a/src/test/testing_rsakeys.c
+++ b/src/test/testing_rsakeys.c
@@ -490,7 +490,7 @@ crypto_pk_generate_key_with_bits__get_cached(crypto_pk_t *env, int bits)
{
if (bits == 1024 || bits == 2048) {
crypto_pk_t *newkey = pk_generate_internal(bits);
- crypto_pk_assign_(env, newkey);
+ crypto_pk_assign_private(env, newkey);
crypto_pk_free(newkey);
} else {
return crypto_pk_generate_key_with_bits__real(env, bits);
@@ -544,4 +544,3 @@ init_pregenerated_keys(void)
crypto_pk_generate_key_with_bits__get_cached);
#endif /* defined(USE_PREGENERATED_RSA_KEYS) */
}
-
1
0
05 Sep '18
commit cb5cfe3177bbf841e5ad18c0103b3d2ebe443e07
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Tue Jul 31 18:42:42 2018 -0400
Also reinitialize the pregenerated keys postfork.
---
src/test/testing_common.c | 2 ++
1 file changed, 2 insertions(+)
diff --git a/src/test/testing_common.c b/src/test/testing_common.c
index 6957342c6..17a075680 100644
--- a/src/test/testing_common.c
+++ b/src/test/testing_common.c
@@ -227,7 +227,9 @@ void tinytest_postfork(void);
void
tinytest_postfork(void)
{
+ free_pregenerated_keys();
crypto_postfork();
+ init_pregenerated_keys();
}
/** Main entry point for unit test code: parse the command line, and run
1
0
commit 9a4f05b05c12687e640d2aed9bb21229138bd1a5
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Sat Aug 11 18:16:04 2018 -0400
Split X509 code out of tortls.c
---
src/core/or/channeltls.c | 1 +
src/core/or/connection_or.c | 1 +
src/feature/nodelist/torcert.c | 1 +
src/feature/relay/routerkeys.c | 1 +
src/lib/tls/include.am | 6 +-
src/lib/tls/tortls.c | 506 +-------------------------------------
src/lib/tls/tortls.h | 76 ++----
src/lib/tls/x509.c | 539 +++++++++++++++++++++++++++++++++++++++++
src/lib/tls/x509.h | 78 ++++++
src/test/test_link_handshake.c | 1 +
src/test/test_tortls.c | 1 +
11 files changed, 649 insertions(+), 562 deletions(-)
diff --git a/src/core/or/channeltls.c b/src/core/or/channeltls.c
index 87f5a02b7..153813c4d 100644
--- a/src/core/or/channeltls.c
+++ b/src/core/or/channeltls.c
@@ -70,6 +70,7 @@
#include "core/or/var_cell_st.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/x509.h"
/** How many CELL_PADDING cells have we received, ever? */
uint64_t stats_n_padding_cells_processed = 0;
diff --git a/src/core/or/connection_or.c b/src/core/or/connection_or.c
index c5ff10f6a..08371d1ad 100644
--- a/src/core/or/connection_or.c
+++ b/src/core/or/connection_or.c
@@ -73,6 +73,7 @@
#include "lib/crypt_ops/crypto_format.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/x509.h"
static int connection_tls_finish_handshake(or_connection_t *conn);
static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
diff --git a/src/feature/nodelist/torcert.c b/src/feature/nodelist/torcert.c
index a27608202..fe67e5640 100644
--- a/src/feature/nodelist/torcert.c
+++ b/src/feature/nodelist/torcert.c
@@ -33,6 +33,7 @@
#include "lib/log/log.h"
#include "trunnel/link_handshake.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/x509.h"
#include "core/or/or_handshake_certs_st.h"
diff --git a/src/feature/relay/routerkeys.c b/src/feature/relay/routerkeys.c
index f12eb3d33..d018f300f 100644
--- a/src/feature/relay/routerkeys.c
+++ b/src/feature/relay/routerkeys.c
@@ -24,6 +24,7 @@
#include "lib/crypt_ops/crypto_util.h"
#include "lib/term/getpass.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/x509.h"
#include "lib/crypt_ops/crypto_format.h"
#define ENC_KEY_HEADER "Boxed Ed25519 key"
diff --git a/src/lib/tls/include.am b/src/lib/tls/include.am
index 9cc57ca77..1fd25a0b3 100644
--- a/src/lib/tls/include.am
+++ b/src/lib/tls/include.am
@@ -7,7 +7,8 @@ endif
src_lib_libtor_tls_a_SOURCES = \
src/lib/tls/buffers_tls.c \
- src/lib/tls/tortls.c
+ src/lib/tls/tortls.c \
+ src/lib/tls/x509.c
src_lib_libtor_tls_a_CFLAGS = $(AM_CFLAGS) $(TOR_CFLAGS_CRYPTLIB)
@@ -20,4 +21,5 @@ src_lib_libtor_tls_testing_a_CFLAGS = \
noinst_HEADERS += \
src/lib/tls/ciphers.inc \
src/lib/tls/buffers_tls.h \
- src/lib/tls/tortls.h
+ src/lib/tls/tortls.h \
+ src/lib/tls/x509.h
diff --git a/src/lib/tls/tortls.c b/src/lib/tls/tortls.c
index 466df8966..20e432081 100644
--- a/src/lib/tls/tortls.c
+++ b/src/lib/tls/tortls.c
@@ -28,6 +28,7 @@
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_dh.h"
#include "lib/crypt_ops/crypto_util.h"
+#include "lib/tls/x509.h"
/* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
* srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
@@ -67,26 +68,6 @@ ENABLE_GCC_WARNING(redundant-decls)
#include "lib/arch/bytes.h"
-#ifdef OPENSSL_1_1_API
-#define X509_get_notBefore_const(cert) \
- X509_get0_notBefore(cert)
-#define X509_get_notAfter_const(cert) \
- X509_get0_notAfter(cert)
-#ifndef X509_get_notBefore
-#define X509_get_notBefore(cert) \
- X509_getm_notBefore(cert)
-#endif
-#ifndef X509_get_notAfter
-#define X509_get_notAfter(cert) \
- X509_getm_notAfter(cert)
-#endif
-#else /* ! OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
-#define X509_get_notBefore_const(cert) \
- ((const ASN1_TIME*) X509_get_notBefore((X509 *)cert))
-#define X509_get_notAfter_const(cert) \
- ((const ASN1_TIME*) X509_get_notAfter((X509 *)cert))
-#endif
-
/* Copied from or.h */
#define LEGAL_NICKNAME_CHARACTERS \
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
@@ -162,10 +143,6 @@ tor_tls_get_by_ssl(const SSL *ssl)
static void tor_tls_context_decref(tor_tls_context_t *ctx);
static void tor_tls_context_incref(tor_tls_context_t *ctx);
-static int check_cert_lifetime_internal(int severity, const X509 *cert,
- time_t now,
- int past_tolerance, int future_tolerance);
-
/** Global TLS contexts. We keep them here because nobody else needs
* to touch them.
*
@@ -267,7 +244,7 @@ tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
/** Log all pending tls errors at level <b>severity</b> in log domain
* <b>domain</b>. Use <b>doing</b> to describe our current activities.
*/
-STATIC void
+void
tls_log_errors(tor_tls_t *tls, int severity, int domain, const char *doing)
{
unsigned long err;
@@ -375,7 +352,7 @@ tor_tls_get_error(tor_tls_t *tls, int r, int extra,
/** Initialize OpenSSL, unless it has already been initialized.
*/
-static void
+void
tor_tls_init(void)
{
check_no_tls_errors();
@@ -459,145 +436,6 @@ always_accept_verify_cb(int preverify_ok,
return 1;
}
-/** Return a newly allocated X509 name with commonName <b>cname</b>. */
-static X509_NAME *
-tor_x509_name_new(const char *cname)
-{
- int nid;
- X509_NAME *name;
- /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
- if (!(name = X509_NAME_new()))
- return NULL;
- if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
- if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
- (unsigned char*)cname, -1, -1, 0)))
- goto error;
- /* LCOV_EXCL_BR_STOP */
- return name;
-
- /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
- error:
- X509_NAME_free(name);
- return NULL;
- /* LCOV_EXCL_STOP */
-}
-
-/** Generate and sign an X509 certificate with the public key <b>rsa</b>,
- * signed by the private key <b>rsa_sign</b>. The commonName of the
- * certificate will be <b>cname</b>; the commonName of the issuer will be
- * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
- * seconds, starting from some time in the past.
- *
- * Return a certificate on success, NULL on failure.
- */
-MOCK_IMPL(STATIC X509 *,
-tor_tls_create_certificate,(crypto_pk_t *rsa,
- crypto_pk_t *rsa_sign,
- const char *cname,
- const char *cname_sign,
- unsigned int cert_lifetime))
-{
- /* OpenSSL generates self-signed certificates with random 64-bit serial
- * numbers, so let's do that too. */
-#define SERIAL_NUMBER_SIZE 8
-
- time_t start_time, end_time;
- BIGNUM *serial_number = NULL;
- unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
- EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
- X509 *x509 = NULL;
- X509_NAME *name = NULL, *name_issuer=NULL;
-
- tor_tls_init();
-
- /* Make sure we're part-way through the certificate lifetime, rather
- * than having it start right now. Don't choose quite uniformly, since
- * then we might pick a time where we're about to expire. Lastly, be
- * sure to start on a day boundary. */
- time_t now = time(NULL);
- /* Our certificate lifetime will be cert_lifetime no matter what, but if we
- * start cert_lifetime in the past, we'll have 0 real lifetime. instead we
- * start up to (cert_lifetime - min_real_lifetime - start_granularity) in
- * the past. */
- const time_t min_real_lifetime = 24*3600;
- const time_t start_granularity = 24*3600;
- time_t earliest_start_time;
- /* Don't actually start in the future! */
- if (cert_lifetime <= min_real_lifetime + start_granularity) {
- earliest_start_time = now - 1;
- } else {
- earliest_start_time = now + min_real_lifetime + start_granularity
- - cert_lifetime;
- }
- start_time = crypto_rand_time_range(earliest_start_time, now);
- /* Round the start time back to the start of a day. */
- start_time -= start_time % start_granularity;
-
- end_time = start_time + cert_lifetime;
-
- tor_assert(rsa);
- tor_assert(cname);
- tor_assert(rsa_sign);
- tor_assert(cname_sign);
- if (!(sign_pkey = crypto_pk_get_openssl_evp_pkey_(rsa_sign,1)))
- goto error;
- if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,0)))
- goto error;
- if (!(x509 = X509_new()))
- goto error;
- if (!(X509_set_version(x509, 2)))
- goto error;
-
- { /* our serial number is 8 random bytes. */
- crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
- if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
- goto error;
- if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
- goto error;
- }
-
- if (!(name = tor_x509_name_new(cname)))
- goto error;
- if (!(X509_set_subject_name(x509, name)))
- goto error;
- if (!(name_issuer = tor_x509_name_new(cname_sign)))
- goto error;
- if (!(X509_set_issuer_name(x509, name_issuer)))
- goto error;
-
- if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
- goto error;
- if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
- goto error;
- if (!X509_set_pubkey(x509, pkey))
- goto error;
-
- if (!X509_sign(x509, sign_pkey, EVP_sha256()))
- goto error;
-
- goto done;
- error:
- if (x509) {
- X509_free(x509);
- x509 = NULL;
- }
- done:
- tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
- if (sign_pkey)
- EVP_PKEY_free(sign_pkey);
- if (pkey)
- EVP_PKEY_free(pkey);
- if (serial_number)
- BN_clear_free(serial_number);
- if (name)
- X509_NAME_free(name);
- if (name_issuer)
- X509_NAME_free(name_issuer);
- return x509;
-
-#undef SERIAL_NUMBER_SIZE
-}
-
/** List of ciphers that servers should select from when the client might be
* claiming extra unsupported ciphers in order to avoid fingerprinting. */
static const char SERVER_CIPHER_LIST[] =
@@ -697,156 +535,6 @@ static const char CLIENT_CIPHER_LIST[] =
#undef CIPHER
#undef XCIPHER
-/** Free all storage held in <b>cert</b> */
-void
-tor_x509_cert_free_(tor_x509_cert_t *cert)
-{
- if (! cert)
- return;
- if (cert->cert)
- X509_free(cert->cert);
- tor_free(cert->encoded);
- memwipe(cert, 0x03, sizeof(*cert));
- /* LCOV_EXCL_BR_START since cert will never be NULL here */
- tor_free(cert);
- /* LCOV_EXCL_BR_STOP */
-}
-
-/**
- * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
- *
- * Steals a reference to x509_cert.
- */
-MOCK_IMPL(STATIC tor_x509_cert_t *,
-tor_x509_cert_new,(X509 *x509_cert))
-{
- tor_x509_cert_t *cert;
- EVP_PKEY *pkey;
- RSA *rsa;
- int length;
- unsigned char *buf = NULL;
-
- if (!x509_cert)
- return NULL;
-
- length = i2d_X509(x509_cert, &buf);
- cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
- if (length <= 0 || buf == NULL) {
- goto err;
- }
- cert->encoded_len = (size_t) length;
- cert->encoded = tor_malloc(length);
- memcpy(cert->encoded, buf, length);
- OPENSSL_free(buf);
-
- cert->cert = x509_cert;
-
- crypto_common_digests(&cert->cert_digests,
- (char*)cert->encoded, cert->encoded_len);
-
- if ((pkey = X509_get_pubkey(x509_cert)) &&
- (rsa = EVP_PKEY_get1_RSA(pkey))) {
- crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(rsa);
- if (crypto_pk_get_common_digests(pk, &cert->pkey_digests) < 0) {
- crypto_pk_free(pk);
- EVP_PKEY_free(pkey);
- goto err;
- }
-
- cert->pkey_digests_set = 1;
- crypto_pk_free(pk);
- EVP_PKEY_free(pkey);
- }
-
- return cert;
- err:
- /* LCOV_EXCL_START for the same reason as the exclusion above */
- tor_free(cert);
- log_err(LD_CRYPTO, "Couldn't wrap encoded X509 certificate.");
- X509_free(x509_cert);
- return NULL;
- /* LCOV_EXCL_STOP */
-}
-
-/** Return a new copy of <b>cert</b>. */
-tor_x509_cert_t *
-tor_x509_cert_dup(const tor_x509_cert_t *cert)
-{
- tor_assert(cert);
- X509 *x509 = cert->cert;
- return tor_x509_cert_new(X509_dup(x509));
-}
-
-/** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
- * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
- * success and NULL on failure. */
-tor_x509_cert_t *
-tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
-{
- X509 *x509;
- const unsigned char *cp = (const unsigned char *)certificate;
- tor_x509_cert_t *newcert;
- tor_assert(certificate);
- check_no_tls_errors();
-
- if (certificate_len > INT_MAX)
- goto err;
-
- x509 = d2i_X509(NULL, &cp, (int)certificate_len);
-
- if (!x509)
- goto err; /* Couldn't decode */
- if (cp - certificate != (int)certificate_len) {
- X509_free(x509);
- goto err; /* Didn't use all the bytes */
- }
- newcert = tor_x509_cert_new(x509);
- if (!newcert) {
- goto err;
- }
- if (newcert->encoded_len != certificate_len ||
- fast_memneq(newcert->encoded, certificate, certificate_len)) {
- /* Cert wasn't in DER */
- tor_x509_cert_free(newcert);
- goto err;
- }
- return newcert;
- err:
- tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
- return NULL;
-}
-
-/** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
- * representation and length, respectively. */
-void
-tor_x509_cert_get_der(const tor_x509_cert_t *cert,
- const uint8_t **encoded_out, size_t *size_out)
-{
- tor_assert(cert);
- tor_assert(encoded_out);
- tor_assert(size_out);
- *encoded_out = cert->encoded;
- *size_out = cert->encoded_len;
-}
-
-/** Return a set of digests for the public key in <b>cert</b>, or NULL if this
- * cert's public key is not one we know how to take the digest of. */
-const common_digests_t *
-tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
-{
- if (cert->pkey_digests_set)
- return &cert->pkey_digests;
- else
- return NULL;
-}
-
-/** Return a set of digests for the public key in <b>cert</b>. */
-const common_digests_t *
-tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
-{
- return &cert->cert_digests;
-}
-
/** Remove a reference to <b>ctx</b>, and free it if it has no more
* references. */
static void
@@ -898,28 +586,6 @@ tor_tls_get_my_client_auth_key(void)
return client_tls_context->auth_key;
}
-/**
- * Return a newly allocated copy of the public key that a certificate
- * certifies. Watch out! This returns NULL if the cert's key is not RSA.
- */
-crypto_pk_t *
-tor_tls_cert_get_key(tor_x509_cert_t *cert)
-{
- crypto_pk_t *result = NULL;
- EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
- RSA *rsa;
- if (!pkey)
- return NULL;
- rsa = EVP_PKEY_get1_RSA(pkey);
- if (!rsa) {
- EVP_PKEY_free(pkey);
- return NULL;
- }
- result = crypto_new_pk_from_openssl_rsa_(rsa);
- EVP_PKEY_free(pkey);
- return result;
-}
-
/** Return true iff the other side of <b>tls</b> has authenticated to us, and
* the key certified in <b>cert</b> is the same as the key they used to do it.
*/
@@ -946,71 +612,6 @@ tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
return result;
}
-/** Check whether <b>cert</b> is well-formed, currently live, and correctly
- * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
- * make sure that it has an RSA key with 1024 bits; otherwise, just check that
- * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
- * we couldn't check it. */
-int
-tor_tls_cert_is_valid(int severity,
- const tor_x509_cert_t *cert,
- const tor_x509_cert_t *signing_cert,
- time_t now,
- int check_rsa_1024)
-{
- check_no_tls_errors();
- EVP_PKEY *cert_key;
- int r, key_ok = 0;
-
- if (!signing_cert || !cert)
- goto bad;
-
- EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
- if (!signing_key)
- goto bad;
- r = X509_verify(cert->cert, signing_key);
- EVP_PKEY_free(signing_key);
- if (r <= 0)
- goto bad;
-
- /* okay, the signature checked out right. Now let's check the check the
- * lifetime. */
- if (check_cert_lifetime_internal(severity, cert->cert, now,
- 48*60*60, 30*24*60*60) < 0)
- goto bad;
-
- cert_key = X509_get_pubkey(cert->cert);
- if (check_rsa_1024 && cert_key) {
- RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
-#ifdef OPENSSL_1_1_API
- if (rsa && RSA_bits(rsa) == 1024)
-#else
- if (rsa && BN_num_bits(rsa->n) == 1024)
-#endif
- key_ok = 1;
- if (rsa)
- RSA_free(rsa);
- } else if (cert_key) {
- int min_bits = 1024;
-#ifdef EVP_PKEY_EC
- if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
- min_bits = 128;
-#endif
- if (EVP_PKEY_bits(cert_key) >= min_bits)
- key_ok = 1;
- }
- EVP_PKEY_free(cert_key);
- if (!key_ok)
- goto bad;
-
- /* XXXX compare DNs or anything? */
-
- return 1;
- bad:
- tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
- return 0;
-}
-
/** Increase the reference count of <b>ctx</b>. */
static void
tor_tls_context_incref(tor_tls_context_t *ctx)
@@ -2146,63 +1747,6 @@ tor_tls_get_own_cert,(tor_tls_t *tls))
return tor_x509_cert_new(duplicate);
}
-/** Warn that a certificate lifetime extends through a certain range. */
-static void
-log_cert_lifetime(int severity, const X509 *cert, const char *problem,
- time_t now)
-{
- BIO *bio = NULL;
- BUF_MEM *buf;
- char *s1=NULL, *s2=NULL;
- char mytime[33];
- struct tm tm;
- size_t n;
-
- if (problem)
- tor_log(severity, LD_GENERAL,
- "Certificate %s. Either their clock is set wrong, or your clock "
- "is wrong.",
- problem);
-
- if (!(bio = BIO_new(BIO_s_mem()))) {
- log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
- }
- if (!(ASN1_TIME_print(bio, X509_get_notBefore_const(cert)))) {
- tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
- goto end;
- }
- BIO_get_mem_ptr(bio, &buf);
- s1 = tor_strndup(buf->data, buf->length);
-
- (void)BIO_reset(bio);
- if (!(ASN1_TIME_print(bio, X509_get_notAfter_const(cert)))) {
- tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
- goto end;
- }
- BIO_get_mem_ptr(bio, &buf);
- s2 = tor_strndup(buf->data, buf->length);
-
- n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
- if (n > 0) {
- tor_log(severity, LD_GENERAL,
- "(certificate lifetime runs from %s through %s. Your time is %s.)",
- s1,s2,mytime);
- } else {
- tor_log(severity, LD_GENERAL,
- "(certificate lifetime runs from %s through %s. "
- "Couldn't get your time.)",
- s1, s2);
- }
-
- end:
- /* Not expected to get invoked */
- tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
- if (bio)
- BIO_free(bio);
- tor_free(s1);
- tor_free(s2);
-}
-
/** Helper function: try to extract a link certificate and an identity
* certificate from <b>tls</b>, and store them in *<b>cert_out</b> and
* *<b>id_cert_out</b> respectively. Log all messages at level
@@ -2325,50 +1869,6 @@ tor_tls_check_lifetime(int severity, tor_tls_t *tls,
return r;
}
-/** Helper: check whether <b>cert</b> is expired give or take
- * <b>past_tolerance</b> seconds, or not-yet-valid give or take
- * <b>future_tolerance</b> seconds. (Relative to the current time
- * <b>now</b>.) If it is live, return 0. If it is not live, log a message
- * and return -1. */
-static int
-check_cert_lifetime_internal(int severity, const X509 *cert,
- time_t now,
- int past_tolerance, int future_tolerance)
-{
- time_t t;
-
- t = now + future_tolerance;
- if (X509_cmp_time(X509_get_notBefore_const(cert), &t) > 0) {
- log_cert_lifetime(severity, cert, "not yet valid", now);
- return -1;
- }
- t = now - past_tolerance;
- if (X509_cmp_time(X509_get_notAfter_const(cert), &t) < 0) {
- log_cert_lifetime(severity, cert, "already expired", now);
- return -1;
- }
-
- return 0;
-}
-
-#ifdef TOR_UNIT_TESTS
-/* Testing only: return a new x509 cert with the same contents as <b>inp</b>,
- but with the expiration time <b>new_expiration_time</b>, signed with
- <b>signing_key</b>. */
-STATIC tor_x509_cert_t *
-tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
- time_t new_expiration_time,
- crypto_pk_t *signing_key)
-{
- X509 *newc = X509_dup(inp->cert);
- X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
- EVP_PKEY *pk = crypto_pk_get_openssl_evp_pkey_(signing_key, 1);
- tor_assert(X509_sign(newc, pk, EVP_sha256()));
- EVP_PKEY_free(pk);
- return tor_x509_cert_new(newc);
-}
-#endif /* defined(TOR_UNIT_TESTS) */
-
/** Return the number of bytes available for reading from <b>tls</b>.
*/
int
diff --git a/src/lib/tls/tortls.h b/src/lib/tls/tortls.h
index fe192b2ab..a1d90c16b 100644
--- a/src/lib/tls/tortls.h
+++ b/src/lib/tls/tortls.h
@@ -18,8 +18,7 @@
/* Opaque structure to hold a TLS connection. */
typedef struct tor_tls_t tor_tls_t;
-/* Opaque structure to hold an X509 certificate. */
-typedef struct tor_x509_cert_t tor_x509_cert_t;
+struct tor_x509_cert_t;
/* Possible return values for most tor_tls_* functions. */
#define MIN_TOR_TLS_ERROR_VAL_ -9
@@ -62,10 +61,11 @@ typedef enum {
} tor_tls_state_t;
#define tor_tls_state_bitfield_t ENUM_BF(tor_tls_state_t)
-struct x509_st;
+#ifdef ENABLE_OPENSSL
struct ssl_st;
struct ssl_ctx_st;
struct ssl_session_st;
+#endif
/** Holds a SSL_CTX object and related state used to configure TLS
* connections.
@@ -73,23 +73,13 @@ struct ssl_session_st;
typedef struct tor_tls_context_t {
int refcnt;
struct ssl_ctx_st *ctx;
- tor_x509_cert_t *my_link_cert;
- tor_x509_cert_t *my_id_cert;
- tor_x509_cert_t *my_auth_cert;
+ struct tor_x509_cert_t *my_link_cert;
+ struct tor_x509_cert_t *my_id_cert;
+ struct tor_x509_cert_t *my_auth_cert;
crypto_pk_t *link_key;
crypto_pk_t *auth_key;
} tor_tls_context_t;
-/** Structure that we use for a single certificate. */
-struct tor_x509_cert_t {
- struct x509_st *cert;
- uint8_t *encoded;
- size_t encoded_len;
- unsigned pkey_digests_set : 1;
- common_digests_t cert_digests;
- common_digests_t pkey_digests;
-};
-
/** Holds a SSL object and its associated data. Members are only
* accessed from within tortls.c.
*/
@@ -134,15 +124,15 @@ STATIC int tor_tls_get_error(tor_tls_t *tls, int r, int extra,
const char *doing, int severity, int domain);
STATIC tor_tls_t *tor_tls_get_by_ssl(const struct ssl_st *ssl);
STATIC void tor_tls_allocate_tor_tls_object_ex_data_index(void);
+MOCK_DECL(STATIC void, try_to_extract_certs_from_tls,
+ (int severity, tor_tls_t *tls, struct x509_st **cert_out,
+ struct x509_st **id_cert_out));
#ifdef TORTLS_OPENSSL_PRIVATE
STATIC int always_accept_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx);
STATIC int tor_tls_classify_client_ciphers(const struct ssl_st *ssl,
STACK_OF(SSL_CIPHER) *peer_ciphers);
#endif
STATIC int tor_tls_client_is_using_v2_ciphers(const struct ssl_st *ssl);
-MOCK_DECL(STATIC void, try_to_extract_certs_from_tls,
- (int severity, tor_tls_t *tls, struct x509_st **cert_out,
- struct x509_st **id_cert_out));
#ifndef HAVE_SSL_SESSION_GET_MASTER_KEY
STATIC size_t SSL_SESSION_get_master_key(struct ssl_session_st *s,
uint8_t *out,
@@ -161,23 +151,13 @@ STATIC int tor_tls_session_secret_cb(struct ssl_st *ssl, void *secret,
STATIC int find_cipher_by_id(const SSL *ssl, const SSL_METHOD *m,
uint16_t cipher);
#endif /* defined(TORTLS_OPENSSL_PRIVATE) */
-MOCK_DECL(STATIC struct x509_st *, tor_tls_create_certificate,
- (crypto_pk_t *rsa,
- crypto_pk_t *rsa_sign,
- const char *cname,
- const char *cname_sign,
- unsigned int cert_lifetime));
STATIC tor_tls_context_t *tor_tls_context_new(crypto_pk_t *identity,
unsigned int key_lifetime, unsigned flags, int is_client);
-MOCK_DECL(STATIC tor_x509_cert_t *, tor_x509_cert_new,
- (struct x509_st *x509_cert));
STATIC int tor_tls_context_init_one(tor_tls_context_t **ppcontext,
crypto_pk_t *identity,
unsigned int key_lifetime,
unsigned int flags,
int is_client);
-STATIC void tls_log_errors(tor_tls_t *tls, int severity, int domain,
- const char *doing);
#ifdef TOR_UNIT_TESTS
extern int tor_tls_object_ex_data_index;
@@ -187,15 +167,10 @@ extern uint16_t v2_cipher_list[];
extern uint64_t total_bytes_written_over_tls;
extern uint64_t total_bytes_written_by_tls;
-STATIC tor_x509_cert_t *tor_x509_cert_replace_expiration(
- const tor_x509_cert_t *inp,
- time_t new_expiration_time,
- crypto_pk_t *signing_key);
#endif /* defined(TOR_UNIT_TESTS) */
#endif /* defined(TORTLS_PRIVATE) */
-tor_x509_cert_t *tor_x509_cert_dup(const tor_x509_cert_t *cert);
const char *tor_tls_err_to_string(int err);
void tor_tls_get_state_description(tor_tls_t *tls, char *buf, size_t sz);
@@ -205,6 +180,9 @@ void tor_tls_free_all(void);
#define TOR_TLS_CTX_USE_ECDHE_P256 (1u<<1)
#define TOR_TLS_CTX_USE_ECDHE_P224 (1u<<2)
+void tor_tls_init(void);
+void tls_log_errors(tor_tls_t *tls, int severity, int domain,
+ const char *doing);
int tor_tls_context_init(unsigned flags,
crypto_pk_t *client_identity,
crypto_pk_t *server_identity,
@@ -218,8 +196,8 @@ int tor_tls_is_server(tor_tls_t *tls);
void tor_tls_free_(tor_tls_t *tls);
#define tor_tls_free(tls) FREE_AND_NULL(tor_tls_t, tor_tls_free_, (tls))
int tor_tls_peer_has_cert(tor_tls_t *tls);
-MOCK_DECL(tor_x509_cert_t *,tor_tls_get_peer_cert,(tor_tls_t *tls));
-MOCK_DECL(tor_x509_cert_t *,tor_tls_get_own_cert,(tor_tls_t *tls));
+MOCK_DECL(struct tor_x509_cert_t *,tor_tls_get_peer_cert,(tor_tls_t *tls));
+MOCK_DECL(struct tor_x509_cert_t *,tor_tls_get_own_cert,(tor_tls_t *tls));
int tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_t **identity);
int tor_tls_check_lifetime(int severity,
tor_tls_t *tls, time_t now,
@@ -248,6 +226,8 @@ MOCK_DECL(double, tls_get_write_overhead_ratio, (void));
int tor_tls_used_v1_handshake(tor_tls_t *tls);
int tor_tls_get_num_server_handshakes(tor_tls_t *tls);
int tor_tls_server_got_renegotiate(tor_tls_t *tls);
+MOCK_DECL(int,tor_tls_cert_matches_key,(const tor_tls_t *tls,
+ const struct tor_x509_cert_t *cert));
MOCK_DECL(int,tor_tls_get_tlssecrets,(tor_tls_t *tls, uint8_t *secrets_out));
MOCK_DECL(int,tor_tls_export_key_material,(
tor_tls_t *tls, uint8_t *secrets_out,
@@ -263,29 +243,11 @@ void check_no_tls_errors_(const char *fname, int line);
void tor_tls_log_one_error(tor_tls_t *tls, unsigned long err,
int severity, int domain, const char *doing);
-void tor_x509_cert_free_(tor_x509_cert_t *cert);
-#define tor_x509_cert_free(c) \
- FREE_AND_NULL(tor_x509_cert_t, tor_x509_cert_free_, (c))
-tor_x509_cert_t *tor_x509_cert_decode(const uint8_t *certificate,
- size_t certificate_len);
-void tor_x509_cert_get_der(const tor_x509_cert_t *cert,
- const uint8_t **encoded_out, size_t *size_out);
-const common_digests_t *tor_x509_cert_get_id_digests(
- const tor_x509_cert_t *cert);
-const common_digests_t *tor_x509_cert_get_cert_digests(
- const tor_x509_cert_t *cert);
int tor_tls_get_my_certs(int server,
- const tor_x509_cert_t **link_cert_out,
- const tor_x509_cert_t **id_cert_out);
+ const struct tor_x509_cert_t **link_cert_out,
+ const struct tor_x509_cert_t **id_cert_out);
crypto_pk_t *tor_tls_get_my_client_auth_key(void);
-crypto_pk_t *tor_tls_cert_get_key(tor_x509_cert_t *cert);
-MOCK_DECL(int,tor_tls_cert_matches_key,(const tor_tls_t *tls,
- const tor_x509_cert_t *cert));
-int tor_tls_cert_is_valid(int severity,
- const tor_x509_cert_t *cert,
- const tor_x509_cert_t *signing_cert,
- time_t now,
- int check_rsa_1024);
+
const char *tor_tls_get_ciphersuite_name(tor_tls_t *tls);
int evaluate_ecgroup_for_tls(const char *ecgroup);
diff --git a/src/lib/tls/x509.c b/src/lib/tls/x509.c
new file mode 100644
index 000000000..feded3473
--- /dev/null
+++ b/src/lib/tls/x509.c
@@ -0,0 +1,539 @@
+/* Copyright (c) 2003, Roger Dingledine.
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+/**
+ * \file x509.c
+ * \brief Wrapper functions to present a consistent interface to
+ * X.509 functions from OpenSSL.
+ **/
+
+#include "lib/tls/x509.h"
+#include "lib/tls/tortls.h"
+//#include "lib/crypt_ops/crypto_cipher.h"
+#include "lib/crypt_ops/crypto_rand.h"
+#include "lib/crypt_ops/crypto_util.h"
+
+/* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
+ * srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
+DISABLE_GCC_WARNING(redundant-decls)
+
+#include <openssl/opensslv.h>
+
+#ifdef OPENSSL_NO_EC
+#error "We require OpenSSL with ECC support"
+#endif
+
+#include <openssl/err.h>
+#include <openssl/asn1.h>
+#include <openssl/bio.h>
+#include <openssl/bn.h>
+#include <openssl/rsa.h>
+
+ENABLE_GCC_WARNING(redundant-decls)
+
+#include "lib/log/log.h"
+#include "lib/log/util_bug.h"
+#include "lib/ctime/di_ops.h"
+#include "lib/encoding/time_fmt.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef OPENSSL_1_1_API
+#define X509_get_notBefore_const(cert) \
+ X509_get0_notBefore(cert)
+#define X509_get_notAfter_const(cert) \
+ X509_get0_notAfter(cert)
+#ifndef X509_get_notBefore
+#define X509_get_notBefore(cert) \
+ X509_getm_notBefore(cert)
+#endif
+#ifndef X509_get_notAfter
+#define X509_get_notAfter(cert) \
+ X509_getm_notAfter(cert)
+#endif
+#else /* ! OPENSSL_VERSION_NUMBER >= OPENSSL_V_SERIES(1,1,0) */
+#define X509_get_notBefore_const(cert) \
+ ((const ASN1_TIME*) X509_get_notBefore((X509 *)cert))
+#define X509_get_notAfter_const(cert) \
+ ((const ASN1_TIME*) X509_get_notAfter((X509 *)cert))
+#endif
+
+/** Return a newly allocated X509 name with commonName <b>cname</b>. */
+static X509_NAME *
+tor_x509_name_new(const char *cname)
+{
+ int nid;
+ X509_NAME *name;
+ /* LCOV_EXCL_BR_START : these branches will only fail on OOM errors */
+ if (!(name = X509_NAME_new()))
+ return NULL;
+ if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
+ if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
+ (unsigned char*)cname, -1, -1, 0)))
+ goto error;
+ /* LCOV_EXCL_BR_STOP */
+ return name;
+
+ /* LCOV_EXCL_START : these lines will only execute on out of memory errors*/
+ error:
+ X509_NAME_free(name);
+ return NULL;
+ /* LCOV_EXCL_STOP */
+}
+
+/** Generate and sign an X509 certificate with the public key <b>rsa</b>,
+ * signed by the private key <b>rsa_sign</b>. The commonName of the
+ * certificate will be <b>cname</b>; the commonName of the issuer will be
+ * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b>
+ * seconds, starting from some time in the past.
+ *
+ * Return a certificate on success, NULL on failure.
+ */
+MOCK_IMPL(X509 *,
+tor_tls_create_certificate,(crypto_pk_t *rsa,
+ crypto_pk_t *rsa_sign,
+ const char *cname,
+ const char *cname_sign,
+ unsigned int cert_lifetime))
+{
+ /* OpenSSL generates self-signed certificates with random 64-bit serial
+ * numbers, so let's do that too. */
+#define SERIAL_NUMBER_SIZE 8
+
+ time_t start_time, end_time;
+ BIGNUM *serial_number = NULL;
+ unsigned char serial_tmp[SERIAL_NUMBER_SIZE];
+ EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
+ X509 *x509 = NULL;
+ X509_NAME *name = NULL, *name_issuer=NULL;
+
+ tor_tls_init();
+
+ /* Make sure we're part-way through the certificate lifetime, rather
+ * than having it start right now. Don't choose quite uniformly, since
+ * then we might pick a time where we're about to expire. Lastly, be
+ * sure to start on a day boundary. */
+ time_t now = time(NULL);
+ /* Our certificate lifetime will be cert_lifetime no matter what, but if we
+ * start cert_lifetime in the past, we'll have 0 real lifetime. instead we
+ * start up to (cert_lifetime - min_real_lifetime - start_granularity) in
+ * the past. */
+ const time_t min_real_lifetime = 24*3600;
+ const time_t start_granularity = 24*3600;
+ time_t earliest_start_time;
+ /* Don't actually start in the future! */
+ if (cert_lifetime <= min_real_lifetime + start_granularity) {
+ earliest_start_time = now - 1;
+ } else {
+ earliest_start_time = now + min_real_lifetime + start_granularity
+ - cert_lifetime;
+ }
+ start_time = crypto_rand_time_range(earliest_start_time, now);
+ /* Round the start time back to the start of a day. */
+ start_time -= start_time % start_granularity;
+
+ end_time = start_time + cert_lifetime;
+
+ tor_assert(rsa);
+ tor_assert(cname);
+ tor_assert(rsa_sign);
+ tor_assert(cname_sign);
+ if (!(sign_pkey = crypto_pk_get_openssl_evp_pkey_(rsa_sign,1)))
+ goto error;
+ if (!(pkey = crypto_pk_get_openssl_evp_pkey_(rsa,0)))
+ goto error;
+ if (!(x509 = X509_new()))
+ goto error;
+ if (!(X509_set_version(x509, 2)))
+ goto error;
+
+ { /* our serial number is 8 random bytes. */
+ crypto_rand((char *)serial_tmp, sizeof(serial_tmp));
+ if (!(serial_number = BN_bin2bn(serial_tmp, sizeof(serial_tmp), NULL)))
+ goto error;
+ if (!(BN_to_ASN1_INTEGER(serial_number, X509_get_serialNumber(x509))))
+ goto error;
+ }
+
+ if (!(name = tor_x509_name_new(cname)))
+ goto error;
+ if (!(X509_set_subject_name(x509, name)))
+ goto error;
+ if (!(name_issuer = tor_x509_name_new(cname_sign)))
+ goto error;
+ if (!(X509_set_issuer_name(x509, name_issuer)))
+ goto error;
+
+ if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
+ goto error;
+ if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
+ goto error;
+ if (!X509_set_pubkey(x509, pkey))
+ goto error;
+
+ if (!X509_sign(x509, sign_pkey, EVP_sha256()))
+ goto error;
+
+ goto done;
+ error:
+ if (x509) {
+ X509_free(x509);
+ x509 = NULL;
+ }
+ done:
+ tls_log_errors(NULL, LOG_WARN, LD_NET, "generating certificate");
+ if (sign_pkey)
+ EVP_PKEY_free(sign_pkey);
+ if (pkey)
+ EVP_PKEY_free(pkey);
+ if (serial_number)
+ BN_clear_free(serial_number);
+ if (name)
+ X509_NAME_free(name);
+ if (name_issuer)
+ X509_NAME_free(name_issuer);
+ return x509;
+
+#undef SERIAL_NUMBER_SIZE
+}
+
+/** Free all storage held in <b>cert</b> */
+void
+tor_x509_cert_free_(tor_x509_cert_t *cert)
+{
+ if (! cert)
+ return;
+ if (cert->cert)
+ X509_free(cert->cert);
+ tor_free(cert->encoded);
+ memwipe(cert, 0x03, sizeof(*cert));
+ /* LCOV_EXCL_BR_START since cert will never be NULL here */
+ tor_free(cert);
+ /* LCOV_EXCL_BR_STOP */
+}
+
+/**
+ * Allocate a new tor_x509_cert_t to hold the certificate "x509_cert".
+ *
+ * Steals a reference to x509_cert.
+ */
+MOCK_IMPL(tor_x509_cert_t *,
+tor_x509_cert_new,(X509 *x509_cert))
+{
+ tor_x509_cert_t *cert;
+ EVP_PKEY *pkey;
+ RSA *rsa;
+ int length;
+ unsigned char *buf = NULL;
+
+ if (!x509_cert)
+ return NULL;
+
+ length = i2d_X509(x509_cert, &buf);
+ cert = tor_malloc_zero(sizeof(tor_x509_cert_t));
+ if (length <= 0 || buf == NULL) {
+ goto err;
+ }
+ cert->encoded_len = (size_t) length;
+ cert->encoded = tor_malloc(length);
+ memcpy(cert->encoded, buf, length);
+ OPENSSL_free(buf);
+
+ cert->cert = x509_cert;
+
+ crypto_common_digests(&cert->cert_digests,
+ (char*)cert->encoded, cert->encoded_len);
+
+ if ((pkey = X509_get_pubkey(x509_cert)) &&
+ (rsa = EVP_PKEY_get1_RSA(pkey))) {
+ crypto_pk_t *pk = crypto_new_pk_from_openssl_rsa_(rsa);
+ if (crypto_pk_get_common_digests(pk, &cert->pkey_digests) < 0) {
+ crypto_pk_free(pk);
+ EVP_PKEY_free(pkey);
+ goto err;
+ }
+
+ cert->pkey_digests_set = 1;
+ crypto_pk_free(pk);
+ EVP_PKEY_free(pkey);
+ }
+
+ return cert;
+ err:
+ /* LCOV_EXCL_START for the same reason as the exclusion above */
+ tor_free(cert);
+ log_err(LD_CRYPTO, "Couldn't wrap encoded X509 certificate.");
+ X509_free(x509_cert);
+ return NULL;
+ /* LCOV_EXCL_STOP */
+}
+
+/** Return a new copy of <b>cert</b>. */
+tor_x509_cert_t *
+tor_x509_cert_dup(const tor_x509_cert_t *cert)
+{
+ tor_assert(cert);
+ X509 *x509 = cert->cert;
+ return tor_x509_cert_new(X509_dup(x509));
+}
+
+/** Read a DER-encoded X509 cert, of length exactly <b>certificate_len</b>,
+ * from a <b>certificate</b>. Return a newly allocated tor_x509_cert_t on
+ * success and NULL on failure. */
+tor_x509_cert_t *
+tor_x509_cert_decode(const uint8_t *certificate, size_t certificate_len)
+{
+ X509 *x509;
+ const unsigned char *cp = (const unsigned char *)certificate;
+ tor_x509_cert_t *newcert;
+ tor_assert(certificate);
+ check_no_tls_errors();
+
+ if (certificate_len > INT_MAX)
+ goto err;
+
+ x509 = d2i_X509(NULL, &cp, (int)certificate_len);
+
+ if (!x509)
+ goto err; /* Couldn't decode */
+ if (cp - certificate != (int)certificate_len) {
+ X509_free(x509);
+ goto err; /* Didn't use all the bytes */
+ }
+ newcert = tor_x509_cert_new(x509);
+ if (!newcert) {
+ goto err;
+ }
+ if (newcert->encoded_len != certificate_len ||
+ fast_memneq(newcert->encoded, certificate, certificate_len)) {
+ /* Cert wasn't in DER */
+ tor_x509_cert_free(newcert);
+ goto err;
+ }
+ return newcert;
+ err:
+ tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "decoding a certificate");
+ return NULL;
+}
+
+/** Set *<b>encoded_out</b> and *<b>size_out</b> to <b>cert</b>'s encoded DER
+ * representation and length, respectively. */
+void
+tor_x509_cert_get_der(const tor_x509_cert_t *cert,
+ const uint8_t **encoded_out, size_t *size_out)
+{
+ tor_assert(cert);
+ tor_assert(encoded_out);
+ tor_assert(size_out);
+ *encoded_out = cert->encoded;
+ *size_out = cert->encoded_len;
+}
+
+/** Return a set of digests for the public key in <b>cert</b>, or NULL if this
+ * cert's public key is not one we know how to take the digest of. */
+const common_digests_t *
+tor_x509_cert_get_id_digests(const tor_x509_cert_t *cert)
+{
+ if (cert->pkey_digests_set)
+ return &cert->pkey_digests;
+ else
+ return NULL;
+}
+
+/** Return a set of digests for the public key in <b>cert</b>. */
+const common_digests_t *
+tor_x509_cert_get_cert_digests(const tor_x509_cert_t *cert)
+{
+ return &cert->cert_digests;
+}
+
+/**
+ * Return a newly allocated copy of the public key that a certificate
+ * certifies. Watch out! This returns NULL if the cert's key is not RSA.
+ */
+crypto_pk_t *
+tor_tls_cert_get_key(tor_x509_cert_t *cert)
+{
+ crypto_pk_t *result = NULL;
+ EVP_PKEY *pkey = X509_get_pubkey(cert->cert);
+ RSA *rsa;
+ if (!pkey)
+ return NULL;
+ rsa = EVP_PKEY_get1_RSA(pkey);
+ if (!rsa) {
+ EVP_PKEY_free(pkey);
+ return NULL;
+ }
+ result = crypto_new_pk_from_openssl_rsa_(rsa);
+ EVP_PKEY_free(pkey);
+ return result;
+}
+
+/** Check whether <b>cert</b> is well-formed, currently live, and correctly
+ * signed by the public key in <b>signing_cert</b>. If <b>check_rsa_1024</b>,
+ * make sure that it has an RSA key with 1024 bits; otherwise, just check that
+ * the key is long enough. Return 1 if the cert is good, and 0 if it's bad or
+ * we couldn't check it. */
+int
+tor_tls_cert_is_valid(int severity,
+ const tor_x509_cert_t *cert,
+ const tor_x509_cert_t *signing_cert,
+ time_t now,
+ int check_rsa_1024)
+{
+ check_no_tls_errors();
+ EVP_PKEY *cert_key;
+ int r, key_ok = 0;
+
+ if (!signing_cert || !cert)
+ goto bad;
+
+ EVP_PKEY *signing_key = X509_get_pubkey(signing_cert->cert);
+ if (!signing_key)
+ goto bad;
+ r = X509_verify(cert->cert, signing_key);
+ EVP_PKEY_free(signing_key);
+ if (r <= 0)
+ goto bad;
+
+ /* okay, the signature checked out right. Now let's check the check the
+ * lifetime. */
+ if (check_cert_lifetime_internal(severity, cert->cert, now,
+ 48*60*60, 30*24*60*60) < 0)
+ goto bad;
+
+ cert_key = X509_get_pubkey(cert->cert);
+ if (check_rsa_1024 && cert_key) {
+ RSA *rsa = EVP_PKEY_get1_RSA(cert_key);
+#ifdef OPENSSL_1_1_API
+ if (rsa && RSA_bits(rsa) == 1024)
+#else
+ if (rsa && BN_num_bits(rsa->n) == 1024)
+#endif
+ key_ok = 1;
+ if (rsa)
+ RSA_free(rsa);
+ } else if (cert_key) {
+ int min_bits = 1024;
+#ifdef EVP_PKEY_EC
+ if (EVP_PKEY_base_id(cert_key) == EVP_PKEY_EC)
+ min_bits = 128;
+#endif
+ if (EVP_PKEY_bits(cert_key) >= min_bits)
+ key_ok = 1;
+ }
+ EVP_PKEY_free(cert_key);
+ if (!key_ok)
+ goto bad;
+
+ /* XXXX compare DNs or anything? */
+
+ return 1;
+ bad:
+ tls_log_errors(NULL, LOG_INFO, LD_CRYPTO, "checking a certificate");
+ return 0;
+}
+
+/** Warn that a certificate lifetime extends through a certain range. */
+static void
+log_cert_lifetime(int severity, const X509 *cert, const char *problem,
+ time_t now)
+{
+ BIO *bio = NULL;
+ BUF_MEM *buf;
+ char *s1=NULL, *s2=NULL;
+ char mytime[33];
+ struct tm tm;
+ size_t n;
+
+ if (problem)
+ tor_log(severity, LD_GENERAL,
+ "Certificate %s. Either their clock is set wrong, or your clock "
+ "is wrong.",
+ problem);
+
+ if (!(bio = BIO_new(BIO_s_mem()))) {
+ log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
+ }
+ if (!(ASN1_TIME_print(bio, X509_get_notBefore_const(cert)))) {
+ tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
+ goto end;
+ }
+ BIO_get_mem_ptr(bio, &buf);
+ s1 = tor_strndup(buf->data, buf->length);
+
+ (void)BIO_reset(bio);
+ if (!(ASN1_TIME_print(bio, X509_get_notAfter_const(cert)))) {
+ tls_log_errors(NULL, LOG_WARN, LD_NET, "printing certificate lifetime");
+ goto end;
+ }
+ BIO_get_mem_ptr(bio, &buf);
+ s2 = tor_strndup(buf->data, buf->length);
+
+ n = strftime(mytime, 32, "%b %d %H:%M:%S %Y UTC", tor_gmtime_r(&now, &tm));
+ if (n > 0) {
+ tor_log(severity, LD_GENERAL,
+ "(certificate lifetime runs from %s through %s. Your time is %s.)",
+ s1,s2,mytime);
+ } else {
+ tor_log(severity, LD_GENERAL,
+ "(certificate lifetime runs from %s through %s. "
+ "Couldn't get your time.)",
+ s1, s2);
+ }
+
+ end:
+ /* Not expected to get invoked */
+ tls_log_errors(NULL, LOG_WARN, LD_NET, "getting certificate lifetime");
+ if (bio)
+ BIO_free(bio);
+ tor_free(s1);
+ tor_free(s2);
+}
+
+/** Helper: check whether <b>cert</b> is expired give or take
+ * <b>past_tolerance</b> seconds, or not-yet-valid give or take
+ * <b>future_tolerance</b> seconds. (Relative to the current time
+ * <b>now</b>.) If it is live, return 0. If it is not live, log a message
+ * and return -1. */
+int
+check_cert_lifetime_internal(int severity, const X509 *cert,
+ time_t now,
+ int past_tolerance, int future_tolerance)
+{
+ time_t t;
+
+ t = now + future_tolerance;
+ if (X509_cmp_time(X509_get_notBefore_const(cert), &t) > 0) {
+ log_cert_lifetime(severity, cert, "not yet valid", now);
+ return -1;
+ }
+ t = now - past_tolerance;
+ if (X509_cmp_time(X509_get_notAfter_const(cert), &t) < 0) {
+ log_cert_lifetime(severity, cert, "already expired", now);
+ return -1;
+ }
+
+ return 0;
+}
+
+#ifdef TOR_UNIT_TESTS
+/* Testing only: return a new x509 cert with the same contents as <b>inp</b>,
+ but with the expiration time <b>new_expiration_time</b>, signed with
+ <b>signing_key</b>. */
+STATIC tor_x509_cert_t *
+tor_x509_cert_replace_expiration(const tor_x509_cert_t *inp,
+ time_t new_expiration_time,
+ crypto_pk_t *signing_key)
+{
+ X509 *newc = X509_dup(inp->cert);
+ X509_time_adj(X509_get_notAfter(newc), 0, &new_expiration_time);
+ EVP_PKEY *pk = crypto_pk_get_openssl_evp_pkey_(signing_key, 1);
+ tor_assert(X509_sign(newc, pk, EVP_sha256()));
+ EVP_PKEY_free(pk);
+ return tor_x509_cert_new(newc);
+}
+#endif /* defined(TOR_UNIT_TESTS) */
diff --git a/src/lib/tls/x509.h b/src/lib/tls/x509.h
new file mode 100644
index 000000000..2f3f3a410
--- /dev/null
+++ b/src/lib/tls/x509.h
@@ -0,0 +1,78 @@
+/* Copyright (c) 2003, Roger Dingledine
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#ifndef TOR_X509_H
+#define TOR_X509_H
+
+/**
+ * \file x509.h
+ * \brief Headers for tortls.c
+ **/
+
+#include "lib/crypt_ops/crypto_rsa.h"
+#include "lib/crypt_ops/compat_openssl.h"
+#include "lib/testsupport/testsupport.h"
+
+/* Opaque structure to hold an X509 certificate. */
+typedef struct tor_x509_cert_t tor_x509_cert_t;
+
+#ifdef ENABLE_OPENSSL
+struct x509_st;
+#endif
+
+/** Structure that we use for a single certificate. */
+struct tor_x509_cert_t {
+#ifdef ENABLE_OPENSSL
+ struct x509_st *cert;
+#endif
+ uint8_t *encoded;
+ size_t encoded_len;
+ unsigned pkey_digests_set : 1;
+ common_digests_t cert_digests;
+ common_digests_t pkey_digests;
+};
+
+MOCK_DECL(struct x509_st *, tor_tls_create_certificate,
+ (crypto_pk_t *rsa,
+ crypto_pk_t *rsa_sign,
+ const char *cname,
+ const char *cname_sign,
+ unsigned int cert_lifetime));
+MOCK_DECL(tor_x509_cert_t *, tor_x509_cert_new,
+ (struct x509_st *x509_cert));
+
+#ifdef TOR_UNIT_TESTS
+tor_x509_cert_t *tor_x509_cert_replace_expiration(
+ const tor_x509_cert_t *inp,
+ time_t new_expiration_time,
+ crypto_pk_t *signing_key);
+#endif
+
+tor_x509_cert_t *tor_x509_cert_dup(const tor_x509_cert_t *cert);
+
+void tor_x509_cert_free_(tor_x509_cert_t *cert);
+#define tor_x509_cert_free(c) \
+ FREE_AND_NULL(tor_x509_cert_t, tor_x509_cert_free_, (c))
+tor_x509_cert_t *tor_x509_cert_decode(const uint8_t *certificate,
+ size_t certificate_len);
+void tor_x509_cert_get_der(const tor_x509_cert_t *cert,
+ const uint8_t **encoded_out, size_t *size_out);
+const common_digests_t *tor_x509_cert_get_id_digests(
+ const tor_x509_cert_t *cert);
+const common_digests_t *tor_x509_cert_get_cert_digests(
+ const tor_x509_cert_t *cert);
+
+crypto_pk_t *tor_tls_cert_get_key(tor_x509_cert_t *cert);
+int tor_tls_cert_is_valid(int severity,
+ const tor_x509_cert_t *cert,
+ const tor_x509_cert_t *signing_cert,
+ time_t now,
+ int check_rsa_1024);
+
+int check_cert_lifetime_internal(int severity, const X509 *cert,
+ time_t now,
+ int past_tolerance, int future_tolerance);
+
+#endif
diff --git a/src/test/test_link_handshake.c b/src/test/test_link_handshake.c
index e0d12fb47..c1ede5420 100644
--- a/src/test/test_link_handshake.c
+++ b/src/test/test_link_handshake.c
@@ -25,6 +25,7 @@
#include "core/or/var_cell_st.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/x509.h"
#include "test/test.h"
#include "test/log_test_helpers.h"
diff --git a/src/test/test_tortls.c b/src/test/test_tortls.c
index cd3435556..f5b11d4f2 100644
--- a/src/test/test_tortls.c
+++ b/src/test/test_tortls.c
@@ -34,6 +34,7 @@ ENABLE_GCC_WARNING(redundant-decls)
#include "lib/log/log.h"
#include "app/config/config.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/x509.h"
#include "app/config/or_state_st.h"
#include "test/test.h"
1
0
[tor/master] Extract tortls structures into a new header; clean up a little
by nickm@torproject.org 05 Sep '18
by nickm@torproject.org 05 Sep '18
05 Sep '18
commit 598bc78bfa62e0879497c0ef03999d3700a5cd16
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Sat Aug 11 19:38:07 2018 -0400
Extract tortls structures into a new header; clean up a little
---
src/lib/tls/tortls.c | 5 ++--
src/lib/tls/tortls.h | 58 +-----------------------------------
src/lib/tls/tortls_st.h | 67 ++++++++++++++++++++++++++++++++++++++++++
src/lib/tls/x509.c | 11 ++++++-
src/lib/tls/x509.h | 24 ++++++++-------
src/test/test_link_handshake.c | 1 +
src/test/test_tortls.c | 3 ++
7 files changed, 99 insertions(+), 70 deletions(-)
diff --git a/src/lib/tls/tortls.c b/src/lib/tls/tortls.c
index 20e432081..cb507057e 100644
--- a/src/lib/tls/tortls.c
+++ b/src/lib/tls/tortls.c
@@ -28,6 +28,7 @@
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_dh.h"
#include "lib/crypt_ops/crypto_util.h"
+#include "lib/crypt_ops/compat_openssl.h"
#include "lib/tls/x509.h"
/* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
@@ -51,8 +52,8 @@ DISABLE_GCC_WARNING(redundant-decls)
ENABLE_GCC_WARNING(redundant-decls)
-#define TORTLS_PRIVATE
#include "lib/tls/tortls.h"
+#include "lib/tls/tortls_st.h"
#include "lib/log/log.h"
#include "lib/log/util_bug.h"
#include "lib/container/smartlist.h"
@@ -599,7 +600,7 @@ tor_tls_cert_matches_key,(const tor_tls_t *tls, const tor_x509_cert_t *cert))
if (!peercert)
return 0;
link_key = X509_get_pubkey(peercert);
- cert_key = X509_get_pubkey(cert->cert);
+ cert_key = X509_get_pubkey((X509 *)tor_x509_cert_get_impl(cert));
result = link_key && cert_key && EVP_PKEY_cmp(cert_key, link_key) == 1;
diff --git a/src/lib/tls/tortls.h b/src/lib/tls/tortls.h
index a1d90c16b..f46e73267 100644
--- a/src/lib/tls/tortls.h
+++ b/src/lib/tls/tortls.h
@@ -12,7 +12,6 @@
**/
#include "lib/crypt_ops/crypto_rsa.h"
-#include "lib/crypt_ops/compat_openssl.h"
#include "lib/testsupport/testsupport.h"
/* Opaque structure to hold a TLS connection. */
@@ -52,14 +51,6 @@ struct tor_x509_cert_t;
#define TOR_TLS_IS_ERROR(rv) ((rv) < TOR_TLS_CLOSE)
#ifdef TORTLS_PRIVATE
-#define TOR_TLS_MAGIC 0x71571571
-
-typedef enum {
- TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
- TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
- TOR_TLS_ST_BUFFEREVENT
-} tor_tls_state_t;
-#define tor_tls_state_bitfield_t ENUM_BF(tor_tls_state_t)
#ifdef ENABLE_OPENSSL
struct ssl_st;
@@ -70,54 +61,7 @@ struct ssl_session_st;
/** Holds a SSL_CTX object and related state used to configure TLS
* connections.
*/
-typedef struct tor_tls_context_t {
- int refcnt;
- struct ssl_ctx_st *ctx;
- struct tor_x509_cert_t *my_link_cert;
- struct tor_x509_cert_t *my_id_cert;
- struct tor_x509_cert_t *my_auth_cert;
- crypto_pk_t *link_key;
- crypto_pk_t *auth_key;
-} tor_tls_context_t;
-
-/** Holds a SSL object and its associated data. Members are only
- * accessed from within tortls.c.
- */
-struct tor_tls_t {
- uint32_t magic;
- tor_tls_context_t *context; /** A link to the context object for this tls. */
- struct ssl_st *ssl; /**< An OpenSSL SSL object. */
- int socket; /**< The underlying file descriptor for this TLS connection. */
- char *address; /**< An address to log when describing this connection. */
- tor_tls_state_bitfield_t state : 3; /**< The current SSL state,
- * depending on which operations
- * have completed successfully. */
- unsigned int isServer:1; /**< True iff this is a server-side connection */
- unsigned int wasV2Handshake:1; /**< True iff the original handshake for
- * this connection used the updated version
- * of the connection protocol (client sends
- * different cipher list, server sends only
- * one certificate). */
- /** True iff we should call negotiated_callback when we're done reading. */
- unsigned int got_renegotiate:1;
- /** Return value from tor_tls_classify_client_ciphers, or 0 if we haven't
- * called that function yet. */
- int8_t client_cipher_list_type;
- /** Incremented every time we start the server side of a handshake. */
- uint8_t server_handshake_count;
- size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
- * time. */
- /** Last values retrieved from BIO_number_read()/write(); see
- * tor_tls_get_n_raw_bytes() for usage.
- */
- unsigned long last_write_count;
- unsigned long last_read_count;
- /** If set, a callback to invoke whenever the client tries to renegotiate
- * the handshake. */
- void (*negotiated_callback)(tor_tls_t *tls, void *arg);
- /** Argument to pass to negotiated_callback. */
- void *callback_arg;
-};
+typedef struct tor_tls_context_t tor_tls_context_t;
STATIC int tor_errno_to_tls_error(int e);
STATIC int tor_tls_get_error(tor_tls_t *tls, int r, int extra,
diff --git a/src/lib/tls/tortls_st.h b/src/lib/tls/tortls_st.h
new file mode 100644
index 000000000..897be497e
--- /dev/null
+++ b/src/lib/tls/tortls_st.h
@@ -0,0 +1,67 @@
+/* Copyright (c) 2003, Roger Dingledine
+ * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
+ * Copyright (c) 2007-2018, The Tor Project, Inc. */
+/* See LICENSE for licensing information */
+
+#ifndef TOR_TORTLS_ST_H
+#define TOR_TORTLS_ST_H
+
+#define TOR_TLS_MAGIC 0x71571571
+
+typedef enum {
+ TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
+ TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED, TOR_TLS_ST_RENEGOTIATE,
+ TOR_TLS_ST_BUFFEREVENT
+} tor_tls_state_t;
+#define tor_tls_state_bitfield_t ENUM_BF(tor_tls_state_t)
+
+struct tor_tls_context_t {
+ int refcnt;
+ struct ssl_ctx_st *ctx;
+ struct tor_x509_cert_t *my_link_cert;
+ struct tor_x509_cert_t *my_id_cert;
+ struct tor_x509_cert_t *my_auth_cert;
+ crypto_pk_t *link_key;
+ crypto_pk_t *auth_key;
+};
+
+/** Holds a SSL object and its associated data. Members are only
+ * accessed from within tortls.c.
+ */
+struct tor_tls_t {
+ uint32_t magic;
+ tor_tls_context_t *context; /** A link to the context object for this tls. */
+ struct ssl_st *ssl; /**< An OpenSSL SSL object. */
+ int socket; /**< The underlying file descriptor for this TLS connection. */
+ char *address; /**< An address to log when describing this connection. */
+ tor_tls_state_bitfield_t state : 3; /**< The current SSL state,
+ * depending on which operations
+ * have completed successfully. */
+ unsigned int isServer:1; /**< True iff this is a server-side connection */
+ unsigned int wasV2Handshake:1; /**< True iff the original handshake for
+ * this connection used the updated version
+ * of the connection protocol (client sends
+ * different cipher list, server sends only
+ * one certificate). */
+ /** True iff we should call negotiated_callback when we're done reading. */
+ unsigned int got_renegotiate:1;
+ /** Return value from tor_tls_classify_client_ciphers, or 0 if we haven't
+ * called that function yet. */
+ int8_t client_cipher_list_type;
+ /** Incremented every time we start the server side of a handshake. */
+ uint8_t server_handshake_count;
+ size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
+ * time. */
+ /** Last values retrieved from BIO_number_read()/write(); see
+ * tor_tls_get_n_raw_bytes() for usage.
+ */
+ unsigned long last_write_count;
+ unsigned long last_read_count;
+ /** If set, a callback to invoke whenever the client tries to renegotiate
+ * the handshake. */
+ void (*negotiated_callback)(tor_tls_t *tls, void *arg);
+ /** Argument to pass to negotiated_callback. */
+ void *callback_arg;
+};
+
+#endif
diff --git a/src/lib/tls/x509.c b/src/lib/tls/x509.c
index feded3473..27cba1be6 100644
--- a/src/lib/tls/x509.c
+++ b/src/lib/tls/x509.c
@@ -9,11 +9,12 @@
* X.509 functions from OpenSSL.
**/
+#define TOR_X509_PRIVATE
#include "lib/tls/x509.h"
#include "lib/tls/tortls.h"
-//#include "lib/crypt_ops/crypto_cipher.h"
#include "lib/crypt_ops/crypto_rand.h"
#include "lib/crypt_ops/crypto_util.h"
+#include "lib/crypt_ops/compat_openssl.h"
/* Some versions of OpenSSL declare SSL_get_selected_srtp_profile twice in
* srtp.h. Suppress the GCC warning so we can build with -Wredundant-decl. */
@@ -332,6 +333,14 @@ tor_x509_cert_get_der(const tor_x509_cert_t *cert,
*size_out = cert->encoded_len;
}
+/** Return the underlying implementation for <b>cert</b> */
+const tor_x509_cert_impl_t *
+tor_x509_cert_get_impl(const tor_x509_cert_t *cert)
+{
+ tor_assert(cert);
+ return cert->cert;
+}
+
/** Return a set of digests for the public key in <b>cert</b>, or NULL if this
* cert's public key is not one we know how to take the digest of. */
const common_digests_t *
diff --git a/src/lib/tls/x509.h b/src/lib/tls/x509.h
index 2f3f3a410..4dadba06d 100644
--- a/src/lib/tls/x509.h
+++ b/src/lib/tls/x509.h
@@ -12,36 +12,35 @@
**/
#include "lib/crypt_ops/crypto_rsa.h"
-#include "lib/crypt_ops/compat_openssl.h"
#include "lib/testsupport/testsupport.h"
/* Opaque structure to hold an X509 certificate. */
typedef struct tor_x509_cert_t tor_x509_cert_t;
#ifdef ENABLE_OPENSSL
-struct x509_st;
+typedef struct x509_st tor_x509_cert_impl_t;
#endif
+#ifdef TOR_X509_PRIVATE
/** Structure that we use for a single certificate. */
struct tor_x509_cert_t {
-#ifdef ENABLE_OPENSSL
- struct x509_st *cert;
-#endif
+ tor_x509_cert_impl_t *cert;
uint8_t *encoded;
size_t encoded_len;
unsigned pkey_digests_set : 1;
common_digests_t cert_digests;
common_digests_t pkey_digests;
};
+#endif
-MOCK_DECL(struct x509_st *, tor_tls_create_certificate,
+MOCK_DECL(tor_x509_cert_impl_t *, tor_tls_create_certificate,
(crypto_pk_t *rsa,
crypto_pk_t *rsa_sign,
const char *cname,
const char *cname_sign,
unsigned int cert_lifetime));
MOCK_DECL(tor_x509_cert_t *, tor_x509_cert_new,
- (struct x509_st *x509_cert));
+ (tor_x509_cert_impl_t *x509_cert));
#ifdef TOR_UNIT_TESTS
tor_x509_cert_t *tor_x509_cert_replace_expiration(
@@ -57,22 +56,27 @@ void tor_x509_cert_free_(tor_x509_cert_t *cert);
FREE_AND_NULL(tor_x509_cert_t, tor_x509_cert_free_, (c))
tor_x509_cert_t *tor_x509_cert_decode(const uint8_t *certificate,
size_t certificate_len);
+const tor_x509_cert_impl_t *tor_x509_cert_get_impl(
+ const tor_x509_cert_t *cert);
void tor_x509_cert_get_der(const tor_x509_cert_t *cert,
const uint8_t **encoded_out, size_t *size_out);
+
const common_digests_t *tor_x509_cert_get_id_digests(
const tor_x509_cert_t *cert);
const common_digests_t *tor_x509_cert_get_cert_digests(
const tor_x509_cert_t *cert);
crypto_pk_t *tor_tls_cert_get_key(tor_x509_cert_t *cert);
+
int tor_tls_cert_is_valid(int severity,
const tor_x509_cert_t *cert,
const tor_x509_cert_t *signing_cert,
time_t now,
int check_rsa_1024);
-int check_cert_lifetime_internal(int severity, const X509 *cert,
- time_t now,
- int past_tolerance, int future_tolerance);
+int check_cert_lifetime_internal(int severity,
+ const tor_x509_cert_impl_t *cert,
+ time_t now,
+ int past_tolerance, int future_tolerance);
#endif
diff --git a/src/test/test_link_handshake.c b/src/test/test_link_handshake.c
index c1ede5420..e4722b4df 100644
--- a/src/test/test_link_handshake.c
+++ b/src/test/test_link_handshake.c
@@ -24,6 +24,7 @@
#include "core/or/or_handshake_state_st.h"
#include "core/or/var_cell_st.h"
+#define TOR_X509_PRIVATE
#include "lib/tls/tortls.h"
#include "lib/tls/x509.h"
diff --git a/src/test/test_tortls.c b/src/test/test_tortls.c
index f5b11d4f2..ec197ba99 100644
--- a/src/test/test_tortls.c
+++ b/src/test/test_tortls.c
@@ -3,6 +3,7 @@
#define TORTLS_PRIVATE
#define TORTLS_OPENSSL_PRIVATE
+#define TOR_X509_PRIVATE
#define LOG_PRIVATE
#include "orconfig.h"
@@ -33,7 +34,9 @@ ENABLE_GCC_WARNING(redundant-decls)
#include "core/or/or.h"
#include "lib/log/log.h"
#include "app/config/config.h"
+#include "lib/crypt_ops/compat_openssl.h"
#include "lib/tls/tortls.h"
+#include "lib/tls/tortls_st.h"
#include "lib/tls/x509.h"
#include "app/config/or_state_st.h"
1
0
[tor/master] The RSA_free in this test is no longer needed or wanted
by nickm@torproject.org 05 Sep '18
by nickm@torproject.org 05 Sep '18
05 Sep '18
commit 3ccb94d7b6ff6806bc17d71ef461f4211a014879
Author: Nick Mathewson <nickm(a)torproject.org>
Date: Sat Aug 11 16:36:05 2018 -0400
The RSA_free in this test is no longer needed or wanted
---
src/test/test_tortls.c | 1 -
1 file changed, 1 deletion(-)
diff --git a/src/test/test_tortls.c b/src/test/test_tortls.c
index 49a39e264..cd3435556 100644
--- a/src/test/test_tortls.c
+++ b/src/test/test_tortls.c
@@ -702,7 +702,6 @@ test_tortls_get_my_client_auth_key(void *ignored)
tt_assert(ret == expected);
done:
- RSA_free(k);
tor_free(expected);
tor_free(ctx);
}
1
0