From 953aab6fe47be9e92fcbf5fb8418dee0d682e7ca Mon Sep 17 00:00:00 2001 From: Chris Mc Date: Tue, 26 Dec 2023 12:23:21 -0500 Subject: [PATCH] Add helper for making RSA key from exponent and modulus (#307) * - Added creation of public key from its components - Split verify function to signature and claims - Added handling of claims set in json while creating a verifier * - Added creation of public key from its components - Split verify function to signature and claims - Added handling of claims set in json while creating a verifier * Fixed missing lines * Added unit tests * Additional changes * delete * refactor free * remove testing * align white space * Update tests/PubKeyTest.cpp Yes I should have removed it. Used it in testing Co-authored-by: Chris Mc * Add support for 1.0.2 * refactor a bit * user jwt define for SSL API that is cross-library * add support for no base64 from jwt * refactor a bit more * fixup wolfssl + linters * missing include for openssl 3 * quick draft of openssl 3 implementation * linter * add in a health layer of error handling and memory management * flip function order * fix typo * error tests for openssl * more all helper tests to one file * update cmake * update tests * more negative test cases * fixup old api calls depending on version * linter * fixup return types * disable failing tests * fixup copy passed * disable more tests * fixup broke tests * better error code handling * test asan with more openssl versions * fix template render path * fix cache conflict running different ubuntu docker images for with different GLIB c and cxx ABIs * add missing lib to tests * run both openssl versions with asan * openssl code always calls new and returns an adress in most cases so always save the pointer to call free? * go back to old raw2bn implementation * Revert "openssl code always calls new and returns an adress in most cases" This reverts commit 45e85b8c667587236ac3dd255d1450bcf22f5723. * remove add new tests (needs to be a seperate pr) * fix jwks verify example + run with asan+lsan * some extra backwards compat for ssl1.1 * compat rsa keygen * fixup copy paste * fix typo * linter * wolfssl compat * compat 1.1.0i * more compat since they changed the API with ever version * linter * fix 1.1.0 * more compat * more compat working on the matrix of wolfssl and libress and 1.1.0 * updated example with hardcoded values * action to install openssl now sets ENV vars for CMake https://gitlab.kitware.com/cmake/cmake/-/blob/master/Modules/FindOpenSSL.cmake#L233 https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-environment-variable https://gitlab.kitware.com/cmake/cmake/-/issues/24236 * update example to create a valid token * update asan to latest compiler * clang tidy * fix memory leak in openssl 1.1.1 this is theoretically only because of the test code but better safe then sorry * clang format * improve docs * enable one more test * fix test impl signature * more test for bio to std::string * DRY up code with new helper for write_bio_to_string * fix copy paste + spell checking * linter * fix typo * fix return type * BIO_get_mem_data is just a define so fixup error implementation to match * put extra tests in too many places its only for certs not just pubkeys --------- Co-authored-by: ZOHARGO Co-authored-by: zgofer1 --- .github/actions/install/cmake/action.yml | 3 +- .github/actions/install/openssl/action.yml | 2 + .github/workflows/jwt.yml | 14 +- example/jwks-verify.cpp | 103 ++++++- include/jwt-cpp/jwt.h | 301 +++++++++++++++++---- tests/CMakeLists.txt | 4 +- tests/HelperTest.cpp | 23 +- tests/OpenSSLErrorTest.cpp | 165 +++++++++++ tests/TokenTest.cpp | 6 +- 9 files changed, 545 insertions(+), 76 deletions(-) diff --git a/.github/actions/install/cmake/action.yml b/.github/actions/install/cmake/action.yml index 8627f7e..ac0a023 100644 --- a/.github/actions/install/cmake/action.yml +++ b/.github/actions/install/cmake/action.yml @@ -14,8 +14,7 @@ runs: id: cache-cmake uses: actions/cache@v3 with: - path: cmake-${{ inputs.version }} - key: ${{ runner.name }}-${{ runner.os }}-${{ runner.arch }}-cmake-${{ inputs.version }} + path: cmake-${{ inputs.version }}${{ runner.name }}-${{ runner.os }}-${{ runner.arch }}-${{ job.container.id }}-cmake-${{ inputs.version }} - name: Build cmake if: steps.cache-cmake.outputs.cache-hit != 'true' run: | diff --git a/.github/actions/install/openssl/action.yml b/.github/actions/install/openssl/action.yml index 7b161b6..83c03a2 100644 --- a/.github/actions/install/openssl/action.yml +++ b/.github/actions/install/openssl/action.yml @@ -16,4 +16,6 @@ runs: ./config --prefix=/tmp --libdir=lib make -j $(nproc) sudo make -j $(nproc) install_sw + echo "OPENSSL_ROOT_DIR=/tmp" >> "$GITHUB_ENV" + echo "OpenSSL_ROOT=/tmp" >> "$GITHUB_ENV" shell: bash diff --git a/.github/workflows/jwt.yml b/.github/workflows/jwt.yml index 46e35cc..07d2d69 100644 --- a/.github/workflows/jwt.yml +++ b/.github/workflows/jwt.yml @@ -53,12 +53,21 @@ jobs: ./tests/fuzz/jwt-cpp-fuzz-BaseDecodeFuzz -runs=100000 ../tests/fuzz/decode-corpus ./tests/fuzz/jwt-cpp-fuzz-TokenDecodeFuzz -runs=100000 ../tests/fuzz/token-corpus - asan: ## Based on https://gist.github.com/jlblancoc/44be9d4d466f0a973b1f3808a8e56782 - runs-on: ubuntu-20.04 + asan: # Based on https://gist.github.com/jlblancoc/44be9d4d466f0a973b1f3808a8e56782 + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + openssl: + - { tag: "openssl-3.0.5", name: "3.0.5" } + - { tag: "OpenSSL_1_1_1q", name: "1.1.1q" } steps: - uses: actions/checkout@v3 - uses: lukka/get-cmake@latest - uses: ./.github/actions/install/gtest + - uses: ./.github/actions/install/openssl + with: + version: ${{ matrix.openssl.tag }} - name: configure run: | @@ -76,6 +85,7 @@ jobs: export ASAN_OPTIONS=check_initialization_order=true:detect_stack_use_after_return=true:fast_unwind_on_malloc=0 ./example/rsa-create ./example/rsa-verify + ./example/jwks-verify ./tests/jwt-cpp-test ubsan: diff --git a/example/jwks-verify.cpp b/example/jwks-verify.cpp index 2464a5f..de4b136 100644 --- a/example/jwks-verify.cpp +++ b/example/jwks-verify.cpp @@ -1,5 +1,6 @@ #include #include +#include int main() { std::string raw_jwks = @@ -9,11 +10,10 @@ int main() { "kty": "RSA", "use": "sig", "x5c": [ - "MIIC+DCCAeCgAwIBAgIJBIGjYW6hFpn2MA0GCSqGSIb3DQEBBQUAMCMxITAfBgNVBAMTGGN1c3RvbWVyLWRlbW9zLmF1dGgwLmNvbTAeFw0xNjExMjIyMjIyMDVaFw0zMDA4MDEyMjIyMDVaMCMxITAfBgNVBAMTGGN1c3RvbWVyLWRlbW9zLmF1dGgwLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMnjZc5bm/eGIHq09N9HKHahM7Y31P0ul+A2wwP4lSpIwFrWHzxw88/7Dwk9QMc+orGXX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/tj7yZ8YbbvUPO402EExrjzeSPXRj9 +fkydsRvTpSd+lAF58xROotyjBK+r8yqR5h9jJ3m3zSoHuNogryjvCKJJSxYW94Zt +ARS9Ln8Wh5RsFuw/Y7Grg8FsoAVzV/Pns4cwjZG75ezXfk4UVpr4oO4B5jzazzCR +3ijoionumWmfwPmP8KBMSciMtz+dy+NN0vLTocT1nqCdiQ7lbF3o9HMwLVDn7E6q ++grQSrtFfSnickR6i3XrDlspd/khcQ== +-----END PRIVATE KEY-----)"; + + // https://stackoverflow.com/a/30138974 + unsigned char nonce[24]; + RAND_bytes(nonce, sizeof(nonce)); + std::string jti = + jwt::base::encode(std::string{reinterpret_cast(nonce), sizeof(nonce)}); + + std::string token = jwt::create() + .set_issuer("auth0") + .set_type("JWT") + .set_id(jti) + .set_key_id("internal-gateway-jwt.api.sc.net") + .set_subject("jwt-cpp.example.localhost") + .set_issued_at(std::chrono::system_clock::now()) + .set_expires_at(std::chrono::system_clock::now() + std::chrono::seconds{36000}) + .set_payload_claim("sample", jwt::claim(std::string{"test"})) + .sign(jwt::algorithm::rs256("", pem_priv_key, "", "")); auto decoded_jwt = jwt::decode(token); auto jwks = jwt::parse_jwks(raw_jwks); @@ -46,12 +105,28 @@ int main() { auto x5c = jwk.get_x5c_key_value(); if (!x5c.empty() && !issuer.empty()) { + std::cout << "Verifying with 'x5c' key" << std::endl; auto verifier = jwt::verify() .allow_algorithm(jwt::algorithm::rs256(jwt::helper::convert_base64_der_to_pem(x5c), "", "", "")) .with_issuer(issuer) + .with_id(jti) .leeway(60UL); // value in seconds, add some to compensate timeout verifier.verify(decoded_jwt); } + // else if the optional 'x5c' was not present + { + std::cout << "Verifying with RSA components" << std::endl; + const auto modulus = jwk.get_jwk_claim("n").as_string(); + const auto exponent = jwk.get_jwk_claim("e").as_string(); + auto verifier = jwt::verify() + .allow_algorithm(jwt::algorithm::rs256( + jwt::helper::create_public_key_from_rsa_components(modulus, exponent))) + .with_issuer(issuer) + .with_id(jti) + .leeway(60UL); // value in seconds, add some to compensate timeout + + verifier.verify(decoded_jwt); + } } diff --git a/include/jwt-cpp/jwt.h b/include/jwt-cpp/jwt.h index dc645a5..fe3fd10 100644 --- a/include/jwt-cpp/jwt.h +++ b/include/jwt-cpp/jwt.h @@ -51,6 +51,7 @@ #if OPENSSL_VERSION_NUMBER >= 0x30000000L // 3.0.0 #define JWT_OPENSSL_3_0 +#include #elif OPENSSL_VERSION_NUMBER >= 0x10101000L // 1.1.1 #define JWT_OPENSSL_1_1_1 #elif OPENSSL_VERSION_NUMBER >= 0x10100000L // 1.1.0 @@ -120,7 +121,9 @@ namespace jwt { load_key_bio_write, load_key_bio_read, create_mem_bio_failed, - no_key_provided + no_key_provided, + set_rsa_failed, + create_context_failed }; /** * \brief Error category for RSA errors @@ -141,6 +144,8 @@ namespace jwt { case rsa_error::load_key_bio_read: return "failed to load key: bio read failed"; case rsa_error::create_mem_bio_failed: return "failed to create memory bio"; case rsa_error::no_key_provided: return "at least one of public or private key need to be present"; + case rsa_error::set_rsa_failed: return "set modulus and exponent to RSA failed"; + case rsa_error::create_context_failed: return "failed to create context"; default: return "unknown RSA error"; } } @@ -491,6 +496,17 @@ namespace jwt { ); } + template + std::string write_bio_to_string(std::unique_ptr& bio_out, std::error_code& ec) { + char* ptr = nullptr; + auto len = BIO_get_mem_data(bio_out.get(), &ptr); + if (len <= 0 || ptr == nullptr) { + ec = error_category::convert_to_pem_failed; + return {}; + } + return {ptr, static_cast(len)}; + } + inline std::unique_ptr make_evp_md_ctx() { return #ifdef JWT_OPENSSL_1_0_0 @@ -533,13 +549,8 @@ namespace jwt { ec = error_category::write_key_failed; return {}; } - char* ptr = nullptr; - auto len = BIO_get_mem_data(keybio.get(), &ptr); - if (len <= 0 || ptr == nullptr) { - ec = error_category::convert_to_pem_failed; - return {}; - } - return {ptr, static_cast(len)}; + + return write_bio_to_string(keybio, ec); } /** @@ -582,14 +593,7 @@ namespace jwt { return {}; } - char* ptr = nullptr; - const auto len = BIO_get_mem_data(certbio.get(), &ptr); - if (len <= 0 || ptr == nullptr) { - ec = error::rsa_error::convert_to_pem_failed; - return {}; - } - - return {ptr, static_cast(len)}; + return write_bio_to_string(certbio, ec); } /** @@ -598,7 +602,7 @@ namespace jwt { * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info * (here)[https://tools.ietf.org/html/rfc7517#section-4.7] * - * \tparam Decode is callabled, taking a string_type and returns a string_type. + * \tparam Decode is callable, taking a string_type and returns a string_type. * It should ensure the padding of the input and then base64 decode and return * the results. * @@ -620,7 +624,7 @@ namespace jwt { * This is useful when using with JWKs as x5c claim is encoded as base64 DER. More info * (here)[https://tools.ietf.org/html/rfc7517#section-4.7] * - * \tparam Decode is callabled, taking a string_type and returns a string_type. + * \tparam Decode is callable, taking a string_type and returns a string_type. * It should ensure the padding of the input and then base64 decode and return * the results. * @@ -640,7 +644,6 @@ namespace jwt { * \brief Convert the certificate provided as DER to PEM. * * \param cert_der_str String containing the DER certificate - * \param decode The function to decode the cert * \throw rsa_exception if an error occurred */ inline std::string convert_der_to_pem(const std::string& cert_der_str) { @@ -803,6 +806,52 @@ namespace jwt { return load_public_key_from_string(key, password, ec); } + /** + * Convert a OpenSSL BIGNUM to a std::string + * \param bn BIGNUM to convert + * \return bignum as string + */ + inline +#ifdef JWT_OPENSSL_1_0_0 + std::string + bn2raw(BIGNUM* bn) +#else + std::string + bn2raw(const BIGNUM* bn) +#endif + { + std::string res(BN_num_bytes(bn), '\0'); + BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast` + return res; + } + /** + * Convert an std::string to a OpenSSL BIGNUM + * \param raw String to convert + * \param ec error_code for error_detection (gets cleared if no error occurs) + * \return BIGNUM representation + */ + inline std::unique_ptr raw2bn(const std::string& raw, std::error_code& ec) { + auto bn = + BN_bin2bn(reinterpret_cast(raw.data()), static_cast(raw.size()), nullptr); + // https://www.openssl.org/docs/man1.1.1/man3/BN_bin2bn.html#RETURN-VALUES + if (!bn) { + ec = error::rsa_error::set_rsa_failed; + return {nullptr, BN_free}; + } + return {bn, BN_free}; + } + /** + * Convert an std::string to a OpenSSL BIGNUM + * \param raw String to convert + * \return BIGNUM representation + */ + inline std::unique_ptr raw2bn(const std::string& raw) { + std::error_code ec; + auto res = raw2bn(raw, ec); + error::throw_if_error(ec); + return res; + } + /** * \brief Load a public key from a string. * @@ -836,6 +885,181 @@ namespace jwt { return load_private_key_from_string(key, password, ec); } + /** + * \brief create public key from modulus and exponent. This is defined in + * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3) + * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter. + * + * \tparam Decode is callable, taking a string_type and returns a string_type. + * It should ensure the padding of the input and then base64url decode and + * return the results. + * \param modulus string containing base64url encoded modulus + * \param exponent string containing base64url encoded exponent + * \param decode The function to decode the RSA parameters + * \param ec error_code for error_detection (gets cleared if no error occur + * \return public key in PEM format + */ + template + std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent, + Decode decode, std::error_code& ec) { + ec.clear(); + auto decoded_modulus = decode(modulus); + auto decoded_exponent = decode(exponent); + + auto n = helper::raw2bn(decoded_modulus, ec); + if (ec) return {}; + auto e = helper::raw2bn(decoded_exponent, ec); + if (ec) return {}; + +#if defined(JWT_OPENSSL_3_0) + // OpenSSL deprecated mutable keys and there is a new way for making them + // https://mta.openssl.org/pipermail/openssl-users/2021-July/013994.html + // https://www.openssl.org/docs/man3.1/man3/OSSL_PARAM_BLD_new.html#Example-2 + std::unique_ptr param_bld(OSSL_PARAM_BLD_new(), + OSSL_PARAM_BLD_free); + if (!param_bld) { + ec = error::rsa_error::create_context_failed; + return {}; + } + + if (OSSL_PARAM_BLD_push_BN(param_bld.get(), "n", n.get()) != 1 || + OSSL_PARAM_BLD_push_BN(param_bld.get(), "e", e.get()) != 1) { + ec = error::rsa_error::set_rsa_failed; + return {}; + } + + std::unique_ptr params(OSSL_PARAM_BLD_to_param(param_bld.get()), + OSSL_PARAM_free); + if (!params) { + ec = error::rsa_error::set_rsa_failed; + return {}; + } + + std::unique_ptr ctx( + EVP_PKEY_CTX_new_from_name(nullptr, "RSA", nullptr), EVP_PKEY_CTX_free); + if (!ctx) { + ec = error::rsa_error::create_context_failed; + return {}; + } + + // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html#EXAMPLES + // Error codes based on https://www.openssl.org/docs/manmaster/man3/EVP_PKEY_fromdata_init.html#RETURN-VALUES + EVP_PKEY* pkey = NULL; + if (EVP_PKEY_fromdata_init(ctx.get()) <= 0 || + EVP_PKEY_fromdata(ctx.get(), &pkey, EVP_PKEY_KEYPAIR, params.get()) <= 0) { + // It's unclear if this can fail after allocating but free it anyways + // https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_fromdata.html + EVP_PKEY_free(pkey); + + ec = error::rsa_error::cert_load_failed; + return {}; + } + + // Transfer ownership so we get ref counter and cleanup + evp_pkey_handle rsa(pkey); + +#else + std::unique_ptr rsa(RSA_new(), RSA_free); + +#if defined(JWT_OPENSSL_1_1_1) || defined(JWT_OPENSSL_1_1_0) + // After this RSA_free will also free the n and e big numbers + // See https://github.com/Thalhammer/jwt-cpp/pull/298#discussion_r1282619186 + if (RSA_set0_key(rsa.get(), n.get(), e.get(), nullptr) == 1) { + // This can only fail we passed in NULL for `n` or `e` + // https://github.com/openssl/openssl/blob/d6e4056805f54bb1a0ef41fa3a6a35b70c94edba/crypto/rsa/rsa_lib.c#L396 + // So to make sure there is no memory leak, we hold the references + n.release(); + e.release(); + } else { + ec = error::rsa_error::set_rsa_failed; + return {}; + } +#elif defined(JWT_OPENSSL_1_0_0) + rsa->e = e.release(); + rsa->n = n.release(); + rsa->d = nullptr; +#endif +#endif + + auto pub_key_bio = make_mem_buf_bio(); + if (!pub_key_bio) { + ec = error::rsa_error::create_mem_bio_failed; + return {}; + } + + auto write_pem_to_bio = +#if defined(JWT_OPENSSL_3_0) + // https://www.openssl.org/docs/man3.1/man3/PEM_write_bio_RSA_PUBKEY.html + &PEM_write_bio_PUBKEY; +#else + &PEM_write_bio_RSA_PUBKEY; +#endif + if (write_pem_to_bio(pub_key_bio.get(), rsa.get()) != 1) { + ec = error::rsa_error::load_key_bio_write; + return {}; + } + + return write_bio_to_string(pub_key_bio, ec); + } + + /** + * Create public key from modulus and exponent. This is defined in + * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3) + * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter. + * + * \tparam Decode is callable, taking a string_type and returns a string_type. + * It should ensure the padding of the input and then base64url decode and + * return the results. + * \param modulus string containing base64url encoded modulus + * \param exponent string containing base64url encoded exponent + * \param decode The function to decode the RSA parameters + * \return public key in PEM format + */ + template + std::string create_public_key_from_rsa_components(const std::string& modulus, const std::string& exponent, + Decode decode) { + std::error_code ec; + auto res = create_public_key_from_rsa_components(modulus, exponent, decode, ec); + error::throw_if_error(ec); + return res; + } + +#ifndef JWT_DISABLE_BASE64 + /** + * Create public key from modulus and exponent. This is defined in + * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3) + * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter. + * + * \param modulus string containing base64 encoded modulus + * \param exponent string containing base64 encoded exponent + * \param ec error_code for error_detection (gets cleared if no error occur + * \return public key in PEM format + */ + inline std::string create_public_key_from_rsa_components(const std::string& modulus, + const std::string& exponent, std::error_code& ec) { + auto decode = [](const std::string& token) { + return base::decode(base::pad(token)); + }; + return create_public_key_from_rsa_components(modulus, exponent, std::move(decode), ec); + } + /** + * Create public key from modulus and exponent. This is defined in + * [RFC 7518 Section 6.3](https://www.rfc-editor.org/rfc/rfc7518#section-6.3) + * Using the required "n" (Modulus) Parameter and "e" (Exponent) Parameter. + * + * \param modulus string containing base64url encoded modulus + * \param exponent string containing base64url encoded exponent + * \return public key in PEM format + */ + inline std::string create_public_key_from_rsa_components(const std::string& modulus, + const std::string& exponent) { + std::error_code ec; + auto res = create_public_key_from_rsa_components(modulus, exponent, ec); + error::throw_if_error(ec); + return res; + } +#endif + /** * \brief Load a private key from a string. * @@ -852,35 +1076,6 @@ namespace jwt { error::throw_if_error(ec); return res; } - - /** - * Convert a OpenSSL BIGNUM to a std::string - * \param bn BIGNUM to convert - * \return bignum as string - */ - inline -#ifdef JWT_OPENSSL_1_0_0 - std::string - bn2raw(BIGNUM* bn) -#else - std::string - bn2raw(const BIGNUM* bn) -#endif - { - std::string res(BN_num_bytes(bn), '\0'); - BN_bn2bin(bn, (unsigned char*)res.data()); // NOLINT(google-readability-casting) requires `const_cast` - return res; - } - /** - * Convert an std::string to a OpenSSL BIGNUM - * \param raw String to convert - * \return BIGNUM representation - */ - inline std::unique_ptr raw2bn(const std::string& raw) { - return std::unique_ptr( - BN_bin2bn(reinterpret_cast(raw.data()), static_cast(raw.size()), nullptr), - BN_free); - } } // namespace helper /** @@ -979,7 +1174,7 @@ namespace jwt { std::string name() const { return alg_name; } private: - /// HMAC secrect + /// HMAC secret const std::string secret; /// HMAC hash generator const EVP_MD* (*md)(); @@ -1263,8 +1458,10 @@ namespace jwt { std::string p1363_to_der_signature(const std::string& signature, std::error_code& ec) const { ec.clear(); - auto r = helper::raw2bn(signature.substr(0, signature.size() / 2)); - auto s = helper::raw2bn(signature.substr(signature.size() / 2)); + auto r = helper::raw2bn(signature.substr(0, signature.size() / 2), ec); + if (ec) return {}; + auto s = helper::raw2bn(signature.substr(signature.size() / 2), ec); + if (ec) return {}; ECDSA_SIG* psig; #ifdef JWT_OPENSSL_1_0_0 @@ -2525,7 +2722,7 @@ namespace jwt { /** * \brief Parses a given token * - * \tparam Decode is callabled, taking a string_type and returns a string_type. + * \tparam Decode is callable, taking a string_type and returns a string_type. * It should ensure the padding of the input and then base64url decode and * return the results. * \param token The token to parse diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 2c39d9f..c41809f 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -49,7 +49,7 @@ add_executable(jwt-cpp-test ${TEST_SOURCES}) # NOTE: Don't use space inside a generator expression here, because the function prematurely breaks the expression into # multiple lines. https://cmake.org/pipermail/cmake/2018-April/067422.html -set(JWT_TESTER_GCC_FLAGS -Wall -Wextra -Wpedantic) +set(JWT_TESTER_GCC_FLAGS -Wall -Wextra -Wpedantic -ggdb) set(JWT_TESTER_CLANG_FLAGS -Weverything -Wno-c++98-compat -Wno-global-constructors -Wno-weak-vtables) target_compile_options( jwt-cpp-test PRIVATE $<$:/W4> $<$:${JWT_TESTER_GCC_FLAGS}> @@ -74,7 +74,7 @@ endif() target_link_libraries(jwt-cpp-test PRIVATE jwt-cpp nlohmann_json::nlohmann_json $<$>:${CMAKE_DL_LIBS}>) -gtest_add_tests(TARGET jwt-cpp-test) +gtest_discover_tests(jwt-cpp-test) if(JWT_ENABLE_COVERAGE) include("code-coverage") diff --git a/tests/HelperTest.cpp b/tests/HelperTest.cpp index a806988..17ea7e3 100644 --- a/tests/HelperTest.cpp +++ b/tests/HelperTest.cpp @@ -24,6 +24,27 @@ TEST(HelperTest, DER2PemCert) { ASSERT_EQ(google_cert, cert_pem); } +TEST(HelperTest, RsaFromComponents) { + const std::string public_key_expected = + R"(-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwoB3iVm4RW+6StkR+nut +x1fQevu2+t0Fu6KBcbvhfyHSXy7w0nJOdTT4jWLjStpRkNQBPZwMwHH35i+21gdn +JtDe/xfO8IX9McFmyodlBUcqX8CruIzDv9AXf2OjXPBG+4aq+03XKl5/muATl32+ ++301Vw1dXoGYNeoWQqLTsHT3WS3tOOf+ehuzNuZ+rj+ephaD3lMBToEArrtC9R91 +KTTN6YSAOK48NxTA8CfOMFK5itxfIqB5+E9OSQTidXyqLyoeA+xxTKMqYfxvypEe +k1oueAhY9u67NCBdmuavxtfyvwp7+o6Sd+NsewxAhmRKFexw13KOYzDhC+9aMJcu +JQIDAQAB +-----END PUBLIC KEY----- +)"; + const std::string modulus = + R"(AMKAd4lZuEVvukrZEfp7rcdX0Hr7tvrdBbuigXG74X8h0l8u8NJyTnU0-I1i40raUZDUAT2cDMBx9-YvttYHZybQ3v8XzvCF_THBZsqHZQVHKl_Aq7iMw7_QF39jo1zwRvuGqvtN1ypef5rgE5d9vvt9NVcNXV6BmDXqFkKi07B091kt7Tjn_nobszbmfq4_nqYWg95TAU6BAK67QvUfdSk0zemEgDiuPDcUwPAnzjBSuYrcXyKgefhPTkkE4nV8qi8qHgPscUyjKmH8b8qRHpNaLngIWPbuuzQgXZrmr8bX8r8Ke_qOknfjbHsMQIZkShXscNdyjmMw4QvvWjCXLiU)"; + const std::string exponent = R"(AQAB)"; + + const auto public_key = jwt::helper::create_public_key_from_rsa_components(modulus, exponent); + + ASSERT_EQ(public_key, public_key_expected); +} + TEST(HelperTest, ErrorCodeMessages) { ASSERT_EQ(std::error_code(jwt::error::rsa_error::ok).message(), "no error"); ASSERT_EQ(std::error_code(static_cast(-1)).message(), "unknown RSA error"); @@ -52,7 +73,7 @@ TEST(HelperTest, ErrorCodeMessages) { std::string("token_verification_error")); int i = 10; - for (i = 10; i < 19; i++) { + for (i = 10; i < 21; i++) { ASSERT_NE(std::error_code(static_cast(i)).message(), std::error_code(static_cast(-1)).message()); } diff --git a/tests/OpenSSLErrorTest.cpp b/tests/OpenSSLErrorTest.cpp index 00966da..b137a0d 100644 --- a/tests/OpenSSLErrorTest.cpp +++ b/tests/OpenSSLErrorTest.cpp @@ -22,6 +22,7 @@ static uint64_t fail_X509_get_pubkey = 0; static uint64_t fail_PEM_write_bio_PUBKEY = 0; static uint64_t fail_PEM_write_bio_cert = 0; static uint64_t fail_BIO_ctrl = 0; +#define fail_BIO_get_mem_data fail_BIO_ctrl static uint64_t fail_BIO_write = 0; static uint64_t fail_PEM_read_bio_PUBKEY = 0; static uint64_t fail_PEM_read_bio_PrivateKey = 0; @@ -50,6 +51,17 @@ static uint64_t fail_EVP_DigestSignFinal = 0; static uint64_t fail_EVP_DigestVerifyFinal = 0; static uint64_t fail_d2i_ECDSA_SIG = 0; static uint64_t fail_i2d_ECDSA_SIG = 0; +#ifdef JWT_OPENSSL_3_0 +static uint64_t fail_OSSL_PARAM_BLD_new = 0; +static uint64_t fail_OSSL_PARAM_BLD_push_BN = 0; +static uint64_t fail_OSSL_PARAM_BLD_to_param = 0; +static uint64_t fail_EVP_PKEY_CTX_new_from_name = 0; +static uint64_t fail_EVP_PKEY_fromdata_init = 0; +static uint64_t fail_EVP_PKEY_fromdata = 0; +#else +static uint64_t fail_PEM_write_bio_RSA_PUBKEY = 0; +static uint64_t fail_RSA_set0_key = 0; +#endif BIO* BIO_new(const BIO_METHOD* type) { static BIO* (*origMethod)(const BIO_METHOD*) = nullptr; @@ -408,6 +420,96 @@ ECDSA_SIG* d2i_ECDSA_SIG(ECDSA_SIG** psig, const unsigned char** ppin, long len) return origMethod(psig, ppin, len); } +#ifdef JWT_OPENSSL_3_0 +OSSL_PARAM_BLD* OSSL_PARAM_BLD_new() { + static OSSL_PARAM_BLD* (*origMethod)() = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "OSSL_PARAM_BLD_new"); + bool fail = fail_OSSL_PARAM_BLD_new & 1; + fail_OSSL_PARAM_BLD_new = fail_OSSL_PARAM_BLD_new >> 1; + if (fail) + return nullptr; + else + return origMethod(); +} + +int OSSL_PARAM_BLD_push_BN(OSSL_PARAM_BLD* bld, const char* key, const BIGNUM* bn) { + static int (*origMethod)(OSSL_PARAM_BLD * bld, const char* key, const BIGNUM* bn) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "OSSL_PARAM_BLD_push_BN"); + bool fail = fail_OSSL_PARAM_BLD_push_BN & 1; + fail_OSSL_PARAM_BLD_push_BN = fail_OSSL_PARAM_BLD_push_BN >> 1; + if (fail) + return 0; + else + return origMethod(bld, key, bn); +} + +OSSL_PARAM* OSSL_PARAM_BLD_to_param(OSSL_PARAM_BLD* bld) { + static OSSL_PARAM* (*origMethod)(OSSL_PARAM_BLD * bld) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "OSSL_PARAM_BLD_to_param"); + bool fail = fail_OSSL_PARAM_BLD_to_param & 1; + fail_OSSL_PARAM_BLD_to_param = fail_OSSL_PARAM_BLD_to_param >> 1; + if (fail) + return nullptr; + else + return origMethod(bld); +} + +EVP_PKEY_CTX* EVP_PKEY_CTX_new_from_name(OSSL_LIB_CTX* libctx, const char* name, const char* propquery) { + static EVP_PKEY_CTX* (*origMethod)(OSSL_LIB_CTX * libctx, const char* name, const char* propquery) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "EVP_PKEY_CTX_new_from_name"); + bool fail = fail_EVP_PKEY_CTX_new_from_name & 1; + fail_EVP_PKEY_CTX_new_from_name = fail_EVP_PKEY_CTX_new_from_name >> 1; + if (fail) + return nullptr; + else + return origMethod(libctx, name, propquery); +} + +int EVP_PKEY_fromdata_init(EVP_PKEY_CTX* ctx) { + static int (*origMethod)(EVP_PKEY_CTX * ctx) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "EVP_PKEY_fromdata_init"); + bool fail = fail_EVP_PKEY_fromdata_init & 1; + fail_EVP_PKEY_fromdata_init = fail_EVP_PKEY_fromdata_init >> 1; + if (fail) + return 0; + else + return origMethod(ctx); +} + +int EVP_PKEY_fromdata(EVP_PKEY_CTX* ctx, EVP_PKEY** ppkey, int selection, OSSL_PARAM params[]) { + static int (*origMethod)(EVP_PKEY_CTX * ctx, EVP_PKEY * *ppkey, int selection, OSSL_PARAM params[]) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "EVP_PKEY_fromdata"); + bool fail = fail_EVP_PKEY_fromdata & 1; + fail_EVP_PKEY_fromdata = fail_EVP_PKEY_fromdata >> 1; + if (fail) + return 0; + else + return origMethod(ctx, ppkey, selection, params); +} +#else +int PEM_write_bio_RSA_PUBKEY(BIO* bp, RSA* x) { + static int (*origMethod)(BIO * bp, RSA * x) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "PEM_write_bio_RSA_PUBKEY"); + bool fail = fail_PEM_write_bio_RSA_PUBKEY & 1; + fail_PEM_write_bio_RSA_PUBKEY = fail_PEM_write_bio_RSA_PUBKEY >> 1; + if (fail) + return 0; + else + return origMethod(bp, x); +} + +int RSA_set0_key(RSA* r, BIGNUM* n, BIGNUM* e, BIGNUM* d) { + static int (*origMethod)(RSA * r, BIGNUM * n, BIGNUM * e, BIGNUM * d) = nullptr; + if (origMethod == nullptr) origMethod = (decltype(origMethod))dlsym(RTLD_NEXT, "RSA_set0_key"); + bool fail = fail_RSA_set0_key & 1; + fail_RSA_set0_key = fail_RSA_set0_key >> 1; + if (fail) + return 0; + else + return origMethod(r, n, e, d); +} +#endif + /** * =========== End of black magic ============ */ @@ -516,6 +618,67 @@ TEST(OpenSSLErrorTest, ExtractPubkeyFromCertErrorCode) { }); } +TEST(OpenSSLErrorTest, CreateRsaPublicKeyFromComponents) { + std::vector mapping{ + {&fail_BIO_new, 1, jwt::error::rsa_error::create_mem_bio_failed}, + {&fail_BIO_get_mem_data, 1, jwt::error::rsa_error::convert_to_pem_failed}, +#ifdef JWT_OPENSSL_3_0 + {&fail_PEM_write_bio_PUBKEY, 1, jwt::error::rsa_error::load_key_bio_write}, + {&fail_OSSL_PARAM_BLD_new, 1, jwt::error::rsa_error::create_context_failed}, + {&fail_OSSL_PARAM_BLD_push_BN, 1, jwt::error::rsa_error::set_rsa_failed}, + {&fail_OSSL_PARAM_BLD_to_param, 1, jwt::error::rsa_error::set_rsa_failed}, + {&fail_EVP_PKEY_CTX_new_from_name, 1, jwt::error::rsa_error::create_context_failed}, + {&fail_EVP_PKEY_fromdata_init, 1, jwt::error::rsa_error::cert_load_failed}, + {&fail_EVP_PKEY_fromdata, 1, jwt::error::rsa_error::cert_load_failed} +#else + {&fail_PEM_write_bio_RSA_PUBKEY, 1, jwt::error::rsa_error::load_key_bio_write}, + {&fail_RSA_set0_key, 1, jwt::error::rsa_error::set_rsa_failed} +#endif + }; + + run_multitest(mapping, [](std::error_code& ec) { + try { + jwt::helper::create_public_key_from_rsa_components( + "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-" + "3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--" + "hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_" + "lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_" + "HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w", + "AQAB"); + FAIL(); // Should never reach this + } catch (const jwt::error::rsa_exception& e) { ec = e.code(); } + }); +} + +TEST(OpenSSLErrorTest, CreateRsaPublicKeyFromComponentsErrorCode) { + std::vector mapping{ + {&fail_BIO_new, 1, jwt::error::rsa_error::create_mem_bio_failed}, + {&fail_BIO_get_mem_data, 1, jwt::error::rsa_error::convert_to_pem_failed}, +#ifdef JWT_OPENSSL_3_0 + {&fail_PEM_write_bio_PUBKEY, 1, jwt::error::rsa_error::load_key_bio_write}, + {&fail_OSSL_PARAM_BLD_new, 1, jwt::error::rsa_error::create_context_failed}, + {&fail_OSSL_PARAM_BLD_push_BN, 1, jwt::error::rsa_error::set_rsa_failed}, + {&fail_OSSL_PARAM_BLD_to_param, 1, jwt::error::rsa_error::set_rsa_failed}, + {&fail_EVP_PKEY_CTX_new_from_name, 1, jwt::error::rsa_error::create_context_failed}, + {&fail_EVP_PKEY_fromdata_init, 1, jwt::error::rsa_error::cert_load_failed}, + {&fail_EVP_PKEY_fromdata, 1, jwt::error::rsa_error::cert_load_failed} +#else + {&fail_PEM_write_bio_RSA_PUBKEY, 1, jwt::error::rsa_error::load_key_bio_write}, + {&fail_RSA_set0_key, 1, jwt::error::rsa_error::set_rsa_failed} +#endif + }; + + run_multitest(mapping, [](std::error_code& ec) { + auto res = jwt::helper::create_public_key_from_rsa_components( + "pjdss8ZaDfEH6K6U7GeW2nxDqR4IP049fk1fK0lndimbMMVBdPv_hSpm8T8EtBDxrUdi1OHZfMhUixGaut-" + "3nQ4GG9nM249oxhCtxqqNvEXrmQRGqczyLxuh-fKn9Fg--hS9UpazHpfVAFnB5aCfXoNhPuI8oByyFKMKaOVgHNqP5NBEqabiLftZD3W_" + "lsFCPGuzr4Vp0YS7zS2hDYScC2oOMu4rGU1LcMZf39p3153Cq7bS2Xh6Y-vw5pwzFYZdjQxDn8x8BG3fJ6j8TGLXQsbKH1218_" + "HcUJRvMwdpbUQG5nvA2GXVqLqdwp054Lzk9_B_f1lVrmOKuHjTNHq48w", + "AQAB", ec); + ASSERT_EQ(res, ""); + }); +} + TEST(OpenSSLErrorTest, ConvertCertBase64DerToPem) { std::vector mapping{{&fail_BIO_new, 1, jwt::error::rsa_error::create_mem_bio_failed}, {&fail_PEM_write_bio_cert, 1, jwt::error::rsa_error::write_cert_failed}, @@ -613,6 +776,7 @@ TEST(OpenSSLErrorTest, LoadPublicKeyCertFromStringReference) { TEST(OpenSSLErrorTest, LoadPublicKeyCertFromString) { std::vector mapping { {&fail_BIO_new, 1, jwt::error::rsa_error::create_mem_bio_failed}, + {&fail_BIO_get_mem_data, 1, jwt::error::rsa_error::convert_to_pem_failed}, #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER < 0x3050300fL {&fail_BIO_write, 1, jwt::error::rsa_error::load_key_bio_write}, #else @@ -634,6 +798,7 @@ TEST(OpenSSLErrorTest, LoadPublicKeyCertFromString) { TEST(OpenSSLErrorTest, LoadPublicKeyCertFromStringErrorCode) { std::vector mapping { {&fail_BIO_new, 1, jwt::error::rsa_error::create_mem_bio_failed}, + {&fail_BIO_get_mem_data, 1, jwt::error::rsa_error::convert_to_pem_failed}, // extract_pubkey_from_cert #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER < 0x3050300fL {&fail_BIO_write, 1, jwt::error::rsa_error::load_key_bio_write}, #else diff --git a/tests/TokenTest.cpp b/tests/TokenTest.cpp index a64e0d1..53574a6 100644 --- a/tests/TokenTest.cpp +++ b/tests/TokenTest.cpp @@ -728,7 +728,7 @@ TEST(TokenTest, VerifyTokenType) { } TEST(TokenTest, GetClaimThrows) { - auto token = "eyJhbGciOiJub25lIiwidHlwIjoiSldTIn0.eyJpc3MiOiJhdXRoMCJ9."; + const std::string token = "eyJhbGciOiJub25lIiwidHlwIjoiSldTIn0.eyJpc3MiOiJhdXRoMCJ9."; auto decoded_token = jwt::decode(token); ASSERT_THROW(decoded_token.get_header_claim("test"), jwt::error::claim_not_present_exception); @@ -775,8 +775,8 @@ TEST(TokenTest, ThrowInvalidKeyLength) { } TEST(TokenTest, MoveDecodedToken) { - std::string token0 = "eyJhbGciOiJub25lIiwidHlwIjoiSldTIn0.eyJpc3MiOiJhdXRoMCJ9."; - std::string token1 = + const std::string token0 = "eyJhbGciOiJub25lIiwidHlwIjoiSldTIn0.eyJpc3MiOiJhdXRoMCJ9."; + const std::string token1 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE"; auto decoded_token0 = jwt::decode(token0); auto decoded_token1 = jwt::decode(token1);