diff --git a/.github/workflows/3.2.0_cpp17_ci.yml b/.github/workflows/3.2.0_cpp17_ci.yml new file mode 100644 index 00000000000..c6285ef91b8 --- /dev/null +++ b/.github/workflows/3.2.0_cpp17_ci.yml @@ -0,0 +1,292 @@ + +# (C) 2020,2022 Jack Lloyd +# (C) 2022 René Meusel, Rohde & Schwarz Cybersecurity +# (C) 2023 Piotr Staniszewski, CodeVision +# +# Botan is released under the Simplified BSD License (see license.txt) + +name: 3.2.0_cpp17_ci + +permissions: + contents: read + # implicitly all other scopes not listed become none + +on: + push: + branches: [ 3.2.0_cpp17 ] + pull_request: + branches: [ 3.2.0_cpp17 ] + +# cancel running workflows when new commits are being pushed in pull requests +# but not on the master branch +concurrency: + group: ${{ github.workflow }} @ ${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + windows: + name: "Windows" + strategy: + fail-fast: false + + matrix: + include: + - target: shared + arch: x86_64 + host_os: windows-2022 + - target: static + arch: x86_64 + host_os: windows-2022 + - target: amalgamation + arch: x86_64 + host_os: windows-2022 + - target: shared + arch: x86 + host_os: windows-2022 + + runs-on: ${{ matrix.host_os }} + + steps: + - uses: actions/checkout@v3 + + - name: Setup Build Agent + uses: ./.github/actions/setup-build-agent + with: + target: ${{ matrix.target }} + cache-key: ${{ matrix.host_os }}-msvc-${{ matrix.arch }}-${{ matrix.target }} + arch: ${{ matrix.arch }} + + - name: Build and Test Botan + run: python3 ./src/scripts/ci_build.py --cc='msvc' --make-tool='ninja' --cpu='${{ matrix.arch }}' --test-results-dir=junit_results ${{ matrix.target }} + + linux: + name: "Linux" + strategy: + fail-fast: false + + matrix: + include: + - compiler: gcc + target: shared + - compiler: gcc + target: amalgamation + - compiler: gcc + target: static + - compiler: clang + target: shared + + runs-on: ubuntu-22.04 + + steps: + - uses: actions/checkout@v3 + + - name: Setup Build Agent + uses: ./.github/actions/setup-build-agent + with: + target: ${{ matrix.target }} + cache-key: linux-${{ matrix.compiler }}-x86_64-${{ matrix.target }} + + - name: Build and Test Botan + run: python3 ./src/scripts/ci_build.py --cc='${{ matrix.compiler }}' --test-results-dir=junit_results ${{ matrix.target }} + + macos: + name: "macOS" + strategy: + fail-fast: false + + matrix: + include: + - target: shared + compiler: clang + - target: amalgamation + compiler: clang + + runs-on: macos-13 + + steps: + - uses: actions/checkout@v3 + + - name: Setup Build Agent + uses: ./.github/actions/setup-build-agent + with: + target: ${{ matrix.target }} + cache-key: macos-${{ matrix.compiler }}-x86_64-${{ matrix.target }} + + - name: Build and Test Botan + run: python3 ./src/scripts/ci_build.py --cc='${{ matrix.compiler }}' --test-results-dir=junit_results ${{ matrix.target }} + + # clang-tidy: + # name: "Clang Tidy" + # runs-on: ubuntu-22.04 + # steps: + # - uses: actions/checkout@v3 + + # - name: Setup Build Agent + # uses: ./.github/actions/setup-build-agent + # with: + # target: clang-tidy + # cache-key: linux-x86_64-clang-tidy + + # - name: Configure Build + # run: python3 ./configure.py --cc=clang + + # - name: Run Clang Tidy + # run: | + # ./src/scripts/ci/gh_get_changes_in_pr.py $(git rev-parse HEAD) --api-token=${{ secrets.GITHUB_TOKEN }} | \ + # python3 ./src/scripts/dev_tools/run_clang_tidy.py --verbose --take-file-list-from-stdin --export-fixes-dir=clang_tidy_diagnostics + + # - name: Display Clang Tidy Results + # if: failure() + # run: ./src/scripts/ci/gh_clang_tidy_fixes_in_pr.py clang_tidy_diagnostics + + analysis: + name: "Analysis" + strategy: + fail-fast: false + + matrix: + include: + - target: coverage + compiler: gcc + host_os: ubuntu-22.04 + - target: sanitizer + compiler: msvc + host_os: windows-2022 + make_tool: ninja + - target: sanitizer + compiler: clang + host_os: ubuntu-22.04 + - target: sanitizer + compiler: gcc + host_os: ubuntu-22.04 + - target: valgrind + compiler: gcc + host_os: ubuntu-22.04 + - target: fuzzers + compiler: gcc + host_os: ubuntu-22.04 + - target: lint + compiler: gcc + host_os: ubuntu-22.04 + # - target: format + # compiler: gcc + # host_os: ubuntu-22.04 + + runs-on: ${{ matrix.host_os }} + + env: + COVERALLS_REPO_TOKEN: pbLoTMBxC1DFvbws9WfrzVOvfEdEZTcCS + + steps: + - uses: actions/checkout@v3 + with: + path: ./source + + - name: Fetch BoringSSL fork for BoGo tests + uses: actions/checkout@v3 + with: + repository: randombit/boringssl + ref: rene/runner-20230705 + path: ./boringssl + if: matrix.target == 'coverage' || matrix.target == 'sanitizer' + + - name: Setup Build Agent + uses: ./source/.github/actions/setup-build-agent + with: + target: ${{ matrix.target }} + cache-key: ${{ matrix.host_os }}-${{ matrix.compiler }}-x86_64-${{ matrix.target }} + + - name: Build and Test Botan + run: python3 ./source/src/scripts/ci_build.py --root-dir=${{ github.workspace }}/source --build-dir=${{ github.workspace }}/build --boringssl-dir=${{ github.workspace }}/boringssl --cc='${{ matrix.compiler }}' --make-tool='${{ matrix.make_tool }}' --test-results-dir=junit_results ${{ matrix.target }} + + specials: + name: "Special" + strategy: + fail-fast: false + + matrix: + include: + - target: examples + compiler: gcc + host_os: ubuntu-22.04 + - target: minimized + compiler: gcc + host_os: ubuntu-22.04 + - target: bsi + compiler: gcc + host_os: ubuntu-22.04 + + runs-on: ${{ matrix.host_os }} + + steps: + - uses: actions/checkout@v3 + with: + path: ./source + + - name: Setup Build Agent + uses: ./source/.github/actions/setup-build-agent + with: + target: ${{ matrix.target }} + cache-key: ${{ matrix.host_os }}-${{ matrix.compiler }}-x86_64-${{ matrix.target }} + + - name: Build and Test Botan + run: python3 ./source/src/scripts/ci_build.py --root-dir=${{ github.workspace }}/source --build-dir=${{ github.workspace }}/build --boringssl-dir=${{ github.workspace }}/boringssl --cc='${{ matrix.compiler }}' --make-tool='${{ matrix.make_tool }}' --test-results-dir=junit_results ${{ matrix.target }} + + x-compile: + name: "Cross" + strategy: + fail-fast: false + + matrix: + include: + - target: cross-i386 + compiler: gcc + host_os: ubuntu-22.04 + - target: cross-arm32 + compiler: gcc + host_os: ubuntu-22.04 + - target: cross-arm64 + compiler: gcc + host_os: ubuntu-22.04 + - target: cross-ppc64 + compiler: gcc + host_os: ubuntu-22.04 + - target: cross-riscv64 + compiler: gcc + host_os: ubuntu-22.04 + - target: cross-s390x + compiler: gcc + host_os: ubuntu-22.04 + - target: cross-android-arm32 + compiler: clang + host_os: ubuntu-22.04 + - target: cross-android-arm64 + compiler: clang + host_os: ubuntu-22.04 + - target: static + compiler: gcc + host_os: windows-2022 + make_tool: mingw32-make + - target: cross-ios-arm64 + compiler: clang + host_os: macos-13 + - target: emscripten + compiler: emcc + host_os: macos-13 + + runs-on: ${{ matrix.host_os }} + + env: + ANDROID_NDK: android-ndk-r26 + + steps: + - uses: actions/checkout@v3 + + - name: Setup Build Agent + uses: ./.github/actions/setup-build-agent + with: + target: ${{ matrix.target }} + cache-key: ${{ matrix.host_os }}-${{ matrix.compiler }}-xcompile-${{ matrix.target }} + + - name: Build and Test Botan + run: python3 ./src/scripts/ci_build.py --cc='${{ matrix.compiler }}' --test-results-dir=junit_results ${{ matrix.target }} diff --git a/doc/api_ref/kdf.rst b/doc/api_ref/kdf.rst index 71cb49760f6..2ce3c399859 100644 --- a/doc/api_ref/kdf.rst +++ b/doc/api_ref/kdf.rst @@ -36,9 +36,9 @@ two contexts. .. cpp:function:: template> \ T derive_key(size_t key_len, \ - std::span secret, \ - std::span salt, \ - std::span label) const + Botan::span secret, \ + Botan::span salt, \ + Botan::span label) const This version is parameterized to the output buffer type, so it can be used to return a ``std::vector``, a ``secure_vector``, or anything else diff --git a/doc/api_ref/pbkdf.rst b/doc/api_ref/pbkdf.rst index ae545b96299..b6bc6dfed17 100644 --- a/doc/api_ref/pbkdf.rst +++ b/doc/api_ref/pbkdf.rst @@ -22,17 +22,17 @@ specified with all parameters (say "Scrypt" with ``N`` = 8192, ``r`` = 64, and .. cpp:class:: PasswordHash - .. cpp:function:: void hash(std::span out, \ + .. cpp:function:: void hash(Botan::span out, \ std::string_view password, \ - std::span salt) + Botan::span salt) Derive a key from the specified *password* and *salt*, placing it into *out*. - .. cpp:function:: void hash(std::span out, \ + .. cpp:function:: void hash(Botan::span out, \ std::string_view password, \ - std::span salt, \ - std::span ad, \ - std::span key) + Botan::span salt, \ + Botan::span ad, \ + Botan::span key) Derive a key from the specified *password*, *salt*, associated data (*ad*), and secret *key*, placing it into *out*. The *ad* and *key* are both allowed diff --git a/doc/api_ref/pubkey.rst b/doc/api_ref/pubkey.rst index 2369d0d295c..11ae59790e7 100644 --- a/doc/api_ref/pubkey.rst +++ b/doc/api_ref/pubkey.rst @@ -473,7 +473,7 @@ The primary interface for encryption is const uint8_t in[], size_t length, RandomNumberGenerator& rng) const .. cpp:function:: std::vector encrypt( \ - std::span in, RandomNumberGenerator& rng) const + Botan::span in, RandomNumberGenerator& rng) const These encrypt a message, returning the ciphertext. @@ -634,7 +634,7 @@ Signature generation is performed using value. This formatting is used in protocols such as TLS and Bitcoin. .. cpp:function:: void update(const uint8_t* in, size_t length) - .. cpp:function:: void update(std::span in) + .. cpp:function:: void update(Botan::span in) .. cpp:function:: void update(uint8_t in) These add more data to be included in the signature computation. Typically, the @@ -649,7 +649,7 @@ Signature generation is performed using const uint8_t* in, size_t length, RandomNumberGenerator& rng) .. cpp:function:: std::vector sign_message( \ - std::span in, RandomNumberGenerator& rng) + Botan::span in, RandomNumberGenerator& rng) These functions are equivalent to calling :cpp:func:`PK_Signer::update` and then :cpp:func:`PK_Signer::signature`. Any data previously provided using ``update`` will @@ -679,14 +679,14 @@ Signatures are verified using *padding* and *format* should be the same as that used by the signer. .. cpp:function:: void update(const uint8_t* in, size_t length) - .. cpp:function:: void update(std::span in) + .. cpp:function:: void update(Botan::span in) .. cpp:function:: void update(uint8_t in) Add further message data that is purportedly associated with the signature that will be checked. .. cpp:function:: bool check_signature(const uint8_t* sig, size_t length) - .. cpp:function:: bool check_signature(std::span sig) + .. cpp:function:: bool check_signature(Botan::span sig) Check to see if *sig* is a valid signature for the message data that was written in. Return true if so. This function clears the internal message state, so after @@ -696,8 +696,8 @@ Signatures are verified using .. cpp:function:: bool verify_message(const uint8_t* msg, size_t msg_length, \ const uint8_t* sig, size_t sig_length) - .. cpp:function:: bool verify_message(std::span msg, \ - std::span sig) + .. cpp:function:: bool verify_message(Botan::span msg, \ + Botan::span sig) These are equivalent to calling :cpp:func:`PK_Verifier::update` on *msg* and then calling :cpp:func:`PK_Verifier::check_signature` on *sig*. Any data previously @@ -792,7 +792,7 @@ produce an output of the desired length. size_t params_len) const .. cpp:function:: SymmetricKey derive_key(size_t key_len, \ - std::span in, \ + Botan::span in, \ const uint8_t params[], size_t params_len) const .. cpp:function:: SymmetricKey derive_key(size_t key_len, \ @@ -800,7 +800,7 @@ produce an output of the desired length. const std::string& params = "") const .. cpp:function:: SymmetricKey derive_key(size_t key_len, \ - const std::span in, \ + const Botan::span in, \ const std::string& params = "") const Return a shared key. The *params* will be hashed along with the shared secret by the @@ -845,16 +845,16 @@ encapsulated key and returns the shared secret. .. cpp:function:: KEM_Encapsulation encrypt(RandomNumberGenerator& rng, \ size_t desired_shared_key_len = 32, \ - std::span salt = {}) + Botan::span salt = {}) Perform a key encapsulation operation with the result being returned as a convenient struct. - .. cpp:function:: void encrypt(std::span out_encapsulated_key, \ - std::span out_shared_key, \ + .. cpp:function:: void encrypt(Botan::span out_encapsulated_key, \ + Botan::span out_shared_key, \ RandomNumberGenerator& rng, \ size_t desired_shared_key_len = 32, \ - std::span salt = {}) + Botan::span salt = {}) Perform a key encapsulation operation by passing in out-buffers of the correct output length. Use encapsulated_key_length() and @@ -864,7 +864,7 @@ encapsulated key and returns the shared secret. secure_vector& out_shared_key, \ size_t desired_shared_key_len, \ RandomNumberGenerator& rng, \ - std::span salt) + Botan::span salt) Perform a key encapsulation operation by passing in out-vectors that will be re-allocated to the correct output size. @@ -891,16 +891,16 @@ encapsulated key and returns the shared secret. Size in bytes of the shared key being produced by this PK_KEM_Encryptor. - .. cpp:function:: secure_vector decrypt(std::span encapsulated_key, \ + .. cpp:function:: secure_vector decrypt(Botan::span encapsulated_key, \ size_t desired_shared_key_len, \ - std::span salt) + Botan::span salt) Perform a key decapsulation operation - .. cpp:function:: void decrypt(std::span out_shared_key, \ - std::span encap_key, \ + .. cpp:function:: void decrypt(Botan::span out_shared_key, \ + Botan::span encap_key, \ size_t desired_shared_key_len = 32, \ - std::span salt = {}) + Botan::span salt = {}) Perform a key decapsulation operation by passing in a pre-allocated out-buffer. Use shared_key_length() to determine the byte-length required. diff --git a/doc/api_ref/tls.rst b/doc/api_ref/tls.rst index 1c47fc338ff..0841285daa0 100644 --- a/doc/api_ref/tls.rst +++ b/doc/api_ref/tls.rst @@ -37,7 +37,7 @@ following members. The first three (``tls_emit_data``, ``tls_record_received``, ``tls_alert``) are mandatory for using TLS, all others are optional and provide additional information about the connection. - .. cpp:function:: void tls_emit_data(std::span data) + .. cpp:function:: void tls_emit_data(Botan::span data) Mandatory. The TLS stack requests that all bytes of *data* be queued up to send to the counterparty. After this function returns, the buffer containing *data* will @@ -51,7 +51,7 @@ additional information about the connection. For TLS all writes must occur *in the order requested*. For DTLS this ordering is not strictly required, but is still recommended. - .. cpp:function:: void tls_record_received(uint64_t rec_no, std::span data) + .. cpp:function:: void tls_record_received(uint64_t rec_no, Botan::span data) Mandatory. Called once for each application_data record which is received, with the matching (TLS level) record sequence number. @@ -212,7 +212,7 @@ available: .. cpp:class:: TLS::Channel .. cpp:function:: size_t received_data(const uint8_t buf[], size_t buf_size) - .. cpp:function:: size_t received_data(std::span buf) + .. cpp:function:: size_t received_data(Botan::span buf) This function is used to provide data sent by the counterparty (eg data that you read off the socket layer). Depending on the @@ -227,7 +227,7 @@ available: .. cpp:function:: void send(const uint8_t buf[], size_t buf_size) .. cpp:function:: void send(std::string_view str) - .. cpp:function:: void send(std::span vec) + .. cpp:function:: void send(Botan::span vec) Create one or more new TLS application records containing the provided data and send them. This will eventually result in at @@ -792,12 +792,12 @@ policy settings from a file. The default ordering puts the best performing ECC first. Default: - Group_Params::X25519, - Group_Params::SECP256R1, Group_Params::BRAINPOOL256R1, - Group_Params::SECP384R1, Group_Params::BRAINPOOL384R1, - Group_Params::SECP521R1, Group_Params::BRAINPOOL512R1, - Group_Params::FFDHE_2048, Group_Params::FFDHE_3072, Group_Params::FFDHE_4096, - Group_Params::FFDHE_6144, Group_Params::FFDHE_8192 + Group_Params_Code::X25519, + Group_Params_Code::SECP256R1, Group_Params_Code::BRAINPOOL256R1, + Group_Params_Code::SECP384R1, Group_Params_Code::BRAINPOOL384R1, + Group_Params_Code::SECP521R1, Group_Params_Code::BRAINPOOL512R1, + Group_Params_Code::FFDHE_2048, Group_Params_Code::FFDHE_3072, Group_Params_Code::FFDHE_4096, + Group_Params_Code::FFDHE_6144, Group_Params_Code::FFDHE_8192 No other values are currently defined. diff --git a/doc/migration_guide.rst b/doc/migration_guide.rst index 48dca75066a..ab0c5eb0440 100644 --- a/doc/migration_guide.rst +++ b/doc/migration_guide.rst @@ -79,7 +79,7 @@ applications: tls_record_received() / tls_emit_data() """"""""""""""""""""""""""""""""""""""" -Those callbacks now take `std::span` instead of `const uint8_t*` +Those callbacks now take `Botan::span` instead of `const uint8_t*` with a `size_t` buffer length. tls_session_established() diff --git a/news.rst b/news.rst index 586176eaccd..401d7b21831 100644 --- a/news.rst +++ b/news.rst @@ -1,6 +1,12 @@ Release Notes ======================================== +Version 3.2.0 for C++17, 2023-12-07 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +* Version 3.2.0 backported to C++17 to be used with older compilers. + Compiler requirements have been decreased to GCC 9, Clang 5, or MSVC 2017. + Version 3.2.0, 2023-10-09 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -61,7 +67,7 @@ Version 3.2.0, 2023-10-09 * On MinGW the global thread pool is disabled by default (GH #3726 #2582) -* Various internal functions now use ``std::span`` instead of raw pointers +* Various internal functions now use ``Botan::span`` instead of raw pointers plus length field. NOTE: any implementations of ``BlockCipher``, ``HashFunction`` etc that live outside the library will have to be updated. This is not covered by the SemVer guarantee; see ``doc/sem_ver.rst`` (GH #3684 #3681 #3713 #3714 diff --git a/src/bogo_shim/bogo_shim.cpp b/src/bogo_shim/bogo_shim.cpp index f233b37d9b6..63605d4702f 100644 --- a/src/bogo_shim/bogo_shim.cpp +++ b/src/bogo_shim/bogo_shim.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include @@ -518,24 +519,24 @@ class Shim_Arguments final { void parse_args(char* argv[]); bool flag_set(const std::string& flag) const { - if(!m_flags.contains(flag)) { + if(!Botan::contains(m_flags, flag)) { throw Shim_Exception("Unknown bool flag " + flag); } - return m_parsed_flags.contains(flag); + return Botan::contains(m_parsed_flags, flag); } std::string test_name() const { return get_string_opt("test-name"); } std::string get_string_opt(const std::string& key) const { - if(!m_string_opts.contains(key)) { + if(!Botan::contains(m_string_opts, key)) { throw Shim_Exception("Unknown string key " + key); } return get_opt(key); } std::string get_string_opt_or_else(const std::string& key, const std::string& def) const { - if(!m_string_opts.contains(key)) { + if(!Botan::contains(m_string_opts, key)) { throw Shim_Exception("Unknown string key " + key); } if(!option_used(key)) { @@ -545,21 +546,21 @@ class Shim_Arguments final { } std::vector get_b64_opt(const std::string& key) const { - if(!m_base64_opts.contains(key)) { + if(!Botan::contains(m_base64_opts, key)) { throw Shim_Exception("Unknown base64 key " + key); } return Botan::unlock(Botan::base64_decode(get_opt(key))); } size_t get_int_opt(const std::string& key) const { - if(!m_int_opts.contains(key)) { + if(!Botan::contains(m_int_opts, key)) { throw Shim_Exception("Unknown int key " + key); } return Botan::to_u32bit(get_opt(key)); } size_t get_int_opt_or_else(const std::string& key, size_t def) const { - if(!m_int_opts.contains(key)) { + if(!Botan::contains(m_int_opts, key)) { throw Shim_Exception("Unknown int key " + key); } if(!option_used(key)) { @@ -570,7 +571,7 @@ class Shim_Arguments final { } std::vector get_int_vec_opt(const std::string& key) const { - if(!m_int_vec_opts.contains(key)) { + if(!Botan::contains(m_int_vec_opts, key)) { throw Shim_Exception("Unknown int vec key " + key); } @@ -594,7 +595,7 @@ class Shim_Arguments final { } bool option_used(const std::string& key) const { - if(!m_all_options.contains(key)) { + if(!Botan::contains(m_all_options, key)) { throw Shim_Exception("Invalid option " + key); } if(m_parsed_opts.find(key) != m_parsed_opts.end()) { @@ -636,18 +637,18 @@ void Shim_Arguments::parse_args(char* argv[]) { if(param.find('-') == 0) { const std::string flag_name = param.substr(1, std::string::npos); - if(m_flags.contains(flag_name)) { + if(Botan::contains(m_flags, flag_name)) { shim_log("flag " + flag_name); m_parsed_flags.insert(flag_name); i += 1; - } else if(m_all_options.contains(flag_name)) { + } else if(Botan::contains(m_all_options, flag_name)) { if(argv[i + 1] == nullptr) { throw Shim_Exception("Expected argument following " + param); } std::string val(argv[i + 1]); shim_log(Botan::fmt("param {}={}", flag_name, val)); - if(m_int_vec_opts.contains(flag_name)) { + if(Botan::contains(m_int_vec_opts, flag_name)) { const size_t v = Botan::to_u32bit(val); m_parsed_int_vec_opts[flag_name].push_back(v); } else { @@ -991,7 +992,7 @@ class Shim_Policy final : public Botan::TLS::Policy { // // TODO: once `TLS::Policy::key_exchange_groups()` contains it by // default, remove this explicit check. - if(group == Botan::TLS::Group_Params::HYBRID_X25519_KYBER_768_R3_OQS) { + if(group == Botan::TLS::Group_Params_Code::HYBRID_X25519_KYBER_768_R3_OQS) { groups.push_back(group); } } @@ -1018,7 +1019,7 @@ class Shim_Policy final : public Botan::TLS::Policy { } } - return Botan::TLS::Group_Params::NONE; + return Botan::TLS::Group_Params_Code::NONE; } bool require_client_certificate_authentication() const override { @@ -1078,17 +1079,17 @@ class Shim_Policy final : public Botan::TLS::Policy { bool allow_tls12() const override { return !m_args.flag_set("dtls") && !m_args.flag_set("no-tls12") && - allow_version(Botan::TLS::Protocol_Version::TLS_V12); + allow_version(Botan::TLS::Version_Code::TLS_V12); } bool allow_tls13() const override { return !m_args.flag_set("dtls") && !m_args.flag_set("no-tls13") && - allow_version(Botan::TLS::Protocol_Version::TLS_V13); + allow_version(Botan::TLS::Version_Code::TLS_V13); } bool allow_dtls12() const override { return m_args.flag_set("dtls") && !m_args.flag_set("no-tls12") && - allow_version(Botan::TLS::Protocol_Version::DTLS_V12); + allow_version(Botan::TLS::Version_Code::DTLS_V12); } //Botan::TLS::Group_Params default_dh_group() const override; @@ -1390,7 +1391,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { bool saw_close_notify() const { return m_got_close; } - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { shim_log("sending record of len " + std::to_string(data.size())); if(m_args.option_used("write-settings")) { @@ -1430,7 +1431,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { return {}; } - void tls_record_received(uint64_t /*seq_no*/, std::span data) override { + void tls_record_received(uint64_t /*seq_no*/, Botan::span data) override { if(data.empty()) { m_empty_records += 1; if(m_empty_records > 32) { @@ -1481,14 +1482,14 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { const Botan::TLS::Policy& /*policy*/) override { if(m_args.flag_set("enable-ocsp-stapling") && m_args.flag_set("use-ocsp-callback") && m_args.flag_set("fail-ocsp-callback")) { - throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::BadCertificateStatusResponse, + throw Botan::TLS::TLS_Exception(Botan::TLS::AlertType::BadCertificateStatusResponse, "Simulated OCSP callback failure"); } if(m_args.flag_set("verify-fail")) { - auto alert = Botan::TLS::Alert::HandshakeFailure; + auto alert = Botan::TLS::AlertType::HandshakeFailure; if(m_args.flag_set("use-custom-verify-callback")) { - alert = Botan::TLS::Alert::CertificateUnknown; + alert = Botan::TLS::AlertType::CertificateUnknown; } throw Botan::TLS::TLS_Exception(alert, "Test requires rejecting cert"); @@ -1511,7 +1512,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { } if(m_args.flag_set("reject-alpn")) { - throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::NoApplicationProtocol, + throw Botan::TLS::TLS_Exception(Botan::TLS::AlertType::NoApplicationProtocol, "Rejecting ALPN request with alert"); } @@ -1541,11 +1542,11 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { shim_log("Got a warning alert " + alert.type_string()); } - if(alert.type() == Botan::TLS::Alert::RecordOverflow) { + if(alert.type() == Botan::TLS::AlertType::RecordOverflow) { shim_exit_with_error(":TLSV1_ALERT_RECORD_OVERFLOW:"); } - if(alert.type() == Botan::TLS::Alert::DecompressionFailure) { + if(alert.type() == Botan::TLS::AlertType::DecompressionFailure) { shim_exit_with_error(":SSLV3_ALERT_DECOMPRESSION_FAILURE:"); } @@ -1556,7 +1557,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { } } - if(alert.type() == Botan::TLS::Alert::CloseNotify) { + if(alert.type() == Botan::TLS::AlertType::CloseNotify) { if(m_got_close == false && !m_args.flag_set("shim-shuts-down")) { shim_log("Sending return close notify"); m_channel->send_alert(alert); @@ -1610,7 +1611,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { void tls_session_activated() override { if(m_args.flag_set("send-alert")) { - m_channel->send_fatal_alert(Botan::TLS::Alert::DecompressionFailure); + m_channel->send_fatal_alert(Botan::TLS::AlertType::DecompressionFailure); return; } @@ -1631,7 +1632,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { } if(alpn == "baz" && !m_args.flag_set("allow-unknown-alpn-protos")) { - throw Botan::TLS::TLS_Exception(Botan::TLS::Alert::IllegalParameter, "Unexpected ALPN protocol"); + throw Botan::TLS::TLS_Exception(Botan::TLS::AlertType::IllegalParameter, "Unexpected ALPN protocol"); } if(m_args.flag_set("shim-shuts-down")) { diff --git a/src/build-data/cc/clang.txt b/src/build-data/cc/clang.txt index 7b4bc3b0bb0..1b4aa35e3db 100644 --- a/src/build-data/cc/clang.txt +++ b/src/build-data/cc/clang.txt @@ -2,9 +2,9 @@ macro_name CLANG binary_name clang++ -minimum_supported_version 14.0 +minimum_supported_version 5 -lang_flags "-std=c++20 -D_REENTRANT" +lang_flags "-std=c++17 -D_REENTRANT" warning_flags "-Wall -Wextra -Wpedantic -Wshadow -Wstrict-aliasing -Wstrict-overflow=5 -Wcast-align -Wmissing-declarations -Wpointer-arith -Wcast-qual -Wshorten-64-to-32 -Wcomma -Wdocumentation" diff --git a/src/build-data/cc/emcc.txt b/src/build-data/cc/emcc.txt index ce7dc320581..1768a2bbfba 100644 --- a/src/build-data/cc/emcc.txt +++ b/src/build-data/cc/emcc.txt @@ -2,7 +2,7 @@ macro_name CLANG binary_name em++ -lang_flags "-s DISABLE_EXCEPTION_CATCHING=0 -std=c++20 -D_REENTRANT" +lang_flags "-s DISABLE_EXCEPTION_CATCHING=0 -std=c++17 -D_REENTRANT" lang_binary_linker_flags "-s ALLOW_MEMORY_GROWTH=1 -s WASM=1 -s NO_DISABLE_EXCEPTION_CATCHING" warning_flags "-Wall -Wextra -Wpedantic -Wshadow -Wstrict-aliasing -Wstrict-overflow=5 -Wcast-align -Wmissing-declarations -Wpointer-arith -Wcast-qual -Wshorten-64-to-32" diff --git a/src/build-data/cc/gcc.txt b/src/build-data/cc/gcc.txt index cebf3a18a8e..f8394dbf610 100644 --- a/src/build-data/cc/gcc.txt +++ b/src/build-data/cc/gcc.txt @@ -2,9 +2,9 @@ macro_name GCC binary_name g++ -minimum_supported_version 11.0 +minimum_supported_version 9.0 -lang_flags "-std=c++20 -D_REENTRANT" +lang_flags "-std=c++17 -D_REENTRANT" # This should only contain flags which are included in GCC 11 warning_flags "-Wall -Wextra -Wpedantic -Wstrict-aliasing -Wcast-align -Wmissing-declarations -Wpointer-arith -Wcast-qual -Wzero-as-null-pointer-constant -Wnon-virtual-dtor -Wold-style-cast -Wsuggest-override -Wshadow -Wextra-semi" diff --git a/src/build-data/cc/icc.txt b/src/build-data/cc/icc.txt index d844af368d1..b2c86c907d3 100644 --- a/src/build-data/cc/icc.txt +++ b/src/build-data/cc/icc.txt @@ -5,7 +5,7 @@ binary_name icpc optimization_flags "-O2" size_optimization_flags "-Os" -lang_flags "-std=c++20" +lang_flags "-std=c++17" warning_flags "-w1" shared_flags "-fPIC" diff --git a/src/build-data/cc/msvc.txt b/src/build-data/cc/msvc.txt index 64b6eae46f4..11e0d4a10ba 100644 --- a/src/build-data/cc/msvc.txt +++ b/src/build-data/cc/msvc.txt @@ -1,6 +1,6 @@ macro_name MSVC -minimum_supported_version 19.30 +minimum_supported_version 19.11 binary_name cl linker_name link diff --git a/src/build-data/cc/sunstudio.txt b/src/build-data/cc/sunstudio.txt index 7bae84f6edf..6c690ea9ccd 100644 --- a/src/build-data/cc/sunstudio.txt +++ b/src/build-data/cc/sunstudio.txt @@ -6,7 +6,7 @@ optimization_flags "-xO2" shared_flags "-KPIC" warning_flags "+w -erroff=truncwarn,wnoretvalue,wlessrestrictedthrow" -lang_flags "-std=c++20 +p -features=extensions" +lang_flags "-std=c++17 +p -features=extensions" ar_command CC ar_options "-xar -o" diff --git a/src/build-data/cc/xlc.txt b/src/build-data/cc/xlc.txt index b61158f1ea3..bf2cf3d0f99 100644 --- a/src/build-data/cc/xlc.txt +++ b/src/build-data/cc/xlc.txt @@ -11,7 +11,7 @@ optimization_flags "-O2" lang_binary_linker_flags "-bbigtoc" shared_flags "-fPIC" -lang_flags "-std=c++20" +lang_flags "-std=c++17" visibility_build_flags "-fvisibility=hidden" visibility_attribute '__attribute__((visibility("default")))' diff --git a/src/cli/argparse.h b/src/cli/argparse.h index 83f768f16ec..51d88e15f39 100644 --- a/src/cli/argparse.h +++ b/src/cli/argparse.h @@ -13,6 +13,8 @@ #include #include +#include + namespace Botan_CLI { class Argument_Parser final { @@ -76,11 +78,11 @@ std::vector Argument_Parser::split_on(const std::string& str, char } bool Argument_Parser::flag_set(const std::string& flag_name) const { - return m_user_flags.contains(flag_name); + return Botan::contains(m_user_flags, flag_name); } bool Argument_Parser::has_arg(const std::string& opt_name) const { - return m_user_args.contains(opt_name); + return Botan::contains(m_user_args, opt_name); } std::string Argument_Parser::get_arg(const std::string& opt_name) const { @@ -128,8 +130,8 @@ void Argument_Parser::parse_args(const std::vector& params) { if(eq == std::string::npos) { const std::string opt_name = param.substr(2, std::string::npos); - if(!m_spec_flags.contains(opt_name)) { - if(m_spec_opts.contains(opt_name)) { + if(!Botan::contains(m_spec_flags, opt_name)) { + if(Botan::contains(m_spec_opts, opt_name)) { throw CLI_Usage_Error("Invalid usage of option --" + opt_name + " without value"); } else { throw CLI_Usage_Error("Unknown flag --" + opt_name); @@ -140,11 +142,11 @@ void Argument_Parser::parse_args(const std::vector& params) { const std::string opt_name = param.substr(2, eq - 2); const std::string opt_val = param.substr(eq + 1, std::string::npos); - if(!m_spec_opts.contains(opt_name)) { + if(!Botan::contains(m_spec_opts, opt_name)) { throw CLI_Usage_Error("Unknown option --" + opt_name); } - if(m_user_args.contains(opt_name)) { + if(Botan::contains(m_user_args, opt_name)) { throw CLI_Usage_Error("Duplicated option --" + opt_name); } @@ -191,7 +193,7 @@ void Argument_Parser::parse_args(const std::vector& params) { // Now insert any defaults for options not supplied by the user for(const auto& opt : m_spec_opts) { - if(!m_user_args.contains(opt.first)) { + if(!Botan::contains(m_user_args, opt.first)) { m_user_args.insert(opt); } } diff --git a/src/cli/cli.cpp b/src/cli/cli.cpp index 996795206bc..90de69bbc7b 100644 --- a/src/cli/cli.cpp +++ b/src/cli/cli.cpp @@ -6,6 +6,7 @@ #include "cli.h" #include "argparse.h" +#include #include #include #include @@ -276,7 +277,7 @@ std::string Command::format_blob(const std::string& format, const uint8_t bits[] Command::Registration::Registration(const std::string& name, const Command::cmd_maker_fn& maker_fn) { std::map& reg = Command::global_registry(); - if(reg.contains(name)) { + if(Botan::contains(reg, name)) { throw CLI_Error("Duplicated registration of command " + name); } diff --git a/src/cli/compress.cpp b/src/cli/compress.cpp index 6514479eeb9..bea3c74e10d 100644 --- a/src/cli/compress.cpp +++ b/src/cli/compress.cpp @@ -8,6 +8,7 @@ #if defined(BOTAN_HAS_COMPRESSION) #include + #include #include #endif @@ -28,7 +29,7 @@ class Compress final : public Command { }; auto suffix_info = suffixes.find(comp_type); - if(!suffixes.contains(comp_type)) { + if(!Botan::contains(suffixes, comp_type)) { throw CLI_Error_Unsupported("Compressing", comp_type); } diff --git a/src/cli/timing_tests.cpp b/src/cli/timing_tests.cpp index ccb36dad062..0b2dd03395d 100644 --- a/src/cli/timing_tests.cpp +++ b/src/cli/timing_tests.cpp @@ -189,7 +189,7 @@ class Lucky13_Timing_Test final : public Timing_Test { Botan::MessageAuthenticationCode::create_or_throw("HMAC(" + m_mac_algo + ")"), 16, m_mac_keylen, - Botan::TLS::Protocol_Version::TLS_V12, + Botan::TLS::Version_Code::TLS_V12, false) {} std::vector prepare_input(const std::string& input) override; diff --git a/src/cli/tls_client.cpp b/src/cli/tls_client.cpp index 7b19abc4121..3574f453e0b 100644 --- a/src/cli/tls_client.cpp +++ b/src/cli/tls_client.cpp @@ -12,6 +12,7 @@ #if defined(BOTAN_HAS_TLS) && defined(BOTAN_TARGET_OS_HAS_FILESYSTEM) && defined(BOTAN_TARGET_OS_HAS_SOCKETS) + #include #include #include #include @@ -43,7 +44,7 @@ class Callbacks : public Botan::TLS::Callbacks { std::ostream& output(); bool flag_set(const std::string& flag_name) const; - void send(std::span buffer); + void send(Botan::span buffer); int peer_closed() const { return m_peer_closed; } @@ -69,7 +70,7 @@ class Callbacks : public Botan::TLS::Callbacks { if(result.successful_validation()) { auto status = result.all_statuses(); - if(!status.empty() && status[0].contains(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)) { + if(!status.empty() && contains(status[0], Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD)) { output() << "Valid OCSP response for this server\n"; } } @@ -106,7 +107,7 @@ class Callbacks : public Botan::TLS::Callbacks { } } - void tls_emit_data(std::span buf) override { + void tls_emit_data(Botan::span buf) override { if(flag_set("debug")) { output() << "<< " << Botan::hex_encode(buf) << "\n"; } @@ -116,7 +117,7 @@ class Callbacks : public Botan::TLS::Callbacks { void tls_alert(Botan::TLS::Alert alert) override { output() << "Alert: " << alert.type_string() << "\n"; } - void tls_record_received(uint64_t /*seq_no*/, std::span buf) override { + void tls_record_received(uint64_t /*seq_no*/, Botan::span buf) override { for(const auto c : buf) { output() << c; } @@ -210,9 +211,9 @@ class TLS_Client final : public Command { if(tls_version != "default") { if(tls_version == "1.2") { - version = use_tcp ? Botan::TLS::Protocol_Version::TLS_V12 : Botan::TLS::Protocol_Version::DTLS_V12; + version = use_tcp ? Botan::TLS::Version_Code::TLS_V12 : Botan::TLS::Version_Code::DTLS_V12; } else if(tls_version == "1.3") { - version = use_tcp ? Botan::TLS::Protocol_Version::TLS_V13 : Botan::TLS::Protocol_Version::DTLS_V13; + version = use_tcp ? Botan::TLS::Version_Code::TLS_V13 : Botan::TLS::Version_Code::DTLS_V13; } else { error_output() << "Unknown TLS protocol version " << tls_version << '\n'; } @@ -345,7 +346,7 @@ class TLS_Client final : public Command { using Command::flag_set; using Command::output; - void send(std::span buf) const { + void send(Botan::span buf) const { while(!buf.empty()) { ssize_t sent = ::send(m_sockfd, buf.data(), buf.size(), MSG_NOSIGNAL); @@ -421,7 +422,7 @@ bool Callbacks::flag_set(const std::string& flag_name) const { return m_client_command.flag_set(flag_name); } -void Callbacks::send(std::span buffer) { +void Callbacks::send(Botan::span buffer) { m_client_command.send(buffer); } diff --git a/src/cli/tls_helpers.h b/src/cli/tls_helpers.h index 7504e7c7518..74c580dc15f 100644 --- a/src/cli/tls_helpers.h +++ b/src/cli/tls_helpers.h @@ -35,7 +35,7 @@ inline bool value_exists(const std::vector& vec, const std::string& inline std::string maybe_hex_encode(std::string_view v) { auto is_printable_char = [](uint8_t c) { return c >= 32 && c < 127; }; if(!std::all_of(v.begin(), v.end(), is_printable_char)) { - return Botan::hex_encode(std::span(reinterpret_cast(v.data()), v.size())); + return Botan::hex_encode(Botan::span(reinterpret_cast(v.data()), v.size())); } return std::string(v); } diff --git a/src/cli/tls_http_server.cpp b/src/cli/tls_http_server.cpp index 3135dd8e583..bf62f3ecf43 100644 --- a/src/cli/tls_http_server.cpp +++ b/src/cli/tls_http_server.cpp @@ -124,7 +124,7 @@ class HTTP_Parser final { HTTP_Parser(Callbacks& cb) : m_cb(cb) {} - void consume_input(std::span buf) { + void consume_input(Botan::span buf) { m_req_buf.append(reinterpret_cast(buf.data()), buf.size()); std::istringstream strm(m_req_buf); @@ -270,7 +270,7 @@ class TLS_Asio_HTTP_Session final : public std::enable_shared_from_this buf) override { + void tls_record_received(uint64_t /*rec_no*/, Botan::span buf) override { if(!m_http_parser) { m_http_parser = std::make_unique(*this); } @@ -325,7 +325,7 @@ class TLS_Asio_HTTP_Session final : public std::enable_shared_from_thisclose(); } - void tls_emit_data(std::span buf) override { + void tls_emit_data(Botan::span buf) override { if(!buf.empty()) { m_s2c_pending.insert(m_s2c_pending.end(), buf.begin(), buf.end()); } @@ -398,7 +398,7 @@ class TLS_Asio_HTTP_Session final : public std::enable_shared_from_thisclose(); } else { std::cout << "Alert " << alert.type_string() << std::endl; diff --git a/src/cli/tls_proxy.cpp b/src/cli/tls_proxy.cpp index 2eed44561b3..f4613ad5ae1 100644 --- a/src/cli/tls_proxy.cpp +++ b/src/cli/tls_proxy.cpp @@ -210,12 +210,12 @@ class tls_proxy_session final : public std::enable_shared_from_this buf) override { + void tls_record_received(uint64_t /*rec_no*/, Botan::span buf) override { // Immediately bounce message to server proxy_write_to_server(buf); } - void tls_emit_data(std::span buf) override { + void tls_emit_data(Botan::span buf) override { if(!buf.empty()) { m_p2c_pending.insert(m_p2c_pending.end(), buf.begin(), buf.end()); } @@ -234,7 +234,7 @@ class tls_proxy_session final : public std::enable_shared_from_this buf) { + void proxy_write_to_server(Botan::span buf) { if(!buf.empty()) { m_p2s_pending.insert(m_p2s_pending.end(), buf.begin(), buf.end()); } @@ -298,7 +298,7 @@ class tls_proxy_session final : public std::enable_shared_from_thisclose(); return; } diff --git a/src/cli/tls_server.cpp b/src/cli/tls_server.cpp index aafd4271b4d..6bb03dc8f6b 100644 --- a/src/cli/tls_server.cpp +++ b/src/cli/tls_server.cpp @@ -52,7 +52,7 @@ class Callbacks : public Botan::TLS::Callbacks { Callbacks(TLS_Server& server_command) : m_server_command(server_command) {} std::ostream& output(); - void send(std::span buffer); + void send(Botan::span buffer); void push_pending_output(std::string line); void tls_session_established(const Botan::TLS::Session_Summary& session) override { @@ -74,7 +74,7 @@ class Callbacks : public Botan::TLS::Callbacks { } } - void tls_record_received(uint64_t /*seq_no*/, std::span input) override { + void tls_record_received(uint64_t /*seq_no*/, Botan::span input) override { for(size_t i = 0; i != input.size(); ++i) { const char c = static_cast(input[i]); m_line_buf += c; @@ -84,7 +84,7 @@ class Callbacks : public Botan::TLS::Callbacks { } } - void tls_emit_data(std::span buf) override { send(buf); } + void tls_emit_data(Botan::span buf) override { send(buf); } void tls_alert(Botan::TLS::Alert alert) override { output() << "Alert: " << alert.type_string() << std::endl; } @@ -276,7 +276,7 @@ class TLS_Server final : public Command { using Command::flag_set; using Command::output; - void send(std::span buf) { + void send(Botan::span buf) { if(m_is_tcp) { ssize_t sent = ::send(m_socket, buf.data(), static_cast(buf.size()), MSG_NOSIGNAL); @@ -361,7 +361,7 @@ std::ostream& Callbacks::output() { return m_server_command.output(); } -void Callbacks::send(std::span buffer) { +void Callbacks::send(Botan::span buffer) { m_server_command.send(buffer); } diff --git a/src/cli/tls_utils.cpp b/src/cli/tls_utils.cpp index 050f5b0d973..b07ac91d0a5 100644 --- a/src/cli/tls_utils.cpp +++ b/src/cli/tls_utils.cpp @@ -25,10 +25,10 @@ class TLS_Ciphersuites final : public Command { static Botan::TLS::Protocol_Version tls_version_from_str(const std::string& str) { if(str == "tls1.2" || str == "TLS1.2" || str == "TLS-1.2") { - return Botan::TLS::Protocol_Version::TLS_V12; + return Botan::TLS::Version_Code::TLS_V12; } if(str == "dtls1.2" || str == "DTLS1.2" || str == "DTLS-1.2") { - return Botan::TLS::Protocol_Version::DTLS_V12; + return Botan::TLS::Version_Code::DTLS_V12; } else { throw CLI_Error("Unknown TLS version '" + str + "'"); } diff --git a/src/examples/tls_13_hybrid_key_exchange_client.cpp b/src/examples/tls_13_hybrid_key_exchange_client.cpp index 73f6e2ad721..6779f3e89f2 100644 --- a/src/examples/tls_13_hybrid_key_exchange_client.cpp +++ b/src/examples/tls_13_hybrid_key_exchange_client.cpp @@ -11,12 +11,12 @@ */ class Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { BOTAN_UNUSED(data); // send data to tls server, e.g., using BSD sockets or boost asio } - void tls_record_received(uint64_t seq_no, std::span data) override { + void tls_record_received(uint64_t seq_no, Botan::span data) override { BOTAN_UNUSED(seq_no, data); // process full TLS record received by tls server, e.g., // by passing it to the application @@ -54,16 +54,16 @@ class Client_Policy : public Botan::TLS::Default_Policy { // additional to the default (classical) key exchange groups std::vector key_exchange_groups() const override { auto groups = Botan::TLS::Default_Policy::key_exchange_groups(); - groups.push_back(Botan::TLS::Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE); - groups.push_back(Botan::TLS::Group_Params::HYBRID_X25519_KYBER_512_R3_OQS); + groups.push_back(Botan::TLS::Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE); + groups.push_back(Botan::TLS::Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS); return groups; } // Define that the client should exclusively pre-offer hybrid groups // in its initial Client Hello. std::vector key_exchange_groups_to_offer() const override { - return {Botan::TLS::Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE, - Botan::TLS::Group_Params::HYBRID_X25519_KYBER_512_R3_OQS}; + return {Botan::TLS::Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE, + Botan::TLS::Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS}; } }; @@ -82,7 +82,7 @@ int main() { policy, rng, Botan::TLS::Server_Information("botan.randombit.net", 443), - Botan::TLS::Protocol_Version::TLS_V12); + Botan::TLS::Version_Code::TLS_V12); while(!client.is_closed()) { // read data received from the tls server, e.g., using BSD sockets or boost asio diff --git a/src/examples/tls_client.cpp b/src/examples/tls_client.cpp index 885d76f720a..498a48ae30a 100644 --- a/src/examples/tls_client.cpp +++ b/src/examples/tls_client.cpp @@ -12,12 +12,12 @@ */ class Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { // send data to tls server, e.g., using BSD sockets or boost asio BOTAN_UNUSED(data); } - void tls_record_received(uint64_t seq_no, std::span data) override { + void tls_record_received(uint64_t seq_no, Botan::span data) override { // process full TLS record received by tls server, e.g., // by passing it to the application BOTAN_UNUSED(seq_no, data); @@ -87,7 +87,7 @@ int main() { policy, rng, Botan::TLS::Server_Information("botan.randombit.net", 443), - Botan::TLS::Protocol_Version::TLS_V12); + Botan::TLS::Version_Code::TLS_V12); while(!client.is_closed()) { // read data received from the tls server, e.g., using BSD sockets or boost asio diff --git a/src/examples/tls_custom_curves_client.cpp b/src/examples/tls_custom_curves_client.cpp index fc34f748c63..eea0030edce 100644 --- a/src/examples/tls_custom_curves_client.cpp +++ b/src/examples/tls_custom_curves_client.cpp @@ -12,12 +12,12 @@ */ class Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { BOTAN_UNUSED(data); // send data to tls server, e.g., using BSD sockets or boost asio } - void tls_record_received(uint64_t seq_no, std::span data) override { + void tls_record_received(uint64_t seq_no, Botan::span data) override { BOTAN_UNUSED(seq_no, data); // process full TLS record received by tls server, e.g., // by passing it to the application @@ -132,7 +132,7 @@ int main() { policy, rng, Botan::TLS::Server_Information("botan.randombit.net", 443), - Botan::TLS::Protocol_Version::TLS_V12); + Botan::TLS::Version_Code::TLS_V12); while(!client.is_closed()) { // read data received from the tls server, e.g., using BSD sockets or boost asio diff --git a/src/examples/tls_proxy.cpp b/src/examples/tls_proxy.cpp index 91c7c12ecfd..6463b52c8db 100644 --- a/src/examples/tls_proxy.cpp +++ b/src/examples/tls_proxy.cpp @@ -15,12 +15,12 @@ */ class Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { // send data to tls client, e.g., using BSD sockets or boost asio BOTAN_UNUSED(data); } - void tls_record_received(uint64_t seq_no, std::span data) override { + void tls_record_received(uint64_t seq_no, Botan::span data) override { // process full TLS record received by tls client, e.g., // by passing it to the application BOTAN_UNUSED(seq_no, data); diff --git a/src/fuzzer/tls_13_handshake_layer.cpp b/src/fuzzer/tls_13_handshake_layer.cpp index 00e4404b5ab..bcdfea5fb34 100644 --- a/src/fuzzer/tls_13_handshake_layer.cpp +++ b/src/fuzzer/tls_13_handshake_layer.cpp @@ -13,7 +13,7 @@ namespace { -Botan::TLS::Handshake_Layer prepare(std::span data) { +Botan::TLS::Handshake_Layer prepare(Botan::span data) { Botan::TLS::Handshake_Layer hl(Botan::TLS::Connection_Side::Client); hl.copy_data(data); return hl; @@ -25,11 +25,11 @@ void fuzz(const uint8_t in[], size_t len) { static Botan::TLS::Default_Policy policy; try { - auto hl1 = prepare(std::span(in, len)); + auto hl1 = prepare(Botan::span(in, len)); Botan::TLS::Transcript_Hash_State ths("SHA-256"); while(hl1.next_message(policy, ths).has_value()) {}; - auto hl2 = prepare(std::span(in, len)); + auto hl2 = prepare(Botan::span(in, len)); while(hl2.next_post_handshake_message(policy).has_value()) {}; } catch(Botan::Exception& e) {} } diff --git a/src/fuzzer/tls_client.cpp b/src/fuzzer/tls_client.cpp index 11d13a8905b..1d523738137 100644 --- a/src/fuzzer/tls_client.cpp +++ b/src/fuzzer/tls_client.cpp @@ -56,11 +56,11 @@ class Fuzzer_TLS_Policy : public Botan::TLS::Policy { class Fuzzer_TLS_Client_Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span) override { + void tls_emit_data(Botan::span) override { // discard } - void tls_record_received(uint64_t, std::span) override { + void tls_record_received(uint64_t, Botan::span) override { // ignore peer data } @@ -91,7 +91,7 @@ void fuzz(const uint8_t in[], size_t len) { auto session_manager = std::make_shared(); auto policy = std::make_shared(); - Botan::TLS::Protocol_Version client_offer = Botan::TLS::Protocol_Version::TLS_V12; + Botan::TLS::Protocol_Version client_offer = Botan::TLS::Version_Code::TLS_V12; Botan::TLS::Server_Information info("server.name", 443); auto callbacks = std::make_shared(); auto creds = std::make_shared(); diff --git a/src/fuzzer/tls_server.cpp b/src/fuzzer/tls_server.cpp index 2cb0d1d651b..e19801721de 100644 --- a/src/fuzzer/tls_server.cpp +++ b/src/fuzzer/tls_server.cpp @@ -156,11 +156,11 @@ class Fuzzer_TLS_Policy : public Botan::TLS::Policy { class Fuzzer_TLS_Server_Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span) override { + void tls_emit_data(Botan::span) override { // discard } - void tls_record_received(uint64_t, std::span) override { + void tls_record_received(uint64_t, Botan::span) override { // ignore peer data } diff --git a/src/lib/asn1/ber_dec.h b/src/lib/asn1/ber_dec.h index 8cdbb1ca00e..b507eba54c4 100644 --- a/src/lib/asn1/ber_dec.h +++ b/src/lib/asn1/ber_dec.h @@ -28,7 +28,7 @@ class BOTAN_PUBLIC_API(2, 0) BER_Decoder final { /** * Set up to BER decode the data in buf of length len */ - BER_Decoder(std::span buf) : BER_Decoder(buf.data(), buf.size()) {} + BER_Decoder(Botan::span buf) : BER_Decoder(buf.data(), buf.size()) {} /** * Set up to BER decode the data in vec @@ -138,9 +138,9 @@ class BOTAN_PUBLIC_API(2, 0) BER_Decoder final { * @return this reference */ template - BER_Decoder& get_next_value(T& out, ASN1_Type type_tag, ASN1_Class class_tag = ASN1_Class::ContextSpecific) - requires std::is_standard_layout::value && std::is_trivial::value - { + BER_Decoder& get_next_value(T& out, ASN1_Type type_tag, ASN1_Class class_tag = ASN1_Class::ContextSpecific) { + static_assert(std::is_standard_layout::value && std::is_trivial::value, "Type must be POD"); + BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); diff --git a/src/lib/asn1/oid_map.cpp b/src/lib/asn1/oid_map.cpp index ef5c46e0e97..c0b89aefbe1 100644 --- a/src/lib/asn1/oid_map.cpp +++ b/src/lib/asn1/oid_map.cpp @@ -4,6 +4,7 @@ * Botan is released under the Simplified BSD License (see license.txt) */ +#include #include namespace Botan { @@ -40,7 +41,7 @@ void OID_Map::add_oid(const OID& oid, std::string_view str) { void OID_Map::add_str2oid(const OID& oid, std::string_view str) { lock_guard_type lock(m_mutex); - if(!m_str2oid.contains(std::string(str))) { + if(!contains(m_str2oid, std::string(str))) { m_str2oid.insert(std::make_pair(str, oid)); } } @@ -48,7 +49,7 @@ void OID_Map::add_str2oid(const OID& oid, std::string_view str) { void OID_Map::add_oid2str(const OID& oid, std::string_view str) { const std::string oid_str = oid.to_string(); lock_guard_type lock(m_mutex); - if(!m_oid2str.contains(oid_str)) { + if(!contains(m_oid2str, oid_str)) { m_oid2str.insert(std::make_pair(oid_str, str)); } } diff --git a/src/lib/base/buf_comp.h b/src/lib/base/buf_comp.h index 1b884809391..f44f603987f 100644 --- a/src/lib/base/buf_comp.h +++ b/src/lib/base/buf_comp.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include namespace Botan { @@ -37,7 +37,7 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { * Add new input to process. * @param in the input to process as a contiguous data range */ - void update(std::span in) { add_data(in); } + void update(Botan::span in) { add_data(in); } void update_be(uint16_t val); void update_be(uint32_t val); @@ -73,7 +73,7 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { * final result as a container of your choice. * @return a contiguous container holding the result */ - template > + template , typename = concepts::resizable_byte_buffer> T final() { T output(output_length()); final_result(output); @@ -82,12 +82,12 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { std::vector final_stdvec() { return final>(); } - void final(std::span out) { + void final(Botan::span out) { BOTAN_ARG_CHECK(out.size() >= output_length(), "provided output buffer has insufficient capacity"); final_result(out); } - template + template > void final(T& out) { out.resize(output_length()); final_result(out); @@ -100,7 +100,7 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { * @param length the length of the byte array * @result the result of the call to final() */ - template > + template , typename = concepts::resizable_byte_buffer> T process(const uint8_t in[], size_t length) { update(in, length); return final(); @@ -112,7 +112,7 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { * @param in the input to process as a string * @result the result of the call to final() */ - template > + template , typename = concepts::resizable_byte_buffer> T process(std::string_view in) { update(in); return final(); @@ -124,8 +124,8 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { * @param in the input to process as a contiguous container * @result the result of the call to final() */ - template > - T process(std::span in) { + template , typename = concepts::resizable_byte_buffer> + T process(Botan::span in) { update(in); return final(); } @@ -137,13 +137,13 @@ class BOTAN_PUBLIC_API(2, 0) Buffered_Computation { * Add more data to the computation * @param input is an input buffer */ - virtual void add_data(std::span input) = 0; + virtual void add_data(Botan::span input) = 0; /** * Write the final output to out * @param out is an output buffer of output_length() */ - virtual void final_result(std::span out) = 0; + virtual void final_result(Botan::span out) = 0; }; } // namespace Botan diff --git a/src/lib/base/info.txt b/src/lib/base/info.txt index 03cdcb5cd89..4ec04794f3b 100644 --- a/src/lib/base/info.txt +++ b/src/lib/base/info.txt @@ -14,4 +14,5 @@ brief -> "Defines some high level types" hex rng utils +cpp20_extras diff --git a/src/lib/base/secmem.h b/src/lib/base/secmem.h index 4f257331c19..46ac6ff6197 100644 --- a/src/lib/base/secmem.h +++ b/src/lib/base/secmem.h @@ -18,19 +18,19 @@ namespace Botan { template +class secure_allocator { + public: + /* + * Assert exists to prevent someone from doing something that will + * probably crash anyway (like secure_vector where ~non_POD_t + * deletes a member pointer which was zeroed before it ran). + * MSVC in debug mode uses non-integral proxy types in container types + * like std::vector, thus we disable the check there. + */ #if !defined(_ITERATOR_DEBUG_LEVEL) || _ITERATOR_DEBUG_LEVEL == 0 -/* - * Assert exists to prevent someone from doing something that will - * probably crash anyway (like secure_vector where ~non_POD_t - * deletes a member pointer which was zeroed before it ran). - * MSVC in debug mode uses non-integral proxy types in container types - * like std::vector, thus we disable the check there. - */ - requires std::is_integral::value + static_assert(std::is_integral::value, "secure_allocator supports only integer types"); #endif -class secure_allocator { - public: typedef T value_type; typedef std::size_t size_type; diff --git a/src/lib/base/sym_algo.cpp b/src/lib/base/sym_algo.cpp index 63ebc8e661e..32616e0c92f 100644 --- a/src/lib/base/sym_algo.cpp +++ b/src/lib/base/sym_algo.cpp @@ -14,7 +14,7 @@ void SymmetricAlgorithm::throw_key_not_set_error() const { throw Key_Not_Set(name()); } -void SymmetricAlgorithm::set_key(std::span key) { +void SymmetricAlgorithm::set_key(Botan::span key) { if(!valid_keylength(key.size())) { throw Invalid_Key_Length(name(), key.size()); } diff --git a/src/lib/base/sym_algo.h b/src/lib/base/sym_algo.h index 96546281749..0976a435daa 100644 --- a/src/lib/base/sym_algo.h +++ b/src/lib/base/sym_algo.h @@ -11,7 +11,7 @@ #include #include -#include +#include namespace Botan { @@ -110,20 +110,20 @@ class BOTAN_PUBLIC_API(2, 0) SymmetricAlgorithm { * Set the symmetric key of this object. * @param key the SymmetricKey to be set. */ - void set_key(const SymmetricKey& key) { set_key(std::span{key.begin(), key.length()}); } + void set_key(const SymmetricKey& key) { set_key(Botan::span{key.begin(), key.length()}); } /** * Set the symmetric key of this object. * @param key the contiguous byte range to be set. */ - void set_key(std::span key); + void set_key(Botan::span key); /** * Set the symmetric key of this object. * @param key the to be set as a byte array. * @param length in bytes of key param */ - void set_key(const uint8_t key[], size_t length) { set_key(std::span{key, length}); } + void set_key(const uint8_t key[], size_t length) { set_key(Botan::span{key, length}); } /** * @return the algorithm name @@ -151,7 +151,7 @@ class BOTAN_PUBLIC_API(2, 0) SymmetricAlgorithm { * Run the key schedule * @param key the key */ - virtual void key_schedule(std::span key) = 0; + virtual void key_schedule(Botan::span key) = 0; }; } // namespace Botan diff --git a/src/lib/base/symkey.h b/src/lib/base/symkey.h index f5c5abba31e..cd664c9bf95 100644 --- a/src/lib/base/symkey.h +++ b/src/lib/base/symkey.h @@ -9,7 +9,7 @@ #define BOTAN_SYMKEY_H_ #include -#include +#include #include namespace Botan { @@ -91,7 +91,7 @@ class BOTAN_PUBLIC_API(2, 0) OctetString final { * Create a new OctetString * @param in a bytestring */ - explicit OctetString(std::span in) : m_data(in.begin(), in.end()) {} + explicit OctetString(Botan::span in) : m_data(in.begin(), in.end()) {} /** * Create a new OctetString diff --git a/src/lib/block/aes/aes.cpp b/src/lib/block/aes/aes.cpp index ac055a91ec9..663cd7a2f6c 100644 --- a/src/lib/block/aes/aes.cpp +++ b/src/lib/block/aes/aes.cpp @@ -845,7 +845,7 @@ void AES_128::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const aes_decrypt_n(in, out, blocks, m_DK); } -void AES_128::key_schedule(std::span key) { +void AES_128::key_schedule(Botan::span key) { #if defined(BOTAN_HAS_AES_NI) if(CPUID::has_aes_ni()) { return aesni_key_schedule(key.data(), key.size()); @@ -908,7 +908,7 @@ void AES_192::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const aes_decrypt_n(in, out, blocks, m_DK); } -void AES_192::key_schedule(std::span key) { +void AES_192::key_schedule(Botan::span key) { #if defined(BOTAN_HAS_AES_NI) if(CPUID::has_aes_ni()) { return aesni_key_schedule(key.data(), key.size()); @@ -971,7 +971,7 @@ void AES_256::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const aes_decrypt_n(in, out, blocks, m_DK); } -void AES_256::key_schedule(std::span key) { +void AES_256::key_schedule(Botan::span key) { #if defined(BOTAN_HAS_AES_NI) if(CPUID::has_aes_ni()) { return aesni_key_schedule(key.data(), key.size()); diff --git a/src/lib/block/aes/aes.h b/src/lib/block/aes/aes.h index 0071e0edbaa..35e79ed4df5 100644 --- a/src/lib/block/aes/aes.h +++ b/src/lib/block/aes/aes.h @@ -33,7 +33,7 @@ class AES_128 final : public Block_Cipher_Fixed_Params<16, 16> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; #if defined(BOTAN_HAS_AES_VPERM) void vperm_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const; @@ -88,7 +88,7 @@ class AES_192 final : public Block_Cipher_Fixed_Params<16, 24> { void hw_aes_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const; #endif - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_EK, m_DK; }; @@ -128,7 +128,7 @@ class AES_256 final : public Block_Cipher_Fixed_Params<16, 32> { void hw_aes_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const; #endif - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_EK, m_DK; }; diff --git a/src/lib/block/aria/aria.cpp b/src/lib/block/aria/aria.cpp index 4577b507766..d300ca052cd 100644 --- a/src/lib/block/aria/aria.cpp +++ b/src/lib/block/aria/aria.cpp @@ -249,7 +249,7 @@ void aria_ks_dk_transform(uint32_t& K0, uint32_t& K1, uint32_t& K2, uint32_t& K3 /* * ARIA Key Schedule */ -void key_schedule(secure_vector& ERK, secure_vector& DRK, std::span key) { +void key_schedule(secure_vector& ERK, secure_vector& DRK, Botan::span key) { const uint32_t KRK[3][4] = {{0x517cc1b7, 0x27220a94, 0xfe13abe8, 0xfa9a6ee0}, {0x6db14acc, 0x9e21c820, 0xff28b1d5, 0xef5de2b0}, {0xdb92371d, 0x2126e970, 0x03249775, 0x04e8c90e}}; @@ -401,15 +401,15 @@ bool ARIA_256::has_keying_material() const { return !m_ERK.empty(); } -void ARIA_128::key_schedule(std::span key) { +void ARIA_128::key_schedule(Botan::span key) { ARIA_F::key_schedule(m_ERK, m_DRK, key); } -void ARIA_192::key_schedule(std::span key) { +void ARIA_192::key_schedule(Botan::span key) { ARIA_F::key_schedule(m_ERK, m_DRK, key); } -void ARIA_256::key_schedule(std::span key) { +void ARIA_256::key_schedule(Botan::span key) { ARIA_F::key_schedule(m_ERK, m_DRK, key); } diff --git a/src/lib/block/aria/aria.h b/src/lib/block/aria/aria.h index 4391219d69e..97d6ac202f2 100644 --- a/src/lib/block/aria/aria.h +++ b/src/lib/block/aria/aria.h @@ -37,7 +37,7 @@ class ARIA_128 final : public Block_Cipher_Fixed_Params<16, 16> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; // Encryption and Decryption round keys. secure_vector m_ERK, m_DRK; @@ -60,7 +60,7 @@ class ARIA_192 final : public Block_Cipher_Fixed_Params<16, 24> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; // Encryption and Decryption round keys. secure_vector m_ERK, m_DRK; @@ -83,7 +83,7 @@ class ARIA_256 final : public Block_Cipher_Fixed_Params<16, 32> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; // Encryption and Decryption round keys. secure_vector m_ERK, m_DRK; diff --git a/src/lib/block/block_cipher.h b/src/lib/block/block_cipher.h index 2b4752d7f42..ab6be34d891 100644 --- a/src/lib/block/block_cipher.h +++ b/src/lib/block/block_cipher.h @@ -102,7 +102,7 @@ class BOTAN_PUBLIC_API(2, 0) BlockCipher : public SymmetricAlgorithm { * Encrypt one or more blocks * @param block the input/output buffer (multiple of block_size()) */ - void encrypt(std::span block) const { + void encrypt(Botan::span block) const { return encrypt_n(block.data(), block.data(), block.size() / block_size()); } @@ -110,7 +110,7 @@ class BOTAN_PUBLIC_API(2, 0) BlockCipher : public SymmetricAlgorithm { * Decrypt one or more blocks * @param block the input/output buffer (multiple of block_size()) */ - void decrypt(std::span block) const { + void decrypt(Botan::span block) const { return decrypt_n(block.data(), block.data(), block.size() / block_size()); } @@ -119,7 +119,7 @@ class BOTAN_PUBLIC_API(2, 0) BlockCipher : public SymmetricAlgorithm { * @param in the input buffer (multiple of block_size()) * @param out the output buffer (same size as in) */ - void encrypt(std::span in, std::span out) const { + void encrypt(Botan::span in, Botan::span out) const { return encrypt_n(in.data(), out.data(), in.size() / block_size()); } @@ -128,7 +128,7 @@ class BOTAN_PUBLIC_API(2, 0) BlockCipher : public SymmetricAlgorithm { * @param in the input buffer (multiple of block_size()) * @param out the output buffer (same size as in) */ - void decrypt(std::span in, std::span out) const { + void decrypt(Botan::span in, Botan::span out) const { return decrypt_n(in.data(), out.data(), in.size() / block_size()); } diff --git a/src/lib/block/blowfish/blowfish.cpp b/src/lib/block/blowfish/blowfish.cpp index 611df1e1e4d..24380c48d1f 100644 --- a/src/lib/block/blowfish/blowfish.cpp +++ b/src/lib/block/blowfish/blowfish.cpp @@ -296,7 +296,7 @@ bool Blowfish::has_keying_material() const { /* * Blowfish Key Schedule */ -void Blowfish::key_schedule(std::span key) { +void Blowfish::key_schedule(Botan::span key) { m_P.resize(18); copy_mem(m_P.data(), P_INIT, 18); diff --git a/src/lib/block/blowfish/blowfish.h b/src/lib/block/blowfish/blowfish.h index 982927b757d..a2e211387b9 100644 --- a/src/lib/block/blowfish/blowfish.h +++ b/src/lib/block/blowfish/blowfish.h @@ -39,7 +39,7 @@ class BOTAN_TEST_API Blowfish final : public Block_Cipher_Fixed_Params<8, 1, 56> bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void key_expansion(const uint8_t key[], size_t key_length, const uint8_t salt[], size_t salt_length); diff --git a/src/lib/block/camellia/camellia.cpp b/src/lib/block/camellia/camellia.cpp index 9b540659c58..f0b54949ef8 100644 --- a/src/lib/block/camellia/camellia.cpp +++ b/src/lib/block/camellia/camellia.cpp @@ -227,7 +227,7 @@ inline uint64_t left_rot_lo(uint64_t h, uint64_t l, size_t shift) { /* * Camellia Key Schedule */ -void key_schedule(secure_vector& SK, std::span key) { +void key_schedule(secure_vector& SK, Botan::span key) { const uint64_t Sigma1 = 0xA09E667F3BCC908B; const uint64_t Sigma2 = 0xB67AE8584CAA73B2; const uint64_t Sigma3 = 0xC6EF372FE94F82BE; @@ -382,15 +382,15 @@ bool Camellia_256::has_keying_material() const { return !m_SK.empty(); } -void Camellia_128::key_schedule(std::span key) { +void Camellia_128::key_schedule(Botan::span key) { Camellia_F::key_schedule(m_SK, key); } -void Camellia_192::key_schedule(std::span key) { +void Camellia_192::key_schedule(Botan::span key) { Camellia_F::key_schedule(m_SK, key); } -void Camellia_256::key_schedule(std::span key) { +void Camellia_256::key_schedule(Botan::span key) { Camellia_F::key_schedule(m_SK, key); } diff --git a/src/lib/block/camellia/camellia.h b/src/lib/block/camellia/camellia.h index 065caf0a480..408c1bab60b 100644 --- a/src/lib/block/camellia/camellia.h +++ b/src/lib/block/camellia/camellia.h @@ -29,7 +29,7 @@ class Camellia_128 final : public Block_Cipher_Fixed_Params<16, 16> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_SK; }; @@ -51,7 +51,7 @@ class Camellia_192 final : public Block_Cipher_Fixed_Params<16, 24> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_SK; }; @@ -73,7 +73,7 @@ class Camellia_256 final : public Block_Cipher_Fixed_Params<16, 32> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_SK; }; diff --git a/src/lib/block/cascade/cascade.cpp b/src/lib/block/cascade/cascade.cpp index 01781b2de98..e7d0c54ad76 100644 --- a/src/lib/block/cascade/cascade.cpp +++ b/src/lib/block/cascade/cascade.cpp @@ -28,7 +28,7 @@ void Cascade_Cipher::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) m_cipher1->decrypt_n(out, out, c1_blocks); } -void Cascade_Cipher::key_schedule(std::span key) { +void Cascade_Cipher::key_schedule(Botan::span key) { BufferSlicer keys(key); m_cipher1->set_key(keys.take(m_cipher1->maximum_keylength())); diff --git a/src/lib/block/cascade/cascade.h b/src/lib/block/cascade/cascade.h index c208c4c391e..0160ae423d1 100644 --- a/src/lib/block/cascade/cascade.h +++ b/src/lib/block/cascade/cascade.h @@ -43,7 +43,7 @@ class Cascade_Cipher final : public BlockCipher { Cascade_Cipher& operator=(const Cascade_Cipher&) = delete; private: - void key_schedule(std::span) override; + void key_schedule(Botan::span) override; std::unique_ptr m_cipher1, m_cipher2; size_t m_block_size; diff --git a/src/lib/block/cast128/cast128.cpp b/src/lib/block/cast128/cast128.cpp index 5d105a83f73..c6cf55f1cfe 100644 --- a/src/lib/block/cast128/cast128.cpp +++ b/src/lib/block/cast128/cast128.cpp @@ -337,7 +337,7 @@ bool CAST_128::has_keying_material() const { /* * CAST-128 Key Schedule */ -void CAST_128::key_schedule(std::span key) { +void CAST_128::key_schedule(Botan::span key) { m_MK.resize(48); m_RK.resize(48); diff --git a/src/lib/block/cast128/cast128.h b/src/lib/block/cast128/cast128.h index 33d16f97d5f..c7333742fb4 100644 --- a/src/lib/block/cast128/cast128.h +++ b/src/lib/block/cast128/cast128.h @@ -29,7 +29,7 @@ class CAST_128 final : public Block_Cipher_Fixed_Params<8, 11, 16> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; static void cast_ks(secure_vector& ks, secure_vector& user_key); diff --git a/src/lib/block/des/des.cpp b/src/lib/block/des/des.cpp index b89d9126a56..196b1b4f5f9 100644 --- a/src/lib/block/des/des.cpp +++ b/src/lib/block/des/des.cpp @@ -332,7 +332,7 @@ bool DES::has_keying_material() const { /* * DES Key Schedule */ -void DES::key_schedule(std::span key) { +void DES::key_schedule(Botan::span key) { m_round_key.resize(32); des_key_schedule(m_round_key.data(), key.data()); } @@ -442,7 +442,7 @@ bool TripleDES::has_keying_material() const { /* * TripleDES Key Schedule */ -void TripleDES::key_schedule(std::span key) { +void TripleDES::key_schedule(Botan::span key) { m_round_key.resize(3 * 32); des_key_schedule(&m_round_key[0], key.first(8).data()); des_key_schedule(&m_round_key[32], key.subspan(8, 8).data()); diff --git a/src/lib/block/des/des.h b/src/lib/block/des/des.h index fd46b0919ef..46a1509b655 100644 --- a/src/lib/block/des/des.h +++ b/src/lib/block/des/des.h @@ -29,7 +29,7 @@ class DES final : public Block_Cipher_Fixed_Params<8, 8> { bool has_keying_material() const override; private: - void key_schedule(std::span) override; + void key_schedule(Botan::span) override; secure_vector m_round_key; }; @@ -51,7 +51,7 @@ class TripleDES final : public Block_Cipher_Fixed_Params<8, 16, 24, 8> { bool has_keying_material() const override; private: - void key_schedule(std::span) override; + void key_schedule(Botan::span) override; secure_vector m_round_key; }; diff --git a/src/lib/block/gost_28147/gost_28147.cpp b/src/lib/block/gost_28147/gost_28147.cpp index 3c94ec43135..11188d1269d 100644 --- a/src/lib/block/gost_28147/gost_28147.cpp +++ b/src/lib/block/gost_28147/gost_28147.cpp @@ -150,7 +150,7 @@ bool GOST_28147_89::has_keying_material() const { /* * GOST Key Schedule */ -void GOST_28147_89::key_schedule(std::span key) { +void GOST_28147_89::key_schedule(Botan::span key) { m_EK.resize(8); for(size_t i = 0; i != 8; ++i) { m_EK[i] = load_le(key.data(), i); diff --git a/src/lib/block/gost_28147/gost_28147.h b/src/lib/block/gost_28147/gost_28147.h index bb0f1991172..70e167c6664 100644 --- a/src/lib/block/gost_28147/gost_28147.h +++ b/src/lib/block/gost_28147/gost_28147.h @@ -81,7 +81,7 @@ class GOST_28147_89 final : public Block_Cipher_Fixed_Params<8, 32> { m_SBOX(other_SBOX), m_EK(8), m_name(name) {} private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; /* * The sbox is not secret, this is just a larger expansion of it diff --git a/src/lib/block/idea/idea.cpp b/src/lib/block/idea/idea.cpp index 164af12f839..1d1fec368f1 100644 --- a/src/lib/block/idea/idea.cpp +++ b/src/lib/block/idea/idea.cpp @@ -169,7 +169,7 @@ bool IDEA::has_keying_material() const { /* * IDEA Key Schedule */ -void IDEA::key_schedule(std::span key) { +void IDEA::key_schedule(Botan::span key) { m_EK.resize(52); m_DK.resize(52); diff --git a/src/lib/block/idea/idea.h b/src/lib/block/idea/idea.h index 1d484edfb32..5af0fd4f3b7 100644 --- a/src/lib/block/idea/idea.h +++ b/src/lib/block/idea/idea.h @@ -36,7 +36,7 @@ class IDEA final : public Block_Cipher_Fixed_Params<8, 16> { static void sse2_idea_op_8(const uint8_t in[64], uint8_t out[64], const uint16_t EK[52]); #endif - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_EK, m_DK; }; diff --git a/src/lib/block/kuznyechik/kuznyechik.cpp b/src/lib/block/kuznyechik/kuznyechik.cpp index 8dc5f38dc54..5451926148c 100644 --- a/src/lib/block/kuznyechik/kuznyechik.cpp +++ b/src/lib/block/kuznyechik/kuznyechik.cpp @@ -4226,7 +4226,7 @@ bool Kuznyechik::has_keying_material() const { return m_has_keying_material; } -void Kuznyechik::key_schedule(std::span key) { +void Kuznyechik::key_schedule(Botan::span key) { using namespace Kuznyechik_F; BOTAN_ASSERT_NOMSG(key.size() == 32); diff --git a/src/lib/block/kuznyechik/kuznyechik.h b/src/lib/block/kuznyechik/kuznyechik.h index 5363abbace6..1c0dc129d60 100644 --- a/src/lib/block/kuznyechik/kuznyechik.h +++ b/src/lib/block/kuznyechik/kuznyechik.h @@ -30,7 +30,7 @@ class Kuznyechik final : public Botan::Block_Cipher_Fixed_Params<16, 32> { ~Kuznyechik() override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; uint64_t m_rke[10][2]; uint64_t m_rkd[10][2]; bool m_has_keying_material; diff --git a/src/lib/block/lion/lion.cpp b/src/lib/block/lion/lion.cpp index a1261999ee9..8a89bf07aa8 100644 --- a/src/lib/block/lion/lion.cpp +++ b/src/lib/block/lion/lion.cpp @@ -79,7 +79,7 @@ bool Lion::has_keying_material() const { /* * Lion Key Schedule */ -void Lion::key_schedule(std::span key) { +void Lion::key_schedule(Botan::span key) { clear(); const size_t half = key.size() / 2; diff --git a/src/lib/block/lion/lion.h b/src/lib/block/lion/lion.h index 6fb22c0bbc0..d7ea34d3180 100644 --- a/src/lib/block/lion/lion.h +++ b/src/lib/block/lion/lion.h @@ -46,7 +46,7 @@ class Lion final : public BlockCipher { Lion(std::unique_ptr hash, std::unique_ptr cipher, size_t block_size); private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; size_t left_size() const { return m_hash->output_length(); } diff --git a/src/lib/block/noekeon/noekeon.cpp b/src/lib/block/noekeon/noekeon.cpp index acd7587e3d8..6b163ac3441 100644 --- a/src/lib/block/noekeon/noekeon.cpp +++ b/src/lib/block/noekeon/noekeon.cpp @@ -198,7 +198,7 @@ bool Noekeon::has_keying_material() const { /* * Noekeon Key Schedule */ -void Noekeon::key_schedule(std::span key) { +void Noekeon::key_schedule(Botan::span key) { uint32_t A0 = load_be(key.data(), 0); uint32_t A1 = load_be(key.data(), 1); uint32_t A2 = load_be(key.data(), 2); diff --git a/src/lib/block/noekeon/noekeon.h b/src/lib/block/noekeon/noekeon.h index fb0bb6490b3..b57b4456417 100644 --- a/src/lib/block/noekeon/noekeon.h +++ b/src/lib/block/noekeon/noekeon.h @@ -41,7 +41,7 @@ class Noekeon final : public Block_Cipher_Fixed_Params<16, 16> { */ static const uint8_t RC[17]; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_EK, m_DK; }; diff --git a/src/lib/block/seed/seed.cpp b/src/lib/block/seed/seed.cpp index f3b9c7504b2..8cf92cabe3b 100644 --- a/src/lib/block/seed/seed.cpp +++ b/src/lib/block/seed/seed.cpp @@ -153,7 +153,7 @@ bool SEED::has_keying_material() const { /* * SEED Key Schedule */ -void SEED::key_schedule(std::span key) { +void SEED::key_schedule(Botan::span key) { const uint32_t RC[16] = {0x9E3779B9, 0x3C6EF373, 0x78DDE6E6, diff --git a/src/lib/block/seed/seed.h b/src/lib/block/seed/seed.h index 708d658ec5e..3f33a9b5574 100644 --- a/src/lib/block/seed/seed.h +++ b/src/lib/block/seed/seed.h @@ -29,7 +29,7 @@ class SEED final : public Block_Cipher_Fixed_Params<16, 16> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_K; }; diff --git a/src/lib/block/serpent/serpent.cpp b/src/lib/block/serpent/serpent.cpp index 8f4dc308422..bbf9423eedf 100644 --- a/src/lib/block/serpent/serpent.cpp +++ b/src/lib/block/serpent/serpent.cpp @@ -320,7 +320,7 @@ bool Serpent::has_keying_material() const { /* * Serpent Key Schedule */ -void Serpent::key_schedule(std::span key) { +void Serpent::key_schedule(Botan::span key) { using namespace Botan::Serpent_F; const uint32_t PHI = 0x9E3779B9; diff --git a/src/lib/block/serpent/serpent.h b/src/lib/block/serpent/serpent.h index 2c2447064d0..8824305c426 100644 --- a/src/lib/block/serpent/serpent.h +++ b/src/lib/block/serpent/serpent.h @@ -48,7 +48,7 @@ class Serpent final : public Block_Cipher_Fixed_Params<16, 16, 32, 8> { void avx512_decrypt_16(const uint8_t in[16 * 16], uint8_t out[16 * 16]) const; #endif - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_round_key; }; diff --git a/src/lib/block/shacal2/shacal2.cpp b/src/lib/block/shacal2/shacal2.cpp index 9ee092c7e2d..cec558b34f8 100644 --- a/src/lib/block/shacal2/shacal2.cpp +++ b/src/lib/block/shacal2/shacal2.cpp @@ -169,7 +169,7 @@ bool SHACAL2::has_keying_material() const { /* * SHACAL2 Key Schedule */ -void SHACAL2::key_schedule(std::span key) { +void SHACAL2::key_schedule(Botan::span key) { const uint32_t RC[64] = { 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, diff --git a/src/lib/block/shacal2/shacal2.h b/src/lib/block/shacal2/shacal2.h index 50ad76a01ee..240c5059706 100644 --- a/src/lib/block/shacal2/shacal2.h +++ b/src/lib/block/shacal2/shacal2.h @@ -31,7 +31,7 @@ class SHACAL2 final : public Block_Cipher_Fixed_Params<32, 16, 64, 4> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; #if defined(BOTAN_HAS_SHACAL2_SIMD) void simd_encrypt_4(const uint8_t in[], uint8_t out[]) const; diff --git a/src/lib/block/sm4/sm4.cpp b/src/lib/block/sm4/sm4.cpp index ba93d9b80c0..e7f3dd5eb68 100644 --- a/src/lib/block/sm4/sm4.cpp +++ b/src/lib/block/sm4/sm4.cpp @@ -282,7 +282,7 @@ bool SM4::has_keying_material() const { /* * SM4 Key Schedule */ -void SM4::key_schedule(std::span key) { +void SM4::key_schedule(Botan::span key) { // System parameter or family key const uint32_t FK[4] = {0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc}; diff --git a/src/lib/block/sm4/sm4.h b/src/lib/block/sm4/sm4.h index ab510b8c87d..05b0ff66753 100644 --- a/src/lib/block/sm4/sm4.h +++ b/src/lib/block/sm4/sm4.h @@ -31,7 +31,7 @@ class SM4 final : public Block_Cipher_Fixed_Params<16, 16> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; #if defined(BOTAN_HAS_SM4_ARMV8) void sm4_armv8_encrypt(const uint8_t in[], uint8_t out[], size_t blocks) const; diff --git a/src/lib/block/threefish_512/threefish_512.cpp b/src/lib/block/threefish_512/threefish_512.cpp index 5b5f7ce3fc2..f25adc7daae 100644 --- a/src/lib/block/threefish_512/threefish_512.cpp +++ b/src/lib/block/threefish_512/threefish_512.cpp @@ -256,7 +256,7 @@ bool Threefish_512::has_keying_material() const { return !m_K.empty(); } -void Threefish_512::key_schedule(std::span key) { +void Threefish_512::key_schedule(Botan::span key) { // todo: define key schedule for smaller keys m_K.resize(9); diff --git a/src/lib/block/threefish_512/threefish_512.h b/src/lib/block/threefish_512/threefish_512.h index 3549c26c13e..0961fb91d4b 100644 --- a/src/lib/block/threefish_512/threefish_512.h +++ b/src/lib/block/threefish_512/threefish_512.h @@ -31,7 +31,7 @@ class Threefish_512 final : public Block_Cipher_Fixed_Params<64, 64, 0, 1, Tweak bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; // Interface for Skein friend class Skein_512; diff --git a/src/lib/block/twofish/twofish.cpp b/src/lib/block/twofish/twofish.cpp index 1f0101d66e4..b6c3df46f40 100644 --- a/src/lib/block/twofish/twofish.cpp +++ b/src/lib/block/twofish/twofish.cpp @@ -190,7 +190,7 @@ bool Twofish::has_keying_material() const { /* * Twofish Key Schedule */ -void Twofish::key_schedule(std::span key) { +void Twofish::key_schedule(Botan::span key) { m_SB.resize(1024); m_RK.resize(40); diff --git a/src/lib/block/twofish/twofish.h b/src/lib/block/twofish/twofish.h index cd78c736ecc..fd937180892 100644 --- a/src/lib/block/twofish/twofish.h +++ b/src/lib/block/twofish/twofish.h @@ -29,7 +29,7 @@ class Twofish final : public Block_Cipher_Fixed_Params<16, 16, 32, 8> { bool has_keying_material() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; static const uint32_t MDS0[256]; static const uint32_t MDS1[256]; diff --git a/src/lib/codec/base32/base32.h b/src/lib/codec/base32/base32.h index d79fe640b5d..59ae76962c2 100644 --- a/src/lib/codec/base32/base32.h +++ b/src/lib/codec/base32/base32.h @@ -9,7 +9,7 @@ #define BOTAN_BASE32_CODEC_H_ #include -#include +#include #include #include @@ -44,7 +44,7 @@ std::string BOTAN_PUBLIC_API(2, 7) base32_encode(const uint8_t input[], size_t i * @param input some input * @return base32 representation of input */ -inline std::string base32_encode(std::span input) { +inline std::string base32_encode(Botan::span input) { return base32_encode(input.data(), input.size()); } diff --git a/src/lib/codec/base58/base58.h b/src/lib/codec/base58/base58.h index 502d8387187..9307864a8a8 100644 --- a/src/lib/codec/base58/base58.h +++ b/src/lib/codec/base58/base58.h @@ -7,10 +7,10 @@ #ifndef BOTAN_BASE58_CODEC_H_ #define BOTAN_BASE58_CODEC_H_ +#include #include #include -#include #include #include #include @@ -43,11 +43,11 @@ std::vector BOTAN_PUBLIC_API(2, 9) base58_check_decode(const char input // Some convenience wrappers: -inline std::string base58_encode(std::span vec) { +inline std::string base58_encode(Botan::span vec) { return base58_encode(vec.data(), vec.size()); } -inline std::string base58_check_encode(std::span vec) { +inline std::string base58_check_encode(Botan::span vec) { return base58_check_encode(vec.data(), vec.size()); } diff --git a/src/lib/codec/base64/base64.cpp b/src/lib/codec/base64/base64.cpp index b6140c301f0..8ed7fc4ccfa 100644 --- a/src/lib/codec/base64/base64.cpp +++ b/src/lib/codec/base64/base64.cpp @@ -164,7 +164,7 @@ size_t base64_decode(uint8_t output[], std::string_view input, bool ignore_ws) { return base64_decode(output, input.data(), input.length(), ignore_ws); } -size_t base64_decode(std::span output, std::string_view input, bool ignore_ws) { +size_t base64_decode(Botan::span output, std::string_view input, bool ignore_ws) { if(output.size() < base64_decode_max_output(input.size())) { throw Invalid_Argument("base64_decode: output buffer is too short"); } diff --git a/src/lib/codec/base64/base64.h b/src/lib/codec/base64/base64.h index e13e7800f6d..f046f80dfb8 100644 --- a/src/lib/codec/base64/base64.h +++ b/src/lib/codec/base64/base64.h @@ -9,7 +9,7 @@ #define BOTAN_BASE64_CODEC_H_ #include -#include +#include #include #include @@ -44,7 +44,7 @@ std::string BOTAN_PUBLIC_API(2, 0) base64_encode(const uint8_t input[], size_t i * @param input some input * @return base64adecimal representation of input */ -inline std::string base64_encode(std::span input) { +inline std::string base64_encode(Botan::span input) { return base64_encode(input.data(), input.size()); } @@ -100,7 +100,7 @@ size_t BOTAN_PUBLIC_API(3, 0) base64_decode(uint8_t output[], std::string_view i exception if whitespace is encountered * @return number of bytes written to output */ -size_t BOTAN_PUBLIC_API(3, 0) base64_decode(std::span output, std::string_view input, bool ignore_ws = true); +size_t BOTAN_PUBLIC_API(3, 0) base64_decode(Botan::span output, std::string_view input, bool ignore_ws = true); /** * Perform base64 decoding diff --git a/src/lib/codec/hex/hex.cpp b/src/lib/codec/hex/hex.cpp index c151e53ee2b..8431a60117a 100644 --- a/src/lib/codec/hex/hex.cpp +++ b/src/lib/codec/hex/hex.cpp @@ -137,7 +137,7 @@ size_t hex_decode(uint8_t output[], std::string_view input, bool ignore_ws) { return hex_decode(output, input.data(), input.length(), ignore_ws); } -size_t hex_decode(std::span output, std::string_view input, bool ignore_ws) { +size_t hex_decode(Botan::span output, std::string_view input, bool ignore_ws) { return hex_decode(output.data(), input.data(), input.length(), ignore_ws); } diff --git a/src/lib/codec/hex/hex.h b/src/lib/codec/hex/hex.h index 4f810106568..38cbf62e697 100644 --- a/src/lib/codec/hex/hex.h +++ b/src/lib/codec/hex/hex.h @@ -9,7 +9,7 @@ #define BOTAN_HEX_CODEC_H_ #include -#include +#include #include #include @@ -40,7 +40,7 @@ std::string BOTAN_PUBLIC_API(2, 0) hex_encode(const uint8_t input[], size_t inpu * @param uppercase should output be upper or lower case? * @return hexadecimal representation of input */ -inline std::string hex_encode(std::span input, bool uppercase = true) { +inline std::string hex_encode(Botan::span input, bool uppercase = true) { return hex_encode(input.data(), input.size(), uppercase); } @@ -88,7 +88,7 @@ size_t BOTAN_PUBLIC_API(3, 0) hex_decode(uint8_t output[], std::string_view inpu * @param input some hex input * @return number of bytes written to output */ -size_t BOTAN_PUBLIC_API(3, 0) hex_decode(std::span output, std::string_view input, bool ignore_ws = true); +size_t BOTAN_PUBLIC_API(3, 0) hex_decode(Botan::span output, std::string_view input, bool ignore_ws = true); /** * Perform hex decoding diff --git a/src/lib/compression/compress_utils.cpp b/src/lib/compression/compress_utils.cpp index 67d98ce6801..5559bc2f205 100644 --- a/src/lib/compression/compress_utils.cpp +++ b/src/lib/compression/compress_utils.cpp @@ -18,7 +18,7 @@ Compression_Error::Compression_Error(const char* func_name, ErrorType type, int Exception(fmt("Compression API {} failed with return code {}", func_name, rc)), m_type(type), m_rc(rc) {} void* Compression_Alloc_Info::do_malloc(size_t n, size_t size) { - if(!BOTAN_CHECKED_MUL(n, size).has_value()) [[unlikely]] { + if(!BOTAN_CHECKED_MUL(n, size).has_value()) { return nullptr; } diff --git a/src/lib/ffi/ffi_rng.cpp b/src/lib/ffi/ffi_rng.cpp index 9a23cde3672..0b60af142ef 100644 --- a/src/lib/ffi/ffi_rng.cpp +++ b/src/lib/ffi/ffi_rng.cpp @@ -100,7 +100,7 @@ int botan_rng_init_custom(botan_rng_t* rng_out, Custom_RNG& operator=(Custom_RNG&& other) = delete; protected: - void fill_bytes_with_input(std::span output, std::span input) override { + void fill_bytes_with_input(Botan::span output, Botan::span input) override { if(accepts_input() && !input.empty()) { int rc = m_add_entropy_cb(m_context, input.data(), input.size()); if(rc) { diff --git a/src/lib/hash/blake2/blake2b.cpp b/src/lib/hash/blake2/blake2b.cpp index 14673e6dc4e..241b65909d5 100644 --- a/src/lib/hash/blake2/blake2b.cpp +++ b/src/lib/hash/blake2/blake2b.cpp @@ -138,7 +138,7 @@ void BLAKE2b::compress(const uint8_t* input, size_t blocks, uint64_t increment) } } -void BLAKE2b::add_data(std::span input) { +void BLAKE2b::add_data(Botan::span input) { BufferSlicer in(input); while(!in.empty()) { @@ -155,7 +155,7 @@ void BLAKE2b::add_data(std::span input) { } } -void BLAKE2b::final_result(std::span output) { +void BLAKE2b::final_result(Botan::span output) { const auto pos = m_buffer.elements_in_buffer(); m_buffer.fill_up_with_zeros(); @@ -185,7 +185,7 @@ bool BLAKE2b::has_keying_material() const { return m_key_size > 0; } -void BLAKE2b::key_schedule(std::span key) { +void BLAKE2b::key_schedule(Botan::span key) { BOTAN_ASSERT_NOMSG(key.size() <= m_buffer.size()); m_key_size = key.size(); diff --git a/src/lib/hash/blake2/blake2b.h b/src/lib/hash/blake2/blake2b.h index 8e12cc533f7..1f34e8c463d 100644 --- a/src/lib/hash/blake2/blake2b.h +++ b/src/lib/hash/blake2/blake2b.h @@ -49,10 +49,10 @@ class BLAKE2b final : public HashFunction, protected: friend class BLAKE2bMAC; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; private: void state_init(); diff --git a/src/lib/hash/checksum/adler32/adler32.cpp b/src/lib/hash/checksum/adler32/adler32.cpp index af17ae11cd3..9c745ea9857 100644 --- a/src/lib/hash/checksum/adler32/adler32.cpp +++ b/src/lib/hash/checksum/adler32/adler32.cpp @@ -68,7 +68,7 @@ void adler32_update(const uint8_t input[], size_t length, uint16_t& S1, uint16_t /* * Update an Adler32 Checksum */ -void Adler32::add_data(std::span input) { +void Adler32::add_data(Botan::span input) { const size_t PROCESS_AMOUNT = 5552; while(input.size() >= PROCESS_AMOUNT) { @@ -82,7 +82,7 @@ void Adler32::add_data(std::span input) { /* * Finalize an Adler32 Checksum */ -void Adler32::final_result(std::span output) { +void Adler32::final_result(Botan::span output) { store_be(output.data(), m_S2, m_S1); clear(); } diff --git a/src/lib/hash/checksum/adler32/adler32.h b/src/lib/hash/checksum/adler32/adler32.h index 7f7a2bc2dc3..f4c12a942a6 100644 --- a/src/lib/hash/checksum/adler32/adler32.h +++ b/src/lib/hash/checksum/adler32/adler32.h @@ -35,8 +35,8 @@ class Adler32 final : public HashFunction { ~Adler32() override { clear(); } private: - void add_data(std::span) override; - void final_result(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; uint16_t m_S1, m_S2; }; diff --git a/src/lib/hash/checksum/crc24/crc24.cpp b/src/lib/hash/checksum/crc24/crc24.cpp index 1c94a648b1f..12b3a87121c 100644 --- a/src/lib/hash/checksum/crc24/crc24.cpp +++ b/src/lib/hash/checksum/crc24/crc24.cpp @@ -172,7 +172,7 @@ std::unique_ptr CRC24::copy_state() const { * T3[j] = (T2[j] >> 8) ^ T0[ T2[j] & 0xFF ] * */ -void CRC24::add_data(std::span input) { +void CRC24::add_data(Botan::span input) { uint32_t tmp = m_crc; // Input is word aligned if WA & input == 0 @@ -204,7 +204,7 @@ void CRC24::add_data(std::span input) { /* * Finalize a CRC24 Checksum */ -void CRC24::final_result(std::span output) { +void CRC24::final_result(Botan::span output) { output[0] = get_byte<3>(m_crc); output[1] = get_byte<2>(m_crc); output[2] = get_byte<1>(m_crc); diff --git a/src/lib/hash/checksum/crc24/crc24.h b/src/lib/hash/checksum/crc24/crc24.h index 1d940b93994..9915450b785 100644 --- a/src/lib/hash/checksum/crc24/crc24.h +++ b/src/lib/hash/checksum/crc24/crc24.h @@ -35,8 +35,8 @@ class CRC24 final : public HashFunction { ~CRC24() override { clear(); } private: - void add_data(std::span) override; - void final_result(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; uint32_t m_crc; }; diff --git a/src/lib/hash/checksum/crc32/crc32.cpp b/src/lib/hash/checksum/crc32/crc32.cpp index 4e6bfcb6539..2477737f6f5 100644 --- a/src/lib/hash/checksum/crc32/crc32.cpp +++ b/src/lib/hash/checksum/crc32/crc32.cpp @@ -49,7 +49,7 @@ alignas(256) const uint32_t CRC32_T0[256] = { /* * Update a CRC32 Checksum */ -void CRC32::add_data(std::span input) { +void CRC32::add_data(Botan::span input) { uint32_t tmp = m_crc; for(; input.size() >= 16; input = input.last(input.size() - 16)) { tmp = CRC32_T0[(tmp ^ input[0]) & 0xFF] ^ (tmp >> 8); @@ -80,7 +80,7 @@ void CRC32::add_data(std::span input) { /* * Finalize a CRC32 Checksum */ -void CRC32::final_result(std::span output) { +void CRC32::final_result(Botan::span output) { m_crc ^= 0xFFFFFFFF; store_be(m_crc, output.data()); clear(); diff --git a/src/lib/hash/checksum/crc32/crc32.h b/src/lib/hash/checksum/crc32/crc32.h index b53b7991027..38c121b4abc 100644 --- a/src/lib/hash/checksum/crc32/crc32.h +++ b/src/lib/hash/checksum/crc32/crc32.h @@ -32,8 +32,8 @@ class CRC32 final : public HashFunction { ~CRC32() override { clear(); } private: - void add_data(std::span) override; - void final_result(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; uint32_t m_crc; }; diff --git a/src/lib/hash/comb4p/comb4p.cpp b/src/lib/hash/comb4p/comb4p.cpp index a5f7cb22051..163840f8c41 100644 --- a/src/lib/hash/comb4p/comb4p.cpp +++ b/src/lib/hash/comb4p/comb4p.cpp @@ -85,12 +85,12 @@ std::unique_ptr Comb4P::copy_state() const { return copy; } -void Comb4P::add_data(std::span input) { +void Comb4P::add_data(Botan::span input) { m_hash1->update(input); m_hash2->update(input); } -void Comb4P::final_result(std::span output) { +void Comb4P::final_result(Botan::span output) { secure_vector h1 = m_hash1->final(); secure_vector h2 = m_hash2->final(); diff --git a/src/lib/hash/comb4p/comb4p.h b/src/lib/hash/comb4p/comb4p.h index c122f8b3905..6a137bef4ce 100644 --- a/src/lib/hash/comb4p/comb4p.h +++ b/src/lib/hash/comb4p/comb4p.h @@ -39,8 +39,8 @@ class Comb4P final : public HashFunction { private: Comb4P() = default; - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; std::unique_ptr m_hash1, m_hash2; }; diff --git a/src/lib/hash/gost_3411/gost_3411.cpp b/src/lib/hash/gost_3411/gost_3411.cpp index 083cfabf97f..fbd4917e4b3 100644 --- a/src/lib/hash/gost_3411/gost_3411.cpp +++ b/src/lib/hash/gost_3411/gost_3411.cpp @@ -34,7 +34,7 @@ std::unique_ptr GOST_34_11::copy_state() const { /** * Hash additional inputs */ -void GOST_34_11::add_data(std::span input) { +void GOST_34_11::add_data(Botan::span input) { BufferSlicer in(input); while(!in.empty()) { @@ -200,7 +200,7 @@ void GOST_34_11::compress_n(const uint8_t input[], size_t blocks) { /** * Produce the final GOST 34.11 output */ -void GOST_34_11::final_result(std::span out) { +void GOST_34_11::final_result(Botan::span out) { if(!m_buffer.in_alignment()) { m_buffer.fill_up_with_zeros(); compress_n(m_buffer.consume().data(), 1); diff --git a/src/lib/hash/gost_3411/gost_3411.h b/src/lib/hash/gost_3411/gost_3411.h index d58193ed67d..45d2ca8a354 100644 --- a/src/lib/hash/gost_3411/gost_3411.h +++ b/src/lib/hash/gost_3411/gost_3411.h @@ -36,8 +36,8 @@ class GOST_34_11 final : public HashFunction { private: void compress_n(const uint8_t input[], size_t blocks); - void add_data(std::span) override; - void final_result(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; GOST_28147_89 m_cipher; AlignmentBuffer m_buffer; diff --git a/src/lib/hash/keccak/keccak.cpp b/src/lib/hash/keccak/keccak.cpp index 56f1b0be41f..48b74fc1a33 100644 --- a/src/lib/hash/keccak/keccak.cpp +++ b/src/lib/hash/keccak/keccak.cpp @@ -42,11 +42,11 @@ std::string Keccak_1600::provider() const { return m_keccak.provider(); } -void Keccak_1600::add_data(std::span input) { +void Keccak_1600::add_data(Botan::span input) { m_keccak.absorb(input); } -void Keccak_1600::final_result(std::span output) { +void Keccak_1600::final_result(Botan::span output) { m_keccak.finish(); m_keccak.squeeze(output); clear(); diff --git a/src/lib/hash/keccak/keccak.h b/src/lib/hash/keccak/keccak.h index 56c72c4eddc..61f657bf2a4 100644 --- a/src/lib/hash/keccak/keccak.h +++ b/src/lib/hash/keccak/keccak.h @@ -51,8 +51,8 @@ class Keccak_1600 final : public HashFunction { std::string provider() const override; private: - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; private: Keccak_Permutation m_keccak; diff --git a/src/lib/hash/md4/md4.cpp b/src/lib/hash/md4/md4.cpp index 4c6227186f2..e7a44dcea42 100644 --- a/src/lib/hash/md4/md4.cpp +++ b/src/lib/hash/md4/md4.cpp @@ -74,7 +74,7 @@ inline void HH4(uint32_t& A, uint32_t& B, uint32_t& C, uint32_t& D, uint32_t M0, /* * MD4 Compression Function */ -void MD4::compress_n(digest_type& digest, std::span input, size_t blocks) { +void MD4::compress_n(digest_type& digest, Botan::span input, size_t blocks) { uint32_t A = digest[0], B = digest[1], C = digest[2], D = digest[3]; BufferSlicer in(input); @@ -135,11 +135,11 @@ std::unique_ptr MD4::copy_state() const { return std::make_unique(*this); } -void MD4::add_data(std::span input) { +void MD4::add_data(Botan::span input) { m_md.update(input); } -void MD4::final_result(std::span output) { +void MD4::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/md4/md4.h b/src/lib/hash/md4/md4.h index 6cb230c09d7..55b0f7032bc 100644 --- a/src/lib/hash/md4/md4.h +++ b/src/lib/hash/md4/md4.h @@ -25,7 +25,7 @@ class MD4 final : public HashFunction { static constexpr size_t output_bytes = 16; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -42,9 +42,9 @@ class MD4 final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/md5/md5.cpp b/src/lib/hash/md5/md5.cpp index 8f509145bfa..f5f35cd2355 100644 --- a/src/lib/hash/md5/md5.cpp +++ b/src/lib/hash/md5/md5.cpp @@ -59,7 +59,7 @@ inline void II(uint32_t& A, uint32_t B, uint32_t C, uint32_t D, uint32_t M) { /* * MD5 Compression Function */ -void MD5::compress_n(MD5::digest_type& digest, std::span input, size_t blocks) { +void MD5::compress_n(MD5::digest_type& digest, Botan::span input, size_t blocks) { uint32_t A = digest[0], B = digest[1], C = digest[2], D = digest[3]; std::array M; @@ -155,11 +155,11 @@ std::unique_ptr MD5::copy_state() const { return std::make_unique(*this); } -void MD5::add_data(std::span input) { +void MD5::add_data(Botan::span input) { m_md.update(input); } -void MD5::final_result(std::span output) { +void MD5::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/md5/md5.h b/src/lib/hash/md5/md5.h index a61c99d1285..275322e680f 100644 --- a/src/lib/hash/md5/md5.h +++ b/src/lib/hash/md5/md5.h @@ -25,7 +25,7 @@ class MD5 final : public HashFunction { static constexpr size_t output_bytes = 16; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -42,9 +42,9 @@ class MD5 final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/mdx_hash/mdx_hash.h b/src/lib/hash/mdx_hash/mdx_hash.h index 7514b1c9784..0379eed5693 100644 --- a/src/lib/hash/mdx_hash/mdx_hash.h +++ b/src/lib/hash/mdx_hash/mdx_hash.h @@ -22,26 +22,42 @@ enum class MD_Endian { Big, }; +// template +// concept md_hash_implementation = +// concepts::contiguous_container && +// requires(typename T::digest_type& digest, Botan::span input, size_t blocks) { +// { T::init(digest) } -> std::same_as; +// { T::compress_n(digest, input, blocks) } -> std::same_as; +// T::bit_endianness; +// T::byte_endianness; +// T::block_bytes; +// T::output_bytes; +// T::ctr_bytes; +// } && T::block_bytes >= 64 && is_power_of_2(T::block_bytes) && T::output_bytes >= 16 && T::ctr_bytes >= 8 && +// is_power_of_2(T::ctr_bytes) && T::ctr_bytes < T::block_bytes; + template -concept md_hash_implementation = - concepts::contiguous_container && - requires(typename T::digest_type& digest, std::span input, size_t blocks) { - { T::init(digest) } -> std::same_as; - { T::compress_n(digest, input, blocks) } -> std::same_as; - T::bit_endianness; - T::byte_endianness; - T::block_bytes; - T::output_bytes; - T::ctr_bytes; - } && T::block_bytes >= 64 && is_power_of_2(T::block_bytes) && T::output_bytes >= 16 && T::ctr_bytes >= 8 && - is_power_of_2(T::ctr_bytes) && T::ctr_bytes < T::block_bytes; - -template +using md_hash_implementation = std::void_t< + std::enable_if_t && + concepts::same_as_v())), void> && + concepts::same_as_v(), + std::declval>(), + std::declval())), + void>>, + decltype(T::bit_endianness), + decltype(T::byte_endianness), + decltype(T::block_bytes), + decltype(T::output_bytes), + decltype(T::ctr_bytes), + std::enable_if_t<(T::block_bytes >= 64) && is_power_of_2(T::block_bytes) && (T::output_bytes >= 16) && + (T::ctr_bytes >= 8) && is_power_of_2(T::ctr_bytes) && (T::ctr_bytes < T::block_bytes)>>; + +template > class MerkleDamgard_Hash final { public: MerkleDamgard_Hash() { clear(); } - void update(std::span input) { + void update(Botan::span input) { BufferSlicer in(input); while(!in.empty()) { @@ -60,7 +76,7 @@ class MerkleDamgard_Hash final { m_count += input.size(); } - void final(std::span output) { + void final(Botan::span output) { append_padding_bit(); append_counter_and_finalize(); copy_output(output); @@ -110,7 +126,7 @@ class MerkleDamgard_Hash final { MD::compress_n(m_digest, m_buffer.consume(), 1); } - void copy_output(std::span output) { + void copy_output(Botan::span output) { BOTAN_ASSERT_NOMSG(output.size() >= MD::output_bytes); if constexpr(MD::byte_endianness == MD_Endian::Big) { diff --git a/src/lib/hash/par_hash/par_hash.cpp b/src/lib/hash/par_hash/par_hash.cpp index 379790989b2..9ce9ee15f14 100644 --- a/src/lib/hash/par_hash/par_hash.cpp +++ b/src/lib/hash/par_hash/par_hash.cpp @@ -13,13 +13,13 @@ namespace Botan { -void Parallel::add_data(std::span input) { +void Parallel::add_data(Botan::span input) { for(auto&& hash : m_hashes) { hash->update(input); } } -void Parallel::final_result(std::span output) { +void Parallel::final_result(Botan::span output) { BufferStuffer out(output); for(auto&& hash : m_hashes) { hash->final(out.next(hash->output_length())); diff --git a/src/lib/hash/par_hash/par_hash.h b/src/lib/hash/par_hash/par_hash.h index d07fc673206..42e1dec9728 100644 --- a/src/lib/hash/par_hash/par_hash.h +++ b/src/lib/hash/par_hash/par_hash.h @@ -35,8 +35,8 @@ class Parallel final : public HashFunction { Parallel& operator=(const Parallel&) = delete; private: - void add_data(std::span) override; - void final_result(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; std::vector> m_hashes; }; diff --git a/src/lib/hash/rmd160/rmd160.cpp b/src/lib/hash/rmd160/rmd160.cpp index 87b626f3956..5416c220951 100644 --- a/src/lib/hash/rmd160/rmd160.cpp +++ b/src/lib/hash/rmd160/rmd160.cpp @@ -73,7 +73,7 @@ inline void F5(uint32_t& A, uint32_t B, uint32_t& C, uint32_t D, uint32_t E, uin /* * RIPEMD-160 Compression Function */ -void RIPEMD_160::compress_n(digest_type& digest, std::span input, size_t blocks) { +void RIPEMD_160::compress_n(digest_type& digest, Botan::span input, size_t blocks) { const uint32_t MAGIC2 = 0x5A827999, MAGIC3 = 0x6ED9EBA1, MAGIC4 = 0x8F1BBCDC, MAGIC5 = 0xA953FD4E, MAGIC6 = 0x50A28BE6, MAGIC7 = 0x5C4DD124, MAGIC8 = 0x6D703EF3, MAGIC9 = 0x7A6D76E9; std::array M; @@ -272,11 +272,11 @@ std::unique_ptr RIPEMD_160::copy_state() const { return std::make_unique(*this); } -void RIPEMD_160::add_data(std::span input) { +void RIPEMD_160::add_data(Botan::span input) { m_md.update(input); } -void RIPEMD_160::final_result(std::span output) { +void RIPEMD_160::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/rmd160/rmd160.h b/src/lib/hash/rmd160/rmd160.h index 4e3e4e0f384..a5ef192b173 100644 --- a/src/lib/hash/rmd160/rmd160.h +++ b/src/lib/hash/rmd160/rmd160.h @@ -25,7 +25,7 @@ class RIPEMD_160 final : public HashFunction { static constexpr size_t output_bytes = 20; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -42,9 +42,9 @@ class RIPEMD_160 final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/sha1/sha1.cpp b/src/lib/hash/sha1/sha1.cpp index 445faf234c0..3e4a9ff3330 100644 --- a/src/lib/hash/sha1/sha1.cpp +++ b/src/lib/hash/sha1/sha1.cpp @@ -60,7 +60,7 @@ inline void F4(uint32_t A, uint32_t& B, uint32_t C, uint32_t D, uint32_t& E, uin /* * SHA-1 Compression Function */ -void SHA_1::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SHA_1::compress_n(digest_type& digest, Botan::span input, size_t blocks) { using namespace SHA1_F; #if defined(BOTAN_HAS_SHA1_X86_SHA_NI) @@ -230,11 +230,11 @@ std::unique_ptr SHA_1::copy_state() const { return std::make_unique(*this); } -void SHA_1::add_data(std::span input) { +void SHA_1::add_data(Botan::span input) { m_md.update(input); } -void SHA_1::final_result(std::span output) { +void SHA_1::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/sha1/sha1.h b/src/lib/hash/sha1/sha1.h index 1903278df11..ea4c944ef2f 100644 --- a/src/lib/hash/sha1/sha1.h +++ b/src/lib/hash/sha1/sha1.h @@ -25,7 +25,7 @@ class SHA_1 final : public HashFunction { static constexpr size_t output_bytes = 20; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -44,22 +44,22 @@ class SHA_1 final : public HashFunction { void clear() override { m_md.clear(); } #if defined(BOTAN_HAS_SHA1_ARMV8) - static void sha1_armv8_compress_n(digest_type& digest, std::span blocks, size_t block_count); + static void sha1_armv8_compress_n(digest_type& digest, Botan::span blocks, size_t block_count); #endif #if defined(BOTAN_HAS_SHA1_SSE2) - static void sse2_compress_n(digest_type& digest, std::span blocks, size_t block_count); + static void sse2_compress_n(digest_type& digest, Botan::span blocks, size_t block_count); #endif #if defined(BOTAN_HAS_SHA1_X86_SHA_NI) // Using x86 SHA instructions in Intel Goldmont and Cannonlake - static void sha1_compress_x86(digest_type& digest, std::span blocks, size_t block_count); + static void sha1_compress_x86(digest_type& digest, Botan::span blocks, size_t block_count); #endif private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/sha1/sha1_armv8/sha1_armv8.cpp b/src/lib/hash/sha1/sha1_armv8/sha1_armv8.cpp index 913df62559e..f8111358887 100644 --- a/src/lib/hash/sha1/sha1_armv8/sha1_armv8.cpp +++ b/src/lib/hash/sha1/sha1_armv8/sha1_armv8.cpp @@ -16,8 +16,9 @@ namespace Botan { * SHA-1 using CPU instructions in ARMv8 */ //static -BOTAN_FUNC_ISA("+crypto") -void SHA_1::sha1_armv8_compress_n(digest_type& digest, std::span input8, size_t blocks) { +BOTAN_FUNC_ISA("+crypto") void SHA_1::sha1_armv8_compress_n(digest_type& digest, + Botan::span input8, + size_t blocks) { uint32x4_t ABCD; uint32_t E0; diff --git a/src/lib/hash/sha1/sha1_sse2/sha1_sse2.cpp b/src/lib/hash/sha1/sha1_sse2/sha1_sse2.cpp index 566a270809f..a754b09da06 100644 --- a/src/lib/hash/sha1/sha1_sse2/sha1_sse2.cpp +++ b/src/lib/hash/sha1/sha1_sse2/sha1_sse2.cpp @@ -112,7 +112,9 @@ inline void F4(uint32_t A, uint32_t& B, uint32_t C, uint32_t D, uint32_t& E, uin * SHA-1 Compression Function using SSE for message expansion */ //static -BOTAN_FUNC_ISA("sse2") void SHA_1::sse2_compress_n(digest_type& digest, std::span input, size_t blocks) { +BOTAN_FUNC_ISA("sse2") void SHA_1::sse2_compress_n(digest_type& digest, + Botan::span input, + size_t blocks) { using namespace SHA1_SSE2_F; const SIMD_4x32 K00_19 = SIMD_4x32::splat(0x5A827999); diff --git a/src/lib/hash/sha1/sha1_x86/sha1_x86.cpp b/src/lib/hash/sha1/sha1_x86/sha1_x86.cpp index 942f18602cb..01291e69284 100644 --- a/src/lib/hash/sha1/sha1_x86/sha1_x86.cpp +++ b/src/lib/hash/sha1/sha1_x86/sha1_x86.cpp @@ -17,8 +17,9 @@ namespace Botan { -BOTAN_FUNC_ISA("sha,ssse3,sse4.1") -void SHA_1::sha1_compress_x86(digest_type& digest, std::span input, size_t blocks) { +BOTAN_FUNC_ISA("sha,ssse3,sse4.1") void SHA_1::sha1_compress_x86(digest_type& digest, + Botan::span input, + size_t blocks) { const __m128i MASK = _mm_set_epi64x(0x0001020304050607, 0x08090a0b0c0d0e0f); const __m128i* input_mm = reinterpret_cast(input.data()); diff --git a/src/lib/hash/sha2_32/sha2_32.cpp b/src/lib/hash/sha2_32/sha2_32.cpp index c07365052f6..392f890da57 100644 --- a/src/lib/hash/sha2_32/sha2_32.cpp +++ b/src/lib/hash/sha2_32/sha2_32.cpp @@ -46,7 +46,7 @@ std::string sha256_provider() { /* * SHA-224 / SHA-256 compression function */ -void SHA_256::compress_digest(digest_type& digest, std::span input, size_t blocks) { +void SHA_256::compress_digest(digest_type& digest, Botan::span input, size_t blocks) { #if defined(BOTAN_HAS_SHA2_32_X86) if(CPUID::has_intel_sha()) { return SHA_256::compress_digest_x86(digest, input, blocks); @@ -173,7 +173,7 @@ std::string SHA_224::provider() const { return sha256_provider(); } -void SHA_224::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SHA_224::compress_n(digest_type& digest, Botan::span input, size_t blocks) { SHA_256::compress_digest(digest, input, blocks); } @@ -189,11 +189,11 @@ std::unique_ptr SHA_224::copy_state() const { return std::make_unique(*this); } -void SHA_224::add_data(std::span input) { +void SHA_224::add_data(Botan::span input) { m_md.update(input); } -void SHA_224::final_result(std::span output) { +void SHA_224::final_result(Botan::span output) { m_md.final(output); } @@ -201,7 +201,7 @@ std::string SHA_256::provider() const { return sha256_provider(); } -void SHA_256::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SHA_256::compress_n(digest_type& digest, Botan::span input, size_t blocks) { SHA_256::compress_digest(digest, input, blocks); } @@ -217,11 +217,11 @@ std::unique_ptr SHA_256::copy_state() const { return std::make_unique(*this); } -void SHA_256::add_data(std::span input) { +void SHA_256::add_data(Botan::span input) { m_md.update(input); } -void SHA_256::final_result(std::span output) { +void SHA_256::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/sha2_32/sha2_32.h b/src/lib/hash/sha2_32/sha2_32.h index 94eacdf2083..3a7ebb6fc96 100644 --- a/src/lib/hash/sha2_32/sha2_32.h +++ b/src/lib/hash/sha2_32/sha2_32.h @@ -26,7 +26,7 @@ class SHA_224 final : public HashFunction { static constexpr size_t output_bytes = 28; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -45,9 +45,9 @@ class SHA_224 final : public HashFunction { std::string provider() const override; private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; @@ -66,7 +66,7 @@ class SHA_256 final : public HashFunction { static constexpr size_t output_bytes = 32; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -85,24 +85,24 @@ class SHA_256 final : public HashFunction { std::string provider() const override; public: - static void compress_digest(digest_type& digest, std::span input, size_t blocks); + static void compress_digest(digest_type& digest, Botan::span input, size_t blocks); #if defined(BOTAN_HAS_SHA2_32_ARMV8) - static void compress_digest_armv8(digest_type& digest, std::span input, size_t blocks); + static void compress_digest_armv8(digest_type& digest, Botan::span input, size_t blocks); #endif #if defined(BOTAN_HAS_SHA2_32_X86_BMI2) - static void compress_digest_x86_bmi2(digest_type& digest, std::span input, size_t blocks); + static void compress_digest_x86_bmi2(digest_type& digest, Botan::span input, size_t blocks); #endif #if defined(BOTAN_HAS_SHA2_32_X86) - static void compress_digest_x86(digest_type& digest, std::span input, size_t blocks); + static void compress_digest_x86(digest_type& digest, Botan::span input, size_t blocks); #endif private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/sha2_32/sha2_32_armv8/sha2_32_armv8.cpp b/src/lib/hash/sha2_32/sha2_32_armv8/sha2_32_armv8.cpp index e32e3924f87..db84a17b938 100644 --- a/src/lib/hash/sha2_32/sha2_32_armv8/sha2_32_armv8.cpp +++ b/src/lib/hash/sha2_32/sha2_32_armv8/sha2_32_armv8.cpp @@ -18,8 +18,9 @@ namespace Botan { * SHA-256 using CPU instructions in ARMv8 */ //static -BOTAN_FUNC_ISA("+crypto") -void SHA_256::compress_digest_armv8(digest_type& digest, std::span input8, size_t blocks) { +BOTAN_FUNC_ISA("+crypto") void SHA_256::compress_digest_armv8(digest_type& digest, + Botan::span input8, + size_t blocks) { alignas(64) static const uint32_t K[] = { 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, diff --git a/src/lib/hash/sha2_32/sha2_32_bmi2/sha2_32_bmi2.cpp b/src/lib/hash/sha2_32/sha2_32_bmi2/sha2_32_bmi2.cpp index 4b6a67cba26..551f5f6d81b 100644 --- a/src/lib/hash/sha2_32/sha2_32_bmi2/sha2_32_bmi2.cpp +++ b/src/lib/hash/sha2_32/sha2_32_bmi2/sha2_32_bmi2.cpp @@ -21,7 +21,7 @@ flags, GCC and Clang use the BMI2 instructions without further help. Likely instruction scheduling could be improved by using inline asm. */ -void SHA_256::compress_digest_x86_bmi2(digest_type& digest, std::span input, size_t blocks) { +void SHA_256::compress_digest_x86_bmi2(digest_type& digest, Botan::span input, size_t blocks) { uint32_t A = digest[0], B = digest[1], C = digest[2], D = digest[3], E = digest[4], F = digest[5], G = digest[6], H = digest[7]; diff --git a/src/lib/hash/sha2_32/sha2_32_x86/sha2_32_x86.cpp b/src/lib/hash/sha2_32/sha2_32_x86/sha2_32_x86.cpp index 61e9ffb1154..6cd37224b54 100644 --- a/src/lib/hash/sha2_32/sha2_32_x86/sha2_32_x86.cpp +++ b/src/lib/hash/sha2_32/sha2_32_x86/sha2_32_x86.cpp @@ -12,8 +12,9 @@ namespace Botan { // called from sha2_32.cpp -BOTAN_FUNC_ISA("sha,sse4.1,ssse3") -void SHA_256::compress_digest_x86(digest_type& digest, std::span input, size_t blocks) { +BOTAN_FUNC_ISA("sha,sse4.1,ssse3") void SHA_256::compress_digest_x86(digest_type& digest, + Botan::span input, + size_t blocks) { alignas(64) static const uint32_t K[] = { 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, diff --git a/src/lib/hash/sha2_64/sha2_64.cpp b/src/lib/hash/sha2_64/sha2_64.cpp index 148f7ed28d6..af1252fac5d 100644 --- a/src/lib/hash/sha2_64/sha2_64.cpp +++ b/src/lib/hash/sha2_64/sha2_64.cpp @@ -34,7 +34,7 @@ std::string sha512_provider() { * SHA-{384,512} Compression Function */ //static -void SHA_512::compress_digest(digest_type& digest, std::span input, size_t blocks) { +void SHA_512::compress_digest(digest_type& digest, Botan::span input, size_t blocks) { #if defined(BOTAN_HAS_SHA2_64_BMI2) if(CPUID::has_bmi2()) { return compress_digest_bmi2(digest, input, blocks); @@ -170,15 +170,15 @@ std::string SHA_512::provider() const { return sha512_provider(); } -void SHA_512_256::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SHA_512_256::compress_n(digest_type& digest, Botan::span input, size_t blocks) { SHA_512::compress_digest(digest, input, blocks); } -void SHA_384::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SHA_384::compress_n(digest_type& digest, Botan::span input, size_t blocks) { SHA_512::compress_digest(digest, input, blocks); } -void SHA_512::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SHA_512::compress_n(digest_type& digest, Botan::span input, size_t blocks) { SHA_512::compress_digest(digest, input, blocks); } @@ -239,27 +239,27 @@ std::unique_ptr SHA_512_256::copy_state() const { return std::make_unique(*this); } -void SHA_384::add_data(std::span input) { +void SHA_384::add_data(Botan::span input) { m_md.update(input); } -void SHA_512::add_data(std::span input) { +void SHA_512::add_data(Botan::span input) { m_md.update(input); } -void SHA_512_256::add_data(std::span input) { +void SHA_512_256::add_data(Botan::span input) { m_md.update(input); } -void SHA_384::final_result(std::span output) { +void SHA_384::final_result(Botan::span output) { m_md.final(output); } -void SHA_512::final_result(std::span output) { +void SHA_512::final_result(Botan::span output) { m_md.final(output); } -void SHA_512_256::final_result(std::span output) { +void SHA_512_256::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/sha2_64/sha2_64.h b/src/lib/hash/sha2_64/sha2_64.h index 8cd07d337f5..087e4afafde 100644 --- a/src/lib/hash/sha2_64/sha2_64.h +++ b/src/lib/hash/sha2_64/sha2_64.h @@ -25,7 +25,7 @@ class SHA_384 final : public HashFunction { static constexpr size_t output_bytes = 48; static constexpr size_t ctr_bytes = 16; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -44,9 +44,9 @@ class SHA_384 final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; @@ -65,7 +65,7 @@ class SHA_512 final : public HashFunction { static constexpr size_t output_bytes = 64; static constexpr size_t ctr_bytes = 16; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -84,16 +84,16 @@ class SHA_512 final : public HashFunction { void clear() override { m_md.clear(); } public: - static void compress_digest(digest_type& digest, std::span input, size_t blocks); + static void compress_digest(digest_type& digest, Botan::span input, size_t blocks); #if defined(BOTAN_HAS_SHA2_64_BMI2) - static void compress_digest_bmi2(digest_type& digest, std::span input, size_t blocks); + static void compress_digest_bmi2(digest_type& digest, Botan::span input, size_t blocks); #endif private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; @@ -112,7 +112,7 @@ class SHA_512_256 final : public HashFunction { static constexpr size_t output_bytes = 32; static constexpr size_t ctr_bytes = 16; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -131,9 +131,9 @@ class SHA_512_256 final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/sha2_64/sha2_64_bmi2/sha2_64_bmi2.cpp b/src/lib/hash/sha2_64/sha2_64_bmi2/sha2_64_bmi2.cpp index 914b69f56cc..647f11fdd3a 100644 --- a/src/lib/hash/sha2_64/sha2_64_bmi2/sha2_64_bmi2.cpp +++ b/src/lib/hash/sha2_64/sha2_64_bmi2/sha2_64_bmi2.cpp @@ -14,7 +14,7 @@ namespace Botan { -void SHA_512::compress_digest_bmi2(digest_type& digest, std::span input, size_t blocks) { +void SHA_512::compress_digest_bmi2(digest_type& digest, Botan::span input, size_t blocks) { uint64_t A = digest[0], B = digest[1], C = digest[2], D = digest[3], E = digest[4], F = digest[5], G = digest[6], H = digest[7]; diff --git a/src/lib/hash/sha3/sha3.cpp b/src/lib/hash/sha3/sha3.cpp index 3ff45454a34..29b5b0b3d81 100644 --- a/src/lib/hash/sha3/sha3.cpp +++ b/src/lib/hash/sha3/sha3.cpp @@ -43,11 +43,11 @@ void SHA_3::clear() { m_keccak.clear(); } -void SHA_3::add_data(std::span input) { +void SHA_3::add_data(Botan::span input) { m_keccak.absorb(input); } -void SHA_3::final_result(std::span output) { +void SHA_3::final_result(Botan::span output) { m_keccak.finish(); m_keccak.squeeze(output); m_keccak.clear(); diff --git a/src/lib/hash/sha3/sha3.h b/src/lib/hash/sha3/sha3.h index a36853049a8..5b4cb92742e 100644 --- a/src/lib/hash/sha3/sha3.h +++ b/src/lib/hash/sha3/sha3.h @@ -37,8 +37,8 @@ class SHA_3 : public HashFunction { std::string provider() const override; private: - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; private: Keccak_Permutation m_keccak; diff --git a/src/lib/hash/shake/shake.cpp b/src/lib/hash/shake/shake.cpp index 0ad314ed311..3d2fc3dffa0 100644 --- a/src/lib/hash/shake/shake.cpp +++ b/src/lib/hash/shake/shake.cpp @@ -30,11 +30,11 @@ std::unique_ptr SHAKE_128::copy_state() const { return std::make_unique(*this); } -void SHAKE_128::add_data(std::span input) { +void SHAKE_128::add_data(Botan::span input) { m_keccak.absorb(input); } -void SHAKE_128::final_result(std::span output) { +void SHAKE_128::final_result(Botan::span output) { m_keccak.finish(); m_keccak.squeeze(output); clear(); @@ -58,11 +58,11 @@ std::unique_ptr SHAKE_256::copy_state() const { return std::make_unique(*this); } -void SHAKE_256::add_data(std::span input) { +void SHAKE_256::add_data(Botan::span input) { m_keccak.absorb(input); } -void SHAKE_256::final_result(std::span output) { +void SHAKE_256::final_result(Botan::span output) { m_keccak.finish(); m_keccak.squeeze(output); clear(); diff --git a/src/lib/hash/shake/shake.h b/src/lib/hash/shake/shake.h index 97473411f5e..f896f888e57 100644 --- a/src/lib/hash/shake/shake.h +++ b/src/lib/hash/shake/shake.h @@ -39,8 +39,8 @@ class SHAKE_128 final : public HashFunction { std::string provider() const override { return m_keccak.provider(); } private: - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; Keccak_Permutation m_keccak; size_t m_output_bits; @@ -70,8 +70,8 @@ class SHAKE_256 final : public HashFunction { std::string provider() const override { return m_keccak.provider(); } private: - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; Keccak_Permutation m_keccak; size_t m_output_bits; diff --git a/src/lib/hash/skein/skein_512.cpp b/src/lib/hash/skein/skein_512.cpp index 568bfba0b26..9f4a74b944e 100644 --- a/src/lib/hash/skein/skein_512.cpp +++ b/src/lib/hash/skein/skein_512.cpp @@ -115,7 +115,7 @@ void Skein_512::ubi_512(const uint8_t msg[], size_t msg_len) { } while(msg_len); } -void Skein_512::add_data(std::span input) { +void Skein_512::add_data(Botan::span input) { BufferSlicer in(input); while(!in.empty()) { @@ -132,7 +132,7 @@ void Skein_512::add_data(std::span input) { } } -void Skein_512::final_result(std::span out) { +void Skein_512::final_result(Botan::span out) { m_T[1] |= (static_cast(1) << 63); // final block flag const auto pos = m_buffer.elements_in_buffer(); diff --git a/src/lib/hash/skein/skein_512.h b/src/lib/hash/skein/skein_512.h index fc41c98c391..211f37557e5 100644 --- a/src/lib/hash/skein/skein_512.h +++ b/src/lib/hash/skein/skein_512.h @@ -50,8 +50,8 @@ class Skein_512 final : public HashFunction { SKEIN_OUTPUT = 63 }; - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; void ubi_512(const uint8_t msg[], size_t msg_len); diff --git a/src/lib/hash/sm3/sm3.cpp b/src/lib/hash/sm3/sm3.cpp index 2bd4089121f..46c07a247ee 100644 --- a/src/lib/hash/sm3/sm3.cpp +++ b/src/lib/hash/sm3/sm3.cpp @@ -78,7 +78,7 @@ inline uint32_t SM3_E(uint32_t W0, uint32_t W7, uint32_t W13, uint32_t W3, uint3 /* * SM3 Compression Function */ -void SM3::compress_n(digest_type& digest, std::span input, size_t blocks) { +void SM3::compress_n(digest_type& digest, Botan::span input, size_t blocks) { uint32_t A = digest[0], B = digest[1], C = digest[2], D = digest[3], E = digest[4], F = digest[5], G = digest[6], H = digest[7]; @@ -245,11 +245,11 @@ std::unique_ptr SM3::copy_state() const { return std::make_unique(*this); } -void SM3::add_data(std::span input) { +void SM3::add_data(Botan::span input) { m_md.update(input); } -void SM3::final_result(std::span output) { +void SM3::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/sm3/sm3.h b/src/lib/hash/sm3/sm3.h index 8e97208cd17..4b7a0ce48e0 100644 --- a/src/lib/hash/sm3/sm3.h +++ b/src/lib/hash/sm3/sm3.h @@ -25,7 +25,7 @@ class SM3 final : public HashFunction { static constexpr size_t output_bytes = 32; static constexpr size_t ctr_bytes = 8; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -42,9 +42,9 @@ class SM3 final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/hash/streebog/streebog.cpp b/src/lib/hash/streebog/streebog.cpp index 2a89d672d6a..0cb4ed88cd5 100644 --- a/src/lib/hash/streebog/streebog.cpp +++ b/src/lib/hash/streebog/streebog.cpp @@ -49,7 +49,7 @@ void Streebog::clear() { /* * Update the hash */ -void Streebog::add_data(std::span input) { +void Streebog::add_data(Botan::span input) { BufferSlicer in(input); while(!in.empty()) { @@ -70,7 +70,7 @@ void Streebog::add_data(std::span input) { /* * Finalize a hash */ -void Streebog::final_result(std::span output) { +void Streebog::final_result(Botan::span output) { const auto pos = m_buffer.elements_in_buffer(); const uint8_t padding = 0x01; diff --git a/src/lib/hash/streebog/streebog.h b/src/lib/hash/streebog/streebog.h index 9420ba3ebd4..f32182bd40a 100644 --- a/src/lib/hash/streebog/streebog.h +++ b/src/lib/hash/streebog/streebog.h @@ -34,8 +34,8 @@ class Streebog final : public HashFunction { explicit Streebog(size_t output_bits); protected: - void add_data(std::span input) override; - void final_result(std::span out) override; + void add_data(Botan::span input) override; + void final_result(Botan::span out) override; void compress(const uint8_t input[], bool lastblock = false); diff --git a/src/lib/hash/trunc_hash/trunc_hash.cpp b/src/lib/hash/trunc_hash/trunc_hash.cpp index 869f365ac7d..749f0ee1a34 100644 --- a/src/lib/hash/trunc_hash/trunc_hash.cpp +++ b/src/lib/hash/trunc_hash/trunc_hash.cpp @@ -13,11 +13,11 @@ namespace Botan { -void Truncated_Hash::add_data(std::span input) { +void Truncated_Hash::add_data(Botan::span input) { m_hash->update(input); } -void Truncated_Hash::final_result(std::span out) { +void Truncated_Hash::final_result(Botan::span out) { BOTAN_ASSERT_NOMSG(m_hash->output_length() * 8 >= m_output_bits); m_hash->final(m_buffer); diff --git a/src/lib/hash/trunc_hash/trunc_hash.h b/src/lib/hash/trunc_hash/trunc_hash.h index f5047d03932..606b948456a 100644 --- a/src/lib/hash/trunc_hash/trunc_hash.h +++ b/src/lib/hash/trunc_hash/trunc_hash.h @@ -36,8 +36,8 @@ class Truncated_Hash final : public HashFunction { Truncated_Hash(std::unique_ptr hash, size_t length); private: - void add_data(std::span) override; - void final_result(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; std::unique_ptr m_hash; size_t m_output_bits; diff --git a/src/lib/hash/whirlpool/whirlpool.cpp b/src/lib/hash/whirlpool/whirlpool.cpp index c0e7fb0e813..2f4b7285a37 100644 --- a/src/lib/hash/whirlpool/whirlpool.cpp +++ b/src/lib/hash/whirlpool/whirlpool.cpp @@ -87,7 +87,7 @@ uint64_t whirl(uint64_t x0, uint64_t x1, uint64_t x2, uint64_t x3, uint64_t x4, /* * Whirlpool Compression Function */ -void Whirlpool::compress_n(digest_type& digest, std::span input, size_t blocks) { +void Whirlpool::compress_n(digest_type& digest, Botan::span input, size_t blocks) { static const uint64_t RC[10] = {0x1823C6E887B8014F, 0x36A6D2F5796F9152, 0x60BC9B8EA30C7B35, @@ -192,11 +192,11 @@ std::unique_ptr Whirlpool::copy_state() const { return std::make_unique(*this); } -void Whirlpool::add_data(std::span input) { +void Whirlpool::add_data(Botan::span input) { m_md.update(input); } -void Whirlpool::final_result(std::span output) { +void Whirlpool::final_result(Botan::span output) { m_md.final(output); } diff --git a/src/lib/hash/whirlpool/whirlpool.h b/src/lib/hash/whirlpool/whirlpool.h index e037e316c6c..51bf4c72ab6 100644 --- a/src/lib/hash/whirlpool/whirlpool.h +++ b/src/lib/hash/whirlpool/whirlpool.h @@ -25,7 +25,7 @@ class Whirlpool final : public HashFunction { static constexpr size_t output_bytes = 64; static constexpr size_t ctr_bytes = 32; - static void compress_n(digest_type& digest, std::span input, size_t blocks); + static void compress_n(digest_type& digest, Botan::span input, size_t blocks); static void init(digest_type& digest); public: @@ -42,9 +42,9 @@ class Whirlpool final : public HashFunction { void clear() override { m_md.clear(); } private: - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span output) override; + void final_result(Botan::span output) override; private: MerkleDamgard_Hash m_md; diff --git a/src/lib/kdf/kdf.h b/src/lib/kdf/kdf.h index 7645728f5e5..fd9fd95bcbd 100644 --- a/src/lib/kdf/kdf.h +++ b/src/lib/kdf/kdf.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -81,7 +81,7 @@ class BOTAN_PUBLIC_API(2, 0) KDF { * @param label_len size of label in bytes * @return the derived key */ - template > + template , typename = concepts::resizable_byte_buffer> T derive_key(size_t key_len, const uint8_t secret[], size_t secret_len, @@ -102,9 +102,9 @@ class BOTAN_PUBLIC_API(2, 0) KDF { * @param label purpose for the derived keying material * @return the derived key */ - template > + template , typename = concepts::resizable_byte_buffer> T derive_key(size_t key_len, - std::span secret, + Botan::span secret, std::string_view salt = "", std::string_view label = "") const { return derive_key(key_len, @@ -123,10 +123,10 @@ class BOTAN_PUBLIC_API(2, 0) KDF { * @param salt a diversifier * @param label purpose for the derived keying material */ - void derive_key(std::span key, - std::span secret, - std::span salt, - std::span label) const { + void derive_key(Botan::span key, + Botan::span secret, + Botan::span salt, + Botan::span label) const { return kdf( key.data(), key.size(), secret.data(), secret.size(), salt.data(), salt.size(), label.data(), label.size()); } @@ -139,11 +139,11 @@ class BOTAN_PUBLIC_API(2, 0) KDF { * @param label purpose for the derived keying material * @return the derived key */ - template > + template , typename = concepts::resizable_byte_buffer> T derive_key(size_t key_len, - std::span secret, - std::span salt, - std::span label) const { + Botan::span secret, + Botan::span salt, + Botan::span label) const { return derive_key( key_len, secret.data(), secret.size(), salt.data(), salt.size(), label.data(), label.size()); } @@ -157,9 +157,9 @@ class BOTAN_PUBLIC_API(2, 0) KDF { * @param label purpose for the derived keying material * @return the derived key */ - template > + template , typename = concepts::resizable_byte_buffer> T derive_key(size_t key_len, - std::span secret, + Botan::span secret, const uint8_t salt[], size_t salt_len, std::string_view label = "") const { @@ -176,7 +176,7 @@ class BOTAN_PUBLIC_API(2, 0) KDF { * @param label purpose for the derived keying material * @return the derived key */ - template > + template , typename = concepts::resizable_byte_buffer> T derive_key(size_t key_len, const uint8_t secret[], size_t secret_len, diff --git a/src/lib/kdf/sp800_56a/sp800_56a.cpp b/src/lib/kdf/sp800_56a/sp800_56a.cpp index 834201d96bb..d2afbcecd53 100644 --- a/src/lib/kdf/sp800_56a/sp800_56a.cpp +++ b/src/lib/kdf/sp800_56a/sp800_56a.cpp @@ -9,6 +9,7 @@ #include #include +#include #include namespace Botan { @@ -77,7 +78,7 @@ std::unique_ptr SP800_56A_Hash::new_object() const { SP800_56A_HMAC::SP800_56A_HMAC(std::unique_ptr mac) : m_mac(std::move(mac)) { // TODO: we need a MessageAuthenticationCode::is_hmac - if(!m_mac->name().starts_with("HMAC(")) { + if(!starts_with(m_mac->name(), "HMAC(")) { throw Algorithm_Not_Found("Only HMAC can be used with KDF SP800-56A"); } } diff --git a/src/lib/mac/blake2mac/blake2bmac.h b/src/lib/mac/blake2mac/blake2bmac.h index c61ebdbd52f..15af7b26126 100644 --- a/src/lib/mac/blake2mac/blake2bmac.h +++ b/src/lib/mac/blake2mac/blake2bmac.h @@ -37,14 +37,14 @@ class BLAKE2bMAC final : public MessageAuthenticationCode { Key_Length_Specification key_spec() const override { return m_blake.key_spec(); } private: - void key_schedule(std::span key) override { m_blake.set_key(key); } + void key_schedule(Botan::span key) override { m_blake.set_key(key); } - void add_data(std::span input) override { + void add_data(Botan::span input) override { assert_key_material_set(); m_blake.update(input); } - void final_result(std::span out) override { + void final_result(Botan::span out) override { assert_key_material_set(); m_blake.final(out); } diff --git a/src/lib/mac/cmac/cmac.cpp b/src/lib/mac/cmac/cmac.cpp index 26aefaf8e64..8d0db06f80f 100644 --- a/src/lib/mac/cmac/cmac.cpp +++ b/src/lib/mac/cmac/cmac.cpp @@ -17,7 +17,7 @@ namespace Botan { /* * Update an CMAC Calculation */ -void CMAC::add_data(std::span input) { +void CMAC::add_data(Botan::span input) { const size_t bs = output_length(); buffer_insert(m_buffer, m_position, input.data(), input.size()); @@ -43,7 +43,7 @@ void CMAC::add_data(std::span input) { /* * Finalize an CMAC Calculation */ -void CMAC::final_result(std::span mac) { +void CMAC::final_result(Botan::span mac) { xor_buf(m_state, m_buffer, m_position); if(m_position == output_length()) { @@ -69,7 +69,7 @@ bool CMAC::has_keying_material() const { /* * CMAC Key Schedule */ -void CMAC::key_schedule(std::span key) { +void CMAC::key_schedule(Botan::span key) { clear(); m_cipher->set_key(key); m_cipher->encrypt(m_B); diff --git a/src/lib/mac/cmac/cmac.h b/src/lib/mac/cmac/cmac.h index 2b6b0536cfb..8ec0400b310 100644 --- a/src/lib/mac/cmac/cmac.h +++ b/src/lib/mac/cmac/cmac.h @@ -38,9 +38,9 @@ class CMAC final : public MessageAuthenticationCode { CMAC& operator=(const CMAC&) = delete; private: - void add_data(std::span) override; - void final_result(std::span) override; - void key_schedule(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; + void key_schedule(Botan::span) override; std::unique_ptr m_cipher; secure_vector m_buffer, m_state, m_B, m_P; diff --git a/src/lib/mac/gmac/gmac.cpp b/src/lib/mac/gmac/gmac.cpp index 20688e32dfe..1eadc7b7113 100644 --- a/src/lib/mac/gmac/gmac.cpp +++ b/src/lib/mac/gmac/gmac.cpp @@ -41,7 +41,7 @@ size_t GMAC::output_length() const { return GCM_BS; } -void GMAC::add_data(std::span input) { +void GMAC::add_data(Botan::span input) { BufferSlicer in(input); while(!in.empty()) { @@ -62,7 +62,7 @@ bool GMAC::has_keying_material() const { return m_cipher->has_keying_material(); } -void GMAC::key_schedule(std::span key) { +void GMAC::key_schedule(Botan::span key) { clear(); m_cipher->set_key(key); @@ -70,7 +70,7 @@ void GMAC::key_schedule(std::span key) { m_ghash->set_key(m_H); } -void GMAC::start_msg(std::span nonce) { +void GMAC::start_msg(Botan::span nonce) { secure_vector y0(GCM_BS); if(nonce.size() == 12) { @@ -87,7 +87,7 @@ void GMAC::start_msg(std::span nonce) { m_initialized = true; } -void GMAC::final_result(std::span mac) { +void GMAC::final_result(Botan::span mac) { // This ensures the GMAC computation has been initialized with a fresh // nonce. The aim of this check is to prevent developers from re-using // nonces (and potential nonce-reuse attacks). diff --git a/src/lib/mac/gmac/gmac.h b/src/lib/mac/gmac/gmac.h index a5ddaa28134..143388b9705 100644 --- a/src/lib/mac/gmac/gmac.h +++ b/src/lib/mac/gmac/gmac.h @@ -47,10 +47,10 @@ class GMAC final : public MessageAuthenticationCode { ~GMAC() override; private: - void add_data(std::span) override; - void final_result(std::span) override; - void start_msg(std::span nonce) override; - void key_schedule(std::span key) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; + void start_msg(Botan::span nonce) override; + void key_schedule(Botan::span key) override; static const size_t GCM_BS = 16; std::unique_ptr m_cipher; diff --git a/src/lib/mac/hmac/hmac.cpp b/src/lib/mac/hmac/hmac.cpp index aa690a3d467..aec8087028a 100644 --- a/src/lib/mac/hmac/hmac.cpp +++ b/src/lib/mac/hmac/hmac.cpp @@ -16,7 +16,7 @@ namespace Botan { /* * Update a HMAC Calculation */ -void HMAC::add_data(std::span input) { +void HMAC::add_data(Botan::span input) { assert_key_material_set(); m_hash->update(input); } @@ -24,7 +24,7 @@ void HMAC::add_data(std::span input) { /* * Finalize a HMAC Calculation */ -void HMAC::final_result(std::span mac) { +void HMAC::final_result(Botan::span mac) { assert_key_material_set(); m_hash->final(mac); m_hash->update(m_okey); @@ -49,7 +49,7 @@ bool HMAC::has_keying_material() const { /* * HMAC Key Schedule */ -void HMAC::key_schedule(std::span key) { +void HMAC::key_schedule(Botan::span key) { const uint8_t ipad = 0x36; const uint8_t opad = 0x5C; diff --git a/src/lib/mac/hmac/hmac.h b/src/lib/mac/hmac/hmac.h index 8a9c66e1082..d05f5a08aaa 100644 --- a/src/lib/mac/hmac/hmac.h +++ b/src/lib/mac/hmac/hmac.h @@ -37,9 +37,9 @@ class HMAC final : public MessageAuthenticationCode { HMAC& operator=(const HMAC&) = delete; private: - void add_data(std::span) override; - void final_result(std::span) override; - void key_schedule(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; + void key_schedule(Botan::span) override; std::unique_ptr m_hash; secure_vector m_ikey, m_okey; diff --git a/src/lib/mac/kmac/kmac.cpp b/src/lib/mac/kmac/kmac.cpp index 437aa2f24d7..b9336b57bcd 100644 --- a/src/lib/mac/kmac/kmac.cpp +++ b/src/lib/mac/kmac/kmac.cpp @@ -51,14 +51,14 @@ std::string KMAC::provider() const { return m_cshake->provider(); } -void KMAC::start_msg(std::span nonce) { +void KMAC::start_msg(Botan::span nonce) { assert_key_material_set(); m_cshake->start(nonce); m_cshake->update(m_encoded_key); m_message_started = true; } -void KMAC::add_data(std::span data) { +void KMAC::add_data(Botan::span data) { assert_key_material_set(!m_encoded_key.empty()); if(!m_message_started) { start(); @@ -66,7 +66,7 @@ void KMAC::add_data(std::span data) { m_cshake->update(data); } -void KMAC::final_result(std::span output) { +void KMAC::final_result(Botan::span output) { assert_key_material_set(); std::array encoded_output_length_buffer; m_cshake->update(keccak_int_right_encode(encoded_output_length_buffer, m_output_bit_length)); @@ -75,7 +75,7 @@ void KMAC::final_result(std::span output) { m_message_started = false; } -void KMAC::key_schedule(std::span key) { +void KMAC::key_schedule(Botan::span key) { clear(); keccak_absorb_padded_strings_encoding(m_encoded_key, m_cshake->block_size(), key); } diff --git a/src/lib/mac/kmac/kmac.h b/src/lib/mac/kmac/kmac.h index 8f3a95396a2..10029682b54 100644 --- a/src/lib/mac/kmac/kmac.h +++ b/src/lib/mac/kmac/kmac.h @@ -34,10 +34,10 @@ class KMAC : public MessageAuthenticationCode { std::string provider() const final; private: - void start_msg(std::span nonce) final; - void add_data(std::span) final; - void final_result(std::span) final; - void key_schedule(std::span) final; + void start_msg(Botan::span nonce) final; + void add_data(Botan::span) final; + void final_result(Botan::span) final; + void key_schedule(Botan::span) final; private: size_t m_output_bit_length; diff --git a/src/lib/mac/mac.cpp b/src/lib/mac/mac.cpp index c05cdb901b5..4231b27aefa 100644 --- a/src/lib/mac/mac.cpp +++ b/src/lib/mac/mac.cpp @@ -152,7 +152,7 @@ std::unique_ptr MessageAuthenticationCode::create_or_ throw Lookup_Error("MAC", algo, provider); } -void MessageAuthenticationCode::start_msg(std::span nonce) { +void MessageAuthenticationCode::start_msg(Botan::span nonce) { BOTAN_UNUSED(nonce); if(!nonce.empty()) { throw Invalid_IV_Length(name(), nonce.size()); @@ -162,7 +162,7 @@ void MessageAuthenticationCode::start_msg(std::span nonce) { /* * Default (deterministic) MAC verification operation */ -bool MessageAuthenticationCode::verify_mac_result(std::span mac) { +bool MessageAuthenticationCode::verify_mac_result(Botan::span mac) { secure_vector our_mac = final(); if(our_mac.size() != mac.size()) { diff --git a/src/lib/mac/mac.h b/src/lib/mac/mac.h index 65dc91bcc49..dc02fe6d9e5 100644 --- a/src/lib/mac/mac.h +++ b/src/lib/mac/mac.h @@ -9,9 +9,9 @@ #define BOTAN_MESSAGE_AUTH_CODE_BASE_H_ #include +#include #include #include -#include #include namespace Botan { @@ -62,7 +62,7 @@ class BOTAN_PUBLIC_API(2, 0) MessageAuthenticationCode : public Buffered_Computa * * @param nonce the message nonce bytes */ - void start(std::span nonce) { start_msg(nonce); } + void start(Botan::span nonce) { start_msg(nonce); } /** * Begin processing a message. @@ -89,7 +89,7 @@ class BOTAN_PUBLIC_API(2, 0) MessageAuthenticationCode : public Buffered_Computa * @param in the MAC to verify as a byte array * @return true if the MAC is valid, false otherwise */ - bool verify_mac(std::span in) { return verify_mac_result(in); } + bool verify_mac(Botan::span in) { return verify_mac_result(in); } /** * @return new object representing the same algorithm as *this @@ -122,12 +122,12 @@ class BOTAN_PUBLIC_API(2, 0) MessageAuthenticationCode : public Buffered_Computa * If the MAC does not support nonces, it should not override the default * implementation. */ - virtual void start_msg(std::span nonce); + virtual void start_msg(Botan::span nonce); /** * Verify the MACs final result */ - virtual bool verify_mac_result(std::span in); + virtual bool verify_mac_result(Botan::span in); }; typedef MessageAuthenticationCode MAC; diff --git a/src/lib/mac/poly1305/poly1305.cpp b/src/lib/mac/poly1305/poly1305.cpp index e24d04d0918..f12cf205645 100644 --- a/src/lib/mac/poly1305/poly1305.cpp +++ b/src/lib/mac/poly1305/poly1305.cpp @@ -25,7 +25,7 @@ void poly1305_init(secure_vector& X, const uint8_t key[32]) { const uint64_t t0 = load_le(key, 0); const uint64_t t1 = load_le(key, 1); - X[0] = (t0)&0xffc0fffffff; + X[0] = (t0) & 0xffc0fffffff; X[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff; X[2] = ((t1 >> 24)) & 0x00ffffffc0f; @@ -172,7 +172,7 @@ bool Poly1305::has_keying_material() const { return m_poly.size() == 8; } -void Poly1305::key_schedule(std::span key) { +void Poly1305::key_schedule(Botan::span key) { m_buf_pos = 0; m_buf.resize(16); m_poly.resize(8); @@ -180,7 +180,7 @@ void Poly1305::key_schedule(std::span key) { poly1305_init(m_poly, key.data()); } -void Poly1305::add_data(std::span input) { +void Poly1305::add_data(Botan::span input) { assert_key_material_set(); if(m_buf_pos) { @@ -205,7 +205,7 @@ void Poly1305::add_data(std::span input) { m_buf_pos += remaining.size(); } -void Poly1305::final_result(std::span out) { +void Poly1305::final_result(Botan::span out) { assert_key_material_set(); if(m_buf_pos != 0) { diff --git a/src/lib/mac/poly1305/poly1305.h b/src/lib/mac/poly1305/poly1305.h index 38e442e920e..1c650d33c6f 100644 --- a/src/lib/mac/poly1305/poly1305.h +++ b/src/lib/mac/poly1305/poly1305.h @@ -34,9 +34,9 @@ class Poly1305 final : public MessageAuthenticationCode { bool has_keying_material() const override; private: - void add_data(std::span) override; - void final_result(std::span) override; - void key_schedule(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; + void key_schedule(Botan::span) override; secure_vector m_poly; secure_vector m_buf; diff --git a/src/lib/mac/siphash/siphash.cpp b/src/lib/mac/siphash/siphash.cpp index 60c97edd178..f808a11cdab 100644 --- a/src/lib/mac/siphash/siphash.cpp +++ b/src/lib/mac/siphash/siphash.cpp @@ -47,7 +47,7 @@ void SipRounds(uint64_t M, secure_vector& V, size_t r) { } // namespace -void SipHash::add_data(std::span input) { +void SipHash::add_data(Botan::span input) { assert_key_material_set(); // SipHash counts the message length mod 256 @@ -78,7 +78,7 @@ void SipHash::add_data(std::span input) { } } -void SipHash::final_result(std::span mac) { +void SipHash::final_result(Botan::span mac) { assert_key_material_set(); if(m_mbuf_pos == 0) { @@ -109,7 +109,7 @@ bool SipHash::has_keying_material() const { return !m_V.empty(); } -void SipHash::key_schedule(std::span key) { +void SipHash::key_schedule(Botan::span key) { const uint64_t K0 = load_le(key.data(), 0); const uint64_t K1 = load_le(key.data(), 1); diff --git a/src/lib/mac/siphash/siphash.h b/src/lib/mac/siphash/siphash.h index 7184ac58db8..30e9e3db7d2 100644 --- a/src/lib/mac/siphash/siphash.h +++ b/src/lib/mac/siphash/siphash.h @@ -28,9 +28,9 @@ class SipHash final : public MessageAuthenticationCode { Key_Length_Specification key_spec() const override { return Key_Length_Specification(16); } private: - void add_data(std::span) override; - void final_result(std::span) override; - void key_schedule(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; + void key_schedule(Botan::span) override; const size_t m_C, m_D; secure_vector m_K; diff --git a/src/lib/mac/x919_mac/x919_mac.cpp b/src/lib/mac/x919_mac/x919_mac.cpp index db82f1f475e..4eb3f21ecda 100644 --- a/src/lib/mac/x919_mac/x919_mac.cpp +++ b/src/lib/mac/x919_mac/x919_mac.cpp @@ -14,7 +14,7 @@ namespace Botan { /* * Update an ANSI X9.19 MAC Calculation */ -void ANSI_X919_MAC::add_data(std::span input) { +void ANSI_X919_MAC::add_data(Botan::span input) { assert_key_material_set(); BufferSlicer in(input); @@ -41,7 +41,7 @@ void ANSI_X919_MAC::add_data(std::span input) { /* * Finalize an ANSI X9.19 MAC Calculation */ -void ANSI_X919_MAC::final_result(std::span mac) { +void ANSI_X919_MAC::final_result(Botan::span mac) { if(m_position) { m_des1->encrypt(m_state); } @@ -58,7 +58,7 @@ bool ANSI_X919_MAC::has_keying_material() const { /* * ANSI X9.19 MAC Key Schedule */ -void ANSI_X919_MAC::key_schedule(std::span key) { +void ANSI_X919_MAC::key_schedule(Botan::span key) { m_state.resize(8); m_des1->set_key(key.first(8)); diff --git a/src/lib/mac/x919_mac/x919_mac.h b/src/lib/mac/x919_mac/x919_mac.h index 3124f8819f4..6b8b754100d 100644 --- a/src/lib/mac/x919_mac/x919_mac.h +++ b/src/lib/mac/x919_mac/x919_mac.h @@ -35,9 +35,9 @@ class ANSI_X919_MAC final : public MessageAuthenticationCode { ANSI_X919_MAC& operator=(const ANSI_X919_MAC&) = delete; private: - void add_data(std::span) override; - void final_result(std::span) override; - void key_schedule(std::span) override; + void add_data(Botan::span) override; + void final_result(Botan::span) override; + void key_schedule(Botan::span) override; std::unique_ptr m_des1, m_des2; secure_vector m_state; diff --git a/src/lib/math/bigint/big_code.cpp b/src/lib/math/bigint/big_code.cpp index c7822198b87..e978ee5e77f 100644 --- a/src/lib/math/bigint/big_code.cpp +++ b/src/lib/math/bigint/big_code.cpp @@ -112,7 +112,7 @@ secure_vector BigInt::encode_1363(const BigInt& n, size_t bytes) { return output; } -void BigInt::encode_1363(std::span output, const BigInt& n) { +void BigInt::encode_1363(Botan::span output, const BigInt& n) { if(n.bytes() > output.size()) { throw Encoding_Error("encode_1363: n is too large to encode properly"); } diff --git a/src/lib/math/bigint/bigint.h b/src/lib/math/bigint/bigint.h index 23febfac589..f2c459da2ae 100644 --- a/src/lib/math/bigint/bigint.h +++ b/src/lib/math/bigint/bigint.h @@ -804,7 +804,7 @@ class BOTAN_PUBLIC_API(2, 0) BigInt final { * @result a secure_vector containing the encoded BigInt */ static secure_vector encode_1363(const BigInt& n, size_t bytes); - static void encode_1363(std::span out, const BigInt& n); + static void encode_1363(Botan::span out, const BigInt& n); static void encode_1363(uint8_t out[], size_t bytes, const BigInt& n); @@ -964,19 +964,19 @@ inline BigInt operator-(const BigInt& x, word y) { return BigInt::add2(x, &y, 1, BigInt::Negative); } -BigInt BOTAN_PUBLIC_API(2, 0) operator*(const BigInt& x, const BigInt& y); -BigInt BOTAN_PUBLIC_API(2, 8) operator*(const BigInt& x, word y); +BigInt BOTAN_PUBLIC_API(2, 0) operator*(const BigInt & x, const BigInt & y); +BigInt BOTAN_PUBLIC_API(2, 8) operator*(const BigInt & x, word y); inline BigInt operator*(word x, const BigInt& y) { return y * x; } -BigInt BOTAN_PUBLIC_API(2, 0) operator/(const BigInt& x, const BigInt& d); -BigInt BOTAN_PUBLIC_API(2, 0) operator/(const BigInt& x, word m); -BigInt BOTAN_PUBLIC_API(2, 0) operator%(const BigInt& x, const BigInt& m); -word BOTAN_PUBLIC_API(2, 0) operator%(const BigInt& x, word m); -BigInt BOTAN_PUBLIC_API(2, 0) operator<<(const BigInt& x, size_t n); -BigInt BOTAN_PUBLIC_API(2, 0) operator>>(const BigInt& x, size_t n); +BigInt BOTAN_PUBLIC_API(2, 0) operator/(const BigInt & x, const BigInt & d); +BigInt BOTAN_PUBLIC_API(2, 0) operator/(const BigInt & x, word m); +BigInt BOTAN_PUBLIC_API(2, 0) operator%(const BigInt & x, const BigInt & m); +word BOTAN_PUBLIC_API(2, 0) operator%(const BigInt & x, word m); +BigInt BOTAN_PUBLIC_API(2, 0) operator<<(const BigInt & x, size_t n); +BigInt BOTAN_PUBLIC_API(2, 0) operator>>(const BigInt & x, size_t n); /* * Comparison Operators diff --git a/src/lib/misc/fpe_fe1/fpe_fe1.cpp b/src/lib/misc/fpe_fe1/fpe_fe1.cpp index 64d00e8d10d..3df4c499cbc 100644 --- a/src/lib/misc/fpe_fe1/fpe_fe1.cpp +++ b/src/lib/misc/fpe_fe1/fpe_fe1.cpp @@ -104,7 +104,7 @@ bool FPE_FE1::has_keying_material() const { return m_mac->has_keying_material(); } -void FPE_FE1::key_schedule(std::span key) { +void FPE_FE1::key_schedule(Botan::span key) { m_mac->set_key(key); } diff --git a/src/lib/misc/fpe_fe1/fpe_fe1.h b/src/lib/misc/fpe_fe1/fpe_fe1.h index d27cdc517ee..3d01ba6e047 100644 --- a/src/lib/misc/fpe_fe1/fpe_fe1.h +++ b/src/lib/misc/fpe_fe1/fpe_fe1.h @@ -67,7 +67,7 @@ class BOTAN_PUBLIC_API(2, 5) FPE_FE1 final : public SymmetricAlgorithm { BigInt decrypt(const BigInt& x, uint64_t tweak) const; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; BigInt F(const BigInt& R, size_t round, const secure_vector& tweak, secure_vector& tmp) const; diff --git a/src/lib/misc/roughtime/roughtime.cpp b/src/lib/misc/roughtime/roughtime.cpp index 2f32494496a..18823e5a417 100644 --- a/src/lib/misc/roughtime/roughtime.cpp +++ b/src/lib/misc/roughtime/roughtime.cpp @@ -30,10 +30,8 @@ struct is_array : std::false_type {}; template struct is_array> : std::true_type {}; -template -T impl_from_little_endian(const uint8_t* t, const size_t i) - requires(sizeof(T) <= sizeof(int64_t)) -{ +template > +T impl_from_little_endian(const uint8_t* t, const size_t i) { return T(static_cast(t[i]) << i * 8) + (i == 0 ? T(0) : impl_from_little_endian(t, i - 1)); } diff --git a/src/lib/modes/aead/aead.h b/src/lib/modes/aead/aead.h index 6c0ebbed53a..1d47d743ccc 100644 --- a/src/lib/modes/aead/aead.h +++ b/src/lib/modes/aead/aead.h @@ -9,8 +9,7 @@ #define BOTAN_AEAD_MODE_H_ #include - -#include +#include namespace Botan { @@ -56,9 +55,9 @@ class BOTAN_PUBLIC_API(2, 0) AEAD_Mode : public Cipher_Mode { * * @param ad the associated data */ - void set_associated_data(std::span ad) { set_associated_data_n(0, ad); } + void set_associated_data(Botan::span ad) { set_associated_data_n(0, ad); } - void set_associated_data(const uint8_t ad[], size_t ad_len) { set_associated_data(std::span(ad, ad_len)); } + void set_associated_data(const uint8_t ad[], size_t ad_len) { set_associated_data(Botan::span(ad, ad_len)); } /** * Set associated data that is not included in the ciphertext but @@ -80,7 +79,7 @@ class BOTAN_PUBLIC_API(2, 0) AEAD_Mode : public Cipher_Mode { * @param idx which associated data to set * @param ad the associated data */ - virtual void set_associated_data_n(size_t idx, std::span ad) = 0; + virtual void set_associated_data_n(size_t idx, Botan::span ad) = 0; /** * Returns the maximum supported number of associated data inputs which @@ -123,7 +122,7 @@ class BOTAN_PUBLIC_API(2, 0) AEAD_Mode : public Cipher_Mode { */ BOTAN_DEPRECATED("Please use set_associated_data") - void set_ad(std::span ad) { set_associated_data(ad); } + void set_ad(Botan::span ad) { set_associated_data(ad); } /** * @return default AEAD nonce size (a commonly supported value among AEAD diff --git a/src/lib/modes/aead/ccm/ccm.cpp b/src/lib/modes/aead/ccm/ccm.cpp index 229184eeefb..dc61b20c9c9 100644 --- a/src/lib/modes/aead/ccm/ccm.cpp +++ b/src/lib/modes/aead/ccm/ccm.cpp @@ -78,11 +78,11 @@ bool CCM_Mode::has_keying_material() const { return m_cipher->has_keying_material(); } -void CCM_Mode::key_schedule(std::span key) { +void CCM_Mode::key_schedule(Botan::span key) { m_cipher->set_key(key); } -void CCM_Mode::set_associated_data_n(size_t idx, std::span ad) { +void CCM_Mode::set_associated_data_n(size_t idx, Botan::span ad) { BOTAN_ARG_CHECK(idx == 0, "CCM: cannot handle non-zero index in set_associated_data_n"); m_ad_buf.clear(); diff --git a/src/lib/modes/aead/ccm/ccm.h b/src/lib/modes/aead/ccm/ccm.h index 671b8d6cbc3..f67b99ff3d4 100644 --- a/src/lib/modes/aead/ccm/ccm.h +++ b/src/lib/modes/aead/ccm/ccm.h @@ -20,7 +20,7 @@ namespace Botan { */ class CCM_Mode : public AEAD_Mode { public: - void set_associated_data_n(size_t idx, std::span ad) final; + void set_associated_data_n(size_t idx, Botan::span ad) final; bool associated_data_requires_key() const final { return false; } @@ -68,7 +68,7 @@ class CCM_Mode : public AEAD_Mode { void start_msg(const uint8_t nonce[], size_t nonce_len) final; size_t process_msg(uint8_t buf[], size_t sz) final; - void key_schedule(std::span key) final; + void key_schedule(Botan::span key) final; const size_t m_tag_size; const size_t m_L; diff --git a/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.cpp b/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.cpp index 205ebdbd70e..c3955863a21 100644 --- a/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.cpp +++ b/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.cpp @@ -47,11 +47,11 @@ bool ChaCha20Poly1305_Mode::has_keying_material() const { return m_chacha->has_keying_material(); } -void ChaCha20Poly1305_Mode::key_schedule(std::span key) { +void ChaCha20Poly1305_Mode::key_schedule(Botan::span key) { m_chacha->set_key(key); } -void ChaCha20Poly1305_Mode::set_associated_data_n(size_t idx, std::span ad) { +void ChaCha20Poly1305_Mode::set_associated_data_n(size_t idx, Botan::span ad) { BOTAN_ARG_CHECK(idx == 0, "ChaCha20Poly1305: cannot handle non-zero index in set_associated_data_n"); if(m_ctext_len > 0 || m_nonce_len > 0) { throw Invalid_State("Cannot set AD for ChaCha20Poly1305 while processing a message"); diff --git a/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.h b/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.h index 909b23ebe9f..c47cd51260a 100644 --- a/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.h +++ b/src/lib/modes/aead/chacha20poly1305/chacha20poly1305.h @@ -24,7 +24,7 @@ namespace Botan { */ class ChaCha20Poly1305_Mode : public AEAD_Mode { public: - void set_associated_data_n(size_t idx, std::span ad) final; + void set_associated_data_n(size_t idx, Botan::span ad) final; bool associated_data_requires_key() const override { return false; } @@ -63,7 +63,7 @@ class ChaCha20Poly1305_Mode : public AEAD_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) override; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; }; /** diff --git a/src/lib/modes/aead/eax/eax.cpp b/src/lib/modes/aead/eax/eax.cpp index 76f4aaa3a00..a7e9d52b6ab 100644 --- a/src/lib/modes/aead/eax/eax.cpp +++ b/src/lib/modes/aead/eax/eax.cpp @@ -84,7 +84,7 @@ bool EAX_Mode::has_keying_material() const { /* * Set the EAX key */ -void EAX_Mode::key_schedule(std::span key) { +void EAX_Mode::key_schedule(Botan::span key) { /* * These could share the key schedule, which is one nice part of EAX, * but it's much easier to ignore that here... @@ -96,7 +96,7 @@ void EAX_Mode::key_schedule(std::span key) { /* * Set the EAX associated data */ -void EAX_Mode::set_associated_data_n(size_t idx, std::span ad) { +void EAX_Mode::set_associated_data_n(size_t idx, Botan::span ad) { BOTAN_ARG_CHECK(idx == 0, "EAX: cannot handle non-zero index in set_associated_data_n"); if(m_nonce_mac.empty() == false) { throw Invalid_State("Cannot set AD for EAX while processing a message"); diff --git a/src/lib/modes/aead/eax/eax.h b/src/lib/modes/aead/eax/eax.h index 19285933908..ccf3177b7ef 100644 --- a/src/lib/modes/aead/eax/eax.h +++ b/src/lib/modes/aead/eax/eax.h @@ -21,7 +21,7 @@ namespace Botan { */ class EAX_Mode : public AEAD_Mode { public: - void set_associated_data_n(size_t idx, std::span ad) final; + void set_associated_data_n(size_t idx, Botan::span ad) final; std::string name() const final; @@ -64,7 +64,7 @@ class EAX_Mode : public AEAD_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) final; - void key_schedule(std::span key) final; + void key_schedule(Botan::span key) final; }; /** diff --git a/src/lib/modes/aead/gcm/gcm.cpp b/src/lib/modes/aead/gcm/gcm.cpp index ec780c5fa64..a0fbefb578f 100644 --- a/src/lib/modes/aead/gcm/gcm.cpp +++ b/src/lib/modes/aead/gcm/gcm.cpp @@ -77,7 +77,7 @@ bool GCM_Mode::has_keying_material() const { return m_ctr->has_keying_material(); } -void GCM_Mode::key_schedule(std::span key) { +void GCM_Mode::key_schedule(Botan::span key) { m_ctr->set_key(key); const std::vector zeros(GCM_BS); @@ -88,7 +88,7 @@ void GCM_Mode::key_schedule(std::span key) { m_ghash->set_key(H); } -void GCM_Mode::set_associated_data_n(size_t idx, std::span ad) { +void GCM_Mode::set_associated_data_n(size_t idx, Botan::span ad) { BOTAN_ARG_CHECK(idx == 0, "GCM: cannot handle non-zero index in set_associated_data_n"); m_ghash->set_associated_data(ad); } @@ -136,7 +136,7 @@ void GCM_Encryption::finish_msg(secure_vector& buffer, size_t offset) { m_ghash->update({buf, sz}); std::array mac = {0}; - m_ghash->final(std::span(mac).first(tag_size())); + m_ghash->final(Botan::span(mac).first(tag_size())); buffer += std::make_pair(mac.data(), tag_size()); } @@ -163,7 +163,7 @@ void GCM_Decryption::finish_msg(secure_vector& buffer, size_t offset) { } std::array mac = {0}; - m_ghash->final(std::span(mac).first(tag_size())); + m_ghash->final(Botan::span(mac).first(tag_size())); const uint8_t* included_tag = &buffer[remaining + offset]; diff --git a/src/lib/modes/aead/gcm/gcm.h b/src/lib/modes/aead/gcm/gcm.h index 129815742df..b8dd7d22484 100644 --- a/src/lib/modes/aead/gcm/gcm.h +++ b/src/lib/modes/aead/gcm/gcm.h @@ -23,7 +23,7 @@ class GHASH; */ class GCM_Mode : public AEAD_Mode { public: - void set_associated_data_n(size_t idx, std::span ad) override final; + void set_associated_data_n(size_t idx, Botan::span ad) override final; std::string name() const override final; @@ -61,7 +61,7 @@ class GCM_Mode : public AEAD_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) override; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; secure_vector m_y0; }; diff --git a/src/lib/modes/aead/ocb/ocb.cpp b/src/lib/modes/aead/ocb/ocb.cpp index 3952814f434..35509fc6000 100644 --- a/src/lib/modes/aead/ocb/ocb.cpp +++ b/src/lib/modes/aead/ocb/ocb.cpp @@ -212,12 +212,12 @@ bool OCB_Mode::has_keying_material() const { return m_cipher->has_keying_material(); } -void OCB_Mode::key_schedule(std::span key) { +void OCB_Mode::key_schedule(Botan::span key) { m_cipher->set_key(key); m_L = std::make_unique(*m_cipher); } -void OCB_Mode::set_associated_data_n(size_t idx, std::span ad) { +void OCB_Mode::set_associated_data_n(size_t idx, Botan::span ad) { BOTAN_ARG_CHECK(idx == 0, "OCB: cannot handle non-zero index in set_associated_data_n"); assert_key_material_set(); m_ad_hash = ocb_hash(*m_L, *m_cipher, ad.data(), ad.size()); diff --git a/src/lib/modes/aead/ocb/ocb.h b/src/lib/modes/aead/ocb/ocb.h index fe364aaf74b..1f484bca0ce 100644 --- a/src/lib/modes/aead/ocb/ocb.h +++ b/src/lib/modes/aead/ocb/ocb.h @@ -30,7 +30,7 @@ class L_computer; */ class BOTAN_TEST_API OCB_Mode : public AEAD_Mode { public: - void set_associated_data_n(size_t idx, std::span ad) override final; + void set_associated_data_n(size_t idx, Botan::span ad) override final; std::string name() const override final; @@ -77,7 +77,7 @@ class BOTAN_TEST_API OCB_Mode : public AEAD_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) override final; - void key_schedule(std::span key) override final; + void key_schedule(Botan::span key) override final; const secure_vector& update_nonce(const uint8_t nonce[], size_t nonce_len); diff --git a/src/lib/modes/aead/siv/siv.cpp b/src/lib/modes/aead/siv/siv.cpp index ffde05e8178..8d526d5fc33 100644 --- a/src/lib/modes/aead/siv/siv.cpp +++ b/src/lib/modes/aead/siv/siv.cpp @@ -69,7 +69,7 @@ bool SIV_Mode::has_keying_material() const { return m_ctr->has_keying_material() && m_mac->has_keying_material(); } -void SIV_Mode::key_schedule(std::span key) { +void SIV_Mode::key_schedule(Botan::span key) { const size_t keylen = key.size() / 2; m_mac->set_key(key.first(keylen)); m_ctr->set_key(key.last(keylen)); @@ -80,7 +80,7 @@ size_t SIV_Mode::maximum_associated_data_inputs() const { return block_size() * 8 - 2; } -void SIV_Mode::set_associated_data_n(size_t n, std::span ad) { +void SIV_Mode::set_associated_data_n(size_t n, Botan::span ad) { const size_t max_ads = maximum_associated_data_inputs(); if(n > max_ads) { throw Invalid_Argument(name() + " allows no more than " + std::to_string(max_ads) + " ADs"); diff --git a/src/lib/modes/aead/siv/siv.h b/src/lib/modes/aead/siv/siv.h index a5ed08338b0..af6270aae0e 100644 --- a/src/lib/modes/aead/siv/siv.h +++ b/src/lib/modes/aead/siv/siv.h @@ -27,7 +27,7 @@ class BOTAN_TEST_API SIV_Mode : public AEAD_Mode { * @param n index into the AD vector * @param ad associated data */ - void set_associated_data_n(size_t n, std::span ad) override final; + void set_associated_data_n(size_t n, Botan::span ad) override final; size_t maximum_associated_data_inputs() const override final; @@ -70,7 +70,7 @@ class BOTAN_TEST_API SIV_Mode : public AEAD_Mode { void start_msg(const uint8_t nonce[], size_t nonce_len) override final; size_t process_msg(uint8_t buf[], size_t size) override final; - void key_schedule(std::span key) override final; + void key_schedule(Botan::span key) override final; const std::string m_name; const size_t m_bs; diff --git a/src/lib/modes/cbc/cbc.cpp b/src/lib/modes/cbc/cbc.cpp index 042edf66115..9873d904cdf 100644 --- a/src/lib/modes/cbc/cbc.cpp +++ b/src/lib/modes/cbc/cbc.cpp @@ -63,7 +63,7 @@ bool CBC_Mode::has_keying_material() const { return m_cipher->has_keying_material(); } -void CBC_Mode::key_schedule(std::span key) { +void CBC_Mode::key_schedule(Botan::span key) { m_cipher->set_key(key); m_state.clear(); } diff --git a/src/lib/modes/cbc/cbc.h b/src/lib/modes/cbc/cbc.h index e08dbddc24f..831d275cc75 100644 --- a/src/lib/modes/cbc/cbc.h +++ b/src/lib/modes/cbc/cbc.h @@ -57,7 +57,7 @@ class CBC_Mode : public Cipher_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) override; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; std::unique_ptr m_cipher; std::unique_ptr m_padding; diff --git a/src/lib/modes/cfb/cfb.cpp b/src/lib/modes/cfb/cfb.cpp index 79a71bc0424..ecba7c5e740 100644 --- a/src/lib/modes/cfb/cfb.cpp +++ b/src/lib/modes/cfb/cfb.cpp @@ -73,7 +73,7 @@ bool CFB_Mode::has_keying_material() const { return m_cipher->has_keying_material(); } -void CFB_Mode::key_schedule(std::span key) { +void CFB_Mode::key_schedule(Botan::span key) { m_cipher->set_key(key); m_keystream.resize(m_cipher->block_size()); } diff --git a/src/lib/modes/cfb/cfb.h b/src/lib/modes/cfb/cfb.h index 444025a6803..83ba636a4d3 100644 --- a/src/lib/modes/cfb/cfb.h +++ b/src/lib/modes/cfb/cfb.h @@ -58,7 +58,7 @@ class CFB_Mode : public Cipher_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) override; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; std::unique_ptr m_cipher; const size_t m_block_size; diff --git a/src/lib/modes/cipher_mode.h b/src/lib/modes/cipher_mode.h index 3f88bb1d53a..c3575c6e9ea 100644 --- a/src/lib/modes/cipher_mode.h +++ b/src/lib/modes/cipher_mode.h @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include #include @@ -86,7 +86,7 @@ class BOTAN_PUBLIC_API(2, 0) Cipher_Mode : public SymmetricAlgorithm { * Begin processing a message with a fresh nonce. * @param nonce the per message nonce */ - void start(std::span nonce) { start_msg(nonce.data(), nonce.size()); } + void start(Botan::span nonce) { start_msg(nonce.data(), nonce.size()); } /** * Begin processing a message with a fresh nonce. @@ -120,7 +120,7 @@ class BOTAN_PUBLIC_API(2, 0) Cipher_Mode : public SymmetricAlgorithm { * @param msg the message to be processed * @return bytes written in-place */ - size_t process(std::span msg) { return this->process_msg(msg.data(), msg.size()); } + size_t process(Botan::span msg) { return this->process_msg(msg.data(), msg.size()); } size_t process(uint8_t msg[], size_t msg_len) { return this->process_msg(msg, msg_len); } @@ -129,10 +129,11 @@ class BOTAN_PUBLIC_API(2, 0) Cipher_Mode : public SymmetricAlgorithm { * @param buffer in/out parameter which will possibly be resized * @param offset an offset into blocks to begin processing */ - template - void update(T& buffer, size_t offset = 0) { + template> + void update(T& buffer, size_t offset = 0) + { BOTAN_ASSERT(buffer.size() >= offset, "Offset ok"); - const size_t written = process(std::span(buffer).subspan(offset)); + const size_t written = process(Botan::span(buffer).subspan(offset)); buffer.resize(offset + written); } @@ -155,7 +156,7 @@ class BOTAN_PUBLIC_API(2, 0) Cipher_Mode : public SymmetricAlgorithm { * minimum_final_size() bytes, and will be set to any final output * @param offset an offset into final_block to begin processing */ - template + template> void finish(T& final_block, size_t offset = 0) { Botan::secure_vector tmp(final_block.begin(), final_block.end()); finish_msg(tmp, offset); diff --git a/src/lib/modes/stream_mode.h b/src/lib/modes/stream_mode.h index ad0786da519..4c6bc55d8b4 100644 --- a/src/lib/modes/stream_mode.h +++ b/src/lib/modes/stream_mode.h @@ -72,7 +72,7 @@ class Stream_Cipher_Mode final : public Cipher_Mode { void finish_msg(secure_vector& buf, size_t offset) override { return update(buf, offset); } - void key_schedule(std::span key) override { m_cipher->set_key(key); } + void key_schedule(Botan::span key) override { m_cipher->set_key(key); } std::unique_ptr m_cipher; }; diff --git a/src/lib/modes/xts/xts.cpp b/src/lib/modes/xts/xts.cpp index 886b7c4a18d..d364a12c2e8 100644 --- a/src/lib/modes/xts/xts.cpp +++ b/src/lib/modes/xts/xts.cpp @@ -67,7 +67,7 @@ bool XTS_Mode::has_keying_material() const { return m_cipher->has_keying_material() && m_tweak_cipher->has_keying_material(); } -void XTS_Mode::key_schedule(std::span key) { +void XTS_Mode::key_schedule(Botan::span key) { const size_t key_half = key.size() / 2; if(key.size() % 2 == 1 || !m_cipher->valid_keylength(key_half)) { diff --git a/src/lib/modes/xts/xts.h b/src/lib/modes/xts/xts.h index 96a6624cb22..933447ca9a1 100644 --- a/src/lib/modes/xts/xts.h +++ b/src/lib/modes/xts/xts.h @@ -56,7 +56,7 @@ class XTS_Mode : public Cipher_Mode { private: void start_msg(const uint8_t nonce[], size_t nonce_len) override; - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; std::unique_ptr m_cipher; std::unique_ptr m_tweak_cipher; diff --git a/src/lib/pbkdf/argon2/argon2_avx2/argon2_avx2.cpp b/src/lib/pbkdf/argon2/argon2_avx2/argon2_avx2.cpp index d0afac31362..eaef5949155 100644 --- a/src/lib/pbkdf/argon2/argon2_avx2/argon2_avx2.cpp +++ b/src/lib/pbkdf/argon2/argon2_avx2/argon2_avx2.cpp @@ -67,10 +67,9 @@ class SIMD_4x64 final { m_simd = _mm256_xor_si256(m_simd, other.m_simd); } - template + template 0) && (ROT < 64)>> BOTAN_FUNC_ISA("avx2") SIMD_4x64 rotr() const - requires(ROT > 0 && ROT < 64) { if constexpr(ROT == 16) { auto shuf_rot_16 = diff --git a/src/lib/pbkdf/argon2/argon2_ssse3/argon2_ssse3.cpp b/src/lib/pbkdf/argon2/argon2_ssse3/argon2_ssse3.cpp index b2329820e25..08a75173125 100644 --- a/src/lib/pbkdf/argon2/argon2_ssse3/argon2_ssse3.cpp +++ b/src/lib/pbkdf/argon2/argon2_ssse3/argon2_ssse3.cpp @@ -50,10 +50,9 @@ class SIMD_2x64 final { void operator^=(const SIMD_2x64& other) { m_simd = _mm_xor_si128(m_simd, other.m_simd); } - template + template 0) && (ROT < 64)>> BOTAN_FUNC_ISA("ssse3") SIMD_2x64 rotr() const - requires(ROT > 0 && ROT < 64) { if constexpr(ROT == 16) { auto tab = _mm_setr_epi8(2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9); @@ -81,10 +80,9 @@ class SIMD_2x64 final { return SIMD_2x64(_mm_add_epi64(m, m)); } - template + template 0) && (T < 16)>> BOTAN_FUNC_ISA("ssse3") static SIMD_2x64 alignr(SIMD_2x64 a, SIMD_2x64 b) - requires(T > 0 && T < 16) { return SIMD_2x64(_mm_alignr_epi8(a.m_simd, b.m_simd, T)); } diff --git a/src/lib/pbkdf/pwdhash.h b/src/lib/pbkdf/pwdhash.h index 4ca467864d2..135492f779d 100644 --- a/src/lib/pbkdf/pwdhash.h +++ b/src/lib/pbkdf/pwdhash.h @@ -7,10 +7,10 @@ #ifndef BOTAN_PWDHASH_H_ #define BOTAN_PWDHASH_H_ +#include #include #include #include -#include #include #include @@ -78,7 +78,7 @@ class BOTAN_PUBLIC_API(2, 8) PasswordHash { * This function is const, but is not thread safe. Different threads should * either use unique objects, or serialize all access. */ - void hash(std::span out, std::string_view password, std::span salt) const { + void hash(Botan::span out, std::string_view password, Botan::span salt) const { this->derive_key(out.data(), out.size(), password.data(), password.size(), salt.data(), salt.size()); } @@ -94,11 +94,11 @@ class BOTAN_PUBLIC_API(2, 8) PasswordHash { * This function is const, but is not thread safe. Different threads should * either use unique objects, or serialize all access. */ - void hash(std::span out, + void hash(Botan::span out, std::string_view password, - std::span salt, - std::span associated_data, - std::span key) const { + Botan::span salt, + Botan::span associated_data, + Botan::span key) const { this->derive_key(out.data(), out.size(), password.data(), diff --git a/src/lib/permutations/keccak_perm/keccak_helpers.cpp b/src/lib/permutations/keccak_perm/keccak_helpers.cpp index 3c7590a0b8d..11654ff7834 100644 --- a/src/lib/permutations/keccak_perm/keccak_helpers.cpp +++ b/src/lib/permutations/keccak_perm/keccak_helpers.cpp @@ -22,7 +22,7 @@ size_t int_encoding_size(uint64_t x) { return ceil_tobytes(std::max(uint8_t(1), ceil_log2(x + 1))); } -uint8_t encode(std::span out, uint64_t x) { +uint8_t encode(Botan::span out, uint64_t x) { const auto bytes_needed = int_encoding_size(x); BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed); @@ -38,13 +38,13 @@ uint8_t encode(std::span out, uint64_t x) { } // namespace -std::span keccak_int_left_encode(std::span out, size_t x) { +Botan::span keccak_int_left_encode(Botan::span out, size_t x) { BOTAN_ASSERT_NOMSG(!out.empty()); out[0] = encode(out.last(out.size() - 1), x); return out.first(out[0] + 1 /* the length tag */); } -std::span keccak_int_right_encode(std::span out, size_t x) { +Botan::span keccak_int_right_encode(Botan::span out, size_t x) { const auto bytes_needed = encode(out, x); BOTAN_ASSERT_NOMSG(out.size() >= bytes_needed + size_t(1)); out[bytes_needed] = bytes_needed; diff --git a/src/lib/permutations/keccak_perm/keccak_helpers.h b/src/lib/permutations/keccak_perm/keccak_helpers.h index 6810eab9c57..d5516515f92 100644 --- a/src/lib/permutations/keccak_perm/keccak_helpers.h +++ b/src/lib/permutations/keccak_perm/keccak_helpers.h @@ -11,10 +11,10 @@ #include #include -#include #include #include +#include namespace Botan { @@ -33,7 +33,7 @@ namespace Botan { * @param x the integer to be left-encoded * @return the byte span that represents the bytes written to @p buffer. */ -BOTAN_TEST_API std::span keccak_int_left_encode(std::span buffer, size_t x); +BOTAN_TEST_API Botan::span keccak_int_left_encode(Botan::span buffer, size_t x); /** * Integer encoding defined in NIST SP.800-185 that can be unambiguously @@ -50,7 +50,7 @@ BOTAN_TEST_API std::span keccak_int_left_encode(std::span keccak_int_right_encode(std::span out, size_t x); +BOTAN_TEST_API Botan::span keccak_int_right_encode(Botan::span out, size_t x); /** * @returns the required bytes for encodings of keccak_int_left_encode() or @@ -67,13 +67,35 @@ constexpr size_t keccak_max_int_encoding_size() { } template -concept updatable_object = requires(T& a, std::span span) { a.update(span); }; +using updatable_object = std::void_t&>().update( + std::declval>()))>; + +template +struct is_updatable_object : std::false_type {}; + +template +struct is_updatable_object> : std::true_type {}; + +template +constexpr bool is_updatable_object_v = is_updatable_object::value; + +template +using appendable_object = std::void_t&>().insert( + std::declval&>().end(), + std::declval>().begin(), + std::declval>().end()))>; + +template +struct is_appendable_object : std::false_type {}; + +template +struct is_appendable_object> : std::true_type {}; template -concept appendable_object = requires(T& a, std::span s) { a.insert(a.end(), s.begin(), s.end()); }; +constexpr bool is_appendable_object_v = is_appendable_object::value; template -concept absorbing_object = updatable_object || appendable_object; +using absorbing_object = std::enable_if_t || is_appendable_object_v>; /** * This is a combination of the functions encode_string() and bytepad() defined @@ -86,8 +108,12 @@ concept absorbing_object = updatable_object || appendable_object; * absorbed into the given @p xof * @returns the number of bytes absorbed into the @p xof */ -template - requires(concepts::constructible_from, Ts> && ...) +template > //, + //typename = concepts::constructible_from, Ts...>> +// TODO: pstanisz check if above and below are equivalent +//requires(concepts::constructible_from, Ts> && ...) size_t keccak_absorb_padded_strings_encoding(T& sink, size_t padding_mod, Ts... byte_strings) { BOTAN_ASSERT_NOMSG(padding_mod > 0); @@ -96,17 +122,17 @@ size_t keccak_absorb_padded_strings_encoding(T& sink, size_t padding_mod, Ts... // absorbs byte strings and counts the number of absorbed bytes size_t bytes_absorbed = 0; - auto absorb = [&](std::span bytes) { - if constexpr(updatable_object) { + auto absorb = [&](Botan::span bytes) { + if constexpr(is_updatable_object_v) { sink.update(bytes); - } else if constexpr(appendable_object) { + } else if constexpr(is_appendable_object_v) { sink.insert(sink.end(), bytes.begin(), bytes.end()); } bytes_absorbed += bytes.size(); }; // encodes a given string and absorbs it into the XOF straight away - auto encode_string_and_absorb = [&](std::span bytes) { + auto encode_string_and_absorb = [&](Botan::span bytes) { absorb(keccak_int_left_encode(int_encoding_buffer, bytes.size() * 8)); absorb(bytes); }; diff --git a/src/lib/permutations/keccak_perm/keccak_perm.cpp b/src/lib/permutations/keccak_perm/keccak_perm.cpp index 6bc4d669b19..400894538fe 100644 --- a/src/lib/permutations/keccak_perm/keccak_perm.cpp +++ b/src/lib/permutations/keccak_perm/keccak_perm.cpp @@ -45,7 +45,7 @@ void Keccak_Permutation::clear() { m_S_outpos = 0; } -void Keccak_Permutation::absorb(std::span input) { +void Keccak_Permutation::absorb(Botan::span input) { BufferSlicer input_slicer(input); // Block-wise incorporation of the input data into the sponge state until @@ -77,7 +77,7 @@ void Keccak_Permutation::absorb(std::span input) { } } -void Keccak_Permutation::squeeze(std::span output) { +void Keccak_Permutation::squeeze(Botan::span output) { BufferStuffer output_stuffer(output); // Block-wise readout of the sponge state until enough bytes diff --git a/src/lib/permutations/keccak_perm/keccak_perm.h b/src/lib/permutations/keccak_perm/keccak_perm.h index 858b1c4b5cf..3251f1859d5 100644 --- a/src/lib/permutations/keccak_perm/keccak_perm.h +++ b/src/lib/permutations/keccak_perm/keccak_perm.h @@ -63,7 +63,7 @@ class Keccak_Permutation final { * * @param input the input data */ - void absorb(std::span input); + void absorb(Botan::span input); /** * @brief Expand output data from the current Keccak state @@ -72,7 +72,7 @@ class Keccak_Permutation final { * * @param output the designated output memory */ - void squeeze(std::span output); + void squeeze(Botan::span output); /** * @brief Add final padding (as provided in the constructor) and permute diff --git a/src/lib/pk_pad/raw_hash/raw_hash.cpp b/src/lib/pk_pad/raw_hash/raw_hash.cpp index ceaa47cc46a..62061925885 100644 --- a/src/lib/pk_pad/raw_hash/raw_hash.cpp +++ b/src/lib/pk_pad/raw_hash/raw_hash.cpp @@ -10,11 +10,11 @@ namespace Botan { -void RawHashFunction::add_data(std::span input) { +void RawHashFunction::add_data(Botan::span input) { m_bits += std::make_pair(input.data(), input.size()); } -void RawHashFunction::final_result(std::span out) { +void RawHashFunction::final_result(Botan::span out) { if(m_output_length > 0 && m_bits.size() != m_output_length) { m_bits.clear(); throw Invalid_Argument("Raw padding was configured to use a " + std::to_string(m_output_length) + diff --git a/src/lib/pk_pad/raw_hash/raw_hash.h b/src/lib/pk_pad/raw_hash/raw_hash.h index 892ccd6fb4f..70dc79a6fda 100644 --- a/src/lib/pk_pad/raw_hash/raw_hash.h +++ b/src/lib/pk_pad/raw_hash/raw_hash.h @@ -26,9 +26,9 @@ class RawHashFunction : public HashFunction { RawHashFunction(std::string_view name, size_t output_length) : m_name(name), m_output_length(output_length) {} - void add_data(std::span input) override; + void add_data(Botan::span input) override; - void final_result(std::span out) override; + void final_result(Botan::span out) override; void clear() override; diff --git a/src/lib/prov/commoncrypto/commoncrypto_block.cpp b/src/lib/prov/commoncrypto/commoncrypto_block.cpp index a07fe118de8..7d6c00a2e5c 100644 --- a/src/lib/prov/commoncrypto/commoncrypto_block.cpp +++ b/src/lib/prov/commoncrypto/commoncrypto_block.cpp @@ -59,7 +59,7 @@ class CommonCrypto_BlockCipher final : public BlockCipher { } } - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; std::string m_cipher_name; CommonCryptor_Opts m_opts; @@ -84,7 +84,7 @@ CommonCrypto_BlockCipher::~CommonCrypto_BlockCipher() { /* * Set the key */ -void CommonCrypto_BlockCipher::key_schedule(std::span key) { +void CommonCrypto_BlockCipher::key_schedule(Botan::span key) { secure_vector full_key(key.begin(), key.end()); clear(); diff --git a/src/lib/prov/commoncrypto/commoncrypto_hash.cpp b/src/lib/prov/commoncrypto/commoncrypto_hash.cpp index 1fb79c419b3..fe5f9c4fd14 100644 --- a/src/lib/prov/commoncrypto/commoncrypto_hash.cpp +++ b/src/lib/prov/commoncrypto/commoncrypto_hash.cpp @@ -55,7 +55,7 @@ class CommonCrypto_HashFunction final : public HashFunction { CommonCrypto_HashFunction(const digest_config_t& info, const CTX& ctx) : m_ctx(ctx), m_info(info) {} private: - void add_data(std::span input) override { + void add_data(Botan::span input) override { BufferSlicer in(input); /* update len parameter is 32 bit unsigned integer, feed input in parts */ @@ -66,7 +66,7 @@ class CommonCrypto_HashFunction final : public HashFunction { } } - void final_result(std::span output) override { + void final_result(Botan::span output) override { if(m_info.final(output.data(), &m_ctx) != 1) throw CommonCrypto_Error("CC_" + m_info.name + "_Final"); clear(); diff --git a/src/lib/prov/commoncrypto/commoncrypto_mode.cpp b/src/lib/prov/commoncrypto/commoncrypto_mode.cpp index ccdb39d34f8..3cddd58dfea 100644 --- a/src/lib/prov/commoncrypto/commoncrypto_mode.cpp +++ b/src/lib/prov/commoncrypto/commoncrypto_mode.cpp @@ -40,7 +40,7 @@ class CommonCrypto_Cipher_Mode final : public Cipher_Mode { bool has_keying_material() const override { return m_key_set; } private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void start_msg(const uint8_t nonce[], size_t nonce_len) override; size_t process_msg(uint8_t msg[], size_t msg_len) override; @@ -194,7 +194,7 @@ Key_Length_Specification CommonCrypto_Cipher_Mode::key_spec() const { return m_opts.key_spec; } -void CommonCrypto_Cipher_Mode::key_schedule(std::span key) { +void CommonCrypto_Cipher_Mode::key_schedule(Botan::span key) { CCCryptorStatus status; CCOperation op = m_direction == Cipher_Dir::Encryption ? kCCEncrypt : kCCDecrypt; status = CCCryptorCreateWithMode( diff --git a/src/lib/prov/pkcs11/p11_object.h b/src/lib/prov/pkcs11/p11_object.h index e5cbb8f5980..d6671b66aeb 100644 --- a/src/lib/prov/pkcs11/p11_object.h +++ b/src/lib/prov/pkcs11/p11_object.h @@ -94,10 +94,10 @@ class BOTAN_PUBLIC_API(2, 0) AttributeContainer { */ template void add_numeric(AttributeType attribute, T value) - requires std::is_integral::value { - m_numerics.push_back(static_cast(value)); - add_attribute(attribute, reinterpret_cast(&m_numerics.back()), sizeof(T)); + static_assert(std::is_integral::value, "Numeric value required."); + m_numerics.push_back(static_cast< uint64_t >(value)); + add_attribute(attribute, reinterpret_cast< uint8_t* >(&m_numerics.back()), sizeof(T)); } protected: diff --git a/src/lib/prov/pkcs11/p11_randomgenerator.cpp b/src/lib/prov/pkcs11/p11_randomgenerator.cpp index 5130f2c87a5..d8ffdb60b88 100644 --- a/src/lib/prov/pkcs11/p11_randomgenerator.cpp +++ b/src/lib/prov/pkcs11/p11_randomgenerator.cpp @@ -12,7 +12,7 @@ namespace Botan::PKCS11 { PKCS11_RNG::PKCS11_RNG(Session& session) : m_session(session) {} -void PKCS11_RNG::fill_bytes_with_input(std::span output, std::span input) { +void PKCS11_RNG::fill_bytes_with_input(Botan::span output, Botan::span input) { if(!input.empty()) { module()->C_SeedRandom(m_session.get().handle(), const_cast(input.data()), Ulong(input.size())); } diff --git a/src/lib/prov/pkcs11/p11_randomgenerator.h b/src/lib/prov/pkcs11/p11_randomgenerator.h index 8784978bd02..66f47cffaf6 100644 --- a/src/lib/prov/pkcs11/p11_randomgenerator.h +++ b/src/lib/prov/pkcs11/p11_randomgenerator.h @@ -43,7 +43,7 @@ class BOTAN_PUBLIC_API(2, 0) PKCS11_RNG final : public Hardware_RNG { private: /// Calls `C_GenerateRandom` to generate random data /// Calls `C_SeedRandom` to add entropy to the random generation function of the token/middleware - void fill_bytes_with_input(std::span output, std::span input) override; + void fill_bytes_with_input(Botan::span output, Botan::span input) override; private: const std::reference_wrapper m_session; diff --git a/src/lib/prov/tpm/tpm.h b/src/lib/prov/tpm/tpm.h index e74283e10ff..d0c091ef2d8 100644 --- a/src/lib/prov/tpm/tpm.h +++ b/src/lib/prov/tpm/tpm.h @@ -83,7 +83,7 @@ class BOTAN_PUBLIC_API(2, 0) TPM_RNG final : public Hardware_RNG { bool is_seeded() const override { return true; } private: - void fill_bytes_with_input(std::span output, std::span input) override { + void fill_bytes_with_input(Botan::span output, Botan::span input) override { if(!input.empty()) { m_ctx.stir_random(input.data(), input.size()); } diff --git a/src/lib/pubkey/curve25519/curve25519.cpp b/src/lib/pubkey/curve25519/curve25519.cpp index d7cf44ab5cb..5bfcda2b85b 100644 --- a/src/lib/pubkey/curve25519/curve25519.cpp +++ b/src/lib/pubkey/curve25519/curve25519.cpp @@ -44,7 +44,7 @@ bool Curve25519_PublicKey::check_key(RandomNumberGenerator& /*rng*/, bool /*stro return true; // no tests possible? } -Curve25519_PublicKey::Curve25519_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span key_bits) { +Curve25519_PublicKey::Curve25519_PublicKey(const AlgorithmIdentifier& /*unused*/, Botan::span key_bits) { m_public.assign(key_bits.begin(), key_bits.end()); size_check(m_public.size(), "public key"); @@ -70,7 +70,7 @@ Curve25519_PrivateKey::Curve25519_PrivateKey(RandomNumberGenerator& rng) { curve25519_basepoint(m_public.data(), m_private.data()); } -Curve25519_PrivateKey::Curve25519_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span key_bits) { +Curve25519_PrivateKey::Curve25519_PrivateKey(const AlgorithmIdentifier& /*unused*/, Botan::span key_bits) { BER_Decoder(key_bits).decode(m_private, ASN1_Type::OctetString).discard_remaining(); size_check(m_private.size(), "private key"); diff --git a/src/lib/pubkey/curve25519/curve25519.h b/src/lib/pubkey/curve25519/curve25519.h index a08e1a76d99..b1738d08284 100644 --- a/src/lib/pubkey/curve25519/curve25519.h +++ b/src/lib/pubkey/curve25519/curve25519.h @@ -35,7 +35,7 @@ class BOTAN_PUBLIC_API(2, 0) Curve25519_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - Curve25519_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + Curve25519_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a Curve25519 Public Key. @@ -66,7 +66,7 @@ class BOTAN_PUBLIC_API(2, 0) Curve25519_PrivateKey final : public Curve25519_Pub * @param alg_id the X.509 algorithm identifier * @param key_bits PKCS #8 structure */ - Curve25519_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + Curve25519_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Generate a private key. diff --git a/src/lib/pubkey/dh/dh.cpp b/src/lib/pubkey/dh/dh.cpp index 5cbceeee0c8..4bcb4cac2b4 100644 --- a/src/lib/pubkey/dh/dh.cpp +++ b/src/lib/pubkey/dh/dh.cpp @@ -13,7 +13,7 @@ namespace Botan { -DH_PublicKey::DH_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +DH_PublicKey::DH_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { m_public_key = std::make_shared(alg_id, key_bits, DL_Group_Format::ANSI_X9_42); } @@ -63,7 +63,7 @@ DH_PrivateKey::DH_PrivateKey(const DL_Group& group, const BigInt& x) { m_public_key = m_private_key->public_key(); } -DH_PrivateKey::DH_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +DH_PrivateKey::DH_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { m_private_key = std::make_shared(alg_id, key_bits, DL_Group_Format::ANSI_X9_42); m_public_key = m_private_key->public_key(); } diff --git a/src/lib/pubkey/dh/dh.h b/src/lib/pubkey/dh/dh.h index 73479559953..54533d78696 100644 --- a/src/lib/pubkey/dh/dh.h +++ b/src/lib/pubkey/dh/dh.h @@ -28,7 +28,7 @@ class BOTAN_PUBLIC_API(2, 0) DH_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - DH_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + DH_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Construct a public key with the specified parameters. @@ -81,7 +81,7 @@ class BOTAN_PUBLIC_API(2, 0) DH_PrivateKey final : public DH_PublicKey, * @param alg_id the X.509 algorithm identifier * @param key_bits PKCS #8 structure */ - DH_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + DH_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Load a private key from the integer encoding diff --git a/src/lib/pubkey/dilithium/dilithium/dilithium_modern.h b/src/lib/pubkey/dilithium/dilithium/dilithium_modern.h index 56e377a15e6..b440a4f9d3c 100644 --- a/src/lib/pubkey/dilithium/dilithium/dilithium_modern.h +++ b/src/lib/pubkey/dilithium/dilithium/dilithium_modern.h @@ -23,7 +23,7 @@ namespace Botan { class Dilithium_Common_Symmetric_Primitives : public Dilithium_Symmetric_Primitives { public: - std::unique_ptr XOF(XofType type, std::span seed, uint16_t nonce) const override { + std::unique_ptr XOF(XofType type, Botan::span seed, uint16_t nonce) const override { const auto xof_type = [&] { switch(type) { case XofType::k128: diff --git a/src/lib/pubkey/dilithium/dilithium_aes/dilithium_aes.h b/src/lib/pubkey/dilithium/dilithium_aes/dilithium_aes.h index eff8cb4e278..a1b1c13ae9a 100644 --- a/src/lib/pubkey/dilithium/dilithium_aes/dilithium_aes.h +++ b/src/lib/pubkey/dilithium/dilithium_aes/dilithium_aes.h @@ -23,7 +23,7 @@ namespace Botan { class Dilithium_AES_Symmetric_Primitives : public Dilithium_Symmetric_Primitives { public: // AES mode always uses AES-256, regardless of the XofType - std::unique_ptr XOF(XofType /* type */, std::span seed, uint16_t nonce) const final { + std::unique_ptr XOF(XofType /* type */, Botan::span seed, uint16_t nonce) const final { // Algorithm Spec V. 3.1 Section 5.3 // In the AES variant, the first 32 bytes of rhoprime are used as // the key and i is extended to a 12 byte nonce for AES-256 in diff --git a/src/lib/pubkey/dilithium/dilithium_common/dilithium.cpp b/src/lib/pubkey/dilithium/dilithium_common/dilithium.cpp index f2668970a76..580264b1fdf 100644 --- a/src/lib/pubkey/dilithium/dilithium_common/dilithium.cpp +++ b/src/lib/pubkey/dilithium/dilithium_common/dilithium.cpp @@ -23,11 +23,11 @@ #include #include #include +#include #include #include #include -#include #include namespace Botan { @@ -116,7 +116,7 @@ class Dilithium_PublicKeyInternal { public: Dilithium_PublicKeyInternal(DilithiumModeConstants mode) : m_mode(std::move(mode)) {} - Dilithium_PublicKeyInternal(DilithiumModeConstants mode, std::span raw_pk) : + Dilithium_PublicKeyInternal(DilithiumModeConstants mode, Botan::span raw_pk) : m_mode(std::move(mode)) { BOTAN_ASSERT_NOMSG(raw_pk.size() == m_mode.public_key_bytes()); @@ -205,7 +205,7 @@ class Dilithium_PrivateKeyInternal { m_s1(std::move(s1)), m_s2(std::move(s2)) {} - Dilithium_PrivateKeyInternal(DilithiumModeConstants mode, std::span sk) : + Dilithium_PrivateKeyInternal(DilithiumModeConstants mode, Botan::span sk) : Dilithium_PrivateKeyInternal(std::move(mode)) { BOTAN_ASSERT_NOMSG(sk.size() == m_mode.private_key_bytes()); @@ -501,10 +501,10 @@ class Dilithium_Verification_Operation final : public PK_Ops::Verification { SHAKE_256 m_shake; }; -Dilithium_PublicKey::Dilithium_PublicKey(const AlgorithmIdentifier& alg_id, std::span pk) : +Dilithium_PublicKey::Dilithium_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span pk) : Dilithium_PublicKey(pk, DilithiumMode(alg_id.oid())) {} -Dilithium_PublicKey::Dilithium_PublicKey(std::span pk, DilithiumMode m) { +Dilithium_PublicKey::Dilithium_PublicKey(Botan::span pk, DilithiumMode m) { DilithiumModeConstants mode(m); BOTAN_ARG_CHECK(pk.empty() || pk.size() == mode.public_key_bytes(), "dilithium public key does not have the correct byte count"); @@ -596,10 +596,10 @@ Dilithium_PrivateKey::Dilithium_PrivateKey(RandomNumberGenerator& rng, Dilithium std::move(mode), std::move(rho), std::move(tr), std::move(key), std::move(s1), std::move(s2), std::move(t0)); } -Dilithium_PrivateKey::Dilithium_PrivateKey(const AlgorithmIdentifier& alg_id, std::span sk) : +Dilithium_PrivateKey::Dilithium_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span sk) : Dilithium_PrivateKey(sk, DilithiumMode(alg_id.oid())) {} -Dilithium_PrivateKey::Dilithium_PrivateKey(std::span sk, DilithiumMode m) { +Dilithium_PrivateKey::Dilithium_PrivateKey(Botan::span sk, DilithiumMode m) { DilithiumModeConstants mode(m); BOTAN_ARG_CHECK(sk.size() == mode.private_key_bytes(), "dilithium private key does not have the correct byte count"); m_private = std::make_shared(std::move(mode), sk); diff --git a/src/lib/pubkey/dilithium/dilithium_common/dilithium.h b/src/lib/pubkey/dilithium/dilithium_common/dilithium.h index 19869089add..665a8b3b6d7 100644 --- a/src/lib/pubkey/dilithium/dilithium_common/dilithium.h +++ b/src/lib/pubkey/dilithium/dilithium_common/dilithium.h @@ -74,9 +74,9 @@ class BOTAN_PUBLIC_API(3, 0) Dilithium_PublicKey : public virtual Public_Key { bool supports_operation(PublicKeyOperation op) const override { return (op == PublicKeyOperation::Signature); } - Dilithium_PublicKey(const AlgorithmIdentifier& alg_id, std::span pk); + Dilithium_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span pk); - Dilithium_PublicKey(std::span pk, DilithiumMode mode); + Dilithium_PublicKey(Botan::span pk, DilithiumMode mode); std::unique_ptr create_verification_op(std::string_view params, std::string_view provider) const override; @@ -109,12 +109,12 @@ class BOTAN_PUBLIC_API(3, 0) Dilithium_PrivateKey final : public virtual Dilithi /** * Read an encoded private key. */ - Dilithium_PrivateKey(const AlgorithmIdentifier& alg_id, std::span sk); + Dilithium_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span sk); /** * Read an encoded private key given the dilithium @p mode. */ - Dilithium_PrivateKey(std::span sk, DilithiumMode mode); + Dilithium_PrivateKey(Botan::span sk, DilithiumMode mode); secure_vector private_key_bits() const override; diff --git a/src/lib/pubkey/dilithium/dilithium_common/dilithium_polynomials.h b/src/lib/pubkey/dilithium/dilithium_common/dilithium_polynomials.h index 569c67d8d92..d2822e53dc7 100644 --- a/src/lib/pubkey/dilithium/dilithium_common/dilithium_polynomials.h +++ b/src/lib/pubkey/dilithium/dilithium_common/dilithium_polynomials.h @@ -16,11 +16,11 @@ #include +#include #include #include #include -#include #include namespace Botan::Dilithium { @@ -158,7 +158,7 @@ class Polynomial { size_t ctr = Polynomial::rej_eta(a, 0, DilithiumModeConstants::N, buf, buf.size(), mode); while(ctr < DilithiumModeConstants::N) { - xof->output(std::span(buf).first(mode.stream256_blockbytes())); + xof->output(Botan::span(buf).first(mode.stream256_blockbytes())); ctr += Polynomial::rej_eta(a, ctr, DilithiumModeConstants::N - ctr, buf, mode.stream256_blockbytes(), mode); } } @@ -623,7 +623,7 @@ class Polynomial { * - const uint8_t *a: byte array with bit-packed_t1 polynomial * - const DilithiumModeConstants& mode: reference to dilihtium mode values **************************************************/ - static Polynomial polyeta_unpack(std::span a, const DilithiumModeConstants& mode) { + static Polynomial polyeta_unpack(Botan::span a, const DilithiumModeConstants& mode) { Polynomial r; switch(mode.eta()) { @@ -709,7 +709,7 @@ class Polynomial { * Arguments: - poly *r: pointer to output polynomial * - const uint8_t *a: byte array with bit-packed_t1 polynomial **************************************************/ - static Polynomial polyt0_unpack(std::span a) { + static Polynomial polyt0_unpack(Botan::span a) { Polynomial r; for(size_t i = 0; i < DilithiumModeConstants::N / 8; ++i) { @@ -996,7 +996,7 @@ class PolynomialVector { std::vector buf(buflen + 2); auto xof = mode.XOF_128(seed, nonce); - xof->output(std::span(buf).first(buflen)); + xof->output(Botan::span(buf).first(buflen)); size_t ctr = Polynomial::rej_uniform(sample_poly, 0, DilithiumModeConstants::N, buf.data(), buflen); size_t off; @@ -1006,7 +1006,7 @@ class PolynomialVector { buf[i] = buf[buflen - off + i]; } - xof->output(std::span(buf).subspan(off, mode.stream128_blockbytes())); + xof->output(Botan::span(buf).subspan(off, mode.stream128_blockbytes())); buflen = mode.stream128_blockbytes() + off; ctr += Polynomial::rej_uniform(sample_poly, ctr, DilithiumModeConstants::N - ctr, buf.data(), buflen); } @@ -1307,7 +1307,7 @@ class PolynomialVector { return packed_eta; } - static PolynomialVector unpack_eta(std::span buffer, + static PolynomialVector unpack_eta(Botan::span buffer, size_t size, const DilithiumModeConstants& mode) { BOTAN_ARG_CHECK(buffer.size() == mode.polyeta_packedbytes() * size, "Invalid buffer size"); @@ -1328,7 +1328,7 @@ class PolynomialVector { return packed_t0; } - static PolynomialVector unpack_t0(std::span buffer, const DilithiumModeConstants& mode) { + static PolynomialVector unpack_t0(Botan::span buffer, const DilithiumModeConstants& mode) { BOTAN_ARG_CHECK(static_cast(buffer.size()) == DilithiumModeConstants::POLYT0_PACKEDBYTES * mode.k(), "Invalid buffer size"); @@ -1348,7 +1348,7 @@ class PolynomialVector { return packed_t1; } - static PolynomialVector unpack_t1(std::span packed_t1, const DilithiumModeConstants& mode) { + static PolynomialVector unpack_t1(Botan::span packed_t1, const DilithiumModeConstants& mode) { BOTAN_ARG_CHECK( static_cast(packed_t1.size()) == DilithiumModeConstants::POLYT1_PACKEDBYTES * mode.k(), "Invalid buffer size"); diff --git a/src/lib/pubkey/dilithium/dilithium_common/dilithium_symmetric_primitives.h b/src/lib/pubkey/dilithium/dilithium_common/dilithium_symmetric_primitives.h index 6d9a126767b..8fa58db1424 100644 --- a/src/lib/pubkey/dilithium/dilithium_common/dilithium_symmetric_primitives.h +++ b/src/lib/pubkey/dilithium/dilithium_common/dilithium_symmetric_primitives.h @@ -12,11 +12,11 @@ #include +#include #include #include #include -#include #include namespace Botan { @@ -35,22 +35,22 @@ class Dilithium_Symmetric_Primitives { virtual ~Dilithium_Symmetric_Primitives() = default; // H is same for all modes - secure_vector H(std::span seed, size_t out_len) const { + secure_vector H(Botan::span seed, size_t out_len) const { return SHAKE_256(out_len * 8).process(seed.data(), seed.size()); } // CRH is same for all modes - secure_vector CRH(std::span in, size_t out_len) const { + secure_vector CRH(Botan::span in, size_t out_len) const { return SHAKE_256(out_len * 8).process(in.data(), in.size()); } // ExpandMatrix always uses the 256 version of the XOF - secure_vector ExpandMask(std::span seed, uint16_t nonce, size_t out_len) const { + secure_vector ExpandMask(Botan::span seed, uint16_t nonce, size_t out_len) const { return XOF(XofType::k256, seed, nonce)->output(out_len); } // Mode dependent function - virtual std::unique_ptr XOF(XofType type, std::span seed, uint16_t nonce) const = 0; + virtual std::unique_ptr XOF(XofType type, Botan::span seed, uint16_t nonce) const = 0; }; enum DilithiumEta : uint32_t { Eta2 = 2, Eta4 = 4 }; @@ -151,19 +151,19 @@ class DilithiumModeConstants { size_t nist_security_strength() const { return m_nist_security_strength; } // Wrapper - decltype(auto) H(std::span seed, size_t out_len) const { + decltype(auto) H(Botan::span seed, size_t out_len) const { return m_symmetric_primitives->H(seed, out_len); } - secure_vector CRH(const std::span in) const { + secure_vector CRH(const Botan::span in) const { return m_symmetric_primitives->CRH(in, DilithiumModeConstants::CRHBYTES); } - std::unique_ptr XOF_128(std::span seed, uint16_t nonce) const { + std::unique_ptr XOF_128(Botan::span seed, uint16_t nonce) const { return this->m_symmetric_primitives->XOF(Dilithium_Symmetric_Primitives::XofType::k128, seed, nonce); } - std::unique_ptr XOF_256(std::span seed, uint16_t nonce) const { + std::unique_ptr XOF_256(Botan::span seed, uint16_t nonce) const { return this->m_symmetric_primitives->XOF(Dilithium_Symmetric_Primitives::XofType::k256, seed, nonce); } diff --git a/src/lib/pubkey/dl_algo/dl_scheme.cpp b/src/lib/pubkey/dl_algo/dl_scheme.cpp index 676f44b6371..5888c03d97d 100644 --- a/src/lib/pubkey/dl_algo/dl_scheme.cpp +++ b/src/lib/pubkey/dl_algo/dl_scheme.cpp @@ -14,7 +14,7 @@ namespace Botan { namespace { -BigInt decode_single_bigint(std::span key_bits) { +BigInt decode_single_bigint(Botan::span key_bits) { BigInt x; BER_Decoder(key_bits).decode(x); return x; @@ -39,7 +39,7 @@ DL_PublicKey::DL_PublicKey(const DL_Group& group, const BigInt& public_key) : m_group(group), m_public_key(public_key) {} DL_PublicKey::DL_PublicKey(const AlgorithmIdentifier& alg_id, - std::span key_bits, + Botan::span key_bits, DL_Group_Format format) : m_group(alg_id.parameters(), format), m_public_key(decode_single_bigint(key_bits)) {} @@ -78,7 +78,7 @@ DL_PrivateKey::DL_PrivateKey(const DL_Group& group, RandomNumberGenerator& rng) m_public_key(m_group.power_g_p(m_private_key, m_private_key.bits())) {} DL_PrivateKey::DL_PrivateKey(const AlgorithmIdentifier& alg_id, - std::span key_bits, + Botan::span key_bits, DL_Group_Format format) : m_group(alg_id.parameters(), format), m_private_key(check_dl_private_key_input(decode_single_bigint(key_bits), m_group)), diff --git a/src/lib/pubkey/dl_algo/dl_scheme.h b/src/lib/pubkey/dl_algo/dl_scheme.h index c306eea9153..40eddcef8e0 100644 --- a/src/lib/pubkey/dl_algo/dl_scheme.h +++ b/src/lib/pubkey/dl_algo/dl_scheme.h @@ -9,8 +9,8 @@ #include #include +#include #include -#include #include namespace Botan { @@ -22,7 +22,7 @@ class DL_PublicKey final { public: DL_PublicKey(const DL_Group& group, const BigInt& public_key); - DL_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits, DL_Group_Format format); + DL_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits, DL_Group_Format format); bool check_key(RandomNumberGenerator& rng, bool strong) const; @@ -52,7 +52,7 @@ class DL_PrivateKey final { DL_PrivateKey(const DL_Group& group, RandomNumberGenerator& rng); - DL_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits, DL_Group_Format format); + DL_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits, DL_Group_Format format); bool check_key(RandomNumberGenerator& rng, bool strong) const; diff --git a/src/lib/pubkey/dsa/dsa.cpp b/src/lib/pubkey/dsa/dsa.cpp index cd498405e2d..c123c9d57b1 100644 --- a/src/lib/pubkey/dsa/dsa.cpp +++ b/src/lib/pubkey/dsa/dsa.cpp @@ -48,7 +48,7 @@ bool DSA_PublicKey::check_key(RandomNumberGenerator& rng, bool strong) const { return m_public_key->check_key(rng, strong); } -DSA_PublicKey::DSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +DSA_PublicKey::DSA_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { m_public_key = std::make_shared(alg_id, key_bits, DL_Group_Format::ANSI_X9_57); BOTAN_ARG_CHECK(m_public_key->group().has_q(), "Q parameter must be set for DSA"); @@ -74,7 +74,7 @@ DSA_PrivateKey::DSA_PrivateKey(const DL_Group& group, const BigInt& x) { m_public_key = m_private_key->public_key(); } -DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { m_private_key = std::make_shared(alg_id, key_bits, DL_Group_Format::ANSI_X9_57); m_public_key = m_private_key->public_key(); diff --git a/src/lib/pubkey/dsa/dsa.h b/src/lib/pubkey/dsa/dsa.h index fe31f5cd3c0..3f682ecf56d 100644 --- a/src/lib/pubkey/dsa/dsa.h +++ b/src/lib/pubkey/dsa/dsa.h @@ -30,7 +30,7 @@ class BOTAN_PUBLIC_API(2, 0) DSA_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - DSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + DSA_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Load a public key from the integer value @@ -86,7 +86,7 @@ class BOTAN_PUBLIC_API(2, 0) DSA_PrivateKey final : public DSA_PublicKey, * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded key bits in ANSI X9.57 format */ - DSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + DSA_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a new private key. diff --git a/src/lib/pubkey/ec_group/ec_group.h b/src/lib/pubkey/ec_group/ec_group.h index b5d71c6226d..001c6e657a1 100644 --- a/src/lib/pubkey/ec_group/ec_group.h +++ b/src/lib/pubkey/ec_group/ec_group.h @@ -12,9 +12,9 @@ #include #include +#include #include #include -#include namespace Botan { @@ -334,7 +334,7 @@ class BOTAN_PUBLIC_API(2, 0) EC_Group final { EC_Point OS2ECP(const uint8_t bits[], size_t len) const; - EC_Point OS2ECP(std::span encoded_point) const { + EC_Point OS2ECP(Botan::span encoded_point) const { return this->OS2ECP(encoded_point.data(), encoded_point.size()); } diff --git a/src/lib/pubkey/ec_group/ec_point.h b/src/lib/pubkey/ec_group/ec_point.h index bdbc21ba494..fd05756e430 100644 --- a/src/lib/pubkey/ec_group/ec_point.h +++ b/src/lib/pubkey/ec_group/ec_point.h @@ -32,7 +32,7 @@ enum class EC_Point_Format { class BOTAN_PUBLIC_API(2, 0) EC_Point final { public: typedef EC_Point_Format Compression_Type; - using enum EC_Point_Format; + //using enum EC_Point_Format; enum { WORKSPACE_SIZE = 8 }; diff --git a/src/lib/pubkey/ecc_key/ecc_key.cpp b/src/lib/pubkey/ecc_key/ecc_key.cpp index 6b063f81dab..d7c58b5b5b1 100644 --- a/src/lib/pubkey/ecc_key/ecc_key.cpp +++ b/src/lib/pubkey/ecc_key/ecc_key.cpp @@ -41,7 +41,7 @@ EC_Group_Encoding default_encoding_for(EC_Group& group) { EC_PublicKey::EC_PublicKey(const EC_Group& dom_par, const EC_Point& pub_point) : m_domain_params(dom_par), m_public_key(pub_point), m_domain_encoding(default_encoding_for(m_domain_params)) {} -EC_PublicKey::EC_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : +EC_PublicKey::EC_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : m_domain_params{EC_Group(alg_id.parameters())}, m_public_key{domain().OS2ECP(key_bits)}, m_domain_encoding(default_encoding_for(m_domain_params)) {} @@ -127,7 +127,7 @@ secure_vector EC_PrivateKey::private_key_bits() const { } EC_PrivateKey::EC_PrivateKey(const AlgorithmIdentifier& alg_id, - std::span key_bits, + Botan::span key_bits, bool with_modular_inverse) { m_domain_params = EC_Group(alg_id.parameters()); m_domain_encoding = default_encoding_for(m_domain_params); diff --git a/src/lib/pubkey/ecc_key/ecc_key.h b/src/lib/pubkey/ecc_key/ecc_key.h index 19cd32d0bfc..9c45cad0543 100644 --- a/src/lib/pubkey/ecc_key/ecc_key.h +++ b/src/lib/pubkey/ecc_key/ecc_key.h @@ -101,7 +101,7 @@ class BOTAN_PUBLIC_API(2, 0) EC_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - EC_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + EC_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); EC_PublicKey() : m_domain_params{}, m_public_key{}, m_domain_encoding(EC_Group_Encoding::Explicit) {} @@ -161,7 +161,7 @@ class BOTAN_PUBLIC_API(2, 0) EC_PrivateKey : public virtual EC_PublicKey, * multiplying directly with x (as in ECDSA). */ EC_PrivateKey(const AlgorithmIdentifier& alg_id, - std::span key_bits, + Botan::span key_bits, bool with_modular_inverse = false); EC_PrivateKey() = default; diff --git a/src/lib/pubkey/ecdh/ecdh.h b/src/lib/pubkey/ecdh/ecdh.h index 0cd082f22b4..0e584ceaa0a 100644 --- a/src/lib/pubkey/ecdh/ecdh.h +++ b/src/lib/pubkey/ecdh/ecdh.h @@ -24,7 +24,7 @@ class BOTAN_PUBLIC_API(2, 0) ECDH_PublicKey : public virtual EC_PublicKey { * @param alg_id algorithm identifier * @param key_bits DER encoded public key bits */ - ECDH_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECDH_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PublicKey(alg_id, key_bits) {} /** @@ -72,7 +72,7 @@ class BOTAN_PUBLIC_API(2, 0) ECDH_PrivateKey final : public ECDH_PublicKey, * @param alg_id the X.509 algorithm identifier * @param key_bits ECPrivateKey bits */ - ECDH_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECDH_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PrivateKey(alg_id, key_bits) {} /** diff --git a/src/lib/pubkey/ecdsa/ecdsa.h b/src/lib/pubkey/ecdsa/ecdsa.h index a63c8a4f849..30993ebe62b 100644 --- a/src/lib/pubkey/ecdsa/ecdsa.h +++ b/src/lib/pubkey/ecdsa/ecdsa.h @@ -31,7 +31,7 @@ class BOTAN_PUBLIC_API(2, 0) ECDSA_PublicKey : public virtual EC_PublicKey { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - ECDSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECDSA_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PublicKey(alg_id, key_bits) {} /** @@ -85,7 +85,7 @@ class BOTAN_PUBLIC_API(2, 0) ECDSA_PrivateKey final : public ECDSA_PublicKey, * @param alg_id the X.509 algorithm identifier * @param key_bits ECPrivateKey bits */ - ECDSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECDSA_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PrivateKey(alg_id, key_bits) {} /** diff --git a/src/lib/pubkey/ecgdsa/ecgdsa.h b/src/lib/pubkey/ecgdsa/ecgdsa.h index 5735a483ebc..ed6b076d226 100644 --- a/src/lib/pubkey/ecgdsa/ecgdsa.h +++ b/src/lib/pubkey/ecgdsa/ecgdsa.h @@ -29,7 +29,7 @@ class BOTAN_PUBLIC_API(2, 0) ECGDSA_PublicKey : public virtual EC_PublicKey { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - ECGDSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECGDSA_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PublicKey(alg_id, key_bits) {} /** @@ -69,7 +69,7 @@ class BOTAN_PUBLIC_API(2, 0) ECGDSA_PrivateKey final : public ECGDSA_PublicKey, * @param alg_id the X.509 algorithm identifier * @param key_bits ECPrivateKey bits */ - ECGDSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECGDSA_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PrivateKey(alg_id, key_bits, true) {} /** diff --git a/src/lib/pubkey/eckcdsa/eckcdsa.h b/src/lib/pubkey/eckcdsa/eckcdsa.h index 045bd078b8d..e0e7d77139f 100644 --- a/src/lib/pubkey/eckcdsa/eckcdsa.h +++ b/src/lib/pubkey/eckcdsa/eckcdsa.h @@ -29,7 +29,7 @@ class BOTAN_PUBLIC_API(2, 0) ECKCDSA_PublicKey : public virtual EC_PublicKey { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - ECKCDSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECKCDSA_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PublicKey(alg_id, key_bits) {} /** @@ -68,7 +68,7 @@ class BOTAN_PUBLIC_API(2, 0) ECKCDSA_PrivateKey final : public ECKCDSA_PublicKey * @param alg_id the X.509 algorithm identifier * @param key_bits ECPrivateKey bits */ - ECKCDSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + ECKCDSA_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PrivateKey(alg_id, key_bits, true) {} /** diff --git a/src/lib/pubkey/ed25519/ed25519.h b/src/lib/pubkey/ed25519/ed25519.h index d2e9ce4bf28..50cb380812c 100644 --- a/src/lib/pubkey/ed25519/ed25519.h +++ b/src/lib/pubkey/ed25519/ed25519.h @@ -38,7 +38,7 @@ class BOTAN_PUBLIC_API(2, 2) Ed25519_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - Ed25519_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + Ed25519_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); template Ed25519_PublicKey(const std::vector& pub) : Ed25519_PublicKey(pub.data(), pub.size()) {} @@ -67,7 +67,7 @@ class BOTAN_PUBLIC_API(2, 2) Ed25519_PrivateKey final : public Ed25519_PublicKey * @param alg_id the X.509 algorithm identifier * @param key_bits PKCS #8 structure */ - Ed25519_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + Ed25519_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Generate a private key. diff --git a/src/lib/pubkey/ed25519/ed25519_internal.h b/src/lib/pubkey/ed25519/ed25519_internal.h index b3644edcc93..8925846c2ec 100644 --- a/src/lib/pubkey/ed25519/ed25519_internal.h +++ b/src/lib/pubkey/ed25519/ed25519_internal.h @@ -24,9 +24,8 @@ inline uint64_t load_4(const uint8_t* in) { return load_le(in, 0); } -template +template 0) && (S < 64)>> inline void carry(int64_t& h0, int64_t& h1) - requires(S > 0 && S < 64) { const int64_t X1 = (static_cast(1) << S); const int64_t X2 = (static_cast(1) << (S - 1)); @@ -35,9 +34,8 @@ inline void carry(int64_t& h0, int64_t& h1) h0 -= c * X1; } -template +template 0) && (S < 64)>> inline void carry0(int64_t& h0, int64_t& h1) - requires(S > 0 && S < 64) { const int64_t X1 = (static_cast(1) << S); int64_t c = h0 >> S; @@ -45,9 +43,8 @@ inline void carry0(int64_t& h0, int64_t& h1) h0 -= c * X1; } -template +template 0) && (S < 32)>> inline void carry0(int32_t& h0, int32_t& h1) - requires(S > 0 && S < 32) { const int32_t X1 = (static_cast(1) << S); int32_t c = h0 >> S; diff --git a/src/lib/pubkey/ed25519/ed25519_key.cpp b/src/lib/pubkey/ed25519/ed25519_key.cpp index 1d63b7b6980..665a586bfa5 100644 --- a/src/lib/pubkey/ed25519/ed25519_key.cpp +++ b/src/lib/pubkey/ed25519/ed25519_key.cpp @@ -70,7 +70,7 @@ Ed25519_PublicKey::Ed25519_PublicKey(const uint8_t pub_key[], size_t pub_len) { m_public.assign(pub_key, pub_key + pub_len); } -Ed25519_PublicKey::Ed25519_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span key_bits) { +Ed25519_PublicKey::Ed25519_PublicKey(const AlgorithmIdentifier& /*unused*/, Botan::span key_bits) { m_public.assign(key_bits.begin(), key_bits.end()); if(m_public.size() != 32) { @@ -102,7 +102,7 @@ Ed25519_PrivateKey::Ed25519_PrivateKey(RandomNumberGenerator& rng) { ed25519_gen_keypair(m_public.data(), m_private.data(), seed.data()); } -Ed25519_PrivateKey::Ed25519_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span key_bits) { +Ed25519_PrivateKey::Ed25519_PrivateKey(const AlgorithmIdentifier& /*unused*/, Botan::span key_bits) { secure_vector bits; BER_Decoder(key_bits).decode(bits, ASN1_Type::OctetString).discard_remaining(); diff --git a/src/lib/pubkey/elgamal/elgamal.cpp b/src/lib/pubkey/elgamal/elgamal.cpp index 8dda6da24c7..038216be123 100644 --- a/src/lib/pubkey/elgamal/elgamal.cpp +++ b/src/lib/pubkey/elgamal/elgamal.cpp @@ -19,7 +19,7 @@ ElGamal_PublicKey::ElGamal_PublicKey(const DL_Group& group, const BigInt& y) { m_public_key = std::make_shared(group, y); } -ElGamal_PublicKey::ElGamal_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +ElGamal_PublicKey::ElGamal_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { m_public_key = std::make_shared(alg_id, key_bits, DL_Group_Format::ANSI_X9_42); } @@ -57,7 +57,7 @@ ElGamal_PrivateKey::ElGamal_PrivateKey(const DL_Group& group, const BigInt& x) { m_public_key = m_private_key->public_key(); } -ElGamal_PrivateKey::ElGamal_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +ElGamal_PrivateKey::ElGamal_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { m_private_key = std::make_shared(alg_id, key_bits, DL_Group_Format::ANSI_X9_42); m_public_key = m_private_key->public_key(); } diff --git a/src/lib/pubkey/elgamal/elgamal.h b/src/lib/pubkey/elgamal/elgamal.h index 2f8ed456f07..70573f0b014 100644 --- a/src/lib/pubkey/elgamal/elgamal.h +++ b/src/lib/pubkey/elgamal/elgamal.h @@ -30,7 +30,7 @@ class BOTAN_PUBLIC_API(2, 0) ElGamal_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - ElGamal_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + ElGamal_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a public key. @@ -80,7 +80,7 @@ class BOTAN_PUBLIC_API(2, 0) ElGamal_PrivateKey final : public ElGamal_PublicKey * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded key bits in ANSI X9.42 format */ - ElGamal_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + ElGamal_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a new random private key. diff --git a/src/lib/pubkey/gost_3410/gost_3410.cpp b/src/lib/pubkey/gost_3410/gost_3410.cpp index a17e5a1e93c..ccdf2f0fe0f 100644 --- a/src/lib/pubkey/gost_3410/gost_3410.cpp +++ b/src/lib/pubkey/gost_3410/gost_3410.cpp @@ -61,7 +61,7 @@ AlgorithmIdentifier GOST_3410_PublicKey::algorithm_identifier() const { return AlgorithmIdentifier(gost_oid, params); } -GOST_3410_PublicKey::GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) { +GOST_3410_PublicKey::GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) { OID ecc_param_id; // The parameters also includes hash and cipher OIDs diff --git a/src/lib/pubkey/gost_3410/gost_3410.h b/src/lib/pubkey/gost_3410/gost_3410.h index 4b51eb28298..f5a12515864 100644 --- a/src/lib/pubkey/gost_3410/gost_3410.h +++ b/src/lib/pubkey/gost_3410/gost_3410.h @@ -32,7 +32,7 @@ class BOTAN_PUBLIC_API(2, 0) GOST_3410_PublicKey : public virtual EC_PublicKey { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + GOST_3410_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Get this keys algorithm name. @@ -77,7 +77,7 @@ class BOTAN_PUBLIC_API(2, 0) GOST_3410_PrivateKey final : public GOST_3410_Publi * @param alg_id the X.509 algorithm identifier * @param key_bits ECPrivateKey bits */ - GOST_3410_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + GOST_3410_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PrivateKey(alg_id, key_bits) {} /** diff --git a/src/lib/pubkey/kyber/kyber/kyber_modern.h b/src/lib/pubkey/kyber/kyber/kyber_modern.h index 15faa3c17e0..333e77017b5 100644 --- a/src/lib/pubkey/kyber/kyber/kyber_modern.h +++ b/src/lib/pubkey/kyber/kyber/kyber_modern.h @@ -35,7 +35,7 @@ class Kyber_Modern_Symmetric_Primitives : public Kyber_Symmetric_Primitives { std::unique_ptr KDF() const override { return m_shake256_256->new_object(); } - Botan::XOF& XOF(std::span seed, std::tuple matrix_position) const override { + Botan::XOF& XOF(Botan::span seed, std::tuple matrix_position) const override { m_shake128->clear(); m_shake128->update(seed); @@ -45,7 +45,7 @@ class Kyber_Modern_Symmetric_Primitives : public Kyber_Symmetric_Primitives { return *m_shake128; } - secure_vector PRF(std::span seed, + secure_vector PRF(Botan::span seed, const uint8_t nonce, const size_t outlen) const override { SHAKE_256 kdf(outlen * 8); diff --git a/src/lib/pubkey/kyber/kyber_90s/kyber_90s.h b/src/lib/pubkey/kyber/kyber_90s/kyber_90s.h index cebced2a8c3..f32f0618b40 100644 --- a/src/lib/pubkey/kyber/kyber_90s/kyber_90s.h +++ b/src/lib/pubkey/kyber/kyber_90s/kyber_90s.h @@ -33,14 +33,14 @@ class Kyber_90s_Symmetric_Primitives : public Kyber_Symmetric_Primitives { std::unique_ptr KDF() const override { return m_sha256->new_object(); } - Botan::XOF& XOF(std::span seed, std::tuple mpos) const override { + Botan::XOF& XOF(Botan::span seed, std::tuple mpos) const override { m_aes256_ctr_xof->clear(); const std::array iv{std::get<0>(mpos), std::get<1>(mpos), 0}; m_aes256_ctr_xof->start(iv, seed); return *m_aes256_ctr_xof; } - secure_vector PRF(std::span seed, + secure_vector PRF(Botan::span seed, const uint8_t nonce, const size_t outlen) const override { m_aes256_ctr_prf->clear(); diff --git a/src/lib/pubkey/kyber/kyber_common/kyber.cpp b/src/lib/pubkey/kyber/kyber_common/kyber.cpp index 23278a49a45..93367770c1f 100644 --- a/src/lib/pubkey/kyber/kyber_common/kyber.cpp +++ b/src/lib/pubkey/kyber/kyber_common/kyber.cpp @@ -212,11 +212,11 @@ class KyberConstants { std::unique_ptr KDF() const { return m_symmetric_primitives->KDF(); } - Botan::XOF& XOF(std::span seed, std::tuple matrix_position) const { + Botan::XOF& XOF(Botan::span seed, std::tuple matrix_position) const { return m_symmetric_primitives->XOF(seed, matrix_position); } - secure_vector PRF(std::span seed, const uint8_t nonce, const size_t outlen) const { + secure_vector PRF(Botan::span seed, const uint8_t nonce, const size_t outlen) const { return m_symmetric_primitives->PRF(seed, nonce, outlen); } @@ -270,7 +270,7 @@ class Polynomial { * Given an array of uniformly random bytes, compute polynomial with coefficients * distributed according to a centered binomial distribution with parameter eta=2 */ - static Polynomial cbd2(std::span buf) { + static Polynomial cbd2(Botan::span buf) { Polynomial r; BOTAN_ASSERT(buf.size() == (2 * r.size() / 4), "wrong input buffer size for cbd2"); @@ -296,7 +296,7 @@ class Polynomial { * * This function is only needed for Kyber-512 */ - static Polynomial cbd3(std::span buf) { + static Polynomial cbd3(Botan::span buf) { Polynomial r; BOTAN_ASSERT(buf.size() == (3 * r.size() / 4), "wrong input buffer size for cbd3"); @@ -326,7 +326,7 @@ class Polynomial { * Sample a polynomial deterministically from a seed and a nonce, with output * polynomial close to centered binomial distribution with parameter eta=2. */ - static Polynomial getnoise_eta2(std::span seed, uint8_t nonce, const KyberConstants& mode) { + static Polynomial getnoise_eta2(Botan::span seed, uint8_t nonce, const KyberConstants& mode) { const auto eta2 = mode.eta2(); BOTAN_ASSERT(eta2 == 2, "Invalid eta2 value"); @@ -338,7 +338,7 @@ class Polynomial { * Sample a polynomial deterministically from a seed and a nonce, with output * polynomial close to centered binomial distribution with parameter mode.eta1() */ - static Polynomial getnoise_eta1(std::span seed, uint8_t nonce, const KyberConstants& mode) { + static Polynomial getnoise_eta1(Botan::span seed, uint8_t nonce, const KyberConstants& mode) { const auto eta1 = mode.eta1(); BOTAN_ASSERT(eta1 == 2 || eta1 == 3, "Invalid eta1 value"); @@ -347,7 +347,7 @@ class Polynomial { : Polynomial::cbd3(mode.PRF(seed, nonce, outlen)); } - static Polynomial from_bytes(std::span a) { + static Polynomial from_bytes(Botan::span a) { Polynomial r; for(size_t i = 0; i < r.size() / 2; ++i) { r.m_coeffs[2 * i] = ((a[3 * i + 0] >> 0) | (static_cast(a[3 * i + 1]) << 8)) & 0xFFF; @@ -356,7 +356,7 @@ class Polynomial { return r; } - static Polynomial from_message(std::span msg) { + static Polynomial from_message(Botan::span msg) { BOTAN_ASSERT(msg.size() == KyberConstants::N / 8, "message length must be Kyber_N/8 bytes"); Polynomial r; @@ -564,7 +564,7 @@ class PolynomialVector { explicit PolynomialVector(const size_t k) : m_vec(k) {} - static PolynomialVector from_bytes(std::span a, const KyberConstants& mode) { + static PolynomialVector from_bytes(Botan::span a, const KyberConstants& mode) { BOTAN_ASSERT(a.size() == mode.polynomial_vector_byte_length(), "wrong byte length for frombytes"); PolynomialVector r(mode.k()); @@ -592,7 +592,9 @@ class PolynomialVector { return r; } - static PolynomialVector getnoise_eta2(std::span seed, uint8_t nonce, const KyberConstants& mode) { + static PolynomialVector getnoise_eta2(Botan::span seed, + uint8_t nonce, + const KyberConstants& mode) { PolynomialVector r(mode.k()); for(auto& p : r.m_vec) { @@ -602,7 +604,9 @@ class PolynomialVector { return r; } - static PolynomialVector getnoise_eta1(std::span seed, uint8_t nonce, const KyberConstants& mode) { + static PolynomialVector getnoise_eta1(Botan::span seed, + uint8_t nonce, + const KyberConstants& mode) { PolynomialVector r(mode.k()); for(auto& p : r.m_vec) { @@ -681,7 +685,7 @@ class PolynomialMatrix { public: PolynomialMatrix() = delete; - static PolynomialMatrix generate(std::span seed, + static PolynomialMatrix generate(Botan::span seed, const bool transposed, const KyberConstants& mode) { BOTAN_ASSERT(seed.size() == KyberConstants::kSymBytes, "unexpected seed size"); @@ -725,7 +729,7 @@ class Ciphertext { Ciphertext(PolynomialVector b, const Polynomial& v, KyberConstants mode) : m_mode(std::move(mode)), m_b(std::move(b)), m_v(v) {} - static Ciphertext from_bytes(std::span buffer, const KyberConstants& mode) { + static Ciphertext from_bytes(Botan::span buffer, const KyberConstants& mode) { const size_t pvb = polynomial_vector_compressed_bytes(mode); const size_t pcb = polynomial_compressed_bytes(mode); @@ -862,7 +866,7 @@ class Ciphertext { return r; } - static PolynomialVector decompress_polynomial_vector(std::span buffer, + static PolynomialVector decompress_polynomial_vector(Botan::span buffer, const KyberConstants& mode) { BOTAN_ASSERT(buffer.size() == polynomial_vector_compressed_bytes(mode), "unexpected length of compressed polynomial vector"); @@ -909,7 +913,7 @@ class Ciphertext { return r; } - static Polynomial decompress_polynomial(std::span buffer, const KyberConstants& mode) { + static Polynomial decompress_polynomial(Botan::span buffer, const KyberConstants& mode) { BOTAN_ASSERT(buffer.size() == polynomial_compressed_bytes(mode), "unexpected length of compressed polynomial"); Polynomial r; @@ -953,7 +957,7 @@ class Ciphertext { class Kyber_PublicKeyInternal { public: - Kyber_PublicKeyInternal(KyberConstants mode, std::span polynomials, std::vector seed) : + Kyber_PublicKeyInternal(KyberConstants mode, Botan::span polynomials, std::vector seed) : m_mode(std::move(mode)), m_polynomials(PolynomialVector::from_bytes(polynomials, m_mode)), m_seed(std::move(seed)), @@ -1013,7 +1017,7 @@ class Kyber_KEM_Cryptor { m_mode(m_public_key->mode()), m_at(PolynomialMatrix::generate(m_public_key->seed(), true, m_mode)) {} - secure_vector indcpa_enc(std::span m, std::span coins) { + secure_vector indcpa_enc(Botan::span m, Botan::span coins) { auto sp = PolynomialVector::getnoise_eta1(coins, 0, m_mode); auto ep = PolynomialVector::getnoise_eta2(coins, m_mode.k(), m_mode); auto epp = Polynomial::getnoise_eta2(coins, 2 * m_mode.k(), m_mode); @@ -1075,8 +1079,8 @@ class Kyber_KEM_Encryptor final : public PK_Ops::KEM_Encryption_with_KDF, return kyber_key_length_to_encap_key_length(m_key.key_length()); } - void raw_kem_encrypt(std::span out_encapsulated_key, - std::span out_shared_key, + void raw_kem_encrypt(Botan::span out_encapsulated_key, + Botan::span out_shared_key, RandomNumberGenerator& rng) override { // naming from kyber spec auto H = mode().H(); @@ -1093,12 +1097,12 @@ class Kyber_KEM_Encryptor final : public PK_Ops::KEM_Encryption_with_KDF, BOTAN_ASSERT_EQUAL(g_out.size(), 64, "Expected output length of Kyber G"); - const auto lower_g_out = std::span(g_out).subspan(0, 32); - const auto upper_g_out = std::span(g_out).subspan(32, 32); + const auto lower_g_out = Botan::span(g_out).subspan(0, 32); + const auto upper_g_out = Botan::span(g_out).subspan(32, 32); const auto encapsulation = indcpa_enc(shared_secret, upper_g_out); - // TODO: avoid copy by letting Ciphertext write straight into std::span<> + // TODO: avoid copy by letting Ciphertext write straight into Botan::span<> BOTAN_ASSERT_NOMSG(encapsulation.size() == out_encapsulated_key.size()); std::copy(encapsulation.begin(), encapsulation.end(), out_encapsulated_key.begin()); @@ -1123,7 +1127,7 @@ class Kyber_KEM_Decryptor final : public PK_Ops::KEM_Decryption_with_KDF, return kyber_key_length_to_encap_key_length(m_key.key_length()); } - void raw_kem_decrypt(std::span out_shared_key, std::span encapsulated_key) override { + void raw_kem_decrypt(Botan::span out_shared_key, Botan::span encapsulated_key) override { // naming from kyber spec auto H = mode().H(); auto G = mode().G(); @@ -1139,8 +1143,8 @@ class Kyber_KEM_Decryptor final : public PK_Ops::KEM_Decryption_with_KDF, BOTAN_ASSERT_EQUAL(g_out.size(), 64, "Expected output length of Kyber G"); - const auto lower_g_out = std::span(g_out).subspan(0, 32); - const auto upper_g_out = std::span(g_out).subspan(32, 32); + const auto lower_g_out = Botan::span(g_out).subspan(0, 32); + const auto upper_g_out = Botan::span(g_out).subspan(32, 32); H->update(encapsulated_key); @@ -1164,7 +1168,7 @@ class Kyber_KEM_Decryptor final : public PK_Ops::KEM_Decryption_with_KDF, } private: - secure_vector indcpa_dec(std::span c) { + secure_vector indcpa_dec(Botan::span c) { auto ct = Ciphertext::from_bytes(c, mode()); return ct.indcpa_decrypt(m_key.m_private->polynomials()); } @@ -1193,7 +1197,7 @@ size_t Kyber_PublicKey::estimated_strength() const { return m_public->mode().estimated_strength(); } -std::shared_ptr Kyber_PublicKey::initialize_from_encoding(std::span pub_key, +std::shared_ptr Kyber_PublicKey::initialize_from_encoding(Botan::span pub_key, KyberMode m) { KyberConstants mode(m); @@ -1210,10 +1214,10 @@ std::shared_ptr Kyber_PublicKey::initialize_from_encodi return std::make_shared(std::move(mode), poly_vec, std::move(seed)); } -Kyber_PublicKey::Kyber_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : +Kyber_PublicKey::Kyber_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : Kyber_PublicKey(key_bits, KyberMode(alg_id.oid())) {} -Kyber_PublicKey::Kyber_PublicKey(std::span pub_key, KyberMode m) : +Kyber_PublicKey::Kyber_PublicKey(Botan::span pub_key, KyberMode m) : m_public(initialize_from_encoding(pub_key, m)) {} Kyber_PublicKey::Kyber_PublicKey(const Kyber_PublicKey& other) : @@ -1269,10 +1273,10 @@ Kyber_PrivateKey::Kyber_PrivateKey(RandomNumberGenerator& rng, KyberMode m) { std::move(mode), std::move(skpv), rng.random_vec(KyberConstants::kZLength)); } -Kyber_PrivateKey::Kyber_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : +Kyber_PrivateKey::Kyber_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : Kyber_PrivateKey(key_bits, KyberMode(alg_id.oid())) {} -Kyber_PrivateKey::Kyber_PrivateKey(std::span sk, KyberMode m) { +Kyber_PrivateKey::Kyber_PrivateKey(Botan::span sk, KyberMode m) { KyberConstants mode(m); if(mode.private_key_byte_length() != sk.size()) { diff --git a/src/lib/pubkey/kyber/kyber_common/kyber.h b/src/lib/pubkey/kyber/kyber_common/kyber.h index a3600e68b50..31a4d51a852 100644 --- a/src/lib/pubkey/kyber/kyber_common/kyber.h +++ b/src/lib/pubkey/kyber/kyber_common/kyber.h @@ -19,7 +19,7 @@ #include #include -#include +#include #if !defined(BOTAN_HAS_KYBER_90S) && !defined(BOTAN_HAS_KYBER) static_assert(false, "botan module 'kyber_common' is useful only when enabling modules 'kyber', 'kyber_90s' or both"); @@ -72,9 +72,9 @@ class Kyber_PrivateKeyInternal; class BOTAN_PUBLIC_API(3, 0) Kyber_PublicKey : public virtual Public_Key { public: - Kyber_PublicKey(std::span pub_key, KyberMode mode); + Kyber_PublicKey(Botan::span pub_key, KyberMode mode); - Kyber_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + Kyber_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); Kyber_PublicKey(const Kyber_PublicKey& other); @@ -108,7 +108,7 @@ class BOTAN_PUBLIC_API(3, 0) Kyber_PublicKey : public virtual Public_Key { protected: Kyber_PublicKey() = default; - static std::shared_ptr initialize_from_encoding(std::span pub_key, + static std::shared_ptr initialize_from_encoding(Botan::span pub_key, KyberMode m); const std::vector& public_key_bits_raw() const; @@ -129,9 +129,9 @@ class BOTAN_PUBLIC_API(3, 0) Kyber_PrivateKey final : public virtual Kyber_Publi public: Kyber_PrivateKey(RandomNumberGenerator& rng, KyberMode mode); - Kyber_PrivateKey(std::span sk, KyberMode mode); + Kyber_PrivateKey(Botan::span sk, KyberMode mode); - Kyber_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + Kyber_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); std::unique_ptr public_key() const override; diff --git a/src/lib/pubkey/kyber/kyber_common/kyber_symmetric_primitives.h b/src/lib/pubkey/kyber/kyber_common/kyber_symmetric_primitives.h index 37fe6c5c927..72dfa3fc5c7 100644 --- a/src/lib/pubkey/kyber/kyber_common/kyber_symmetric_primitives.h +++ b/src/lib/pubkey/kyber/kyber_common/kyber_symmetric_primitives.h @@ -11,9 +11,9 @@ #include #include +#include #include -#include #include #include @@ -33,9 +33,9 @@ class Kyber_Symmetric_Primitives { virtual std::unique_ptr H() const = 0; virtual std::unique_ptr KDF() const = 0; - virtual Botan::XOF& XOF(std::span seed, std::tuple matrix_position) const = 0; + virtual Botan::XOF& XOF(Botan::span seed, std::tuple matrix_position) const = 0; - virtual secure_vector PRF(std::span seed, uint8_t nonce, size_t outlen) const = 0; + virtual secure_vector PRF(Botan::span seed, uint8_t nonce, size_t outlen) const = 0; }; } // namespace Botan diff --git a/src/lib/pubkey/mce/mceliece.h b/src/lib/pubkey/mce/mceliece.h index 3d798b67b10..2defe3cccc0 100644 --- a/src/lib/pubkey/mce/mceliece.h +++ b/src/lib/pubkey/mce/mceliece.h @@ -22,7 +22,7 @@ class polyn_gf2m; class BOTAN_PUBLIC_API(2, 0) McEliece_PublicKey : public virtual Public_Key { public: - explicit McEliece_PublicKey(std::span key_bits); + explicit McEliece_PublicKey(Botan::span key_bits); McEliece_PublicKey(const std::vector& pub_matrix, size_t t, size_t the_code_length) : m_public_matrix(pub_matrix), m_t(t), m_code_length(the_code_length) {} @@ -91,7 +91,7 @@ class BOTAN_PUBLIC_API(2, 0) McEliece_PrivateKey final : public virtual McEliece */ McEliece_PrivateKey(RandomNumberGenerator& rng, size_t code_length, size_t t); - explicit McEliece_PrivateKey(std::span key_bits); + explicit McEliece_PrivateKey(Botan::span key_bits); McEliece_PrivateKey(const polyn_gf2m& goppa_polyn, const std::vector& parity_check_matrix_coeffs, diff --git a/src/lib/pubkey/mce/mceliece_key.cpp b/src/lib/pubkey/mce/mceliece_key.cpp index 8e54fd56230..ad076a23d70 100644 --- a/src/lib/pubkey/mce/mceliece_key.cpp +++ b/src/lib/pubkey/mce/mceliece_key.cpp @@ -98,7 +98,7 @@ size_t McEliece_PublicKey::estimated_strength() const { return mceliece_work_factor(m_code_length, m_t); } -McEliece_PublicKey::McEliece_PublicKey(std::span key_bits) { +McEliece_PublicKey::McEliece_PublicKey(Botan::span key_bits) { BER_Decoder dec(key_bits); size_t n; size_t t; @@ -164,7 +164,7 @@ bool McEliece_PrivateKey::check_key(RandomNumberGenerator& rng, bool /*unused*/) return true; } -McEliece_PrivateKey::McEliece_PrivateKey(std::span key_bits) { +McEliece_PrivateKey::McEliece_PrivateKey(Botan::span key_bits) { size_t n, t; secure_vector enc_g; BER_Decoder dec_base(key_bits); @@ -290,8 +290,8 @@ class MCE_KEM_Encryptor final : public PK_Ops::KEM_Encryption_with_KDF { size_t encapsulated_key_length() const override { return (m_key.get_code_length() + 7) / 8; } - void raw_kem_encrypt(std::span out_encapsulated_key, - std::span raw_shared_key, + void raw_kem_encrypt(Botan::span out_encapsulated_key, + Botan::span raw_shared_key, RandomNumberGenerator& rng) override { secure_vector plaintext = m_key.random_plaintext_element(rng); @@ -325,7 +325,7 @@ class MCE_KEM_Decryptor final : public PK_Ops::KEM_Decryption_with_KDF { size_t encapsulated_key_length() const override { return (m_key.get_code_length() + 7) / 8; } - void raw_kem_decrypt(std::span out_shared_key, std::span encapsulated_key) override { + void raw_kem_decrypt(Botan::span out_shared_key, Botan::span encapsulated_key) override { secure_vector plaintext, error_mask; mceliece_decrypt(plaintext, error_mask, encapsulated_key.data(), encapsulated_key.size(), m_key); diff --git a/src/lib/pubkey/pbes2/pbes2.cpp b/src/lib/pubkey/pbes2/pbes2.cpp index c9b7b483530..e8640d2fd3d 100644 --- a/src/lib/pubkey/pbes2/pbes2.cpp +++ b/src/lib/pubkey/pbes2/pbes2.cpp @@ -16,6 +16,7 @@ #include #include #include +#include namespace Botan { @@ -53,7 +54,7 @@ secure_vector derive_key(std::string_view passphrase, } const std::string prf = prf_algo.oid().human_name_or_empty(); - if(prf.empty() || !prf.starts_with("HMAC")) { + if(prf.empty() || !starts_with(prf, "HMAC")) { throw Decoding_Error(fmt("Unknown PBES2 PRF {}", prf_algo.oid())); } @@ -183,7 +184,7 @@ secure_vector derive_key(std::string_view passphrase, /* * PKCS#5 v2.0 PBE Encryption */ -std::pair> pbes2_encrypt_shared(std::span key_bits, +std::pair> pbes2_encrypt_shared(Botan::span key_bits, std::string_view passphrase, size_t* msec_in_iterations_out, size_t iterations_if_msec_null, @@ -229,7 +230,7 @@ std::pair> pbes2_encrypt_shared(std::s } // namespace -std::pair> pbes2_encrypt(std::span key_bits, +std::pair> pbes2_encrypt(Botan::span key_bits, std::string_view passphrase, std::chrono::milliseconds msec, std::string_view cipher, @@ -240,7 +241,7 @@ std::pair> pbes2_encrypt(std::span> pbes2_encrypt_msec(std::span key_bits, +std::pair> pbes2_encrypt_msec(Botan::span key_bits, std::string_view passphrase, std::chrono::milliseconds msec, size_t* out_iterations_if_nonnull, @@ -258,7 +259,7 @@ std::pair> pbes2_encrypt_msec(std::spa return ret; } -std::pair> pbes2_encrypt_iter(std::span key_bits, +std::pair> pbes2_encrypt_iter(Botan::span key_bits, std::string_view passphrase, size_t pbkdf_iter, std::string_view cipher, @@ -267,7 +268,7 @@ std::pair> pbes2_encrypt_iter(std::spa return pbes2_encrypt_shared(key_bits, passphrase, nullptr, pbkdf_iter, cipher, digest, rng); } -secure_vector pbes2_decrypt(std::span key_bits, +secure_vector pbes2_decrypt(Botan::span key_bits, std::string_view passphrase, const std::vector& params) { AlgorithmIdentifier kdf_algo, enc_algo; diff --git a/src/lib/pubkey/pbes2/pbes2.h b/src/lib/pubkey/pbes2/pbes2.h index b256e7c6992..bf174539e10 100644 --- a/src/lib/pubkey/pbes2/pbes2.h +++ b/src/lib/pubkey/pbes2/pbes2.h @@ -9,8 +9,8 @@ #define BOTAN_PBE_PKCS_V20_H_ #include +#include #include -#include namespace Botan { @@ -25,7 +25,7 @@ class RandomNumberGenerator; * @param digest specifies the PRF to use with PBKDF2 (eg "HMAC(SHA-1)") * @param rng a random number generator */ -std::pair> pbes2_encrypt(std::span key_bits, +std::pair> pbes2_encrypt(Botan::span key_bits, std::string_view passphrase, std::chrono::milliseconds msec, std::string_view cipher, @@ -43,7 +43,7 @@ std::pair> pbes2_encrypt(std::span> pbes2_encrypt_msec(std::span key_bits, +std::pair> pbes2_encrypt_msec(Botan::span key_bits, std::string_view passphrase, std::chrono::milliseconds msec, size_t* out_iterations_if_nonnull, @@ -60,7 +60,7 @@ std::pair> pbes2_encrypt_msec(std::spa * @param digest specifies the PRF to use with PBKDF2 (eg "HMAC(SHA-1)") * @param rng a random number generator */ -std::pair> pbes2_encrypt_iter(std::span key_bits, +std::pair> pbes2_encrypt_iter(Botan::span key_bits, std::string_view passphrase, size_t iterations, std::string_view cipher, @@ -73,7 +73,7 @@ std::pair> pbes2_encrypt_iter(std::spa * @param passphrase the passphrase to use for decryption * @param params the PBES2 parameters */ -secure_vector pbes2_decrypt(std::span key_bits, +secure_vector pbes2_decrypt(Botan::span key_bits, std::string_view passphrase, const std::vector& params); diff --git a/src/lib/pubkey/pk_algs.cpp b/src/lib/pubkey/pk_algs.cpp index 69cd2971e45..c11eaf37d31 100644 --- a/src/lib/pubkey/pk_algs.cpp +++ b/src/lib/pubkey/pk_algs.cpp @@ -9,6 +9,7 @@ #include #include +#include #if defined(BOTAN_HAS_RSA) #include @@ -89,7 +90,7 @@ namespace Botan { std::unique_ptr load_public_key(const AlgorithmIdentifier& alg_id, - [[maybe_unused]] std::span key_bits) { + [[maybe_unused]] Botan::span key_bits) { const std::string oid_str = alg_id.oid().to_formatted_string(); const std::vector alg_info = split_on(oid_str, '/'); std::string_view alg_name = alg_info[0]; @@ -113,7 +114,7 @@ std::unique_ptr load_public_key(const AlgorithmIdentifier& alg_id, #endif #if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S) - if(alg_name == "Kyber" || alg_name.starts_with("Kyber-")) { + if(alg_name == "Kyber" || starts_with(alg_name, "Kyber-")) { return std::make_unique(alg_id, key_bits); } #endif @@ -185,13 +186,13 @@ std::unique_ptr load_public_key(const AlgorithmIdentifier& alg_id, #endif #if defined(BOTAN_HAS_DILITHIUM) || defined(BOTAN_HAS_DILITHIUM_AES) - if(alg_name == "Dilithium" || alg_name.starts_with("Dilithium-")) { + if(alg_name == "Dilithium" || starts_with(alg_name, "Dilithium-")) { return std::make_unique(alg_id, key_bits); } #endif #if defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHA2) || defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHAKE) - if(alg_name == "SPHINCS+" || alg_name.starts_with("SphincsPlus-")) { + if(alg_name == "SPHINCS+" || Botan::starts_with(alg_name, "SphincsPlus-")) { return std::make_unique(alg_id, key_bits); } #endif @@ -200,7 +201,7 @@ std::unique_ptr load_public_key(const AlgorithmIdentifier& alg_id, } std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, - [[maybe_unused]] std::span key_bits) { + [[maybe_unused]] Botan::span key_bits) { const std::string oid_str = alg_id.oid().to_formatted_string(); const std::vector alg_info = split_on(oid_str, '/'); std::string_view alg_name = alg_info[0]; @@ -242,7 +243,7 @@ std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, #endif #if defined(BOTAN_HAS_KYBER) || defined(BOTAN_HAS_KYBER_90S) - if(alg_name == "Kyber" || alg_name.starts_with("Kyber-")) { + if(alg_name == "Kyber" || starts_with(alg_name, "Kyber-")) { return std::make_unique(alg_id, key_bits); } #endif @@ -296,13 +297,13 @@ std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, #endif #if defined(BOTAN_HAS_DILITHIUM) || defined(BOTAN_HAS_DILITHIUM_AES) - if(alg_name == "Dilithium" || alg_name.starts_with("Dilithium-")) { + if(alg_name == "Dilithium" || starts_with(alg_name, "Dilithium-")) { return std::make_unique(alg_id, key_bits); } #endif #if defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHA2) || defined(BOTAN_HAS_SPHINCS_PLUS_WITH_SHAKE) - if(alg_name == "SPHINCS+" || alg_name.starts_with("SphincsPlus-")) { + if(alg_name == "SPHINCS+" || starts_with(alg_name, "SphincsPlus-")) { return std::make_unique(alg_id, key_bits); } #endif diff --git a/src/lib/pubkey/pk_algs.h b/src/lib/pubkey/pk_algs.h index 2b98a219f49..7e499def38f 100644 --- a/src/lib/pubkey/pk_algs.h +++ b/src/lib/pubkey/pk_algs.h @@ -15,10 +15,10 @@ namespace Botan { BOTAN_PUBLIC_API(2, 0) -std::unique_ptr load_public_key(const AlgorithmIdentifier& alg_id, std::span key_bits); +std::unique_ptr load_public_key(const AlgorithmIdentifier& alg_id, Botan::span key_bits); BOTAN_PUBLIC_API(2, 0) -std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, std::span key_bits); +std::unique_ptr load_private_key(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a new key diff --git a/src/lib/pubkey/pk_keys.h b/src/lib/pubkey/pk_keys.h index 618b48cff61..66340ed6f84 100644 --- a/src/lib/pubkey/pk_keys.h +++ b/src/lib/pubkey/pk_keys.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -364,7 +364,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Key_Agreement_Key : public virtual Private_Key { std::string BOTAN_PUBLIC_API(2, 4) create_hex_fingerprint(const uint8_t bits[], size_t len, std::string_view hash_name); -inline std::string create_hex_fingerprint(std::span vec, std::string_view hash_name) { +inline std::string create_hex_fingerprint(Botan::span vec, std::string_view hash_name) { return create_hex_fingerprint(vec.data(), vec.size(), hash_name); } diff --git a/src/lib/pubkey/pk_ops.cpp b/src/lib/pubkey/pk_ops.cpp index f81a8cf2543..61e5343300d 100644 --- a/src/lib/pubkey/pk_ops.cpp +++ b/src/lib/pubkey/pk_ops.cpp @@ -166,11 +166,11 @@ size_t PK_Ops::KEM_Encryption_with_KDF::shared_key_length(size_t desired_shared_ } } -void PK_Ops::KEM_Encryption_with_KDF::kem_encrypt(std::span out_encapsulated_key, - std::span out_shared_key, +void PK_Ops::KEM_Encryption_with_KDF::kem_encrypt(Botan::span out_encapsulated_key, + Botan::span out_shared_key, RandomNumberGenerator& rng, size_t desired_shared_key_len, - std::span salt) { + Botan::span salt) { BOTAN_ARG_CHECK(salt.empty() || m_kdf, "PK_KEM_Encryptor::encrypt requires a KDF to use a salt"); BOTAN_ASSERT_NOMSG(out_encapsulated_key.size() == encapsulated_key_length()); @@ -201,10 +201,10 @@ size_t PK_Ops::KEM_Decryption_with_KDF::shared_key_length(size_t desired_shared_ } } -void PK_Ops::KEM_Decryption_with_KDF::kem_decrypt(std::span out_shared_key, - std::span encapsulated_key, +void PK_Ops::KEM_Decryption_with_KDF::kem_decrypt(Botan::span out_shared_key, + Botan::span encapsulated_key, size_t desired_shared_key_len, - std::span salt) { + Botan::span salt) { BOTAN_ARG_CHECK(salt.empty() || m_kdf, "PK_KEM_Decryptor::decrypt requires a KDF to use a salt"); if(m_kdf) { diff --git a/src/lib/pubkey/pk_ops.h b/src/lib/pubkey/pk_ops.h index 846ceb94bc7..a6e45d0ce27 100644 --- a/src/lib/pubkey/pk_ops.h +++ b/src/lib/pubkey/pk_ops.h @@ -139,11 +139,11 @@ class Key_Agreement { */ class KEM_Encryption { public: - virtual void kem_encrypt(std::span out_encapsulated_key, - std::span out_shared_key, + virtual void kem_encrypt(Botan::span out_encapsulated_key, + Botan::span out_shared_key, RandomNumberGenerator& rng, size_t desired_shared_key_len, - std::span salt) = 0; + Botan::span salt) = 0; virtual size_t shared_key_length(size_t desired_shared_key_len) const = 0; @@ -154,10 +154,10 @@ class KEM_Encryption { class KEM_Decryption { public: - virtual void kem_decrypt(std::span out_shared_key, - std::span encapsulated_key, + virtual void kem_decrypt(Botan::span out_shared_key, + Botan::span encapsulated_key, size_t desired_shared_key_len, - std::span salt) = 0; + Botan::span salt) = 0; virtual size_t shared_key_length(size_t desired_shared_key_len) const = 0; diff --git a/src/lib/pubkey/pk_ops_impl.h b/src/lib/pubkey/pk_ops_impl.h index d95f960158b..cc1c2a605d6 100644 --- a/src/lib/pubkey/pk_ops_impl.h +++ b/src/lib/pubkey/pk_ops_impl.h @@ -120,19 +120,19 @@ class Key_Agreement_with_KDF : public Key_Agreement { class KEM_Encryption_with_KDF : public KEM_Encryption { public: - void kem_encrypt(std::span out_encapsulated_key, - std::span out_shared_key, + void kem_encrypt(Botan::span out_encapsulated_key, + Botan::span out_shared_key, RandomNumberGenerator& rng, size_t desired_shared_key_len, - std::span salt) final; + Botan::span salt) final; size_t shared_key_length(size_t desired_shared_key_len) const final; ~KEM_Encryption_with_KDF() override = default; protected: - virtual void raw_kem_encrypt(std::span out_encapsulated_key, - std::span out_raw_shared_key, + virtual void raw_kem_encrypt(Botan::span out_encapsulated_key, + Botan::span out_raw_shared_key, RandomNumberGenerator& rng) = 0; virtual size_t raw_kem_shared_key_length() const = 0; @@ -145,18 +145,18 @@ class KEM_Encryption_with_KDF : public KEM_Encryption { class KEM_Decryption_with_KDF : public KEM_Decryption { public: - void kem_decrypt(std::span out_shared_key, - std::span encapsulated_key, + void kem_decrypt(Botan::span out_shared_key, + Botan::span encapsulated_key, size_t desired_shared_key_len, - std::span salt) final; + Botan::span salt) final; size_t shared_key_length(size_t desired_shared_key_len) const final; ~KEM_Decryption_with_KDF() override = default; protected: - virtual void raw_kem_decrypt(std::span out_raw_shared_key, - std::span encapsulated_key) = 0; + virtual void raw_kem_decrypt(Botan::span out_raw_shared_key, + Botan::span encapsulated_key) = 0; virtual size_t raw_kem_shared_key_length() const = 0; diff --git a/src/lib/pubkey/pkcs8.cpp b/src/lib/pubkey/pkcs8.cpp index bdd08a982d5..ff5212db845 100644 --- a/src/lib/pubkey/pkcs8.cpp +++ b/src/lib/pubkey/pkcs8.cpp @@ -317,18 +317,18 @@ std::unique_ptr load_key(DataSource& source, const std::function load_key(std::span source, +std::unique_ptr load_key(Botan::span source, const std::function& get_passphrase) { Botan::DataSource_Memory ds(source); return load_key(ds, get_passphrase); } -std::unique_ptr load_key(std::span source, std::string_view pass) { +std::unique_ptr load_key(Botan::span source, std::string_view pass) { Botan::DataSource_Memory ds(source); return load_key(ds, pass); } -std::unique_ptr load_key(std::span source) { +std::unique_ptr load_key(Botan::span source) { Botan::DataSource_Memory ds(source); return load_key(ds); } diff --git a/src/lib/pubkey/pkcs8.h b/src/lib/pubkey/pkcs8.h index 1d92f28e0fd..898da773623 100644 --- a/src/lib/pubkey/pkcs8.h +++ b/src/lib/pubkey/pkcs8.h @@ -12,10 +12,10 @@ #include #include #include +#include #include #include #include -#include #include namespace Botan { @@ -210,7 +210,7 @@ std::unique_ptr load_key(DataSource& source); * @return loaded private key object */ BOTAN_PUBLIC_API(3, 0) -std::unique_ptr load_key(std::span source, +std::unique_ptr load_key(Botan::span source, const std::function& get_passphrase); /** Load an encrypted key from memory. @@ -219,14 +219,14 @@ std::unique_ptr load_key(std::span source, * @return loaded private key object */ BOTAN_PUBLIC_API(3, 0) -std::unique_ptr load_key(std::span source, std::string_view pass); +std::unique_ptr load_key(Botan::span source, std::string_view pass); /** Load an unencrypted key from memory. * @param source the byte buffer containing the encoded key * @return loaded private key object */ BOTAN_PUBLIC_API(3, 0) -std::unique_ptr load_key(std::span source); +std::unique_ptr load_key(Botan::span source); /** * Copy an existing encoded key object. diff --git a/src/lib/pubkey/pubkey.cpp b/src/lib/pubkey/pubkey.cpp index 9f0d83eeb95..3c4ea3ae7d0 100644 --- a/src/lib/pubkey/pubkey.cpp +++ b/src/lib/pubkey/pubkey.cpp @@ -152,11 +152,11 @@ size_t PK_KEM_Encryptor::encapsulated_key_length() const { return m_op->encapsulated_key_length(); } -void PK_KEM_Encryptor::encrypt(std::span out_encapsulated_key, - std::span out_shared_key, +void PK_KEM_Encryptor::encrypt(Botan::span out_encapsulated_key, + Botan::span out_shared_key, RandomNumberGenerator& rng, size_t desired_shared_key_len, - std::span salt) { + Botan::span salt) { BOTAN_ARG_CHECK(out_encapsulated_key.size() == encapsulated_key_length(), "not enough space for encapsulated key"); BOTAN_ARG_CHECK(out_shared_key.size() == shared_key_length(desired_shared_key_len), "not enough space for shared key"); @@ -186,10 +186,10 @@ PK_KEM_Decryptor::~PK_KEM_Decryptor() = default; PK_KEM_Decryptor::PK_KEM_Decryptor(PK_KEM_Decryptor&&) noexcept = default; PK_KEM_Decryptor& PK_KEM_Decryptor::operator=(PK_KEM_Decryptor&&) noexcept = default; -void PK_KEM_Decryptor::decrypt(std::span out_shared_key, - std::span encap_key, +void PK_KEM_Decryptor::decrypt(Botan::span out_shared_key, + Botan::span encap_key, size_t desired_shared_key_len, - std::span salt) { + Botan::span salt) { BOTAN_ARG_CHECK(out_shared_key.size() == shared_key_length(desired_shared_key_len), "inconsistent size of shared key output buffer"); m_op->kem_decrypt(out_shared_key, encap_key, desired_shared_key_len, salt); diff --git a/src/lib/pubkey/pubkey.h b/src/lib/pubkey/pubkey.h index 5da1226bd18..d7469ee8daa 100644 --- a/src/lib/pubkey/pubkey.h +++ b/src/lib/pubkey/pubkey.h @@ -11,8 +11,8 @@ #include #include #include +#include #include -#include #include #include #include @@ -44,7 +44,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Encryptor { * @param rng the random number source to use * @return encrypted message */ - std::vector encrypt(std::span in, RandomNumberGenerator& rng) const { + std::vector encrypt(Botan::span in, RandomNumberGenerator& rng) const { return enc(in.data(), in.size(), rng); } @@ -93,7 +93,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Decryptor { * @param in the ciphertext * @return decrypted message */ - secure_vector decrypt(std::span in) const { return decrypt(in.data(), in.size()); } + secure_vector decrypt(Botan::span in) const { return decrypt(in.data(), in.size()); } /** * Decrypt a ciphertext. If the ciphertext is invalid (eg due to @@ -194,7 +194,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Signer final { * @param rng the rng to use * @return signature */ - std::vector sign_message(std::span in, RandomNumberGenerator& rng) { + std::vector sign_message(Botan::span in, RandomNumberGenerator& rng) { return sign_message(in.data(), in.size(), rng); } @@ -215,7 +215,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Signer final { * Add a message part. * @param in the message part to add */ - void update(std::span in) { update(in.data(), in.size()); } + void update(Botan::span in) { update(in.data(), in.size()); } /** * Add a message part. @@ -322,7 +322,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Verifier final { * @param sig the signature * @return true if the signature is valid */ - bool verify_message(std::span msg, std::span sig) { + bool verify_message(Botan::span msg, Botan::span sig) { return verify_message(msg.data(), msg.size(), sig.data(), sig.size()); } @@ -346,7 +346,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Verifier final { * signature to be verified. * @param in the new message part */ - void update(std::span in) { update(in.data(), in.size()); } + void update(Botan::span in) { update(in.data(), in.size()); } /** * Add a message part of the message corresponding to the @@ -369,7 +369,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Verifier final { * @param sig the signature to be verified * @return true if the signature is valid, false otherwise */ - bool check_signature(std::span sig) { return check_signature(sig.data(), sig.size()); } + bool check_signature(Botan::span sig) { return check_signature(sig.data(), sig.size()); } /** * Set the format of the signatures fed to this verifier. @@ -435,7 +435,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Key_Agreement final { * @param params_len the length of params in bytes */ SymmetricKey derive_key(size_t key_len, - std::span in, + Botan::span in, const uint8_t params[], size_t params_len) const { return derive_key(key_len, in.data(), in.size(), params, params_len); @@ -458,7 +458,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_Key_Agreement final { * @param in the other parties key * @param params extra derivation params */ - SymmetricKey derive_key(size_t key_len, const std::span in, std::string_view params = "") const { + SymmetricKey derive_key(size_t key_len, const Botan::span in, std::string_view params = "") const { return derive_key(key_len, in.data(), in.size(), cast_char_ptr_to_uint8(params.data()), params.length()); } @@ -654,11 +654,11 @@ class BOTAN_PUBLIC_API(2, 0) PK_KEM_Encryptor final { */ KEM_Encapsulation encrypt(RandomNumberGenerator& rng, size_t desired_shared_key_len = 32, - std::span salt = {}) { + Botan::span salt = {}) { std::vector encapsulated_shared_key(encapsulated_key_length()); secure_vector shared_key(shared_key_length(desired_shared_key_len)); - encrypt(std::span{encapsulated_shared_key}, std::span{shared_key}, rng, desired_shared_key_len, salt); + encrypt(Botan::span{encapsulated_shared_key}, Botan::span{shared_key}, rng, desired_shared_key_len, salt); return KEM_Encapsulation(std::move(encapsulated_shared_key), std::move(shared_key)); } @@ -676,10 +676,10 @@ class BOTAN_PUBLIC_API(2, 0) PK_KEM_Encryptor final { secure_vector& out_shared_key, RandomNumberGenerator& rng, size_t desired_shared_key_len = 32, - std::span salt = {}) { + Botan::span salt = {}) { out_encapsulated_key.resize(encapsulated_key_length()); out_shared_key.resize(shared_key_length(desired_shared_key_len)); - encrypt(std::span{out_encapsulated_key}, std::span{out_shared_key}, rng, desired_shared_key_len, salt); + encrypt(Botan::span{out_encapsulated_key}, Botan::span{out_shared_key}, rng, desired_shared_key_len, salt); } /** @@ -692,13 +692,13 @@ class BOTAN_PUBLIC_API(2, 0) PK_KEM_Encryptor final { * @param salt a salt value used in the KDF * (ignored if no KDF is used) */ - void encrypt(std::span out_encapsulated_key, - std::span out_shared_key, + void encrypt(Botan::span out_encapsulated_key, + Botan::span out_shared_key, RandomNumberGenerator& rng, size_t desired_shared_key_len = 32, - std::span salt = {}); + Botan::span salt = {}); - BOTAN_DEPRECATED("use overload with salt as std::span<>") + BOTAN_DEPRECATED("use overload with salt as Botan::span<>") void encrypt(secure_vector& out_encapsulated_key, secure_vector& out_shared_key, @@ -715,7 +715,7 @@ class BOTAN_PUBLIC_API(2, 0) PK_KEM_Encryptor final { secure_vector& out_shared_key, size_t desired_shared_key_len, RandomNumberGenerator& rng, - std::span salt = {}) { + Botan::span salt = {}) { out_encapsulated_key.resize(encapsulated_key_length()); out_shared_key.resize(shared_key_length(desired_shared_key_len)); encrypt(out_encapsulated_key, out_shared_key, rng, desired_shared_key_len, salt); @@ -780,10 +780,10 @@ class BOTAN_PUBLIC_API(2, 0) PK_KEM_Decryptor final { * @param salt a salt value used in the KDF * (ignored if no KDF is used) */ - void decrypt(std::span out_shared_key, - std::span encap_key, + void decrypt(Botan::span out_shared_key, + Botan::span encap_key, size_t desired_shared_key_len = 32, - std::span salt = {}); + Botan::span salt = {}); /** * Decrypts the shared key for data encryption. @@ -820,9 +820,9 @@ class BOTAN_PUBLIC_API(2, 0) PK_KEM_Decryptor final { * * @return the shared data encryption key */ - secure_vector decrypt(std::span encap_key, + secure_vector decrypt(Botan::span encap_key, size_t desired_shared_key_len = 32, - std::span salt = {}) { + Botan::span salt = {}) { secure_vector shared_key(shared_key_length(desired_shared_key_len)); decrypt(shared_key, encap_key, desired_shared_key_len, salt); return shared_key; diff --git a/src/lib/pubkey/rsa/rsa.cpp b/src/lib/pubkey/rsa/rsa.cpp index b8ad1b25580..20ec491c838 100644 --- a/src/lib/pubkey/rsa/rsa.cpp +++ b/src/lib/pubkey/rsa/rsa.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -144,7 +145,7 @@ void RSA_PublicKey::init(BigInt&& n, BigInt&& e) { m_public = std::make_shared(std::move(n), std::move(e)); } -RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, std::span key_bits) { +RSA_PublicKey::RSA_PublicKey(const AlgorithmIdentifier& /*unused*/, Botan::span key_bits) { BigInt n, e; BER_Decoder(key_bits).start_sequence().decode(n).decode(e).end_cons(); @@ -241,7 +242,7 @@ void RSA_PrivateKey::init(BigInt&& d, BigInt&& p, BigInt&& q, BigInt&& d1, BigIn std::move(d), std::move(p), std::move(q), std::move(d1), std::move(d2), std::move(c)); } -RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, std::span key_bits) { +RSA_PrivateKey::RSA_PrivateKey(const AlgorithmIdentifier& /*unused*/, Botan::span key_bits) { BigInt n, e, d, p, q, d1, d2, c; BER_Decoder(key_bits) @@ -445,7 +446,7 @@ class RSA_Private_Operation { m_max_d1_bits(m_private->p_bits() + m_blinding_bits), m_max_d2_bits(m_private->q_bits() + m_blinding_bits) {} - void raw_op(std::span out, std::span input) { + void raw_op(Botan::span out, Botan::span input) { if(input.size() > public_modulus_bytes()) { throw Decoding_Error("RSA input is too long for this key"); } @@ -575,7 +576,7 @@ AlgorithmIdentifier RSA_Signature_Operation::algorithm_identifier() const { return AlgorithmIdentifier(oid, AlgorithmIdentifier::USE_EMPTY_PARAM); } catch(Lookup_Error&) {} - if(emsa_name.starts_with("EMSA4(")) { + if(starts_with(emsa_name, "EMSA4(")) { auto parameters = PSS_Params::from_emsa_name(m_emsa->name()).serialize(); return AlgorithmIdentifier("RSA/EMSA4", parameters); } @@ -606,7 +607,7 @@ class RSA_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with_KD size_t encapsulated_key_length() const override { return public_modulus_bytes(); } - void raw_kem_decrypt(std::span out_shared_key, std::span encapsulated_key) override { + void raw_kem_decrypt(Botan::span out_shared_key, Botan::span encapsulated_key) override { raw_op(out_shared_key, encapsulated_key); } }; @@ -694,8 +695,8 @@ class RSA_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with_KD size_t encapsulated_key_length() const override { return public_modulus_bytes(); } - void raw_kem_encrypt(std::span out_encapsulated_key, - std::span raw_shared_key, + void raw_kem_encrypt(Botan::span out_encapsulated_key, + Botan::span raw_shared_key, RandomNumberGenerator& rng) override { const BigInt r = BigInt::random_integer(rng, 1, get_n()); const BigInt c = public_op(r); diff --git a/src/lib/pubkey/rsa/rsa.h b/src/lib/pubkey/rsa/rsa.h index 25efbd19ff6..94d75754067 100644 --- a/src/lib/pubkey/rsa/rsa.h +++ b/src/lib/pubkey/rsa/rsa.h @@ -29,7 +29,7 @@ class BOTAN_PUBLIC_API(2, 0) RSA_PublicKey : public virtual Public_Key { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - RSA_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + RSA_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a public key. @@ -102,7 +102,7 @@ class BOTAN_PUBLIC_API(2, 0) RSA_PrivateKey final : public Private_Key, * @param alg_id the X.509 algorithm identifier * @param key_bits PKCS#1 RSAPrivateKey bits */ - RSA_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + RSA_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Construct a private key from the specified parameters. diff --git a/src/lib/pubkey/sm2/sm2.cpp b/src/lib/pubkey/sm2/sm2.cpp index 8d4c47b5272..dc985fda352 100644 --- a/src/lib/pubkey/sm2/sm2.cpp +++ b/src/lib/pubkey/sm2/sm2.cpp @@ -38,7 +38,7 @@ bool SM2_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { return KeyPair::signature_consistency_check(rng, *this, "user@example.com,SM3"); } -SM2_PrivateKey::SM2_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : +SM2_PrivateKey::SM2_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PrivateKey(alg_id, key_bits) { m_da_inv = domain().inverse_mod_order(m_private_key + 1); } diff --git a/src/lib/pubkey/sm2/sm2.h b/src/lib/pubkey/sm2/sm2.h index 5aa90473de1..597b62c99ab 100644 --- a/src/lib/pubkey/sm2/sm2.h +++ b/src/lib/pubkey/sm2/sm2.h @@ -29,7 +29,7 @@ class BOTAN_PUBLIC_API(2, 2) SM2_PublicKey : public virtual EC_PublicKey { * @param alg_id the X.509 algorithm identifier * @param key_bits DER encoded public key bits */ - SM2_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : + SM2_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : EC_PublicKey(alg_id, key_bits) {} /** @@ -72,7 +72,7 @@ class BOTAN_PUBLIC_API(2, 2) SM2_PrivateKey final : public SM2_PublicKey, * @param alg_id the X.509 algorithm identifier * @param key_bits ECPrivateKey bits */ - SM2_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + SM2_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); /** * Create a private key. diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_address.h b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_address.h index 3ce4ce09852..449405cc8b9 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_address.h +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_address.h @@ -43,7 +43,7 @@ class BOTAN_TEST_API Sphincs_Address final { static constexpr size_t tree_index_offset = hash_offset; public: - using enum Sphincs_Address_Type; + //using enum Sphincs_Address_Type; Sphincs_Address(Sphincs_Address_Type type) { m_address.fill(0); diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_fors.cpp b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_fors.cpp index 5b596572993..db8996bf2bf 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_fors.cpp +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_fors.cpp @@ -25,7 +25,7 @@ namespace Botan { namespace { -std::vector fors_message_to_indices(std::span message, const Sphincs_Parameters& params) { +std::vector fors_message_to_indices(Botan::span message, const Sphincs_Parameters& params) { BOTAN_ASSERT_NOMSG((message.size() * 8) >= (params.k() * params.a())); std::vector indices(params.k()); @@ -55,7 +55,7 @@ SphincsTreeNode fors_sign_and_pkgen(StrongSpan sig_out, auto fors_tree_addr = Sphincs_Address::as_keypair_from(address); - auto fors_pk_addr = Sphincs_Address::as_keypair_from(address).set_type(Sphincs_Address::ForsTreeRootsCompression); + auto fors_pk_addr = Sphincs_Address::as_keypair_from(address).set_type(Sphincs_Address_Type::ForsTreeRootsCompression); std::vector roots_buffer(params.k() * params.n()); BufferStuffer roots(roots_buffer); @@ -116,9 +116,9 @@ SphincsTreeNode fors_public_key_from_signature(const SphincsHashedMessage& hashe Sphincs_Hash_Functions& hashes) { const auto indices = fors_message_to_indices(hashed_message, params); - auto fors_tree_addr = Sphincs_Address::as_keypair_from(address).set_type(Sphincs_Address::ForsTree); + auto fors_tree_addr = Sphincs_Address::as_keypair_from(address).set_type(Sphincs_Address_Type::ForsTree); - auto fors_pk_addr = Sphincs_Address::as_keypair_from(address).set_type(Sphincs_Address::ForsTreeRootsCompression); + auto fors_pk_addr = Sphincs_Address::as_keypair_from(address).set_type(Sphincs_Address_Type::ForsTreeRootsCompression); BufferSlicer s(signature); std::vector roots_buffer(params.k() * params.n()); diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.cpp b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.cpp index 4517d3a7ccd..5be9e967fa8 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.cpp +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.cpp @@ -57,7 +57,7 @@ std::unique_ptr Sphincs_Hash_Functions::create(const Sph namespace { template -T from_first_n_bits(const uint32_t nbits, std::span bytes) { +T from_first_n_bits(const uint32_t nbits, Botan::span bytes) { using wrapped_type = typename T::wrapped_type; constexpr const auto outsize = sizeof(wrapped_type); @@ -76,7 +76,7 @@ T from_first_n_bits(const uint32_t nbits, std::span bytes) { } // namespace std::tuple Sphincs_Hash_Functions::H_msg( - StrongSpan r, const SphincsTreeNode& root, std::span message) { + StrongSpan r, const SphincsTreeNode& root, Botan::span message) { const auto digest = H_msg_digest(r, root, message); // The following calculates the message digest and indices from the diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.h b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.h index 2d63916e8bd..3c732ec4d3c 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.h +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_hash.h @@ -36,7 +36,7 @@ class BOTAN_TEST_API Sphincs_Hash_Functions { public: std::tuple H_msg( - StrongSpan r, const SphincsTreeNode& root, std::span message); + StrongSpan r, const SphincsTreeNode& root, Botan::span message); /** * Using SK.PRF, the optional randomness, and a message, computes the message random R, @@ -50,10 +50,10 @@ class BOTAN_TEST_API Sphincs_Hash_Functions { virtual void PRF_msg(StrongSpan out, const SphincsSecretPRF& sk_prf, const SphincsOptionalRandomness& opt_rand, - std::span msg) = 0; + Botan::span msg) = 0; template - void T(std::span out, const Sphincs_Address& address, BufferTs&&... in) { + void T(Botan::span out, const Sphincs_Address& address, BufferTs&&... in) { auto& hash = tweak_hash(address, (std::forward(in).size() + ...)); (hash.update(std::forward(in)), ...); hash.final(out); @@ -96,7 +96,7 @@ class BOTAN_TEST_API Sphincs_Hash_Functions { virtual std::vector H_msg_digest(StrongSpan r, const SphincsTreeNode& root, - std::span message) = 0; + Botan::span message) = 0; const Sphincs_Parameters& m_sphincs_params; const SphincsPublicSeed& m_pub_seed; diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_treehash.cpp b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_treehash.cpp index 0151ba99915..7ea4b52ca92 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_treehash.cpp +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_treehash.cpp @@ -16,7 +16,7 @@ namespace Botan { namespace { -void copy_into(std::span out, std::span in) { +void copy_into(Botan::span out, Botan::span in) { BOTAN_ASSERT_NOMSG(in.size() == out.size()); std::copy(in.begin(), in.end(), out.begin()); } @@ -77,7 +77,7 @@ void treehash(StrongSpan out_root, // At this point we know that we'll need to use the stack. Get a // reference to the correct location. - auto stack_location = std::span(stack).subspan(h.get() * params.n(), params.n()); + auto stack_location = Botan::span(stack).subspan(h.get() * params.n(), params.n()); // Check if we're at a left child; if so, stop going up the stack // Exception: if we've reached the end of the tree, keep on going (so diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_wots.cpp b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_wots.cpp index 2f05f1002ef..0b45b38cab5 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_wots.cpp +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sp_wots.cpp @@ -40,7 +40,7 @@ void gen_chain(StrongSpan out, * Interprets an array of bytes as integers in base w. * This only works when log_w is a divisor of 8. */ -void base_w(std::span output, std::span input, const Sphincs_Parameters& params) { +void base_w(Botan::span output, Botan::span input, const Sphincs_Parameters& params) { BOTAN_ASSERT_NOMSG(output.size() <= 8 * input.size() / params.log_w()); size_t input_offset = 0; @@ -59,8 +59,8 @@ void base_w(std::span output, std::span input, con } /** Computes the WOTS+ checksum over a message (in base_w). */ -void wots_checksum(std::span output, - std::span msg_base_w, +void wots_checksum(Botan::span output, + Botan::span msg_base_w, const Sphincs_Parameters& params) { uint32_t csum = 0; @@ -77,7 +77,7 @@ void wots_checksum(std::span output, const size_t csum_bytes_size = params.wots_checksum_bytes(); BOTAN_ASSERT_NOMSG(csum_bytes.size() >= csum_bytes_size); - base_w(output, std::span(csum_bytes).last(csum_bytes_size), params); + base_w(output, Botan::span(csum_bytes).last(csum_bytes_size), params); } } // namespace @@ -85,8 +85,8 @@ void wots_checksum(std::span output, std::vector chain_lengths(const SphincsTreeNode& msg, const Sphincs_Parameters& params) { std::vector result(params.wots_len_1() + params.wots_len_2()); - auto msg_base_w = std::span(result).first(params.wots_len_1()); - auto checksum_base_w = std::span(result).last(params.wots_len_2()); + auto msg_base_w = Botan::span(result).first(params.wots_len_1()); + auto checksum_base_w = Botan::span(result).last(params.wots_len_2()); base_w(msg_base_w, msg.get(), params); wots_checksum(checksum_base_w, msg_base_w, params); diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.cpp b/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.cpp index b876718c213..bc38f962b86 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.cpp +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.cpp @@ -34,7 +34,7 @@ class SphincsPlus_PublicKeyInternal final { SphincsTreeNode sphincs_root) : m_params(params), m_public_seed(std::move(public_seed)), m_sphincs_root(std::move(sphincs_root)) {} - SphincsPlus_PublicKeyInternal(Sphincs_Parameters params, std::span key_bits) : m_params(params) { + SphincsPlus_PublicKeyInternal(Sphincs_Parameters params, Botan::span key_bits) : m_params(params) { if(key_bits.size() != m_params.public_key_bytes()) { throw Decoding_Error("Sphincs Public Key doesn't have the expected length"); } @@ -65,7 +65,7 @@ class SphincsPlus_PrivateKeyInternal final { SphincsPlus_PrivateKeyInternal(SphincsSecretSeed secret_seed, SphincsSecretPRF prf) : m_secret_seed(std::move(secret_seed)), m_prf(std::move(prf)) {} - SphincsPlus_PrivateKeyInternal(const Sphincs_Parameters& params, std::span key_bits) { + SphincsPlus_PrivateKeyInternal(const Sphincs_Parameters& params, Botan::span key_bits) { if(key_bits.size() != params.private_key_bytes() - params.public_key_bytes()) { throw Decoding_Error("Sphincs Private Key doesn't have the expected length"); } @@ -88,15 +88,15 @@ class SphincsPlus_PrivateKeyInternal final { SphincsSecretPRF m_prf; }; -SphincsPlus_PublicKey::SphincsPlus_PublicKey(std::span pub_key, +SphincsPlus_PublicKey::SphincsPlus_PublicKey(Botan::span pub_key, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash) : m_public(std::make_shared(Sphincs_Parameters::create(type, hash), pub_key)) {} -SphincsPlus_PublicKey::SphincsPlus_PublicKey(std::span pub_key, Sphincs_Parameters params) : +SphincsPlus_PublicKey::SphincsPlus_PublicKey(Botan::span pub_key, Sphincs_Parameters params) : m_public(std::make_shared(params, pub_key)) {} -SphincsPlus_PublicKey::SphincsPlus_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : +SphincsPlus_PublicKey::SphincsPlus_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : m_public(std::make_shared(Sphincs_Parameters::create(alg_id.oid()), key_bits)) {} SphincsPlus_PublicKey::~SphincsPlus_PublicKey() = default; @@ -204,7 +204,7 @@ bool SphincsPlus_PublicKey::supports_operation(PublicKeyOperation op) const { namespace { -std::span slice_off_public_key(const OID& oid, std::span key_bits) { +Botan::span slice_off_public_key(const OID& oid, Botan::span key_bits) { const auto params = Sphincs_Parameters::create(oid); // Note: We need to transiently instantiate the `Sphincs_Parameters` object // to know the size of the public/private key. That's slightly @@ -220,15 +220,15 @@ std::span slice_off_public_key(const OID& oid, std::span private_key, +SphincsPlus_PrivateKey::SphincsPlus_PrivateKey(Botan::span private_key, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash) : SphincsPlus_PrivateKey(private_key, Sphincs_Parameters::create(type, hash)) {} -SphincsPlus_PrivateKey::SphincsPlus_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits) : +SphincsPlus_PrivateKey::SphincsPlus_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits) : SphincsPlus_PrivateKey(key_bits, Sphincs_Parameters::create(alg_id.oid())) {} -SphincsPlus_PrivateKey::SphincsPlus_PrivateKey(std::span private_key, Sphincs_Parameters params) : +SphincsPlus_PrivateKey::SphincsPlus_PrivateKey(Botan::span private_key, Sphincs_Parameters params) : SphincsPlus_PublicKey(slice_off_public_key(params.object_identifier(), private_key), params) { const auto private_portion_bytes = params.private_key_bytes() - params.public_key_bytes(); BOTAN_ASSERT_NOMSG(private_key.size() >= private_portion_bytes); diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.h b/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.h index e2664d36809..19695a162a6 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.h +++ b/src/lib/pubkey/sphincsplus/sphincsplus_common/sphincsplus.h @@ -32,9 +32,9 @@ class SphincsPlus_PrivateKeyInternal; */ class BOTAN_PUBLIC_API(3, 1) SphincsPlus_PublicKey : public virtual Public_Key { public: - SphincsPlus_PublicKey(std::span pub_key, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash); - SphincsPlus_PublicKey(std::span pub_key, Sphincs_Parameters params); - SphincsPlus_PublicKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + SphincsPlus_PublicKey(Botan::span pub_key, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash); + SphincsPlus_PublicKey(Botan::span pub_key, Sphincs_Parameters params); + SphincsPlus_PublicKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); ~SphincsPlus_PublicKey() override; @@ -68,9 +68,9 @@ BOTAN_DIAGNOSTIC_IGNORE_INHERITED_VIA_DOMINANCE class BOTAN_PUBLIC_API(3, 1) SphincsPlus_PrivateKey final : public virtual SphincsPlus_PublicKey, public virtual Private_Key { public: - SphincsPlus_PrivateKey(std::span private_key, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash); - SphincsPlus_PrivateKey(std::span private_key, Sphincs_Parameters params); - SphincsPlus_PrivateKey(const AlgorithmIdentifier& alg_id, std::span key_bits); + SphincsPlus_PrivateKey(Botan::span private_key, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash); + SphincsPlus_PrivateKey(Botan::span private_key, Sphincs_Parameters params); + SphincsPlus_PrivateKey(const AlgorithmIdentifier& alg_id, Botan::span key_bits); SphincsPlus_PrivateKey(RandomNumberGenerator& rng, Sphincs_Parameter_Set type, Sphincs_Hash_Type hash); SphincsPlus_PrivateKey(RandomNumberGenerator& rng, Sphincs_Parameters params); diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_sha2/sp_hash_sha2.h b/src/lib/pubkey/sphincsplus/sphincsplus_sha2/sp_hash_sha2.h index 65fb3920e8f..f0e13d3e937 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_sha2/sp_hash_sha2.h +++ b/src/lib/pubkey/sphincsplus/sphincsplus_sha2/sp_hash_sha2.h @@ -44,7 +44,7 @@ class Sphincs_Hash_Functions_Sha2 : public Sphincs_Hash_Functions { std::vector H_msg_digest(StrongSpan r, const SphincsTreeNode& root, - std::span message) override { + Botan::span message) override { m_sha_x_full->update(r); m_sha_x_full->update(m_pub_seed); m_sha_x_full->update(root); @@ -90,7 +90,7 @@ class Sphincs_Hash_Functions_Sha2 : public Sphincs_Hash_Functions { void PRF_msg(StrongSpan out, const SphincsSecretPRF& sk_prf, const SphincsOptionalRandomness& opt_rand, - std::span in) override { + Botan::span in) override { HMAC hmac_sha_x(m_sha_x_full->new_object()); hmac_sha_x.set_key(sk_prf); hmac_sha_x.update(opt_rand); diff --git a/src/lib/pubkey/sphincsplus/sphincsplus_shake/sp_hash_shake.h b/src/lib/pubkey/sphincsplus/sphincsplus_shake/sp_hash_shake.h index 6aa0ce5ce00..fd1a3a107f2 100644 --- a/src/lib/pubkey/sphincsplus/sphincsplus_shake/sp_hash_shake.h +++ b/src/lib/pubkey/sphincsplus/sphincsplus_shake/sp_hash_shake.h @@ -29,7 +29,7 @@ class Sphincs_Hash_Functions_Shake : public Sphincs_Hash_Functions { std::vector H_msg_digest(StrongSpan r, const SphincsTreeNode& root, - std::span message) override { + Botan::span message) override { m_h_msg_hash.update(r); m_h_msg_hash.update(m_pub_seed); m_h_msg_hash.update(root); @@ -50,7 +50,7 @@ class Sphincs_Hash_Functions_Shake : public Sphincs_Hash_Functions { void PRF_msg(StrongSpan out, const SphincsSecretPRF& sk_prf, const SphincsOptionalRandomness& opt_rand, - std::span in) override { + Botan::span in) override { m_hash.update(sk_prf); m_hash.update(opt_rand); m_hash.update(in); diff --git a/src/lib/pubkey/x509_key.h b/src/lib/pubkey/x509_key.h index 07738224bf4..c5bf34385eb 100644 --- a/src/lib/pubkey/x509_key.h +++ b/src/lib/pubkey/x509_key.h @@ -65,7 +65,7 @@ inline std::unique_ptr load_key(const std::vector& enc) { * @param enc the memory region containing the DER or PEM encoded key * @return new public key object */ -inline std::unique_ptr load_key(std::span enc) { +inline std::unique_ptr load_key(Botan::span enc) { DataSource_Memory source(enc); return X509::load_key(source); } diff --git a/src/lib/pubkey/xmss/xmss.h b/src/lib/pubkey/xmss/xmss.h index ae8de668cf2..2ca68852197 100644 --- a/src/lib/pubkey/xmss/xmss.h +++ b/src/lib/pubkey/xmss/xmss.h @@ -15,6 +15,7 @@ #include #include #include +#include namespace Botan { @@ -55,7 +56,7 @@ class BOTAN_PUBLIC_API(2, 0) XMSS_PublicKey : public virtual Public_Key { * * @param key_bits DER encoded public key bits */ - XMSS_PublicKey(std::span key_bits); + XMSS_PublicKey(Botan::span key_bits); /** * Creates a new XMSS public key for a chosen XMSS signature method as @@ -182,7 +183,7 @@ class BOTAN_PUBLIC_API(2, 0) XMSS_PrivateKey final : public virtual XMSS_PublicK * * @param raw_key An XMSS private key serialized using raw_private_key(). **/ - XMSS_PrivateKey(std::span raw_key); + XMSS_PrivateKey(Botan::span raw_key); /** * Creates a new XMSS private key for the chosen XMSS signature method diff --git a/src/lib/pubkey/xmss/xmss_hash.cpp b/src/lib/pubkey/xmss/xmss_hash.cpp index ea02c7c5c78..e8c1173a9e7 100644 --- a/src/lib/pubkey/xmss/xmss_hash.cpp +++ b/src/lib/pubkey/xmss/xmss_hash.cpp @@ -31,9 +31,9 @@ XMSS_Hash::XMSS_Hash(const XMSS_Parameters& params) : BOTAN_ASSERT(m_hash->output_length() > 0, "Hash output length of zero is invalid."); } -void XMSS_Hash::h_msg_init(std::span randomness, - std::span root, - std::span index_bytes) { +void XMSS_Hash::h_msg_init(Botan::span randomness, + Botan::span root, + Botan::span index_bytes) { m_msg_hash->clear(); m_msg_hash->update(m_zero_padding); m_msg_hash->update(0x02); @@ -42,7 +42,7 @@ void XMSS_Hash::h_msg_init(std::span randomness, m_msg_hash->update(index_bytes.data(), index_bytes.size()); } -void XMSS_Hash::h_msg_update(std::span data) { +void XMSS_Hash::h_msg_update(Botan::span data) { m_msg_hash->update(data.data(), data.size()); } diff --git a/src/lib/pubkey/xmss/xmss_hash.h b/src/lib/pubkey/xmss/xmss_hash.h index be57be4ead0..9ac7e6f5dbd 100644 --- a/src/lib/pubkey/xmss/xmss_hash.h +++ b/src/lib/pubkey/xmss/xmss_hash.h @@ -10,7 +10,7 @@ #include -#include +#include namespace Botan { @@ -36,8 +36,8 @@ class XMSS_Hash final { private: inline void calculate_hash(const uint8_t hash_id, secure_vector& result, - std::span key, - std::span data) { + Botan::span key, + Botan::span data) { m_hash->update(m_zero_padding); m_hash->update(hash_id); m_hash->update(key.data(), key.size()); @@ -54,7 +54,7 @@ class XMSS_Hash final { * @param[in] key An n-byte key value. * @param[in] data A 32-byte XMSS_Address data value **/ - inline void prf(secure_vector& result, std::span key, std::span data) { + inline void prf(secure_vector& result, Botan::span key, Botan::span data) { calculate_hash(0x03, result, key, data); } @@ -70,8 +70,8 @@ class XMSS_Hash final { * @param[in] data A 32-byte XMSS_Address data value **/ inline void prf_keygen(secure_vector& result, - std::span key, - std::span data) { + Botan::span key, + Botan::span data) { calculate_hash(0x04, result, key, data); } @@ -82,7 +82,7 @@ class XMSS_Hash final { * @param[in] key key of length n bytes. * @param[in] data string of arbitrary length. **/ - void f(secure_vector& result, std::span key, std::span data) { + void f(secure_vector& result, Botan::span key, Botan::span data) { calculate_hash(0x00, result, key, data); } @@ -94,7 +94,7 @@ class XMSS_Hash final { * @param[in] key key of length n bytes. * @param[in] data string of 2n bytes length. **/ - void h(secure_vector& result, std::span key, std::span data) { + void h(secure_vector& result, Botan::span key, Botan::span data) { calculate_hash(0x01, result, key, data); } @@ -109,10 +109,10 @@ class XMSS_Hash final { * * @return hash value of n-bytes length. **/ - secure_vector h_msg(std::span randomness, - std::span root, - std::span index_bytes, - std::span data) { + secure_vector h_msg(Botan::span randomness, + Botan::span root, + Botan::span index_bytes, + Botan::span data) { h_msg_init(randomness, root, index_bytes); h_msg_update(data); return m_msg_hash->final(); @@ -125,16 +125,16 @@ class XMSS_Hash final { * @param root n-byte root node. * @param index_bytes Index value padded with leading zeros. **/ - void h_msg_init(std::span randomness, - std::span root, - std::span index_bytes); + void h_msg_init(Botan::span randomness, + Botan::span root, + Botan::span index_bytes); /** * Adds a message block to buffered h_msg computation. * * @param data A message block **/ - void h_msg_update(std::span data); + void h_msg_update(Botan::span data); /** * Finalizes buffered h_msg computation and retrieves the result. diff --git a/src/lib/pubkey/xmss/xmss_privatekey.cpp b/src/lib/pubkey/xmss/xmss_privatekey.cpp index 37b8e30cdba..87e5aeb6c3c 100644 --- a/src/lib/pubkey/xmss/xmss_privatekey.cpp +++ b/src/lib/pubkey/xmss/xmss_privatekey.cpp @@ -36,7 +36,7 @@ namespace Botan { namespace { // fall back to raw decoding for previous versions, which did not encode an OCTET STRING -secure_vector extract_raw_private_key(std::span key_bits, const XMSS_Parameters& xmss_params) { +secure_vector extract_raw_private_key(Botan::span key_bits, const XMSS_Parameters& xmss_params) { secure_vector raw_key; // The public part of the input key bits was already parsed, so we can @@ -83,7 +83,7 @@ class XMSS_PrivateKey_Internal { XMSS_PrivateKey_Internal(const XMSS_Parameters& xmss_params, const XMSS_WOTS_Parameters& wots_params, - std::span key_bits) : + Botan::span key_bits) : m_xmss_params(xmss_params), m_wots_params(wots_params), m_hash(m_xmss_params), @@ -199,7 +199,7 @@ class XMSS_PrivateKey_Internal { XMSS_Index_Registry& m_index_reg; }; -XMSS_PrivateKey::XMSS_PrivateKey(std::span key_bits) : +XMSS_PrivateKey::XMSS_PrivateKey(Botan::span key_bits) : XMSS_PublicKey(key_bits), m_private(std::make_shared(m_xmss_params, m_wots_params, key_bits)) {} diff --git a/src/lib/pubkey/xmss/xmss_publickey.cpp b/src/lib/pubkey/xmss/xmss_publickey.cpp index bb27c848875..26fecbb86fd 100644 --- a/src/lib/pubkey/xmss/xmss_publickey.cpp +++ b/src/lib/pubkey/xmss/xmss_publickey.cpp @@ -28,7 +28,7 @@ namespace Botan { namespace { -XMSS_Parameters::xmss_algorithm_t deserialize_xmss_oid(std::span raw_key) { +XMSS_Parameters::xmss_algorithm_t deserialize_xmss_oid(Botan::span raw_key) { if(raw_key.size() < 4) { throw Decoding_Error("XMSS signature OID missing."); } @@ -43,7 +43,7 @@ XMSS_Parameters::xmss_algorithm_t deserialize_xmss_oid(std::span } // fall back to raw decoding for previous versions, which did not encode an OCTET STRING -std::vector extract_raw_public_key(std::span key_bits) { +std::vector extract_raw_public_key(Botan::span key_bits) { std::vector raw_key; try { DataSource_Memory src(key_bits); @@ -74,7 +74,7 @@ XMSS_PublicKey::XMSS_PublicKey(XMSS_Parameters::xmss_algorithm_t xmss_oid, Rando m_root(m_xmss_params.element_size()), m_public_seed(rng.random_vec(m_xmss_params.element_size())) {} -XMSS_PublicKey::XMSS_PublicKey(std::span key_bits) : +XMSS_PublicKey::XMSS_PublicKey(Botan::span key_bits) : m_raw_key(extract_raw_public_key(key_bits)), m_xmss_params(deserialize_xmss_oid(m_raw_key)), m_wots_params(m_xmss_params.ots_oid()) { diff --git a/src/lib/pubkey/xmss/xmss_wots.cpp b/src/lib/pubkey/xmss/xmss_wots.cpp index 6387dcb33be..46cb1c32257 100644 --- a/src/lib/pubkey/xmss/xmss_wots.cpp +++ b/src/lib/pubkey/xmss/xmss_wots.cpp @@ -46,7 +46,7 @@ void chain(const XMSS_WOTS_Parameters& params, size_t start_idx, size_t steps, XMSS_Address& adrs, - std::span seed, + Botan::span seed, XMSS_Hash& hash) { BOTAN_ASSERT_NOMSG(result.size() == hash.output_length()); BOTAN_ASSERT_NOMSG(start_idx + steps < params.wots_parameter()); @@ -77,7 +77,7 @@ void chain(const XMSS_WOTS_Parameters& params, } // namespace XMSS_WOTS_PublicKey::XMSS_WOTS_PublicKey(XMSS_WOTS_Parameters params, - std::span public_seed, + Botan::span public_seed, const XMSS_WOTS_PrivateKey& private_key, XMSS_Address& adrs, XMSS_Hash& hash) : @@ -89,7 +89,7 @@ XMSS_WOTS_PublicKey::XMSS_WOTS_PublicKey(XMSS_WOTS_Parameters params, } XMSS_WOTS_PublicKey::XMSS_WOTS_PublicKey(XMSS_WOTS_Parameters params, - std::span public_seed, + Botan::span public_seed, wots_keysig_t signature, const secure_vector& msg, XMSS_Address& adrs, @@ -112,7 +112,7 @@ XMSS_WOTS_PublicKey::XMSS_WOTS_PublicKey(XMSS_WOTS_Parameters params, } wots_keysig_t XMSS_WOTS_PrivateKey::sign(const secure_vector& msg, - std::span public_seed, + Botan::span public_seed, XMSS_Address& adrs, XMSS_Hash& hash) { secure_vector msg_digest{m_params.base_w(msg, m_params.len_1())}; @@ -129,8 +129,8 @@ wots_keysig_t XMSS_WOTS_PrivateKey::sign(const secure_vector& msg, } XMSS_WOTS_PrivateKey::XMSS_WOTS_PrivateKey(XMSS_WOTS_Parameters params, - std::span public_seed, - std::span private_seed, + Botan::span public_seed, + Botan::span private_seed, XMSS_Address adrs, XMSS_Hash& hash) : XMSS_WOTS_Base(std::move(params)) { @@ -144,7 +144,7 @@ XMSS_WOTS_PrivateKey::XMSS_WOTS_PrivateKey(XMSS_WOTS_Parameters params, // Constructor for legacy XMSS_PrivateKeys XMSS_WOTS_PrivateKey::XMSS_WOTS_PrivateKey(XMSS_WOTS_Parameters params, - std::span private_seed, + Botan::span private_seed, XMSS_Address adrs, XMSS_Hash& hash) : XMSS_WOTS_Base(std::move(params)) { diff --git a/src/lib/pubkey/xmss/xmss_wots.h b/src/lib/pubkey/xmss/xmss_wots.h index 38342bb1b84..387fb4b2087 100644 --- a/src/lib/pubkey/xmss/xmss_wots.h +++ b/src/lib/pubkey/xmss/xmss_wots.h @@ -66,7 +66,7 @@ class XMSS_WOTS_PublicKey : public XMSS_WOTS_Base { * thread executing at. **/ XMSS_WOTS_PublicKey(XMSS_WOTS_Parameters params, - std::span public_seed, + Botan::span public_seed, const XMSS_WOTS_PrivateKey& private_key, XMSS_Address& adrs, XMSS_Hash& hash); @@ -85,7 +85,7 @@ class XMSS_WOTS_PublicKey : public XMSS_WOTS_Base { * thread executing at. */ XMSS_WOTS_PublicKey(XMSS_WOTS_Parameters params, - std::span public_seed, + Botan::span public_seed, wots_keysig_t signature, const secure_vector& msg, XMSS_Address& adrs, @@ -118,8 +118,8 @@ class XMSS_WOTS_PrivateKey : public XMSS_WOTS_Base { * thread executing at. **/ XMSS_WOTS_PrivateKey(XMSS_WOTS_Parameters params, - std::span public_seed, - std::span private_seed, + Botan::span public_seed, + Botan::span private_seed, XMSS_Address adrs, XMSS_Hash& hash); @@ -137,7 +137,7 @@ class XMSS_WOTS_PrivateKey : public XMSS_WOTS_Base { * thread executing it. **/ XMSS_WOTS_PrivateKey(XMSS_WOTS_Parameters params, - std::span private_seed, + Botan::span private_seed, XMSS_Address adrs, XMSS_Hash& hash); @@ -159,7 +159,7 @@ class XMSS_WOTS_PrivateKey : public XMSS_WOTS_Base { * @return signature for msg. **/ wots_keysig_t sign(const secure_vector& msg, - std::span public_seed, + Botan::span public_seed, XMSS_Address& adrs, XMSS_Hash& hash); }; diff --git a/src/lib/rng/auto_rng/auto_rng.cpp b/src/lib/rng/auto_rng/auto_rng.cpp index e7a5c88b170..9296a08d6d5 100644 --- a/src/lib/rng/auto_rng/auto_rng.cpp +++ b/src/lib/rng/auto_rng/auto_rng.cpp @@ -95,7 +95,7 @@ size_t AutoSeeded_RNG::reseed(Entropy_Sources& srcs, size_t poll_bits, std::chro return m_rng->reseed(srcs, poll_bits, poll_timeout); } -void AutoSeeded_RNG::fill_bytes_with_input(std::span out, std::span in) { +void AutoSeeded_RNG::fill_bytes_with_input(Botan::span out, Botan::span in) { if(in.empty()) { m_rng->randomize_with_ts_input(out); } else { diff --git a/src/lib/rng/auto_rng/auto_rng.h b/src/lib/rng/auto_rng/auto_rng.h index 36429707966..6595c0a61b5 100644 --- a/src/lib/rng/auto_rng/auto_rng.h +++ b/src/lib/rng/auto_rng/auto_rng.h @@ -84,7 +84,7 @@ class BOTAN_PUBLIC_API(2, 0) AutoSeeded_RNG final : public RandomNumberGenerator ~AutoSeeded_RNG() override; private: - void fill_bytes_with_input(std::span out, std::span in) override; + void fill_bytes_with_input(Botan::span out, Botan::span in) override; private: std::unique_ptr m_rng; diff --git a/src/lib/rng/chacha_rng/chacha_rng.cpp b/src/lib/rng/chacha_rng/chacha_rng.cpp index ee09306e343..edb6f756b62 100644 --- a/src/lib/rng/chacha_rng/chacha_rng.cpp +++ b/src/lib/rng/chacha_rng/chacha_rng.cpp @@ -15,7 +15,7 @@ ChaCha_RNG::ChaCha_RNG() : Stateful_RNG() { clear(); } -ChaCha_RNG::ChaCha_RNG(std::span seed) : Stateful_RNG() { +ChaCha_RNG::ChaCha_RNG(Botan::span seed) : Stateful_RNG() { m_hmac = MessageAuthenticationCode::create_or_throw("HMAC(SHA-256)"); m_chacha = StreamCipher::create_or_throw("ChaCha(20)"); clear(); @@ -50,7 +50,7 @@ void ChaCha_RNG::clear_state() { m_chacha->set_key(m_hmac->final()); } -void ChaCha_RNG::generate_output(std::span output, std::span input) { +void ChaCha_RNG::generate_output(Botan::span output, Botan::span input) { BOTAN_ASSERT_NOMSG(!output.empty()); if(!input.empty()) { @@ -60,7 +60,7 @@ void ChaCha_RNG::generate_output(std::span output, std::spanwrite_keystream(output); } -void ChaCha_RNG::update(std::span input) { +void ChaCha_RNG::update(Botan::span input) { m_hmac->update(input); m_chacha->set_key(m_hmac->final()); const auto mac_key = m_chacha->keystream_bytes(m_hmac->output_length()); diff --git a/src/lib/rng/chacha_rng/chacha_rng.h b/src/lib/rng/chacha_rng/chacha_rng.h index 0dfe4353c1c..8b1355efccb 100644 --- a/src/lib/rng/chacha_rng/chacha_rng.h +++ b/src/lib/rng/chacha_rng/chacha_rng.h @@ -61,7 +61,7 @@ class BOTAN_PUBLIC_API(2, 3) ChaCha_RNG final : public Stateful_RNG { * * @param seed the seed material, should be at least 256 bits */ - ChaCha_RNG(std::span seed); + ChaCha_RNG(Botan::span seed); /** * Automatic reseeding from @p underlying_rng will take place after @@ -106,9 +106,9 @@ class BOTAN_PUBLIC_API(2, 3) ChaCha_RNG final : public Stateful_RNG { size_t max_number_of_bytes_per_request() const override { return 0; } private: - void update(std::span input) override; + void update(Botan::span input) override; - void generate_output(std::span output, std::span input) override; + void generate_output(Botan::span output, Botan::span input) override; void clear_state() override; diff --git a/src/lib/rng/hmac_drbg/hmac_drbg.cpp b/src/lib/rng/hmac_drbg/hmac_drbg.cpp index d2d689fb506..350e2babcdf 100644 --- a/src/lib/rng/hmac_drbg/hmac_drbg.cpp +++ b/src/lib/rng/hmac_drbg/hmac_drbg.cpp @@ -126,7 +126,7 @@ std::string HMAC_DRBG::name() const { * HMAC_DRBG generation * See NIST SP800-90A section 10.1.2.5 */ -void HMAC_DRBG::generate_output(std::span output, std::span input) { +void HMAC_DRBG::generate_output(Botan::span output, Botan::span input) { BOTAN_ASSERT_NOMSG(!output.empty()); if(!input.empty()) { @@ -149,7 +149,7 @@ void HMAC_DRBG::generate_output(std::span output, std::span input) { +void HMAC_DRBG::update(Botan::span input) { secure_vector T(m_V.size()); m_mac->update(m_V); m_mac->update(0x00); diff --git a/src/lib/rng/hmac_drbg/hmac_drbg.h b/src/lib/rng/hmac_drbg/hmac_drbg.h index af688da4ecc..4322f688b9d 100644 --- a/src/lib/rng/hmac_drbg/hmac_drbg.h +++ b/src/lib/rng/hmac_drbg/hmac_drbg.h @@ -130,9 +130,9 @@ class BOTAN_PUBLIC_API(2, 0) HMAC_DRBG final : public Stateful_RNG { size_t max_number_of_bytes_per_request() const override { return m_max_number_of_bytes_per_request; } private: - void update(std::span input) override; + void update(Botan::span input) override; - void generate_output(std::span output, std::span input) override; + void generate_output(Botan::span output, Botan::span input) override; void clear_state() override; diff --git a/src/lib/rng/processor_rng/processor_rng.cpp b/src/lib/rng/processor_rng/processor_rng.cpp index f72813b0294..bb73477deb3 100644 --- a/src/lib/rng/processor_rng/processor_rng.cpp +++ b/src/lib/rng/processor_rng/processor_rng.cpp @@ -125,7 +125,7 @@ std::string Processor_RNG::name() const { #endif } -void Processor_RNG::fill_bytes_with_input(std::span out, std::span in) { +void Processor_RNG::fill_bytes_with_input(Botan::span out, Botan::span in) { // No way to provide entropy to processor-specific generator, ignore... BOTAN_UNUSED(in); diff --git a/src/lib/rng/processor_rng/processor_rng.h b/src/lib/rng/processor_rng/processor_rng.h index 99c0c37e590..f2e745a5cd6 100644 --- a/src/lib/rng/processor_rng/processor_rng.h +++ b/src/lib/rng/processor_rng/processor_rng.h @@ -40,7 +40,7 @@ class BOTAN_PUBLIC_API(2, 15) Processor_RNG final : public Hardware_RNG { std::string name() const override; private: - void fill_bytes_with_input(std::span out, std::span in) override; + void fill_bytes_with_input(Botan::span out, Botan::span in) override; }; } // namespace Botan diff --git a/src/lib/rng/rng.cpp b/src/lib/rng/rng.cpp index f7f5ca7662d..effc9247121 100644 --- a/src/lib/rng/rng.cpp +++ b/src/lib/rng/rng.cpp @@ -18,14 +18,19 @@ namespace Botan { -void RandomNumberGenerator::randomize_with_ts_input(std::span output) { +void RandomNumberGenerator::randomize_with_ts_input(Botan::span output) { if(this->accepts_input()) { constexpr auto s_hd_clk = sizeof(decltype(OS::get_high_resolution_clock())); constexpr auto s_sys_ts = sizeof(decltype(OS::get_system_timestamp_ns())); constexpr auto s_pid = sizeof(decltype(OS::get_process_id())); std::array additional_input = {0}; - auto s_additional_input = std::span(additional_input.begin(), additional_input.end()); +// TODO: pstanisz to fix Botan::span to be constructed with std::array iterators +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + auto s_additional_input = Botan::span(&(*additional_input.begin()), &(*additional_input.end())); +#else + auto s_additional_input = Botan::span(additional_input.begin(), additional_input.end()); +#endif store_le(OS::get_high_resolution_clock(), s_additional_input.data()); s_additional_input = s_additional_input.subspan(s_hd_clk); diff --git a/src/lib/rng/rng.h b/src/lib/rng/rng.h index c605a791ca5..89e74862ba2 100644 --- a/src/lib/rng/rng.h +++ b/src/lib/rng/rng.h @@ -13,10 +13,10 @@ #include #include #include +#include #include #include -#include #include #include @@ -49,9 +49,9 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @throws PRNG_Unseeded if the RNG fails because it has not enough entropy * @throws Exception if the RNG fails */ - void randomize(std::span output) { this->fill_bytes_with_input(output, {}); } + void randomize(Botan::span output) { this->fill_bytes_with_input(output, {}); } - void randomize(uint8_t output[], size_t length) { this->randomize(std::span(output, length)); } + void randomize(uint8_t output[], size_t length) { this->randomize(Botan::span(output, length)); } /** * Returns false if it is known that this RNG object is not able to accept @@ -72,17 +72,15 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @param input a byte array containing the entropy to be added * @throws Exception may throw if the RNG accepts input, but adding the entropy failed. */ - void add_entropy(std::span input) { this->fill_bytes_with_input({}, input); } + void add_entropy(Botan::span input) { this->fill_bytes_with_input({}, input); } - void add_entropy(const uint8_t input[], size_t length) { this->add_entropy(std::span(input, length)); } + void add_entropy(const uint8_t input[], size_t length) { this->add_entropy(Botan::span(input, length)); } /** * Incorporate some additional data into the RNG state. */ - template - void add_entropy_T(const T& t) - requires std::is_standard_layout::value && std::is_trivial::value - { + template void add_entropy_T(const T& t) { + static_assert(std::is_standard_layout::value && std::is_trivial::value, "add_entropy_T data must be POD"); this->add_entropy(reinterpret_cast(&t), sizeof(T)); } @@ -102,12 +100,12 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @throws Exception if the RNG fails * @throws Exception may throw if the RNG accepts input, but adding the entropy failed. */ - void randomize_with_input(std::span output, std::span input) { + void randomize_with_input(Botan::span output, Botan::span input) { this->fill_bytes_with_input(output, input); } void randomize_with_input(uint8_t output[], size_t output_len, const uint8_t input[], size_t input_len) { - this->randomize_with_input(std::span(output, output_len), std::span(input, input_len)); + this->randomize_with_input(Botan::span(output, output_len), Botan::span(input, input_len)); } /** @@ -124,10 +122,10 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @throws Exception if the RNG fails * @throws Exception may throw if the RNG accepts input, but adding the entropy failed. */ - void randomize_with_ts_input(std::span output); + void randomize_with_ts_input(Botan::span output); void randomize_with_ts_input(uint8_t output[], size_t output_len) { - this->randomize_with_ts_input(std::span(output, output_len)); + this->randomize_with_ts_input(Botan::span(output, output_len)); } /** @@ -177,7 +175,7 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @param v the container to be filled with @p bytes random bytes * @throws Exception if RNG fails */ - void random_vec(std::span v) { this->randomize(v); } + void random_vec(Botan::span v) { this->randomize(v); } /** * Resize a given byte container to @p bytes and fill it with random bytes @@ -187,7 +185,7 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @param bytes number of random bytes to initialize the container with * @throws Exception if RNG or memory allocation fails */ - template + template> void random_vec(T& v, size_t bytes) { v.resize(bytes); random_vec(v); @@ -201,8 +199,8 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * @return a container of type T with @p bytes random bytes * @throws Exception if RNG or memory allocation fails */ - template > - requires concepts::default_initializable + template, + typename = std::enable_if_t && concepts::is_default_initializable_v>> T random_vec(size_t bytes) { T result; random_vec(result, bytes); @@ -217,7 +215,7 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { */ uint8_t next_byte() { uint8_t b; - this->fill_bytes_with_input(std::span(&b, 1), {}); + this->fill_bytes_with_input(Botan::span(&b, 1), {}); return b; } @@ -250,7 +248,7 @@ class BOTAN_PUBLIC_API(2, 0) RandomNumberGenerator { * the RNG's internal state. Implementations may choose to * ignore the bytes in this buffer. */ - virtual void fill_bytes_with_input(std::span output, std::span input) = 0; + virtual void fill_bytes_with_input(Botan::span output, Botan::span input) = 0; }; /** @@ -282,7 +280,7 @@ class BOTAN_PUBLIC_API(2, 0) Null_RNG final : public RandomNumberGenerator { std::string name() const override { return "Null_RNG"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { // throw if caller tries to obtain random bytes if(!output.empty()) { throw PRNG_Unseeded("Null_RNG called"); diff --git a/src/lib/rng/stateful_rng/stateful_rng.cpp b/src/lib/rng/stateful_rng/stateful_rng.cpp index f46e47ebebd..0db9f955de0 100644 --- a/src/lib/rng/stateful_rng/stateful_rng.cpp +++ b/src/lib/rng/stateful_rng/stateful_rng.cpp @@ -28,14 +28,14 @@ bool Stateful_RNG::is_seeded() const { return m_reseed_counter > 0; } -void Stateful_RNG::initialize_with(std::span input) { +void Stateful_RNG::initialize_with(Botan::span input) { lock_guard_type lock(m_mutex); clear(); add_entropy(input); } -void Stateful_RNG::generate_batched_output(std::span output, std::span input) { +void Stateful_RNG::generate_batched_output(Botan::span output, Botan::span input) { BOTAN_ASSERT_NOMSG(!output.empty()); const size_t max_per_request = max_number_of_bytes_per_request(); @@ -59,7 +59,7 @@ void Stateful_RNG::generate_batched_output(std::span output, std::span< } } -void Stateful_RNG::fill_bytes_with_input(std::span output, std::span input) { +void Stateful_RNG::fill_bytes_with_input(Botan::span output, Botan::span input) { lock_guard_type lock(m_mutex); if(output.empty()) { diff --git a/src/lib/rng/stateful_rng/stateful_rng.h b/src/lib/rng/stateful_rng/stateful_rng.h index df299540888..e2c2bb42a59 100644 --- a/src/lib/rng/stateful_rng/stateful_rng.h +++ b/src/lib/rng/stateful_rng/stateful_rng.h @@ -62,9 +62,9 @@ class BOTAN_PUBLIC_API(2, 0) Stateful_RNG : public RandomNumberGenerator { * of the length of the input or the current seeded state of * the RNG. */ - void initialize_with(std::span input); + void initialize_with(Botan::span input); - void initialize_with(const uint8_t input[], size_t length) { this->initialize_with(std::span(input, length)); } + void initialize_with(const uint8_t input[], size_t length) { this->initialize_with(Botan::span(input, length)); } bool is_seeded() const final; @@ -110,16 +110,16 @@ class BOTAN_PUBLIC_API(2, 0) Stateful_RNG : public RandomNumberGenerator { protected: void reseed_check(); - virtual void generate_output(std::span output, std::span input) = 0; + virtual void generate_output(Botan::span output, Botan::span input) = 0; - virtual void update(std::span input) = 0; + virtual void update(Botan::span input) = 0; virtual void clear_state() = 0; private: - void generate_batched_output(std::span output, std::span input); + void generate_batched_output(Botan::span output, Botan::span input); - void fill_bytes_with_input(std::span output, std::span input) final; + void fill_bytes_with_input(Botan::span output, Botan::span input) final; void reset_reseed_counter(); diff --git a/src/lib/rng/system_rng/system_rng.cpp b/src/lib/rng/system_rng/system_rng.cpp index b2f7b4c45f7..0ce18d843b9 100644 --- a/src/lib/rng/system_rng/system_rng.cpp +++ b/src/lib/rng/system_rng/system_rng.cpp @@ -62,7 +62,7 @@ class System_RNG_Impl final : public RandomNumberGenerator { std::string name() const override { return "RtlGenRandom"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { const size_t limit = std::numeric_limits::max(); uint8_t* pData = output.data(); @@ -116,7 +116,7 @@ class System_RNG_Impl final : public RandomNumberGenerator { std::string name() const override { return "crypto_ng"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { /* There is a flag BCRYPT_RNG_USE_ENTROPY_IN_BUFFER to provide entropy inputs, but it is ignored in Windows 8 and later. @@ -158,7 +158,7 @@ class System_RNG_Impl final : public RandomNumberGenerator { std::string name() const override { return "CCRandomGenerateBytes"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { if(::CCRandomGenerateBytes(output.data(), output.size()) != kCCSuccess) { throw System_Error("System_RNG CCRandomGenerateBytes failed", errno); } @@ -181,7 +181,7 @@ class System_RNG_Impl final : public RandomNumberGenerator { std::string name() const override { return "arc4random"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { // macOS 10.15 arc4random crashes if called with buf == nullptr && len == 0 // however it uses ccrng_generate internally which returns a status, ignored // to respect arc4random "no-fail" interface contract @@ -207,7 +207,7 @@ class System_RNG_Impl final : public RandomNumberGenerator { std::string name() const override { return "getrandom"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { const unsigned int flags = 0; uint8_t* buf = output.data(); @@ -295,15 +295,15 @@ class System_RNG_Impl final : public RandomNumberGenerator { std::string name() const override { return "urandom"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override; - void maybe_write_entropy(std::span input); + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override; + void maybe_write_entropy(Botan::span input); private: int m_fd; bool m_writable; }; -void System_RNG_Impl::fill_bytes_with_input(std::span output, std::span input) { +void System_RNG_Impl::fill_bytes_with_input(Botan::span output, Botan::span input) { maybe_write_entropy(input); uint8_t* buf = output.data(); @@ -324,7 +324,7 @@ void System_RNG_Impl::fill_bytes_with_input(std::span output, std::span } } -void System_RNG_Impl::maybe_write_entropy(std::span entropy_input) { +void System_RNG_Impl::maybe_write_entropy(Botan::span entropy_input) { if(!m_writable || entropy_input.empty()) return; diff --git a/src/lib/rng/system_rng/system_rng.h b/src/lib/rng/system_rng/system_rng.h index 016faa92c5d..96cbb627061 100644 --- a/src/lib/rng/system_rng/system_rng.h +++ b/src/lib/rng/system_rng/system_rng.h @@ -33,7 +33,7 @@ class BOTAN_PUBLIC_API(2, 0) System_RNG final : public RandomNumberGenerator { void clear() override { system_rng().clear(); } protected: - void fill_bytes_with_input(std::span out, std::span in) override { + void fill_bytes_with_input(Botan::span out, Botan::span in) override { system_rng().randomize_with_input(out, in); } }; diff --git a/src/lib/stream/chacha/chacha.cpp b/src/lib/stream/chacha/chacha.cpp index 66a3d5e03c1..0d879c074a1 100644 --- a/src/lib/stream/chacha/chacha.cpp +++ b/src/lib/stream/chacha/chacha.cpp @@ -293,7 +293,7 @@ size_t ChaCha::buffer_size() const { /* * ChaCha Key Schedule */ -void ChaCha::key_schedule(std::span key) { +void ChaCha::key_schedule(Botan::span key) { m_key.resize(key.size() / 4); load_le(m_key.data(), key.data(), m_key.size()); diff --git a/src/lib/stream/chacha/chacha.h b/src/lib/stream/chacha/chacha.h index aab6fad12e0..17ab3fe3d27 100644 --- a/src/lib/stream/chacha/chacha.h +++ b/src/lib/stream/chacha/chacha.h @@ -51,7 +51,7 @@ class ChaCha final : public StreamCipher { size_t buffer_size() const override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void cipher_bytes(const uint8_t in[], uint8_t out[], size_t length) override; diff --git a/src/lib/stream/ctr/ctr.cpp b/src/lib/stream/ctr/ctr.cpp index 45871758648..e2da0c11fc0 100644 --- a/src/lib/stream/ctr/ctr.cpp +++ b/src/lib/stream/ctr/ctr.cpp @@ -66,7 +66,7 @@ bool CTR_BE::has_keying_material() const { return m_cipher->has_keying_material(); } -void CTR_BE::key_schedule(std::span key) { +void CTR_BE::key_schedule(Botan::span key) { m_cipher->set_key(key); // Set a default all-zeros IV diff --git a/src/lib/stream/ctr/ctr.h b/src/lib/stream/ctr/ctr.h index f836cf95223..6bfe37176e2 100644 --- a/src/lib/stream/ctr/ctr.h +++ b/src/lib/stream/ctr/ctr.h @@ -44,7 +44,7 @@ class CTR_BE final : public StreamCipher { void seek(uint64_t offset) override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void cipher_bytes(const uint8_t in[], uint8_t out[], size_t length) override; void generate_keystream(uint8_t out[], size_t length) override; void set_iv_bytes(const uint8_t iv[], size_t iv_len) override; diff --git a/src/lib/stream/ofb/ofb.cpp b/src/lib/stream/ofb/ofb.cpp index e4c9c113b7f..d4195d9920c 100644 --- a/src/lib/stream/ofb/ofb.cpp +++ b/src/lib/stream/ofb/ofb.cpp @@ -29,7 +29,7 @@ size_t OFB::buffer_size() const { return m_buffer.size(); // block size } -void OFB::key_schedule(std::span key) { +void OFB::key_schedule(Botan::span key) { m_cipher->set_key(key); // Set a default all-zeros IV diff --git a/src/lib/stream/ofb/ofb.h b/src/lib/stream/ofb/ofb.h index 641d428c504..94d1a79aa16 100644 --- a/src/lib/stream/ofb/ofb.h +++ b/src/lib/stream/ofb/ofb.h @@ -42,7 +42,7 @@ class OFB final : public StreamCipher { void seek(uint64_t offset) override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void cipher_bytes(const uint8_t in[], uint8_t out[], size_t length) override; void set_iv_bytes(const uint8_t iv[], size_t iv_len) override; diff --git a/src/lib/stream/rc4/rc4.cpp b/src/lib/stream/rc4/rc4.cpp index 45ec020ff78..dc4a4186a46 100644 --- a/src/lib/stream/rc4/rc4.cpp +++ b/src/lib/stream/rc4/rc4.cpp @@ -91,7 +91,7 @@ bool RC4::has_keying_material() const { /* * RC4 Key Schedule */ -void RC4::key_schedule(std::span key) { +void RC4::key_schedule(Botan::span key) { m_state.resize(256); m_buffer.resize(256); diff --git a/src/lib/stream/rc4/rc4.h b/src/lib/stream/rc4/rc4.h index 03ec960d2fe..c29a7a421ee 100644 --- a/src/lib/stream/rc4/rc4.h +++ b/src/lib/stream/rc4/rc4.h @@ -39,7 +39,7 @@ class RC4 final : public StreamCipher { ~RC4() override { clear(); } private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void cipher_bytes(const uint8_t in[], uint8_t out[], size_t length) override; void set_iv_bytes(const uint8_t iv[], size_t iv_len) override; void generate(); diff --git a/src/lib/stream/salsa20/salsa20.cpp b/src/lib/stream/salsa20/salsa20.cpp index 0a6a4aebb19..9ac9af9c92a 100644 --- a/src/lib/stream/salsa20/salsa20.cpp +++ b/src/lib/stream/salsa20/salsa20.cpp @@ -172,7 +172,7 @@ size_t Salsa20::buffer_size() const { /* * Salsa20 Key Schedule */ -void Salsa20::key_schedule(std::span key) { +void Salsa20::key_schedule(Botan::span key) { m_key.resize(key.size() / 4); load_le(m_key.data(), key.data(), m_key.size()); diff --git a/src/lib/stream/salsa20/salsa20.h b/src/lib/stream/salsa20/salsa20.h index ed0c34e0ef0..dd39d09e193 100644 --- a/src/lib/stream/salsa20/salsa20.h +++ b/src/lib/stream/salsa20/salsa20.h @@ -39,7 +39,7 @@ class Salsa20 final : public StreamCipher { void set_iv_bytes(const uint8_t iv[], size_t iv_len) override; private: - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; void initialize_state(); diff --git a/src/lib/stream/shake_cipher/shake_cipher.cpp b/src/lib/stream/shake_cipher/shake_cipher.cpp index 3e47fc3bd81..9ee00c0b91b 100644 --- a/src/lib/stream/shake_cipher/shake_cipher.cpp +++ b/src/lib/stream/shake_cipher/shake_cipher.cpp @@ -48,7 +48,7 @@ void SHAKE_Cipher::cipher_bytes(const uint8_t in[], uint8_t out[], size_t length if(bytes > 0) { BOTAN_ASSERT_NOMSG(bytes <= block_size); BOTAN_ASSERT_NOMSG(bytes <= length); - generate_keystream_internal(std::span(m_keystream_buffer).first(bytes)); + generate_keystream_internal(Botan::span(m_keystream_buffer).first(bytes)); xor_buf(out, m_keystream_buffer.data(), in, bytes); out += bytes; in += bytes; @@ -76,12 +76,12 @@ void SHAKE_Cipher::generate_keystream(uint8_t out[], size_t length) { generate_keystream_internal({out, length}); } -void SHAKE_Cipher::generate_keystream_internal(std::span out) { +void SHAKE_Cipher::generate_keystream_internal(Botan::span out) { m_keccak.squeeze(out); m_bytes_generated += out.size(); } -void SHAKE_Cipher::key_schedule(std::span key) { +void SHAKE_Cipher::key_schedule(Botan::span key) { clear(); m_keccak.absorb(key); m_keccak.finish(); diff --git a/src/lib/stream/shake_cipher/shake_cipher.h b/src/lib/stream/shake_cipher/shake_cipher.h index 41fe0719af0..cc5bec9da58 100644 --- a/src/lib/stream/shake_cipher/shake_cipher.h +++ b/src/lib/stream/shake_cipher/shake_cipher.h @@ -36,14 +36,14 @@ class SHAKE_Cipher : public StreamCipher { size_t buffer_size() const final { return m_keccak.byte_rate(); } private: - void key_schedule(std::span key) final; + void key_schedule(Botan::span key) final; /** * Produce more XOF output */ void cipher_bytes(const uint8_t in[], uint8_t out[], size_t length) final; void generate_keystream(uint8_t out[], size_t length) override; - void generate_keystream_internal(std::span out); + void generate_keystream_internal(Botan::span out); /** * IV not supported, this function will throw unless iv_len == 0 diff --git a/src/lib/stream/stream_cipher.h b/src/lib/stream/stream_cipher.h index a725d7693f0..cc3f2792603 100644 --- a/src/lib/stream/stream_cipher.h +++ b/src/lib/stream/stream_cipher.h @@ -61,7 +61,7 @@ class BOTAN_PUBLIC_API(2, 0) StreamCipher : public SymmetricAlgorithm { * @param out the byte array to hold the output, i.e. the ciphertext * with at least the same size as @p in */ - void cipher(std::span in, std::span out) { + void cipher(Botan::span in, Botan::span out) { BOTAN_ARG_CHECK(in.size() <= out.size(), "Output buffer of stream cipher must be at least as long as input buffer"); cipher_bytes(in.data(), out.data(), in.size()); @@ -84,14 +84,14 @@ class BOTAN_PUBLIC_API(2, 0) StreamCipher : public SymmetricAlgorithm { * * @param out the byte array to hold the keystream */ - void write_keystream(std::span out) { generate_keystream(out.data(), out.size()); } + void write_keystream(Botan::span out) { generate_keystream(out.data(), out.size()); } /** * Get @p bytes from the keystream * * @param bytes The number of bytes to be produced */ - template > + template, typename = Botan::concepts::resizable_byte_buffer> T keystream_bytes(size_t bytes) { T out(bytes); write_keystream(out); @@ -111,28 +111,28 @@ class BOTAN_PUBLIC_API(2, 0) StreamCipher : public SymmetricAlgorithm { * The message is encrypted/decrypted in place. * @param buf the plaintext / ciphertext */ - void cipher1(std::span buf) { cipher(buf, buf); } + void cipher1(Botan::span buf) { cipher(buf, buf); } /** * Encrypt a message * The message is encrypted/decrypted in place. * @param inout the plaintext / ciphertext */ - void encipher(std::span inout) { cipher(inout.data(), inout.data(), inout.size()); } + void encipher(Botan::span inout) { cipher(inout.data(), inout.data(), inout.size()); } /** * Encrypt a message * The message is encrypted in place. * @param inout the plaintext / ciphertext */ - void encrypt(std::span inout) { cipher(inout.data(), inout.data(), inout.size()); } + void encrypt(Botan::span inout) { cipher(inout.data(), inout.data(), inout.size()); } /** * Decrypt a message in place * The message is decrypted in place. * @param inout the plaintext / ciphertext */ - void decrypt(std::span inout) { cipher(inout.data(), inout.data(), inout.size()); } + void decrypt(Botan::span inout) { cipher(inout.data(), inout.data(), inout.size()); } /** * Return the optimium buffer size to use with this cipher @@ -160,7 +160,7 @@ class BOTAN_PUBLIC_API(2, 0) StreamCipher : public SymmetricAlgorithm { * Resync the cipher using the IV * @param iv the initialization vector */ - void set_iv(std::span iv) { set_iv_bytes(iv.data(), iv.size()); } + void set_iv(Botan::span iv) { set_iv_bytes(iv.data(), iv.size()); } /** * Return the default (preferred) nonce length diff --git a/src/lib/tls/asio/asio_stream.h b/src/lib/tls/asio/asio_stream.h index 9da6c1a23d7..050f84f7f72 100644 --- a/src/lib/tls/asio/asio_stream.h +++ b/src/lib/tls/asio/asio_stream.h @@ -556,12 +556,12 @@ class Stream { ~StreamCore() override = default; - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { send_buffer.commit(boost::asio::buffer_copy(send_buffer.prepare(data.size()), boost::asio::buffer(data.data(), data.size()))); } - void tls_record_received(uint64_t, std::span data) override { + void tls_record_received(uint64_t, Botan::span data) override { receive_buffer.commit(boost::asio::buffer_copy(receive_buffer.prepare(data.size()), boost::asio::const_buffer(data.data(), data.size()))); } diff --git a/src/lib/tls/msg_cert_verify.cpp b/src/lib/tls/msg_cert_verify.cpp index 8105e211d48..45be97c7328 100644 --- a/src/lib/tls/msg_cert_verify.cpp +++ b/src/lib/tls/msg_cert_verify.cpp @@ -19,7 +19,9 @@ #include #include -namespace Botan::TLS { +namespace Botan { + +namespace TLS { /* * Create a new Certificate Verify message for TLS 1.2 @@ -128,8 +130,8 @@ Signature_Scheme choose_signature_scheme(const Private_Key& key, } } - throw TLS_Exception(Alert::HandshakeFailure, "Failed to agree on a signature algorithm"); -} + throw TLS_Exception(AlertType::HandshakeFailure, "Failed to agree on a signature algorithm"); + } } // namespace @@ -152,12 +154,12 @@ Certificate_Verify_13::Certificate_Verify_13(const Certificate_13& certificate_m certificate_msg.leaf(), m_side == Connection_Side::Client ? "tls-client" : "tls-server", std::string(hostname)); if(!private_key) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a private key for its certificate"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a private key for its certificate"); } m_scheme = choose_signature_scheme(*private_key, policy.allowed_signature_schemes(), peer_allowed_schemes); BOTAN_ASSERT_NOMSG(m_scheme.is_available()); - BOTAN_ASSERT_NOMSG(m_scheme.is_compatible_with(Protocol_Version::TLS_V13)); + BOTAN_ASSERT_NOMSG(m_scheme.is_compatible_with(Version_Code::TLS_V13)); m_signature = callbacks.tls_sign_message( *private_key, rng, m_scheme.padding_string(), m_scheme.format().value(), message(m_side, hash)); @@ -166,11 +168,11 @@ Certificate_Verify_13::Certificate_Verify_13(const Certificate_13& certificate_m Certificate_Verify_13::Certificate_Verify_13(const std::vector& buf, const Connection_Side side) : Certificate_Verify(buf), m_side(side) { if(!m_scheme.is_available()) { - throw TLS_Exception(Alert::HandshakeFailure, "Peer sent unknown signature scheme"); + throw TLS_Exception(AlertType::HandshakeFailure, "Peer sent unknown signature scheme"); } - if(!m_scheme.is_compatible_with(Protocol_Version::TLS_V13)) { - throw TLS_Exception(Alert::IllegalParameter, "Peer sent signature algorithm that is not suitable for TLS 1.3"); + if(!m_scheme.is_compatible_with(Version_Code::TLS_V13)) { + throw TLS_Exception(AlertType::IllegalParameter, "Peer sent signature algorithm that is not suitable for TLS 1.3"); } } @@ -186,7 +188,7 @@ bool Certificate_Verify_13::verify(const X509_Certificate& cert, // The keys found in certificates MUST [...] be of appropriate type for // the signature algorithms they are used with. if(m_scheme.key_algorithm_identifier() != cert.subject_public_key_algo()) { - throw TLS_Exception(Alert::IllegalParameter, "Signature algorithm does not match certificate's public key"); + throw TLS_Exception(AlertType::IllegalParameter, "Signature algorithm does not match certificate's public key"); } const auto key = cert.subject_public_key(); @@ -203,4 +205,6 @@ bool Certificate_Verify_13::verify(const X509_Certificate& cert, #endif // BOTAN_HAS_TLS_13 -} // namespace Botan::TLS +} // namespace TLS + +} // namespace Botan diff --git a/src/lib/tls/msg_client_hello.cpp b/src/lib/tls/msg_client_hello.cpp index 12f1fbc6e36..e51cffc81a6 100644 --- a/src/lib/tls/msg_client_hello.cpp +++ b/src/lib/tls/msg_client_hello.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include @@ -124,15 +125,15 @@ class Client_Hello_Internal { // 0x0303 and a supported_versions extension present with 0x0304 as // the highest version indicated therein. if(!extensions().has() || - !extensions().get()->supports(Protocol_Version::TLS_V13)) { + !extensions().get()->supports(Version_Code::TLS_V13)) { // The exact legacy_version is ignored we just inspect it to // distinguish TLS and DTLS. - return (m_legacy_version.is_datagram_protocol()) ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12; + return (m_legacy_version.is_datagram_protocol()) ? Version_Code::DTLS_V12 : Version_Code::TLS_V12; } // Note: The Client_Hello_13 class will make sure that legacy_version // is exactly 0x0303 (aka ossified TLS 1.2) - return Protocol_Version::TLS_V13; + return Version_Code::TLS_V13; } Protocol_Version legacy_version() const { return m_legacy_version; } @@ -439,7 +440,7 @@ Client_Hello_12::Client_Hello_12(std::unique_ptr data) : if(offered_suite(static_cast(TLS_EMPTY_RENEGOTIATION_INFO_SCSV))) { if(Renegotiation_Extension* reneg = m_data->extensions().get()) { if(!reneg->renegotiation_info().empty()) { - throw TLS_Exception(Alert::HandshakeFailure, "Client sent renegotiation SCSV and non-empty extension"); + throw TLS_Exception(AlertType::HandshakeFailure, "Client sent renegotiation SCSV and non-empty extension"); } } else { // add fake extension @@ -616,7 +617,7 @@ Client_Hello_13::Client_Hello_13(std::unique_ptr data) : // Servers MAY abort the handshake upon receiving a ClientHello with // legacy_version 0x0304 or later. if(m_data->legacy_version().is_tls_13_or_later()) { - throw TLS_Exception(Alert::DecodeError, "TLS 1.3 Client Hello has invalid legacy_version"); + throw TLS_Exception(AlertType::DecodeError, "TLS 1.3 Client Hello has invalid legacy_version"); } // RFC 8446 4.1.2 @@ -625,7 +626,7 @@ Client_Hello_13::Client_Hello_13(std::unique_ptr data) : // received with any other value in this field, the server MUST abort the // handshake with an "illegal_parameter" alert. if(m_data->comp_methods().size() != 1 || m_data->comp_methods().front() != 0) { - throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression"); + throw TLS_Exception(AlertType::IllegalParameter, "Client did not offer NULL compression"); } // RFC 8446 4.2.9 @@ -635,7 +636,7 @@ Client_Hello_13::Client_Hello_13(std::unique_ptr data) : // the handshake. if(exts.has()) { if(!exts.has()) { - throw TLS_Exception(Alert::MissingExtension, + throw TLS_Exception(AlertType::MissingExtension, "Client Hello offered a PSK without a psk_key_exchange_modes extension"); } @@ -644,7 +645,7 @@ Client_Hello_13::Client_Hello_13(std::unique_ptr data) : // ClientHello [...]. Servers MUST check that it is the last extension // and otherwise fail the handshake with an "illegal_parameter" alert. if(exts.all().back()->type() != Extension_Code::PresharedKey) { - throw TLS_Exception(Alert::IllegalParameter, "PSK extension was not at the very end of the Client Hello"); + throw TLS_Exception(AlertType::IllegalParameter, "PSK extension was not at the very end of the Client Hello"); } } @@ -665,12 +666,12 @@ Client_Hello_13::Client_Hello_13(std::unique_ptr data) : if(!exts.has()) { if(!exts.has() || !exts.has()) { throw TLS_Exception( - Alert::MissingExtension, + AlertType::MissingExtension, "Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions"); } } if(exts.has() != exts.has()) { - throw TLS_Exception(Alert::MissingExtension, + throw TLS_Exception(AlertType::MissingExtension, "Client Hello must either contain both key_share and supported_groups extensions or neither"); } @@ -710,7 +711,7 @@ Client_Hello_13::Client_Hello_13(std::unique_ptr data) : // Servers MAY check for violations of these rules and abort the // handshake with an "illegal_parameter" alert if one is violated. if(!found_in_supported_groups(offered)) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "Offered key exchange groups do not align with claimed supported groups"); } } @@ -737,13 +738,13 @@ Client_Hello_13::Client_Hello_13(const Policy& policy, // "supported_versions" extension (Section 4.2.1) and the // legacy_version field MUST be set to 0x0303, which is the version // number for TLS 1.2. - m_data->m_legacy_version = Protocol_Version::TLS_V12; + m_data->m_legacy_version = Version_Code::TLS_V12; m_data->m_random = make_hello_random(rng, cb, policy); - m_data->m_suites = policy.ciphersuite_list(Protocol_Version::TLS_V13); + m_data->m_suites = policy.ciphersuite_list(Version_Code::TLS_V13); if(policy.allow_tls12()) // Note: DTLS 1.3 is NYI, hence dtls_12 is not checked { - const auto legacy_suites = policy.ciphersuite_list(Protocol_Version::TLS_V12); + const auto legacy_suites = policy.ciphersuite_list(Version_Code::TLS_V12); m_data->m_suites.insert(m_data->m_suites.end(), legacy_suites.cbegin(), legacy_suites.cend()); } @@ -766,7 +767,7 @@ Client_Hello_13::Client_Hello_13(const Policy& policy, m_data->extensions().add(new Key_Share(policy, cb, rng)); - m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13, policy)); + m_data->extensions().add(new Supported_Versions(Version_Code::TLS_V13, policy)); m_data->extensions().add(new Signature_Algorithms(policy.acceptable_signature_schemes())); if(auto cert_signing_prefs = policy.acceptable_certificate_signature_schemes()) { @@ -824,7 +825,7 @@ Client_Hello_13::Client_Hello_13(const Policy& policy, // The "pre_shared_key" extension MUST be the last extension in the // ClientHello (this facilitates implementation [...]). if(m_data->extensions().all().back()->type() != Extension_Code::PresharedKey) { - throw TLS_Exception(Alert::InternalError, + throw TLS_Exception(AlertType::InternalError, "Application modified extensions of Client Hello, PSK is not last anymore"); } calculate_psk_binders({}); @@ -903,7 +904,7 @@ void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) { if(m_data->session_id() != new_ch.m_data->session_id() || m_data->random() != new_ch.m_data->random() || m_data->ciphersuites() != new_ch.m_data->ciphersuites() || m_data->comp_methods() != new_ch.m_data->comp_methods()) { - throw TLS_Exception(Alert::IllegalParameter, "Client Hello core values changed after Hello Retry Request"); + throw TLS_Exception(AlertType::IllegalParameter, "Client Hello core values changed after Hello Retry Request"); } const auto oldexts = extension_types(); @@ -911,7 +912,7 @@ void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) { // Check that extension omissions are justified for(const auto oldext : oldexts) { - if(!newexts.contains(oldext)) { + if(!contains(newexts, (oldext))) { const auto ext = extensions().get(oldext); // We don't make any assumptions about unimplemented extensions. @@ -934,13 +935,13 @@ void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) { // if(oldext == Padding::static_type()) // continue; - throw TLS_Exception(Alert::IllegalParameter, "Extension removed in updated Client Hello"); + throw TLS_Exception(AlertType::IllegalParameter, "Extension removed in updated Client Hello"); } } // Check that extension additions are justified for(const auto newext : newexts) { - if(!oldexts.contains(newext)) { + if(!contains(oldexts, newext)) { const auto ext = new_ch.extensions().get(newext); // We don't make any assumptions about unimplemented extensions. @@ -963,7 +964,7 @@ void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) { // if(newext == Padding::static_type()) // continue; - throw TLS_Exception(Alert::UnsupportedExtension, "Added an extension in updated Client Hello"); + throw TLS_Exception(AlertType::UnsupportedExtension, "Added an extension in updated Client Hello"); } } @@ -971,7 +972,7 @@ void Client_Hello_13::validate_updates(const Client_Hello_13& new_ch) { // Removing the "early_data" extension (Section 4.2.10) if one was // present. Early data is not permitted after a HelloRetryRequest. if(new_ch.extensions().has()) { - throw TLS_Exception(Alert::IllegalParameter, "Updated Client Hello indicates early data"); + throw TLS_Exception(AlertType::IllegalParameter, "Updated Client Hello indicates early data"); } // TODO: Contents of extensions are not checked for update compatibility, see: diff --git a/src/lib/tls/msg_server_hello.cpp b/src/lib/tls/msg_server_hello.cpp index 09c227cbb48..201cedc9e2a 100644 --- a/src/lib/tls/msg_server_hello.cpp +++ b/src/lib/tls/msg_server_hello.cpp @@ -11,6 +11,7 @@ #include +#include #include #include #include @@ -134,7 +135,7 @@ class Server_Hello_Internal { // // Note: Here we just take a message parsing decision, further validation of // the extension's contents is done later. - return (extensions().has()) ? Protocol_Version::TLS_V13 : m_legacy_version; + return (extensions().has()) ? Version_Code::TLS_V13 : m_legacy_version; } Protocol_Version legacy_version() const { return m_legacy_version; } @@ -261,7 +262,7 @@ Server_Hello_12::Server_Hello_12(Handshake_IO& io, m_data->extensions().add(new Encrypt_then_MAC); } - if(c && c->ecc_ciphersuite() && client_hello.extension_types().contains(Extension_Code::EcPointFormats)) { + if(c && c->ecc_ciphersuite() && contains(client_hello.extension_types(), Extension_Code::EcPointFormats)) { m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression())); } @@ -331,7 +332,7 @@ Server_Hello_12::Server_Hello_12(Handshake_IO& io, } if(resumed_session.ciphersuite().ecc_ciphersuite() && - client_hello.extension_types().contains(Extension_Code::EcPointFormats)) { + contains(client_hello.extension_types(), Extension_Code::EcPointFormats)) { m_data->extensions().add(new Supported_Point_Formats(policy.use_ecc_point_compression())); } @@ -353,7 +354,7 @@ Server_Hello_12::Server_Hello_12(const std::vector& buf) : Server_Hello_12::Server_Hello_12(std::unique_ptr data) : Server_Hello(std::move(data)) { if(!m_data->version().is_pre_tls_13()) { - throw TLS_Exception(Alert::ProtocolVersion, "Expected server hello of (D)TLS 1.2 or lower"); + throw TLS_Exception(AlertType::ProtocolVersion, "Expected server hello of (D)TLS 1.2 or lower"); } } @@ -417,10 +418,10 @@ bool Server_Hello_12::prefers_compressed_ec_points() const { std::optional Server_Hello_12::random_signals_downgrade() const { const uint64_t last8 = load_be(m_data->random().data(), 3); if(last8 == DOWNGRADE_TLS11) { - return Protocol_Version::TLS_V11; + return Version_Code::TLS_V11; } if(last8 == DOWNGRADE_TLS12) { - return Protocol_Version::TLS_V12; + return Version_Code::TLS_V12; } return std::nullopt; @@ -479,15 +480,15 @@ std::variant Server_Hello_13::create(const // If there is no overlap between the received "supported_groups" and the // groups supported by the server, then the server MUST abort the // handshake with a "handshake_failure" or an "insufficient_security" alert. - if(selected_group == Named_Group::NONE) { - throw TLS_Exception(Alert::HandshakeFailure, "Client did not offer any acceptable group"); + if(selected_group == Group_Params_Code::NONE) { + throw TLS_Exception(AlertType::HandshakeFailure, "Client did not offer any acceptable group"); } // RFC 8446 4.2.8: // Servers MUST NOT send a KeyShareEntry for any group not indicated in the // client's "supported_groups" extension [...] if(!value_exists(supported_by_client, selected_group)) { - throw TLS_Exception(Alert::InternalError, "Application selected a group that is not supported by the client"); + throw TLS_Exception(AlertType::InternalError, "Application selected a group that is not supported by the client"); } // RFC 8446 4.1.4 @@ -522,7 +523,7 @@ std::variant Server_Hello } // ... the TLS 1.3 "special case" aka. Hello_Retry_Request - if(version == Protocol_Version::TLS_V13) { + if(version == Version_Code::TLS_V13) { if(data->is_hello_retry_request()) { return Hello_Retry_Request(std::move(data)); } @@ -530,14 +531,14 @@ std::variant Server_Hello return Server_Hello_13(std::move(data)); } - throw TLS_Exception(Alert::ProtocolVersion, "unexpected server hello version: " + version.to_string()); + throw TLS_Exception(AlertType::ProtocolVersion, "unexpected server hello version: " + version.to_string()); } /** * Validation that applies to both Server Hello and Hello Retry Request */ void Server_Hello_13::basic_validation() const { - BOTAN_ASSERT_NOMSG(m_data->version() == Protocol_Version::TLS_V13); + BOTAN_ASSERT_NOMSG(m_data->version() == Version_Code::TLS_V13); // Note: checks that cannot be performed without contextual information // are done in the specific TLS client implementation. @@ -555,29 +556,29 @@ void Server_Hello_13::basic_validation() const { // RFC 8446 4.1.3 // In TLS 1.3, [...] the legacy_version field MUST be set to 0x0303 - if(legacy_version() != Protocol_Version::TLS_V12) { - throw TLS_Exception(Alert::ProtocolVersion, + if(legacy_version() != Version_Code::TLS_V12) { + throw TLS_Exception(AlertType::ProtocolVersion, "legacy_version '" + legacy_version().to_string() + "' is not allowed"); } // RFC 8446 4.1.3 // legacy_compression_method: A single byte which MUST have the value 0. if(compression_method() != 0x00) { - throw TLS_Exception(Alert::DecodeError, "compression is not supported in TLS 1.3"); + throw TLS_Exception(AlertType::DecodeError, "compression is not supported in TLS 1.3"); } // RFC 8446 4.1.3 // All TLS 1.3 ServerHello messages MUST contain the "supported_versions" extension. if(!extensions().has()) { - throw TLS_Exception(Alert::MissingExtension, "server hello did not contain 'supported version' extension"); + throw TLS_Exception(AlertType::MissingExtension, "server hello did not contain 'supported version' extension"); } // RFC 8446 4.2.1 // A server which negotiates TLS 1.3 MUST respond by sending // a "supported_versions" extension containing the selected version // value (0x0304). - if(selected_version() != Protocol_Version::TLS_V13) { - throw TLS_Exception(Alert::IllegalParameter, "TLS 1.3 Server Hello selected a different version"); + if(selected_version() != Version_Code::TLS_V13) { + throw TLS_Exception(AlertType::IllegalParameter, "TLS 1.3 Server Hello selected a different version"); } } @@ -606,7 +607,7 @@ Server_Hello_13::Server_Hello_13(std::unique_ptr data, Se // As the ServerHello shall only contain essential extensions, we don't give // any slack for extensions not implemented by Botan here. if(exts.contains_other_than(allowed)) { - throw TLS_Exception(Alert::UnsupportedExtension, "Server Hello contained an extension that is not allowed"); + throw TLS_Exception(AlertType::UnsupportedExtension, "Server Hello contained an extension that is not allowed"); } // RFC 8446 4.1.3 @@ -614,7 +615,7 @@ Server_Hello_13::Server_Hello_13(std::unique_ptr data, Se // either the "pre_shared_key" extension or the "key_share" // extension, or both [...]. if(!exts.has() && !exts.has()) { - throw TLS_Exception(Alert::MissingExtension, "server hello must contain key exchange information"); + throw TLS_Exception(AlertType::MissingExtension, "server hello must contain key exchange information"); } } @@ -640,7 +641,7 @@ Server_Hello_13::Server_Hello_13(std::unique_ptr data, // As the Hello Retry Request shall only contain essential extensions, we // don't give any slack for extensions not implemented by Botan here. if(exts.contains_other_than(allowed)) { - throw TLS_Exception(Alert::UnsupportedExtension, + throw TLS_Exception(AlertType::UnsupportedExtension, "Hello Retry Request contained an extension that is not allowed"); } @@ -648,7 +649,8 @@ Server_Hello_13::Server_Hello_13(std::unique_ptr data, // Clients MUST abort the handshake with an "illegal_parameter" alert if // the HelloRetryRequest would not result in any change in the ClientHello. if(!exts.has() && !exts.has()) { - throw TLS_Exception(Alert::IllegalParameter, "Hello Retry Request does not request any changes to Client Hello"); + throw TLS_Exception(AlertType::IllegalParameter, + "Hello Retry Request does not request any changes to Client Hello"); } } @@ -660,7 +662,7 @@ namespace { uint16_t choose_ciphersuite(const Client_Hello_13& ch, const Policy& policy) { auto pref_list = ch.ciphersuites(); // TODO: DTLS might need to make this version dynamic - auto other_list = policy.ciphersuite_list(Protocol_Version::TLS_V13); + auto other_list = policy.ciphersuite_list(Version_Code::TLS_V13); if(policy.server_uses_own_ciphersuite_preferences()) { std::swap(pref_list, other_list); @@ -697,7 +699,7 @@ uint16_t choose_ciphersuite(const Client_Hello_13& ch, const Policy& policy) { // If the server is unable to negotiate a supported set of parameters // [...], it MUST abort the handshake with either a "handshake_failure" // or "insufficient_security" fatal alert [...]. - throw TLS_Exception(Alert::HandshakeFailure, "Can't agree on a ciphersuite with client"); + throw TLS_Exception(AlertType::HandshakeFailure, "Can't agree on a ciphersuite with client"); } } // namespace @@ -709,9 +711,9 @@ Server_Hello_13::Server_Hello_13(const Client_Hello_13& ch, Callbacks& cb, const Policy& policy) : Server_Hello(std::make_unique( - Protocol_Version::TLS_V12, + Version_Code::TLS_V12, ch.session_id(), - make_server_hello_random(rng, Protocol_Version::TLS_V13, cb, policy), + make_server_hello_random(rng, Version_Code::TLS_V13, cb, policy), choose_ciphersuite(ch, policy), uint8_t(0) /* compression method */ )) { @@ -723,7 +725,7 @@ Server_Hello_13::Server_Hello_13(const Client_Hello_13& ch, // // Note that the legacy version (TLS 1.2) is set in this constructor's // initializer list, accordingly. - m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13)); + m_data->extensions().add(new Supported_Versions(Version_Code::TLS_V13)); if(key_exchange_group.has_value()) { BOTAN_ASSERT_NOMSG(ch.extensions().has()); @@ -764,10 +766,10 @@ Server_Hello_13::Server_Hello_13(const Client_Hello_13& ch, std::optional Server_Hello_13::random_signals_downgrade() const { const uint64_t last8 = load_be(m_data->random().data(), 3); if(last8 == DOWNGRADE_TLS11) { - return Protocol_Version::TLS_V11; + return Version_Code::TLS_V11; } if(last8 == DOWNGRADE_TLS12) { - return Protocol_Version::TLS_V12; + return Version_Code::TLS_V12; } return std::nullopt; @@ -788,7 +790,7 @@ Hello_Retry_Request::Hello_Retry_Request(const Client_Hello_13& ch, Named_Group selected_group, const Policy& policy, Callbacks& cb) : - Server_Hello_13(std::make_unique(Protocol_Version::TLS_V12 /* legacy_version */, + Server_Hello_13(std::make_unique(Version_Code::TLS_V12 /* legacy_version */, ch.session_id(), HELLO_RETRY_REQUEST_MARKER, choose_ciphersuite(ch, policy), @@ -817,7 +819,7 @@ Hello_Retry_Request::Hello_Retry_Request(const Client_Hello_13& ch, // // Note that the legacy version (TLS 1.2) is set in this constructor's // initializer list, accordingly. - m_data->extensions().add(new Supported_Versions(Protocol_Version::TLS_V13)); + m_data->extensions().add(new Supported_Versions(Version_Code::TLS_V13)); m_data->extensions().add(new Key_Share(selected_group)); diff --git a/src/lib/tls/msg_session_ticket.cpp b/src/lib/tls/msg_session_ticket.cpp index c8524eff3da..1b0cea93769 100644 --- a/src/lib/tls/msg_session_ticket.cpp +++ b/src/lib/tls/msg_session_ticket.cpp @@ -18,7 +18,7 @@ #include -#include +#include namespace Botan::TLS { @@ -49,7 +49,7 @@ New_Session_Ticket_12::New_Session_Ticket_12(const std::vector& buf) { namespace { template -void store_lifetime(std::span sink, std::chrono::seconds lifetime) { +void store_lifetime(Botan::span sink, std::chrono::seconds lifetime) { BOTAN_ARG_CHECK(lifetime.count() >= 0 && lifetime.count() <= std::numeric_limits::max(), "Ticket lifetime is out of range"); store_be(static_cast(lifetime.count()), sink.data()); @@ -85,8 +85,8 @@ New_Session_Ticket_13::New_Session_Ticket_13(const std::vector& buf, Co // RFC 8446 4.6.1 // Servers MUST NOT use any value [of ticket_lifetime] greater than 604800 // seconds (7 days). - if(m_ticket_lifetime_hint > std::chrono::days(7)) { - throw TLS_Exception(Alert::IllegalParameter, "Received a session ticket with lifetime longer than one week."); + if(m_ticket_lifetime_hint > std::chrono::seconds(604800)) { + throw TLS_Exception(AlertType::IllegalParameter, "Received a session ticket with lifetime longer than one week."); } m_ticket_age_add = reader.get_uint32_t(); @@ -100,7 +100,7 @@ New_Session_Ticket_13::New_Session_Ticket_13(const std::vector& buf, Co // "early_data", indicating that the ticket may be used to send 0-RTT // data [...]. Clients MUST ignore unrecognized extensions. if(m_extensions.contains_implemented_extensions_other_than({Extension_Code::EarlyData})) { - throw TLS_Exception(Alert::IllegalParameter, "NewSessionTicket message contained unexpected extension"); + throw TLS_Exception(AlertType::IllegalParameter, "NewSessionTicket message contained unexpected extension"); } reader.assert_done(); @@ -119,7 +119,7 @@ std::optional New_Session_Ticket_13::early_data_byte_limit() const { std::vector New_Session_Ticket_13::serialize() const { std::vector result(8); - store_lifetime(std::span(result.data(), 4), m_ticket_lifetime_hint); + store_lifetime(Botan::span(result.data(), 4), m_ticket_lifetime_hint); store_be(m_ticket_age_add, result.data() + 4); append_tls_length_value(result, m_ticket_nonce.get(), 1); append_tls_length_value(result, m_handle.get(), 2); diff --git a/src/lib/tls/sessions_sql/tls_session_manager_sql.cpp b/src/lib/tls/sessions_sql/tls_session_manager_sql.cpp index 13611eb56a3..c629dd1b29c 100644 --- a/src/lib/tls/sessions_sql/tls_session_manager_sql.cpp +++ b/src/lib/tls/sessions_sql/tls_session_manager_sql.cpp @@ -104,7 +104,7 @@ void Session_Manager_SQL::create_with_latest_schema(std::string_view passphrase, const size_t iterations = pbkdf->iterations(); const size_t check_val = make_uint16(derived_key[0], derived_key[1]); - m_session_key = SymmetricKey(std::span(derived_key).subspan(2)); + m_session_key = SymmetricKey(Botan::span(derived_key).subspan(2)); auto stmt = m_db->new_statement("INSERT INTO tls_sessions_metadata VALUES (?1, ?2, ?3, ?4, ?5)"); @@ -142,7 +142,7 @@ void Session_Manager_SQL::initialize_existing_database(std::string_view passphra throw Invalid_Argument("Session database password not valid"); } - m_session_key = SymmetricKey(std::span(derived_key).subspan(2)); + m_session_key = SymmetricKey(Botan::span(derived_key).subspan(2)); } void Session_Manager_SQL::store(const Session& session, const Session_Handle& handle) { @@ -221,7 +221,7 @@ std::vector Session_Manager_SQL::find_some(const Server_Inf auto handle = [&]() -> Session_Handle { auto ticket_blob = stmt->get_blob(1); if(ticket_blob.second > 0) { - return Session_Ticket(std::span(ticket_blob.first, ticket_blob.second)); + return Session_Ticket(Botan::span(ticket_blob.first, ticket_blob.second)); } else { return Session_ID(Botan::hex_decode(stmt->get_str(0))); } diff --git a/src/lib/tls/tls12/msg_certificate_12.cpp b/src/lib/tls/tls12/msg_certificate_12.cpp index 5ad94b0bac1..049052b1435 100644 --- a/src/lib/tls/tls12/msg_certificate_12.cpp +++ b/src/lib/tls/tls12/msg_certificate_12.cpp @@ -72,7 +72,7 @@ Certificate_12::Certificate_12(const std::vector& buf, const Policy& po * But, require that the leaf certificate be v3 */ if(!m_certs.empty() && m_certs[0].x509_version() != 3) { - throw TLS_Exception(Alert::BadCertificate, "The leaf certificate must be v3"); + throw TLS_Exception(AlertType::BadCertificate, "The leaf certificate must be v3"); } } diff --git a/src/lib/tls/tls12/msg_client_kex.cpp b/src/lib/tls/tls12/msg_client_kex.cpp index f82d65d992a..a99ed7c0661 100644 --- a/src/lib/tls/tls12/msg_client_kex.cpp +++ b/src/lib/tls/tls12/msg_client_kex.cpp @@ -81,7 +81,7 @@ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, DL_Group group(modulus, generator); if(!group.verify_group(rng, false)) { - throw TLS_Exception(Alert::InsufficientSecurity, "DH group validation failed"); + throw TLS_Exception(AlertType::InsufficientSecurity, "DH group validation failed"); } const auto private_key = state.callbacks().tls_generate_ephemeral_key(group, rng); @@ -106,12 +106,12 @@ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, const std::vector peer_public_value = reader.get_range(1, 1, 255); if(!curve_id.is_ecdh_named_curve() && !curve_id.is_x25519()) { - throw TLS_Exception(Alert::HandshakeFailure, + throw TLS_Exception(AlertType::HandshakeFailure, "Server selected a group that is not compatible with the negotiated ciphersuite"); } if(policy.choose_key_exchange_group({curve_id}, {}) != curve_id) { - throw TLS_Exception(Alert::HandshakeFailure, "Server sent ECC curve prohibited by policy"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server sent ECC curve prohibited by policy"); } const auto private_key = state.callbacks().tls_generate_ephemeral_key(curve_id, rng); @@ -122,8 +122,9 @@ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, // With X25519 and X448, a receiving party MUST check whether the // computed premaster secret is the all-zero value and abort the // handshake if so, as described in Section 6 of [RFC7748]. - if(curve_id == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) { - throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange"); + if(curve_id == Group_Params_Code::X25519 && + CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) { + throw TLS_Exception(AlertType::DecryptError, "Bad X25519 key exchange"); } if(kex_algo == Kex_Algo::ECDH) { @@ -136,7 +137,7 @@ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, if(curve_id.is_ecdh_named_curve()) { auto ecdh_key = dynamic_cast(private_key.get()); if(!ecdh_key) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a ECDH_PublicKey"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a ECDH_PublicKey"); } append_tls_length_value(m_key_material, ecdh_key->public_value(state.server_hello()->prefers_compressed_ec_points() @@ -175,7 +176,7 @@ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, append_tls_length_value(m_key_material, encrypted_key, 2); } else { - throw TLS_Exception(Alert::HandshakeFailure, + throw TLS_Exception(AlertType::HandshakeFailure, "Expected a RSA key in server cert but got " + server_public_key->algo_name()); } } @@ -247,7 +248,7 @@ Client_Key_Exchange::Client_Key_Exchange(const std::vector& contents, if(policy.hide_unknown_users()) { psk = SymmetricKey(rng, 16); } else { - throw TLS_Exception(Alert::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value()); + throw TLS_Exception(AlertType::UnknownPSKIdentity, "No PSK for identifier " + m_psk_identity.value()); } } } @@ -264,7 +265,7 @@ Client_Key_Exchange::Client_Key_Exchange(const std::vector& contents, : reader.get_range(1, 1, 255); const auto shared_group = state.server_kex()->shared_group(); - BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params::NONE); + BOTAN_STATE_CHECK(shared_group && shared_group.value() != Group_Params_Code::NONE); try { auto shared_secret = @@ -281,8 +282,9 @@ Client_Key_Exchange::Client_Key_Exchange(const std::vector& contents, // handshake if so, as described in Section 6 of [RFC7748]. BOTAN_ASSERT_NOMSG(state.server_kex()->params().size() >= 3); Group_Params group = static_cast(state.server_kex()->params().at(2)); - if(group == Group_Params::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) { - throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange"); + if(group == Group_Params_Code::X25519 && + CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) { + throw TLS_Exception(AlertType::DecryptError, "Bad X25519 key exchange"); } } @@ -293,7 +295,7 @@ Client_Key_Exchange::Client_Key_Exchange(const std::vector& contents, m_pre_master = shared_secret; } } catch(Invalid_Argument& e) { - throw TLS_Exception(Alert::IllegalParameter, e.what()); + throw TLS_Exception(AlertType::IllegalParameter, e.what()); } catch(TLS_Exception& e) { // NOLINTNEXTLINE(cert-err60-cpp) throw e; diff --git a/src/lib/tls/tls12/msg_server_kex.cpp b/src/lib/tls/tls12/msg_server_kex.cpp index 0dd0aea8ef6..10d446c01e0 100644 --- a/src/lib/tls/tls12/msg_server_kex.cpp +++ b/src/lib/tls/tls12/msg_server_kex.cpp @@ -47,7 +47,7 @@ Server_Key_Exchange::Server_Key_Exchange(Handshake_IO& io, if(kex_algo == Kex_Algo::DH) { const std::vector dh_groups = state.client_hello()->supported_dh_groups(); - m_shared_group = Group_Params::NONE; + m_shared_group = Group_Params_Code::NONE; /* If the client does not send any DH groups that we recognize in @@ -61,8 +61,8 @@ Server_Key_Exchange::Server_Key_Exchange(Handshake_IO& io, m_shared_group = policy.choose_key_exchange_group(dh_groups, {}); } - if(m_shared_group.value() == Group_Params::NONE) { - throw TLS_Exception(Alert::HandshakeFailure, "Could not agree on a DH group with the client"); + if(m_shared_group.value() == Group_Params_Code::NONE) { + throw TLS_Exception(AlertType::HandshakeFailure, "Could not agree on a DH group with the client"); } BOTAN_ASSERT(m_shared_group.value().is_dh_named_group(), "DH ciphersuite is using a finite field group"); @@ -78,7 +78,7 @@ Server_Key_Exchange::Server_Key_Exchange(Handshake_IO& io, m_kex_key = state.callbacks().tls_generate_ephemeral_key(m_shared_group.value(), rng); auto dh = dynamic_cast(m_kex_key.get()); if(!dh) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a Diffie-Hellman key"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a Diffie-Hellman key"); } append_tls_length_value(m_params, BigInt::encode(dh->get_int_field("p")), 2); @@ -93,23 +93,23 @@ Server_Key_Exchange::Server_Key_Exchange(Handshake_IO& io, m_shared_group = policy.choose_key_exchange_group(ec_groups, {}); - if(m_shared_group.value() == Group_Params::NONE) { - throw TLS_Exception(Alert::HandshakeFailure, "No shared ECC group with client"); + if(m_shared_group.value() == Group_Params_Code::NONE) { + throw TLS_Exception(AlertType::HandshakeFailure, "No shared ECC group with client"); } std::vector ecdh_public_val; - if(m_shared_group.value() == Group_Params::X25519) { + if(m_shared_group.value() == Group_Params_Code::X25519) { m_kex_key = state.callbacks().tls_generate_ephemeral_key(m_shared_group.value(), rng); if(!m_kex_key) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a X25519 key"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a X25519 key"); } ecdh_public_val = m_kex_key->public_value(); } else { m_kex_key = state.callbacks().tls_generate_ephemeral_key(m_shared_group.value(), rng); auto ecdh = dynamic_cast(m_kex_key.get()); if(!ecdh) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a EC-Diffie-Hellman key"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a EC-Diffie-Hellman key"); } // follow client's preference for point compression diff --git a/src/lib/tls/tls12/tls_cbc/tls_cbc.cpp b/src/lib/tls/tls12/tls_cbc/tls_cbc.cpp index 36a875129c0..1c58944ec2c 100644 --- a/src/lib/tls/tls12/tls_cbc/tls_cbc.cpp +++ b/src/lib/tls/tls12/tls_cbc/tls_cbc.cpp @@ -91,7 +91,7 @@ bool TLS_CBC_HMAC_AEAD_Mode::has_keying_material() const { return mac().has_keying_material() && cbc().has_keying_material(); } -void TLS_CBC_HMAC_AEAD_Mode::key_schedule(std::span key) { +void TLS_CBC_HMAC_AEAD_Mode::key_schedule(Botan::span key) { // Both keys are of fixed length specified by the ciphersuite if(key.size() != m_cipher_keylen + m_mac_keylen) { @@ -127,7 +127,7 @@ std::vector TLS_CBC_HMAC_AEAD_Mode::assoc_data_with_len(uint16_t len) { return ad; } -void TLS_CBC_HMAC_AEAD_Mode::set_associated_data_n(size_t idx, std::span ad) { +void TLS_CBC_HMAC_AEAD_Mode::set_associated_data_n(size_t idx, Botan::span ad) { BOTAN_ARG_CHECK(idx == 0, "TLS 1.2 CBC/HMAC: cannot handle non-zero index in set_associated_data_n"); if(ad.size() != 13) { throw Invalid_Argument("Invalid TLS AEAD associated data length"); @@ -135,7 +135,7 @@ void TLS_CBC_HMAC_AEAD_Mode::set_associated_data_n(size_t idx, std::span ad) { +void TLS_CBC_HMAC_AEAD_Encryption::set_associated_data_n(size_t idx, Botan::span ad) { TLS_CBC_HMAC_AEAD_Mode::set_associated_data_n(idx, ad); if(use_encrypt_then_mac()) { @@ -360,7 +360,7 @@ void TLS_CBC_HMAC_AEAD_Decryption::finish_msg(secure_vector& buffer, si // This early exit does not leak info because all the values compared are public if(record_len < tag_size() || (record_len - (use_encrypt_then_mac() ? tag_size() : 0)) % block_size() != 0) { - throw TLS_Exception(Alert::BadRecordMac, "Message authentication failure"); + throw TLS_Exception(AlertType::BadRecordMac, "Message authentication failure"); } if(use_encrypt_then_mac()) { @@ -383,7 +383,7 @@ void TLS_CBC_HMAC_AEAD_Decryption::finish_msg(secure_vector& buffer, si const bool mac_ok = constant_time_compare(&record_contents[mac_offset], mac_buf.data(), tag_size()); if(!mac_ok) { - throw TLS_Exception(Alert::BadRecordMac, "Message authentication failure"); + throw TLS_Exception(AlertType::BadRecordMac, "Message authentication failure"); } cbc_decrypt_record(record_contents, enc_size); @@ -393,7 +393,7 @@ void TLS_CBC_HMAC_AEAD_Decryption::finish_msg(secure_vector& buffer, si // No oracle here, whoever sent us this had the key since MAC check passed if(pad_size == 0) { - throw TLS_Exception(Alert::BadRecordMac, "Message authentication failure"); + throw TLS_Exception(AlertType::BadRecordMac, "Message authentication failure"); } const uint8_t* plaintext_block = &record_contents[0]; @@ -460,7 +460,7 @@ void TLS_CBC_HMAC_AEAD_Decryption::finish_msg(secure_vector& buffer, si if(is_datagram_protocol()) { mac().final(mac_buf); } - throw TLS_Exception(Alert::BadRecordMac, "Message authentication failure"); + throw TLS_Exception(AlertType::BadRecordMac, "Message authentication failure"); } } } diff --git a/src/lib/tls/tls12/tls_cbc/tls_cbc.h b/src/lib/tls/tls12/tls_cbc/tls_cbc.h index 371dd261ee8..ae14ae88b2d 100644 --- a/src/lib/tls/tls12/tls_cbc/tls_cbc.h +++ b/src/lib/tls/tls12/tls_cbc/tls_cbc.h @@ -24,7 +24,7 @@ class BOTAN_TEST_API TLS_CBC_HMAC_AEAD_Mode : public AEAD_Mode { public: std::string name() const final; - void set_associated_data_n(size_t idx, std::span ad) override; + void set_associated_data_n(size_t idx, Botan::span ad) override; size_t update_granularity() const final; @@ -84,7 +84,7 @@ class BOTAN_TEST_API TLS_CBC_HMAC_AEAD_Mode : public AEAD_Mode { void start_msg(const uint8_t nonce[], size_t nonce_len) final; size_t process_msg(uint8_t buf[], size_t sz) final; - void key_schedule(std::span key) final; + void key_schedule(Botan::span key) final; const std::string m_cipher_name; const std::string m_mac_name; @@ -125,7 +125,7 @@ class BOTAN_TEST_API TLS_CBC_HMAC_AEAD_Encryption final : public TLS_CBC_HMAC_AE version, use_encrypt_then_mac) {} - void set_associated_data_n(size_t idx, std::span ad) override; + void set_associated_data_n(size_t idx, Botan::span ad) override; size_t output_length(size_t input_length) const override; diff --git a/src/lib/tls/tls12/tls_channel_impl_12.cpp b/src/lib/tls/tls12/tls_channel_impl_12.cpp index 93030abfe91..14221de286a 100644 --- a/src/lib/tls/tls12/tls_channel_impl_12.cpp +++ b/src/lib/tls/tls12/tls_channel_impl_12.cpp @@ -17,6 +17,7 @@ #include #include #include +#include namespace Botan::TLS { @@ -118,7 +119,7 @@ Handshake_State& Channel_Impl_12::create_handshake_state(Protocol_Version versio Protocol_Version active_version = active->version(); if(active_version.is_datagram_protocol() != version.is_datagram_protocol()) { - throw TLS_Exception(Alert::ProtocolVersion, + throw TLS_Exception(AlertType::ProtocolVersion, "Active state using version " + active_version.to_string() + " cannot change to " + version.to_string() + " in pending"); } @@ -197,7 +198,8 @@ void Channel_Impl_12::change_cipher_spec_reader(Connection_Side side) { const uint16_t epoch = sequence_numbers().current_read_epoch(); - BOTAN_ASSERT(!m_read_cipher_states.contains(epoch), "No read cipher state currently set for next epoch"); + BOTAN_ASSERT(!contains(m_read_cipher_states, epoch), + "No read cipher state currently set for next epoch"); // flip side as we are reading std::shared_ptr read_state( @@ -224,7 +226,8 @@ void Channel_Impl_12::change_cipher_spec_writer(Connection_Side side) { const uint16_t epoch = sequence_numbers().current_write_epoch(); - BOTAN_ASSERT(!m_write_cipher_states.contains(epoch), "No write cipher state currently set for next epoch"); + BOTAN_ASSERT(!contains(m_write_cipher_states, epoch), + "No write cipher state currently set for next epoch"); std::shared_ptr write_state( new Connection_Cipher_State(pending->version(), @@ -265,7 +268,7 @@ void Channel_Impl_12::activate_session() { callbacks().tls_session_activated(); } -size_t Channel_Impl_12::from_peer(std::span data) { +size_t Channel_Impl_12::from_peer(Botan::span data) { const bool allow_epoch0_restart = m_is_datagram && m_is_server && policy().allow_dtls_epoch0_restart(); auto input = data.data(); @@ -308,7 +311,7 @@ size_t Channel_Impl_12::from_peer(std::span data) { } if(m_record_buf.size() > MAX_PLAINTEXT_SIZE) { - throw TLS_Exception(Alert::RecordOverflow, "TLS plaintext record is larger than allowed maximum"); + throw TLS_Exception(AlertType::RecordOverflow, "TLS plaintext record is larger than allowed maximum"); } const bool epoch0_restart = m_is_datagram && record.epoch() == 0 && active_state(); @@ -320,30 +323,30 @@ size_t Channel_Impl_12::from_peer(std::span data) { if(initial_record) { // For initial records just check for basic sanity if(record.version().major_version() != 3 && record.version().major_version() != 0xFE) { - throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version in initial record"); + throw TLS_Exception(AlertType::ProtocolVersion, "Received unexpected record version in initial record"); } } else if(auto pending = pending_state()) { if(pending->server_hello() != nullptr && record.version() != pending->version()) { - throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version"); + throw TLS_Exception(AlertType::ProtocolVersion, "Received unexpected record version"); } } else if(auto active = active_state()) { if(record.version() != active->version()) { - throw TLS_Exception(Alert::ProtocolVersion, "Received unexpected record version"); + throw TLS_Exception(AlertType::ProtocolVersion, "Received unexpected record version"); } } } if(record.type() == Record_Type::Handshake || record.type() == Record_Type::ChangeCipherSpec) { if(m_has_been_closed) { - throw TLS_Exception(Alert::UnexpectedMessage, "Received handshake data after connection closure"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Received handshake data after connection closure"); } process_handshake_ccs(m_record_buf, record.sequence(), record.type(), record.version(), epoch0_restart); } else if(record.type() == Record_Type::ApplicationData) { if(m_has_been_closed) { - throw TLS_Exception(Alert::UnexpectedMessage, "Received application data after connection closure"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Received application data after connection closure"); } if(pending_state() != nullptr) { - throw TLS_Exception(Alert::UnexpectedMessage, "Can't interleave application and handshake data"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Can't interleave application and handshake data"); } process_application_data(record.sequence(), m_record_buf); } else if(record.type() == Record_Type::Alert) { @@ -359,13 +362,13 @@ size_t Channel_Impl_12::from_peer(std::span data) { send_fatal_alert(e.type()); throw; } catch(Invalid_Authentication_Tag&) { - send_fatal_alert(Alert::BadRecordMac); + send_fatal_alert(AlertType::BadRecordMac); throw; } catch(Decoding_Error&) { - send_fatal_alert(Alert::DecodeError); + send_fatal_alert(AlertType::DecodeError); throw; } catch(...) { - send_fatal_alert(Alert::InternalError); + send_fatal_alert(AlertType::InternalError); throw; } } @@ -432,7 +435,7 @@ void Channel_Impl_12::process_application_data(uint64_t seq_no, const secure_vec void Channel_Impl_12::process_alert(const secure_vector& record) { Alert alert_msg(record); - if(alert_msg.type() == Alert::NoRenegotiation) { + if(alert_msg.type() == AlertType::NoRenegotiation) { m_pending_state.reset(); } @@ -447,14 +450,14 @@ void Channel_Impl_12::process_alert(const secure_vector& record) { } } - if(alert_msg.type() == Alert::CloseNotify) { + if(alert_msg.type() == AlertType::CloseNotify) { // TLS 1.2 requires us to immediately react with our "close_notify", // the return value of the application's callback has no effect on that. callbacks().tls_peer_closed_connection(); - send_warning_alert(Alert::CloseNotify); // reply in kind + send_warning_alert(AlertType::CloseNotify); // reply in kind } - if(alert_msg.type() == Alert::CloseNotify || alert_msg.is_fatal()) { + if(alert_msg.type() == AlertType::CloseNotify || alert_msg.is_fatal()) { m_has_been_closed = true; } } @@ -506,7 +509,7 @@ void Channel_Impl_12::send_record_under_epoch(uint16_t epoch, send_record_array(epoch, record_type, record.data(), record.size()); } -void Channel_Impl_12::to_peer(std::span data) { +void Channel_Impl_12::to_peer(Botan::span data) { if(!is_active()) { throw Invalid_State("Data cannot be sent on inactive TLS connection"); } @@ -523,7 +526,7 @@ void Channel_Impl_12::send_alert(const Alert& alert) { } } - if(alert.type() == Alert::NoRenegotiation) { + if(alert.type() == AlertType::NoRenegotiation) { m_pending_state.reset(); } @@ -537,7 +540,7 @@ void Channel_Impl_12::send_alert(const Alert& alert) { reset_state(); } - if(alert.type() == Alert::CloseNotify || alert.is_fatal()) { + if(alert.type() == AlertType::CloseNotify || alert.is_fatal()) { m_has_been_closed = true; } } @@ -549,7 +552,7 @@ void Channel_Impl_12::secure_renegotiation_check(const Client_Hello_12* client_h const bool active_sr = active->client_hello()->secure_renegotiation(); if(active_sr != secure_renegotiation) { - throw TLS_Exception(Alert::HandshakeFailure, "Client changed its mind about secure renegotiation"); + throw TLS_Exception(AlertType::HandshakeFailure, "Client changed its mind about secure renegotiation"); } } @@ -557,7 +560,7 @@ void Channel_Impl_12::secure_renegotiation_check(const Client_Hello_12* client_h const std::vector& data = client_hello->renegotiation_info(); if(data != secure_renegotiation_data_for_client_hello()) { - throw TLS_Exception(Alert::HandshakeFailure, "Client sent bad values for secure renegotiation"); + throw TLS_Exception(AlertType::HandshakeFailure, "Client sent bad values for secure renegotiation"); } } } @@ -569,7 +572,7 @@ void Channel_Impl_12::secure_renegotiation_check(const Server_Hello_12* server_h const bool active_sr = active->server_hello()->secure_renegotiation(); if(active_sr != secure_renegotiation) { - throw TLS_Exception(Alert::HandshakeFailure, "Server changed its mind about secure renegotiation"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server changed its mind about secure renegotiation"); } } @@ -577,7 +580,7 @@ void Channel_Impl_12::secure_renegotiation_check(const Server_Hello_12* server_h const std::vector& data = server_hello->renegotiation_info(); if(data != secure_renegotiation_data_for_server_hello()) { - throw TLS_Exception(Alert::HandshakeFailure, "Server sent bad values for secure renegotiation"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server sent bad values for secure renegotiation"); } } } diff --git a/src/lib/tls/tls12/tls_channel_impl_12.h b/src/lib/tls/tls12/tls_channel_impl_12.h index 5b9f9ee6e8e..b86fed280e4 100644 --- a/src/lib/tls/tls12/tls_channel_impl_12.h +++ b/src/lib/tls/tls12/tls_channel_impl_12.h @@ -73,8 +73,8 @@ class Channel_Impl_12 : public Channel_Impl { ~Channel_Impl_12() override; - size_t from_peer(std::span data) override; - void to_peer(std::span data) override; + size_t from_peer(Botan::span data) override; + void to_peer(Botan::span data) override; /** * Send a TLS alert message. If the alert is fatal, the internal diff --git a/src/lib/tls/tls12/tls_client_impl_12.cpp b/src/lib/tls/tls12/tls_client_impl_12.cpp index 48867fc0932..3bc48a47161 100644 --- a/src/lib/tls/tls12/tls_client_impl_12.cpp +++ b/src/lib/tls/tls12/tls_client_impl_12.cpp @@ -94,7 +94,7 @@ Client_Impl_12::Client_Impl_12(const std::shared_ptr& callbacks, m_creds(creds), m_info(std::move(info)) { BOTAN_ASSERT_NONNULL(m_creds); - const auto version = datagram ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12; + const auto version = datagram ? Version_Code::DTLS_V12 : Version_Code::TLS_V12; Handshake_State& state = create_handshake_state(version); send_client_hello(state, false, version, std::nullopt /* no a-priori session to resume */, next_protocols); } @@ -109,7 +109,7 @@ Client_Impl_12::Client_Impl_12(const Channel_Impl::Downgrade_Information& downgr downgrade_info.io_buffer_size), m_creds(downgrade_info.creds), m_info(downgrade_info.server_info) { - Handshake_State& state = create_handshake_state(Protocol_Version::TLS_V12); + Handshake_State& state = create_handshake_state(Version_Code::TLS_V12); if(!downgrade_info.client_hello_message.empty()) { // Downgrade detected after receiving a TLS 1.2 server hello. We need to @@ -158,7 +158,7 @@ std::vector Client_Impl_12::get_peer_cert_chain(const Handshak */ void Client_Impl_12::initiate_handshake(Handshake_State& state, bool force_full_renegotiation) { // we don't support TLS < 1.2 anymore and TLS 1.3 should not use this client impl - const auto version = state.version().is_datagram_protocol() ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12; + const auto version = state.version().is_datagram_protocol() ? Version_Code::DTLS_V12 : Version_Code::TLS_V12; send_client_hello(state, force_full_renegotiation, version); } @@ -257,7 +257,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, Hello_Request hello_request(contents); if(state.client_hello()) { - throw TLS_Exception(Alert::HandshakeFailure, "Cannot renegotiate during a handshake"); + throw TLS_Exception(AlertType::HandshakeFailure, "Cannot renegotiate during a handshake"); } if(policy().allow_server_initiated_renegotiation()) { @@ -265,14 +265,14 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, state.mark_as_renegotiation(); initiate_handshake(state, true /* force_full_renegotiation */); } else { - throw TLS_Exception(Alert::HandshakeFailure, "Client policy prohibits insecure renegotiation"); + throw TLS_Exception(AlertType::HandshakeFailure, "Client policy prohibits insecure renegotiation"); } } else { if(policy().abort_connection_on_undesired_renegotiation()) { - throw TLS_Exception(Alert::NoRenegotiation, "Client policy prohibits renegotiation"); + throw TLS_Exception(AlertType::NoRenegotiation, "Client policy prohibits renegotiation"); } else { // RFC 5746 section 4.2 - send_warning_alert(Alert::NoRenegotiation); + send_warning_alert(AlertType::NoRenegotiation); } } @@ -296,16 +296,16 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, state.server_hello(new Server_Hello_12(contents)); if(!state.server_hello()->legacy_version().valid()) { - throw TLS_Exception(Alert::ProtocolVersion, "Server replied with an invalid version"); + throw TLS_Exception(AlertType::ProtocolVersion, "Server replied with an invalid version"); } if(!state.client_hello()->offered_suite(state.server_hello()->ciphersuite())) { - throw TLS_Exception(Alert::HandshakeFailure, "Server replied with ciphersuite we didn't send"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server replied with ciphersuite we didn't send"); } const auto suite = Ciphersuite::by_id(state.server_hello()->ciphersuite()); if(!suite || !suite->usable_in_version(state.server_hello()->legacy_version())) { - throw TLS_Exception(Alert::HandshakeFailure, + throw TLS_Exception(AlertType::HandshakeFailure, "Server replied using a ciphersuite not allowed in version it offered"); } @@ -315,16 +315,16 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, // Data (AEAD) ciphersuite, it MUST NOT send an encrypt-then-MAC // response extension back to the client. if(suite->aead_ciphersuite() && state.server_hello()->supports_encrypt_then_mac()) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "Server replied using an AEAD ciphersuite and an encrypt-then-MAC response extension"); } if(Ciphersuite::is_scsv(state.server_hello()->ciphersuite())) { - throw TLS_Exception(Alert::HandshakeFailure, "Server replied with a signaling ciphersuite"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server replied with a signaling ciphersuite"); } if(state.server_hello()->compression_method() != 0) { - throw TLS_Exception(Alert::IllegalParameter, "Server replied with non-null compression method"); + throw TLS_Exception(AlertType::IllegalParameter, "Server replied with non-null compression method"); } if(state.client_hello()->legacy_version() > state.server_hello()->legacy_version()) { @@ -338,8 +338,8 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, // // TLS 1.3 servers will still set the magic string to DOWNGRADE_TLS12. Don't abort in this case. if(auto requested = state.server_hello()->random_signals_downgrade(); - requested.has_value() && requested.value() <= Protocol_Version::TLS_V11) { - throw TLS_Exception(Alert::IllegalParameter, "Downgrade attack detected"); + requested.has_value() && requested.value() <= Version_Code::TLS_V11) { + throw TLS_Exception(AlertType::IllegalParameter, "Downgrade attack detected"); } } @@ -359,12 +359,12 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, for(auto&& d : diff) { msg << " " << static_cast(d); } - throw TLS_Exception(Alert::UnsupportedExtension, msg.str()); + throw TLS_Exception(AlertType::UnsupportedExtension, msg.str()); } if(uint16_t srtp = state.server_hello()->srtp_profile()) { if(!value_exists(state.client_hello()->srtp_profiles(), srtp)) { - throw TLS_Exception(Alert::HandshakeFailure, "Server replied with DTLS-SRTP alg we did not send"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server replied with DTLS-SRTP alg we did not send"); } } @@ -389,17 +389,17 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, * session, and the server must resume with the same version. */ if(state.server_hello()->legacy_version() != state.client_hello()->legacy_version()) { - throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session but with wrong version"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server resumed session but with wrong version"); } if(state.server_hello()->supports_extended_master_secret() && !state.resumed_session_supports_extended_master_secret()) { - throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session but added extended master secret"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server resumed session but added extended master secret"); } if(!state.server_hello()->supports_extended_master_secret() && state.resumed_session_supports_extended_master_secret()) { - throw TLS_Exception(Alert::HandshakeFailure, "Server resumed session and removed extended master secret"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server resumed session and removed extended master secret"); } state.compute_session_keys(state.resume_master_secret()); @@ -418,12 +418,12 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, // in a resumption scenario. if(active_state->version() != state.server_hello()->legacy_version()) { - throw TLS_Exception(Alert::ProtocolVersion, "Server changed version after renegotiation"); + throw TLS_Exception(AlertType::ProtocolVersion, "Server changed version after renegotiation"); } if(state.server_hello()->supports_extended_master_secret() != active_state->server_hello()->supports_extended_master_secret()) { - throw TLS_Exception(Alert::HandshakeFailure, "Server changed its mind about extended master secret"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server changed its mind about extended master secret"); } } @@ -431,19 +431,19 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, if(state.client_hello()->legacy_version().is_datagram_protocol() != state.server_hello()->legacy_version().is_datagram_protocol()) { - throw TLS_Exception(Alert::ProtocolVersion, "Server replied with different protocol type than we offered"); + throw TLS_Exception(AlertType::ProtocolVersion, "Server replied with different protocol type than we offered"); } if(state.version() > state.client_hello()->legacy_version()) { - throw TLS_Exception(Alert::HandshakeFailure, "Server replied with later version than client offered"); + throw TLS_Exception(AlertType::HandshakeFailure, "Server replied with later version than client offered"); } if(state.version().major_version() == 3 && state.version().minor_version() == 0) { - throw TLS_Exception(Alert::ProtocolVersion, "Server attempting to negotiate SSLv3 which is not supported"); + throw TLS_Exception(AlertType::ProtocolVersion, "Server attempting to negotiate SSLv3 which is not supported"); } if(!policy().acceptable_protocol_version(state.version())) { - throw TLS_Exception(Alert::ProtocolVersion, + throw TLS_Exception(AlertType::ProtocolVersion, "Server version " + state.version().to_string() + " is unacceptable by policy"); } @@ -473,7 +473,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, const std::vector& server_certs = state.server_certs()->cert_chain(); if(server_certs.empty()) { - throw TLS_Exception(Alert::HandshakeFailure, "Client: No certificates sent by server"); + throw TLS_Exception(AlertType::HandshakeFailure, "Client: No certificates sent by server"); } /* @@ -488,7 +488,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, X509_Certificate current_cert = active_state->server_certs()->cert_chain().at(0); if(current_cert != server_cert) { - throw TLS_Exception(Alert::BadCertificate, "Server certificate changed during renegotiation"); + throw TLS_Exception(AlertType::BadCertificate, "Server certificate changed during renegotiation"); } } @@ -498,11 +498,11 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, state.ciphersuite().signature_used() ? state.ciphersuite().sig_algo() : "RSA"; if(peer_key->algo_name() != expected_key_type) { - throw TLS_Exception(Alert::IllegalParameter, "Certificate key type did not match ciphersuite"); + throw TLS_Exception(AlertType::IllegalParameter, "Certificate key type did not match ciphersuite"); } if(!key_usage_matches_ciphersuite(server_cert.constraints(), state.ciphersuite())) { - throw TLS_Exception(Alert::BadCertificate, "Certificate usage constraints do not allow this ciphersuite"); + throw TLS_Exception(AlertType::BadCertificate, "Certificate usage constraints do not allow this ciphersuite"); } state.record_server_public_key(std::move(peer_key)); @@ -525,7 +525,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, } catch(TLS_Exception&) { throw; } catch(std::exception& e) { - throw TLS_Exception(Alert::InternalError, e.what()); + throw TLS_Exception(AlertType::InternalError, e.what()); } } } else if(type == Handshake_Type::CertificateStatus) { @@ -550,7 +550,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, const Public_Key& server_key = state.server_public_key(); if(!state.server_kex()->verify(server_key, state, policy())) { - throw TLS_Exception(Alert::DecryptError, "Bad signature on server key exchange"); + throw TLS_Exception(AlertType::DecryptError, "Bad signature on server key exchange"); } } } else if(type == Handshake_Type::CertificateRequest) { @@ -560,7 +560,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, state.server_hello_done(new Server_Hello_Done(contents)); if(state.handshake_io().have_more_data()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after ServerHelloDone"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Have data remaining in buffer after ServerHelloDone"); } if(state.server_certs() != nullptr && state.server_hello()->supports_certificate_status_message()) { @@ -581,7 +581,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, } catch(TLS_Exception&) { throw; } catch(std::exception& e) { - throw TLS_Exception(Alert::InternalError, e.what()); + throw TLS_Exception(AlertType::InternalError, e.what()); } } @@ -604,7 +604,7 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, m_creds->private_key_for(state.client_certs()->cert_chain()[0], "tls-client", m_info.hostname()); if(!private_key) { - throw TLS_Exception(Alert::InternalError, "Failed to get private key for signing"); + throw TLS_Exception(AlertType::InternalError, "Failed to get private key for signing"); } state.client_verify( @@ -632,13 +632,13 @@ void Client_Impl_12::process_handshake_msg(const Handshake_State* active_state, change_cipher_spec_reader(Connection_Side::Client); } else if(type == Handshake_Type::Finished) { if(state.handshake_io().have_more_data()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after Finished"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Have data remaining in buffer after Finished"); } state.server_finished(new Finished_12(contents)); if(!state.server_finished()->verify(state, Connection_Side::Server)) { - throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify"); + throw TLS_Exception(AlertType::DecryptError, "Finished message didn't verify"); } state.hash().update(state.handshake_io().format(contents, type)); diff --git a/src/lib/tls/tls12/tls_handshake_io.cpp b/src/lib/tls/tls12/tls_handshake_io.cpp index c6be0a0a205..a42e51b021c 100644 --- a/src/lib/tls/tls12/tls_handshake_io.cpp +++ b/src/lib/tls/tls12/tls_handshake_io.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include namespace Botan::TLS { @@ -36,7 +37,7 @@ uint64_t steady_clock_ms() { } // namespace Protocol_Version Stream_Handshake_IO::initial_record_version() const { - return Protocol_Version::TLS_V12; + return Version_Code::TLS_V12; } void Stream_Handshake_IO::add_record(const uint8_t record[], @@ -115,7 +116,7 @@ std::vector Stream_Handshake_IO::send(const Handshake_Message& msg) { } Protocol_Version Datagram_Handshake_IO::initial_record_version() const { - return Protocol_Version::DTLS_V12; + return Version_Code::DTLS_V12; } void Datagram_Handshake_IO::retransmit_last_flight() { @@ -226,7 +227,7 @@ std::pair> Datagram_Handshake_IO::get_next_ if(!m_messages.empty()) { const uint16_t current_epoch = m_messages.begin()->second.epoch(); - if(m_ccs_epochs.contains(current_epoch)) { + if(contains(m_ccs_epochs, current_epoch)) { return std::make_pair(Handshake_Type::HandshakeCCS, std::vector()); } } diff --git a/src/lib/tls/tls12/tls_handshake_state.cpp b/src/lib/tls/tls12/tls_handshake_state.cpp index 493964ff45f..b73f5d62d3f 100644 --- a/src/lib/tls/tls12/tls_handshake_state.cpp +++ b/src/lib/tls/tls12/tls_handshake_state.cpp @@ -83,7 +83,7 @@ const char* handshake_type_to_string(Handshake_Type type) { return "invalid"; } - throw TLS_Exception(Alert::UnexpectedMessage, + throw TLS_Exception(AlertType::UnexpectedMessage, "Unknown TLS handshake message type " + std::to_string(static_cast(type))); } @@ -271,7 +271,7 @@ std::pair Handshake_State::choose_sig_format(cons const std::string hash = chosen_scheme.hash_function_name(); if(!policy.allowed_signature_hash(hash)) { - throw TLS_Exception(Alert::HandshakeFailure, "Policy refuses to accept signing with any hash supported by peer"); + throw TLS_Exception(AlertType::HandshakeFailure, "Policy refuses to accept signing with any hash supported by peer"); } if(!chosen_scheme.format().has_value()) { @@ -306,11 +306,11 @@ std::pair Handshake_State::parse_sig_format( const std::string key_type = key.algo_name(); if(!policy.allowed_signature_method(key_type)) { - throw TLS_Exception(Alert::HandshakeFailure, "Rejecting " + key_type + " signature"); + throw TLS_Exception(AlertType::HandshakeFailure, "Rejecting " + key_type + " signature"); } if(!scheme.is_available()) { - throw TLS_Exception(Alert::HandshakeFailure, "Peer sent unknown signature scheme"); + throw TLS_Exception(AlertType::HandshakeFailure, "Peer sent unknown signature scheme"); } if(key_type != scheme.algorithm_name()) { @@ -318,7 +318,7 @@ std::pair Handshake_State::parse_sig_format( } if(for_client_auth && !cert_req()) { - throw TLS_Exception(Alert::HandshakeFailure, "No certificate verify set"); + throw TLS_Exception(AlertType::HandshakeFailure, "No certificate verify set"); } /* @@ -331,12 +331,12 @@ std::pair Handshake_State::parse_sig_format( const std::string hash_algo = scheme.hash_function_name(); - if(!scheme.is_compatible_with(Protocol_Version::TLS_V12)) { - throw TLS_Exception(Alert::IllegalParameter, "Peer sent unexceptable signature scheme"); + if(!scheme.is_compatible_with(Version_Code::TLS_V12)) { + throw TLS_Exception(AlertType::IllegalParameter, "Peer sent unexceptable signature scheme"); } if(!supported_algos_include(supported_algos, key_type, hash_algo)) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "TLS signature extension did not allow for " + key_type + "/" + hash_algo + " signature"); } diff --git a/src/lib/tls/tls12/tls_record.cpp b/src/lib/tls/tls12/tls_record.cpp index e871c67055e..c2ac45f55e1 100644 --- a/src/lib/tls/tls12/tls_record.cpp +++ b/src/lib/tls/tls12/tls_record.cpp @@ -276,7 +276,7 @@ void decrypt_record(secure_vector& output, * including older versions of TLS-Attacker. */ if(msg_length < aead.minimum_final_size()) { - throw TLS_Exception(Alert::BadRecordMac, "AEAD packet is shorter than the tag"); + throw TLS_Exception(AlertType::BadRecordMac, "AEAD packet is shorter than the tag"); } const size_t ptext_size = aead.output_length(msg_length); @@ -326,11 +326,11 @@ Record_Header read_tls_record(secure_vector& readbuf, const std::string first5 = std::string(reinterpret_cast(readbuf.data()), 5); if(first5 == "GET /" || first5 == "PUT /" || first5 == "POST " || first5 == "HEAD ") { - throw TLS_Exception(Alert::ProtocolVersion, "Client sent plaintext HTTP request instead of TLS handshake"); + throw TLS_Exception(AlertType::ProtocolVersion, "Client sent plaintext HTTP request instead of TLS handshake"); } if(first5 == "CONNE") { - throw TLS_Exception(Alert::ProtocolVersion, + throw TLS_Exception(AlertType::ProtocolVersion, "Client sent plaintext HTTP proxy CONNECT request instead of TLS handshake"); } @@ -338,25 +338,25 @@ Record_Header read_tls_record(secure_vector& readbuf, // RFC 5246 Section 6. // If a TLS implementation receives an unexpected record type, it MUST // send an unexpected_message alert. - throw TLS_Exception(Alert::UnexpectedMessage, "TLS record type had unexpected value"); + throw TLS_Exception(AlertType::UnexpectedMessage, "TLS record type had unexpected value"); } - throw TLS_Exception(Alert::ProtocolVersion, "TLS record version had unexpected value"); + throw TLS_Exception(AlertType::ProtocolVersion, "TLS record version had unexpected value"); } const Protocol_Version version(readbuf[1], readbuf[2]); if(version.is_datagram_protocol()) { - throw TLS_Exception(Alert::ProtocolVersion, "Expected TLS but got a record with DTLS version"); + throw TLS_Exception(AlertType::ProtocolVersion, "Expected TLS but got a record with DTLS version"); } const size_t record_size = make_uint16(readbuf[TLS_HEADER_SIZE - 2], readbuf[TLS_HEADER_SIZE - 1]); if(record_size > MAX_CIPHERTEXT_SIZE) { - throw TLS_Exception(Alert::RecordOverflow, "Received a record that exceeds maximum size"); + throw TLS_Exception(AlertType::RecordOverflow, "Received a record that exceeds maximum size"); } if(record_size == 0) { - throw TLS_Exception(Alert::DecodeError, "Received a completely empty record"); + throw TLS_Exception(AlertType::DecodeError, "Received a completely empty record"); } if(size_t needed = fill_buffer_to(readbuf, input, input_len, consumed, TLS_HEADER_SIZE + record_size)) { diff --git a/src/lib/tls/tls12/tls_server_impl_12.cpp b/src/lib/tls/tls12/tls_server_impl_12.cpp index 20d27fe9963..cffa25e8791 100644 --- a/src/lib/tls/tls12/tls_server_impl_12.cpp +++ b/src/lib/tls/tls12/tls_server_impl_12.cpp @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -91,7 +92,8 @@ std::optional check_for_resume(const Session_Handle& handle_to_resume, Client previously negotiated session with extended master secret, but has now attempted to resume without the extension: abort */ - throw TLS_Exception(Alert::HandshakeFailure, "Client resumed extended ms session without sending extension"); + throw TLS_Exception(AlertType::HandshakeFailure, + "Client resumed extended ms session without sending extension"); } } @@ -101,7 +103,8 @@ std::optional check_for_resume(const Session_Handle& handle_to_resume, Client previously negotiated session with Encrypt-then-MAC, but has now attempted to resume without the extension: abort */ - throw TLS_Exception(Alert::HandshakeFailure, "Client resumed Encrypt-then-MAC session without sending extension"); + throw TLS_Exception(AlertType::HandshakeFailure, + "Client resumed Encrypt-then-MAC session without sending extension"); } return session; @@ -119,16 +122,16 @@ uint16_t choose_ciphersuite(const Policy& policy, const std::vector server_suites = policy.ciphersuite_list(version); if(server_suites.empty()) { - throw TLS_Exception(Alert::HandshakeFailure, "Policy forbids us from negotiating any ciphersuite"); + throw TLS_Exception(AlertType::HandshakeFailure, "Policy forbids us from negotiating any ciphersuite"); } const bool have_shared_ecc_curve = - (policy.choose_key_exchange_group(client_hello.supported_ecc_curves(), {}) != Group_Params::NONE); + (policy.choose_key_exchange_group(client_hello.supported_ecc_curves(), {}) != Group_Params_Code::NONE); const bool client_supports_ffdhe_groups = !client_hello.supported_dh_groups().empty(); const bool have_shared_dh_group = - (policy.choose_key_exchange_group(client_hello.supported_dh_groups(), {}) != Group_Params::NONE); + (policy.choose_key_exchange_group(client_hello.supported_dh_groups(), {}) != Group_Params_Code::NONE); /* Walk down one list in preference order @@ -164,7 +167,7 @@ uint16_t choose_ciphersuite(const Policy& policy, const std::string sig_algo = suite->sig_algo(); // Do we have any certificates for this sig? - if(!cert_chains.contains(sig_algo)) { + if(!contains(cert_chains, sig_algo)) { continue; } @@ -191,7 +194,7 @@ uint16_t choose_ciphersuite(const Policy& policy, } if(we_support_some_hash_by_client == false) { - throw TLS_Exception(Alert::HandshakeFailure, + throw TLS_Exception(AlertType::HandshakeFailure, "Policy does not accept any hash function supported by client"); } } @@ -206,10 +209,11 @@ uint16_t choose_ciphersuite(const Policy& policy, // suites are acceptable to the server, the server MUST end the // connection with a fatal TLS alert of type insufficient_security(71). if(client_supports_ffdhe_groups && !have_shared_dh_group) { - throw TLS_Exception(Alert::InsufficientSecurity, "Can't agree on a sufficiently strong ciphersuite with client"); + throw TLS_Exception(AlertType::InsufficientSecurity, + "Can't agree on a sufficiently strong ciphersuite with client"); } - throw TLS_Exception(Alert::HandshakeFailure, "Can't agree on a ciphersuite with client"); + throw TLS_Exception(AlertType::HandshakeFailure, "Can't agree on a ciphersuite with client"); } std::map> get_server_certs( @@ -291,15 +295,15 @@ Protocol_Version select_version(const TLS::Policy& policy, if(!supported_versions.empty()) { if(is_datagram) { - if(policy.allow_dtls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::DTLS_V12))) { - return Protocol_Version::DTLS_V12; + if(policy.allow_dtls12() && value_exists(supported_versions, Protocol_Version(Version_Code::DTLS_V12))) { + return Version_Code::DTLS_V12; } - throw TLS_Exception(Alert::ProtocolVersion, "No shared DTLS version"); + throw TLS_Exception(AlertType::ProtocolVersion, "No shared DTLS version"); } else { - if(policy.allow_tls12() && value_exists(supported_versions, Protocol_Version(Protocol_Version::TLS_V12))) { - return Protocol_Version::TLS_V12; + if(policy.allow_tls12() && value_exists(supported_versions, Protocol_Version(Version_Code::TLS_V12))) { + return Version_Code::TLS_V12; } - throw TLS_Exception(Alert::ProtocolVersion, "No shared TLS version"); + throw TLS_Exception(AlertType::ProtocolVersion, "No shared TLS version"); } } @@ -313,7 +317,7 @@ Protocol_Version select_version(const TLS::Policy& policy, */ if(active_version > client_offer) { throw TLS_Exception( - Alert::ProtocolVersion, + AlertType::ProtocolVersion, "Client negotiated " + active_version.to_string() + " then renegotiated with " + client_offer.to_string()); } else { return active_version; @@ -321,16 +325,16 @@ Protocol_Version select_version(const TLS::Policy& policy, } if(is_datagram) { - if(policy.allow_dtls12() && client_offer >= Protocol_Version::DTLS_V12) { - return Protocol_Version::DTLS_V12; + if(policy.allow_dtls12() && client_offer >= Version_Code::DTLS_V12) { + return Version_Code::DTLS_V12; } } else { - if(policy.allow_tls12() && client_offer >= Protocol_Version::TLS_V12) { - return Protocol_Version::TLS_V12; + if(policy.allow_tls12() && client_offer >= Version_Code::TLS_V12) { + return Version_Code::TLS_V12; } } - throw TLS_Exception(Alert::ProtocolVersion, + throw TLS_Exception(AlertType::ProtocolVersion, "Client version " + client_offer.to_string() + " is unacceptable by policy"); } } // namespace @@ -348,20 +352,20 @@ void Server_Impl_12::process_client_hello_msg(const Handshake_State* active_stat if(initial_handshake == false && policy().allow_client_initiated_renegotiation() == false) { if(policy().abort_connection_on_undesired_renegotiation()) { - throw TLS_Exception(Alert::NoRenegotiation, "Server policy prohibits renegotiation"); + throw TLS_Exception(AlertType::NoRenegotiation, "Server policy prohibits renegotiation"); } else { - send_warning_alert(Alert::NoRenegotiation); + send_warning_alert(AlertType::NoRenegotiation); } return; } if(!policy().allow_insecure_renegotiation() && !(initial_handshake || secure_renegotiation_supported())) { - send_warning_alert(Alert::NoRenegotiation); + send_warning_alert(AlertType::NoRenegotiation); return; } if(pending_state.handshake_io().have_more_data()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after ClientHello"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Have data remaining in buffer after ClientHello"); } pending_state.client_hello(new Client_Hello_12(contents)); @@ -370,14 +374,14 @@ void Server_Impl_12::process_client_hello_msg(const Handshake_State* active_stat if(datagram) { if(client_offer.major_version() == 0xFF) { - throw TLS_Exception(Alert::ProtocolVersion, "Client offered DTLS version with major version 0xFF"); + throw TLS_Exception(AlertType::ProtocolVersion, "Client offered DTLS version with major version 0xFF"); } } else { if(client_offer.major_version() < 3) { - throw TLS_Exception(Alert::ProtocolVersion, "Client offered TLS version with major version under 3"); + throw TLS_Exception(AlertType::ProtocolVersion, "Client offered TLS version with major version under 3"); } if(client_offer.major_version() == 3 && client_offer.minor_version() == 0) { - throw TLS_Exception(Alert::ProtocolVersion, "Client offered SSLv3 which is not supported"); + throw TLS_Exception(AlertType::ProtocolVersion, "Client offered SSLv3 which is not supported"); } } @@ -401,7 +405,7 @@ void Server_Impl_12::process_client_hello_msg(const Handshake_State* active_stat const auto compression_methods = pending_state.client_hello()->compression_methods(); if(!value_exists(compression_methods, uint8_t(0))) { - throw TLS_Exception(Alert::IllegalParameter, "Client did not offer NULL compression"); + throw TLS_Exception(AlertType::IllegalParameter, "Client did not offer NULL compression"); } if(initial_handshake && datagram) { @@ -427,7 +431,8 @@ void Server_Impl_12::process_client_hello_msg(const Handshake_State* active_stat return; } } else if(epoch0_restart) { - throw TLS_Exception(Alert::HandshakeFailure, "Reuse of DTLS association requires DTLS cookie secret be set"); + throw TLS_Exception(AlertType::HandshakeFailure, + "Reuse of DTLS association requires DTLS cookie secret be set"); } } @@ -468,7 +473,7 @@ void Server_Impl_12::process_certificate_msg(Server_Handshake_State& pending_sta // CERTIFICATE_REQUIRED would make more sense but BoGo expects handshake failure alert if(pending_state.client_certs()->empty() && policy().require_client_certificate_authentication()) { - throw TLS_Exception(Alert::HandshakeFailure, "Policy requires client send a certificate, but it did not"); + throw TLS_Exception(AlertType::HandshakeFailure, "Policy requires client send a certificate, but it did not"); } pending_state.set_expected_next(Handshake_Type::ClientKeyExchange); @@ -501,11 +506,11 @@ void Server_Impl_12::process_certificate_verify_msg(Server_Handshake_State& pend const std::vector& client_certs = pending_state.client_certs()->cert_chain(); if(client_certs.empty()) { - throw TLS_Exception(Alert::DecodeError, "No client certificate sent"); + throw TLS_Exception(AlertType::DecodeError, "No client certificate sent"); } if(!client_certs[0].allowed_usage(Key_Constraints::DigitalSignature)) { - throw TLS_Exception(Alert::BadCertificate, "Client certificate does not support signing"); + throw TLS_Exception(AlertType::BadCertificate, "Client certificate does not support signing"); } const bool sig_valid = pending_state.client_verify()->verify(client_certs[0], pending_state, policy()); @@ -518,7 +523,7 @@ void Server_Impl_12::process_certificate_verify_msg(Server_Handshake_State& pend * unable to correctly verify a signature, ..." */ if(!sig_valid) { - throw TLS_Exception(Alert::DecryptError, "Client cert verify failed"); + throw TLS_Exception(AlertType::DecryptError, "Client cert verify failed"); } try { @@ -532,7 +537,7 @@ void Server_Impl_12::process_certificate_verify_msg(Server_Handshake_State& pend sni_hostname, policy()); } catch(std::exception& e) { - throw TLS_Exception(Alert::BadCertificate, e.what()); + throw TLS_Exception(AlertType::BadCertificate, e.what()); } pending_state.set_expected_next(Handshake_Type::HandshakeCCS); @@ -544,13 +549,13 @@ void Server_Impl_12::process_finished_msg(Server_Handshake_State& pending_state, pending_state.set_expected_next(Handshake_Type::None); if(pending_state.handshake_io().have_more_data()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Have data remaining in buffer after Finished"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Have data remaining in buffer after Finished"); } pending_state.client_finished(new Finished_12(contents)); if(!pending_state.client_finished()->verify(pending_state, Connection_Side::Client)) { - throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify"); + throw TLS_Exception(AlertType::DecryptError, "Finished message didn't verify"); } if(!pending_state.server_finished()) { @@ -743,7 +748,7 @@ void Server_Impl_12::session_create(Server_Handshake_State& pending_state) { * anonymous/PSK operation. */ if(!cert_chains.empty()) { - send_warning_alert(Alert::UnrecognizedName); + send_warning_alert(AlertType::UnrecognizedName); } } diff --git a/src/lib/tls/tls13/msg_certificate_13.cpp b/src/lib/tls/tls13/msg_certificate_13.cpp index 5ab6bc24696..074fb4420e1 100644 --- a/src/lib/tls/tls13/msg_certificate_13.cpp +++ b/src/lib/tls/tls13/msg_certificate_13.cpp @@ -38,13 +38,13 @@ bool certificate_allows_signing(const X509_Certificate& cert) { std::vector filter_signature_schemes(const std::vector& peer_scheme_preference) { std::vector compatible_schemes; for(const auto& scheme : peer_scheme_preference) { - if(scheme.is_available() && scheme.is_compatible_with(Protocol_Version::TLS_V13)) { + if(scheme.is_available() && scheme.is_compatible_with(Version_Code::TLS_V13)) { compatible_schemes.push_back(scheme.algorithm_name()); } } if(compatible_schemes.empty()) { - throw TLS_Exception(Alert::HandshakeFailure, "Failed to agree on any signature algorithm"); + throw TLS_Exception(AlertType::HandshakeFailure, "Failed to agree on any signature algorithm"); } return compatible_schemes; @@ -68,7 +68,7 @@ void Certificate_13::validate_extensions(const std::set& request // extensions in the CertificateRequest message from the server. for(const auto& entry : m_entries) { if(entry.extensions.contains_other_than(requested_extensions)) { - throw TLS_Exception(Alert::IllegalParameter, "Certificate Entry contained an extension that was not offered"); + throw TLS_Exception(AlertType::IllegalParameter, "Certificate Entry contained an extension that was not offered"); } cb.tls_examine_extensions(entry.extensions, m_side, type()); @@ -101,7 +101,7 @@ void Certificate_13::verify(Callbacks& callbacks, const auto& server_cert = m_entries.front().certificate; if(!certificate_allows_signing(server_cert)) { - throw TLS_Exception(Alert::BadCertificate, "Certificate usage constraints do not allow signing"); + throw TLS_Exception(AlertType::BadCertificate, "Certificate usage constraints do not allow signing"); } // Note that m_side represents the sender, so the usages here are swapped @@ -123,7 +123,7 @@ void Certificate_13::setup_entries(std::vector cert_chain, : std::vector>(cert_chain.size()); if(ocsp_responses.size() != cert_chain.size()) { - throw TLS_Exception(Alert::InternalError, "Application didn't provide the correct number of OCSP responses"); + throw TLS_Exception(AlertType::InternalError, "Application didn't provide the correct number of OCSP responses"); } for(size_t i = 0; i < cert_chain.size(); ++i) { @@ -196,13 +196,13 @@ Certificate_13::Certificate_13(const std::vector& buf, const Policy& po // RFC 8446 4.4.2 // [...] in the case of server authentication, this field SHALL be zero length. if(m_side == Connection_Side::Server && !m_request_context.empty()) { - throw TLS_Exception(Alert::IllegalParameter, "Server Certificate message must not contain a request context"); + throw TLS_Exception(AlertType::IllegalParameter, "Server Certificate message must not contain a request context"); } const auto cert_entries_len = reader.get_uint24_t(); if(reader.remaining_bytes() != cert_entries_len) { - throw TLS_Exception(Alert::DecodeError, "Certificate: Message malformed"); + throw TLS_Exception(AlertType::DecodeError, "Certificate: Message malformed"); } const size_t max_size = policy.maximum_certificate_chain_size(); @@ -224,7 +224,7 @@ Certificate_13::Certificate_13(const std::vector& buf, const Policy& po // the intermediates are outside of the control of the server. // But, require that the leaf certificate be v3. if(m_entries.empty() && entry.certificate.x509_version() != 3) { - throw TLS_Exception(Alert::BadCertificate, "The leaf certificate must be v3"); + throw TLS_Exception(AlertType::BadCertificate, "The leaf certificate must be v3"); } // Extensions are simply tacked at the end of the certificate entry. This @@ -249,7 +249,7 @@ Certificate_13::Certificate_13(const std::vector& buf, const Policy& po Extension_Code::CertificateStatusRequest, // Extension_Code::SignedCertificateTimestamp })) { - throw TLS_Exception(Alert::IllegalParameter, "Certificate Entry contained an extension that is not allowed"); + throw TLS_Exception(AlertType::IllegalParameter, "Certificate Entry contained an extension that is not allowed"); } m_entries.push_back(std::move(entry)); @@ -265,7 +265,7 @@ Certificate_13::Certificate_13(const std::vector& buf, const Policy& po // If the server supplies an empty Certificate message, the client MUST // abort the handshake with a "decode_error" alert. if(m_side == Connection_Side::Server) { - throw TLS_Exception(Alert::DecodeError, "No certificates sent by server"); + throw TLS_Exception(AlertType::DecodeError, "No certificates sent by server"); } } else { /* validation of provided certificate public key */ @@ -274,7 +274,7 @@ Certificate_13::Certificate_13(const std::vector& buf, const Policy& po policy.check_peer_key_acceptable(*key); if(!policy.allowed_signature_method(key->algo_name())) { - throw TLS_Exception(Alert::HandshakeFailure, "Rejecting " + key->algo_name() + " signature"); + throw TLS_Exception(AlertType::HandshakeFailure, "Rejecting " + key->algo_name() + " signature"); } } } diff --git a/src/lib/tls/tls13/msg_certificate_req_13.cpp b/src/lib/tls/tls13/msg_certificate_req_13.cpp index e36ec54c354..05da4b8d957 100644 --- a/src/lib/tls/tls13/msg_certificate_req_13.cpp +++ b/src/lib/tls/tls13/msg_certificate_req_13.cpp @@ -25,7 +25,7 @@ Certificate_Request_13::Certificate_Request_13(const std::vector& buf, // A server which is authenticating with a certificate MAY optionally // request a certificate from the client. if(side != Connection_Side::Server) { - throw TLS_Exception(Alert::UnexpectedMessage, "Received a Certificate_Request message from a client"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Received a Certificate_Request message from a client"); } m_context = reader.get_tls_length_value(1); @@ -37,7 +37,7 @@ Certificate_Request_13::Certificate_Request_13(const std::vector& buf, // Clients MUST ignore unrecognized extensions. if(!m_extensions.has()) { - throw TLS_Exception(Alert::MissingExtension, + throw TLS_Exception(AlertType::MissingExtension, "Certificate_Request message did not provide a signature_algorithms extension"); } @@ -60,7 +60,7 @@ Certificate_Request_13::Certificate_Request_13(const std::vector& buf, }; if(m_extensions.contains_implemented_extensions_other_than(allowed_extensions)) { - throw TLS_Exception(Alert::IllegalParameter, "Certificate Request contained an extension that is not allowed"); + throw TLS_Exception(AlertType::IllegalParameter, "Certificate Request contained an extension that is not allowed"); } } diff --git a/src/lib/tls/tls13/msg_encrypted_extensions.cpp b/src/lib/tls/tls13/msg_encrypted_extensions.cpp index 1275f1a382a..c7635747bf3 100644 --- a/src/lib/tls/tls13/msg_encrypted_extensions.cpp +++ b/src/lib/tls/tls13/msg_encrypted_extensions.cpp @@ -40,7 +40,7 @@ Encrypted_Extensions::Encrypted_Extensions(const Client_Hello_13& client_hello, // Endpoints SHOULD advertise the "record_size_limit" extension, even if // they have no need to limit the size of records. For clients, this // allows servers to advertise a limit at their discretion. - throw TLS_Exception(Alert::MissingExtension, + throw TLS_Exception(AlertType::MissingExtension, "Server cannot enforce record size limit without the client supporting it"); } @@ -73,7 +73,7 @@ Encrypted_Extensions::Encrypted_Extensions(const std::vector& buf) { // be empty. However, in that case we should at least see a two-byte length // field that reads 0x00 0x00. if(buf.size() < 2) { - throw TLS_Exception(Alert::DecodeError, "Server sent an empty Encrypted Extensions message"); + throw TLS_Exception(AlertType::DecodeError, "Server sent an empty Encrypted Extensions message"); } m_extensions.deserialize(reader, Connection_Side::Server, type()); @@ -101,7 +101,7 @@ Encrypted_Extensions::Encrypted_Extensions(const std::vector& buf) { Extension_Code::RecordSizeLimit, }; if(m_extensions.contains_implemented_extensions_other_than(allowed_exts)) { - throw TLS_Exception(Alert::IllegalParameter, "Encrypted Extensions contained an extension that is not allowed"); + throw TLS_Exception(AlertType::IllegalParameter, "Encrypted Extensions contained an extension that is not allowed"); } } diff --git a/src/lib/tls/tls13/msg_key_update.cpp b/src/lib/tls/tls13/msg_key_update.cpp index 970cdfb1121..5974a50e3e2 100644 --- a/src/lib/tls/tls13/msg_key_update.cpp +++ b/src/lib/tls/tls13/msg_key_update.cpp @@ -16,7 +16,7 @@ Key_Update::Key_Update(const bool request_peer_update) : m_update_requested(requ Key_Update::Key_Update(const std::vector& buf) { if(buf.size() != 1) { - throw TLS_Exception(Alert::DecodeError, "malformed key_update"); + throw TLS_Exception(AlertType::DecodeError, "malformed key_update"); } // RFC 8446 4.6.3 @@ -24,7 +24,7 @@ Key_Update::Key_Update(const std::vector& buf) { // terminate the connection with an "illegal_parameter" alert. const uint8_t update_requested = buf.at(0); if(update_requested > 1) { - throw TLS_Exception(Alert::IllegalParameter, "unexpected key_update parameter"); + throw TLS_Exception(AlertType::IllegalParameter, "unexpected key_update parameter"); } m_update_requested = update_requested == 1; diff --git a/src/lib/tls/tls13/tls_channel_impl_13.cpp b/src/lib/tls/tls13/tls_channel_impl_13.cpp index 6cb23437589..3a952903289 100644 --- a/src/lib/tls/tls13/tls_channel_impl_13.cpp +++ b/src/lib/tls/tls13/tls_channel_impl_13.cpp @@ -21,11 +21,11 @@ namespace { bool is_user_canceled_alert(const Botan::TLS::Alert& alert) { - return alert.type() == Botan::TLS::Alert::UserCanceled; + return alert.type() == Botan::TLS::AlertType::UserCanceled; } bool is_close_notify_alert(const Botan::TLS::Alert& alert) { - return alert.type() == Botan::TLS::Alert::CloseNotify; + return alert.type() == Botan::TLS::AlertType::CloseNotify; } bool is_error_alert(const Botan::TLS::Alert& alert) { @@ -65,7 +65,7 @@ Channel_Impl_13::Channel_Impl_13(const std::shared_ptr& callbacks, Channel_Impl_13::~Channel_Impl_13() = default; -size_t Channel_Impl_13::from_peer(std::span data) { +size_t Channel_Impl_13::from_peer(Botan::span data) { BOTAN_STATE_CHECK(!is_downgrading()); // RFC 8446 6.1 @@ -181,13 +181,13 @@ size_t Channel_Impl_13::from_peer(std::span data) { // RFC 8446 5.2 // If the decryption fails, the receiver MUST terminate the connection // with a "bad_record_mac" alert. - send_fatal_alert(Alert::BadRecordMac); + send_fatal_alert(AlertType::BadRecordMac); throw; } catch(Decoding_Error&) { - send_fatal_alert(Alert::DecodeError); + send_fatal_alert(AlertType::DecodeError); throw; } catch(...) { - send_fatal_alert(Alert::InternalError); + send_fatal_alert(AlertType::InternalError); throw; } } @@ -255,7 +255,7 @@ void Channel_Impl_13::send_dummy_change_cipher_spec() { send_record(Record_Type::ChangeCipherSpec, {0x01}); } -void Channel_Impl_13::to_peer(std::span data) { +void Channel_Impl_13::to_peer(Botan::span data) { if(!is_active()) { throw Invalid_State("Data cannot be sent on inactive TLS connection"); } @@ -375,7 +375,7 @@ void Channel_Impl_13::process_alert(const secure_vector& record) { if(expects_downgrade()) { m_downgrade_info->received_tls_13_error_alert = true; } else { - throw TLS_Exception(Alert::DecodeError, "Error alert not marked fatal"); // will shutdown in send_alert + throw TLS_Exception(AlertType::DecodeError, "Error alert not marked fatal"); // will shutdown in send_alert } } diff --git a/src/lib/tls/tls13/tls_channel_impl_13.h b/src/lib/tls/tls13/tls_channel_impl_13.h index 660869ba3cb..2dbf057624c 100644 --- a/src/lib/tls/tls13/tls_channel_impl_13.h +++ b/src/lib/tls/tls13/tls_channel_impl_13.h @@ -117,8 +117,8 @@ class Channel_Impl_13 : public Channel_Impl { ~Channel_Impl_13() override; - size_t from_peer(std::span data) override; - void to_peer(std::span data) override; + size_t from_peer(Botan::span data) override; + void to_peer(Botan::span data) override; /** * Send a TLS alert message. If the alert is fatal, the internal diff --git a/src/lib/tls/tls13/tls_cipher_state.cpp b/src/lib/tls/tls13/tls_cipher_state.cpp index 8ab5d17d5eb..5803913c17a 100644 --- a/src/lib/tls/tls13/tls_cipher_state.cpp +++ b/src/lib/tls/tls13/tls_cipher_state.cpp @@ -326,7 +326,7 @@ std::string Cipher_State::hash_algorithm() const { } bool Cipher_State::is_compatible_with(const Ciphersuite& cipher) const { - if(!cipher.usable_in_version(Protocol_Version::TLS_V13)) { + if(!cipher.usable_in_version(Version_Code::TLS_V13)) { return false; } diff --git a/src/lib/tls/tls13/tls_client_impl_13.cpp b/src/lib/tls/tls13/tls_client_impl_13.cpp index ce4c9a0b900..65522d428b7 100644 --- a/src/lib/tls/tls13/tls_client_impl_13.cpp +++ b/src/lib/tls/tls13/tls_client_impl_13.cpp @@ -102,7 +102,7 @@ void Client_Impl_13::process_dummy_change_cipher_spec() { // the first ClientHello message or after the peer's Finished message, it MUST be // treated as an unexpected record type [("unexpected_message" alert)]. if(!m_handshake_state.has_client_hello() || m_handshake_state.has_server_finished()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Received an unexpected dummy Change Cipher Spec"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Received an unexpected dummy Change Cipher Spec"); } // RFC 8446 5. @@ -149,7 +149,7 @@ std::optional Client_Impl_13::find_session_for_resumption() void Client_Impl_13::handle(const Server_Hello_12& server_hello_msg) { if(m_handshake_state.has_hello_retry_request()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Version downgrade received after Hello Retry"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Version downgrade received after Hello Retry"); } // RFC 8446 Appendix D.1 @@ -157,7 +157,7 @@ void Client_Impl_13::handle(const Server_Hello_12& server_hello_msg) { // (or is not acceptable), the client MUST abort the handshake with a // "protocol_version" alert. if(!expects_downgrade()) { - throw TLS_Exception(Alert::ProtocolVersion, "Received an unexpected legacy Server Hello"); + throw TLS_Exception(AlertType::ProtocolVersion, "Received an unexpected legacy Server Hello"); } // RFC 8446 4.1.3 @@ -171,7 +171,7 @@ void Client_Impl_13::handle(const Server_Hello_12& server_hello_msg) { // is found, the client MUST abort the handshake with an // "illegal_parameter" alert. if(server_hello_msg.random_signals_downgrade().has_value()) { - throw TLS_Exception(Alert::IllegalParameter, "Downgrade attack detected"); + throw TLS_Exception(AlertType::IllegalParameter, "Downgrade attack detected"); } // RFC 8446 4.2.1 @@ -181,7 +181,7 @@ void Client_Impl_13::handle(const Server_Hello_12& server_hello_msg) { // Note that this condition should never happen, as the Server_Hello parsing // code decides to create a Server_Hello_12 based on the absense of this extension. if(server_hello_msg.extensions().has()) { - throw TLS_Exception(Alert::IllegalParameter, "Unexpected extension received"); + throw TLS_Exception(AlertType::IllegalParameter, "Unexpected extension received"); } // RFC 8446 Appendix D.1 @@ -191,7 +191,7 @@ void Client_Impl_13::handle(const Server_Hello_12& server_hello_msg) { const auto& client_hello_exts = m_handshake_state.client_hello().extensions(); BOTAN_ASSERT_NOMSG(client_hello_exts.has()); if(!client_hello_exts.get()->supports(server_hello_msg.selected_version())) { - throw TLS_Exception(Alert::ProtocolVersion, "Protocol version was not offered"); + throw TLS_Exception(AlertType::ProtocolVersion, "Protocol version was not offered"); } if(policy().tls_13_middlebox_compatibility_mode() && @@ -200,7 +200,7 @@ void Client_Impl_13::handle(const Server_Hello_12& server_hello_msg) { // However, a TLS 1.2 server that wants to downgrade cannot have found the random session ID // we sent. Therefore, we have to consider this as an attack. // (Thanks BoGo test EchoTLS13CompatibilitySessionID!) - throw TLS_Exception(Alert::IllegalParameter, "Unexpected session ID during downgrade"); + throw TLS_Exception(AlertType::IllegalParameter, "Unexpected session ID during downgrade"); } request_downgrade(); @@ -217,14 +217,14 @@ void validate_server_hello_ish(const Client_Hello_13& ch, const Server_Hello_13& // A client which receives a legacy_session_id_echo field that does not match what // it sent in the ClientHello MUST abort the handshake with an "illegal_parameter" alert. if(ch.session_id() != sh.session_id()) { - throw TLS_Exception(Alert::IllegalParameter, "echoed session id did not match"); + throw TLS_Exception(AlertType::IllegalParameter, "echoed session id did not match"); } // RFC 8446 4.1.3 // A client which receives a cipher suite that was not offered MUST abort the handshake // with an "illegal_parameter" alert. if(!ch.offered_suite(sh.ciphersuite())) { - throw TLS_Exception(Alert::IllegalParameter, "Server replied with ciphersuite we didn't send"); + throw TLS_Exception(AlertType::IllegalParameter, "Server replied with ciphersuite we didn't send"); } // RFC 8446 4.2.1 @@ -235,7 +235,7 @@ void validate_server_hello_ish(const Client_Hello_13& ch, const Server_Hello_13& // Note: Server_Hello_13 parsing checks that its selected version is TLS 1.3 BOTAN_ASSERT_NOMSG(ch.extensions().has()); if(!ch.extensions().get()->supports(sh.selected_version())) { - throw TLS_Exception(Alert::IllegalParameter, "Protocol version was not offered"); + throw TLS_Exception(AlertType::IllegalParameter, "Protocol version was not offered"); } } } // namespace @@ -254,7 +254,7 @@ void Client_Impl_13::handle(const Server_Hello_13& sh) { // receiving such an extension, an endpoint MUST abort the handshake // with an "unsupported_extension" alert. if(sh.extensions().contains_other_than(ch.extensions().extension_types())) { - throw TLS_Exception(Alert::UnsupportedExtension, "Unsupported extension found in Server Hello"); + throw TLS_Exception(AlertType::UnsupportedExtension, "Unsupported extension found in Server Hello"); } if(m_handshake_state.has_hello_retry_request()) { @@ -265,7 +265,7 @@ void Client_Impl_13::handle(const Server_Hello_13& sh) { // supplied in the ServerHello is the same as that in the HelloRetryRequest // and otherwise abort the handshake with an "illegal_parameter" alert. if(hrr.ciphersuite() != sh.ciphersuite()) { - throw TLS_Exception(Alert::IllegalParameter, "server changed its chosen ciphersuite"); + throw TLS_Exception(AlertType::IllegalParameter, "server changed its chosen ciphersuite"); } // RFC 8446 4.1.4 @@ -273,7 +273,7 @@ void Client_Impl_13::handle(const Server_Hello_13& sh) { // extension MUST be retained in the ServerHello, and a client MUST abort the // handshake with an "illegal_parameter" alert if the value changes. if(hrr.selected_version() != sh.selected_version()) { - throw TLS_Exception(Alert::IllegalParameter, "server changed its chosen protocol version"); + throw TLS_Exception(AlertType::IllegalParameter, "server changed its chosen protocol version"); } } @@ -284,8 +284,8 @@ void Client_Impl_13::handle(const Server_Hello_13& sh) { // Although TLS 1.3 uses the same cipher suite space as previous versions // of TLS [...] cipher suites for TLS 1.2 and lower cannot be used with // TLS 1.3. - if(!cipher->usable_in_version(Protocol_Version::TLS_V13)) { - throw TLS_Exception(Alert::IllegalParameter, + if(!cipher->usable_in_version(Version_Code::TLS_V13)) { + throw TLS_Exception(AlertType::IllegalParameter, "Server replied using a ciphersuite not allowed in version it offered"); } @@ -300,7 +300,7 @@ void Client_Impl_13::handle(const Server_Hello_13& sh) { // // TODO: Implement PSK-only mode. if(!sh.extensions().has()) { - throw TLS_Exception(Alert::IllegalParameter, "Server Hello did not contain a key share extension"); + throw TLS_Exception(AlertType::IllegalParameter, "Server Hello did not contain a key share extension"); } auto my_keyshare = ch.extensions().get(); @@ -351,7 +351,7 @@ void Client_Impl_13::handle(const Hello_Retry_Request& hrr) { auto allowed_exts = ch.extensions().extension_types(); allowed_exts.insert(Extension_Code::Cookie); if(hrr.extensions().contains_other_than(allowed_exts)) { - throw TLS_Exception(Alert::UnsupportedExtension, "Unsupported extension found in Hello Retry Request"); + throw TLS_Exception(AlertType::UnsupportedExtension, "Unsupported extension found in Hello Retry Request"); } auto cipher = Ciphersuite::by_id(hrr.ciphersuite()); @@ -382,7 +382,7 @@ void Client_Impl_13::handle(const Encrypted_Extensions& encrypted_extensions_msg // with an "unsupported_extension" alert. const auto& requested_exts = m_handshake_state.client_hello().extensions().extension_types(); if(exts.contains_other_than(requested_exts)) { - throw TLS_Exception(Alert::UnsupportedExtension, + throw TLS_Exception(AlertType::UnsupportedExtension, "Encrypted Extensions contained an extension that was not offered"); } @@ -419,7 +419,7 @@ void Client_Impl_13::handle(const Certificate_Request_13& certificate_request_ms // [The 'context' field] SHALL be zero length unless used for the // post-handshake authentication exchanges described in Section 4.6.2. if(!m_handshake_state.handshake_finished() && !certificate_request_msg.context().empty()) { - throw TLS_Exception(Alert::DecodeError, "Certificate_Request context must be empty in the main handshake"); + throw TLS_Exception(AlertType::DecodeError, "Certificate_Request context must be empty in the main handshake"); } callbacks().tls_examine_extensions( @@ -432,7 +432,7 @@ void Client_Impl_13::handle(const Certificate_13& certificate_msg) { // certificate_request_context: [...] In the case of server authentication, // this field SHALL be zero length. if(!certificate_msg.request_context().empty()) { - throw TLS_Exception(Alert::DecodeError, "Received a server certificate message with non-empty request context"); + throw TLS_Exception(AlertType::DecodeError, "Received a server certificate message with non-empty request context"); } // RFC 8446 4.4.2 @@ -459,7 +459,7 @@ void Client_Impl_13::handle(const Certificate_Verify_13& certificate_verify_msg) // an unsupported signature scheme, we opt to abort the handshake. const auto offered = m_handshake_state.client_hello().signature_schemes(); if(!value_exists(offered, certificate_verify_msg.signature_scheme())) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "We did not offer the usage of " + certificate_verify_msg.signature_scheme().to_string() + " as a signature scheme"); } @@ -468,7 +468,7 @@ void Client_Impl_13::handle(const Certificate_Verify_13& certificate_verify_msg) m_handshake_state.server_certificate().leaf(), callbacks(), m_transcript_hash.previous()); if(!sig_valid) { - throw TLS_Exception(Alert::DecryptError, "Server certificate verification failed"); + throw TLS_Exception(AlertType::DecryptError, "Server certificate verification failed"); } m_transitions.set_expected_next(Handshake_Type::Finished); @@ -510,7 +510,7 @@ void Client_Impl_13::handle(const Finished_13& finished_msg) { // correct and if incorrect MUST terminate the connection with a // "decrypt_error" alert. if(!finished_msg.verify(m_cipher_state.get(), m_transcript_hash.previous())) { - throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify"); + throw TLS_Exception(AlertType::DecryptError, "Finished message didn't verify"); } // Give the application a chance for a final veto before fully diff --git a/src/lib/tls/tls13/tls_extensions_key_share.cpp b/src/lib/tls/tls13/tls_extensions_key_share.cpp index c330c23194a..d558920cbff 100644 --- a/src/lib/tls/tls13/tls_extensions_key_share.cpp +++ b/src/lib/tls/tls13/tls_extensions_key_share.cpp @@ -49,7 +49,7 @@ class Key_Share_Entry { Key_Share_Entry(const TLS::Group_Params group, Callbacks& cb, RandomNumberGenerator& rng) : m_group(group), m_private_key(cb.tls_kem_generate_key(group, rng)) { if(!m_private_key) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a suitable ephemeral key pair"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a suitable ephemeral key pair"); } if(group.is_kem()) { @@ -57,7 +57,7 @@ class Key_Share_Entry { } else if(group.is_ecdh_named_curve()) { auto pkey = dynamic_cast(m_private_key.get()); if(!pkey) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a ECDH_PublicKey"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a ECDH_PublicKey"); } // RFC 8446 Ch. 4.2.8.2 @@ -72,14 +72,14 @@ class Key_Share_Entry { } else { auto pkey = dynamic_cast(m_private_key.get()); if(!pkey) { - throw TLS_Exception(Alert::InternalError, "Application did not provide a key-agreement key"); + throw TLS_Exception(AlertType::InternalError, "Application did not provide a key-agreement key"); } m_key_exchange = pkey->public_value(); } } - bool empty() const { return (m_group == Group_Params::NONE) && m_key_exchange.empty(); } + bool empty() const { return (m_group == Group_Params_Code::NONE) && m_key_exchange.empty(); } std::vector serialize() const { std::vector result; @@ -125,8 +125,9 @@ class Key_Share_Entry { // With X25519 and X448, a receiving party MUST check whether the // computed premaster secret is the all-zero value and abort the // handshake if so, as described in Section 6 of [RFC7748]. - if(m_group == Named_Group::X25519 && CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) { - throw TLS_Exception(Alert::DecryptError, "Bad X25519 key exchange"); + if(m_group == Group_Params_Code::X25519 && + CT::all_zeros(shared_secret.data(), shared_secret.size()).is_set()) { + throw TLS_Exception(AlertType::DecryptError, "Bad X25519 key exchange"); } return shared_secret; @@ -202,7 +203,7 @@ class Key_Share_ClientHello { while(reader.has_remaining() && remaining() > 0) { if(remaining() < 4) { - throw TLS_Exception(Alert::DecodeError, "Not enough data to read another KeyShareEntry"); + throw TLS_Exception(AlertType::DecodeError, "Not enough data to read another KeyShareEntry"); } Key_Share_Entry new_entry(reader); @@ -215,7 +216,8 @@ class Key_Share_ClientHello { if(std::find_if(m_client_shares.begin(), m_client_shares.end(), [&](const auto& entry) { return entry.group() == new_entry.group(); }) != m_client_shares.end()) { - throw TLS_Exception(Alert::IllegalParameter, "Received multiple key share entries for the same group"); + throw TLS_Exception(AlertType::IllegalParameter, + "Received multiple key share entries for the same group"); } m_client_shares.emplace_back(std::move(new_entry)); @@ -264,7 +266,7 @@ class Key_Share_ClientHello { if(std::find_if(m_client_shares.cbegin(), m_client_shares.cend(), [&](const auto& kse) { return kse.group() == to_offer; }) != m_client_shares.cend()) { - throw TLS_Exception(Alert::IllegalParameter, "group was already offered"); + throw TLS_Exception(AlertType::IllegalParameter, "group was already offered"); } m_client_shares.clear(); @@ -337,7 +339,7 @@ class Key_Share_ClientHello { // as the KeyShareEntry value offered by the client that the server // has selected for the negotiated key exchange. if(match == m_client_shares.end()) { - throw TLS_Exception(Alert::IllegalParameter, "Server selected a key exchange group we didn't offer."); + throw TLS_Exception(AlertType::IllegalParameter, "Server selected a key exchange group we didn't offer."); } return match->decapsulate(server_selected, policy, cb, rng); @@ -390,7 +392,7 @@ class Key_Share_HelloRetryRequest { throw Invalid_Argument("Hello Retry Request never offers any key exchange groups"); } - bool empty() const { return m_selected_group == Group_Params::NONE; } + bool empty() const { return m_selected_group == Group_Params_Code::NONE; } private: Named_Group m_selected_group; @@ -500,7 +502,8 @@ void Key_Share::retry_offer(const Key_Share& retry_request_keyshare, // [T]he selected_group field [MUST correspond] to a group which was provided in // the "supported_groups" extension in the original ClientHello if(!value_exists(supported_groups, selected)) { - throw TLS_Exception(Alert::IllegalParameter, "group was not advertised as supported"); + throw TLS_Exception(AlertType::IllegalParameter, + "group was not advertised as supported"); } return ch.retry_offer(selected, cb, rng); diff --git a/src/lib/tls/tls13/tls_extensions_psk.cpp b/src/lib/tls/tls13/tls_extensions_psk.cpp index a01527d16e4..8864f4f0111 100644 --- a/src/lib/tls/tls13/tls_extensions_psk.cpp +++ b/src/lib/tls/tls13/tls_extensions_psk.cpp @@ -141,7 +141,7 @@ class PSK::PSK_Internal { PSK::PSK(TLS_Data_Reader& reader, uint16_t extension_size, Handshake_Type message_type) { if(message_type == Handshake_Type::ServerHello) { if(extension_size != 2) { - throw TLS_Exception(Alert::DecodeError, "Server provided a malformed PSK extension"); + throw TLS_Exception(AlertType::DecodeError, "Server provided a malformed PSK extension"); } const uint16_t selected_id = reader.get_uint16_t(); @@ -158,36 +158,36 @@ PSK::PSK(TLS_Data_Reader& reader, uint16_t extension_size, Handshake_Type messag } if(psk_identities.empty()) { - throw TLS_Exception(Alert::DecodeError, "Empty PSK list"); + throw TLS_Exception(AlertType::DecodeError, "Empty PSK list"); } if(reader.read_so_far() - identities_offset != identities_length) { - throw TLS_Exception(Alert::DecodeError, "Inconsistent PSK identity list"); + throw TLS_Exception(AlertType::DecodeError, "Inconsistent PSK identity list"); } const auto binders_length = reader.get_uint16_t(); const auto binders_offset = reader.read_so_far(); if(binders_length == 0) { - throw TLS_Exception(Alert::DecodeError, "Empty PSK binders list"); + throw TLS_Exception(AlertType::DecodeError, "Empty PSK binders list"); } std::vector psks; for(auto& psk_identity : psk_identities) { if(!reader.has_remaining() || reader.read_so_far() - binders_offset >= binders_length) { - throw TLS_Exception(Alert::IllegalParameter, "Not enough PSK binders"); + throw TLS_Exception(AlertType::IllegalParameter, "Not enough PSK binders"); } psks.emplace_back(std::move(psk_identity), reader.get_tls_length_value(1)); } if(reader.read_so_far() - binders_offset != binders_length) { - throw TLS_Exception(Alert::IllegalParameter, "Too many PSK binders"); + throw TLS_Exception(AlertType::IllegalParameter, "Too many PSK binders"); } m_impl = std::make_unique(std::move(psks)); } else { - throw TLS_Exception(Alert::DecodeError, "Found a PSK extension in an unexpected handshake message"); + throw TLS_Exception(AlertType::DecodeError, "Found a PSK extension in an unexpected handshake message"); } } @@ -236,7 +236,7 @@ std::pair, std::unique_ptr> PSK::take_s // consistent, the client MUST abort the handshake with an // "illegal_parameter" alert. if(id >= ids.size()) { - throw TLS_Exception(Alert::IllegalParameter, "PSK identity selected by server is out of bounds"); + throw TLS_Exception(AlertType::IllegalParameter, "PSK identity selected by server is out of bounds"); } auto& selected_psk = ids.at(id); @@ -260,7 +260,7 @@ std::pair, std::unique_ptr> PSK::take_s // are not consistent, the client MUST abort the handshake with an // "illegal_parameter" alert. if(!cipher_state->is_compatible_with(cipher)) { - throw TLS_Exception(Alert::IllegalParameter, "PSK and ciphersuite selected by server are not compatible"); + throw TLS_Exception(AlertType::IllegalParameter, "PSK and ciphersuite selected by server are not compatible"); } return {std::move(psk_id), std::move(cipher_state)}; @@ -291,7 +291,7 @@ std::unique_ptr PSK::select_offered_psk(std::string_view host, // same KDF hash algorithm as that used to establish the original // connection. if(session.ciphersuite().prf_algo() != cipher.prf_algo()) { - throw TLS_Exception(Alert::InternalError, + throw TLS_Exception(AlertType::InternalError, "Application chose a ticket that is not compatible with the negotiated ciphersuite"); } @@ -314,7 +314,7 @@ std::unique_ptr PSK::select_offered_psk(std::string_view host, // The server MUST ensure that it selects a compatible PSK (if any) // and cipher suite. if(psk.prf_algo() != cipher.prf_algo()) { - throw TLS_Exception(Alert::InternalError, + throw TLS_Exception(AlertType::InternalError, "Application chose a PSK that is not compatible with the negotiated ciphersuite"); } @@ -323,7 +323,7 @@ std::unique_ptr PSK::select_offered_psk(std::string_view host, return offered_psk.identity_as_string() == psk.identity(); }); if(selected_itr == psk_identities.end()) { - throw TLS_Exception(Alert::InternalError, + throw TLS_Exception(AlertType::InternalError, "Application provided a PSK with an identity that was not offered by the client"); } diff --git a/src/lib/tls/tls13/tls_handshake_layer_13.cpp b/src/lib/tls/tls13/tls_handshake_layer_13.cpp index 77a8af4a249..79a4e57c98c 100644 --- a/src/lib/tls/tls13/tls_handshake_layer_13.cpp +++ b/src/lib/tls/tls13/tls_handshake_layer_13.cpp @@ -16,7 +16,7 @@ namespace Botan::TLS { -void Handshake_Layer::copy_data(std::span data_from_peer) { +void Handshake_Layer::copy_data(Botan::span data_from_peer) { m_read_buffer.insert(m_read_buffer.end(), data_from_peer.begin(), data_from_peer.end()); } @@ -122,7 +122,7 @@ std::optional Handshake_Layer::next_message(const Policy& auto msg = parse_message(reader, policy, m_peer); if(msg.has_value()) { BOTAN_ASSERT_NOMSG(m_read_buffer.size() >= reader.read_so_far()); - transcript_hash.update(std::span{m_read_buffer.data(), reader.read_so_far()}); + transcript_hash.update(Botan::span{m_read_buffer.data(), reader.read_so_far()}); m_read_buffer.erase(m_read_buffer.cbegin(), m_read_buffer.cbegin() + reader.read_so_far()); } diff --git a/src/lib/tls/tls13/tls_handshake_layer_13.h b/src/lib/tls/tls13/tls_handshake_layer_13.h index ed793ba18a9..58672afcc76 100644 --- a/src/lib/tls/tls13/tls_handshake_layer_13.h +++ b/src/lib/tls/tls13/tls_handshake_layer_13.h @@ -36,7 +36,7 @@ class BOTAN_TEST_API Handshake_Layer { * * @param data_from_peer The data to be parsed. */ - void copy_data(std::span data_from_peer); + void copy_data(Botan::span data_from_peer); /** * Parses one handshake message off the internal buffer that is being filled using `copy_data`. diff --git a/src/lib/tls/tls13/tls_handshake_state_13.h b/src/lib/tls/tls13/tls_handshake_state_13.h index 20b2e89f892..b1c87528a7b 100644 --- a/src/lib/tls/tls13/tls_handshake_state_13.h +++ b/src/lib/tls/tls13/tls_handshake_state_13.h @@ -135,17 +135,17 @@ class BOTAN_TEST_API Handshake_State_13 : public Internal::Handshake_State_13_Ba public: Handshake_State_13() : Handshake_State_13_Base(whoami) {} - template + template >> std::reference_wrapper sending(MsgT msg) - requires(std::is_constructible_v) { return std::reference_wrapper(store(std::move(msg), false)); } template decltype(auto) sending(std::variant message) - requires(is_generalizable_to(message)) { + static_assert(is_generalizable_to(message) == true, "message is not generalizable to Outbound_Message_T"); return std::visit( [&](auto msg) -> as_wrapped_references_t> { return sending(std::move(msg)); }, std::move(message)); diff --git a/src/lib/tls/tls13/tls_record_layer_13.cpp b/src/lib/tls/tls13/tls_record_layer_13.cpp index 1f774d2c699..58c8cf4c998 100644 --- a/src/lib/tls/tls13/tls_record_layer_13.cpp +++ b/src/lib/tls/tls13/tls_record_layer_13.cpp @@ -39,7 +39,7 @@ Record_Type read_record_type(const uint8_t type_byte) { type_byte != static_cast(Record_Type::Handshake) && type_byte != static_cast(Record_Type::Alert) && type_byte != static_cast(Record_Type::ChangeCipherSpec)) { - throw TLS_Exception(Alert::UnexpectedMessage, "TLS record type had unexpected value"); + throw TLS_Exception(AlertType::UnexpectedMessage, "TLS record type had unexpected value"); } return static_cast(type_byte); @@ -59,14 +59,14 @@ class TLSPlaintext_Header final { // If no full version check is requested, we just verify the practically // ossified major version number. if(m_legacy_version.major_version() != 0x03) { - throw TLS_Exception(Alert::IllegalParameter, "Received unexpected record version"); + throw TLS_Exception(AlertType::IllegalParameter, "Received unexpected record version"); } // RFC 8446 5.1 // legacy_record_version: MUST be set to 0x0303 for all records // generated by a TLS 1.3 implementation if(check_tls13_version && m_legacy_version.version_code() != 0x0303) { - throw TLS_Exception(Alert::IllegalParameter, "Received unexpected record version"); + throw TLS_Exception(AlertType::IllegalParameter, "Received unexpected record version"); } // RFC 8446 5.1 @@ -76,7 +76,7 @@ class TLSPlaintext_Header final { // Zero-length fragments of Application Data MAY be sent, as they are // potentially useful as a traffic analysis countermeasure. if(m_fragment_length == 0 && type() != Record_Type::ApplicationData) { - throw TLS_Exception(Alert::DecodeError, "empty record received"); + throw TLS_Exception(AlertType::DecodeError, "empty record received"); } if(m_type == Record_Type::ApplicationData) { @@ -90,7 +90,7 @@ class TLSPlaintext_Header final { // encrypted data. Constricted devices must be able to deal with // data overhead inflicted by the AEAD. if(m_fragment_length > MAX_CIPHERTEXT_SIZE_TLS13) { - throw TLS_Exception(Alert::RecordOverflow, "Received an encrypted record that exceeds maximum size"); + throw TLS_Exception(AlertType::RecordOverflow, "Received an encrypted record that exceeds maximum size"); } } else { // RFC 8446 5.1 @@ -103,7 +103,7 @@ class TLSPlaintext_Header final { // than the RecordSizeLimit value it receives from its peer. // -> Unprotected messages are not subject to this limit. <- if(m_fragment_length > MAX_PLAINTEXT_SIZE) { - throw TLS_Exception(Alert::RecordOverflow, "Received a record that exceeds maximum size"); + throw TLS_Exception(AlertType::RecordOverflow, "Received a record that exceeds maximum size"); } } } @@ -167,12 +167,12 @@ Record_Layer::Record_Layer(Connection_Side side) : m_sending_compat_mode(m_side == Connection_Side::Client), m_receiving_compat_mode(true) {} -void Record_Layer::copy_data(std::span data) { +void Record_Layer::copy_data(Botan::span data) { m_read_buffer.insert(m_read_buffer.end(), data.begin(), data.end()); } std::vector Record_Layer::prepare_records(const Record_Type type, - std::span data, + Botan::span data, Cipher_State* cipher_state) const { // RFC 8446 5. // Note that [change_cipher_spec records] may appear at a point at the @@ -301,7 +301,8 @@ Record_Layer::ReadResult Record_Layer::next_record(Cipher_State* cipher_ if(cipher_state != nullptr && plaintext_header.type() != Record_Type::ApplicationData && plaintext_header.type() != Record_Type::ChangeCipherSpec && (!cipher_state->must_expect_unprotected_alert_traffic() || plaintext_header.type() != Record_Type::Alert)) { - throw TLS_Exception(Alert::UnexpectedMessage, "unprotected record received where protected traffic was expected"); + throw TLS_Exception(AlertType::UnexpectedMessage, + "unprotected record received where protected traffic was expected"); } if(m_read_buffer.size() < TLS_HEADER_SIZE + plaintext_header.fragment_length()) { @@ -313,7 +314,7 @@ Record_Layer::ReadResult Record_Layer::next_record(Cipher_State* cipher_ if(plaintext_header.type() == Record_Type::ChangeCipherSpec && !verify_change_cipher_spec(fragment_begin, plaintext_header.fragment_length())) { - throw TLS_Exception(Alert::UnexpectedMessage, "malformed change cipher spec record received"); + throw TLS_Exception(AlertType::UnexpectedMessage, "malformed change cipher spec record received"); } Record record(plaintext_header.type(), secure_vector(fragment_begin, fragment_end)); @@ -323,15 +324,16 @@ Record_Layer::ReadResult Record_Layer::next_record(Cipher_State* cipher_ if(cipher_state == nullptr) { // This could also mean a misuse of the interface, i.e. failing to provide a valid // cipher_state to parse_records when receiving valid (encrypted) Application Data. - throw TLS_Exception(Alert::UnexpectedMessage, "premature Application Data received"); + throw TLS_Exception(AlertType::UnexpectedMessage, "premature Application Data received"); } if(record.fragment.size() < cipher_state->minimum_decryption_input_length()) { - throw TLS_Exception(Alert::BadRecordMac, "incomplete record mac received"); + throw TLS_Exception(AlertType::BadRecordMac, "incomplete record mac received"); } if(cipher_state->decrypt_output_length(record.fragment.size()) > m_incoming_record_size_limit) { - throw TLS_Exception(Alert::RecordOverflow, "Received an encrypted record that exceeds maximum plaintext size"); + throw TLS_Exception(AlertType::RecordOverflow, + "Received an encrypted record that exceeds maximum plaintext size"); } record.seq_no = cipher_state->decrypt_record_fragment(plaintext_header.serialized(), record.fragment); @@ -345,7 +347,7 @@ Record_Layer::ReadResult Record_Layer::next_record(Cipher_State* cipher_ // If a receiving implementation does not // find a non-zero octet in the cleartext, it MUST terminate the // connection with an "unexpected_message" alert. - throw TLS_Exception(Alert::UnexpectedMessage, "No content type found in encrypted record"); + throw TLS_Exception(AlertType::UnexpectedMessage, "No content type found in encrypted record"); } // hydrate the actual content type from TLSInnerPlaintext @@ -355,7 +357,7 @@ Record_Layer::ReadResult Record_Layer::next_record(Cipher_State* cipher_ // RFC 8446 5 // An implementation [...] which receives a protected change_cipher_spec record MUST // abort the handshake with an "unexpected_message" alert. - throw TLS_Exception(Alert::UnexpectedMessage, "protected change cipher spec received"); + throw TLS_Exception(AlertType::UnexpectedMessage, "protected change cipher spec received"); } // erase content type and padding diff --git a/src/lib/tls/tls13/tls_record_layer_13.h b/src/lib/tls/tls13/tls_record_layer_13.h index f9780c08b37..76e5436bc32 100644 --- a/src/lib/tls/tls13/tls_record_layer_13.h +++ b/src/lib/tls/tls13/tls_record_layer_13.h @@ -10,11 +10,11 @@ #define BOTAN_TLS_RECORD_LAYER_13_H_ #include -#include #include #include #include +#include #include #include @@ -56,7 +56,7 @@ class BOTAN_TEST_API Record_Layer { * * @param data_from_peer The data to be parsed. */ - void copy_data(std::span data_from_peer); + void copy_data(Botan::span data_from_peer); /** * Parses one record off the internal buffer that is being filled using `copy_data`. @@ -72,7 +72,7 @@ class BOTAN_TEST_API Record_Layer { ReadResult next_record(Cipher_State* cipher_state = nullptr); std::vector prepare_records(Record_Type type, - std::span data, + Botan::span data, Cipher_State* cipher_state = nullptr) const; /** diff --git a/src/lib/tls/tls13/tls_server_impl_13.cpp b/src/lib/tls/tls13/tls_server_impl_13.cpp index e2711876d18..82edcd52e8d 100644 --- a/src/lib/tls/tls13/tls_server_impl_13.cpp +++ b/src/lib/tls/tls13/tls_server_impl_13.cpp @@ -136,7 +136,7 @@ void Server_Impl_13::process_dummy_change_cipher_spec() { // the first ClientHello message or after the peer's Finished message, it MUST be // treated as an unexpected record type [("unexpected_message" alert)]. if(!m_handshake_state.has_client_hello() || m_handshake_state.has_client_finished()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Received an unexpected dummy Change Cipher Spec"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Received an unexpected dummy Change Cipher Spec"); } // RFC 8446 5. @@ -241,7 +241,7 @@ void Server_Impl_13::handle_reply_to_client_hello(Server_Hello_13 server_hello) // of this extension in the first place. if(!exts.get()->validate_binder(*psk_extension, psk_cipher_state->psk_binder_mac(m_transcript_hash.truncated()))) { - throw TLS_Exception(Alert::DecryptError, "PSK binder does not check out"); + throw TLS_Exception(AlertType::DecryptError, "PSK binder does not check out"); } // RFC 8446 4.2.10 @@ -368,7 +368,7 @@ void Server_Impl_13::handle(const Client_Hello_12& ch) { // After we sent a Hello Retry Request we must not accept a downgrade. if(m_handshake_state.has_hello_retry_request()) { - throw TLS_Exception(Alert::UnexpectedMessage, "Received a TLS 1.2 Client Hello after Hello Retry Request"); + throw TLS_Exception(AlertType::UnexpectedMessage, "Received a TLS 1.2 Client Hello after Hello Retry Request"); } // RFC 8446 Appendix D.2 @@ -378,7 +378,7 @@ void Server_Impl_13::handle(const Client_Hello_12& ch) { // // If we're not expecting a downgrade, we only support TLS 1.3. if(!expects_downgrade()) { - throw TLS_Exception(Alert::ProtocolVersion, "Received a legacy Client Hello"); + throw TLS_Exception(AlertType::ProtocolVersion, "Received a legacy Client Hello"); } downgrade(); @@ -392,14 +392,14 @@ void Server_Impl_13::handle(const Client_Hello_13& client_hello) { if(is_initial_client_hello) { const auto preferred_version = client_hello.highest_supported_version(policy()); if(!preferred_version) { - throw TLS_Exception(Alert::ProtocolVersion, "No shared TLS version"); + throw TLS_Exception(AlertType::ProtocolVersion, "No shared TLS version"); } // RFC 8446 4.2.2 // Clients MUST NOT use cookies in their initial ClientHello in subsequent // connections. if(exts.has()) { - throw TLS_Exception(Alert::IllegalParameter, "Received a Cookie in the initial client hello"); + throw TLS_Exception(AlertType::IllegalParameter, "Received a Cookie in the initial client hello"); } } @@ -421,7 +421,8 @@ void Server_Impl_13::handle(const Client_Hello_13& client_hello) { const auto offered_groups = exts.get()->offered_groups(); const auto selected_group = hrr_exts.get()->selected_group(); if(offered_groups.size() != 1 || offered_groups.at(0) != selected_group) { - throw TLS_Exception(Alert::IllegalParameter, "Client did not comply with the requested key exchange group"); + throw TLS_Exception(AlertType::IllegalParameter, + "Client did not comply with the requested key exchange group"); } } @@ -441,7 +442,8 @@ void Server_Impl_13::handle(const Certificate_13& certificate_msg) { // certificate_request_context: [...] This field SHALL be zero length // unless used for the post-handshake authentication exchanges [...]. if(!handshake_finished() && !certificate_msg.request_context().empty()) { - throw TLS_Exception(Alert::DecodeError, "Received a client certificate message with non-empty request context"); + throw TLS_Exception(AlertType::DecodeError, + "Received a client certificate message with non-empty request context"); } // RFC 8446 4.4.2 @@ -457,7 +459,8 @@ void Server_Impl_13::handle(const Certificate_13& certificate_msg) { // a "certificate_required" alert. if(certificate_msg.empty()) { if(policy().require_client_certificate_authentication()) { - throw TLS_Exception(Alert::CertificateRequired, "Policy requires client send a certificate, but it did not"); + throw TLS_Exception(AlertType::CertificateRequired, + "Policy requires client send a certificate, but it did not"); } // RFC 8446 4.4.2 @@ -497,7 +500,7 @@ void Server_Impl_13::handle(const Certificate_Verify_13& certificate_verify_msg) // CertificateRequest message. const auto offered = m_handshake_state.certificate_request().signature_schemes(); if(!value_exists(offered, certificate_verify_msg.signature_scheme())) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "We did not offer the usage of " + certificate_verify_msg.signature_scheme().to_string() + " as a signature scheme"); } @@ -511,7 +514,7 @@ void Server_Impl_13::handle(const Certificate_Verify_13& certificate_verify_msg) // If the verification fails, the receiver MUST terminate the handshake // with a "decrypt_error" alert. if(!sig_valid) { - throw TLS_Exception(Alert::DecryptError, "Client certificate verification failed"); + throw TLS_Exception(AlertType::DecryptError, "Client certificate verification failed"); } m_transitions.set_expected_next(Handshake_Type::Finished); @@ -523,7 +526,7 @@ void Server_Impl_13::handle(const Finished_13& finished_msg) { // correct and if incorrect MUST terminate the connection with a // "decrypt_error" alert. if(!finished_msg.verify(m_cipher_state.get(), m_transcript_hash.previous())) { - throw TLS_Exception(Alert::DecryptError, "Finished message didn't verify"); + throw TLS_Exception(AlertType::DecryptError, "Finished message didn't verify"); } // Give the application a chance for a final veto before fully diff --git a/src/lib/tls/tls13/tls_transcript_hash_13.cpp b/src/lib/tls/tls13/tls_transcript_hash_13.cpp index b2ab1d0975c..1da60323051 100644 --- a/src/lib/tls/tls13/tls_transcript_hash_13.cpp +++ b/src/lib/tls/tls13/tls_transcript_hash_13.cpp @@ -73,7 +73,7 @@ namespace { // // Finds the truncation offset in a serialization of Client Hello as defined in // RFC 8446 4.2.11.2 used for the calculation of PSK binder MACs. -size_t find_client_hello_truncation_mark(std::span client_hello) { +size_t find_client_hello_truncation_mark(Botan::span client_hello) { TLS_Data_Reader reader("Client Hello Truncation", client_hello); // handshake message type @@ -123,7 +123,7 @@ size_t find_client_hello_truncation_mark(std::span client_hello) // check that only the binders are left in the buffer... const auto binders_length = reader.peek_uint16_t(); if(binders_length != reader.remaining_bytes() - 2 /* binders_length */) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "Failed to truncate Client Hello that doesn't end on the PSK binders list"); } @@ -144,7 +144,7 @@ std::vector read_hash_state(std::unique_ptr& hash) { } // namespace -void Transcript_Hash_State::update(std::span serialized_message_s) { +void Transcript_Hash_State::update(Botan::span serialized_message_s) { auto serialized_message = serialized_message_s.data(); auto serialized_message_length = serialized_message_s.size(); if(m_hash != nullptr) { diff --git a/src/lib/tls/tls13/tls_transcript_hash_13.h b/src/lib/tls/tls13/tls_transcript_hash_13.h index 7bc48049010..c48ac7c61dc 100644 --- a/src/lib/tls/tls13/tls_transcript_hash_13.h +++ b/src/lib/tls/tls13/tls_transcript_hash_13.h @@ -11,9 +11,9 @@ #include #include +#include #include -#include #include #include @@ -48,7 +48,7 @@ class BOTAN_TEST_API Transcript_Hash_State { Transcript_Hash_State(Transcript_Hash_State&&) = default; Transcript_Hash_State& operator=(Transcript_Hash_State&&) = default; - void update(std::span serialized_message_s); + void update(Botan::span serialized_message_s); /** * returns the latest transcript hash diff --git a/src/lib/tls/tls13_pqc/hybrid_public_key.cpp b/src/lib/tls/tls13_pqc/hybrid_public_key.cpp index 7fc531bc54f..f0c1cd4fb7f 100644 --- a/src/lib/tls/tls13_pqc/hybrid_public_key.cpp +++ b/src/lib/tls/tls13_pqc/hybrid_public_key.cpp @@ -25,19 +25,19 @@ std::vector> algorithm_specs_for_group(Group BOTAN_ARG_CHECK(group.is_pqc_hybrid(), "Group is not hybrid"); switch(group.code()) { - case Group_Params::HYBRID_X25519_KYBER_512_R3_OQS: - case Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE: + case Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS: + case Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE: return {{"Curve25519", "Curve25519"}, {"Kyber", "Kyber-512-r3"}}; - case Group_Params::HYBRID_X25519_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_X25519_KYBER_768_R3_OQS: return {{"Curve25519", "Curve25519"}, {"Kyber", "Kyber-768-r3"}}; - case Group_Params::HYBRID_SECP256R1_KYBER_512_R3_OQS: + case Group_Params_Code::HYBRID_SECP256R1_KYBER_512_R3_OQS: return {{"ECDH", "secp256r1"}, {"Kyber", "Kyber-512-r3"}}; - case Group_Params::HYBRID_SECP256R1_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_SECP256R1_KYBER_768_R3_OQS: return {{"ECDH", "secp256r1"}, {"Kyber", "Kyber-768-r3"}}; - case Group_Params::HYBRID_SECP384R1_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_SECP384R1_KYBER_768_R3_OQS: return {{"ECDH", "secp384r1"}, {"Kyber", "Kyber-768-r3"}}; - case Group_Params::HYBRID_SECP521R1_KYBER_1024_R3_OQS: + case Group_Params_Code::HYBRID_SECP521R1_KYBER_1024_R3_OQS: return {{"ECDH", "secp521r1"}, {"Kyber", "Kyber-1024-r3"}}; default: @@ -74,19 +74,19 @@ std::vector public_value_lengths_for_group(Group_Params group) { // TODO: Find a way to expose important algorithm constants globally // in the library, to avoid violating the DRY principle. switch(group.code()) { - case Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE: - case Group_Params::HYBRID_X25519_KYBER_512_R3_OQS: + case Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE: + case Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS: return {32, 800}; - case Group_Params::HYBRID_X25519_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_X25519_KYBER_768_R3_OQS: return {32, 1184}; - case Group_Params::HYBRID_SECP256R1_KYBER_512_R3_OQS: + case Group_Params_Code::HYBRID_SECP256R1_KYBER_512_R3_OQS: return {32, 800}; - case Group_Params::HYBRID_SECP256R1_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_SECP256R1_KYBER_768_R3_OQS: return {32, 1184}; - case Group_Params::HYBRID_SECP384R1_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_SECP384R1_KYBER_768_R3_OQS: return {48, 1184}; - case Group_Params::HYBRID_SECP521R1_KYBER_1024_R3_OQS: + case Group_Params_Code::HYBRID_SECP521R1_KYBER_1024_R3_OQS: return {66, 1568}; default: @@ -97,7 +97,7 @@ std::vector public_value_lengths_for_group(Group_Params group) { } // namespace std::unique_ptr Hybrid_KEM_PublicKey::load_for_group( - Group_Params group, std::span concatenated_public_values) { + Group_Params group, Botan::span concatenated_public_values) { const auto public_value_lengths = public_value_lengths_for_group(group); auto alg_ids = algorithm_identifiers_for_group(group); BOTAN_ASSERT_NOMSG(public_value_lengths.size() == alg_ids.size()); @@ -226,8 +226,8 @@ class Hybrid_KEM_Encryption_Operation final : public PK_Ops::KEM_Encryption_with size_t encapsulated_key_length() const override { return m_encapsulated_key_length; } - void raw_kem_encrypt(std::span out_encapsulated_key, - std::span raw_shared_key, + void raw_kem_encrypt(Botan::span out_encapsulated_key, + Botan::span raw_shared_key, Botan::RandomNumberGenerator& rng) override { BOTAN_ASSERT_NOMSG(out_encapsulated_key.size() == encapsulated_key_length()); BOTAN_ASSERT_NOMSG(raw_shared_key.size() == raw_kem_shared_key_length()); @@ -334,7 +334,7 @@ class Hybrid_KEM_Decryption final : public PK_Ops::KEM_Decryption_with_KDF { } } - void raw_kem_decrypt(std::span out_shared_key, std::span encap_key) override { + void raw_kem_decrypt(Botan::span out_shared_key, Botan::span encap_key) override { BOTAN_ASSERT_NOMSG(out_shared_key.size() == raw_kem_shared_key_length()); BOTAN_ASSERT_NOMSG(encap_key.size() == encapsulated_key_length()); diff --git a/src/lib/tls/tls13_pqc/hybrid_public_key.h b/src/lib/tls/tls13_pqc/hybrid_public_key.h index 9dc00b156c6..1487f51c562 100644 --- a/src/lib/tls/tls13_pqc/hybrid_public_key.h +++ b/src/lib/tls/tls13_pqc/hybrid_public_key.h @@ -39,8 +39,8 @@ namespace Botan::TLS { */ class BOTAN_TEST_API Hybrid_KEM_PublicKey : public virtual Public_Key { public: - static std::unique_ptr load_for_group(Group_Params group, - std::span concatenated_public_values); + static std::unique_ptr load_for_group( + Group_Params group, Botan::span concatenated_public_values); public: explicit Hybrid_KEM_PublicKey(std::vector> pks); diff --git a/src/lib/tls/tls13_pqc/kex_to_kem_adapter.cpp b/src/lib/tls/tls13_pqc/kex_to_kem_adapter.cpp index 92226105707..bb372019813 100644 --- a/src/lib/tls/tls13_pqc/kex_to_kem_adapter.cpp +++ b/src/lib/tls/tls13_pqc/kex_to_kem_adapter.cpp @@ -158,8 +158,8 @@ class KEX_to_KEM_Adapter_Encryption_Operation final : public PK_Ops::KEM_Encrypt size_t encapsulated_key_length() const override { return kex_public_value(m_public_key).size(); } - void raw_kem_encrypt(std::span out_encapsulated_key, - std::span raw_shared_key, + void raw_kem_encrypt(Botan::span out_encapsulated_key, + Botan::span raw_shared_key, Botan::RandomNumberGenerator& rng) override { const auto sk = generate_key_agreement_private_key(m_public_key, rng); const auto shared_key = PK_Key_Agreement(*sk, rng, "Raw", m_provider) @@ -168,7 +168,7 @@ class KEX_to_KEM_Adapter_Encryption_Operation final : public PK_Ops::KEM_Encrypt const auto public_value = sk->public_value(); - // TODO: perhaps avoid these copies by providing std::span out-params + // TODO: perhaps avoid these copies by providing Botan::span out-params // for `PK_Key_Agreement::derive_key()` and // `PK_Key_Agreement_Key::public_value()` BOTAN_ASSERT_EQUAL(public_value.size(), @@ -195,7 +195,7 @@ class KEX_to_KEM_Decryption_Operation final : public PK_Ops::KEM_Decryption_with m_operation(key, rng, "Raw", provider), m_encapsulated_key_length(key.public_value().size()) {} - void raw_kem_decrypt(std::span out_shared_key, std::span encap_key) override { + void raw_kem_decrypt(Botan::span out_shared_key, Botan::span encap_key) override { secure_vector shared_secret = m_operation.derive_key(0 /* no KDF */, encap_key).bits_of(); BOTAN_ASSERT_EQUAL( shared_secret.size(), out_shared_key.size(), "KEX-to-KEM Adapter: shared key out-param has correct length"); diff --git a/src/lib/tls/tls_alert.cpp b/src/lib/tls/tls_alert.cpp index 234711a8913..75024554ac4 100644 --- a/src/lib/tls/tls_alert.cpp +++ b/src/lib/tls/tls_alert.cpp @@ -21,7 +21,7 @@ Alert::Alert(const secure_vector& buf) { } else if(buf[0] == 2) { m_fatal = true; } else { - throw TLS_Exception(Alert::IllegalParameter, "Bad code for TLS alert level"); + throw TLS_Exception(AlertType::IllegalParameter, "Bad code for TLS alert level"); } const uint8_t dc = buf[1]; diff --git a/src/lib/tls/tls_alert.h b/src/lib/tls/tls_alert.h index 61d7cbf6bb9..391c22e5c63 100644 --- a/src/lib/tls/tls_alert.h +++ b/src/lib/tls/tls_alert.h @@ -69,7 +69,6 @@ enum class AlertType { class BOTAN_PUBLIC_API(2, 0) Alert final { public: typedef AlertType Type; - using enum AlertType; /** * @return true iff this alert is non-empty diff --git a/src/lib/tls/tls_algos.cpp b/src/lib/tls/tls_algos.cpp index 41958402c0a..68004cf7502 100644 --- a/src/lib/tls/tls_algos.cpp +++ b/src/lib/tls/tls_algos.cpp @@ -136,75 +136,75 @@ Auth_Method auth_method_from_string(std::string_view str) { std::optional Group_Params::from_string(std::string_view group_name) { if(group_name == "secp256r1") { - return Group_Params::SECP256R1; + return Group_Params_Code::SECP256R1; } if(group_name == "secp384r1") { - return Group_Params::SECP384R1; + return Group_Params_Code::SECP384R1; } if(group_name == "secp521r1") { - return Group_Params::SECP521R1; + return Group_Params_Code::SECP521R1; } if(group_name == "brainpool256r1") { - return Group_Params::BRAINPOOL256R1; + return Group_Params_Code::BRAINPOOL256R1; } if(group_name == "brainpool384r1") { - return Group_Params::BRAINPOOL384R1; + return Group_Params_Code::BRAINPOOL384R1; } if(group_name == "brainpool512r1") { - return Group_Params::BRAINPOOL512R1; + return Group_Params_Code::BRAINPOOL512R1; } if(group_name == "x25519") { - return Group_Params::X25519; + return Group_Params_Code::X25519; } if(group_name == "ffdhe/ietf/2048") { - return Group_Params::FFDHE_2048; + return Group_Params_Code::FFDHE_2048; } if(group_name == "ffdhe/ietf/3072") { - return Group_Params::FFDHE_3072; + return Group_Params_Code::FFDHE_3072; } if(group_name == "ffdhe/ietf/4096") { - return Group_Params::FFDHE_4096; + return Group_Params_Code::FFDHE_4096; } if(group_name == "ffdhe/ietf/6144") { - return Group_Params::FFDHE_6144; + return Group_Params_Code::FFDHE_6144; } if(group_name == "ffdhe/ietf/8192") { - return Group_Params::FFDHE_8192; + return Group_Params_Code::FFDHE_8192; } if(group_name == "Kyber-512-r3") { - return Group_Params::KYBER_512_R3_OQS; + return Group_Params_Code::KYBER_512_R3_OQS; } if(group_name == "Kyber-768-r3") { - return Group_Params::KYBER_768_R3_OQS; + return Group_Params_Code::KYBER_768_R3_OQS; } if(group_name == "Kyber-1024-r3") { - return Group_Params::KYBER_1024_R3_OQS; + return Group_Params_Code::KYBER_1024_R3_OQS; } if(group_name == "x25519/Kyber-512-r3/cloudflare") { - return Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE; + return Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE; } if(group_name == "x25519/Kyber-512-r3") { - return Group_Params::HYBRID_X25519_KYBER_512_R3_OQS; + return Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS; } if(group_name == "x25519/Kyber-768-r3") { - return Group_Params::HYBRID_X25519_KYBER_768_R3_OQS; + return Group_Params_Code::HYBRID_X25519_KYBER_768_R3_OQS; } if(group_name == "secp256r1/Kyber-512-r3") { - return Group_Params::HYBRID_SECP256R1_KYBER_512_R3_OQS; + return Group_Params_Code::HYBRID_SECP256R1_KYBER_512_R3_OQS; } if(group_name == "secp256r1/Kyber-768-r3") { - return Group_Params::HYBRID_SECP256R1_KYBER_768_R3_OQS; + return Group_Params_Code::HYBRID_SECP256R1_KYBER_768_R3_OQS; } if(group_name == "secp384r1/Kyber-768-r3") { - return Group_Params::HYBRID_SECP384R1_KYBER_768_R3_OQS; + return Group_Params_Code::HYBRID_SECP384R1_KYBER_768_R3_OQS; } if(group_name == "secp521r1/Kyber-1024-r3") { - return Group_Params::HYBRID_SECP521R1_KYBER_1024_R3_OQS; + return Group_Params_Code::HYBRID_SECP521R1_KYBER_1024_R3_OQS; } return std::nullopt; @@ -212,54 +212,54 @@ std::optional Group_Params::from_string(std::string_view group_nam std::optional Group_Params::to_string() const { switch(m_code) { - case Group_Params::SECP256R1: + case Group_Params_Code::SECP256R1: return "secp256r1"; - case Group_Params::SECP384R1: + case Group_Params_Code::SECP384R1: return "secp384r1"; - case Group_Params::SECP521R1: + case Group_Params_Code::SECP521R1: return "secp521r1"; - case Group_Params::BRAINPOOL256R1: + case Group_Params_Code::BRAINPOOL256R1: return "brainpool256r1"; - case Group_Params::BRAINPOOL384R1: + case Group_Params_Code::BRAINPOOL384R1: return "brainpool384r1"; - case Group_Params::BRAINPOOL512R1: + case Group_Params_Code::BRAINPOOL512R1: return "brainpool512r1"; - case Group_Params::X25519: + case Group_Params_Code::X25519: return "x25519"; - case Group_Params::FFDHE_2048: + case Group_Params_Code::FFDHE_2048: return "ffdhe/ietf/2048"; - case Group_Params::FFDHE_3072: + case Group_Params_Code::FFDHE_3072: return "ffdhe/ietf/3072"; - case Group_Params::FFDHE_4096: + case Group_Params_Code::FFDHE_4096: return "ffdhe/ietf/4096"; - case Group_Params::FFDHE_6144: + case Group_Params_Code::FFDHE_6144: return "ffdhe/ietf/6144"; - case Group_Params::FFDHE_8192: + case Group_Params_Code::FFDHE_8192: return "ffdhe/ietf/8192"; - case Group_Params::KYBER_512_R3_OQS: + case Group_Params_Code::KYBER_512_R3_OQS: return "Kyber-512-r3"; - case Group_Params::KYBER_768_R3_OQS: + case Group_Params_Code::KYBER_768_R3_OQS: return "Kyber-768-r3"; - case Group_Params::KYBER_1024_R3_OQS: + case Group_Params_Code::KYBER_1024_R3_OQS: return "Kyber-1024-r3"; - case Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE: + case Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE: return "x25519/Kyber-512-r3/cloudflare"; - case Group_Params::HYBRID_X25519_KYBER_512_R3_OQS: + case Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS: return "x25519/Kyber-512-r3"; - case Group_Params::HYBRID_X25519_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_X25519_KYBER_768_R3_OQS: return "x25519/Kyber-768-r3"; - case Group_Params::HYBRID_SECP256R1_KYBER_512_R3_OQS: + case Group_Params_Code::HYBRID_SECP256R1_KYBER_512_R3_OQS: return "secp256r1/Kyber-512-r3"; - case Group_Params::HYBRID_SECP256R1_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_SECP256R1_KYBER_768_R3_OQS: return "secp256r1/Kyber-768-r3"; - case Group_Params::HYBRID_SECP384R1_KYBER_768_R3_OQS: + case Group_Params_Code::HYBRID_SECP384R1_KYBER_768_R3_OQS: return "secp384r1/Kyber-768-r3"; - case Group_Params::HYBRID_SECP521R1_KYBER_1024_R3_OQS: + case Group_Params_Code::HYBRID_SECP521R1_KYBER_1024_R3_OQS: return "secp521r1/Kyber-1024-r3"; default: diff --git a/src/lib/tls/tls_algos.h b/src/lib/tls/tls_algos.h index e3f84533817..0f6cecea680 100644 --- a/src/lib/tls/tls_algos.h +++ b/src/lib/tls/tls_algos.h @@ -123,8 +123,6 @@ enum class Group_Params_Code : uint16_t { class BOTAN_PUBLIC_API(3, 2) Group_Params final { public: - using enum Group_Params_Code; - constexpr Group_Params() : m_code(Group_Params_Code::NONE) {} constexpr Group_Params(Group_Params_Code code) : m_code(code) {} @@ -138,8 +136,12 @@ class BOTAN_PUBLIC_API(3, 2) Group_Params final { constexpr bool operator==(Group_Params_Code code) const { return m_code == code; } + constexpr bool operator!=(Group_Params_Code code) const { return !operator==(code); } + constexpr bool operator==(Group_Params other) const { return m_code == other.m_code; } + constexpr bool operator!=(Group_Params other) const { return !operator==(other); } + constexpr bool operator<(Group_Params other) const { return m_code < other.m_code; } constexpr Group_Params_Code code() const { return m_code; } @@ -170,7 +172,7 @@ class BOTAN_PUBLIC_API(3, 2) Group_Params final { constexpr bool is_post_quantum() const { return is_pure_kyber() || is_pqc_hybrid(); } constexpr bool is_pqc_hybrid() const { - return m_code == Group_Params::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE || + return m_code == Group_Params_Code::HYBRID_X25519_KYBER_512_R3_CLOUDFLARE || m_code == Group_Params_Code::HYBRID_X25519_KYBER_512_R3_OQS || m_code == Group_Params_Code::HYBRID_X25519_KYBER_768_R3_OQS || m_code == Group_Params_Code::HYBRID_SECP256R1_KYBER_512_R3_OQS || diff --git a/src/lib/tls/tls_callbacks.cpp b/src/lib/tls/tls_callbacks.cpp index faf0e82fb1a..7b82d954940 100644 --- a/src/lib/tls/tls_callbacks.cpp +++ b/src/lib/tls/tls_callbacks.cpp @@ -98,7 +98,7 @@ void TLS::Callbacks::tls_verify_cert_chain(const std::vector& ocsp_responses); if(!result.successful_validation()) { - throw TLS_Exception(Alert::BadCertificate, "Certificate validation failure: " + result.result_string()); + throw TLS_Exception(AlertType::BadCertificate, "Certificate validation failure: " + result.result_string()); } } @@ -175,7 +175,7 @@ KEM_Encapsulation TLS::Callbacks::tls_kem_encapsulate(TLS::Group_Params group, } #endif - throw TLS_Exception(Alert::IllegalParameter, "KEM is not supported"); + throw TLS_Exception(AlertType::IllegalParameter, "KEM is not supported"); }(); return PK_KEM_Encryptor(*kem_pub_key, "Raw").encrypt(rng); @@ -249,10 +249,10 @@ std::unique_ptr TLS::Callbacks::tls_generate_ephemeral_key #endif if(group_params.is_kem()) { - throw TLS_Exception(Alert::IllegalParameter, "cannot generate an ephemeral KEX key for a KEM"); + throw TLS_Exception(AlertType::IllegalParameter, "cannot generate an ephemeral KEX key for a KEM"); } - throw TLS_Exception(Alert::DecodeError, "cannot create a key offering without a group definition"); + throw TLS_Exception(AlertType::DecodeError, "cannot create a key offering without a group definition"); } secure_vector TLS::Callbacks::tls_ephemeral_key_agreement( @@ -280,7 +280,7 @@ secure_vector TLS::Callbacks::tls_ephemeral_key_agreement( * advantage to bogus keys anyway. */ if(Y <= 1 || Y >= dl_group.get_p() - 1) { - throw TLS_Exception(Alert::IllegalParameter, "Server sent bad DH key for DHE exchange"); + throw TLS_Exception(AlertType::IllegalParameter, "Server sent bad DH key for DHE exchange"); } DH_PublicKey peer_key(dl_group, Y); @@ -303,7 +303,7 @@ secure_vector TLS::Callbacks::tls_ephemeral_key_agreement( #if defined(BOTAN_HAS_CURVE_25519) if(group_params.is_x25519()) { if(public_value.size() != 32) { - throw TLS_Exception(Alert::HandshakeFailure, "Invalid X25519 key size"); + throw TLS_Exception(AlertType::HandshakeFailure, "Invalid X25519 key size"); } Curve25519_PublicKey peer_key(public_value); @@ -313,7 +313,7 @@ secure_vector TLS::Callbacks::tls_ephemeral_key_agreement( } #endif - throw TLS_Exception(Alert::IllegalParameter, "Did not recognize the key exchange group"); + throw TLS_Exception(AlertType::IllegalParameter, "Did not recognize the key exchange group"); } } // namespace Botan diff --git a/src/lib/tls/tls_callbacks.h b/src/lib/tls/tls_callbacks.h index 51f78875792..2529b6f17df 100644 --- a/src/lib/tls/tls_callbacks.h +++ b/src/lib/tls/tls_callbacks.h @@ -54,7 +54,7 @@ class BOTAN_PUBLIC_API(2, 0) Callbacks { * * @param data a contiguous data buffer to send */ - virtual void tls_emit_data(std::span data) = 0; + virtual void tls_emit_data(Botan::span data) = 0; /** * Mandatory callback: process application data @@ -65,7 +65,7 @@ class BOTAN_PUBLIC_API(2, 0) Callbacks { * * @param data a contiguous data buffer containing the received record */ - virtual void tls_record_received(uint64_t seq_no, std::span data) = 0; + virtual void tls_record_received(uint64_t seq_no, Botan::span data) = 0; /** * Mandatory callback: alert received @@ -354,7 +354,7 @@ class BOTAN_PUBLIC_API(2, 0) Callbacks { * security risks are associated with customizing TLS's key exchange * mechanism. * - * @throws TLS_Exception(Alert::DecodeError) if the @p group is not known. + * @throws TLS_Exception(AlertType::DecodeError) if the @p group is not known. * * @param group the group identifier to generate an ephemeral keypair for * TLS 1.2 allows for specifying custom discrete logarithm @@ -416,7 +416,7 @@ class BOTAN_PUBLIC_API(2, 0) Callbacks { * protocol to use. RFC 7301 requires that if the server does not support * any protocols offered by the client, then it should close the connection * with an alert of no_application_protocol. Within this callback this would - * be done by throwing a TLS_Exception(Alert::NoApplicationProtocol) + * be done by throwing a TLS_Exception(AlertType::NoApplicationProtocol) * * @param client_protos the vector of protocols the client is willing to negotiate * diff --git a/src/lib/tls/tls_channel.h b/src/lib/tls/tls_channel.h index 6819cfb9ced..6a9306557c4 100644 --- a/src/lib/tls/tls_channel.h +++ b/src/lib/tls/tls_channel.h @@ -16,8 +16,8 @@ #include #include #include +#include -#include #include #include #include @@ -34,8 +34,8 @@ class BOTAN_PUBLIC_API(2, 0) Channel { virtual ~Channel() = default; protected: - virtual size_t from_peer(std::span data) = 0; - virtual void to_peer(std::span data) = 0; + virtual size_t from_peer(Botan::span data) = 0; + virtual void to_peer(Botan::span data) = 0; public: /** @@ -43,23 +43,23 @@ class BOTAN_PUBLIC_API(2, 0) Channel { * @return a hint as to how many more bytes we need to process the * current record (this may be 0 if on a record boundary) */ - size_t received_data(std::span data) { return this->from_peer(data); } + size_t received_data(Botan::span data) { return this->from_peer(data); } - size_t received_data(const uint8_t buf[], size_t buf_size) { return this->from_peer(std::span(buf, buf_size)); } + size_t received_data(const uint8_t buf[], size_t buf_size) { return this->from_peer(Botan::span(buf, buf_size)); } /** * Inject plaintext intended for counterparty * Throws an exception if is_active() is false */ - void send(std::span data) { this->to_peer(data); } + void send(Botan::span data) { this->to_peer(data); } - void send(const uint8_t buf[], size_t buf_size) { this->to_peer(std::span(buf, buf_size)); } + void send(const uint8_t buf[], size_t buf_size) { this->to_peer(Botan::span(buf, buf_size)); } /** * Inject plaintext intended for counterparty * Throws an exception if is_active() is false */ - void send(std::string_view val) { this->send(std::span(cast_char_ptr_to_uint8(val.data()), val.size())); } + void send(std::string_view val) { this->send(Botan::span(cast_char_ptr_to_uint8(val.data()), val.size())); } /** * Inject plaintext intended for counterparty diff --git a/src/lib/tls/tls_channel_impl.h b/src/lib/tls/tls_channel_impl.h index b9bf8bc5078..f8a2834ce45 100644 --- a/src/lib/tls/tls_channel_impl.h +++ b/src/lib/tls/tls_channel_impl.h @@ -49,13 +49,13 @@ class Channel_Impl { * @return a hint as the how many more bytes we need to q the * current record (this may be 0 if on a record boundary) */ - virtual size_t from_peer(std::span data) = 0; + virtual size_t from_peer(Botan::span data) = 0; /** * Inject plaintext intended for counterparty * Throws an exception if is_active() is false */ - virtual void to_peer(std::span data) = 0; + virtual void to_peer(Botan::span data) = 0; /** * Send a TLS alert message. If the alert is fatal, the internal @@ -77,7 +77,7 @@ class Channel_Impl { /** * Send a close notification alert */ - void close() { send_warning_alert(Alert::CloseNotify); } + void close() { send_warning_alert(AlertType::CloseNotify); } /** * @return true iff the connection is active for sending application data @@ -213,12 +213,12 @@ class Channel_Impl { std::unique_ptr m_downgrade_info; - void preserve_peer_transcript(std::span input) { + void preserve_peer_transcript(Botan::span input) { BOTAN_STATE_CHECK(m_downgrade_info); m_downgrade_info->peer_transcript.insert(m_downgrade_info->peer_transcript.end(), input.begin(), input.end()); } - void preserve_client_hello(std::span msg) { + void preserve_client_hello(Botan::span msg) { BOTAN_STATE_CHECK(m_downgrade_info); m_downgrade_info->client_hello_message.assign(msg.begin(), msg.end()); } diff --git a/src/lib/tls/tls_client.cpp b/src/lib/tls/tls_client.cpp index 6fbb7504053..2059e92c65c 100644 --- a/src/lib/tls/tls_client.cpp +++ b/src/lib/tls/tls_client.cpp @@ -40,7 +40,7 @@ Client::Client(const std::shared_ptr& callbacks, "Policy does not allow to offer requested protocol version"); #if defined(BOTAN_HAS_TLS_13) - if(offer_version == Protocol_Version::TLS_V13) { + if(offer_version == Version_Code::TLS_V13) { m_impl = std::make_unique( callbacks, session_manager, creds, policy, rng, std::move(info), next_protocols); @@ -87,7 +87,7 @@ size_t Client::downgrade() { } } -size_t Client::from_peer(std::span data) { +size_t Client::from_peer(Botan::span data) { auto read = m_impl->from_peer(data); if(m_impl->is_downgrading()) { @@ -137,7 +137,7 @@ bool Client::secure_renegotiation_supported() const { return m_impl->secure_renegotiation_supported(); } -void Client::to_peer(std::span data) { +void Client::to_peer(Botan::span data) { m_impl->to_peer(data); } diff --git a/src/lib/tls/tls_client.h b/src/lib/tls/tls_client.h index 918e87eb881..63b79fd3e04 100644 --- a/src/lib/tls/tls_client.h +++ b/src/lib/tls/tls_client.h @@ -69,7 +69,7 @@ class BOTAN_PUBLIC_API(2, 0) Client final : public Channel { */ std::string application_protocol() const override; - size_t from_peer(std::span data) override; + size_t from_peer(Botan::span data) override; bool is_active() const override; bool is_closed() const override; @@ -89,7 +89,7 @@ class BOTAN_PUBLIC_API(2, 0) Client final : public Channel { bool secure_renegotiation_supported() const override; - void to_peer(std::span data) override; + void to_peer(Botan::span data) override; void send_alert(const Alert& alert) override; diff --git a/src/lib/tls/tls_extensions.cpp b/src/lib/tls/tls_extensions.cpp index 19aadae146d..32de13fe0bc 100644 --- a/src/lib/tls/tls_extensions.cpp +++ b/src/lib/tls/tls_extensions.cpp @@ -124,7 +124,7 @@ void Extensions::deserialize(TLS_Data_Reader& reader, const Connection_Side from const auto type = static_cast(extension_code); if(this->has(type)) { - throw TLS_Exception(TLS::Alert::DecodeError, "Peer sent duplicated extensions"); + throw TLS_Exception(TLS::AlertType::DecodeError, "Peer sent duplicated extensions"); } // TODO offer a function on reader that returns a byte range as a reference @@ -328,7 +328,7 @@ Application_Layer_Protocol_Notification::Application_Layer_Protocol_Notification // the "ProtocolNameList" MUST contain exactly one "ProtocolName". if(from == Connection_Side::Server && m_protocols.size() != 1) { throw TLS_Exception( - Alert::DecodeError, + AlertType::DecodeError, "Server sent " + std::to_string(m_protocols.size()) + " protocols in ALPN extension response"); } } @@ -343,7 +343,7 @@ std::vector Application_Layer_Protocol_Notification::serialize(Connecti for(auto&& p : m_protocols) { if(p.length() >= 256) { - throw TLS_Exception(Alert::InternalError, "ALPN name too long"); + throw TLS_Exception(AlertType::InternalError, "ALPN name too long"); } if(!p.empty()) { append_tls_length_value(buf, cast_char_ptr_to_uint8(p.data()), p.size(), 1); @@ -466,7 +466,7 @@ Supported_Point_Formats::Supported_Point_Formats(TLS_Data_Reader& reader, uint16 // RFC 8422 5.1.2. explicitly requires this check, // but only if the Supported Groups extension was sent. if(!includes_uncompressed) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "Supported Point Formats Extension must contain the uncompressed point format"); } } @@ -602,19 +602,19 @@ std::vector Supported_Versions::serialize(Connection_Side whoami) const Supported_Versions::Supported_Versions(Protocol_Version offer, const Policy& policy) { if(offer.is_datagram_protocol()) { #if defined(BOTAN_HAS_TLS_12) - if(offer >= Protocol_Version::DTLS_V12 && policy.allow_dtls12()) { - m_versions.push_back(Protocol_Version::DTLS_V12); + if(offer >= Version_Code::DTLS_V12 && policy.allow_dtls12()) { + m_versions.push_back(Version_Code::DTLS_V12); } #endif } else { #if defined(BOTAN_HAS_TLS_13) - if(offer >= Protocol_Version::TLS_V13 && policy.allow_tls13()) { - m_versions.push_back(Protocol_Version::TLS_V13); + if(offer >= Version_Code::TLS_V13 && policy.allow_tls13()) { + m_versions.push_back(Version_Code::TLS_V13); } #endif #if defined(BOTAN_HAS_TLS_12) - if(offer >= Protocol_Version::TLS_V12 && policy.allow_tls12()) { - m_versions.push_back(Protocol_Version::TLS_V12); + if(offer >= Version_Code::TLS_V12 && policy.allow_tls12()) { + m_versions.push_back(Version_Code::TLS_V12); } #endif } @@ -656,7 +656,7 @@ Record_Size_Limit::Record_Size_Limit(const uint16_t limit) : m_limit(limit) { Record_Size_Limit::Record_Size_Limit(TLS_Data_Reader& reader, uint16_t extension_size, Connection_Side from) { if(extension_size != 2) { - throw TLS_Exception(Alert::DecodeError, "invalid record_size_limit extension"); + throw TLS_Exception(AlertType::DecodeError, "invalid record_size_limit extension"); } m_limit = reader.get_uint16_t(); @@ -675,7 +675,7 @@ Record_Size_Limit::Record_Size_Limit(TLS_Data_Reader& reader, uint16_t extension // we check for the TLS 1.3 limit. The TLS 1.2 limit would not include // the "content type byte" and hence be one byte less! if(m_limit > MAX_PLAINTEXT_SIZE + 1 /* encrypted content type byte */ && from == Connection_Side::Server) { - throw TLS_Exception(Alert::IllegalParameter, + throw TLS_Exception(AlertType::IllegalParameter, "Server requested a record size limit larger than the protocol's maximum"); } @@ -684,7 +684,7 @@ Record_Size_Limit::Record_Size_Limit(TLS_Data_Reader& reader, uint16_t extension // smaller than 64. An endpoint MUST treat receipt of a smaller value // as a fatal error and generate an "illegal_parameter" alert. if(m_limit < 64) { - throw TLS_Exception(Alert::IllegalParameter, "Received a record size limit smaller than 64 bytes"); + throw TLS_Exception(AlertType::IllegalParameter, "Received a record size limit smaller than 64 bytes"); } } @@ -818,14 +818,14 @@ EarlyDataIndication::EarlyDataIndication(TLS_Data_Reader& reader, Handshake_Type message_type) { if(message_type == Handshake_Type::NewSessionTicket) { if(extension_size != 4) { - throw TLS_Exception(Alert::DecodeError, + throw TLS_Exception(AlertType::DecodeError, "Received an early_data extension in a NewSessionTicket message " "without maximum early data size indication"); } m_max_early_data_size = reader.get_uint32_t(); } else if(extension_size != 0) { - throw TLS_Exception(Alert::DecodeError, + throw TLS_Exception(AlertType::DecodeError, "Received an early_data extension containing an unexpected data " "size indication"); } diff --git a/src/lib/tls/tls_extensions_cert_status_req.cpp b/src/lib/tls/tls_extensions_cert_status_req.cpp index 1cf2a19cc14..4924b09b32a 100644 --- a/src/lib/tls/tls_extensions_cert_status_req.cpp +++ b/src/lib/tls/tls_extensions_cert_status_req.cpp @@ -142,7 +142,7 @@ Certificate_Status_Request::Certificate_Status_Request(TLS_Data_Reader& reader, // all other contexts are not allowed for this extension else { - throw TLS_Exception(Alert::UnsupportedExtension, + throw TLS_Exception(AlertType::UnsupportedExtension, "Server sent a Certificate_Status_Request extension in an unsupported context"); } } diff --git a/src/lib/tls/tls_handshake_transitions.cpp b/src/lib/tls/tls_handshake_transitions.cpp index 25a653affec..2bc7ac22a03 100644 --- a/src/lib/tls/tls_handshake_transitions.cpp +++ b/src/lib/tls/tls_handshake_transitions.cpp @@ -80,7 +80,7 @@ uint32_t bitmask_for_handshake_type(Handshake_Type type) { return 0; } - throw TLS_Exception(Alert::UnexpectedMessage, + throw TLS_Exception(AlertType::UnexpectedMessage, "Unknown TLS handshake message type " + std::to_string(static_cast(type))); } diff --git a/src/lib/tls/tls_policy.cpp b/src/lib/tls/tls_policy.cpp index deb8bbcde88..6090aa8d706 100644 --- a/src/lib/tls/tls_policy.cpp +++ b/src/lib/tls/tls_policy.cpp @@ -118,7 +118,7 @@ bool Policy::use_ecc_point_compression() const { Group_Params Policy::choose_key_exchange_group(const std::vector& supported_by_peer, const std::vector& offered_by_peer) const { if(supported_by_peer.empty()) { - return Group_Params::NONE; + return Group_Params_Code::NONE; } const std::vector our_groups = key_exchange_groups(); @@ -139,7 +139,7 @@ Group_Params Policy::choose_key_exchange_group(const std::vector& } } - return Group_Params::NONE; + return Group_Params_Code::NONE; } Group_Params Policy::default_dh_group() const { @@ -152,21 +152,28 @@ Group_Params Policy::default_dh_group() const { } } - return Group_Params::FFDHE_2048; + return Group_Params_Code::FFDHE_2048; } std::vector Policy::key_exchange_groups() const { // Default list is ordered by performance return { #if defined(BOTAN_HAS_CURVE_25519) - Group_Params::X25519, + Group_Params_Code::X25519, #endif - Group_Params::SECP256R1, Group_Params::BRAINPOOL256R1, Group_Params::SECP384R1, Group_Params::BRAINPOOL384R1, - Group_Params::SECP521R1, Group_Params::BRAINPOOL512R1, - - Group_Params::FFDHE_2048, Group_Params::FFDHE_3072, Group_Params::FFDHE_4096, Group_Params::FFDHE_6144, - Group_Params::FFDHE_8192, + Group_Params_Code::SECP256R1, + Group_Params_Code::BRAINPOOL256R1, + Group_Params_Code::SECP384R1, + Group_Params_Code::BRAINPOOL384R1, + Group_Params_Code::SECP521R1, + Group_Params_Code::BRAINPOOL512R1, + + Group_Params_Code::FFDHE_2048, + Group_Params_Code::FFDHE_3072, + Group_Params_Code::FFDHE_4096, + Group_Params_Code::FFDHE_6144, + Group_Params_Code::FFDHE_8192, }; } @@ -231,7 +238,7 @@ void Policy::check_peer_key_acceptable(const Public_Key& public_key) const { // else some other algo, so leave expected_keylength as zero and the check is a no-op if(keylength < expected_keylength) { - throw TLS_Exception(Alert::InsufficientSecurity, + throw TLS_Exception(AlertType::InsufficientSecurity, "Peer sent " + std::to_string(keylength) + " bit " + algo_name + " key" ", policy requires at least " + @@ -244,7 +251,7 @@ size_t Policy::maximum_session_tickets_per_client_hello() const { } std::chrono::seconds Policy::session_ticket_lifetime() const { - return std::chrono::days(1); + return std::chrono::seconds(86400); } bool Policy::reuse_session_tickets() const { @@ -257,17 +264,17 @@ size_t Policy::new_session_tickets_upon_handshake_success() const { bool Policy::acceptable_protocol_version(Protocol_Version version) const { #if defined(BOTAN_HAS_TLS_13) - if(version == Protocol_Version::TLS_V13 && allow_tls13()) { + if(version == Version_Code::TLS_V13 && allow_tls13()) { return true; } #endif #if defined(BOTAN_HAS_TLS_12) - if(version == Protocol_Version::TLS_V12 && allow_tls12()) { + if(version == Version_Code::TLS_V12 && allow_tls12()) { return true; } - if(version == Protocol_Version::DTLS_V12 && allow_dtls12()) { + if(version == Version_Code::DTLS_V12 && allow_dtls12()) { return true; } #endif @@ -277,18 +284,18 @@ bool Policy::acceptable_protocol_version(Protocol_Version version) const { Protocol_Version Policy::latest_supported_version(bool datagram) const { if(datagram) { - if(acceptable_protocol_version(Protocol_Version::DTLS_V12)) { - return Protocol_Version::DTLS_V12; + if(acceptable_protocol_version(Version_Code::DTLS_V12)) { + return Version_Code::DTLS_V12; } throw Invalid_State("Policy forbids all available DTLS version"); } else { #if defined(BOTAN_HAS_TLS_13) - if(acceptable_protocol_version(Protocol_Version::TLS_V13)) { - return Protocol_Version::TLS_V13; + if(acceptable_protocol_version(Version_Code::TLS_V13)) { + return Version_Code::TLS_V13; } #endif - if(acceptable_protocol_version(Protocol_Version::TLS_V12)) { - return Protocol_Version::TLS_V12; + if(acceptable_protocol_version(Version_Code::TLS_V12)) { + return Version_Code::TLS_V12; } throw Invalid_State("Policy forbids all available TLS version"); } diff --git a/src/lib/tls/tls_policy.h b/src/lib/tls/tls_policy.h index 75d4a4b3adf..63d443faf27 100644 --- a/src/lib/tls/tls_policy.h +++ b/src/lib/tls/tls_policy.h @@ -122,7 +122,7 @@ class BOTAN_PUBLIC_API(2, 0) Policy { * peer. In TLS 1.3 handshakes the peer might have provided cryptographic material * for a subset of its available groups. Choosing a group for which no share was * provided will result in an additional round trip. If none are acceptable, return - * Group_Params::NONE. + * Group_Params_Code::NONE. * * By default this will try to optimize for less round trips even if this results * in the usage of a less preferred group. @@ -467,7 +467,7 @@ class BOTAN_PUBLIC_API(2, 0) NSA_Suite_B_128 : public Policy { return std::vector({"ECDSA"}); } - std::vector key_exchange_groups() const override { return {Group_Params::SECP256R1}; } + std::vector key_exchange_groups() const override { return {Group_Params_Code::SECP256R1}; } size_t minimum_signature_strength() const override { return 128; } @@ -499,7 +499,7 @@ class BOTAN_PUBLIC_API(2, 7) NSA_Suite_B_192 : public Policy { return std::vector({"ECDSA"}); } - std::vector key_exchange_groups() const override { return {Group_Params::SECP384R1}; } + std::vector key_exchange_groups() const override { return {Group_Params_Code::SECP384R1}; } size_t minimum_signature_strength() const override { return 192; } @@ -537,14 +537,14 @@ class BOTAN_PUBLIC_API(2, 0) BSI_TR_02102_2 : public Policy { } std::vector key_exchange_groups() const override { - return std::vector({Group_Params::BRAINPOOL512R1, - Group_Params::BRAINPOOL384R1, - Group_Params::BRAINPOOL256R1, - Group_Params::SECP384R1, - Group_Params::SECP256R1, - Group_Params::FFDHE_4096, - Group_Params::FFDHE_3072, - Group_Params::FFDHE_2048}); + return std::vector({Group_Params_Code::BRAINPOOL512R1, + Group_Params_Code::BRAINPOOL384R1, + Group_Params_Code::BRAINPOOL256R1, + Group_Params_Code::SECP384R1, + Group_Params_Code::SECP256R1, + Group_Params_Code::FFDHE_4096, + Group_Params_Code::FFDHE_3072, + Group_Params_Code::FFDHE_2048}); } bool allow_insecure_renegotiation() const override { return false; } diff --git a/src/lib/tls/tls_reader.h b/src/lib/tls/tls_reader.h index 2f557492f68..8a10d38c6f0 100644 --- a/src/lib/tls/tls_reader.h +++ b/src/lib/tls/tls_reader.h @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include @@ -23,7 +23,7 @@ namespace Botan::TLS { */ class TLS_Data_Reader final { public: - TLS_Data_Reader(const char* type, std::span buf_in) : + TLS_Data_Reader(const char* type, Botan::span buf_in) : m_typename(type), m_buf(buf_in), m_offset(0) {} void assert_done() const { @@ -169,7 +169,7 @@ class TLS_Data_Reader final { } const char* m_typename; - std::span m_buf; + Botan::span m_buf; size_t m_offset; }; diff --git a/src/lib/tls/tls_server.cpp b/src/lib/tls/tls_server.cpp index 1993e418fb5..4043bebab27 100644 --- a/src/lib/tls/tls_server.cpp +++ b/src/lib/tls/tls_server.cpp @@ -51,7 +51,7 @@ Server::Server(const std::shared_ptr& callbacks, Server::~Server() = default; -size_t Server::from_peer(std::span data) { +size_t Server::from_peer(Botan::span data) { auto read = m_impl->from_peer(data); if(m_impl->is_downgrading()) { @@ -113,7 +113,7 @@ bool Server::secure_renegotiation_supported() const { return m_impl->secure_renegotiation_supported(); } -void Server::to_peer(std::span data) { +void Server::to_peer(Botan::span data) { m_impl->to_peer(data); } diff --git a/src/lib/tls/tls_server.h b/src/lib/tls/tls_server.h index 9e29bdfaad8..4eb9ada0949 100644 --- a/src/lib/tls/tls_server.h +++ b/src/lib/tls/tls_server.h @@ -64,7 +64,7 @@ class BOTAN_PUBLIC_API(2, 0) Server final : public Channel { */ std::string application_protocol() const override; - size_t from_peer(std::span data) override; + size_t from_peer(Botan::span data) override; bool is_active() const override; @@ -88,7 +88,7 @@ class BOTAN_PUBLIC_API(2, 0) Server final : public Channel { bool secure_renegotiation_supported() const override; - void to_peer(std::span data) override; + void to_peer(Botan::span data) override; void send_alert(const Alert& alert) override; diff --git a/src/lib/tls/tls_session.cpp b/src/lib/tls/tls_session.cpp index f8bb229fd6c..e9473eca4d8 100644 --- a/src/lib/tls/tls_session.cpp +++ b/src/lib/tls/tls_session.cpp @@ -270,7 +270,7 @@ Session::Session(secure_vector&& session_psk, Session::Session(std::string_view pem) : Session(PEM_Code::decode_check_label(pem, "TLS SESSION")) {} -Session::Session(std::span ber_data) { +Session::Session(Botan::span ber_data) { uint8_t side_code = 0; ASN1_String server_hostname; @@ -429,7 +429,7 @@ std::vector Session::encrypt(const SymmetricKey& key, RandomNumberGener return buf; } -Session Session::decrypt(std::span in, const SymmetricKey& key) { +Session Session::decrypt(Botan::span in, const SymmetricKey& key) { try { const size_t min_session_size = 48 + 4; // serious under-estimate if(in.size() < TLS_SESSION_CRYPT_OVERHEAD + min_session_size) { diff --git a/src/lib/tls/tls_session.h b/src/lib/tls/tls_session.h index fde753855ff..8e2efe835f3 100644 --- a/src/lib/tls/tls_session.h +++ b/src/lib/tls/tls_session.h @@ -17,10 +17,10 @@ #include #include #include +#include #include #include -#include #include namespace Botan::TLS { @@ -368,7 +368,7 @@ class BOTAN_PUBLIC_API(3, 0) Session final : public Session_Base { * Load a session from DER representation (created by DER_encode) * @param ber_data DER representation buffer */ - Session(std::span ber_data); + Session(Botan::span ber_data); /** * Load a session from PEM representation (created by PEM_encode) @@ -395,7 +395,7 @@ class BOTAN_PUBLIC_API(3, 0) Session final : public Session_Base { * @param key the same key used by the encrypting side */ static inline Session decrypt(const uint8_t ctext[], size_t ctext_size, const SymmetricKey& key) { - return Session::decrypt(std::span(ctext, ctext_size), key); + return Session::decrypt(Botan::span(ctext, ctext_size), key); } /** @@ -403,7 +403,7 @@ class BOTAN_PUBLIC_API(3, 0) Session final : public Session_Base { * @param ctext the ciphertext returned by encrypt * @param key the same key used by the encrypting side */ - static Session decrypt(std::span ctext, const SymmetricKey& key); + static Session decrypt(Botan::span ctext, const SymmetricKey& key); /** * Encode this session data for storage diff --git a/src/lib/tls/tls_session_manager.cpp b/src/lib/tls/tls_session_manager.cpp index 3b73a347a36..ded4b055658 100644 --- a/src/lib/tls/tls_session_manager.cpp +++ b/src/lib/tls/tls_session_manager.cpp @@ -211,7 +211,8 @@ std::optional> Session_Manager::choose_from_offered // Note that the TLS server currently does not ensure that tickets aren't // reused. As a result, no locking is required on this level. - for(uint16_t i = 0; const auto& ticket : tickets) { + uint16_t i = 0U; + for(const auto& ticket : tickets) { auto session = retrieve(Opaque_Session_Handle(ticket.identity()), callbacks, policy); if(session.has_value() && session->ciphersuite().prf_algo() == hash_function && session->version().is_tls_13_or_later()) { diff --git a/src/lib/tls/tls_session_manager_memory.cpp b/src/lib/tls/tls_session_manager_memory.cpp index 7d1543a2181..1ff4aa35220 100644 --- a/src/lib/tls/tls_session_manager_memory.cpp +++ b/src/lib/tls/tls_session_manager_memory.cpp @@ -10,6 +10,7 @@ #include #include +#include #include @@ -97,7 +98,7 @@ size_t Session_Manager_In_Memory::remove_internal(const Session_Handle& handle) // Unfortunately, at the time of this writing Android NDK shipped with // a std::erase_if that returns void. Hence, the workaround. const auto before = m_sessions.size(); - std::erase_if(m_sessions, [&](const auto& item) { + Botan::erase_if(m_sessions, [&](const auto& item) { const auto& [_unused1, session_and_handle] = item; const auto& [_unused2, this_handle] = session_and_handle; return this_handle.is_ticket() && this_handle.ticket().value() == ticket; diff --git a/src/lib/tls/tls_text_policy.cpp b/src/lib/tls/tls_text_policy.cpp index cd5ac16eef1..7a544964263 100644 --- a/src/lib/tls/tls_text_policy.cpp +++ b/src/lib/tls/tls_text_policy.cpp @@ -217,14 +217,14 @@ std::vector Text_Policy::get_list(const std::string& key, const std std::vector Text_Policy::read_group_list(std::string_view group_str) const { std::vector groups; for(const auto& group_name : split_on(group_str, ' ')) { - Group_Params group_id = Group_Params::from_string(group_name).value_or(Group_Params::NONE); + Group_Params group_id = Group_Params::from_string(group_name).value_or(Group_Params_Code::NONE); #if !defined(BOTAN_HAS_CURVE_25519) - if(group_id == Group_Params::X25519) + if(group_id == Group_Params_Code::X25519) continue; #endif - if(group_id == Group_Params::NONE) { + if(group_id == Group_Params_Code::NONE) { try { size_t consumed = 0; unsigned long ll_id = std::stoul(group_name, &consumed, 0); @@ -244,7 +244,7 @@ std::vector Text_Policy::read_group_list(std::string_view group_st } } - if(group_id != Group_Params::NONE) { + if(group_id != Group_Params_Code::NONE) { groups.push_back(group_id); } } diff --git a/src/lib/tls/tls_version.cpp b/src/lib/tls/tls_version.cpp index 0f031366109..e784540c032 100644 --- a/src/lib/tls/tls_version.cpp +++ b/src/lib/tls/tls_version.cpp @@ -38,18 +38,18 @@ bool Protocol_Version::is_datagram_protocol() const { } bool Protocol_Version::is_pre_tls_13() const { - return (!is_datagram_protocol() && *this <= Protocol_Version::TLS_V12) || - (is_datagram_protocol() && *this <= Protocol_Version::DTLS_V12); + return (!is_datagram_protocol() && *this <= Version_Code::TLS_V12) || + (is_datagram_protocol() && *this <= Version_Code::DTLS_V12); } bool Protocol_Version::is_tls_13_or_later() const { - return (!is_datagram_protocol() && *this >= Protocol_Version::TLS_V13) || - (is_datagram_protocol() && *this >= Protocol_Version::DTLS_V13); + return (!is_datagram_protocol() && *this >= Version_Code::TLS_V13) || + (is_datagram_protocol() && *this >= Version_Code::DTLS_V13); } bool Protocol_Version::operator>(const Protocol_Version& other) const { if(this->is_datagram_protocol() != other.is_datagram_protocol()) { - throw TLS_Exception(Alert::ProtocolVersion, "Version comparing " + to_string() + " with " + other.to_string()); + throw TLS_Exception(AlertType::ProtocolVersion, "Version comparing " + to_string() + " with " + other.to_string()); } if(this->is_datagram_protocol()) { @@ -82,11 +82,11 @@ bool Protocol_Version::valid() const { } bool Protocol_Version::known_version() const { - return (m_version == static_cast(Protocol_Version::TLS_V12) || + return (m_version == static_cast(Version_Code::TLS_V12) || #if defined(BOTAN_HAS_TLS_13) - m_version == static_cast(Protocol_Version::TLS_V13) || + m_version == static_cast(Version_Code::TLS_V13) || #endif - m_version == static_cast(Protocol_Version::DTLS_V12)); + m_version == static_cast(Version_Code::DTLS_V12)); } } // namespace Botan::TLS diff --git a/src/lib/tls/tls_version.h b/src/lib/tls/tls_version.h index 880cae422da..66c9590a048 100644 --- a/src/lib/tls/tls_version.h +++ b/src/lib/tls/tls_version.h @@ -28,23 +28,23 @@ enum class Version_Code : uint16_t { */ class BOTAN_PUBLIC_API(2, 0) Protocol_Version final { public: - using enum Version_Code; + //using enum Version_Code; /** * @return latest known TLS version */ static Protocol_Version latest_tls_version() { #if defined(BOTAN_HAS_TLS_13) - return Protocol_Version(TLS_V13); + return Protocol_Version(Version_Code::TLS_V13); #else - return Protocol_Version(TLS_V12); + return Protocol_Version(Version_Code::TLS_V12); #endif } /** * @return latest known DTLS version */ - static Protocol_Version latest_dtls_version() { return Protocol_Version(DTLS_V12); } + static Protocol_Version latest_dtls_version() { return Protocol_Version(Version_Code::DTLS_V12); } Protocol_Version() : m_version(0) {} diff --git a/src/lib/utils/alignment_buffer.h b/src/lib/utils/alignment_buffer.h index 64b7bec1c68..a3e00f9ac8c 100644 --- a/src/lib/utils/alignment_buffer.h +++ b/src/lib/utils/alignment_buffer.h @@ -55,8 +55,8 @@ enum class AlignmentBufferFinalBlock : size_t { */ template - requires(BLOCK_SIZE > 0) + AlignmentBufferFinalBlock FINAL_BLOCK_STRATEGY = AlignmentBufferFinalBlock::is_not_special, + typename = std::enable_if_t<(BLOCK_SIZE > 0)>> class AlignmentBuffer { public: AlignmentBuffer() : m_position(0) {} @@ -87,7 +87,7 @@ class AlignmentBuffer { * Appends the provided @p elements to the buffer. The user has to make * sure that @p elements fits in the remaining capacity of the buffer. */ - void append(std::span elements) { + void append(Botan::span elements) { BOTAN_ASSERT_NOMSG(elements.size() <= elements_until_alignment()); std::copy(elements.begin(), elements.end(), m_buffer.begin() + m_position); m_position += elements.size(); @@ -99,9 +99,9 @@ class AlignmentBuffer { * capacity into account nor does it change the internal cursor. * Beware not to overwrite unconsumed bytes. */ - std::span directly_modify_first(size_t elements) { + Botan::span directly_modify_first(size_t elements) { BOTAN_ASSERT_NOMSG(size() >= elements); - return std::span(m_buffer).first(elements); + return Botan::span(m_buffer).first(elements); } /** @@ -110,9 +110,9 @@ class AlignmentBuffer { * capacity into account nor does it change the internal cursor. * Beware not to overwrite unconsumed bytes. */ - std::span directly_modify_last(size_t elements) { + Botan::span directly_modify_last(size_t elements) { BOTAN_ASSERT_NOMSG(size() >= elements); - return std::span(m_buffer).last(elements); + return Botan::span(m_buffer).last(elements); } /** @@ -123,7 +123,7 @@ class AlignmentBuffer { * @returns a view onto the aligned data from @p slicer and the number of * full blocks that are represented by this view. */ - [[nodiscard]] std::tuple, size_t> aligned_data_to_process(BufferSlicer& slicer) const { + [[nodiscard]] std::tuple, size_t> aligned_data_to_process(BufferSlicer& slicer) const { BOTAN_ASSERT_NOMSG(in_alignment()); // When the final block is to be deferred, the last block must not be @@ -140,7 +140,8 @@ class AlignmentBuffer { * @returns a view onto the next full block from @p slicer or std::nullopt * if not enough data is available in @p slicer. */ - [[nodiscard]] std::optional> next_aligned_block_to_process(BufferSlicer& slicer) const { + [[nodiscard]] std::optional> next_aligned_block_to_process( + BufferSlicer& slicer) const { BOTAN_ASSERT_NOMSG(in_alignment()); // When the final block is to be deferred, the last block must not be @@ -163,7 +164,7 @@ class AlignmentBuffer { * @returns a view onto a full block once enough data was collected, or * std::nullopt if no full block is available yet */ - [[nodiscard]] std::optional> handle_unaligned_data(BufferSlicer& slicer) { + [[nodiscard]] std::optional> handle_unaligned_data(BufferSlicer& slicer) { // When the final block is to be deferred, we would need to store and // hold a buffer that contains exactly one block until more data is // passed or it is explicitly consumed. @@ -197,7 +198,7 @@ class AlignmentBuffer { * responsibility to ensure that the buffer is filled fully. After * consumption, the buffer is cleared and ready to collect new data. */ - [[nodiscard]] std::span consume() { + [[nodiscard]] Botan::span consume() { BOTAN_ASSERT_NOMSG(ready_to_consume()); m_position = 0; return m_buffer; @@ -208,10 +209,10 @@ class AlignmentBuffer { * buffer. After consumption, the buffer is cleared and ready to collect * new data. */ - [[nodiscard]] std::span consume_partial() { + [[nodiscard]] Botan::span consume_partial() { const auto elements = elements_in_buffer(); m_position = 0; - return std::span(m_buffer).first(elements); + return Botan::span(m_buffer).first(elements); } constexpr size_t size() const { return m_buffer.size(); } diff --git a/src/lib/utils/bit_ops.h b/src/lib/utils/bit_ops.h index 504c363ef9e..eef84d6ba9a 100644 --- a/src/lib/utils/bit_ops.h +++ b/src/lib/utils/bit_ops.h @@ -20,9 +20,8 @@ namespace Botan { * If top bit of arg is set, return ~0. Otherwise return 0. */ template -inline constexpr T expand_top_bit(T a) - requires(std::is_integral::value) -{ +inline constexpr T expand_top_bit(T a) { + static_assert(std::is_integral::value, "expand_top_bit needs integral"); return static_cast(0) - (a >> (sizeof(T) * 8 - 1)); } @@ -30,9 +29,8 @@ inline constexpr T expand_top_bit(T a) * If arg is zero, return ~0. Otherwise return 0 */ template -inline constexpr T ct_is_zero(T x) - requires(std::is_integral::value) -{ +inline constexpr T ct_is_zero(T x) { + static_assert(std::is_integral::value, "ct_is_zero needs integral"); return expand_top_bit(~x & (x - 1)); } @@ -42,9 +40,8 @@ inline constexpr T ct_is_zero(T x) * @return true iff arg is 2^n for some n > 0 */ template -inline constexpr bool is_power_of_2(T arg) - requires(std::is_unsigned::value) -{ +inline constexpr bool is_power_of_2(T arg) { + static_assert(std::is_unsigned::value, "is_power_of_2 needs unsigned"); return (arg != 0) && (arg != 1) && ((arg & static_cast(arg - 1)) == 0); } @@ -55,9 +52,8 @@ inline constexpr bool is_power_of_2(T arg) * @return index of the highest set bit in n */ template -inline constexpr size_t high_bit(T n) - requires(std::is_unsigned::value) -{ +inline constexpr size_t high_bit(T n) { + static_assert(std::is_unsigned::value, "high_bit needs unsigned"); size_t hb = 0; for(size_t s = 8 * sizeof(T) / 2; s > 0; s /= 2) { @@ -77,9 +73,8 @@ inline constexpr size_t high_bit(T n) * @return number of significant bytes in n */ template -inline constexpr size_t significant_bytes(T n) - requires(std::is_integral::value) -{ +inline constexpr size_t significant_bytes(T n) { + static_assert(std::is_integral::value, "significant_bytes needs integral"); size_t b = 0; for(size_t s = 8 * sizeof(n) / 2; s >= 8; s /= 2) { @@ -99,9 +94,9 @@ inline constexpr size_t significant_bytes(T n) * @return maximum x st 2^x divides n */ template -inline constexpr size_t ctz(T n) - requires(std::is_integral::value) -{ +inline constexpr size_t ctz(T n) { + static_assert(std::is_integral::value, "ctz needs integral"); + /* * If n == 0 then this function will compute 8*sizeof(T)-1, so * initialize lb to 1 if n == 0 to produce the expected result. @@ -118,10 +113,8 @@ inline constexpr size_t ctz(T n) return lb; } -template -constexpr uint8_t ceil_log2(T x) - requires(std::is_integral::value && sizeof(T) < 32) -{ +template ::value && (sizeof(T) < 32)>> +constexpr uint8_t ceil_log2(T x) { if(x >> (sizeof(T) * 8 - 1)) { return sizeof(T) * 8; } @@ -140,10 +133,8 @@ constexpr uint8_t ceil_log2(T x) /** * Return the number of bytes necessary to contain @p bits bits. */ -template -inline constexpr T ceil_tobytes(T bits) - requires(std::is_integral::value) -{ +template >> +inline constexpr T ceil_tobytes(T bits) { return (bits + 7) / 8; } diff --git a/src/lib/utils/concepts.h b/src/lib/utils/concepts.h index 6e5c09ff30f..2058649bdee 100644 --- a/src/lib/utils/concepts.h +++ b/src/lib/utils/concepts.h @@ -2,6 +2,7 @@ * Useful concepts that are available throughout the library * (C) 2023 Jack Lloyd * 2023 René Meusel - Rohde & Schwarz Cybersecurity + * 2023 Piotr Staniszewski - CodeVision * * Botan is released under the Simplified BSD License (see license.txt) */ @@ -31,6 +32,10 @@ constexpr bool is_strong_type_v = is_strong_type...>::va namespace concepts { +#define NO_CPP20 + +#ifndef NO_CPP20 + // TODO: C++20 use std::convertible_to<> that was not available in Android NDK // as of this writing. Tested with API Level up to 33. template @@ -43,8 +48,8 @@ concept convertible_to = std::is_convertible_v && requires { static_ template concept equality_comparable = requires(const std::remove_reference_t& a, const std::remove_reference_t b) { - { a == b } -> convertible_to; - }; + { a == b } -> convertible_to; +}; template concept three_way_comparison_result = @@ -53,8 +58,8 @@ concept three_way_comparison_result = template concept three_way_comparable = requires(const std::remove_reference_t& a, const std::remove_reference_t b) { - { a <=> b } -> three_way_comparison_result; - }; + { a <=> b } -> three_way_comparison_result; +}; template concept destructible = std::is_nothrow_destructible_v; @@ -80,29 +85,29 @@ concept container_pointer = template concept container = requires(T a) { - { a.begin() } -> container_iterator; - { a.end() } -> container_iterator; - { a.cbegin() } -> container_iterator; - { a.cend() } -> container_iterator; - { a.size() } -> std::same_as; - typename T::value_type; - }; + { a.begin() } -> container_iterator; + { a.end() } -> container_iterator; + { a.cbegin() } -> container_iterator; + { a.cend() } -> container_iterator; + { a.size() } -> std::same_as; + typename T::value_type; +}; template concept contiguous_container = container && requires(T a) { - { a.data() } -> container_pointer; - }; + { a.data() } -> container_pointer; +}; template concept has_empty = requires(T a) { - { a.empty() } -> std::same_as; - }; + { a.empty() } -> std::same_as; +}; template concept resizable_container = container && requires(T& c, typename T::size_type s) { - T(s); - c.resize(s); - }; + T(s); + c.resize(s); +}; template concept resizable_byte_buffer = @@ -123,6 +128,213 @@ concept contiguous_strong_type = strong_type && contiguous_container; template concept integral = std::is_integral_v; +#endif + +// TODO: C++20 use std::convertible_to<> that was not available in Android NDK +// as of this writing. Tested with API Level up to 33. +template +using convertible_to = + typename std::void_t), decltype(static_cast(std::declval()))>; + +template +struct is_convertible_to : std::false_type {}; + +template +struct is_convertible_to> : std::true_type {}; + +template +constexpr bool is_convertible_to_v = is_convertible_to::value; + +template +using equality_comparable = + typename std::enable_if_t&>() == + std::declval>()), + bool>>; + +template +struct is_equality_comparable : std::false_type {}; + +template +struct is_equality_comparable> : std::true_type {}; + +template +constexpr bool is_equality_comparable_v = is_equality_comparable::value; + +template +using less_comparable = + typename std::enable_if_t&>() < + std::declval>()), + bool>>; + +template +using greater_comparable = + typename std::enable_if_t&>() > + std::declval>()), + bool>>; + +template +using destructible = typename std::is_nothrow_destructible; + +template +constexpr bool is_destructible_v = destructible::value; + +template +using constructible_from = typename std::enable_if_t && std::is_constructible_v>; + +template +constexpr bool is_constructible_from_v = is_destructible_v && std::is_constructible_v; + +template +using default_initializable = typename std:: + void_t>, decltype(T{}), decltype(::new(static_cast(nullptr)) T)>; + +template +struct is_default_initializable : std::false_type {}; + +template +struct is_default_initializable> : std::true_type {}; + +template +constexpr bool is_default_initializable_v = is_default_initializable::value; + +template +struct same_as : std::false_type {}; + +template +struct same_as && std::is_same_v>> : std::true_type {}; + +template +constexpr bool same_as_v = same_as::value; + +template +using container_iterator = typename std::enable_if_t || + same_as_v>; + +template +struct is_container_iterator : std::false_type {}; + +template +struct is_container_iterator> : std::true_type {}; + +template +constexpr bool is_container_iterator_v = is_container_iterator::value; + +template +using container_pointer = typename std::enable_if_t || + same_as_v>; + +template +struct is_container_pointer : std::false_type {}; + +template +struct is_container_pointer> : std::true_type {}; + +template +constexpr bool is_container_pointer_v = is_container_pointer::value; + +template +using container = typename std::enable_if_t().begin()), T> && + is_container_iterator_v().end()), T> && + is_container_iterator_v().cbegin()), T> && + is_container_iterator_v().cend()), T> && + same_as_v().size()), typename T::size_type>>; + +template +struct is_container : std::false_type {}; + +template +struct is_container> : std::true_type { + using value_type = typename T::value_type; +}; + +template +constexpr bool is_container_v = is_container::value; + +template +using contiguous_container = + typename std::enable_if_t && is_container_pointer_v().data()), T>>; + +template +struct is_contiguous_container : std::false_type {}; + +template +struct is_contiguous_container> : std::true_type {}; + +template +constexpr bool is_contiguous_container_v = is_contiguous_container::value; + +template +using has_empty = typename std::enable_if_t().empty()), bool>>; + +template +struct has_empty_method : std::false_type {}; + +template +struct has_empty_method> : std::true_type {}; + +template +constexpr bool has_empty_method_v = has_empty_method::value; + +template +constexpr bool has_empty_v = has_empty::value; + +template +using resizable_container = typename std::void_t>, + decltype(T(typename T::size_type{})), + decltype(std::declval().resize(typename T::size_type{}))>; + +template +struct is_resizable_container : std::false_type {}; + +template +struct is_resizable_container> : std::true_type {}; + +template +constexpr bool is_resizable_container_v = is_resizable_container::value; + +template +using resizable_byte_buffer = typename std::enable_if_t && is_resizable_container_v && + same_as_v>; + +template +struct is_resizable_byte_buffer : std::false_type {}; + +template +struct is_resizable_byte_buffer> : std::true_type {}; + +template +constexpr bool is_resizable_byte_buffer_v = is_resizable_byte_buffer::value; + +template +using streamable = typename std::void_t() << std::declval())>; + +template +struct is_streamable : std::false_type {}; + +template +struct is_streamable> : std::true_type {}; + +template +constexpr bool is_streamable_v = is_streamable::value; + +template +using contiguous_strong_type = typename std::enable_if_t && is_contiguous_container_v>; + +template +struct is_contiguous_strong_type : std::false_type {}; + +template +struct is_contiguous_strong_type> : std::true_type {}; + +template +constexpr bool is_contiguous_strong_type_v = is_contiguous_strong_type::value; + +template +constexpr bool is_integral_v = std::is_integral_v; + +template +constexpr bool is_both_integral_v = std::is_integral_v && std::is_integral_v; + } // namespace concepts } // namespace Botan diff --git a/src/lib/utils/cpp20_extras/contains.h b/src/lib/utils/cpp20_extras/contains.h new file mode 100644 index 00000000000..7cec654bf61 --- /dev/null +++ b/src/lib/utils/cpp20_extras/contains.h @@ -0,0 +1,22 @@ +/* +* (C) 2023 Piotr Staniszewski - CodeVision +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_CONTAINS_H_ +#define BOTAN_CONTAINS_H_ + +#include + +namespace Botan { + +// Replaces C++20 member method contains available in key-value based containers +template +inline bool contains(const C& container, const typename C::key_type& what) { + return container.find(what) != container.end(); +} + +} // namespace Botan + +#endif \ No newline at end of file diff --git a/src/lib/utils/cpp20_extras/erase_if.h b/src/lib/utils/cpp20_extras/erase_if.h new file mode 100644 index 00000000000..bb1ddafde6e --- /dev/null +++ b/src/lib/utils/cpp20_extras/erase_if.h @@ -0,0 +1,30 @@ +/* +* (C) 2023 Piotr Staniszewski - CodeVision +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_ERASE_IF_H_ +#define BOTAN_ERASE_IF_H_ + +#include + +namespace Botan { + +// Replaces C++20 member method erase_if available in std::map +template +typename std::map::size_type erase_if(std::map& c, Pred pred) { + auto old_size = c.size(); + for(auto first = c.begin(), last = c.end(); first != last;) { + if(pred(*first)) { + first = c.erase(first); + } else { + ++first; + } + } + return old_size - c.size(); +} + +} // namespace Botan + +#endif diff --git a/src/lib/utils/cpp20_extras/info.txt b/src/lib/utils/cpp20_extras/info.txt new file mode 100644 index 00000000000..15bf1b96d80 --- /dev/null +++ b/src/lib/utils/cpp20_extras/info.txt @@ -0,0 +1,16 @@ + +CPP20_EXTRAS -> 20231120 + + + +name -> "C++20 extra features" +brief -> "C++20 features which are provided by Botan to allow compilation with lower standards" + + + +span.h +type_traits.h +contains.h +starts_with.h +erase_if.h + \ No newline at end of file diff --git a/src/lib/utils/cpp20_extras/span.h b/src/lib/utils/cpp20_extras/span.h new file mode 100644 index 00000000000..d708f3b7423 --- /dev/null +++ b/src/lib/utils/cpp20_extras/span.h @@ -0,0 +1,354 @@ +/* +* Implementation of C++20 Botan::span replacement for compilers not supporting C++20 +* (C) 2023 Piotr Staniszewski - CodeVision +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_SPAN_H_ +#define BOTAN_SPAN_H_ + +#include +#include +#include + +#include + +namespace Botan { + +// Non-member span constant +inline constexpr std::size_t dynamic_extent = std::numeric_limits::max(); + +// Forward +template +class span; + +namespace detail { + +template +struct is_span_convertible { + static constexpr bool value = std::is_convertible_v; +}; + +template +inline constexpr bool is_span_convertible_v = is_span_convertible::value; + +template +struct is_dynamic_extent { + static constexpr bool value = (E == dynamic_extent); +}; + +template +inline constexpr bool is_dynamic_extent_v = is_dynamic_extent::value; + +template +struct is_span_capacity { + static constexpr bool value = (is_dynamic_extent_v || E == N); +}; + +template +inline constexpr bool is_span_capacity_v = is_span_capacity::value; + +template +struct is_span_compatible { + static constexpr bool value = is_span_capacity_v && is_span_convertible_v; +}; + +template +inline constexpr bool is_span_compatible_v = is_span_compatible::value; + +template +struct is_span_explicit { + static constexpr bool value = (!is_dynamic_extent_v && is_dynamic_extent_v); +}; + +template +inline constexpr bool is_span_explicit_v = is_span_explicit::value; + +template +struct is_span_copyable { + static constexpr bool value = (is_dynamic_extent_v || is_span_capacity_v)&&is_span_convertible_v; +}; + +template +inline constexpr bool is_span_copyable_v = is_span_copyable::value; + +template +struct is_span : std::false_type {}; + +template +struct is_span> : std::true_type {}; + +template +inline constexpr bool is_span_v = is_span::value; + +template +struct is_std_array : std::false_type {}; + +template +struct is_std_array> : std::true_type {}; + +template +inline constexpr bool is_std_array_v = is_std_array::value; + +template +constexpr auto size(const Container& c) -> decltype(c.size()) { + return c.size(); +} + +template +constexpr std::size_t size(const T (&)[N]) noexcept { + return N; +} + +template +constexpr auto data(Container& c) -> decltype(c.data()) { + return c.data(); +} + +template +constexpr auto data(const Container& c) -> decltype(c.data()) { + return c.data(); +} + +template +constexpr T* data(T (&arr)[N]) noexcept { + return arr; +} + +template +struct has_size : std::false_type {}; + +template +struct has_size()))>> : std::true_type {}; + +template +inline constexpr bool has_size_v = has_size::value; + +template +struct has_data : std::false_type {}; + +template +struct has_data()))>> : std::true_type {}; + +template +inline constexpr bool has_data_v = has_data::value; + +template > +struct is_container { + static constexpr bool value = + !is_span_v && !is_std_array_v && !std::is_array_v && has_size_v && has_data_v; +}; + +template +inline constexpr bool is_container_v = is_container::value; + +template +struct is_container_type_compatible : std::false_type {}; + +template +struct is_container_type_compatible< + C, + U, + typename std::enable_if_t< + std::is_convertible_v()))> (*)[], U (*)[]>>> + : std::true_type {}; + +template +inline constexpr bool is_container_type_compatible_v = is_container_type_compatible::value; + +} // namespace detail + +// Span implementation according to https://en.cppreference.com/w/cpp/container/span +template +class span { + public: + // Member types + using element_type = Type; + using value_type = typename std::remove_cv_t; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using pointer = Type*; + using const_pointer = const Type*; + using reference = Type&; + using const_reference = const Type&; + using iterator = pointer; + using reverse_iterator = std::reverse_iterator; + + // Member constant + static constexpr std::size_t extent = Extent; + + // Constructors + template , bool> = true> + constexpr span() noexcept : m_data(nullptr), m_size(0UL) {} + + template && + detail::is_span_convertible_v, + bool> = true> + constexpr span(Iter_first* first, size_type count) noexcept : m_data(first), m_size(count) {} + + template && + detail::is_span_convertible_v, + bool> = true> + explicit constexpr span(Iter_first* first, size_type count) noexcept : m_data(first), m_size(count) {} + + template && + detail::is_span_convertible_v, + bool> = true> + constexpr span(Iter_first* first, Iter_last* last) noexcept : m_data(first), m_size(last - first) {} + + template && + detail::is_span_convertible_v, + bool> = true> + explicit constexpr span(Iter_first* first, Iter_last* last) noexcept : m_data(first), m_size(last - first) {} + + template , bool> = true> + constexpr span(typename std::enable_if_t (&arr)[N]) noexcept : m_data(arr), m_size(N) {} + + template , bool> = true> + constexpr span(std::array& arr) noexcept : m_data(arr.data()), m_size(N) {} + + template , bool> = true> + constexpr span(const std::array& arr) noexcept : m_data(arr.data()), m_size(N) {} + + // Instead of ranges + template && detail::is_container_v && + detail::is_container_type_compatible_v, + bool> = true> + constexpr span(Container& cont) : m_data(Botan::detail::data(cont)), m_size(Botan::detail::size(cont)) {} + + template && detail::is_container_v && + detail::is_container_type_compatible_v, + bool> = true> + constexpr span(const Container& cont) : m_data(Botan::detail::data(cont)), m_size(Botan::detail::size(cont)) {} + + constexpr span(const span& other) noexcept = default; + + template && + detail::is_span_copyable_v, + bool> = true> + constexpr span(const span& other) noexcept : m_data(other.data()), m_size(other.size()) {} + + template && + detail::is_span_copyable_v, + bool> = true> + explicit constexpr span(const span& other) noexcept : m_data(other.data()), m_size(other.size()) {} + + constexpr span& operator=(const span& other) noexcept = default; + + // Iterators + constexpr iterator begin() const noexcept { return data(); } + + constexpr iterator end() const noexcept { return data() + size(); } + + constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator(end()); } + + constexpr reverse_iterator rend() const noexcept { return reverse_iterator(begin()); } + + // Element access + constexpr reference front() const { return *data(); } + + constexpr reference back() const { return *(data() + (size() - 1)); } + + constexpr reference operator[](size_type idx) const { return *(data() + idx); } + + constexpr pointer data() const noexcept { return m_data; } + + // Observers + constexpr std::size_t size() const noexcept { return m_size; } + + constexpr size_type size_bytes() const noexcept { return size() * sizeof(Type); } + + constexpr bool empty() const noexcept { return (size() == 0); } + + // Subviews + template + constexpr span first() const { + static_assert(Count <= Extent, "Count <= Extent"); + return span(data(), Count); + } + + constexpr span first(size_type count) const { + return span(data(), count); + } + + template + constexpr span last() const { + static_assert(Count <= Extent, "Count <= Extent"); + return span(data() + (size() - Count), Count); + } + + constexpr span last(size_type count) const { + return span(data() + (size() - count), count); + } + + template + constexpr typename std::enable_if_t> subspan() const { + static_assert(Offset <= Extent && Count <= Extent - Offset, "Offset <= Extent && Count <= Extent - Offset"); + return span(data() + Offset, Count); + } + + constexpr span subspan(size_type offset, size_type count = dynamic_extent) const { + return span(data() + offset, (count == dynamic_extent ? size() - offset : count)); + } + + private: + element_type* m_data; + size_type m_size; +}; + +// Deduction guidelines as described in https://en.cppreference.com/w/cpp/container/span/deduction_guides +template +span(Iter_first*, End_or_size) -> span>; + +template +span(Type (&)[N]) -> span; + +template +span(std::array&) -> span; + +template +span(const std::array&) -> span; + +// Instead of ranges +template +span(Container&) -> span()))>>; + +template +span(const Container&) -> span; + +// Non-member span functions +template +span ? dynamic_extent : sizeof(Type) * Extent)> as_bytes( + span s) noexcept { + return {reinterpret_cast(s.data()), s.size_bytes()}; +} + +template , bool> = true> +span ? dynamic_extent : sizeof(Type) * Extent)> as_writable_bytes( + span s) noexcept { + return {reinterpret_cast(s.data()), s.size_bytes()}; +} + +} // namespace Botan + +#endif diff --git a/src/lib/utils/cpp20_extras/starts_with.h b/src/lib/utils/cpp20_extras/starts_with.h new file mode 100644 index 00000000000..f1bf24165d0 --- /dev/null +++ b/src/lib/utils/cpp20_extras/starts_with.h @@ -0,0 +1,28 @@ +/* +* (C) 2023 Piotr Staniszewski - CodeVision +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_STARTS_WITH_H_ +#define BOTAN_STARTS_WITH_H_ + +#include +#include + +namespace Botan { + +namespace { + +constexpr unsigned long ZERO_POS = 0UL; + +} + +// Replaces C++20 member method starts_with available in std::string or std::string_view +inline bool starts_with(std::string_view str, std::string_view what) { + return (str.find(what) == ZERO_POS); +} + +} // namespace Botan + +#endif \ No newline at end of file diff --git a/src/lib/utils/cpp20_extras/type_traits.h b/src/lib/utils/cpp20_extras/type_traits.h new file mode 100644 index 00000000000..b11ab18737e --- /dev/null +++ b/src/lib/utils/cpp20_extras/type_traits.h @@ -0,0 +1,27 @@ +/* +* Implementation of C++20 type_traits replacement for compilers not supporting C++20 +* (C) 2023 Piotr Staniszewski - CodeVision +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TYPE_TRAITS_H_ +#define BOTAN_TYPE_TRAITS_H_ + +#include + +namespace Botan { + +// Replaces C++20 std::remove_cvref +template +struct remove_cvref { + typedef std::remove_cv_t> type; +}; + +// Replaces C++20 std::remove_cvref_t +template +using remove_cvref_t = typename remove_cvref::type; + +} // namespace Botan + +#endif diff --git a/src/lib/utils/ct_utils.h b/src/lib/utils/ct_utils.h index 0e0cb8b5ca5..d2847311694 100644 --- a/src/lib/utils/ct_utils.h +++ b/src/lib/utils/ct_utils.h @@ -76,12 +76,17 @@ inline void unpoison(T& p) { * This must be verified with tooling (eg binary disassembly or using valgrind) * since you never know what a compiler might do. */ -template - requires(std::is_unsigned::value && !std::is_same::value) +template ::value && !std::is_same::value>> class Mask final { public: - Mask(const Mask& other) = default; - Mask& operator=(const Mask& other) = default; + Mask(const Mask& other) : m_mask(other.m_mask) {} + + Mask& operator=(const Mask& other) { + if(&other != this) { + m_mask = other.m_mask; + } + return *this; + } /** * Derive a Mask from a Mask of a larger type diff --git a/src/lib/utils/data_src.h b/src/lib/utils/data_src.h index 9fe0fc0b382..0636f58c421 100644 --- a/src/lib/utils/data_src.h +++ b/src/lib/utils/data_src.h @@ -10,8 +10,8 @@ #define BOTAN_DATA_SRC_H_ #include +#include #include -#include #include #include @@ -127,7 +127,7 @@ class BOTAN_PUBLIC_API(2, 0) DataSource_Memory final : public DataSource { * Construct a memory source that reads from an arbitrary byte buffer * @param in the MemoryRegion to read from */ - explicit DataSource_Memory(std::span in) : m_source(in.begin(), in.end()), m_offset(0) {} + explicit DataSource_Memory(Botan::span in) : m_source(in.begin(), in.end()), m_offset(0) {} /** * Construct a memory source that reads from a std::vector diff --git a/src/lib/utils/ghash/ghash.cpp b/src/lib/utils/ghash/ghash.cpp index 38604afdbed..06fc433a6e1 100644 --- a/src/lib/utils/ghash/ghash.cpp +++ b/src/lib/utils/ghash/ghash.cpp @@ -31,7 +31,7 @@ std::string GHASH::provider() const { return "base"; } -void GHASH::ghash_multiply(secure_vector& x, std::span input, size_t blocks) { +void GHASH::ghash_multiply(secure_vector& x, Botan::span input, size_t blocks) { #if defined(BOTAN_HAS_GHASH_CLMUL_CPU) if(CPUID::has_carryless_multiply()) { BOTAN_ASSERT_NOMSG(!m_H_pow.empty()); @@ -78,7 +78,7 @@ void GHASH::ghash_multiply(secure_vector& x, std::span i CT::unpoison(x.data(), x.size()); } -void GHASH::ghash_update(secure_vector& ghash, std::span input) { +void GHASH::ghash_update(secure_vector& ghash, Botan::span input) { assert_key_material_set(!m_H.empty()); /* @@ -105,7 +105,7 @@ bool GHASH::has_keying_material() const { return !m_ghash.empty(); } -void GHASH::key_schedule(std::span key) { +void GHASH::key_schedule(Botan::span key) { m_H.assign(key.begin(), key.end()); // TODO: C++23 - std::vector<>::assign_range() m_H_ad.resize(GCM_BS); m_ad_len = 0; @@ -143,13 +143,13 @@ void GHASH::key_schedule(std::span key) { #endif } -void GHASH::start(std::span nonce) { +void GHASH::start(Botan::span nonce) { BOTAN_ARG_CHECK(nonce.size() == 16, "GHASH requires a 128-bit nonce"); m_nonce.assign(nonce.begin(), nonce.end()); // TODO: C++23: assign_range m_ghash = m_H_ad; } -void GHASH::set_associated_data(std::span input) { +void GHASH::set_associated_data(Botan::span input) { if(m_ghash.empty() == false) { throw Invalid_State("Too late to set AD in GHASH"); } @@ -160,13 +160,13 @@ void GHASH::set_associated_data(std::span input) { m_ad_len = input.size(); } -void GHASH::update_associated_data(std::span ad) { +void GHASH::update_associated_data(Botan::span ad) { assert_key_material_set(); m_ad_len += ad.size(); ghash_update(m_ghash, ad); } -void GHASH::update(std::span input) { +void GHASH::update(Botan::span input) { assert_key_material_set(); m_text_len += input.size(); ghash_update(m_ghash, input); @@ -182,7 +182,7 @@ void GHASH::add_final_block(secure_vector& hash, size_t ad_len, size_t ghash_update(hash, {final_block, GCM_BS}); } -void GHASH::final(std::span mac) { +void GHASH::final(Botan::span mac) { BOTAN_ARG_CHECK(!mac.empty() && mac.size() <= 16, "GHASH output length"); assert_key_material_set(); @@ -196,7 +196,7 @@ void GHASH::final(std::span mac) { m_text_len = 0; } -void GHASH::nonce_hash(secure_vector& y0, std::span nonce) { +void GHASH::nonce_hash(secure_vector& y0, Botan::span nonce) { BOTAN_ASSERT(m_ghash.empty(), "nonce_hash called during wrong time"); ghash_update(y0, nonce); diff --git a/src/lib/utils/ghash/ghash.h b/src/lib/utils/ghash/ghash.h index f75b37e47ed..e53be6cb5f0 100644 --- a/src/lib/utils/ghash/ghash.h +++ b/src/lib/utils/ghash/ghash.h @@ -17,23 +17,23 @@ namespace Botan { */ class GHASH final : public SymmetricAlgorithm { public: - void set_associated_data(std::span ad); + void set_associated_data(Botan::span ad); - void nonce_hash(secure_vector& y0, std::span nonce); + void nonce_hash(secure_vector& y0, Botan::span nonce); - void start(std::span nonce); + void start(Botan::span nonce); /* * Assumes input len is multiple of 16 */ - void update(std::span in); + void update(Botan::span in); /* * Incremental update of associated data */ - void update_associated_data(std::span ad); + void update_associated_data(Botan::span ad); - void final(std::span out); + void final(Botan::span out); Key_Length_Specification key_spec() const override { return Key_Length_Specification(16); } @@ -47,7 +47,7 @@ class GHASH final : public SymmetricAlgorithm { std::string provider() const; - void ghash_update(secure_vector& x, std::span input); + void ghash_update(secure_vector& x, Botan::span input); void add_final_block(secure_vector& x, size_t ad_len, size_t pt_len); @@ -62,9 +62,9 @@ class GHASH final : public SymmetricAlgorithm { static void ghash_multiply_vperm(uint8_t x[16], const uint64_t HM[256], const uint8_t input[], size_t blocks); #endif - void key_schedule(std::span key) override; + void key_schedule(Botan::span key) override; - void ghash_multiply(secure_vector& x, std::span input, size_t blocks); + void ghash_multiply(secure_vector& x, Botan::span input, size_t blocks); static const size_t GCM_BS = 16; diff --git a/src/lib/utils/http_util/http_util.cpp b/src/lib/utils/http_util/http_util.cpp index d3982530807..e6c692f32b4 100644 --- a/src/lib/utils/http_util/http_util.cpp +++ b/src/lib/utils/http_util/http_util.cpp @@ -8,12 +8,14 @@ #include +#include #include #include #include #include #include #include + #include namespace Botan::HTTP { @@ -198,7 +200,7 @@ Response http_sync(const http_exch_fn& http_transact, } } - if(status_code == 301 && headers.contains("Location")) { + if(status_code == 301 && contains(headers, "Location")) { if(allowable_redirects == 0) { throw HTTP_Error("HTTP redirection count exceeded"); } diff --git a/src/lib/utils/loadstor.h b/src/lib/utils/loadstor.h index f0e50a1c2e3..7f7406ca55d 100644 --- a/src/lib/utils/loadstor.h +++ b/src/lib/utils/loadstor.h @@ -32,9 +32,8 @@ inline constexpr uint8_t get_byte_var(size_t byte_num, T input) { * @param input the value to extract from * @return byte byte number B of input */ -template +template > inline constexpr uint8_t get_byte(T input) - requires(B < sizeof(T)) { const size_t shift = ((~B) & (sizeof(T) - 1)) << 3; return static_cast((input >> shift) & 0xFF); diff --git a/src/lib/utils/mem_ops.cpp b/src/lib/utils/mem_ops.cpp index 64cd07ec521..152830e746a 100644 --- a/src/lib/utils/mem_ops.cpp +++ b/src/lib/utils/mem_ops.cpp @@ -40,14 +40,14 @@ BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size) { void* ptr = std::calloc(elems, elem_size); // NOLINT(*-no-malloc) #endif if(!ptr) { - [[unlikely]] throw std::bad_alloc(); + throw std::bad_alloc(); } return ptr; } void deallocate_memory(void* p, size_t elems, size_t elem_size) { if(p == nullptr) { - [[unlikely]] return; + return; } secure_scrub_memory(p, elems * elem_size); diff --git a/src/lib/utils/mem_ops.h b/src/lib/utils/mem_ops.h index b270e93ac17..9457d41a828 100644 --- a/src/lib/utils/mem_ops.h +++ b/src/lib/utils/mem_ops.h @@ -9,8 +9,8 @@ #define BOTAN_MEMORY_OPS_H_ #include +#include #include -#include #include #include @@ -116,29 +116,27 @@ inline constexpr void clear_mem(T* ptr, size_t n) { * @param in the source array * @param n the number of elements of in/out */ -template -inline constexpr void copy_mem(T* out, const T* in, size_t n) - requires std::is_trivial::type>::value +template inline constexpr void copy_mem(T* out, const T* in, size_t n) { - BOTAN_ASSERT_IMPLICATION(n > 0, in != nullptr && out != nullptr, "If n > 0 then args are not null"); + static_assert(std::is_trivial::type>::value, ""); + BOTAN_ASSERT_IMPLICATION(n > 0, in != nullptr && out != nullptr, + "If n > 0 then args are not null"); if(in != nullptr && out != nullptr && n > 0) { std::memmove(out, in, sizeof(T) * n); } } -template -inline constexpr void typecast_copy(uint8_t out[], T in[], size_t N) - requires std::is_trivially_copyable::value +template inline constexpr void typecast_copy(uint8_t out[], T in[], size_t N) { - std::memcpy(out, in, sizeof(T) * N); + static_assert(std::is_trivially_copyable::value, ""); + std::memcpy(out, in, sizeof(T)*N); } -template -inline constexpr void typecast_copy(T out[], const uint8_t in[], size_t N) - requires std::is_trivial::value +template inline constexpr void typecast_copy(T out[], const uint8_t in[], size_t N) { - std::memcpy(out, in, sizeof(T) * N); + static_assert(std::is_trivial::value, ""); + std::memcpy(out, in, sizeof(T)*N); } template @@ -146,17 +144,15 @@ inline constexpr void typecast_copy(uint8_t out[], T in) { typecast_copy(out, &in, 1); } -template -inline constexpr void typecast_copy(T& out, const uint8_t in[]) - requires std::is_trivial::type>::value +template inline constexpr void typecast_copy(T& out, const uint8_t in[]) { + static_assert(std::is_trivial::type>::value, ""); typecast_copy(&out, in, 1); } -template -inline constexpr To typecast_copy(const FromT* src) noexcept - requires std::is_trivially_copyable::value && std::is_trivial::value +template inline constexpr To typecast_copy(const FromT *src) noexcept { + static_assert(std::is_trivially_copyable::value && std::is_trivial::value, ""); To dst; std::memcpy(&dst, src, sizeof(To)); return dst; @@ -287,7 +283,7 @@ inline void xor_buf(uint8_t out[], const uint8_t in[], const uint8_t in2[], size } } -inline void xor_buf(std::span out, std::span in, size_t n) { +inline void xor_buf(Botan::span out, Botan::span in, size_t n) { xor_buf(out.data(), in.data(), n); } diff --git a/src/lib/utils/prefetch.h b/src/lib/utils/prefetch.h index 066d2b6d0ff..a5f77904e16 100644 --- a/src/lib/utils/prefetch.h +++ b/src/lib/utils/prefetch.h @@ -30,11 +30,11 @@ uint64_t prefetch_array_raw(size_t bytes, const void* array) noexcept; * to not elide otherwise "useless" reads. The return value will always * be zero. */ -template -T prefetch_arrays(T (&... arr)[Ns]) noexcept - requires std::is_integral::value +template +T prefetch_arrays(T (&...arr)[Ns]) noexcept { - return (static_cast(prefetch_array_raw(sizeof(T) * Ns, arr)) & ...); + static_assert(std::is_integral::value, "prefetch_arrays must use integral type"); + return (static_cast(prefetch_array_raw(sizeof(T)*Ns, arr)) & ...); } } // namespace Botan diff --git a/src/lib/utils/rotate.h b/src/lib/utils/rotate.h index cc2970d52ad..c6792844644 100644 --- a/src/lib/utils/rotate.h +++ b/src/lib/utils/rotate.h @@ -19,9 +19,9 @@ namespace Botan { */ template inline constexpr T rotl(T input) - requires(ROT > 0 && ROT < 8 * sizeof(T)) { - return static_cast((input << ROT) | (input >> (8 * sizeof(T) - ROT))); + static_assert(ROT > 0 && ROT < 8*sizeof(T), "Invalid rotation constant"); + return static_cast((input << ROT) | (input >> (8*sizeof(T) - ROT))); } /** @@ -31,9 +31,9 @@ inline constexpr T rotl(T input) */ template inline constexpr T rotr(T input) - requires(ROT > 0 && ROT < 8 * sizeof(T)) { - return static_cast((input >> ROT) | (input << (8 * sizeof(T) - ROT))); + static_assert(ROT > 0 && ROT < 8*sizeof(T), "Invalid rotation constant"); + return static_cast((input >> ROT) | (input << (8*sizeof(T) - ROT))); } /** diff --git a/src/lib/utils/safeint.h b/src/lib/utils/safeint.h index 3fa7547cc29..fcde25a1f29 100644 --- a/src/lib/utils/safeint.h +++ b/src/lib/utils/safeint.h @@ -30,13 +30,13 @@ class Integer_Overflow_Detected final : public Exception { inline size_t checked_add(size_t x, size_t y, const char* file, int line) { #if BOTAN_COMPILER_HAS_BUILTIN(__builtin_add_overflow) size_t z; - if(__builtin_add_overflow(x, y, &z)) [[unlikely]] + if(__builtin_add_overflow(x, y, &z)) #elif defined(_MSC_VER) size_t z; - if(SizeTAdd(x, y, &z) != S_OK) [[unlikely]] + if(SizeTAdd(x, y, &z) != S_OK) #else size_t z = x + y; - if(z < x) [[unlikely]] + if(z < x) #endif { throw Integer_Overflow_Detected(file, line); @@ -47,13 +47,13 @@ inline size_t checked_add(size_t x, size_t y, const char* file, int line) { inline std::optional checked_mul(size_t x, size_t y) { #if BOTAN_COMPILER_HAS_BUILTIN(__builtin_add_overflow) size_t z; - if(__builtin_mul_overflow(x, y, &z)) [[unlikely]] + if(__builtin_mul_overflow(x, y, &z)) #elif defined(_MSC_VER) size_t z; - if(SizeTMult(x, y, &z) != S_OK) [[unlikely]] + if(SizeTMult(x, y, &z) != S_OK) #else size_t z = x * y; - if(y && z / y != x) [[unlikely]] + if(y && z / y != x) #endif { return std::nullopt; diff --git a/src/lib/utils/simd/simd_32.h b/src/lib/utils/simd/simd_32.h index 5f62d5645b4..512e875392b 100644 --- a/src/lib/utils/simd/simd_32.h +++ b/src/lib/utils/simd/simd_32.h @@ -276,9 +276,9 @@ class SIMD_4x32 final { * Left rotation by a compile time constant */ template - SIMD_4x32 rotl() const noexcept - requires(ROT > 0 && ROT < 32) - { + SIMD_4x32 rotl() const noexcept { + static_assert(ROT > 0 && ROT < 32, "Invalid rotation constant"); + #if defined(BOTAN_SIMD_USE_SSE2) return SIMD_4x32(_mm_or_si128(_mm_slli_epi32(m_simd, static_cast(ROT)), @@ -412,10 +412,11 @@ class SIMD_4x32 final { #endif } - template - SIMD_4x32 shl() const noexcept - requires(SHIFT > 0 && SHIFT < 32) + + template SIMD_4x32 shl() const noexcept { + static_assert(SHIFT > 0 && SHIFT < 32, "Invalid shift count"); + #if defined(BOTAN_SIMD_USE_SSE2) return SIMD_4x32(_mm_slli_epi32(m_simd, SHIFT)); @@ -489,8 +490,9 @@ class SIMD_4x32 final { template SIMD_4x32 shift_elems_left() const noexcept - requires(I <= 3) { + static_assert(I <= 3, "Invalid shift count"); + #if defined(BOTAN_SIMD_USE_SSE2) return SIMD_4x32(_mm_slli_si128(raw(), 4 * I)); #elif defined(BOTAN_SIMD_USE_NEON) @@ -510,8 +512,9 @@ class SIMD_4x32 final { template SIMD_4x32 shift_elems_right() const noexcept - requires(I <= 3) { + static_assert(I <= 3, "Invalid shift count"); + #if defined(BOTAN_SIMD_USE_SSE2) return SIMD_4x32(_mm_srli_si128(raw(), 4 * I)); #elif defined(BOTAN_SIMD_USE_NEON) diff --git a/src/lib/utils/simd/simd_avx2/simd_avx2.h b/src/lib/utils/simd/simd_avx2/simd_avx2.h index 963e8cdf1cc..b7937f1fa28 100644 --- a/src/lib/utils/simd/simd_avx2/simd_avx2.h +++ b/src/lib/utils/simd/simd_avx2/simd_avx2.h @@ -61,9 +61,8 @@ class SIMD_8x32 final { BOTAN_AVX2_FN void store_be(uint8_t out[]) const noexcept { bswap().store_le(out); } - template + template 0) && (ROT < 32)>> BOTAN_AVX2_FN SIMD_8x32 rotl() const noexcept - requires(ROT > 0 && ROT < 32) { #if defined(__AVX512VL__) return SIMD_8x32(_mm256_rol_epi32(m_avx2, ROT)); diff --git a/src/lib/utils/simd/simd_avx512/simd_avx512.h b/src/lib/utils/simd/simd_avx512/simd_avx512.h index 35a18f3b957..95e6829ddac 100644 --- a/src/lib/utils/simd/simd_avx512/simd_avx512.h +++ b/src/lib/utils/simd/simd_avx512/simd_avx512.h @@ -65,9 +65,8 @@ class SIMD_16x32 final { BOTAN_AVX512_FN void store_be(uint8_t out[]) const { bswap().store_le(out); } - template + template 0) && (ROT < 32)>> BOTAN_AVX512_FN SIMD_16x32 rotl() const - requires(ROT > 0 && ROT < 32) { return SIMD_16x32(_mm512_rol_epi32(m_avx512, ROT)); } diff --git a/src/lib/utils/socket/socket_udp.cpp b/src/lib/utils/socket/socket_udp.cpp index 862602b6592..06a4c048aa2 100644 --- a/src/lib/utils/socket/socket_udp.cpp +++ b/src/lib/utils/socket/socket_udp.cpp @@ -160,7 +160,7 @@ class BSD_SocketUDP final : public OS::SocketUDP { m_socket = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); - if(m_socket == invalid_socket()) [[unlikely]] { + if(m_socket == invalid_socket()) { // unsupported socket type? continue; } diff --git a/src/lib/utils/sqlite3/sqlite3.cpp b/src/lib/utils/sqlite3/sqlite3.cpp index ea2d0676fd0..ea35e71e0ca 100644 --- a/src/lib/utils/sqlite3/sqlite3.cpp +++ b/src/lib/utils/sqlite3/sqlite3.cpp @@ -30,7 +30,7 @@ Sqlite3_Database::Sqlite3_Database(std::string_view db_filename, std::optional #include #include -#include #include #include #include @@ -20,16 +19,18 @@ #include #include +#include #include +#include namespace Botan { -template > +template , typename = concepts::contiguous_container> inline T to_byte_vector(std::string_view s) { return T(s.cbegin(), s.cend()); } -inline std::string to_string(std::span bytes) { +inline std::string to_string(Botan::span bytes) { return std::string(bytes.begin(), bytes.end()); } @@ -42,10 +43,11 @@ inline std::string to_string(std::span bytes) { * * @return the accumulator containing the reduction of @p keys */ -template -RetT reduce(const std::vector& keys, RetT acc, ReducerT reducer) - requires std::is_convertible_v> -{ +template >>> +RetT reduce(const std::vector& keys, RetT acc, ReducerT reducer) { for(const KeyT& key : keys) { acc = reducer(std::move(acc), key); } @@ -139,9 +141,9 @@ void map_remove_if(Pred pred, T& assoc) { */ class BufferSlicer final { public: - BufferSlicer(std::span buffer) : m_remaining(buffer) {} + BufferSlicer(Botan::span buffer) : m_remaining(buffer) {} - template + template >> auto copy(const size_t count) { const auto result = take(count); return ContainerT(result.begin(), result.end()); @@ -151,21 +153,21 @@ class BufferSlicer final { auto copy_as_secure_vector(const size_t count) { return copy>(count); } - std::span take(const size_t count) { + Botan::span take(const size_t count) { BOTAN_STATE_CHECK(remaining() >= count); auto result = m_remaining.first(count); m_remaining = m_remaining.subspan(count); return result; } - template + template >> StrongSpan take(const size_t count) { return StrongSpan(take(count)); } uint8_t take_byte() { return take(1)[0]; } - void copy_into(std::span sink) { + void copy_into(Botan::span sink) { const auto data = take(sink.size()); std::copy(data.begin(), data.end(), sink.begin()); } @@ -177,7 +179,7 @@ class BufferSlicer final { bool empty() const { return m_remaining.empty(); } private: - std::span m_remaining; + Botan::span m_remaining; }; /** @@ -189,13 +191,13 @@ class BufferSlicer final { */ class BufferStuffer { public: - BufferStuffer(std::span buffer) : m_buffer(buffer) {} + BufferStuffer(Botan::span buffer) : m_buffer(buffer) {} /** * @returns a span for the next @p bytes bytes in the concatenated buffer. * Checks that the buffer is not exceded. */ - std::span next(size_t bytes) { + Botan::span next(size_t bytes) { BOTAN_STATE_CHECK(m_buffer.size() >= bytes); auto result = m_buffer.first(bytes); @@ -203,7 +205,7 @@ class BufferStuffer { return result; } - template + template >> StrongSpan next(size_t bytes) { return StrongSpan(next(bytes)); } @@ -213,7 +215,7 @@ class BufferStuffer { */ uint8_t& next_byte() { return next(1)[0]; } - void append(std::span buffer) { + void append(Botan::span buffer) { auto sink = next(buffer.size()); std::copy(buffer.begin(), buffer.end(), sink.begin()); } @@ -223,7 +225,7 @@ class BufferStuffer { size_t remaining_capacity() const { return m_buffer.size(); } private: - std::span m_buffer; + Botan::span m_buffer; }; /** @@ -234,7 +236,7 @@ template decltype(auto) concat(Ts&&... buffers) { static_assert(sizeof...(buffers) > 0, "concat requires at least one buffer"); - using result_t = std::remove_cvref_t>>; + using result_t = Botan::remove_cvref_t>>; result_t result; result.reserve((buffers.size() + ...)); (result.insert(result.end(), buffers.begin(), buffers.end()), ...); @@ -273,10 +275,10 @@ constexpr bool is_generalizable_to(const std::variant&) noexcept { * This is useful to convert restricted variant types into more general * variants types. */ -template -constexpr GeneralVariantT generalize_to(SpecialT&& specific) noexcept - requires(std::is_constructible_v>) -{ +template >>> +constexpr GeneralVariantT generalize_to(SpecialT&& specific) noexcept { return std::forward(specific); } diff --git a/src/lib/utils/strong_type.h b/src/lib/utils/strong_type.h index dda41492da6..a0a9bdd54f4 100644 --- a/src/lib/utils/strong_type.h +++ b/src/lib/utils/strong_type.h @@ -2,6 +2,7 @@ * A wrapper class to implement strong types * (C) 2022 Jack Lloyd * 2022 René Meusel - Rohde & Schwarz Cybersecurity + * 2023 Piotr Staniszewski - CodeVision * * Botan is released under the Simplified BSD License (see license.txt) */ @@ -9,10 +10,9 @@ #ifndef BOTAN_STRONG_TYPE_H_ #define BOTAN_STRONG_TYPE_H_ -#include -#include - #include +#include +#include namespace Botan { @@ -52,20 +52,20 @@ class Strong_Base { const T& get() const { return m_value; } }; -template +template class Strong_Adapter : public Strong_Base { public: using Strong_Base::Strong_Base; }; -template -class Strong_Adapter : public Strong_Base { +template +class Strong_Adapter>> : public Strong_Base { public: using Strong_Base::Strong_Base; }; -template -class Strong_Adapter : public Strong_Base { +template +class Strong_Adapter>> : public Strong_Base { public: using value_type = typename T::value_type; using size_type = typename T::size_type; @@ -77,23 +77,20 @@ class Strong_Adapter : public Strong_Base { public: using Strong_Base::Strong_Base; - explicit Strong_Adapter(std::span span) - requires(concepts::contiguous_container) - : Strong_Adapter(T(span.begin(), span.end())) {} + template >> + explicit Strong_Adapter(Botan::span span) : Strong_Adapter(T(span.begin(), span.end())) {} - explicit Strong_Adapter(size_t size) - requires(concepts::resizable_container) - : Strong_Adapter(T(size)) {} + template >> + explicit Strong_Adapter(size_t size) : Strong_Adapter(T(size)) {} template Strong_Adapter(InputIt begin, InputIt end) : Strong_Adapter(T(begin, end)) {} // Disambiguates the usage of string literals, otherwise: - // Strong_Adapter(std::span<>) and Strong_Adapter(const char*) + // Strong_Adapter(Botan::span<>) and Strong_Adapter(const char*) // would be ambiguous. - explicit Strong_Adapter(const char* str) - requires(std::same_as) - : Strong_Adapter(std::string(str)) {} + template >> + explicit Strong_Adapter(const char* str) : Strong_Adapter(std::string(str)) {} public: decltype(auto) begin() noexcept(noexcept(this->get().begin())) { return this->get().begin(); } @@ -114,27 +111,23 @@ class Strong_Adapter : public Strong_Base { size_type size() const noexcept(noexcept(this->get().size())) { return this->get().size(); } - decltype(auto) data() noexcept(noexcept(this->get().data())) - requires(concepts::contiguous_container) - { + template >> + decltype(auto) data() noexcept(noexcept(this->get().data())) { return this->get().data(); } - decltype(auto) data() const noexcept(noexcept(this->get().data())) - requires(concepts::contiguous_container) - { + template >> + decltype(auto) data() const noexcept(noexcept(this->get().data())) { return this->get().data(); } - bool empty() const noexcept(noexcept(this->get().empty())) - requires(concepts::has_empty) - { + template >> + bool empty() const noexcept(noexcept(this->get().empty())) { return this->get().empty(); } - void resize(size_type size) noexcept(noexcept(this->get().resize(size))) - requires(concepts::resizable_container) - { + template >> + void resize(size_type size) noexcept(noexcept(this->get().resize(size))) { this->get().resize(size); } }; @@ -161,342 +154,480 @@ class Strong : public detail::Strong_Adapter { using Tag = TagTypeT; }; -template - requires(concepts::streamable) decltype(auto) -operator<<(std::ostream& os, const Strong& v) { +template > +decltype(auto) operator<<(std::ostream& os, const Strong& v) { return os << v.get(); } -template - requires(concepts::equality_comparable) bool -operator==(const Strong& lhs, const Strong& rhs) { +template > +bool operator==(const Strong& lhs, const Strong& rhs) { return lhs.get() == rhs.get(); } -template - requires(concepts::three_way_comparable) -auto operator<=>(const Strong& lhs, const Strong& rhs) { - return lhs.get() <=> rhs.get(); +template > +bool operator!=(const Strong& lhs, const Strong& rhs) { + return !operator==(lhs, rhs); +} + +template > +auto operator<(const Strong& lhs, const Strong& rhs) { + return lhs.get() < rhs.get(); +} + +template > +auto operator>(const Strong& lhs, const Strong& rhs) { + return lhs.get() > rhs.get(); +} + +template > +auto operator<=(const Strong& lhs, const Strong& rhs) { + return lhs.get() <= rhs.get(); +} + +template > +auto operator>=(const Strong& lhs, const Strong& rhs) { + return lhs.get() >= rhs.get(); +} + +template >> +auto operator<(T1 a, Strong b) { + return a < b.get(); +} + +template >> +auto operator<=(Strong a, T2 b) { + return a.get() <= b; +} + +template >> +auto operator<=(T1 a, Strong b) { + return a <= b.get(); +} + +template >> +auto operator>=(Strong a, T2 b) { + return a.get() >= b; } -template -auto operator<=>(T1 a, Strong b) { - return a <=> b.get(); +template >> +auto operator>=(T1 a, Strong b) { + return a >= b.get(); } -template -auto operator<=>(Strong a, T2 b) { - return a.get() <=> b; +template >> +auto operator<(Strong a, T2 b) { + return a.get() < b; } -template +template >> +auto operator>(T1 a, Strong b) { + return a > b.get(); +} + +template >> +auto operator>(Strong a, T2 b) { + return a.get() > b; +} + +template >> auto operator==(T1 a, Strong b) { return a == b.get(); } -template +template >> auto operator==(Strong a, T2 b) { return a.get() == b; } -template - requires(detail::has_capability) +template >> +auto operator!=(T1 a, Strong b) { + return !operator==(a, b); +} + +template >> +auto operator!=(Strong a, T2 b) { + return !operator==(a, b); +} + +template && + detail::has_capability>> constexpr decltype(auto) operator+(T1 a, Strong b) { return Strong(a + b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator+(Strong a, T2 b) { return Strong(a.get() + b); } -template +template >> constexpr decltype(auto) operator+(Strong a, Strong b) { return Strong(a.get() + b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator-(T1 a, Strong b) { return Strong(a - b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator-(Strong a, T2 b) { return Strong(a.get() - b); } -template +template >> constexpr decltype(auto) operator-(Strong a, Strong b) { return Strong(a.get() - b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator*(T1 a, Strong b) { return Strong(a * b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator*(Strong a, T2 b) { return Strong(a.get() * b); } -template +template >> constexpr decltype(auto) operator*(Strong a, Strong b) { return Strong(a.get() * b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator/(T1 a, Strong b) { return Strong(a / b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator/(Strong a, T2 b) { return Strong(a.get() / b); } -template +template >> constexpr decltype(auto) operator/(Strong a, Strong b) { return Strong(a.get() / b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator^(T1 a, Strong b) { return Strong(a ^ b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator^(Strong a, T2 b) { return Strong(a.get() ^ b); } -template +template >> constexpr decltype(auto) operator^(Strong a, Strong b) { return Strong(a.get() ^ b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator&(T1 a, Strong b) { return Strong(a & b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator&(Strong a, T2 b) { return Strong(a.get() & b); } -template +template >> constexpr decltype(auto) operator&(Strong a, Strong b) { return Strong(a.get() & b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator|(T1 a, Strong b) { return Strong(a | b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator|(Strong a, T2 b) { return Strong(a.get() | b); } -template +template >> constexpr decltype(auto) operator|(Strong a, Strong b) { return Strong(a.get() | b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator>>(T1 a, Strong b) { return Strong(a >> b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator>>(Strong a, T2 b) { return Strong(a.get() >> b); } -template +template >> constexpr decltype(auto) operator>>(Strong a, Strong b) { return Strong(a.get() >> b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator<<(T1 a, Strong b) { return Strong(a << b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr decltype(auto) operator<<(Strong a, T2 b) { return Strong(a.get() << b); } -template +template >> constexpr decltype(auto) operator<<(Strong a, Strong b) { return Strong(a.get() << b.get()); } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator+=(Strong& a, T2 b) { a.get() += b; return a; } -template +template >> constexpr auto operator+=(Strong& a, Strong b) { a.get() += b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator-=(Strong& a, T2 b) { a.get() -= b; return a; } -template +template >> constexpr auto operator-=(Strong& a, Strong b) { a.get() -= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator*=(Strong& a, T2 b) { a.get() *= b; return a; } -template +template >> constexpr auto operator*=(Strong& a, Strong b) { a.get() *= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator/=(Strong& a, T2 b) { a.get() /= b; return a; } -template +template >> constexpr auto operator/=(Strong& a, Strong b) { a.get() /= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator^=(Strong& a, T2 b) { a.get() ^= b; return a; } -template +template >> constexpr auto operator^=(Strong& a, Strong b) { a.get() ^= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator&=(Strong& a, T2 b) { a.get() &= b; return a; } -template +template >> constexpr auto operator&=(Strong& a, Strong b) { a.get() &= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator|=(Strong& a, T2 b) { a.get() |= b; return a; } -template +template >> constexpr auto operator|=(Strong& a, Strong b) { a.get() |= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator>>=(Strong& a, T2 b) { a.get() >>= b; return a; } -template +template >> constexpr auto operator>>=(Strong& a, Strong b) { a.get() >>= b.get(); return a; } -template - requires(detail::has_capability) +template && + detail::has_capability>> constexpr auto operator<<=(Strong& a, T2 b) { a.get() <<= b; return a; } -template +template >> constexpr auto operator<<=(Strong& a, Strong b) { a.get() <<= b.get(); return a; } -template +template >> constexpr auto operator++(Strong& a, int) { auto tmp = a; ++a.get(); return tmp; } -template +template >> constexpr auto operator++(Strong& a) { ++a.get(); return a; } -template +template >> constexpr auto operator--(Strong& a, int) { auto tmp = a; --a.get(); return tmp; } -template +template >> constexpr auto operator--(Strong& a) { --a.get(); return a; } /** - * This mimmicks a std::span but keeps track of the strong-type information. Use + * This mimmicks a Botan::span but keeps track of the strong-type information. Use * this when you would want to use `const Strong<...>&` as a parameter * declaration. In particular this allows assigning strong-type information to * slices of a bigger buffer without copying the bytes. E.g: @@ -510,10 +641,11 @@ constexpr auto operator--(Strong& a) { * bar(slicer.take()); // This does not copy the data from buffer but * // just annotates the 'Foo' strong-type info. */ -template +template > class StrongSpan { - using underlying_span = std:: - conditional_t, std::span, std::span>; + using underlying_span = std::conditional_t, + Botan::span, + Botan::span>; public: using value_type = typename underlying_span::value_type; @@ -538,8 +670,9 @@ class StrongSpan { // a declaration of an ordinary copy constructor. The existance of a copy constructor // is interpreted as "not cheap to copy", setting off the `performance-unnecessary-value-param` check. // See also: https://github.com/randombit/botan/issues/3591 - template >>> + template && + std::is_same_v>>> StrongSpan(const StrongSpan& other) : m_span(other.get()) {} StrongSpan(const StrongSpan& other) = default; @@ -547,12 +680,12 @@ class StrongSpan { ~StrongSpan() = default; /** - * @returns the underlying std::span without any type constraints + * @returns the underlying Botan::span without any type constraints */ underlying_span get() const { return m_span; } /** - * @returns the underlying std::span without any type constraints + * @returns the underlying Botan::span without any type constraints */ underlying_span get() { return m_span; } diff --git a/src/lib/x509/pkix_enums.h b/src/lib/x509/pkix_enums.h index 460851c22b7..3a05c070487 100644 --- a/src/lib/x509/pkix_enums.h +++ b/src/lib/x509/pkix_enums.h @@ -150,7 +150,7 @@ class BOTAN_PUBLIC_API(3, 0) Key_Constraints { return Key_Constraints(Key_Constraints::KeyCertSign | Key_Constraints::CrlSign); } - bool operator==(const Key_Constraints&) const = default; + bool operator==(const Key_Constraints& other) const { return m_value == other.m_value; } void operator|=(Key_Constraints::Bits other) { m_value |= other; } @@ -160,7 +160,8 @@ class BOTAN_PUBLIC_API(3, 0) Key_Constraints { bool includes(Key_Constraints other) const { return (m_value & other.m_value) == other.m_value; } // Return true if any of the bits provided are set - bool includes_any(auto&&... bits) const { return (m_value & (bits | ...)) > 0; } + template + bool includes_any(Ts&& ...bits) const { return (m_value & (bits | ...)) > 0; } bool empty() const { return m_value == 0; } diff --git a/src/lib/x509/x509_ext.cpp b/src/lib/x509/x509_ext.cpp index 2e8fbf14299..ee860aa89c0 100644 --- a/src/lib/x509/x509_ext.cpp +++ b/src/lib/x509/x509_ext.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -123,7 +124,7 @@ void Certificate_Extension::validate(const X509_Certificate& /*unused*/, */ void Extensions::add(std::unique_ptr extn, bool critical) { // sanity check: we don't want to have the same extension more than once - if(m_extension_info.contains(extn->oid_of())) { + if(contains(m_extension_info, extn->oid_of())) { const std::string name = extn->oid_name(); throw Invalid_Argument("Extension " + name + " already present in Extensions::add"); } @@ -135,7 +136,7 @@ void Extensions::add(std::unique_ptr extn, bool critical) } bool Extensions::add_new(std::unique_ptr extn, bool critical) { - if(m_extension_info.contains(extn->oid_of())) { + if(contains(m_extension_info, extn->oid_of())) { return false; // already exists } @@ -745,7 +746,7 @@ void CRL_Distribution_Points::decode_inner(const std::vector& buf) { } void CRL_Distribution_Points::Distribution_Point::encode_into(DER_Encoder& der) const { - if(!m_point.get_attributes().contains("URI")) { + if(!Botan::contains(m_point.get_attributes(), "URI")) { throw Not_Implemented("Empty CRL_Distribution_Point encoding"); } diff --git a/src/lib/x509/x509_obj.cpp b/src/lib/x509/x509_obj.cpp index fcd4604325b..f7aff662bd1 100644 --- a/src/lib/x509/x509_obj.cpp +++ b/src/lib/x509/x509_obj.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -168,7 +169,7 @@ std::string x509_signature_padding_for(const std::string& algo_name, } } else if(algo_name == "Ed25519") { return user_specified_padding.empty() ? "Pure" : std::string(user_specified_padding); - } else if(algo_name.starts_with("Dilithium-")) { + } else if(starts_with(algo_name, "Dilithium-")) { return user_specified_padding.empty() ? "Randomized" : std::string(user_specified_padding); } else if(algo_name == "XMSS") { // XMSS does not take any padding, but if the user insists, we pass it along diff --git a/src/lib/x509/x509path.cpp b/src/lib/x509/x509path.cpp index a57aa069baf..e61e19d209c 100644 --- a/src/lib/x509/x509path.cpp +++ b/src/lib/x509/x509path.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -135,7 +136,7 @@ CertificatePathStatusCodes PKIX::check_chain(const std::vector // Ignore untrusted hashes on self-signed roots if(!trusted_hashes.empty() && !at_self_signed_root) { - if(!trusted_hashes.contains(hash_used_for_signature)) { + if(!contains(trusted_hashes, hash_used_for_signature)) { status.insert(Certificate_Status_Code::UNTRUSTED_HASH); } } @@ -542,7 +543,7 @@ CertificatePathStatusCodes PKIX::check_crl_online(const std::vectoradd_crl(*crls[i]); @@ -607,7 +608,7 @@ Certificate_Status_Code PKIX::build_certificate_path(std::vectorfingerprint("SHA-256"); - if(certs_seen.contains(fprint)) // already seen? + if(contains(certs_seen, fprint)) // already seen? { return Certificate_Status_Code::CERT_CHAIN_LOOP; } diff --git a/src/lib/xof/aes_crystals_xof/aes_crystals_xof.cpp b/src/lib/xof/aes_crystals_xof/aes_crystals_xof.cpp index c8e93b258b9..dcc9e120366 100644 --- a/src/lib/xof/aes_crystals_xof/aes_crystals_xof.cpp +++ b/src/lib/xof/aes_crystals_xof/aes_crystals_xof.cpp @@ -22,7 +22,7 @@ void AES_256_CTR_XOF::reset() { m_stream_cipher->clear(); } -void AES_256_CTR_XOF::start_msg(std::span iv, std::span key) { +void AES_256_CTR_XOF::start_msg(Botan::span iv, Botan::span key) { m_stream_cipher->set_key(key); m_stream_cipher->set_iv(iv); } @@ -39,13 +39,13 @@ std::unique_ptr AES_256_CTR_XOF::copy_state() const { throw Not_Implemented(fmt("Copying the state of XOF {} is not implemented", name())); } -void AES_256_CTR_XOF::add_data(std::span input) { +void AES_256_CTR_XOF::add_data(Botan::span input) { if(!input.empty()) { throw Not_Implemented(fmt("XOF {} does not support data input", name())); } } -void AES_256_CTR_XOF::generate_bytes(std::span output) { +void AES_256_CTR_XOF::generate_bytes(Botan::span output) { m_stream_cipher->write_keystream(output); } diff --git a/src/lib/xof/aes_crystals_xof/aes_crystals_xof.h b/src/lib/xof/aes_crystals_xof/aes_crystals_xof.h index 50e2ad1ba72..ae8d9d515d2 100644 --- a/src/lib/xof/aes_crystals_xof/aes_crystals_xof.h +++ b/src/lib/xof/aes_crystals_xof/aes_crystals_xof.h @@ -51,14 +51,14 @@ class BOTAN_TEST_API AES_256_CTR_XOF final : public XOF { * Sets the @p IV and @p key of the underlying AES-256/CTR object. * Do not call AES_256_CTR_XOF::update(), on this object! */ - void start_msg(std::span iv = {}, std::span key = {}) override; + void start_msg(Botan::span iv = {}, Botan::span key = {}) override; /** * @throws Not_Implemented, use XOF::start() instead of XOF::update() */ - void add_data(std::span) override; + void add_data(Botan::span) override; - void generate_bytes(std::span output) override; + void generate_bytes(Botan::span output) override; private: std::unique_ptr m_stream_cipher; diff --git a/src/lib/xof/cshake_xof/cshake_xof.cpp b/src/lib/xof/cshake_xof/cshake_xof.cpp index 873237ab027..f878b444822 100644 --- a/src/lib/xof/cshake_xof/cshake_xof.cpp +++ b/src/lib/xof/cshake_xof/cshake_xof.cpp @@ -21,7 +21,7 @@ cSHAKE_XOF::cSHAKE_XOF(size_t capacity, std::vector function_name) : BOTAN_ASSERT_NOMSG(capacity == 256 || capacity == 512); } -cSHAKE_XOF::cSHAKE_XOF(size_t capacity, std::span function_name) : +cSHAKE_XOF::cSHAKE_XOF(size_t capacity, Botan::span function_name) : cSHAKE_XOF(capacity, std::vector{function_name.begin(), function_name.end()}) {} cSHAKE_XOF::cSHAKE_XOF(size_t capacity, std::string_view function_name) : @@ -52,18 +52,18 @@ bool cSHAKE_XOF::valid_salt_length(size_t salt_length) const { return m_function_name.size() + salt_length > 0; } -void cSHAKE_XOF::start_msg(std::span salt, std::span key) { +void cSHAKE_XOF::start_msg(Botan::span salt, Botan::span key) { BOTAN_STATE_CHECK(!m_output_generated); BOTAN_ASSERT_NOMSG(key.empty()); keccak_absorb_padded_strings_encoding(*this, block_size(), m_function_name, salt); } -void cSHAKE_XOF::add_data(std::span input) { +void cSHAKE_XOF::add_data(Botan::span input) { BOTAN_STATE_CHECK(!m_output_generated); m_keccak.absorb(input); } -void cSHAKE_XOF::generate_bytes(std::span output) { +void cSHAKE_XOF::generate_bytes(Botan::span output) { if(!m_output_generated) { m_output_generated = true; m_keccak.finish(); diff --git a/src/lib/xof/cshake_xof/cshake_xof.h b/src/lib/xof/cshake_xof/cshake_xof.h index d32440d5c89..8a12a34d454 100644 --- a/src/lib/xof/cshake_xof/cshake_xof.h +++ b/src/lib/xof/cshake_xof/cshake_xof.h @@ -30,7 +30,7 @@ class BOTAN_TEST_API cSHAKE_XOF : public XOF { * derived from cSHAKE */ cSHAKE_XOF(size_t capacity, std::vector function_name); - cSHAKE_XOF(size_t capacity, std::span function_name); + cSHAKE_XOF(size_t capacity, Botan::span function_name); cSHAKE_XOF(size_t capacity, std::string_view function_name); public: @@ -50,9 +50,9 @@ class BOTAN_TEST_API cSHAKE_XOF : public XOF { * @param salt the S value for cSHAKE (see NIST SP.800-185) * @param key not supported, must be an empty buffer */ - void start_msg(std::span salt, std::span key) final; - void add_data(std::span input) final; - void generate_bytes(std::span output) final; + void start_msg(Botan::span salt, Botan::span key) final; + void add_data(Botan::span input) final; + void generate_bytes(Botan::span output) final; void reset() final; private: @@ -69,7 +69,7 @@ class BOTAN_TEST_API cSHAKE_128_XOF final : public cSHAKE_XOF { public: cSHAKE_128_XOF(std::vector function_name) : cSHAKE_XOF(256, std::move(function_name)) {} - cSHAKE_128_XOF(std::span function_name) : cSHAKE_XOF(256, function_name) {} + cSHAKE_128_XOF(Botan::span function_name) : cSHAKE_XOF(256, function_name) {} cSHAKE_128_XOF(std::string_view function_name) : cSHAKE_XOF(256, function_name) {} @@ -88,7 +88,7 @@ class BOTAN_TEST_API cSHAKE_256_XOF final : public cSHAKE_XOF { public: cSHAKE_256_XOF(std::vector function_name) : cSHAKE_XOF(512, std::move(function_name)) {} - cSHAKE_256_XOF(std::span function_name) : cSHAKE_XOF(512, function_name) {} + cSHAKE_256_XOF(Botan::span function_name) : cSHAKE_XOF(512, function_name) {} cSHAKE_256_XOF(std::string_view function_name) : cSHAKE_XOF(512, function_name) {} diff --git a/src/lib/xof/shake_xof/shake_xof.cpp b/src/lib/xof/shake_xof/shake_xof.cpp index c4e9dcba89b..8c72fb59e0a 100644 --- a/src/lib/xof/shake_xof/shake_xof.cpp +++ b/src/lib/xof/shake_xof/shake_xof.cpp @@ -20,12 +20,12 @@ void SHAKE_XOF::reset() { m_output_generated = false; } -void SHAKE_XOF::add_data(std::span input) { +void SHAKE_XOF::add_data(Botan::span input) { BOTAN_STATE_CHECK(!m_output_generated); m_keccak.absorb(input); } -void SHAKE_XOF::generate_bytes(std::span output) { +void SHAKE_XOF::generate_bytes(Botan::span output) { if(!m_output_generated) { m_output_generated = true; m_keccak.finish(); diff --git a/src/lib/xof/shake_xof/shake_xof.h b/src/lib/xof/shake_xof/shake_xof.h index f25ca11897e..b30e2c60019 100644 --- a/src/lib/xof/shake_xof/shake_xof.h +++ b/src/lib/xof/shake_xof/shake_xof.h @@ -37,8 +37,8 @@ class SHAKE_XOF : public XOF { bool accepts_input() const final { return !m_output_generated; } private: - void add_data(std::span input) final; - void generate_bytes(std::span output) final; + void add_data(Botan::span input) final; + void generate_bytes(Botan::span output) final; void reset() final; private: diff --git a/src/lib/xof/xof.cpp b/src/lib/xof/xof.cpp index 5153e8080d0..a02f3a146fc 100644 --- a/src/lib/xof/xof.cpp +++ b/src/lib/xof/xof.cpp @@ -55,7 +55,7 @@ std::string XOF::provider() const { return "base"; } -void XOF::start(std::span salt, std::span key) { +void XOF::start(Botan::span salt, Botan::span key) { if(!key_spec().valid_keylength(key.size())) { throw Invalid_Key_Length(name(), key.size()); } @@ -68,7 +68,7 @@ void XOF::start(std::span salt, std::span key) { start_msg(salt, key); } -void XOF::start_msg(std::span salt, std::span key) { +void XOF::start_msg(Botan::span salt, Botan::span key) { BOTAN_UNUSED(salt, key); } diff --git a/src/lib/xof/xof.h b/src/lib/xof/xof.h index b6a3bd6ccd1..f479a68c87e 100644 --- a/src/lib/xof/xof.h +++ b/src/lib/xof/xof.h @@ -83,7 +83,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { * @param salt a salt value to parameterize the XOF * @param key a key to parameterize the XOF */ - void start(std::span salt = {}, std::span key = {}); + void start(Botan::span salt = {}, Botan::span key = {}); /** * @returns true if salt length is acceptable, false otherwise @@ -139,7 +139,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { * * @param input the data that shall be */ - void update(std::span input) { + void update(Botan::span input) { if(!m_xof_started) { // If the user didn't start() before the first input, we enforce // it with a default value, here. @@ -151,7 +151,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { /** * @return the next @p bytes output bytes as the specified container type @p T. */ - template > + template , typename = concepts::resizable_byte_buffer> T output(size_t bytes) { T out(bytes); generate_bytes(out); @@ -170,7 +170,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { * Fill @p output with the next output bytes. The number of bytes * depends on the size of @p output. */ - void output(std::span output) { generate_bytes(output); } + void output(Botan::span output) { generate_bytes(output); } /** * @return the next single output byte @@ -189,7 +189,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { * @param salt a salt value to parameterize the XOF * @param key a key to parameterize the XOF */ - virtual void start_msg(std::span salt, std::span key); + virtual void start_msg(Botan::span salt, Botan::span key); /** * Consume @p input data bytes into the XOF's internal state @@ -202,7 +202,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { * @param input the span to be consumed entirely into the internal state * @throws Invalid_State if input is added after generating output */ - virtual void add_data(std::span input) = 0; + virtual void add_data(Botan::span input) = 0; /** * Fill the entire @p output span with the next bytes in their output @@ -214,7 +214,7 @@ class BOTAN_PUBLIC_API(3, 2) XOF { * * @param output the span to be filled entirely with output bytes */ - virtual void generate_bytes(std::span output) = 0; + virtual void generate_bytes(Botan::span output) = 0; /** * Clear the XOF's internal state and allow for new input. diff --git a/src/tests/runner/test_runner.cpp b/src/tests/runner/test_runner.cpp index 289e9aad7fc..2bfcc6d14fa 100644 --- a/src/tests/runner/test_runner.cpp +++ b/src/tests/runner/test_runner.cpp @@ -44,7 +44,7 @@ class Testsuite_RNG final : public Botan::RandomNumberGenerator { bool is_seeded() const override { return true; } - void fill_bytes_with_input(std::span output, std::span input) override { + void fill_bytes_with_input(Botan::span output, Botan::span input) override { for(const auto byte : input) { mix(byte); } diff --git a/src/tests/test_bigint.cpp b/src/tests/test_bigint.cpp index 5da90d8406b..c8b5eb491e4 100644 --- a/src/tests/test_bigint.cpp +++ b/src/tests/test_bigint.cpp @@ -14,6 +14,7 @@ #include #include #include + #include #endif namespace Botan_Tests { @@ -698,7 +699,7 @@ class Lucas_Primality_Test final : public Test { if(is_lucas_pp) { result.confirm("Lucas pseudoprime is in list", lucas_pp.count(i) == 1); } else { - result.confirm("Lucas non-pseudoprime is not in list", !lucas_pp.contains(i)); + result.confirm("Lucas non-pseudoprime is not in list", !Botan::contains(lucas_pp, i)); } } diff --git a/src/tests/test_bufcomp.cpp b/src/tests/test_bufcomp.cpp index 04df35684b0..7f5d13b7cbb 100644 --- a/src/tests/test_bufcomp.cpp +++ b/src/tests/test_bufcomp.cpp @@ -27,7 +27,7 @@ class Test_Buf_Comp final : public Botan::Buffered_Computation { size_t output_length() const override { return sizeof(m_counter); } - void add_data(std::span input) override { + void add_data(Botan::span input) override { if(m_result.test_eq("input length as expected", input.size(), size_t(5))) { m_result.confirm("input[0] == 'A'", input[0] == 'A'); m_result.confirm("input[0] == 'B'", input[1] == 'B'); @@ -39,7 +39,7 @@ class Test_Buf_Comp final : public Botan::Buffered_Computation { ++m_counter; } - void final_result(std::span out) override { + void final_result(Botan::span out) override { const uint8_t* counter = reinterpret_cast(&m_counter); std::copy(counter, counter + sizeof(m_counter), out.begin()); } @@ -51,7 +51,7 @@ class Test_Buf_Comp final : public Botan::Buffered_Computation { size_t m_counter; }; -void check(Test::Result& result, std::span produced, size_t expected) { +void check(Test::Result& result, Botan::span produced, size_t expected) { const uint8_t* eptr = reinterpret_cast(&expected); result.confirm("result is correct", Botan::same_mem(produced.data(), eptr, sizeof(size_t))); } diff --git a/src/tests/test_contains.cpp b/src/tests/test_contains.cpp new file mode 100644 index 00000000000..b2246cce6ef --- /dev/null +++ b/src/tests/test_contains.cpp @@ -0,0 +1,83 @@ +/* + * (C) 2023 Piotr Staniszewski - CodeVision + * + * Botan is released under the Simplified BSD License (see license.txt) + */ + +#include "tests.h" + +#include + +#include +#include +#include +#include + +namespace Botan_Tests { + +namespace { + +std::vector test_contains() { + return { + Botan_Tests::CHECK("std::map contains", + [](auto& result) { + std::map input{{1, "a"}, {2, "b"}, {3, "c"}}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 1), true); + }), + Botan_Tests::CHECK("std::multimap contains", + [](auto& result) { + std::multimap input{{1, "a"}, {2, "b"}, {3, "c"}, {2, "d"}}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 2), true); + }), + Botan_Tests::CHECK("std::set contains", + [](auto& result) { + std::set input{1, 2, 3}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 1), true); + }), + Botan_Tests::CHECK("std::multiset contains", + [](auto& result) { + std::multiset input{1, 2, 3, 2}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 2), true); + }), + + Botan_Tests::CHECK("std::unordered_map contains", + [](auto& result) { + std::unordered_map input{{1, "a"}, {2, "b"}, {3, "c"}}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 1), true); + }), + Botan_Tests::CHECK("std::unordered_multimap contains", + [](auto& result) { + std::unordered_multimap input{{1, "a"}, {2, "b"}, {3, "c"}, {2, "d"}}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 2), true); + }), + Botan_Tests::CHECK("std::unordered_set contains", + [](auto& result) { + std::unordered_set input{1, 2, 3}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 1), true); + }), + Botan_Tests::CHECK("std::unordered_multiset contains", [](auto& result) { + std::unordered_multiset input{1, 2, 3, 2}; + + result.confirm("not contains", Botan::contains(input, 5), false); + result.confirm("contains", Botan::contains(input, 2), true); + })}; +} +} // namespace + +BOTAN_REGISTER_TEST_FN("utils", "contains", test_contains); + +} // namespace Botan_Tests diff --git a/src/tests/test_erase_if.cpp b/src/tests/test_erase_if.cpp new file mode 100644 index 00000000000..9ba46d0a3f0 --- /dev/null +++ b/src/tests/test_erase_if.cpp @@ -0,0 +1,53 @@ +/* + * (C) 2023 Piotr Staniszewski - CodeVision + * + * Botan is released under the Simplified BSD License (see license.txt) + */ + +#include "tests.h" + +#include + +#include + +namespace Botan_Tests { + +namespace { + +std::vector test_erase_if() { + return { + Botan_Tests::CHECK("erase_if from empty", + [](auto& result) { + std::map m{}; + + auto erased_count = Botan::erase_if(m, [](const auto&) { return true; }); + result.test_is_eq("erase_if from empty", erased_count, size_t(0)); + }), + Botan_Tests::CHECK("erase_if none", + [](auto& result) { + std::map m{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}}; + + auto erased_count = Botan::erase_if(m, [](const auto&) { return false; }); + result.test_is_eq("erase_if erases nothing", erased_count, size_t(0)); + }), + Botan_Tests::CHECK("erase_if single", + [](auto& result) { + std::map m{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}}; + + auto erased_count = Botan::erase_if(m, [](const auto& elem) { return elem.first == 2; }); + result.test_is_eq("erase_if erases 1 element", erased_count, size_t(1)); + }), + Botan_Tests::CHECK("erase_if all", + [](auto& result) { + std::map m{{1, "a"}, {2, "b"}, {3, "c"}, {4, "d"}}; + + auto erased_count = Botan::erase_if(m, [](const auto&) { return true; }); + result.test_is_eq("erase_if erases all elements", erased_count, size_t(4)); + }), + }; +} +} // namespace + +BOTAN_REGISTER_TEST_FN("utils", "erase_if", test_erase_if); + +} // namespace Botan_Tests diff --git a/src/tests/test_ffi.cpp b/src/tests/test_ffi.cpp index 02618f89c62..e8068c92304 100644 --- a/src/tests/test_ffi.cpp +++ b/src/tests/test_ffi.cpp @@ -16,6 +16,7 @@ #include #include #include + #include #include #endif @@ -1439,7 +1440,7 @@ class FFI_ErrorHandling_Test final : public FFI_Test { std::string s(err); if(s != "Unknown error") { - result.confirm("No duplicate messages", !errors.contains(s)); + result.confirm("No duplicate messages", !Botan::contains(errors, s)); errors.insert(s); } } diff --git a/src/tests/test_ocb.cpp b/src/tests/test_ocb.cpp index 657249c0d77..f825a5da805 100644 --- a/src/tests/test_ocb.cpp +++ b/src/tests/test_ocb.cpp @@ -37,7 +37,7 @@ class OCB_Wide_Test_Block_Cipher final : public Botan::BlockCipher { bool has_keying_material() const override { return !m_key.empty(); } - void key_schedule(std::span key) override { m_key.assign(key.begin(), key.end()); } + void key_schedule(Botan::span key) override { m_key.assign(key.begin(), key.end()); } Botan::Key_Length_Specification key_spec() const override { return Botan::Key_Length_Specification(m_bs); } diff --git a/src/tests/test_ocsp.cpp b/src/tests/test_ocsp.cpp index d64e3619561..d92819b2e3f 100644 --- a/src/tests/test_ocsp.cpp +++ b/src/tests/test_ocsp.cpp @@ -12,6 +12,7 @@ #include #include #include + #include #include #endif @@ -178,8 +179,8 @@ class OCSP_Tests final : public Test { return result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1) && result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1) && result.confirm(std::string("Status: '") + Botan::to_string(expected) + "'", - ocsp_status[0].contains(expected)); - }; + contains(ocsp_status[0], expected)); + }; check_ocsp(Botan::calendar_point(2016, 11, 11, 12, 30, 0).to_std_timepoint(), Botan::Certificate_Status_Code::OCSP_NOT_YET_VALID); @@ -218,8 +219,8 @@ class OCSP_Tests final : public Test { return result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1) && result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1) && result.confirm(std::string("Status: '") + Botan::to_string(expected) + "'", - ocsp_status[0].contains(expected)); - }; + contains(ocsp_status[0], expected)); + }; check_ocsp(Botan::calendar_point(2016, 11, 11, 12, 30, 0).to_std_timepoint(), Botan::Certificate_Status_Code::OCSP_NOT_YET_VALID); @@ -258,8 +259,8 @@ class OCSP_Tests final : public Test { return result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1) && result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1) && result.confirm(std::string("Status: '") + Botan::to_string(expected) + "'", - ocsp_status[0].contains(expected)); - }; + contains(ocsp_status[0], expected)); + }; check_ocsp(Botan::calendar_point(2019, 5, 28, 7, 0, 0).to_std_timepoint(), Botan::Certificate_Status_Code::OCSP_NOT_YET_VALID); @@ -293,8 +294,8 @@ class OCSP_Tests final : public Test { return result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1) && result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1) && result.confirm(std::string("Status: '") + Botan::to_string(expected) + "'", - ocsp_status[0].contains(expected)); - }; + contains(ocsp_status[0], expected)); + }; check_ocsp(Botan::calendar_point(2019, 5, 28, 7, 0, 0).to_std_timepoint(), Botan::Certificate_Status_Code::OCSP_NOT_YET_VALID); @@ -354,9 +355,8 @@ class OCSP_Tests final : public Test { if(result.test_eq("Expected size of ocsp_status", ocsp_status.size(), 1)) { if(result.test_eq("Expected size of ocsp_status[0]", ocsp_status[0].size(), 1)) { - const bool status_good = ocsp_status[0].contains(Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD); - const bool server_not_found = - ocsp_status[0].contains(Botan::Certificate_Status_Code::OCSP_SERVER_NOT_AVAILABLE); + const bool status_good = Botan::contains(ocsp_status[0], Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD); + const bool server_not_found = Botan::contains(ocsp_status[0], Botan::Certificate_Status_Code::OCSP_SERVER_NOT_AVAILABLE); result.confirm("Expected status", status_good || server_not_found); } } diff --git a/src/tests/test_rng.h b/src/tests/test_rng.h index 511d64e0d32..ab9e83bc3a8 100644 --- a/src/tests/test_rng.h +++ b/src/tests/test_rng.h @@ -59,7 +59,7 @@ class Fixed_Output_RNG : public Botan::RandomNumberGenerator { Fixed_Output_RNG() = default; protected: - void fill_bytes_with_input(std::span output, std::span input) override { + void fill_bytes_with_input(Botan::span output, Botan::span input) override { m_buf.insert(m_buf.end(), input.begin(), input.end()); for(auto& o : output) { @@ -105,7 +105,7 @@ class Fixed_Output_Position_RNG final : public Fixed_Output_RNG { Fixed_Output_RNG(in_str), m_pos(pos) {} private: - void fill_bytes_with_input(std::span output, std::span input) override { + void fill_bytes_with_input(Botan::span output, Botan::span input) override { if(!input.empty()) { throw Test_Error("add_entropy() not supported by this RNG, test bug?"); } @@ -141,7 +141,7 @@ class SeedCapturing_RNG final : public Botan::RandomNumberGenerator { const std::vector& seed_material() const { return m_seed; } private: - void fill_bytes_with_input(std::span output, std::span input) override { + void fill_bytes_with_input(Botan::span output, Botan::span input) override { if(!output.empty()) { throw Test_Error("SeedCapturing_RNG has no output"); } @@ -174,7 +174,7 @@ class Request_Counting_RNG final : public Botan::RandomNumberGenerator { std::string name() const override { return "Request_Counting_RNG"; } private: - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { /* The HMAC_DRBG and ChaCha reseed KATs assume this RNG type outputs all 0x80 @@ -206,14 +206,14 @@ class CTR_DRBG_AES256 final : public Botan::RandomNumberGenerator { bool is_seeded() const override { return true; } - CTR_DRBG_AES256(std::span seed); + CTR_DRBG_AES256(Botan::span seed); private: - void fill_bytes_with_input(std::span output, std::span input) override; + void fill_bytes_with_input(Botan::span output, Botan::span input) override; - void incr_V_into(std::span output); + void incr_V_into(Botan::span output); - void update(std::span provided_data); + void update(Botan::span provided_data); uint64_t m_V0, m_V1; std::unique_ptr m_cipher; diff --git a/src/tests/test_rng_behavior.cpp b/src/tests/test_rng_behavior.cpp index bd39bc3cf4d..e879fb68ebd 100644 --- a/src/tests/test_rng_behavior.cpp +++ b/src/tests/test_rng_behavior.cpp @@ -8,6 +8,8 @@ #include "test_rng.h" #include "tests.h" +#include + #if defined(BOTAN_HAS_STATEFUL_RNG) #include #endif @@ -583,7 +585,7 @@ std::vector hmac_drbg_multiple_requests() { rng1->randomize_with_input(bulk, seed); std::vector split(3 * rng_max_output); - std::span split_span(split); + Botan::span split_span(split); rng2->randomize_with_input(split_span.subspan(0, rng_max_output), seed); rng2->randomize_with_input(split_span.subspan(rng_max_output, rng_max_output), {}); rng2->randomize_with_input(split_span.subspan(2 * rng_max_output), {}); @@ -704,7 +706,7 @@ class AutoSeeded_RNG_Tests final : public Test { Botan::AutoSeeded_RNG rng; - result.confirm("AutoSeeded_RNG::name", rng.name().starts_with("HMAC_DRBG(HMAC(SHA-")); + result.confirm("AutoSeeded_RNG::name", Botan::starts_with(rng.name(), "HMAC_DRBG(HMAC(SHA-")); result.confirm("AutoSeeded_RNG starts seeded", rng.is_seeded()); rng.random_vec(16); // generate and discard output diff --git a/src/tests/test_rngs.cpp b/src/tests/test_rngs.cpp index 60041bb519a..2aa7a33be5c 100644 --- a/src/tests/test_rngs.cpp +++ b/src/tests/test_rngs.cpp @@ -23,7 +23,7 @@ void CTR_DRBG_AES256::clear() { m_V1 = 0; } -void CTR_DRBG_AES256::fill_bytes_with_input(std::span output, std::span input) { +void CTR_DRBG_AES256::fill_bytes_with_input(Botan::span output, Botan::span input) { if(!input.empty()) { if(input.size() != 48) { throw Test_Error("CTR_DRBG(AES-256) assumes 48 byte input"); @@ -54,12 +54,12 @@ void CTR_DRBG_AES256::fill_bytes_with_input(std::span output, std::span } } -CTR_DRBG_AES256::CTR_DRBG_AES256(std::span seed) { +CTR_DRBG_AES256::CTR_DRBG_AES256(Botan::span seed) { m_cipher = Botan::BlockCipher::create_or_throw("AES-256"); add_entropy(seed); } -void CTR_DRBG_AES256::incr_V_into(std::span output) { +void CTR_DRBG_AES256::incr_V_into(Botan::span output) { BOTAN_ASSERT_NOMSG(output.size() == 16); m_V1 += 1; @@ -70,10 +70,10 @@ void CTR_DRBG_AES256::incr_V_into(std::span output) { Botan::store_be(output.data(), m_V0, m_V1); } -void CTR_DRBG_AES256::update(std::span provided_data) { +void CTR_DRBG_AES256::update(Botan::span provided_data) { std::array temp = {0}; - std::span t(temp); + Botan::span t(temp); for(size_t i = 0; i != 3; ++i) { incr_V_into(t.subspan(16 * i, 16)); } diff --git a/src/tests/test_span.cpp b/src/tests/test_span.cpp new file mode 100644 index 00000000000..6a34678fc93 --- /dev/null +++ b/src/tests/test_span.cpp @@ -0,0 +1,622 @@ +/* +* (C) 2023 Piotr Staniszewski - CodeVision +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +#include + +#include +#include +#include +#include + +namespace Botan_Tests { + +namespace { + +constexpr size_t SIZE = 5UL; +int C_ARRAY[SIZE] = {1, 2, 3, 4, 5}; +std::array ARRAY = {1, 2, 3, 4, 5}; +const std::array CONST_ARRAY = {1, 2, 3, 4, 5}; +std::vector VECTOR = {1, 2, 3, 4, 5}; +const std::vector CONST_VECTOR = {1, 2, 3, 4, 5}; +const std::string CONST_STRING = "abcdef"; + +template +struct Dummy {}; + +template +struct With_size { + std::size_t size() const noexcept { return 1; } +}; + +template +struct With_data { + T* data() const noexcept { return &value; } + + private: + T value; +}; + +template +struct With_size_and_data : public With_size, + With_data {}; + +std::vector test_ctors() { + return {Botan_Tests::CHECK("default ctor", + [](auto& result) { + Botan::span s; + + result.test_is_eq("size()", s.size(), size_t(0U)); + result.test_is_eq("data()", s.data(), static_cast(nullptr)); + }), + Botan_Tests::CHECK("ctor with first and size", + [](auto& result) { +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + Botan::span s(&(*std::begin(ARRAY)), ARRAY.size()); +#else + Botan::span s(std::begin(ARRAY), ARRAY.size()); +#endif + + result.test_is_eq("size()", s.size(), ARRAY.size()); +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + result.test_is_eq("data()", s.data(), &(*ARRAY.begin())); +#else + result.test_is_eq("data()", s.data(), ARRAY.begin()); +#endif + }), + Botan_Tests::CHECK("ctor with first and last", + [](auto& result) { +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + Botan::span s(&(*std::begin(ARRAY)), &(*std::end(ARRAY))); +#else + Botan::span s(std::begin(ARRAY), std::end(ARRAY)); +#endif + + result.test_is_eq("size()", s.size(), ARRAY.size()); +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + result.test_is_eq("data()", s.data(), &(*ARRAY.begin())); +#else + result.test_is_eq("data()", s.data(), ARRAY.begin()); +#endif + }), + Botan_Tests::CHECK("ctor with C array", + [](auto& result) { + Botan::span s(C_ARRAY); + + result.test_is_eq("size()", s.size(), size_t(SIZE)); + result.test_is_eq("data()", s.data(), &C_ARRAY[0]); + }), + Botan_Tests::CHECK("ctor with std::array", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("size()", s.size(), ARRAY.size()); +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + result.test_is_eq("data()", s.data(), &(*ARRAY.begin())); +#else + result.test_is_eq("data()", s.data(), ARRAY.begin()); +#endif + }), + Botan_Tests::CHECK("ctor with const std::array", + [](auto& result) { + const Botan::span s(CONST_ARRAY); + + result.test_is_eq("size()", s.size(), CONST_ARRAY.size()); +#if defined(BOTAN_BUILD_COMPILER_IS_MSVC) + result.test_is_eq("data()", s.data(), &(*CONST_ARRAY.begin())); +#else + result.test_is_eq("data()", s.data(), CONST_ARRAY.begin()); +#endif + }), + Botan_Tests::CHECK("ctor with std::vector", + [](auto& result) { + Botan::span s(VECTOR); + + result.test_is_eq("size()", s.size(), VECTOR.size()); + }), + Botan_Tests::CHECK("ctor with const std::vector", + [](auto& result) { + const Botan::span s(CONST_VECTOR); + + result.test_is_eq("size()", s.size(), CONST_VECTOR.size()); + }), + Botan_Tests::CHECK("ctor with span", [](auto& result) { + const Botan::span s(ARRAY); + Botan::span s2(s); + + result.test_is_eq("size()", s2.size(), s.size()); + result.test_is_eq("data()", s2.data(), s.data()); + })}; +} + +std::vector test_assignment_operator() { + return {Botan_Tests::CHECK("operator= from empty", + [](auto& result) { + Botan::span s; + Botan::span s1; + + s = s1; + result.test_is_eq("size()", s.size(), s1.size()); + result.test_is_eq("data()", s.data(), s1.data()); + }), + Botan_Tests::CHECK("operator= from non-empty", [](auto& result) { + Botan::span s; + Botan::span s1(ARRAY); + + s = s1; + result.test_is_eq("size()", s.size(), s1.size()); + result.test_is_eq("data()", s.data(), s1.data()); + })}; +} + +std::vector test_iterators() { + return {Botan_Tests::CHECK("begin() and end() with empty", + [](auto& result) { + Botan::span s; + + result.test_is_eq("begin() == end()", s.begin(), s.end()); + }), + Botan_Tests::CHECK("begin() with non-empty", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("begin() points to first", &(*s.begin()), &ARRAY[0]); + }), + Botan_Tests::CHECK( + "end() with non-empty", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("begin() to end() distance", size_t(std::distance(s.begin(), s.end())), SIZE); + result.test_is_eq("end() points to one after last", &(*(s.end() - 1)), &ARRAY[SIZE - 1]); + }), + Botan_Tests::CHECK("rbegin() and rend() with empty", + [](auto& result) { + Botan::span s; + + result.test_is_eq("rbegin() == rend()", s.rbegin(), s.rend()); + }), + Botan_Tests::CHECK("rbegin() with non-empty", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("rbegin() points to last", &(*s.rbegin()), &ARRAY[SIZE - 1]); + }), + Botan_Tests::CHECK("rend() with non-empty", [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("rbegin() to rend() distance", size_t(std::distance(s.rbegin(), s.rend())), SIZE); + result.test_is_eq("rend() points to one before first", &(*(s.rend() - 1)), &ARRAY[0]); + })}; +} + +std::vector test_element_access() { + return {Botan_Tests::CHECK("front()", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("front() gives first", s.front(), ARRAY[0]); + }), + Botan_Tests::CHECK("back()", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("back() gives last", s.back(), ARRAY[SIZE - 1]); + }), + Botan_Tests::CHECK("operator[]", + [](auto& result) { + Botan::span s(ARRAY); + + for(decltype(ARRAY.size()) i = 0; i < ARRAY.size(); ++i) { + result.test_is_eq("operator[] gives reference to element", s[i], ARRAY[i]); + } + }), + Botan_Tests::CHECK("data()", [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("data() gives pointer to beginning", s.data(), &ARRAY[0]); + })}; +} + +std::vector test_observers() { + return {Botan_Tests::CHECK("size()", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq("size() gives span length", s.size(), ARRAY.size()); + }), + Botan_Tests::CHECK("size_bytes()", + [](auto& result) { + Botan::span s(ARRAY); + + result.test_is_eq( + "size_bytes() gives span size in bytes", s.size_bytes(), sizeof(ARRAY)); + }), + Botan_Tests::CHECK("empty() with empty", + [](auto& result) { + Botan::span s; + + result.confirm("empty() is true", s.empty(), true); + }), + Botan_Tests::CHECK("empty() with non-empty", [](auto& result) { + Botan::span s(ARRAY); + + result.confirm("empty() is false", s.empty(), false); + })}; +} + +std::vector test_subviews() { + return {Botan_Tests::CHECK("first(0) from empty", + [](auto& result) { + Botan::span s; + auto sub = s.first(0UL); + + result.confirm("first(0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("first(0) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.first(0UL); + + result.confirm("first(0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("first(1) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.first(1UL); + + result.test_is_eq("first(1) gives one element span", sub.size(), size_t(1UL)); + result.test_is_eq("first(1) gives first element", &(*sub.begin()), &ARRAY[0]); + }), + Botan_Tests::CHECK("first(SIZE) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.first(SIZE); + + result.test_is_eq("first(SIZE) gives SIZE element span", sub.size(), size_t(SIZE)); + }), + Botan_Tests::CHECK("last(0) from empty", + [](auto& result) { + Botan::span s; + auto sub = s.last(0UL); + + result.confirm("last(0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("last(0) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.last(0UL); + + result.confirm("last(0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("last(1) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.last(1UL); + + result.test_is_eq("last(1) gives one element span", sub.size(), size_t(1UL)); + result.test_is_eq("last(1) gives last element", &(*(sub.end() - 1)), &ARRAY[SIZE - 1]); + }), + Botan_Tests::CHECK("last(SIZE) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.last(SIZE); + + result.test_is_eq("last(SIZE) gives SIZE element span", sub.size(), size_t(SIZE)); + }), + Botan_Tests::CHECK("subspan(0, 0) from empty", + [](auto& result) { + Botan::span s; + auto sub = s.subspan(0UL, 0UL); + + result.confirm("subspan(0, 0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("subspan(0, 0) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.subspan(0UL, 0UL); + + result.confirm("subspan(0, 0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("subspan(1, 0) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.subspan(1UL, 0UL); + + result.confirm("subspan(1, 0) gives empty span", sub.empty(), true); + }), + Botan_Tests::CHECK("subspan(1, 1) from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.subspan(1UL, 1UL); + + result.test_is_eq("subspan(1, 1) gives one element span", sub.size(), size_t(1UL)); + result.test_is_eq( + "subspan(1, 1) starts from second element", &(*sub.begin()), &ARRAY[1]); + }), + Botan_Tests::CHECK("subspan(1, 4) from non-empty", [](auto& result) { + Botan::span s(ARRAY); + auto sub = s.subspan(1UL, 4UL); + + result.test_is_eq("subspan(1, 4) gives 4 elements span", sub.size(), size_t(SIZE - 1UL)); + result.test_is_eq("subspan(1, 4) starts from second element", &(*sub.begin()), &ARRAY[1]); + result.test_is_eq("subspan(1, 4) ends with last element", &(*(sub.end() - 1)), &ARRAY[SIZE - 1UL]); + })}; +} + +std::vector test_non_member() { + return {Botan_Tests::CHECK("as_bytes() from empty", + [](auto& result) { + Botan::span s; + const auto const_bytes = Botan::as_bytes(s); + + result.confirm("as_bytes() gives empty span", const_bytes.empty(), true); + }), + Botan_Tests::CHECK("as_writable_bytes() from empty", + [](auto& result) { + Botan::span s; + auto bytes = Botan::as_bytes(s); + + result.confirm("as_writable_bytes() gives empty span", bytes.empty(), true); + }), + Botan_Tests::CHECK("as_bytes() from non-empty", + [](auto& result) { + Botan::span s(ARRAY); + const auto const_bytes = Botan::as_bytes(s); + + result.test_is_eq("as_bytes() gives sizeof(ARRAY) elements const span", + const_bytes.size(), + size_t(sizeof(ARRAY))); + }), + Botan_Tests::CHECK("as_writable_bytes() from non-empty", [](auto& result) { + Botan::span s(ARRAY); + auto bytes = Botan::as_writable_bytes(s); + + result.test_is_eq("as_writable_bytes() gives sizeof(ARRAY) elements non-const span", + bytes.size(), + size_t(sizeof(ARRAY))); + })}; +} + +std::vector test_misc() { + return {Botan_Tests::CHECK("implicit from std::vector", + [](auto& result) { + std::vector vec{1, 2, 3}; + Botan::span s(vec); + + result.test_is_eq("span from std::vector", s.size(), vec.size()); + }), + Botan_Tests::CHECK("implicit from secure_vector", + [](auto& result) { + Botan::secure_vector vec{1, 2, 3}; + Botan::span s(vec); + + result.test_is_eq("span from secure_vector", s.size(), vec.size()); + }), + Botan_Tests::CHECK("implicit from std::string", [](auto& result) { + std::string str = "abc"; + Botan::span s(str); + + result.test_is_eq("span from std::string", s.size(), str.size()); + })}; +} + +std::vector test_span_detail() { + return { + Botan_Tests::CHECK( + "is_span_convertible_v", + [](auto& result) { + result.confirm("is_span_convertible_v", Botan::detail::is_span_convertible_v, true); + result.confirm( + "is_span_convertible_v", Botan::detail::is_span_convertible_v, true); + result.confirm("is_span_convertible_v", Botan::detail::is_span_convertible_v, false); + result.confirm("is_span_convertible_v", + Botan::detail::is_span_convertible_v, + false); + result.confirm( + "is_span_convertible_v", Botan::detail::is_span_convertible_v, false); + }), + Botan_Tests::CHECK("is_dynamic_extent_v", + [](auto& result) { + result.confirm("is_dynamic_extent_v<0>", Botan::detail::is_dynamic_extent_v<0>, false); + result.confirm( + "is_dynamic_extent_v<100UL>", Botan::detail::is_dynamic_extent_v<100UL>, false); + result.confirm("is_dynamic_extent_v", + Botan::detail::is_dynamic_extent_v, + true); + }), + Botan_Tests::CHECK( + "is_span_capacity_v", + [](auto& result) { + result.confirm("is_span_capacity_v<0, 0>", Botan::detail::is_span_capacity_v<0, 0>, true); + result.confirm("is_span_capacity_v<10, 10>", Botan::detail::is_span_capacity_v<10, 10>, true); + result.confirm("is_span_capacity_v<1, 0>", Botan::detail::is_span_capacity_v<1, 0>, false); + result.confirm("is_span_capacity_v<10, 11>", Botan::detail::is_span_capacity_v<10, 11>, false); + result.confirm("is_span_capacity_v<10UL, 10>", Botan::detail::is_span_capacity_v<10UL, 10>, true); + result.confirm("is_span_capacity_v", + Botan::detail::is_span_capacity_v, + true); + }), + Botan_Tests::CHECK( + "is_span_compatible_v", + [](auto& result) { + result.confirm( + "is_span_compatible_v", Botan::detail::is_span_compatible_v, true); + result.confirm( + "is_span_compatible_v", Botan::detail::is_span_compatible_v, false); + result.confirm("is_span_compatible_v", + Botan::detail::is_span_compatible_v, + false); + result.confirm("is_span_compatible_v", + Botan::detail::is_span_compatible_v, + true); + result.confirm("is_span_compatible_v", + Botan::detail::is_span_compatible_v, + false); + }), + Botan_Tests::CHECK( + "is_span_explicit_v", + [](auto& result) { + result.confirm("is_span_explicit_v<0, 0>", Botan::detail::is_span_explicit_v<0, 0>, false); + result.confirm("is_span_explicit_v<10, 10>", Botan::detail::is_span_explicit_v<10, 10>, false); + result.confirm("is_span_explicit_v", + Botan::detail::is_span_explicit_v, + false); + result.confirm("is_span_explicit_v<10, dynamic_extent>", + Botan::detail::is_span_explicit_v<10, Botan::dynamic_extent>, + true); + result.confirm("is_span_explicit_v", + Botan::detail::is_span_explicit_v, + false); + }), + Botan_Tests::CHECK( + "is_span_copyable_v", + [](auto& result) { + result.confirm( + "is_span_copyable_v", Botan::detail::is_span_copyable_v, false); + result.confirm( + "is_span_copyable_v", Botan::detail::is_span_copyable_v, true); + result.confirm("is_span_copyable_v", + Botan::detail::is_span_copyable_v, + true); + result.confirm("is_span_copyable_v", + Botan::detail::is_span_copyable_v, + true); + result.confirm("is_span_copyable_v", + Botan::detail::is_span_copyable_v, + true); + result.confirm("is_span_copyable_v", + Botan::detail::is_span_copyable_v, + true); + result.confirm("is_span_copyable_v", + Botan::detail::is_span_copyable_v, + false); + }), + Botan_Tests::CHECK( + "is_span_v", + [](auto& result) { + result.confirm("is_span_v", Botan::detail::is_span_v, false); + result.confirm("is_span_v", Botan::detail::is_span_v, false); + result.confirm("is_span_v>", Botan::detail::is_span_v>, false); + result.confirm("is_span_v>", Botan::detail::is_span_v>, false); + result.confirm("is_span_v>", Botan::detail::is_span_v>, true); + }), + Botan_Tests::CHECK( + "is_std_array_v", + [](auto& result) { + result.confirm("is_std_array_v", Botan::detail::is_std_array_v, false); + result.confirm("is_std_array_v", Botan::detail::is_std_array_v, false); + result.confirm( + "is_std_array_v>", Botan::detail::is_std_array_v>, true); + result.confirm("is_std_array_v>", Botan::detail::is_std_array_v>, false); + result.confirm("is_std_array_v>", Botan::detail::is_std_array_v>, false); + }), + Botan_Tests::CHECK( + "size(const Container& c)", + [](auto& result) { + result.test_is_eq("size(C_ARRAY)", Botan::detail::size(C_ARRAY), SIZE); + result.test_is_eq("size(ARRAY)", Botan::detail::size(ARRAY), ARRAY.size()); + result.test_is_eq("size(CONST_ARRAY)", Botan::detail::size(CONST_ARRAY), CONST_ARRAY.size()); + result.test_is_eq("size(VECTOR)", Botan::detail::size(VECTOR), VECTOR.size()); + result.test_is_eq("size(CONST_VECTOR)", Botan::detail::size(CONST_VECTOR), CONST_VECTOR.size()); + result.test_is_eq("size(CONST_STRING)", Botan::detail::size(CONST_STRING), CONST_STRING.size()); + }), + Botan_Tests::CHECK( + "data(const Container& c)", + [](auto& result) { + result.test_is_eq("data(C_ARRAY)", Botan::detail::data(C_ARRAY), &C_ARRAY[0]); + result.test_is_eq("data(ARRAY)", Botan::detail::data(ARRAY), ARRAY.data()); + result.test_is_eq("data(CONST_ARRAY)", Botan::detail::data(CONST_ARRAY), CONST_ARRAY.data()); + result.test_is_eq("data(VECTOR)", Botan::detail::data(VECTOR), VECTOR.data()); + result.test_is_eq("data(CONST_VECTOR)", Botan::detail::data(CONST_VECTOR), CONST_VECTOR.data()); + result.test_is_eq("data(CONST_STRING)", Botan::detail::data(CONST_STRING), CONST_STRING.data()); + }), + Botan_Tests::CHECK( + "has_size_v", + [](auto& result) { + result.confirm("has_size_v", Botan::detail::has_size_v, false); + result.confirm("has_size_v", Botan::detail::has_size_v, false); + result.confirm("has_size_v>", Botan::detail::has_size_v>, false); + result.confirm("has_size_v>", Botan::detail::has_size_v>, true); + result.confirm("has_size_v", Botan::detail::has_size_v, true); + result.confirm("has_size_v>", Botan::detail::has_size_v>, true); + result.confirm("has_size_v>", Botan::detail::has_size_v>, true); + result.confirm("has_size_v>", Botan::detail::has_size_v>, true); + }), + Botan_Tests::CHECK( + "has_data_v", + [](auto& result) { + result.confirm("has_data_v", Botan::detail::has_data_v, false); + result.confirm("has_data_v", Botan::detail::has_data_v, false); + result.confirm("has_data_v>", Botan::detail::has_data_v>, false); + result.confirm("has_data_v>", Botan::detail::has_data_v>, true); + result.confirm("has_data_v", Botan::detail::has_data_v, true); + result.confirm("has_data_v>", Botan::detail::has_data_v>, true); + result.confirm("has_data_v>", Botan::detail::has_data_v>, true); + result.confirm("has_data_v>", Botan::detail::has_data_v>, true); + }), + Botan_Tests::CHECK( + "is_container_v", + [](auto& result) { + result.confirm("is_container_v", Botan::detail::is_container_v, false); + result.confirm("is_container_v", Botan::detail::is_container_v, false); + result.confirm("is_container_v>", Botan::detail::is_container_v>, false); + result.confirm("is_container_v>", Botan::detail::is_container_v>, false); + result.confirm("is_container_v>", Botan::detail::is_container_v>, false); + result.confirm( + "is_container_v>", Botan::detail::is_container_v>, true); + result.confirm("is_container_v", Botan::detail::is_container_v, true); + result.confirm( + "is_container_v>", Botan::detail::is_container_v>, false); + result.confirm("is_container_v>", Botan::detail::is_container_v>, true); + result.confirm("is_container_v>", Botan::detail::is_container_v>, false); + }), + Botan_Tests::CHECK("is_container_type_compatible_v", [](auto& result) { + result.confirm( + "is_container_type_compatible_v", Botan::detail::is_container_type_compatible_v, false); + result.confirm("is_container_type_compatible_v, int>", + Botan::detail::is_container_type_compatible_v, int>, + false); + result.confirm("is_container_type_compatible_v, float>", + Botan::detail::is_container_type_compatible_v, float>, + false); + result.confirm("is_container_type_compatible_v, int>", + Botan::detail::is_container_type_compatible_v, int>, + true); + result.confirm("is_container_type_compatible_v", + Botan::detail::is_container_type_compatible_v, + false); + result.confirm("is_container_type_compatible_v, const int>", + Botan::detail::is_container_type_compatible_v, const int>, + true); + result.confirm("is_container_type_compatible_v, unsigned int>", + Botan::detail::is_container_type_compatible_v, unsigned int>, + false); + result.confirm("is_container_type_compatible_v, const int>", + Botan::detail::is_container_type_compatible_v, const int>, + true); + result.confirm("is_container_type_compatible_v, int>", + Botan::detail::is_container_type_compatible_v, int>, + false); + })}; +} + +BOTAN_REGISTER_TEST_FN("utils", + "span", + test_ctors, + test_assignment_operator, + test_iterators, + test_element_access, + test_observers, + test_subviews, + test_non_member, + test_misc, + test_span_detail); + +} // namespace + +} // namespace Botan_Tests diff --git a/src/tests/test_sphincsplus_fors.cpp b/src/tests/test_sphincsplus_fors.cpp index 18fa396b00e..7700251640f 100644 --- a/src/tests/test_sphincsplus_fors.cpp +++ b/src/tests/test_sphincsplus_fors.cpp @@ -23,7 +23,7 @@ namespace Botan_Tests { class SPHINCS_Plus_FORS_Test final : public Text_Based_Test { private: - static Botan::Sphincs_Address read_address(std::span address_buffer) { + static Botan::Sphincs_Address read_address(Botan::span address_buffer) { BOTAN_ASSERT_NOMSG(address_buffer.size() == 32); std::array adrs; diff --git a/src/tests/test_sphincsplus_utils.cpp b/src/tests/test_sphincsplus_utils.cpp index 9329f20fc0f..c7f329ce029 100644 --- a/src/tests/test_sphincsplus_utils.cpp +++ b/src/tests/test_sphincsplus_utils.cpp @@ -35,7 +35,7 @@ std::vector test_sphincsplus_address() { Botan_Tests::CHECK("set up an address", [&](Test::Result& result) { - Botan::Sphincs_Address a(Botan::Sphincs_Address::ForsTree); + Botan::Sphincs_Address a(Botan::Sphincs_Address_Type::ForsTree); a.set_layer(Botan::HypertreeLayerIndex(1337)) .set_tree(Botan::XmssTreeIndexInLayer(4294967338) /* longer than 32bits */) .set_keypair(Botan::TreeNodeIndex(131072)) @@ -50,7 +50,7 @@ std::vector test_sphincsplus_address() { Botan_Tests::CHECK("set up another address", [&](Test::Result& result) { - Botan::Sphincs_Address a(Botan::Sphincs_Address::ForsTree); + Botan::Sphincs_Address a(Botan::Sphincs_Address_Type::ForsTree); a.set_layer(Botan::HypertreeLayerIndex(1337)) .set_tree(Botan::XmssTreeIndexInLayer(4294967338) /* longer than 32bits */) .set_keypair(Botan::TreeNodeIndex(131072)) @@ -65,7 +65,7 @@ std::vector test_sphincsplus_address() { Botan_Tests::CHECK( "copy subtree", [&](Test::Result& result) { - Botan::Sphincs_Address a(Botan::Sphincs_Address::ForsTree); + Botan::Sphincs_Address a(Botan::Sphincs_Address_Type::ForsTree); a.set_layer(Botan::HypertreeLayerIndex(1337)) .set_tree(Botan::XmssTreeIndexInLayer(4294967338) /* longer than 32bits */) .set_keypair(Botan::TreeNodeIndex(131072)) @@ -87,7 +87,7 @@ std::vector test_sphincsplus_address() { Botan_Tests::CHECK( "copy keypair", [&](Test::Result& result) { - Botan::Sphincs_Address a(Botan::Sphincs_Address::ForsTree); + Botan::Sphincs_Address a(Botan::Sphincs_Address_Type::ForsTree); a.set_layer(Botan::HypertreeLayerIndex(1337)) .set_tree(Botan::XmssTreeIndexInLayer(4294967338) /* longer than 32bits */) .set_keypair(Botan::TreeNodeIndex(131072)) diff --git a/src/tests/test_sphincsplus_wots.cpp b/src/tests/test_sphincsplus_wots.cpp index 3635e3b3283..3bd9be157a4 100644 --- a/src/tests/test_sphincsplus_wots.cpp +++ b/src/tests/test_sphincsplus_wots.cpp @@ -24,7 +24,7 @@ namespace Botan_Tests { class SPHINCS_Plus_WOTS_Test final : public Text_Based_Test { private: static std::pair read_address_and_leaf_idx( - std::span address_buffer) { + Botan::span address_buffer) { BOTAN_ASSERT_NOMSG(address_buffer.size() == 32); std::array adrs; diff --git a/src/tests/test_starts_with.cpp b/src/tests/test_starts_with.cpp new file mode 100644 index 00000000000..510a00fdc4a --- /dev/null +++ b/src/tests/test_starts_with.cpp @@ -0,0 +1,81 @@ +/* + * (C) 2023 Piotr Staniszewski - CodeVision + * + * Botan is released under the Simplified BSD License (see license.txt) + */ + +#include "tests.h" + +#include + +namespace Botan_Tests { + +namespace { + +std::vector test_starts_with() { + return {Botan_Tests::CHECK("starts_with empty", + [](auto& result) { + std::string input{"Hello, World!"}; + + // This is a behavior of std::string's starts_with("") + result.confirm("starts with", Botan::starts_with(input, ""), true); + }), + Botan_Tests::CHECK("empty starts_with empty", + [](auto& result) { + std::string input; + + // This is a behavior of empty std::string's starts_with("") + result.confirm("starts with", Botan::starts_with(input, ""), true); + }), + Botan_Tests::CHECK("empty starts_with non-empty", + [](auto& result) { + std::string input; + + result.confirm("not starts with", Botan::starts_with(input, "Hello"), false); + }), + Botan_Tests::CHECK("std::string starts_with", + [](auto& result) { + std::string input{"Hello, World!"}; + + result.confirm("not starts with", Botan::starts_with(input, "World!"), false); + result.confirm("starts with", Botan::starts_with(input, "Hello"), true); + }), + Botan_Tests::CHECK("std::string_view starts_with", + [](auto& result) { + std::string str{"Hello, World!"}; + std::string_view input{str}; + + result.confirm("not starts with", Botan::starts_with(input, "World!"), false); + result.confirm("starts with", Botan::starts_with(input, "Hello"), true); + }), + Botan_Tests::CHECK("starts_with std::string", + [](auto& result) { + std::string input{"Hello, World!"}; + + result.confirm( + "not starts with", Botan::starts_with(input, std::string("World!")), false); + result.confirm("starts with", Botan::starts_with(input, std::string("Hello")), true); + }), + Botan_Tests::CHECK("starts_with std::string_view", + [](auto& result) { + std::string input{"Hello, World!"}; + std::string_view world = "World!"; + std::string_view hello = "Hello"; + + result.confirm("not starts with", Botan::starts_with(input, world), false); + result.confirm("starts with", Botan::starts_with(input, hello), true); + }), + Botan_Tests::CHECK("starts_with char*", [](auto& result) { + std::string input{"Hello, World!"}; + const char world[] = "World!"; + const char hello[] = "Hello"; + + result.confirm("not starts with", Botan::starts_with(input, world), false); + result.confirm("starts with", Botan::starts_with(input, hello), true); + })}; +} +} // namespace + +BOTAN_REGISTER_TEST_FN("utils", "starts_with", test_starts_with); + +} // namespace Botan_Tests diff --git a/src/tests/test_strong_type.cpp b/src/tests/test_strong_type.cpp index 91e8277bc03..9217c832b9c 100644 --- a/src/tests/test_strong_type.cpp +++ b/src/tests/test_strong_type.cpp @@ -118,29 +118,29 @@ std::vector test_container_strong_type() { using Test_Map = Botan::Strong, struct Test_Map_>; using Test_Array = Botan::Strong, struct Test_Array_>; - result.confirm("Test_Nonce is container", Botan::concepts::container); - result.confirm("Test_Array is container", Botan::concepts::container); - result.confirm("Test_Map is container", Botan::concepts::container); - result.confirm("Test_Size is not container", !Botan::concepts::container); - - result.confirm("Test_Nonce is contiguous_container", Botan::concepts::contiguous_container); - result.confirm("Test_Array is contiguous_container", Botan::concepts::contiguous_container); - result.confirm("Test_Map is not contiguous_container", !Botan::concepts::contiguous_container); - result.confirm("Test_Size is not contiguous_container", !Botan::concepts::contiguous_container); - - result.confirm("Test_Nonce is resizable_container", Botan::concepts::resizable_container); - result.confirm("Test_Array is not resizable_container", !Botan::concepts::resizable_container); - result.confirm("Test_Map is not resizable_container", !Botan::concepts::resizable_container); - result.confirm("Test_Size is not resizable_container", !Botan::concepts::resizable_container); + result.confirm("Test_Nonce is container", Botan::concepts::is_container_v); + result.confirm("Test_Array is container", Botan::concepts::is_container_v); + result.confirm("Test_Map is container", Botan::concepts::is_container_v); + result.confirm("Test_Size is not container", !Botan::concepts::is_container_v); + + result.confirm("Test_Nonce is contiguous_container", Botan::concepts::is_contiguous_container_v); + result.confirm("Test_Array is contiguous_container", Botan::concepts::is_contiguous_container_v); + result.confirm("Test_Map is not contiguous_container", !Botan::concepts::is_contiguous_container_v); + result.confirm("Test_Size is not contiguous_container", !Botan::concepts::is_contiguous_container_v); + + result.confirm("Test_Nonce is resizable_container", Botan::concepts::is_resizable_container_v); + result.confirm("Test_Array is not resizable_container", !Botan::concepts::is_resizable_container_v); + result.confirm("Test_Map is not resizable_container", !Botan::concepts::is_resizable_container_v); + result.confirm("Test_Size is not resizable_container", !Botan::concepts::is_resizable_container_v); }), - Botan_Tests::CHECK("binds to a std::span<>", + Botan_Tests::CHECK("binds to a Botan::span<>", [](auto& result) { - auto get_size = [](std::span data) { return data.size(); }; + auto get_size = [](Botan::span data) { return data.size(); }; const auto nonce = Test_Nonce(Botan::hex_decode("DEADBEEF")); - result.test_is_eq("can bind to std::span<>", get_size(nonce), nonce.size()); + result.test_is_eq("can bind to Botan::span<>", get_size(nonce), nonce.size()); }), Botan_Tests::CHECK("std::string container", @@ -385,12 +385,12 @@ Test::Result test_strong_span() { Botan::StrongSpan span(foo); result.confirm("underlying type is uint8_t", std::is_same_v); - result.confirm("strong type is a contiguous buffer", Botan::concepts::contiguous_container); + result.confirm("strong type is a contiguous buffer", Botan::concepts::is_contiguous_container_v); result.confirm("strong type is a contiguous strong type buffer", - Botan::concepts::contiguous_strong_type); - result.confirm("strong span is not a contiguous buffer", !Botan::concepts::contiguous_container); + Botan::concepts::is_contiguous_strong_type_v); + result.confirm("strong span is not a contiguous buffer", !Botan::concepts::is_contiguous_container_v); result.confirm("strong span is not a contiguous strong type buffer", - !Botan::concepts::contiguous_strong_type); + !Botan::concepts::is_contiguous_strong_type_v); return result; } diff --git a/src/tests/test_tls.cpp b/src/tests/test_tls.cpp index c2ffc25e54f..be415bd7164 100644 --- a/src/tests/test_tls.cpp +++ b/src/tests/test_tls.cpp @@ -32,7 +32,7 @@ class TLS_Session_Tests final : public Test { Test::Result result("TLS::Session"); Botan::TLS::Session session(Botan::secure_vector{0xCC, 0xDD}, - Botan::TLS::Protocol_Version::TLS_V12, + Botan::TLS::Version_Code::TLS_V12, 0xC02F, Botan::TLS::Connection_Side::Client, true, @@ -72,7 +72,7 @@ class TLS_Session_Tests final : public Test { result.test_eq("Only randomness comes from RNG", ctextf1, ctextf2); Botan::TLS::Session session2(Botan::secure_vector{0xCC, 0xEE}, - Botan::TLS::Protocol_Version::TLS_V12, + Botan::TLS::Version_Code::TLS_V12, 0xBAAD, // cipher suite does not exist Botan::TLS::Connection_Side::Client, true, @@ -125,9 +125,9 @@ class TLS_CBC_Tests final : public Text_Based_Test { size_t output_length() const override { return m_mac_len; } - void add_data(std::span /*input*/) override {} + void add_data(Botan::span /*input*/) override {} - void final_result(std::span out) override { + void final_result(Botan::span out) override { for(size_t i = 0; i != m_mac_len; ++i) { out[i] = 0; } @@ -144,7 +144,7 @@ class TLS_CBC_Tests final : public Text_Based_Test { } private: - void key_schedule(std::span /* key */) override {} + void key_schedule(Botan::span /* key */) override {} size_t m_mac_len; }; @@ -178,7 +178,7 @@ class TLS_CBC_Tests final : public Text_Based_Test { } private: - void key_schedule(std::span /*key*/) override {} + void key_schedule(Botan::span /*key*/) override {} size_t m_bs; }; @@ -200,7 +200,7 @@ class TLS_CBC_Tests final : public Text_Based_Test { std::make_unique(mac_len), 0, 0, - Botan::TLS::Protocol_Version::TLS_V12, + Botan::TLS::Version_Code::TLS_V12, encrypt_then_mac); tls_cbc.set_key(std::vector(0)); @@ -238,39 +238,39 @@ class Test_TLS_Alert_Strings : public Test { Test::Result result("TLS::Alert::type_string"); const std::vector alert_types = { - Botan::TLS::Alert::CloseNotify, - Botan::TLS::Alert::UnexpectedMessage, - Botan::TLS::Alert::BadRecordMac, - Botan::TLS::Alert::DecryptionFailed, - Botan::TLS::Alert::RecordOverflow, - Botan::TLS::Alert::DecompressionFailure, - Botan::TLS::Alert::HandshakeFailure, - Botan::TLS::Alert::NoCertificate, - Botan::TLS::Alert::BadCertificate, - Botan::TLS::Alert::UnsupportedCertificate, - Botan::TLS::Alert::CertificateRevoked, - Botan::TLS::Alert::CertificateExpired, - Botan::TLS::Alert::CertificateUnknown, - Botan::TLS::Alert::IllegalParameter, - Botan::TLS::Alert::UnknownCA, - Botan::TLS::Alert::AccessDenied, - Botan::TLS::Alert::DecodeError, - Botan::TLS::Alert::DecryptError, - Botan::TLS::Alert::ExportRestriction, - Botan::TLS::Alert::ProtocolVersion, - Botan::TLS::Alert::InsufficientSecurity, - Botan::TLS::Alert::InternalError, - Botan::TLS::Alert::InappropriateFallback, - Botan::TLS::Alert::UserCanceled, - Botan::TLS::Alert::NoRenegotiation, - Botan::TLS::Alert::MissingExtension, - Botan::TLS::Alert::UnsupportedExtension, - Botan::TLS::Alert::CertificateUnobtainable, - Botan::TLS::Alert::UnrecognizedName, - Botan::TLS::Alert::BadCertificateStatusResponse, - Botan::TLS::Alert::BadCertificateHashValue, - Botan::TLS::Alert::UnknownPSKIdentity, - Botan::TLS::Alert::NoApplicationProtocol, + Botan::TLS::AlertType::CloseNotify, + Botan::TLS::AlertType::UnexpectedMessage, + Botan::TLS::AlertType::BadRecordMac, + Botan::TLS::AlertType::DecryptionFailed, + Botan::TLS::AlertType::RecordOverflow, + Botan::TLS::AlertType::DecompressionFailure, + Botan::TLS::AlertType::HandshakeFailure, + Botan::TLS::AlertType::NoCertificate, + Botan::TLS::AlertType::BadCertificate, + Botan::TLS::AlertType::UnsupportedCertificate, + Botan::TLS::AlertType::CertificateRevoked, + Botan::TLS::AlertType::CertificateExpired, + Botan::TLS::AlertType::CertificateUnknown, + Botan::TLS::AlertType::IllegalParameter, + Botan::TLS::AlertType::UnknownCA, + Botan::TLS::AlertType::AccessDenied, + Botan::TLS::AlertType::DecodeError, + Botan::TLS::AlertType::DecryptError, + Botan::TLS::AlertType::ExportRestriction, + Botan::TLS::AlertType::ProtocolVersion, + Botan::TLS::AlertType::InsufficientSecurity, + Botan::TLS::AlertType::InternalError, + Botan::TLS::AlertType::InappropriateFallback, + Botan::TLS::AlertType::UserCanceled, + Botan::TLS::AlertType::NoRenegotiation, + Botan::TLS::AlertType::MissingExtension, + Botan::TLS::AlertType::UnsupportedExtension, + Botan::TLS::AlertType::CertificateUnobtainable, + Botan::TLS::AlertType::UnrecognizedName, + Botan::TLS::AlertType::BadCertificateStatusResponse, + Botan::TLS::AlertType::BadCertificateHashValue, + Botan::TLS::AlertType::UnknownPSKIdentity, + Botan::TLS::AlertType::NoApplicationProtocol, }; std::set seen; diff --git a/src/tests/test_tls_messages.cpp b/src/tests/test_tls_messages.cpp index 716b4d0f3ac..afdd4fe45f3 100644 --- a/src/tests/test_tls_messages.cpp +++ b/src/tests/test_tls_messages.cpp @@ -59,11 +59,11 @@ class Test_Callbacks : public Botan::TLS::Callbacks { Test_Callbacks(Test::Result& result) : m_result(result) {} public: - void tls_emit_data(std::span) override { + void tls_emit_data(Botan::span) override { m_result.test_failure("unsolicited call to tls_emit_data"); } - void tls_record_received(uint64_t, std::span) override { + void tls_record_received(uint64_t, Botan::span) override { m_result.test_failure("unsolicited call to tls_record_received"); } diff --git a/src/tests/test_tls_rfc8448.cpp b/src/tests/test_tls_rfc8448.cpp index 2f0acbcacb5..f7e93b46eb8 100644 --- a/src/tests/test_tls_rfc8448.cpp +++ b/src/tests/test_tls_rfc8448.cpp @@ -23,6 +23,7 @@ #include "test_rng.h" #include + #include #include #include #include @@ -135,12 +136,12 @@ class Test_TLS_13_Callbacks : public Botan::TLS::Callbacks { m_mock_signatures(std::move(mock_signatures)), m_timestamp(from_milliseconds_since_epoch(timestamp)) {} - void tls_emit_data(std::span data) override { + void tls_emit_data(Botan::span data) override { count_callback_invocation("tls_emit_data"); send_buffer.insert(send_buffer.end(), data.begin(), data.end()); } - void tls_record_received(uint64_t seq_no, std::span data) override { + void tls_record_received(uint64_t seq_no, Botan::span data) override { count_callback_invocation("tls_record_received"); received_seq_no = seq_no; receive_buffer.insert(receive_buffer.end(), data.begin(), data.end()); @@ -316,7 +317,7 @@ class Test_TLS_13_Callbacks : public Botan::TLS::Callbacks { private: void count_callback_invocation(const std::string& callback_name) const { - if(!m_callback_invocations.contains(callback_name)) { + if(!Botan::contains(m_callback_invocations, callback_name)) { m_callback_invocations[callback_name] = 0; } @@ -477,7 +478,7 @@ class RFC8448_Text_Policy : public Botan::TLS::Text_Policy { return value_exists(supported_by_peer, group); }); - return selected_group != supported_by_us.end() ? *selected_group : Named_Group::NONE; + return selected_group != supported_by_us.end() ? *selected_group : Group_Params_Code::NONE; } private: @@ -629,7 +630,7 @@ class TLS_Context { const auto& invokes = m_callbacks->callback_invocations(); for(const auto& cbn : callback_names) { result.confirm(Botan::fmt("{} was invoked (Context: {})", cbn, context), - invokes.contains(cbn) && invokes.at(cbn) > 0); + Botan::contains(invokes, cbn) && invokes.at(cbn) > 0); } for(const auto& invoke : invokes) { @@ -689,7 +690,7 @@ class Client_Context : public TLS_Context { m_policy, m_rng, Botan::TLS::Server_Information("server"), - Botan::TLS::Protocol_Version::TLS_V13) {} + Botan::TLS::Version_Code::TLS_V13) {} void send(const std::vector& data) override { client.send(data.data(), data.size()); } diff --git a/src/tests/test_tls_session_manager.cpp b/src/tests/test_tls_session_manager.cpp index 6c11adcaec8..0fad74a1baf 100644 --- a/src/tests/test_tls_session_manager.cpp +++ b/src/tests/test_tls_session_manager.cpp @@ -34,7 +34,7 @@ // This file contains a number of `Botan::TLS::Version_Code::TLS_V**` protocol // version specifications. This is to work around a compiler bug in GCC 11.3 -// where `Botan::TLS::Protocol_Version::TLS_V12` would lead to an "Internal +// where `Botan::TLS::Version_Code::TLS_V12` would lead to an "Internal // Compiler Error" when used in the affected context. // // TODO: remove the workaround once GCC 11 is not supported anymore. @@ -59,9 +59,9 @@ class Empty_Credentials_Manager : public Botan::Credentials_Manager {}; class Session_Manager_Callbacks : public Botan::TLS::Callbacks { public: - void tls_emit_data(std::span) override { BOTAN_ASSERT_NOMSG(false); } + void tls_emit_data(Botan::span) override { BOTAN_ASSERT_NOMSG(false); } - void tls_record_received(uint64_t, std::span) override { BOTAN_ASSERT_NOMSG(false); } + void tls_record_received(uint64_t, Botan::span) override { BOTAN_ASSERT_NOMSG(false); } void tls_alert(Botan::TLS::Alert) override { BOTAN_ASSERT_NOMSG(false); } @@ -112,7 +112,7 @@ const Botan::TLS::Server_Information server_info("botan.randombit.net"); decltype(auto) default_session(Botan::TLS::Connection_Side side, Botan::TLS::Callbacks& cbs, - Botan::TLS::Protocol_Version version = Botan::TLS::Protocol_Version::TLS_V12) { + Botan::TLS::Protocol_Version version = Botan::TLS::Version_Code::TLS_V12) { if(version.is_pre_tls_13()) { return Botan::TLS::Session( {}, version, 0x009C, side, true, true, {}, server_info, 0, cbs.tls_current_timestamp()); @@ -122,7 +122,7 @@ decltype(auto) default_session(Botan::TLS::Connection_Side side, std::nullopt, 0, std::chrono::seconds(1024), - Botan::TLS::Protocol_Version::TLS_V13, + Botan::TLS::Version_Code::TLS_V13, Botan::TLS::Ciphersuite::from_name("AES_128_GCM_SHA256")->ciphersuite_code(), side, {}, @@ -393,7 +393,7 @@ std::vector test_session_manager_choose_ticket() { auto default_session = [&](const std::string& suite, Botan::TLS::Callbacks& mycbs, - Botan::TLS::Protocol_Version version = Botan::TLS::Protocol_Version::TLS_V13) { + Botan::TLS::Protocol_Version version = Botan::TLS::Version_Code::TLS_V13) { return (version.is_pre_tls_13()) ? Botan::TLS::Session({}, version, @@ -417,7 +417,7 @@ std::vector test_session_manager_choose_ticket() { mycbs.tls_current_timestamp()); }; - auto ticket = [&](std::span identity) { + auto ticket = [&](Botan::span identity) { return Botan::TLS::PskIdentity(std::vector(identity.begin(), identity.end()), 0); }; diff --git a/src/tests/test_tls_stream_integration.cpp b/src/tests/test_tls_stream_integration.cpp index a8708f24a29..b8ad1409104 100644 --- a/src/tests/test_tls_stream_integration.cpp +++ b/src/tests/test_tls_stream_integration.cpp @@ -109,7 +109,7 @@ class Peer { void reset_timeout(const std::string& message) { m_timeout_timer.expires_after(k_timeout); - m_timeout_timer.async_wait([=, this](const error_code& ec) { + m_timeout_timer.async_wait([=](const error_code &ec) { if(ec != net::error::operation_aborted) // timer cancelled { if(m_on_timeout) { @@ -350,9 +350,9 @@ class TestBase { m_server(std::make_shared(server_policy, ioc, m_name)), m_result(m_name) { m_client->on_timeout( - [=, this](const std::string& msg) { m_result.test_failure("timeout in client during: " + msg); }); + [=](const std::string& msg) { m_result.test_failure("timeout in client during: " + msg); }); m_server->on_timeout( - [=, this](const std::string& msg) { m_result.test_failure("timeout in server during: " + msg); }); + [=](const std::string& msg) { m_result.test_failure("timeout in server during: " + msg); }); m_server->listen(); } diff --git a/src/tests/test_utils.cpp b/src/tests/test_utils.cpp index ae056009d83..6699daf204a 100644 --- a/src/tests/test_utils.cpp +++ b/src/tests/test_utils.cpp @@ -649,7 +649,7 @@ class UUID_Tests : public Test { public: explicit AllSame_RNG(uint8_t b) : m_val(b) {} - void fill_bytes_with_input(std::span output, std::span /* ignored */) override { + void fill_bytes_with_input(Botan::span output, Botan::span /* ignored */) override { for(auto& byte : output) { byte = m_val; } diff --git a/src/tests/test_x509_path.cpp b/src/tests/test_x509_path.cpp index bd7fb5338a0..b53c3af00ed 100644 --- a/src/tests/test_x509_path.cpp +++ b/src/tests/test_x509_path.cpp @@ -18,6 +18,7 @@ #include #include #include + #include #include #include @@ -1038,7 +1039,7 @@ class Path_Validation_With_OCSP_Tests final : public Test { result.test_is_eq("should result in expected validation status code", path_result.result(), expected); if(also_expected) { result.confirm("Secondary error is also present", - flatten(path_result.all_statuses()).contains(also_expected.value())); + Botan::contains(flatten(path_result.all_statuses()), also_expected.value())); } }; @@ -1089,7 +1090,7 @@ class Path_Validation_With_OCSP_Tests final : public Test { result.test_is_eq( "Path validation with forged OCSP response should fail with", path_result.result(), expected); result.confirm("Secondary error is also present", - flatten(path_result.all_statuses()).contains(also_expected)); + Botan::contains(flatten(path_result.all_statuses()), also_expected)); result.test_note(std::string("Failed with: ") + Botan::to_string(path_result.result())); }; diff --git a/src/tests/test_xof.cpp b/src/tests/test_xof.cpp index 2f825d716d9..28c825a27e2 100644 --- a/src/tests/test_xof.cpp +++ b/src/tests/test_xof.cpp @@ -133,14 +133,14 @@ class XOF_Tests final : public Text_Based_Test { new_accepts_input); new_xof->start(salt, key); - std::span in_span(in); + Botan::span in_span(in); while(!in_span.empty()) { const auto bytes = std::min(block_size, in_span.size()); new_xof->update(in_span.first(bytes)); in_span = in_span.last(in_span.size() - bytes); } std::vector blockwise_out(expected.size()); - std::span out_span(blockwise_out); + Botan::span out_span(blockwise_out); while(!out_span.empty()) { const auto bytes = std::min(block_size, out_span.size()); new_xof->output(out_span.first(bytes)); @@ -157,11 +157,11 @@ class XOF_Tests final : public Text_Based_Test { try { xof->clear(); xof->start(salt, key); - xof->update(std::span(in).first(in.size() / 2)); + xof->update(Botan::span(in).first(in.size() / 2)); auto xof2 = xof->copy_state(); result.test_eq("copied object might still accept input", xof2->accepts_input(), new_accepts_input); - xof->update(std::span(in).last(in.size() - in.size() / 2)); - xof2->update(std::span(in).last(in.size() - in.size() / 2)); + xof->update(Botan::span(in).last(in.size() - in.size() / 2)); + xof2->update(Botan::span(in).last(in.size() - in.size() / 2)); auto cp_out1 = xof->output_stdvec(expected.size()); auto cp_out2_1 = xof2->output_stdvec(expected.size() / 2); auto xof3 = xof2->copy_state(); @@ -198,14 +198,17 @@ class XOF_Tests final : public Text_Based_Test { }), #endif #if defined(BOTAN_HAS_AES_CRYSTALS_XOF) - Botan_Tests::CHECK("AES-256/CTR XOF failure modes", [](Test::Result& result) { - Botan::AES_256_CTR_XOF aes_xof; - result.test_throws("AES-256/CTR XOF throws for empty key", [&]() { aes_xof.start({}, {}); }); - result.test_throws("AES-256/CTR XOF throws for too long key", - [&]() { aes_xof.start({}, std::vector(33)); }); - result.test_throws("AES-256/CTR XOF throws for too long IV", - [&]() { aes_xof.start(std::vector(17), std::vector(32)); }); - }), + Botan_Tests::CHECK("AES-256/CTR XOF failure modes", + [](Test::Result& result) { + Botan::AES_256_CTR_XOF aes_xof; + result.test_throws("AES-256/CTR XOF throws for empty key", + [&]() { aes_xof.start({}, {}); }); + result.test_throws("AES-256/CTR XOF throws for too long key", + [&]() { aes_xof.start({}, std::vector(33)); }); + result.test_throws("AES-256/CTR XOF throws for too long IV", [&]() { + aes_xof.start(std::vector(17), std::vector(32)); + }); + }), #endif }; } diff --git a/src/tests/tests.cpp b/src/tests/tests.cpp index 5d9d002adc3..7a6ea9c8b4a 100644 --- a/src/tests/tests.cpp +++ b/src/tests/tests.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -85,7 +86,7 @@ void Test::Result::test_note(const std::string& note, const char* extra) { void Test::Result::note_missing(const std::string& whatever) { static std::set s_already_seen; - if(!s_already_seen.contains(whatever)) { + if(!Botan::contains(s_already_seen, whatever)) { test_note("Skipping tests due to missing " + whatever); s_already_seen.insert(whatever); } @@ -466,15 +467,15 @@ class Test_Registry { bool smoke_test, bool needs_serialization, std::function()> maker_fn) { - if(m_tests.contains(name)) { + if(Botan::contains(m_tests, name)) { throw Test_Error("Duplicate registration of test '" + name + "'"); } - if(m_tests.contains(category)) { + if(Botan::contains(m_tests, category)) { throw Test_Error("'" + category + "' cannot be used as category, test exists"); } - if(m_categories.contains(name)) { + if(Botan::contains(m_categories, name)) { throw Test_Error("'" + name + "' cannot be used as test name, category exists"); } @@ -1078,9 +1079,8 @@ std::vector Text_Based_Test::run() { std::string key = strip_ws(std::string(line.begin(), line.begin() + equal_i - 1)); std::string val = strip_ws(std::string(line.begin() + equal_i + 1, line.end())); - if(!m_required_keys.contains(key) && !m_optional_keys.contains(key)) { - auto r = Test::Result::Failure(header_or_name, Botan::fmt("{} failed unknown key {}", test_id, key)); - results.push_back(r); + if(!Botan::contains(m_required_keys, key) && !Botan::contains(m_optional_keys, key)) { + results.push_back(Test::Result::Failure(header_or_name, test_id + " failed unknown key " + key)); } vars.add(key, val); diff --git a/src/tests/unit_asio_stream.cpp b/src/tests/unit_asio_stream.cpp index 79a32f5746d..f97b494f2a3 100644 --- a/src/tests/unit_asio_stream.cpp +++ b/src/tests/unit_asio_stream.cpp @@ -50,7 +50,7 @@ class MockChannel { m_callbacks(std::move(core)), m_bytes_till_complete_record(TEST_DATA_SIZE), m_active(false) {} public: - std::size_t received_data(std::span data) { + std::size_t received_data(Botan::span data) { if(m_bytes_till_complete_record <= data.size()) { m_callbacks->tls_record_received(0, TEST_DATA); m_active = true; // claim to be active once a full record has been received (for handshake test) @@ -60,7 +60,7 @@ class MockChannel { return m_bytes_till_complete_record; } - void send(std::span buf) { m_callbacks->tls_emit_data(buf); } + void send(Botan::span buf) { m_callbacks->tls_emit_data(buf); } bool is_active() const { return m_active; } @@ -72,13 +72,13 @@ class MockChannel { class ThrowingMockChannel : public MockChannel { public: - static boost::system::error_code expected_ec() { return Botan::TLS::Alert::UnexpectedMessage; } + static boost::system::error_code expected_ec() { return Botan::TLS::AlertType::UnexpectedMessage; } ThrowingMockChannel(std::shared_ptr core) : MockChannel(std::move(core)) {} - std::size_t received_data(std::span) { throw Botan::TLS::Unexpected_Message("test_error"); } + std::size_t received_data(Botan::span) { throw Botan::TLS::Unexpected_Message("test_error"); } - void send(std::span) { throw Botan::TLS::Unexpected_Message("test_error"); } + void send(Botan::span) { throw Botan::TLS::Unexpected_Message("test_error"); } }; // Unfortunately, boost::beast::test::stream keeps lowest_layer_type private and diff --git a/src/tests/unit_tls.cpp b/src/tests/unit_tls.cpp index 78aabbbd43a..a1fce95acbe 100644 --- a/src/tests/unit_tls.cpp +++ b/src/tests/unit_tls.cpp @@ -338,11 +338,11 @@ class TLS_Handshake_Test final { } } - void tls_emit_data(std::span bits) override { + void tls_emit_data(Botan::span bits) override { m_outbound.insert(m_outbound.end(), bits.begin(), bits.end()); } - void tls_record_received(uint64_t /*seq*/, std::span bits) override { + void tls_record_received(uint64_t /*seq*/, Botan::span bits) override { m_recv.insert(m_recv.end(), bits.begin(), bits.end()); } @@ -551,7 +551,7 @@ void TLS_Handshake_Test::go() { client->send(&client_msg[sent_so_far], sending); sent_so_far += sending; } - client->send_warning_alert(Botan::TLS::Alert::NoRenegotiation); + client->send_warning_alert(Botan::TLS::AlertType::NoRenegotiation); client_has_written = true; } @@ -568,7 +568,7 @@ void TLS_Handshake_Test::go() { sent_so_far += sending; } - m_server->send_warning_alert(Botan::TLS::Alert::NoRenegotiation); + m_server->send_warning_alert(Botan::TLS::AlertType::NoRenegotiation); server_has_written = true; } @@ -733,8 +733,8 @@ class TLS_Unit_Tests final : public Test { policy->set("signature_methods", "IMPLICIT"); } - std::vector versions = {Botan::TLS::Protocol_Version::TLS_V12, - Botan::TLS::Protocol_Version::DTLS_V12}; + std::vector versions = {Botan::TLS::Version_Code::TLS_V12, + Botan::TLS::Version_Code::DTLS_V12}; return test_with_policy(test_descr, results, client_ses, server_ses, creds, versions, policy, client_auth); } @@ -786,8 +786,8 @@ class TLS_Unit_Tests final : public Test { policy->set(kv.first, kv.second); } - std::vector versions = {Botan::TLS::Protocol_Version::TLS_V12, - Botan::TLS::Protocol_Version::DTLS_V12}; + std::vector versions = {Botan::TLS::Version_Code::TLS_V12, + Botan::TLS::Version_Code::DTLS_V12}; return test_with_policy(test_descr, results, client_ses, server_ses, creds, versions, policy, client_auth); } @@ -795,8 +795,8 @@ class TLS_Unit_Tests final : public Test { void test_session_established_abort(std::vector& results, std::shared_ptr creds, std::shared_ptr rng) { - std::vector versions = {Botan::TLS::Protocol_Version::TLS_V12, - Botan::TLS::Protocol_Version::DTLS_V12}; + std::vector versions = {Botan::TLS::Version_Code::TLS_V12, + Botan::TLS::Version_Code::DTLS_V12}; auto policy = std::make_shared(); auto noop_session_manager = std::make_shared(); @@ -844,21 +844,21 @@ class TLS_Unit_Tests final : public Test { }; client_aborts(std::make_exception_ptr( - Botan::TLS::TLS_Exception(Botan::TLS::Alert::AccessDenied, "some test TLS exception")), - Botan::TLS::Alert::AccessDenied); + Botan::TLS::TLS_Exception(Botan::TLS::AlertType::AccessDenied, "some test TLS exception")), + Botan::TLS::AlertType::AccessDenied); client_aborts(std::make_exception_ptr(Botan::Invalid_Authentication_Tag("some symmetric crypto failed :o)")), - Botan::TLS::Alert::BadRecordMac); + Botan::TLS::AlertType::BadRecordMac); client_aborts(std::make_exception_ptr(std::runtime_error("something strange happened")), - Botan::TLS::Alert::InternalError); + Botan::TLS::AlertType::InternalError); server_aborts(std::make_exception_ptr( - Botan::TLS::TLS_Exception(Botan::TLS::Alert::AccessDenied, "some server test TLS exception")), - Botan::TLS::Alert::AccessDenied); + Botan::TLS::TLS_Exception(Botan::TLS::AlertType::AccessDenied, "some server test TLS exception")), + Botan::TLS::AlertType::AccessDenied); server_aborts(std::make_exception_ptr( Botan::Invalid_Authentication_Tag("some symmetric crypto failed in the server :o)")), - Botan::TLS::Alert::BadRecordMac); + Botan::TLS::AlertType::BadRecordMac); server_aborts(std::make_exception_ptr(std::runtime_error("something strange happened in the server")), - Botan::TLS::Alert::InternalError); + Botan::TLS::AlertType::InternalError); } public: @@ -908,12 +908,12 @@ class TLS_Unit_Tests final : public Test { client_ses, server_ses, creds, - {Botan::TLS::Protocol_Version::TLS_V12}, + {Botan::TLS::Version_Code::TLS_V12}, strict_policy); auto suiteb_128 = std::make_shared(); test_with_policy( - "Suite B", results, client_ses, server_ses, creds, {Botan::TLS::Protocol_Version::TLS_V12}, suiteb_128); + "Suite B", results, client_ses, server_ses, creds, {Botan::TLS::Version_Code::TLS_V12}, suiteb_128); // Remove server sessions before client, so clients retry with session server doesn't know server_ses->remove_all(); @@ -1085,11 +1085,11 @@ class DTLS_Reconnection_Test : public Test { Test_Callbacks(Test::Result& results, std::vector& outbound, std::vector& recv_buf) : m_results(results), m_outbound(outbound), m_recv(recv_buf) {} - void tls_emit_data(std::span bits) override { + void tls_emit_data(Botan::span bits) override { m_outbound.insert(m_outbound.end(), bits.begin(), bits.end()); } - void tls_record_received(uint64_t /*seq*/, std::span bits) override { + void tls_record_received(uint64_t /*seq*/, Botan::span bits) override { m_recv.insert(m_recv.end(), bits.begin(), bits.end()); } diff --git a/src/tests/unit_tls_policy.cpp b/src/tests/unit_tls_policy.cpp index e11c45309e9..7428391d3c8 100644 --- a/src/tests/unit_tls_policy.cpp +++ b/src/tests/unit_tls_policy.cpp @@ -156,9 +156,9 @@ class TLS_Policy_Unit_Tests final : public Test { const std::string two_groups = "key_exchange_groups_to_offer = secp256r1 ffdhe/ietf/4096"; result.test_eq("list of offerings (size)", TP(two_groups).key_exchange_groups_to_offer().size(), 2); result.confirm("list of offerings (0)", - TP(two_groups).key_exchange_groups_to_offer()[0] == Botan::TLS::Group_Params::SECP256R1); + TP(two_groups).key_exchange_groups_to_offer()[0] == Botan::TLS::Group_Params_Code::SECP256R1); result.confirm("list of offerings (1)", - TP(two_groups).key_exchange_groups_to_offer()[1] == Botan::TLS::Group_Params::FFDHE_4096); + TP(two_groups).key_exchange_groups_to_offer()[1] == Botan::TLS::Group_Params_Code::FFDHE_4096); return result; } diff --git a/src/tests/unit_x509.cpp b/src/tests/unit_x509.cpp index 6bc3d3fc1ac..ca628a280ed 100644 --- a/src/tests/unit_x509.cpp +++ b/src/tests/unit_x509.cpp @@ -1332,8 +1332,9 @@ Test::Result test_x509_extensions(const Botan::Private_Key& ca_key, if(result.confirm("CRL Distribution Points extension present in self-signed certificate", !cert_cdps->crl_distribution_urls().empty())) { for(const auto& cdp : cert_cdps->distribution_points()) { - result.confirm("CDP URI present in self-signed certificate", - std::ranges::find(cdp_urls, cdp.point().get_first_attribute("URI")) != cdp_urls.end()); + result.confirm( + "CDP URI present in self-signed certificate", + std::find(cdp_urls.begin(), cdp_urls.end(), cdp.point().get_first_attribute("URI")) != cdp_urls.end()); } } @@ -1368,8 +1369,9 @@ Test::Result test_x509_extensions(const Botan::Private_Key& ca_key, if(result.confirm("CRL Distribution Points extension present in self-signed certificate", !cert_cdps->crl_distribution_urls().empty())) { for(const auto& cdp : cert_cdps->distribution_points()) { - result.confirm("CDP URI present in self-signed certificate", - std::ranges::find(cdp_urls, cdp.point().get_first_attribute("URI")) != cdp_urls.end()); + result.confirm( + "CDP URI present in self-signed certificate", + std::find(cdp_urls.begin(), cdp_urls.end(), cdp.point().get_first_attribute("URI")) != cdp_urls.end()); } }