diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2cdd4acd0..d6158d73f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: name: rustfmt runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Install Rustfmt run: rustup default stable && rustup component add rustfmt - name: Check formatting @@ -34,7 +34,7 @@ jobs: env: CARGO_HOME: ${{ github.workspace }}/.cache/cargo steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: 'recursive' - name: Install Rust @@ -45,7 +45,7 @@ jobs: run: | echo "version=$(rustc --version)" >> $GITHUB_OUTPUT - name: Cache cargo index - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: | .cache/cargo/registry/index @@ -55,12 +55,12 @@ jobs: - name: Fetch dependencies run: cargo fetch - name: Cache target directory - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: target key: clippy-${{ steps.rust-version.outputs.version }}-${{ hashFiles('Cargo.lock') }} - name: Cache cargo index (save) - uses: actions/cache/save@v4 + uses: actions/cache/save@v6 with: path: | .cache/cargo/registry/index @@ -109,6 +109,7 @@ jobs: - x86_64-mingw - i686-msvc - x86_64-msvc + - x86_64-msvc-static include: - check_only: false - extra_test_args: '' @@ -263,7 +264,7 @@ jobs: CARGO_HOME: ${{ github.workspace }}/.cache/cargo CARGO_BUILD_BUILD_DIR: ${{ github.workspace }}/.cache/build-dir steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: 'recursive' - name: Install Rust (rustup) @@ -274,18 +275,10 @@ jobs: shell: bash run: | echo "version=$(rustc --version)" >> $GITHUB_OUTPUT - - name: Install golang - uses: actions/setup-go@v5 - with: - go-version: '>=1.22.0' - name: Install target-specific APT dependencies if: "matrix.apt_packages != ''" run: sudo apt update && sudo apt install -y ${{ matrix.apt_packages }} shell: bash - - name: Install nasm - if: startsWith(matrix.os, 'windows') - run: choco install nasm - shell: cmd - name: Setup 32-bit MSYS2 if: matrix.thing == 'i686-mingw' uses: msys2/setup-msys2@v2 @@ -312,20 +305,14 @@ jobs: echo >> $GITHUB_ENV BINDGEN_EXTRA_CLANG_ARGS="-mlong-double-64 -I$MSYS_ROOT\\mingw32\\include" echo >> $GITHUB_ENV LIBRARY_PATH="$MSYS_ROOT\\mingw32\\lib" echo >> $GITHUB_ENV LDFLAGS="-L$MSYS_ROOT\\mingw32\\lib" - - name: Install LLVM and Clang - if: startsWith(matrix.os, 'windows') - uses: KyleMayes/install-llvm-action@v1 - with: - version: "11.0" - directory: ${{ runner.temp }}/llvm - name: Set LIBCLANG_PATH if: startsWith(matrix.os, 'windows') - run: echo "LIBCLANG_PATH=$((gcm clang).source -replace "clang.exe")" >> $env:GITHUB_ENV + run: echo "LIBCLANG_PATH=C:\Program Files\LLVM\bin" >> $env:GITHUB_ENV - name: Set Android Linker path if: endsWith(matrix.thing, '-android') run: echo "CARGO_TARGET_$(echo ${{ matrix.target }} | tr \\-a-z _A-Z)_LINKER=$ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/$(echo ${{ matrix.target }} | sed s/armv7/armv7a/)21-clang++" >> "$GITHUB_ENV" - name: Prepopulate cargo index - uses: actions/cache/restore@v4 + uses: actions/cache/restore@v6 with: path: | .cache/cargo/registry/index @@ -339,7 +326,7 @@ jobs: # Windows builds are the slowest - name: Cache deps in Windows tests if: startsWith(matrix.os, 'windows') - uses: actions/cache/restore@v4 + uses: actions/cache/restore@v6 id: test-cache-restore with: path: .cache/build-dir @@ -352,7 +339,7 @@ jobs: # By default it'd be saved after later cargo calls, which already invalidated the cache - name: Cache deps in Windows tests if: startsWith(matrix.os, 'windows') - uses: actions/cache/save@v4 + uses: actions/cache/save@v6 with: path: .cache/build-dir key: ${{ steps.test-cache-restore.outputs.cache-primary-key }} @@ -381,16 +368,17 @@ jobs: name: Test FIPS integration runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: 'recursive' - name: Install Rust (rustup) run: rustup update stable --no-self-update && rustup default stable shell: bash - name: Install golang - uses: actions/setup-go@v5 + uses: actions/setup-go@v7 with: - go-version: '>=1.22.0' + go-version: '>=1.27.0' + cache: false - name: Run tests run: cargo test --features fips - name: Test boring-sys cargo publish (FIPS) @@ -410,13 +398,14 @@ jobs: name: Test BoringSSL upstream test suite runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: 'recursive' - name: Install golang - uses: actions/setup-go@v5 + uses: actions/setup-go@v7 with: - go-version: '>=1.22.0' + go-version: '>=1.27.0' + cache: false - name: Install build tools (ninja, cmake) run: sudo apt-get update && sudo apt-get install -y ninja-build cmake - name: Apply boring-sys patches @@ -447,16 +436,12 @@ jobs: include: - target: x86_64-unknown-linux-gnu steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: 'recursive' - name: Install Rust (rustup) run: rustup toolchain install stable --no-self-update --profile minimal --target ${{ matrix.target }} && rustup default stable shell: bash - - name: Install golang - uses: actions/setup-go@v5 - with: - go-version: '>=1.22.0' - name: Install ${{ matrix.target }} toolchain run: brew tap messense/macos-cross-toolchains && brew trust messense/macos-cross-toolchains && brew install ${{ matrix.target }} - name: Set BORING_BSSL_SYSROOT @@ -476,7 +461,7 @@ jobs: env: CARGO_INCREMENTAL: 1 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 with: submodules: 'recursive' - name: Install Rust (rustup) @@ -493,4 +478,4 @@ jobs: - run: cargo test --features rpk,underscore-wildcards name: Run `rpk,underscore-wildcards` tests - run: cargo test --features rpk,underscore-wildcards,mlkem,mldsa - name: Run `rpk,underscore-wildcards` tests + name: Run `rpk,underscore-wildcards,mlkem,mldsa` tests diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml index 62b7ccdd7..4e8e3a6cc 100644 --- a/.github/workflows/semgrep.yml +++ b/.github/workflows/semgrep.yml @@ -16,11 +16,11 @@ jobs: name: semgrep-oss runs-on: ubuntu-slim steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@v7 with: fetch-depth: 1 - id: cache-semgrep - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: ~/.local key: semgrep-1.160.0-${{ runner.os }} diff --git a/Cargo.toml b/Cargo.toml index 426150ee9..0b7884960 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ members = [ resolver = "2" [workspace.package] -version = "5.2.0" +version = "5.3.0" rust-version = "1.85" repository = "https://github.com/cloudflare/boring" edition = "2021" @@ -20,11 +20,11 @@ tag-prefix = "" publish = false [workspace.dependencies] -boring-sys = { version = "5.2.0", path = "./boring-sys", default-features = false } -boring = { version = "5.2.0", path = "./boring", default-features = false } -tokio-boring = { version = "5.2.0", path = "./tokio-boring", default-features = false } +boring-sys = { version = "5.3.0", path = "./boring-sys", default-features = false } +boring = { version = "5.3.0", path = "./boring", default-features = false } +tokio-boring = { version = "5.3.0", path = "./tokio-boring", default-features = false } -bindgen = { version = "0.72.0", default-features = false, features = ["runtime"] } +bindgen = { version = "0.72.0", default-features = false, features = ["runtime", "prettyplease"] } bitflags = "2.9" brotli = "8.0" bytes = "1" diff --git a/RELEASE_NOTES b/RELEASE_NOTES index 91cff5eb2..bb0372b92 100644 --- a/RELEASE_NOTES +++ b/RELEASE_NOTES @@ -1,4 +1,5 @@ 5.2.0 +- 2026-10-14 Add action-aware certificate selection callbacks, including ECH fallback - 2026-05-21 Export `DEP_BORINGSSL_VERSION_MAJOR` var - 2026-04-27 Expose DTLS version constants in SslVersion @@ -2495,4 +2496,3 @@ - 2011-12-15 Add manifest for rust-pkg. - 2011-12-15 Initial commit. - diff --git a/boring-sys/Cargo.toml b/boring-sys/Cargo.toml index 009fff672..d9ba68bcb 100644 --- a/boring-sys/Cargo.toml +++ b/boring-sys/Cargo.toml @@ -63,7 +63,7 @@ rpk = [] # Require mlkem.h mlkem = [] -# Violate RFC 5280 5.1.2.1 and allow certs with CRL extensions in X.509 version 1. +# Violate RFC 5280 5.1.2.1 and allow extensions on X.509 version 1 CRLs. # This feature is not guaranteed to be supported in future minor releases. allow-crl-extensions-bad-version = [] @@ -80,9 +80,11 @@ underscore-wildcards = [] # 19 (see `include/openssl/base.h`) changed `enforce_rsa_key_usage` to # `true`, making a client-side RSA leaf whose keyUsage does not include the # bit required by the negotiated cipher suite a fatal handshake error -# (KEY_USAGE_BIT_INCORRECT). Enabling this feature applies a build-time -# patch that sets the default back to `false`, so RSA keyUsage mismatches -# are non-fatal. Non-RSA keyUsage enforcement is unaffected. +# (KEY_USAGE_BIT_INCORRECT). Upstream later removed the +# `enforce_rsa_key_usage` config field entirely, so enabling this feature +# applies a build-time patch that restores the conditional the flag used to +# guard, hardwired to the relaxed behaviour, making RSA keyUsage mismatches +# non-fatal again. Non-RSA keyUsage enforcement is unaffected. relax-cert-validation = [] [build-dependencies] diff --git a/boring-sys/build/main.rs b/boring-sys/build/main.rs index 449571ce4..24426c952 100644 --- a/boring-sys/build/main.rs +++ b/boring-sys/build/main.rs @@ -493,7 +493,7 @@ fn ensure_patches_applied(config: &Config) -> io::Result<()> { if config.features.allow_crl_extensions_bad_version { println!( - "cargo:warning=applying the patch for disabling cert version \ + "cargo:warning=applying the patch for disabling CRL version \ validation for extensions" ); apply_patch(config, "bad-cert-verification.patch")?; @@ -786,7 +786,8 @@ fn generate_bindings(config: &Config) -> Result Date: Mon, 13 Mar 2023 14:28:10 -0700 -Subject: [PATCH] PINGORA-474: disable cert version check for openssl +Subject: [PATCH] PINGORA-474: disable CRL version check for openssl compatibility -Some free customers use badly crafted cert (with verification off). -Openssl allows these cert but boring does't. +Some free customers use badly crafted CRLs (with verification off). +Openssl allows these CRLs but boring does't. --- - crypto/x509/x509_test.cc | 4 ++-- + crypto/x509/x509_test.cc | 4 +--- crypto/x509/x_crl.cc | 2 ++ - 2 files changed, 4 insertions(+), 2 deletions(-) + 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crypto/x509/x509_test.cc b/crypto/x509/x509_test.cc -index aa5bfda5d..15c1c73ee 100644 +index f98aa26cc..c881a4199 100644 --- a/crypto/x509/x509_test.cc +++ b/crypto/x509/x509_test.cc -@@ -3859,8 +3859,8 @@ TEST(X509Test, InvalidVersion) { - EXPECT_FALSE(CertFromPEM(kNegativeVersionPEM)); - EXPECT_FALSE(CertFromPEM(kFutureVersionPEM)); - EXPECT_FALSE(CertFromPEM(kOverflowVersionPEM)); -- EXPECT_FALSE(CertFromPEM(kV1WithExtensionsPEM)); -- EXPECT_FALSE(CertFromPEM(kV2WithExtensionsPEM)); -+ ASSERT_TRUE(CertFromPEM(kV1WithExtensionsPEM)); -+ ASSERT_TRUE(CertFromPEM(kV2WithExtensionsPEM)); - EXPECT_FALSE(CertFromPEM(kV1WithIssuerUniqueIDPEM)); +@@ -4473,9 +4473,7 @@ TEST(X509Test, InvalidVersion) { + EXPECT_TRUE(ErrorsAreAndClear({{ERR_LIB_ASN1, ASN1_R_DECODE_ERROR}})); EXPECT_FALSE(CertFromPEM(kV1WithSubjectUniqueIDPEM)); - EXPECT_FALSE(CRLFromPEM(kV1CRLWithExtensionsPEM)); + EXPECT_TRUE(ErrorsAreAndClear({{ERR_LIB_ASN1, ASN1_R_DECODE_ERROR}})); +- EXPECT_FALSE(CRLFromPEM(kV1CRLWithExtensionsPEM)); +- EXPECT_TRUE( +- ErrorsAreAndClear({{ERR_LIB_X509, X509_R_INVALID_FIELD_FOR_VERSION}})); ++ EXPECT_TRUE(CRLFromPEM(kV1CRLWithExtensionsPEM)); + EXPECT_FALSE(CRLFromPEM(kV1CRLWithEntryExtensionsPEM)); + EXPECT_TRUE(ErrorsAreAndClear({{ERR_LIB_X509, X509_R_INVALID_VERSION}})); + EXPECT_FALSE(CRLFromPEM(kV3CRLPEM)); diff --git a/crypto/x509/x_crl.cc b/crypto/x509/x_crl.cc -index 1d22ed638..4f50bc03f 100644 +index d30c17253..5af682ca9 100644 --- a/crypto/x509/x_crl.cc +++ b/crypto/x509/x_crl.cc -@@ -148,10 +148,12 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, +@@ -157,10 +157,12 @@ static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, } // Per RFC 5280, section 5.1.2.1, extensions require v2. @@ -43,6 +43,3 @@ index 1d22ed638..4f50bc03f 100644 // Extensions is a SEQUENCE SIZE (1..MAX), so it cannot be empty. An empty // extensions list is encoded by omitting the OPTIONAL field. --- -2.39.5 - diff --git a/boring-sys/patches/boring-pq.patch b/boring-sys/patches/boring-pq.patch index 7e7d92d1f..29bcc5121 100644 --- a/boring-sys/patches/boring-pq.patch +++ b/boring-sys/patches/boring-pq.patch @@ -1,65 +1,61 @@ -From fc01a66ac146778c4e6651d6fc6d62c7e12bfb32 Mon Sep 17 00:00:00 2001 -From: Christopher Patton +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Bas Westerbaan Date: Wed, 27 May 2026 09:55:52 -0700 Subject: [PATCH] Add additional post-quantum key agreement This patch adds: -1. Enable X25519MLKEM768 by default. +1. Enable X25519MLKEM768 in the fips202205 compliance profile. Upstream + previously enabled it by default in commit e748facbaa5e, and created + a new fips202609 profile including X25519MLKEM768 and MLKEM1024. -2. Supports for P256Kyber768Draft00 under 0xfe32, which we temporarily +2. Supports for P256Kyber768Draft00 (0xfe32), which we temporarily need for compliance reasons. (Note that this is not the codepoint allocated for that exchange in the IANA table.) - Enables by default and in FIPS mode. + Enabled by default and in the fips202205 compliance profile, omitted + from fips202609 since P256Kyber is deprecated. -3. Add SSL(_CTX)_use_second_keyshare. By default BoringSSL will send a - non post-quantum and a post-quantum keyshare if available. These - functions allow one to change the behaviour to only send a single - keyshare. +3. Add SSL(_CTX)_use_second_keyshare. By default BoringSSL clients send + both a PQ and non-PQ keyshare if permitted. These functions allow one + to change the behaviour to only send a single keyshare. For testing + purposes, add option `bssl client -disable-second-keyshare`. + +4. Restore X25519Kyber768Draft00 (0x6399), removed upstream in 188ce3c1. + Upstream deleted its Kyber implementation, so both Kyber hybrids are + now built on ML-KEM-768, applying Kyber's key derivation + `SHAKE-256(K || SHA3-256(c))` to the ML-KEM shared secret. See + https://words.filippo.io/mlkem768/#bonus-track-using-a-ml-kem-implementation-as-kyber-v3 --- - crypto/obj/obj_dat.h | 6 +- - crypto/obj/obj_mac.num | 1 + - crypto/obj/objects.txt | 1 + - include/openssl/nid.h | 3 + - include/openssl/ssl.h | 15 ++++ - ssl/extensions.cc | 26 ++++--- - ssl/internal.h | 12 ++- - ssl/ssl_key_share.cc | 111 +++++++++++++++++++++++++++- - ssl/ssl_lib.cc | 16 +++- - ssl/ssl_test.cc | 24 +++++- - ssl/test/runner/basic_tests.go | 2 + - ssl/test/runner/cbc_tests.go | 3 + - ssl/test/runner/common.go | 2 +- - ssl/test/runner/curve_tests.go | 28 +++---- - ssl/test/runner/ech_tests.go | 24 +++++- - ssl/test/runner/extension_tests.go | 3 +- - ssl/test/runner/key_update_tests.go | 6 +- - tool/client.cc | 9 +++ - 18 files changed, 249 insertions(+), 43 deletions(-) + crypto/obj/obj_dat.h | 5 +- + crypto/obj/obj_mac.num | 1 + + crypto/obj/objects.txt | 1 + + include/openssl/nid.h | 3 + + include/openssl/prefix_symbols.h | 4 + + include/openssl/ssl.h | 17 ++ + ssl/extensions.cc | 35 ++- + ssl/internal.h | 12 +- + ssl/ssl_key_share.cc | 257 +++++++++++++++++++++ + ssl/ssl_lib.cc | 16 +- + ssl/ssl_test.cc | 28 ++- + ssl/test/runner/compliance_policy_tests.go | 2 + + tool/client.cc | 9 + + 13 files changed, 370 insertions(+), 20 deletions(-) diff --git a/crypto/obj/obj_dat.h b/crypto/obj/obj_dat.h -index feb8f2d1e..7ca28d9f5 100644 +index ced3582f9..f35a79e0b 100644 --- a/crypto/obj/obj_dat.h +++ b/crypto/obj/obj_dat.h -@@ -16,7 +16,7 @@ - - - BSSL_NAMESPACE_BEGIN --#define NUM_NID 973 -+#define NUM_NID 974 - - static const uint8_t kObjectData[] = { - /* NID_rsadsi */ -@@ -8802,6 +8802,8 @@ static const ASN1_OBJECT kObjects[NUM_NID] = { +@@ -8865,7 +8865,8 @@ static const ASN1_OBJECT kObjects[NUM_NID] = { 0}, {NULL, NULL, NID_undef, 0, NULL, 0}, {"X-Wing", "X-Wing", NID_X_Wing, 0, NULL, 0}, +- {NULL, NULL, NID_undef, 0, NULL, 0}, + {"P256Kyber768Draft00", "P256Kyber768Draft00", NID_P256Kyber768Draft00, 0, + NULL, 0}, - }; - - static const uint16_t kNIDsInShortNameOrder[] = { -@@ -8934,6 +8936,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { + {NULL, NULL, NID_undef, 0, NULL, 0}, + {NULL, NULL, NID_undef, 0, NULL, 0}, + {"alg-mtcProof-draft", "alg-mtcProof-draft", NID_alg_mtcProof_draft, 10, +@@ -9012,6 +9013,7 @@ static const uint16_t kNIDsInShortNameOrder[] = { 18 /* OU */, 749 /* Oakley-EC2N-3 */, 750 /* Oakley-EC2N-4 */, @@ -67,7 +63,7 @@ index feb8f2d1e..7ca28d9f5 100644 9 /* PBE-MD2-DES */, 168 /* PBE-MD2-RC2-64 */, 10 /* PBE-MD5-DES */, -@@ -9858,6 +9861,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { +@@ -9942,6 +9944,7 @@ static const uint16_t kNIDsInLongNameOrder[] = { 366 /* OCSP Nonce */, 371 /* OCSP Service Locator */, 180 /* OCSP Signing */, @@ -76,19 +72,22 @@ index feb8f2d1e..7ca28d9f5 100644 69 /* PBKDF2 */, 162 /* PBMAC1 */, diff --git a/crypto/obj/obj_mac.num b/crypto/obj/obj_mac.num -index 7b8bd2ead..dc7b2878f 100644 +index 582412081..4a0e651dc 100644 --- a/crypto/obj/obj_mac.num +++ b/crypto/obj/obj_mac.num -@@ -959,3 +959,4 @@ ML_DSA_65 968 +@@ -959,6 +959,7 @@ ML_DSA_65 968 ML_DSA_87 969 ML_KEM_768 970 X_Wing 972 +P256Kyber768Draft00 973 + alg_mtcProof_draft 976 + rdna_trustAnchorID_draft 977 + pe_mtcCertificationAuthority_draft 978 diff --git a/crypto/obj/objects.txt b/crypto/obj/objects.txt -index 67b9ade43..384b25753 100644 +index fa4bd648c..32ae303c7 100644 --- a/crypto/obj/objects.txt +++ b/crypto/obj/objects.txt -@@ -1340,6 +1340,7 @@ secg-scheme 14 3 : dhSinglePass-cofactorDH-sha512kdf-scheme +@@ -1343,6 +1343,7 @@ secg-scheme 14 3 : dhSinglePass-cofactorDH-sha512kdf-scheme # NIDs for post quantum hybrid KEMs in TLS (no corresponding OIDs). : X25519Kyber768Draft00 @@ -97,7 +96,7 @@ index 67b9ade43..384b25753 100644 # NIDs for PQ/T hybrid KEMs (no corresponding OIDs). diff --git a/include/openssl/nid.h b/include/openssl/nid.h -index 6b3bb4506..068fc5977 100644 +index 9ca8e6707..584d139f9 100644 --- a/include/openssl/nid.h +++ b/include/openssl/nid.h @@ -5511,6 +5511,9 @@ extern "C" { @@ -107,23 +106,69 @@ index 6b3bb4506..068fc5977 100644 +#define SN_P256Kyber768Draft00 "P256Kyber768Draft00" +#define NID_P256Kyber768Draft00 973 + - - #if defined(__cplusplus) - } /* extern C */ + #define SN_alg_mtcProof_draft "alg-mtcProof-draft" + #define NID_alg_mtcProof_draft 976 + #define OBJ_alg_mtcProof_draft 1L, 3L, 6L, 1L, 4L, 1L, 44363L, 47L, 0L +diff --git a/include/openssl/prefix_symbols.h b/include/openssl/prefix_symbols.h +index f59abe8b9..e41c0eb55 100644 +--- a/include/openssl/prefix_symbols.h ++++ b/include/openssl/prefix_symbols.h +@@ -2112,6 +2112,7 @@ + #pragma redefine_extname SSL_CTX_use_certificate_chain_file BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_use_certificate_chain_file) + #pragma redefine_extname SSL_CTX_use_certificate_file BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_use_certificate_file) + #pragma redefine_extname SSL_CTX_use_psk_identity_hint BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_use_psk_identity_hint) ++#pragma redefine_extname SSL_CTX_use_second_keyshare BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_CTX_use_second_keyshare) + #pragma redefine_extname SSL_ECH_KEYS_add BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_add) + #pragma redefine_extname SSL_ECH_KEYS_free BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_free) + #pragma redefine_extname SSL_ECH_KEYS_has_duplicate_config_id BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_ECH_KEYS_has_duplicate_config_id) +@@ -2463,6 +2464,7 @@ + #pragma redefine_extname SSL_use_certificate_ASN1 BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_use_certificate_ASN1) + #pragma redefine_extname SSL_use_certificate_file BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_use_certificate_file) + #pragma redefine_extname SSL_use_psk_identity_hint BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_use_psk_identity_hint) ++#pragma redefine_extname SSL_use_second_keyshare BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_use_second_keyshare) + #pragma redefine_extname SSL_used_hello_retry_request BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_used_hello_retry_request) + #pragma redefine_extname SSL_version BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_version) + #pragma redefine_extname SSL_want BORINGSSL_ADD_USER_LABEL_AND_PREFIX(SSL_want) +@@ -5264,6 +5266,7 @@ + #define SSL_CTX_use_certificate_chain_file BORINGSSL_ADD_PREFIX(SSL_CTX_use_certificate_chain_file) + #define SSL_CTX_use_certificate_file BORINGSSL_ADD_PREFIX(SSL_CTX_use_certificate_file) + #define SSL_CTX_use_psk_identity_hint BORINGSSL_ADD_PREFIX(SSL_CTX_use_psk_identity_hint) ++#define SSL_CTX_use_second_keyshare BORINGSSL_ADD_PREFIX(SSL_CTX_use_second_keyshare) + #define SSL_ECH_KEYS_add BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_add) + #define SSL_ECH_KEYS_free BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_free) + #define SSL_ECH_KEYS_has_duplicate_config_id BORINGSSL_ADD_PREFIX(SSL_ECH_KEYS_has_duplicate_config_id) +@@ -5615,6 +5618,7 @@ + #define SSL_use_certificate_ASN1 BORINGSSL_ADD_PREFIX(SSL_use_certificate_ASN1) + #define SSL_use_certificate_file BORINGSSL_ADD_PREFIX(SSL_use_certificate_file) + #define SSL_use_psk_identity_hint BORINGSSL_ADD_PREFIX(SSL_use_psk_identity_hint) ++#define SSL_use_second_keyshare BORINGSSL_ADD_PREFIX(SSL_use_second_keyshare) + #define SSL_used_hello_retry_request BORINGSSL_ADD_PREFIX(SSL_used_hello_retry_request) + #define SSL_version BORINGSSL_ADD_PREFIX(SSL_version) + #define SSL_want BORINGSSL_ADD_PREFIX(SSL_want) diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h -index 055b3e025..09d6508f4 100644 +index ca1c2d50b..a13db1400 100644 --- a/include/openssl/ssl.h +++ b/include/openssl/ssl.h -@@ -2586,6 +2586,7 @@ OPENSSL_EXPORT size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx); +@@ -2725,7 +2725,9 @@ OPENSSL_EXPORT size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx); + #define SSL_GROUP_SECP521R1 25 + #define SSL_GROUP_X25519 29 #define SSL_GROUP_X25519_MLKEM768 0x11ec - #define SSL_GROUP_X25519_KYBER768_DRAFT00 0x6399 ++#define SSL_GROUP_X25519_KYBER768_DRAFT00 0x6399 #define SSL_GROUP_MLKEM1024 0x0202 +#define SSL_GROUP_P256_KYBER768_DRAFT00 0xfe32 - // SSL_CTX_set1_group_ids sets the preferred groups for |ctx| to |group_ids|. - // Each element of |group_ids| should be a unique one of the |SSL_GROUP_*| -@@ -6241,6 +6242,20 @@ OPENSSL_EXPORT int SSL_CTX_set1_curves_list(SSL_CTX *ctx, const char *curves); - // SSL_set1_curves_list calls |SSL_set1_groups_list|. + // SSL_CTX_set1_group_ids sets the preferred groups for `ctx` to `group_ids`. + // Each element of `group_ids` should be a unique one of the `SSL_GROUP_*` +@@ -6388,6 +6390,7 @@ OPENSSL_EXPORT int SSL_CTX_set_tlsext_status_arg(SSL_CTX *ctx, void *arg); + #define SSL_CURVE_SECP384R1 SSL_GROUP_SECP384R1 + #define SSL_CURVE_SECP521R1 SSL_GROUP_SECP521R1 + #define SSL_CURVE_X25519 SSL_GROUP_X25519 ++#define SSL_CURVE_X25519_KYBER768_DRAFT00 SSL_GROUP_X25519_KYBER768_DRAFT00 + + // SSL_get_curve_id calls `SSL_get_group_id`. + OPENSSL_EXPORT uint16_t SSL_get_curve_id(const SSL *ssl); +@@ -6412,6 +6415,20 @@ OPENSSL_EXPORT int SSL_CTX_set1_curves_list(SSL_CTX *ctx, const char *curves); + // SSL_set1_curves_list calls `SSL_set1_groups_list`. OPENSSL_EXPORT int SSL_set1_curves_list(SSL *ssl, const char *curves); +// By default, a client will send both a non post-quantum and a post-quantum @@ -141,21 +186,30 @@ index 055b3e025..09d6508f4 100644 +OPENSSL_EXPORT void SSL_CTX_use_second_keyshare(SSL_CTX *ctx, int enabled); + // TLSEXT_nid_unknown is a constant used in OpenSSL for - // |SSL_get_negotiated_group| to return an unrecognized group. BoringSSL never + // `SSL_get_negotiated_group` to return an unrecognized group. BoringSSL never // returns this value, but we define this constant for compatibility. diff --git a/ssl/extensions.cc b/ssl/extensions.cc -index db1a29139..05c8c1e16 100644 +index ab32bb93f..2677314d0 100644 --- a/ssl/extensions.cc +++ b/ssl/extensions.cc -@@ -107,6 +107,7 @@ static bool tls1_check_duplicate_extensions(const CBS *cbs) { +@@ -107,7 +107,15 @@ static bool tls1_check_duplicate_extensions(const CBS *cbs) { + } + static bool is_post_quantum_group(uint16_t id) { - switch (id) { - case SSL_GROUP_X25519_KYBER768_DRAFT00: +- return id == SSL_GROUP_X25519_MLKEM768 || id == SSL_GROUP_MLKEM1024; ++ switch (id) { ++ case SSL_GROUP_X25519_KYBER768_DRAFT00: + case SSL_GROUP_P256_KYBER768_DRAFT00: - case SSL_GROUP_X25519_MLKEM768: - case SSL_GROUP_MLKEM1024: - return true; -@@ -2418,18 +2419,21 @@ bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id) { ++ case SSL_GROUP_X25519_MLKEM768: ++ case SSL_GROUP_MLKEM1024: ++ return true; ++ default: ++ return false; ++ } + } + + bool ssl_parse_client_hello_with_trailing_data(const SSLImpl *ssl, CBS *cbs, +@@ -2445,18 +2453,21 @@ bool ssl_setup_key_shares(SSL_HANDSHAKE *hs, uint16_t override_group_id) { if (!default_key_shares.TryPushBack(supported_group_list[0])) { return false; } @@ -189,19 +243,19 @@ index db1a29139..05c8c1e16 100644 selected_key_shares.emplace(default_key_shares); } diff --git a/ssl/internal.h b/ssl/internal.h -index 2bea8f62d..47b688bf4 100644 +index 8efc21e06..57fffadde 100644 --- a/ssl/internal.h +++ b/ssl/internal.h -@@ -913,7 +913,7 @@ struct NamedGroup { +@@ -952,7 +952,7 @@ struct NamedGroup { Span NamedGroups(); // kNumNamedGroups is the number of supported groups. --constexpr size_t kNumNamedGroups = 7u; +-constexpr size_t kNumNamedGroups = 6u; +constexpr size_t kNumNamedGroups = 8u; // DefaultSupportedGroupIds returns the list of IDs for the default groups that // are supported when the caller hasn't explicitly configured supported groups. -@@ -3531,6 +3531,11 @@ struct SSL_CONFIG { +@@ -3642,6 +3642,11 @@ struct SSL_CONFIG { // permute_extensions is whether to permute extensions when sending messages. bool permute_extensions : 1; @@ -210,10 +264,10 @@ index 2bea8f62d..47b688bf4 100644 + // we will only send the most preferred keyshare. + bool disable_second_keyshare : 1; + - // aes_hw_override if set indicates we should override checking for aes - // hardware support, and use the value in aes_hw_override_value instead. - bool aes_hw_override : 1; -@@ -4172,6 +4177,11 @@ struct ssl_ctx_st : public bssl::RefCounted { + // alps_use_new_codepoint if set indicates we use new ALPS extension codepoint + // to negotiate and convey application settings. + bool alps_use_new_codepoint : 1; +@@ -4263,6 +4268,11 @@ class SSLContext : public ssl_ctx_st, public RefCounted { // permute_extensions is whether to permute extensions when sending messages. bool permute_extensions : 1; @@ -226,72 +280,135 @@ index 2bea8f62d..47b688bf4 100644 // protocols from the peer. bool allow_unknown_alpn_protos : 1; diff --git a/ssl/ssl_key_share.cc b/ssl/ssl_key_share.cc -index d155b5527..4fb08906b 100644 +index 84394b247..2f006e982 100644 --- a/ssl/ssl_key_share.cc +++ b/ssl/ssl_key_share.cc -@@ -193,6 +193,109 @@ class X25519KeyShare : public SSLKeyShare { +@@ -32,6 +32,7 @@ + #include + #include + ++#include "../crypto/fipsmodule/keccak/internal.h" + #include "../crypto/internal.h" + #include "internal.h" + +@@ -192,6 +193,253 @@ class X25519KeyShare : public SSLKeyShare { uint8_t private_key_[32]; }; ++// Kyber768 (round-3, "draft00") is implemented on top of ML-KEM-768. See ++// https://words.filippo.io/mlkem768/#bonus-track-using-a-ml-kem-implementation-as-kyber-v3 ++constexpr size_t kKyber768PublicKeyBytes = MLKEM768_PUBLIC_KEY_BYTES; ++constexpr size_t kKyber768CiphertextBytes = MLKEM768_CIPHERTEXT_BYTES; ++constexpr size_t kKyber768SharedSecretBytes = 32; ++ ++// kyber768_kdf applies Kyber's KDF(K || H(c)) to `mlkem_secret`, the shared ++// secret that ML-KEM produced for `ciphertext`. ++void kyber768_kdf(uint8_t out[kKyber768SharedSecretBytes], ++ const uint8_t mlkem_secret[MLKEM_SHARED_SECRET_BYTES], ++ Span ciphertext) { ++ uint8_t buf[MLKEM_SHARED_SECRET_BYTES + 32]; ++ OPENSSL_memcpy(buf, mlkem_secret, MLKEM_SHARED_SECRET_BYTES); ++ BORINGSSL_keccak(buf + MLKEM_SHARED_SECRET_BYTES, 32, ciphertext.data(), ++ ciphertext.size(), boringssl_sha3_256); ++ BORINGSSL_keccak(out, kKyber768SharedSecretBytes, buf, sizeof(buf), ++ boringssl_shake256); ++ OPENSSL_cleanse(buf, sizeof(buf)); ++} ++ ++// Kyber768KEM is a Kyber768 KEM built out of ML-KEM-768. On decapsulation ++// failure it derives from ML-KEM's implicit-rejection secret rather than ++// Kyber's. That output is unpredictable by design and is not an ++// interoperability target. ++class Kyber768KEM { ++ public: ++ void Generate(uint8_t out_public_key[kKyber768PublicKeyBytes]) { ++ MLKEM768_generate_key(out_public_key, /*optional_out_seed=*/nullptr, ++ &private_key_); ++ } ++ ++ bool Encap(uint8_t out_ciphertext[kKyber768CiphertextBytes], ++ uint8_t out_secret[kKyber768SharedSecretBytes], ++ Span peer_key) { ++ MLKEM768_public_key peer_public_key; ++ CBS cbs; ++ CBS_init(&cbs, peer_key.data(), peer_key.size()); ++ if (!MLKEM768_parse_public_key(&peer_public_key, &cbs)) { ++ return false; ++ } ++ ++ uint8_t mlkem_secret[MLKEM_SHARED_SECRET_BYTES]; ++ MLKEM768_encap(out_ciphertext, mlkem_secret, &peer_public_key); ++ kyber768_kdf(out_secret, mlkem_secret, ++ Span(out_ciphertext, kKyber768CiphertextBytes)); ++ OPENSSL_cleanse(mlkem_secret, sizeof(mlkem_secret)); ++ return true; ++ } ++ ++ bool Decap(uint8_t out_secret[kKyber768SharedSecretBytes], ++ Span ciphertext) { ++ uint8_t mlkem_secret[MLKEM_SHARED_SECRET_BYTES]; ++ if (!MLKEM768_decap(mlkem_secret, ciphertext.data(), ciphertext.size(), ++ &private_key_)) { ++ return false; ++ } ++ kyber768_kdf(out_secret, mlkem_secret, ciphertext); ++ OPENSSL_cleanse(mlkem_secret, sizeof(mlkem_secret)); ++ return true; ++ } ++ ++ private: ++ MLKEM768_private_key private_key_; ++}; ++ ++// P256Kyber768Draft00 is a hybrid of P-256 and Kyber768 under a private ++// codepoint. It is not standardised and is retained for compliance reasons. +class P256Kyber768Draft00KeyShare : public SSLKeyShare { + public: -+ P256Kyber768Draft00KeyShare() -+ : ecks_(EC_group_p256(), SSL_GROUP_SECP256R1) {} ++ P256Kyber768Draft00KeyShare() : ecks_(EC_group_p256(), SSL_GROUP_SECP256R1) {} + + uint16_t GroupID() const override { + return SSL_GROUP_P256_KYBER768_DRAFT00; + } + + bool Generate(CBB *out) override { -+ uint8_t kyber_public_key[KYBER_PUBLIC_KEY_BYTES]; -+ KYBER_generate_key(kyber_public_key, &kyber_private_key_); -+ -+ if(!ecks_.Generate(out) || -+ !CBB_add_bytes(out, kyber_public_key, sizeof(kyber_public_key))) { -+ return false; -+ } -+ -+ return true; ++ uint8_t kyber_public_key[kKyber768PublicKeyBytes]; ++ kyber_.Generate(kyber_public_key); ++ return ecks_.Generate(out) && ++ CBB_add_bytes(out, kyber_public_key, sizeof(kyber_public_key)); + } + + bool Encap(CBB *out_ciphertext, Array *out_secret, + uint8_t *out_alert, Span peer_key) override { -+ Array ec_secret; -+ + *out_alert = SSL_AD_INTERNAL_ERROR; + -+ if(peer_key.size() != p256_share_size + KYBER_PUBLIC_KEY_BYTES) { ++ if (peer_key.size() != kP256ShareSize + kKyber768PublicKeyBytes) { + *out_alert = SSL_AD_ILLEGAL_PARAMETER; + OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); + return false; + } + ++ Array ec_secret; + if (!ecks_.Encap(out_ciphertext, &ec_secret, out_alert, -+ peer_key.subspan(0, p256_share_size))) { ++ peer_key.subspan(0, kP256ShareSize))) { + return false; + } + -+ KYBER_public_key peer_kyber_pub; -+ CBS peer_kyber_cbs; -+ CBS_init(&peer_kyber_cbs, peer_key.data() + p256_share_size, -+ KYBER_PUBLIC_KEY_BYTES); -+ -+ if (!KYBER_parse_public_key(&peer_kyber_pub, &peer_kyber_cbs)) { -+ *out_alert = SSL_AD_ILLEGAL_PARAMETER; -+ OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); ++ Array secret; ++ if (!secret.InitForOverwrite(kP256SecretSize + ++ kKyber768SharedSecretBytes)) { + return false; + } ++ OPENSSL_memcpy(secret.data(), ec_secret.data(), ec_secret.size()); + -+ uint8_t kyber_ciphertext[KYBER_CIPHERTEXT_BYTES]; -+ Array secret; -+ if (!secret.InitForOverwrite(p256_secret_size + KYBER_SHARED_SECRET_BYTES)) { ++ uint8_t kyber_ciphertext[kKyber768CiphertextBytes]; ++ if (!kyber_.Encap(kyber_ciphertext, secret.data() + kP256SecretSize, ++ peer_key.subspan(kP256ShareSize))) { ++ *out_alert = SSL_AD_ILLEGAL_PARAMETER; ++ OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); + return false; + } -+ OPENSSL_memcpy(secret.data(), ec_secret.data(), ec_secret.size()); -+ KYBER_encap(kyber_ciphertext, secret.data() + p256_secret_size, -+ &peer_kyber_pub); + -+ if(!CBB_add_bytes(out_ciphertext, kyber_ciphertext, ++ if (!CBB_add_bytes(out_ciphertext, kyber_ciphertext, + sizeof(kyber_ciphertext))) { + return false; + } @@ -304,46 +421,135 @@ index d155b5527..4fb08906b 100644 + Span ciphertext) override { + *out_alert = SSL_AD_INTERNAL_ERROR; + -+ Array ec_secret; -+ -+ if (ciphertext.size() != p256_share_size + KYBER_CIPHERTEXT_BYTES) { ++ if (ciphertext.size() != kP256ShareSize + kKyber768CiphertextBytes) { + *out_alert = SSL_AD_ILLEGAL_PARAMETER; + OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); + return false; + } + ++ Array ec_secret; + if (!ecks_.Decap(&ec_secret, out_alert, -+ ciphertext.subspan(0, p256_share_size))) { ++ ciphertext.subspan(0, kP256ShareSize))) { + return false; + } + + Array secret; -+ if (!secret.InitForOverwrite(p256_secret_size + KYBER_SHARED_SECRET_BYTES)) { ++ if (!secret.InitForOverwrite(kP256SecretSize + ++ kKyber768SharedSecretBytes)) { + return false; + } + OPENSSL_memcpy(secret.data(), ec_secret.data(), ec_secret.size()); -+ KYBER_decap(secret.data() + p256_secret_size, -+ ciphertext.data() + p256_share_size, &kyber_private_key_); ++ ++ if (!kyber_.Decap(secret.data() + kP256SecretSize, ++ ciphertext.subspan(kP256ShareSize))) { ++ *out_alert = SSL_AD_ILLEGAL_PARAMETER; ++ OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); ++ return false; ++ } ++ + *out_secret = std::move(secret); + return true; + } + + private: ++ static constexpr size_t kP256ShareSize = 65; ++ static constexpr size_t kP256SecretSize = 32; ++ + ECKeyShare ecks_; -+ KYBER_private_key kyber_private_key_; ++ Kyber768KEM kyber_; ++}; ++ ++// draft-tls-westerbaan-xyber768d00-03 ++class X25519Kyber768KeyShare : public SSLKeyShare { ++ public: ++ X25519Kyber768KeyShare() {} ++ ++ uint16_t GroupID() const override { ++ return SSL_GROUP_X25519_KYBER768_DRAFT00; ++ } ++ ++ bool Generate(CBB *out) override { ++ uint8_t x25519_public_key[X25519_PUBLIC_VALUE_LEN]; ++ X25519_keypair(x25519_public_key, x25519_private_key_); ++ ++ uint8_t kyber_public_key[kKyber768PublicKeyBytes]; ++ kyber_.Generate(kyber_public_key); ++ ++ return CBB_add_bytes(out, x25519_public_key, sizeof(x25519_public_key)) && ++ CBB_add_bytes(out, kyber_public_key, sizeof(kyber_public_key)); ++ } ++ ++ bool Encap(CBB *out_ciphertext, Array *out_secret, ++ uint8_t *out_alert, Span peer_key) override { ++ *out_alert = SSL_AD_INTERNAL_ERROR; + -+ static constexpr size_t p256_share_size = 65; -+ static constexpr size_t p256_secret_size = 32; ++ Array secret; ++ if (!secret.InitForOverwrite(X25519_SHARED_KEY_LEN + ++ kKyber768SharedSecretBytes)) { ++ return false; ++ } ++ ++ uint8_t x25519_public_key[X25519_PUBLIC_VALUE_LEN]; ++ X25519_keypair(x25519_public_key, x25519_private_key_); ++ ++ uint8_t kyber_ciphertext[kKyber768CiphertextBytes]; ++ if (peer_key.size() != X25519_PUBLIC_VALUE_LEN + kKyber768PublicKeyBytes || ++ !X25519(secret.data(), x25519_private_key_, peer_key.data()) || ++ !kyber_.Encap(kyber_ciphertext, secret.data() + X25519_SHARED_KEY_LEN, ++ peer_key.subspan(X25519_PUBLIC_VALUE_LEN))) { ++ *out_alert = SSL_AD_ILLEGAL_PARAMETER; ++ OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); ++ return false; ++ } ++ ++ if (!CBB_add_bytes(out_ciphertext, x25519_public_key, ++ sizeof(x25519_public_key)) || ++ !CBB_add_bytes(out_ciphertext, kyber_ciphertext, ++ sizeof(kyber_ciphertext))) { ++ return false; ++ } ++ ++ *out_secret = std::move(secret); ++ return true; ++ } ++ ++ bool Decap(Array *out_secret, uint8_t *out_alert, ++ Span ciphertext) override { ++ *out_alert = SSL_AD_INTERNAL_ERROR; ++ ++ Array secret; ++ if (!secret.InitForOverwrite(X25519_SHARED_KEY_LEN + ++ kKyber768SharedSecretBytes)) { ++ return false; ++ } ++ ++ if (ciphertext.size() != ++ X25519_PUBLIC_VALUE_LEN + kKyber768CiphertextBytes || ++ !X25519(secret.data(), x25519_private_key_, ciphertext.data()) || ++ !kyber_.Decap(secret.data() + X25519_SHARED_KEY_LEN, ++ ciphertext.subspan(X25519_PUBLIC_VALUE_LEN))) { ++ *out_alert = SSL_AD_ILLEGAL_PARAMETER; ++ OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT); ++ return false; ++ } ++ ++ *out_secret = std::move(secret); ++ return true; ++ } ++ ++ private: ++ uint8_t x25519_private_key_[X25519_PRIVATE_KEY_LEN]; ++ Kyber768KEM kyber_; +}; + - // draft-tls-westerbaan-xyber768d00-03 - class X25519Kyber768KeyShare : public SSLKeyShare { + // RFC 10024 + class X25519MLKEM768KeyShare : public SSLKeyShare { public: -@@ -441,9 +544,11 @@ constexpr NamedGroup kNamedGroups[] = { +@@ -350,8 +598,12 @@ constexpr NamedGroup kNamedGroups[] = { + {NID_secp384r1, SSL_GROUP_SECP384R1, "P-384", "secp384r1"}, {NID_secp521r1, SSL_GROUP_SECP521R1, "P-521", "secp521r1"}, {NID_X25519, SSL_GROUP_X25519, "X25519", "x25519"}, - {NID_X25519Kyber768Draft00, SSL_GROUP_X25519_KYBER768_DRAFT00, -- "X25519Kyber768Draft00", ""}, ++ {NID_X25519Kyber768Draft00, SSL_GROUP_X25519_KYBER768_DRAFT00, + "X25519Kyber768Draft00", "Xyber768D00"}, {NID_X25519MLKEM768, SSL_GROUP_X25519_MLKEM768, "X25519MLKEM768", ""}, {NID_ML_KEM_1024, SSL_GROUP_MLKEM1024, "MLKEM1024", ""}, @@ -352,17 +558,20 @@ index d155b5527..4fb08906b 100644 }; static_assert(std::size(kNamedGroups) == kNumNamedGroups, -@@ -455,6 +560,8 @@ Span NamedGroups() { return kNamedGroups; } - +@@ -364,6 +616,7 @@ Span NamedGroups() { return kNamedGroups; } Span DefaultSupportedGroupIds() { static const uint16_t kDefaultSupportedGroupIds[] = { -+ SSL_GROUP_X25519_MLKEM768, + SSL_GROUP_X25519_MLKEM768, + SSL_GROUP_P256_KYBER768_DRAFT00, SSL_GROUP_X25519, SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1, -@@ -478,6 +585,8 @@ UniquePtr SSLKeyShare::Create(uint16_t group_id) { +@@ -383,8 +636,12 @@ UniquePtr SSLKeyShare::Create(uint16_t group_id) { + return MakeUnique(); + case SSL_GROUP_X25519_MLKEM768: return MakeUnique(); ++ case SSL_GROUP_X25519_KYBER768_DRAFT00: ++ return MakeUnique(); case SSL_GROUP_MLKEM1024: return MakeUnique(); + case SSL_GROUP_P256_KYBER768_DRAFT00: @@ -371,26 +580,26 @@ index d155b5527..4fb08906b 100644 return nullptr; } diff --git a/ssl/ssl_lib.cc b/ssl/ssl_lib.cc -index 89702eaaf..a7505841c 100644 +index b59029f54..33cc42dde 100644 --- a/ssl/ssl_lib.cc +++ b/ssl/ssl_lib.cc -@@ -385,6 +385,7 @@ ssl_ctx_st::ssl_ctx_st(const SSL_METHOD *ssl_method) - channel_id_enabled(false), +@@ -383,6 +383,7 @@ bssl::SSLContext::SSLContext(const SSL_METHOD *ssl_method) grease_enabled(false), + grease_sigalgs_enabled(false), permute_extensions(false), + disable_second_keyshare(false), allow_unknown_alpn_protos(false), false_start_allowed_without_alpn(false), handoff(false), -@@ -517,6 +518,7 @@ SSL *SSL_new(SSL_CTX *ctx) { +@@ -515,6 +516,7 @@ SSL *SSL_new(SSL_CTX *ctx) { ssl->config->retain_only_sha256_of_client_certs = - ctx->retain_only_sha256_of_client_certs; - ssl->config->permute_extensions = ctx->permute_extensions; -+ ssl->config->disable_second_keyshare = ctx->disable_second_keyshare; - ssl->config->aes_hw_override = ctx->aes_hw_override; - ssl->config->aes_hw_override_value = ctx->aes_hw_override_value; - ssl->config->compliance_policy = ctx->compliance_policy; -@@ -582,6 +584,7 @@ SSL_CONFIG::SSL_CONFIG(SSL *ssl_arg) + ctx_impl->retain_only_sha256_of_client_certs; + ssl->config->permute_extensions = ctx_impl->permute_extensions; ++ ssl->config->disable_second_keyshare = ctx_impl->disable_second_keyshare; + ssl->config->compliance_policy = ctx_impl->compliance_policy; + + if (!ssl->config->tls13_cipher_list.CopyFrom(ctx_impl->tls13_cipher_list)) { +@@ -583,6 +585,7 @@ SSL_CONFIG::SSL_CONFIG(SSLImpl *ssl_arg) jdk11_workaround(false), quic_use_legacy_codepoint(false), permute_extensions(false), @@ -398,38 +607,49 @@ index 89702eaaf..a7505841c 100644 alps_use_new_codepoint(true), server_padding_enabled(false) { assert(ssl); -@@ -3390,6 +3393,15 @@ int SSL_set1_curves_list(SSL *ssl, const char *curves) { +@@ -3577,6 +3580,15 @@ int SSL_set1_curves_list(SSL *ssl, const char *curves) { return SSL_set1_groups_list(ssl, curves); } +void SSL_use_second_keyshare(SSL *ssl, int enabled) { -+ ssl->config->disable_second_keyshare = !enabled; ++ FromOpaque(ssl)->config->disable_second_keyshare = !enabled; +} + +void SSL_CTX_use_second_keyshare(SSL_CTX *ctx, int enabled) { -+ ctx->disable_second_keyshare = !enabled; ++ FromOpaque(ctx)->disable_second_keyshare = !enabled; +} + + namespace fips202205 { // (References are to SP 800-52r2): -@@ -3401,7 +3413,9 @@ namespace fips202205 { +@@ -3588,7 +3600,9 @@ namespace fips202205 { // Section 3.3.1 // "The server shall be configured to only use cipher suites that are // composed entirely of NIST approved algorithms" -static const uint16_t kGroups[] = {SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1}; +static const uint16_t kGroups[] = { -+ SSL_GROUP_P256_KYBER768_DRAFT00, ++ SSL_GROUP_X25519_MLKEM768, SSL_GROUP_P256_KYBER768_DRAFT00, + SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1}; static const uint16_t kSigAlgs[] = { SSL_SIGN_RSA_PKCS1_SHA256, diff --git a/ssl/ssl_test.cc b/ssl/ssl_test.cc -index a91a6268c..3999ad61b 100644 +index 25d0ca38b..36b1d6ba7 100644 --- a/ssl/ssl_test.cc +++ b/ssl/ssl_test.cc -@@ -522,6 +522,14 @@ static const CurveTest kCurveTests[] = { +@@ -495,6 +495,10 @@ static const CurveTest kCurveTests[] = { + "P-256", + {SSL_GROUP_SECP256R1}, + }, ++ { ++ "P-256:X25519Kyber768Draft00", ++ {SSL_GROUP_SECP256R1, SSL_GROUP_X25519_KYBER768_DRAFT00}, ++ }, + { + "P-256:X25519MLKEM768", + {SSL_GROUP_SECP256R1, SSL_GROUP_X25519_MLKEM768}, +@@ -507,6 +511,14 @@ static const CurveTest kCurveTests[] = { "MLKEM1024:X25519MLKEM768", {SSL_GROUP_MLKEM1024, SSL_GROUP_X25519_MLKEM768}, }, @@ -444,250 +664,58 @@ index a91a6268c..3999ad61b 100644 { "P-256:P-384:P-521:X25519", -@@ -683,7 +691,9 @@ TEST(SSLTest, CurveRules) { +@@ -686,8 +698,10 @@ TEST(SSLTest, CurveRules) { } TEST(SSLTest, DefaultCurves) { -- const uint16_t kDefaults[] = {SSL_GROUP_X25519, SSL_GROUP_SECP256R1, +- const uint16_t kDefaults[] = {SSL_GROUP_X25519_MLKEM768, SSL_GROUP_X25519, +- SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1}; + const uint16_t kDefaults[] = {SSL_GROUP_X25519_MLKEM768, + SSL_GROUP_P256_KYBER768_DRAFT00, + SSL_GROUP_X25519, SSL_GROUP_SECP256R1, - SSL_GROUP_SECP384R1}; ++ SSL_GROUP_SECP384R1}; // Test the group ID APIs. -@@ -1643,6 +1653,9 @@ static bool GetClientHello(SSL *ssl, std::vector *out) { - static size_t GetClientHelloLen(uint16_t max_version, uint16_t session_version, - size_t ticket_len) { - bssl::UniquePtr ctx(SSL_CTX_new(TLS_method())); -+ // RTG-3417 bas: we need to disable PQ here so that the small ClientHello -+ // padding tests properly tests things. -+ SSL_CTX_set1_curves_list(ctx.get(), "X25519"); - bssl::UniquePtr session = - CreateSessionWithTicket(session_version, ticket_len); - if (!ctx || !session) { -@@ -2317,7 +2330,10 @@ TEST(SSLTest, SetGroupIdsWithEqualPreference) { - // Test that the SSL group flags are defaulted to zero when zero groups are set + { +@@ -2224,7 +2238,9 @@ TEST(SSLTest, SetGroupIdsWithEqualPreference) { // (i.e. using the default groups). TEST(SSLTest, SetGroupIdsWithFlags_DefaultGroups) { -- const uint16_t kDefaultGroups[] = {SSL_GROUP_X25519, SSL_GROUP_SECP256R1, -+ const uint16_t kDefaultGroups[] = {SSL_GROUP_X25519_MLKEM768, + const uint16_t kDefaultGroups[] = {SSL_GROUP_X25519_MLKEM768, +- SSL_GROUP_X25519, SSL_GROUP_SECP256R1, + SSL_GROUP_P256_KYBER768_DRAFT00, + SSL_GROUP_X25519, + SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1}; const uint32_t kBogusFlags[] = {SSL_GROUP_FLAG_EQUAL_PREFERENCE_WITH_NEXT, SSL_GROUP_FLAG_EQUAL_PREFERENCE_WITH_NEXT, 0}; -@@ -7112,7 +7128,9 @@ TEST(SSLTest, ApplyHandoffRemovesUnsupportedCurves) { +@@ -7411,8 +7427,10 @@ TEST(SSLTest, ApplyHandoffRemovesUnsupportedCurves) { // The default list of groups is used before applying the handoff. - EXPECT_THAT(server->config->supported_group_list, -- ElementsAreArray({SSL_GROUP_X25519, SSL_GROUP_SECP256R1, + EXPECT_THAT(FromOpaque(server.get())->config->supported_group_list, +- ElementsAreArray({SSL_GROUP_X25519_MLKEM768, SSL_GROUP_X25519, +- SSL_GROUP_SECP256R1, SSL_GROUP_SECP384R1})); + ElementsAreArray({SSL_GROUP_X25519_MLKEM768, + SSL_GROUP_P256_KYBER768_DRAFT00, + SSL_GROUP_X25519, SSL_GROUP_SECP256R1, - SSL_GROUP_SECP384R1})); ++ SSL_GROUP_SECP384R1})); ASSERT_TRUE(SSL_apply_handoff(server.get(), handoff)); - EXPECT_EQ(1u, server->config->supported_group_list.size()); -diff --git a/ssl/test/runner/basic_tests.go b/ssl/test/runner/basic_tests.go -index 54d49637b..5887c715a 100644 ---- a/ssl/test/runner/basic_tests.go -+++ b/ssl/test/runner/basic_tests.go -@@ -132,6 +132,7 @@ read alert 1 0 - `write hs 1 - read hs 3 - write hs 1 -+write hs 1 - read hs 2 - read hs 11 - read hs 12 -@@ -2003,6 +2004,7 @@ read alert 1 0 - write hs 2 - write hs 8 - write hs 11 -+write hs 11 - write hs 15 - write hs 20 - read hs 20 -diff --git a/ssl/test/runner/cbc_tests.go b/ssl/test/runner/cbc_tests.go -index 6f49d12af..5e970b2b5 100644 ---- a/ssl/test/runner/cbc_tests.go -+++ b/ssl/test/runner/cbc_tests.go -@@ -14,6 +14,8 @@ - - package runner - -+import "strconv" -+ - func addCBCPaddingTests() { - testCases = append(testCases, testCase{ - name: "MaxCBCPadding", -@@ -104,6 +106,7 @@ func addCBCSplittingTests() { - "-partial-write", - // BoringSSL disables 3DES by default. - "-cipher", "ALL:3DES", -+ "-curves", strconv.Itoa(int(CurveX25519)), - }, - }) - } -diff --git a/ssl/test/runner/common.go b/ssl/test/runner/common.go -index c241c418e..9ffafa248 100644 ---- a/ssl/test/runner/common.go -+++ b/ssl/test/runner/common.go -@@ -2186,7 +2186,7 @@ type ProtocolBugs struct { - FailIfHelloRetryRequested bool - - // FailIfPostQuantumOffered will cause a server to reject a ClientHello if -- // post-quantum curves are supported. -+ // post-quantum curves are not supported. - FailIfPostQuantumOffered bool - - // ExpectKeyShares, if not nil, lists (in order) the curves that a ClientHello -diff --git a/ssl/test/runner/curve_tests.go b/ssl/test/runner/curve_tests.go -index 956a73203..d04a1531d 100644 ---- a/ssl/test/runner/curve_tests.go -+++ b/ssl/test/runner/curve_tests.go -@@ -582,17 +582,6 @@ func addCurveTests() { - }) - } - -- // ML-KEM and Kyber should not be offered by default as a client. -- testCases = append(testCases, testCase{ -- name: "PostQuantumNotEnabledByDefaultInClients", -- config: Config{ -- MinVersion: VersionTLS13, -- Bugs: ProtocolBugs{ -- FailIfPostQuantumOffered: true, -- }, -- }, -- }) -- - for _, curve := range testCurves { - if !isMLKEMGroup(curve.id) { - continue -@@ -682,18 +671,19 @@ func addCurveTests() { - }) - } - -- // As a server, ML-KEMs and Kyber are not yet supported by default. -+ // If ML-KEM is offered, both X25519 and ML-KEM should have a key-share. - testCases = append(testCases, testCase{ -- testType: serverTest, -- name: "PostQuantumNotEnabledByDefaultForAServer", -+ name: "NotJustMLKEMKeyShare", - config: Config{ -- MinVersion: VersionTLS13, -- CurvePreferences: []CurveID{CurveX25519MLKEM768, CurveMLKEM1024, CurveX25519Kyber768, CurveX25519}, -- DefaultCurves: []CurveID{CurveX25519MLKEM768, CurveMLKEM1024, CurveX25519Kyber768}, -+ MinVersion: VersionTLS13, -+ Bugs: ProtocolBugs{ -+ ExpectedKeyShares: []CurveID{CurveX25519MLKEM768, CurveX25519}, -+ }, - }, - flags: []string{ -- "-server-preference", -- "-expect-curve-id", strconv.Itoa(int(CurveX25519)), -+ "-curves", strconv.Itoa(int(CurveX25519MLKEM768)), -+ "-curves", strconv.Itoa(int(CurveX25519)), -+ "-expect-curve-id", strconv.Itoa(int(CurveX25519MLKEM768)), - }, - }) - -diff --git a/ssl/test/runner/ech_tests.go b/ssl/test/runner/ech_tests.go -index 2cd3c10d3..f19d8d20a 100644 ---- a/ssl/test/runner/ech_tests.go -+++ b/ssl/test/runner/ech_tests.go -@@ -451,7 +451,8 @@ func addEncryptedClientHelloTests() { - expectMsgCallback += clientAndServerHello + EXPECT_EQ(1u, FromOpaque(server.get())->config->supported_group_list.size()); + EXPECT_EQ(SSL_GROUP_SECP256R1, +diff --git a/ssl/test/runner/compliance_policy_tests.go b/ssl/test/runner/compliance_policy_tests.go +index 3e97718b8..269fbcca6 100644 +--- a/ssl/test/runner/compliance_policy_tests.go ++++ b/ssl/test/runner/compliance_policy_tests.go +@@ -151,6 +151,8 @@ func addCompliancePolicyTests() { + switch curve.id { + case CurveP256, CurveP384: + isFIPSCurve = true ++ case CurveX25519MLKEM768: ++ isFIPSCurve = true } - // EncryptedExtensions onwards. -- expectMsgCallback += `write hs 8 -+ if protocol != dtls { -+ expectMsgCallback += `write hs 8 - write hs 11 - write hs 15 - write hs 20 -@@ -462,6 +463,20 @@ write hs 4 - read ack - read ack - ` -+ } else { -+ expectMsgCallback += `write hs 8 -+write hs 11 -+write hs 11 -+write hs 15 -+write hs 20 -+read hs 20 -+write ack -+write hs 4 -+write hs 4 -+read ack -+read ack -+` -+ } - if protocol != dtls { - expectMsgCallback = strings.ReplaceAll(expectMsgCallback, "write ack\n", "") - expectMsgCallback = strings.ReplaceAll(expectMsgCallback, "read ack\n", "") -@@ -2349,8 +2364,11 @@ read ack - // Test the message callback is correctly reported, with and without - // HelloRetryRequest. -- clientAndServerHello := "write clienthelloinner\nwrite hs 1\nread hs 2\n" -- clientAndServerHelloInitial := clientAndServerHello -+ clientAndServerHelloInitial := "write clienthelloinner\nwrite hs 1\nwrite hs 1\nread hs 2\n" -+ clientAndServerHello := "write clienthelloinner\nwrite hs 1\nread hs 2\n" -+ if protocol != dtls { -+ clientAndServerHelloInitial = clientAndServerHello -+ } - if protocol == tls { - clientAndServerHelloInitial += "write ccs\n" - } -diff --git a/ssl/test/runner/extension_tests.go b/ssl/test/runner/extension_tests.go -index ab9b0b02d..834da257f 100644 ---- a/ssl/test/runner/extension_tests.go -+++ b/ssl/test/runner/extension_tests.go -@@ -16,6 +16,7 @@ package runner - - import ( - "fmt" -+ "strconv" - ) - - func addExtensionTests() { -@@ -2001,7 +2002,7 @@ func addExtensionTests() { - // This hostname just needs to be long enough to push the - // ClientHello into F5's danger zone between 256 and 511 bytes - // long. -- flags: []string{"-host-name", "01234567890123456789012345678901234567890123456789012345678901234567890123456789.com"}, -+ flags: []string{"-host-name", "01234567890123456789012345678901234567890123456789012345678901234567890123456789.com", "-curves", strconv.Itoa(int(CurveX25519))}, - }) - - // Test that illegal extensions in TLS 1.3 are rejected by the client if -diff --git a/ssl/test/runner/key_update_tests.go b/ssl/test/runner/key_update_tests.go -index f98528265..2068b1102 100644 ---- a/ssl/test/runner/key_update_tests.go -+++ b/ssl/test/runner/key_update_tests.go -@@ -14,7 +14,10 @@ - - package runner - --import "slices" -+import ( -+ "slices" -+ "strconv" -+) - - func addKeyUpdateTests() { - // TLS tests. -@@ -295,6 +298,7 @@ func addKeyUpdateTests() { - }, - }, - shimSendsKeyUpdateBeforeRead: true, -+ flags: []string{"-curves", strconv.Itoa(int(CurveX25519))}, - }) - - // Test that shim responds to KeyUpdate requests. + var isFIPSPQCurve bool diff --git a/tool/client.cc b/tool/client.cc -index 1653af8da..cab725d40 100644 +index 1f2b19965..6cf555433 100644 --- a/tool/client.cc +++ b/tool/client.cc @@ -156,6 +156,11 @@ static const struct argument kArguments[] = { @@ -713,6 +741,3 @@ index 1653af8da..cab725d40 100644 // Configure accepted roots. if (args_map.count("-root-certs") != 0) { if (!SSL_CTX_load_verify_locations( --- -2.50.1 (Apple Git-155) - diff --git a/boring-sys/patches/relax-cert-validation.patch b/boring-sys/patches/relax-cert-validation.patch index 884e5e57b..f880dd328 100644 --- a/boring-sys/patches/relax-cert-validation.patch +++ b/boring-sys/patches/relax-cert-validation.patch @@ -14,19 +14,80 @@ BoringSSL pin accepted them. There is no Rust API to relax this per connection. Restore the historical default (off) so RSA keyUsage mismatches are non-fatal again; non-RSA keyUsage enforcement is unaffected. + +Upstream removed the enforce_rsa_key_usage field in 39dc2564e, so this +now restores the conditional it used to guard instead of flipping a +default. --- -diff --git a/ssl/ssl_lib.cc b/ssl/ssl_lib.cc -index 89702eaaf..4be64f8a5 100644 ---- a/ssl/ssl_lib.cc -+++ b/ssl/ssl_lib.cc -@@ -575,7 +575,7 @@ SSL_CONFIG::SSL_CONFIG(SSL *ssl_arg) - signed_cert_timestamps_enabled(false), - ocsp_stapling_enabled(false), - channel_id_enabled(false), -- enforce_rsa_key_usage(true), -+ enforce_rsa_key_usage(false), - retain_only_sha256_of_client_certs(false), - handoff(false), - shed_handshake_config(false), --- -2.39.5 + ssl/handshake_client.cc | 13 ++++++++++++- + ssl/test/runner/key_usage_tests.go | 15 +++++++++++---- + 2 files changed, 23 insertions(+), 5 deletions(-) + +diff --git a/ssl/handshake_client.cc b/ssl/handshake_client.cc +index a4a53cda6..950ac611d 100644 +--- a/ssl/handshake_client.cc ++++ b/ssl/handshake_client.cc +@@ -1402,11 +1402,22 @@ static enum ssl_hs_wait_t do_send_client_key_exchange(SSL_HANDSHAKE *hs) { + + // Check the key usage matches the cipher suite. Key usage is only checked + // for X.509 certs. (RPKs have no keyUsage to enforce.) ++ // ++ // BoringSSL enforces this for RSA leaves too, but many real-world origins ++ // serve RSA certificates whose keyUsage does not assert the bit that the ++ // negotiated cipher suite requires, and OpenSSL accepts them. Restore the ++ // historical, non-fatal behaviour for RSA only. Enforcement for non-RSA ++ // keys is unaffected; in particular it is still needed to distinguish ECDH ++ // certificates, which we do not support, from ECDSA certificates. ++ // See https://crbug.com/795089. + ssl_key_usage_t intended_use = (alg_k & SSL_kRSA) + ? key_usage_encipherment + : key_usage_digital_signature; + if (!ssl_cert_check_key_usage(&leaf_cbs, intended_use)) { +- return ssl_hs_error; ++ if (EVP_PKEY_id(hs->peer_pubkey.get()) != EVP_PKEY_RSA) { ++ return ssl_hs_error; ++ } ++ ERR_clear_error(); + } + } + +diff --git a/ssl/test/runner/key_usage_tests.go b/ssl/test/runner/key_usage_tests.go +index c9555066f..8b7d0bffc 100644 +--- a/ssl/test/runner/key_usage_tests.go ++++ b/ssl/test/runner/key_usage_tests.go +@@ -82,6 +82,15 @@ func addRSAKeyUsageTests() { + } + + for _, ver := range tlsVersions { ++ // The relax-cert-validation patch restores the historical behaviour of ++ // not enforcing RSA keyUsage on the client. That check only ever lived ++ // on the TLS 1.2-and-below code path, so TLS 1.3 still rejects these. ++ rsaClientEnforced := ver.version >= VersionTLS13 ++ rsaClientError := "" ++ if rsaClientEnforced { ++ rsaClientError = ":KEY_USAGE_BIT_INCORRECT:" ++ } ++ + testCases = append(testCases, testCase{ + testType: clientTest, + name: "RSAKeyUsage-Client-WantSignature-GotEncipherment-" + ver.name, +@@ -91,8 +100,8 @@ func addRSAKeyUsageTests() { + Credential: &encCert, + CipherSuites: dsSuites, + }, +- shouldFail: true, +- expectedError: ":KEY_USAGE_BIT_INCORRECT:", ++ shouldFail: rsaClientEnforced, ++ expectedError: rsaClientError, + }) + + testCases = append(testCases, testCase{ +@@ -128,8 +137,6 @@ func addRSAKeyUsageTests() { + Credential: &dsCert, + CipherSuites: encSuites, + }, +- shouldFail: true, +- expectedError: ":KEY_USAGE_BIT_INCORRECT:", + }) + } + diff --git a/boring-sys/patches/rpk.patch b/boring-sys/patches/rpk.patch index 5a97bbe20..e73c3a0dd 100644 --- a/boring-sys/patches/rpk.patch +++ b/boring-sys/patches/rpk.patch @@ -16,14 +16,14 @@ The new methods match the Rust bindings present in boring <= 5: --- include/openssl/ssl.h | 55 +++++++++++++++++++++++++++++++++++++++++++ ssl/ssl_credential.cc | 48 +++++++++++++++++++++++++++++++++++++ - ssl/ssl_lib.cc | 28 ++++++++++++++++++++++ - 3 files changed, 131 insertions(+) + ssl/ssl_lib.cc | 31 ++++++++++++++++++++++++ + 3 files changed, 134 insertions(+) diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h -index 055b3e025..9bfb82215 100644 +index 0dab3b037..4747aae96 100644 --- a/include/openssl/ssl.h +++ b/include/openssl/ssl.h -@@ -4027,6 +4027,61 @@ OPENSSL_EXPORT int SSL_get_peer_cert_type(const SSL *ssl); +@@ -4090,6 +4090,61 @@ OPENSSL_EXPORT int SSL_get_peer_cert_type(const SSL *ssl); OPENSSL_EXPORT EVP_PKEY *SSL_get0_peer_rpk(const SSL *ssl); @@ -86,10 +86,10 @@ index 055b3e025..9bfb82215 100644 // // Password Authenticated Key Exchange protocols allow client and server to diff --git a/ssl/ssl_credential.cc b/ssl/ssl_credential.cc -index b1090a212..5e2b2e17a 100644 +index d7317da80..448f78a90 100644 --- a/ssl/ssl_credential.cc +++ b/ssl/ssl_credential.cc -@@ -403,6 +403,54 @@ SSL_CREDENTIAL *SSL_CREDENTIAL_new_raw_public_key_custom( +@@ -440,6 +440,54 @@ SSL_CREDENTIAL *SSL_CREDENTIAL_new_raw_public_key_custom( return cred.release(); } @@ -145,41 +145,41 @@ index b1090a212..5e2b2e17a 100644 FromOpaque(cred)->UpRefInternal(); } diff --git a/ssl/ssl_lib.cc b/ssl/ssl_lib.cc -index 89702eaaf..06c6eb1e6 100644 +index 8c8b2bad4..ade682944 100644 --- a/ssl/ssl_lib.cc +++ b/ssl/ssl_lib.cc -@@ -3804,3 +3804,31 @@ void SSL_set_server_padding_enabled(SSL *ssl, int enabled) { +@@ -3961,3 +3961,34 @@ void SSL_set_server_padding_enabled(SSL *ssl, int enabled) { int SSL_server_sent_requested_padding(const SSL *ssl) { - return ssl->s3->server_sent_requested_padding; + return FromOpaque(ssl)->s3->server_sent_requested_padding; } + +// The following functions are compatibility shims for the Rust bindings in +// boring-sys. They are not part of upstream BoringSSL. + +const EVP_PKEY *SSL_get0_peer_pubkey(const SSL *ssl) { -+ if (ssl->s3->hs == nullptr) { ++ const auto *ssl_impl = FromOpaque(ssl); ++ if (ssl_impl->s3->hs == nullptr) { + return nullptr; + } -+ return ssl->s3->hs->peer_pubkey.get(); ++ return ssl_impl->s3->hs->peer_pubkey.get(); +} + +void SSL_CTX_get0_accepted_peer_cert_types(const SSL_CTX *ctx, + const uint8_t **types, + size_t *types_len) { -+ *types = ctx->accepted_peer_cert_types.data(); -+ *types_len = ctx->accepted_peer_cert_types.size(); ++ const auto *ctx_impl = FromOpaque(ctx); ++ *types = ctx_impl->accepted_peer_cert_types.data(); ++ *types_len = ctx_impl->accepted_peer_cert_types.size(); +} + +void SSL_get0_accepted_peer_cert_types(const SSL *ssl, const uint8_t **types, + size_t *types_len) { -+ if (ssl->config == nullptr) { ++ const auto *ssl_impl = FromOpaque(ssl); ++ if (ssl_impl->config == nullptr) { + *types = nullptr; + *types_len = 0; + return; + } -+ *types = ssl->config->accepted_peer_cert_types.data(); -+ *types_len = ssl->config->accepted_peer_cert_types.size(); ++ *types = ssl_impl->config->accepted_peer_cert_types.data(); ++ *types_len = ssl_impl->config->accepted_peer_cert_types.size(); +} --- -2.50.1 (Apple Git-155) - diff --git a/boring-sys/patches/underscore-wildcards.patch b/boring-sys/patches/underscore-wildcards.patch index 20c97d3f5..5e02e5437 100644 --- a/boring-sys/patches/underscore-wildcards.patch +++ b/boring-sys/patches/underscore-wildcards.patch @@ -4,16 +4,16 @@ Date: Wed, 27 May 2026 13:59:54 -0700 Subject: [PATCH] Introduce X509_CHECK_FLAG_UNDERSCORE_WILDCARDS --- - crypto/x509/v3_utl.cc | 4 +++- - crypto/x509/x509_test.cc | 27 +++++++++++++++++++++++++++ - include/openssl/x509.h | 3 +++ - 3 files changed, 33 insertions(+), 1 deletion(-) + crypto/x509/v3_utl.cc | 4 +++- + crypto/x509/x509_test.cc | 27 +++++++++++++++++++++++++++ + include/openssl/x509.h | 4 ++++ + 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crypto/x509/v3_utl.cc b/crypto/x509/v3_utl.cc -index 6605c5c0d..10fb91a63 100644 +index 765dfa634..ab45d3b13 100644 --- a/crypto/x509/v3_utl.cc +++ b/crypto/x509/v3_utl.cc -@@ -709,7 +709,9 @@ static int wildcard_match(const unsigned char *prefix, size_t prefix_len, +@@ -697,7 +697,9 @@ static int wildcard_match(const unsigned char *prefix, size_t prefix_len, // Check that the part matched by the wildcard contains only // permitted characters and only matches a single label. for (p = wildcard_start; p != wildcard_end; ++p) { @@ -25,10 +25,10 @@ index 6605c5c0d..10fb91a63 100644 } } diff --git a/crypto/x509/x509_test.cc b/crypto/x509/x509_test.cc -index cc79b0901..e32dc575e 100644 +index f151a8dd8..278fc5481 100644 --- a/crypto/x509/x509_test.cc +++ b/crypto/x509/x509_test.cc -@@ -5778,6 +5778,33 @@ TEST(X509Test, Names) { +@@ -5871,6 +5871,33 @@ TEST(X509Test, Names) { /*invalid_emails=*/{}, /*flags=*/0, }, @@ -63,19 +63,17 @@ index cc79b0901..e32dc575e 100644 size_t i = 0; diff --git a/include/openssl/x509.h b/include/openssl/x509.h -index e72d9ca9b..6dba691c3 100644 +index d08e888b2..d4dc47643 100644 --- a/include/openssl/x509.h +++ b/include/openssl/x509.h -@@ -3372,6 +3372,9 @@ OPENSSL_EXPORT int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param, +@@ -3372,6 +3372,10 @@ OPENSSL_EXPORT int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param, // enabled when subjectAltNames is missing. #define X509_CHECK_FLAG_NEVER_CHECK_SUBJECT 0x20 -+// X509_CHECK_FLAG_UNDERSCORE_WILDCARDS allows underscores in DNS wildcard matches. ++// X509_CHECK_FLAG_UNDERSCORE_WILDCARDS allows underscores in DNS wildcard ++// matches. +#define X509_CHECK_FLAG_UNDERSCORE_WILDCARDS 0x40 + - // X509_VERIFY_PARAM_set_hostflags sets the name-checking flags on |param| to - // |flags|. |flags| should be a combination of |X509_CHECK_FLAG_*| constants. + // X509_VERIFY_PARAM_set_hostflags sets the name-checking flags on `param` to + // `flags`. `flags` should be a combination of `X509_CHECK_FLAG_*` constants. OPENSSL_EXPORT void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param, --- -2.50.1 (Apple Git-155) - diff --git a/boring-sys/src/lib.rs b/boring-sys/src/lib.rs index 8572fbb4c..8b0094e89 100644 --- a/boring-sys/src/lib.rs +++ b/boring-sys/src/lib.rs @@ -71,6 +71,7 @@ pub fn init() { // CBS_init is inline in BoringSSL, so bindgen can't generate bindings for it. #[inline] +#[must_use] pub fn cbs_init(data: &[u8]) -> CBS { CBS { data: data.as_ptr(), diff --git a/boring/src/aead.rs b/boring/src/aead.rs index 5340087b2..c17890480 100644 --- a/boring/src/aead.rs +++ b/boring/src/aead.rs @@ -36,22 +36,33 @@ //! following safe nonce practices for the selected algorithm. //! [`Algorithm::nonce_len`] returns the required nonce size in bytes. //! +//! # Mutability +//! +//! All seal and open methods require `&mut self`. While the generic AEADs +//! (AES-GCM, ChaCha20-Poly1305, etc.) are stateless after initialization, +//! the TLS-specific AEADs are **stateful** and internally mutate the context +//! during seal operations. Using `&mut self` universally prevents LLVM from +//! incorrectly optimizing away state changes — an issue that has caused +//! real-world cryptographic failures (see [quiche#2383]). +//! +//! [quiche#2383]: https://github.com/cloudflare/quiche/pull/2383 +//! //! # Example //! //! ``` //! use boring::aead::{AeadCtx, Algorithm}; //! //! let algorithm = Algorithm::aes_128_gcm(); -//! let ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); +//! let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); //! let nonce = [0u8; 12]; //! let aad = b"record-header"; //! let mut payload = b"hello world".to_vec(); //! let mut tag = vec![0u8; algorithm.max_overhead()]; //! -//! ctx.seal_in_place(&nonce, payload.as_mut_slice(), &mut tag, aad) +//! ctx.seal_in_place_mut(&nonce, payload.as_mut_slice(), &mut tag, aad) //! .unwrap(); //! -//! ctx.open_in_place(&nonce, payload.as_mut_slice(), &tag, aad) +//! ctx.open_in_place_mut(&nonce, payload.as_mut_slice(), &tag, aad) //! .unwrap(); //! //! assert_eq!(payload.as_slice(), b"hello world"); @@ -110,6 +121,70 @@ impl Algorithm { unsafe { Self(ffi::EVP_aead_xchacha20_poly1305()) } } + /// AES-128-GCM with TLS 1.2 nonce construction. + /// + /// Seal operations fail if nonces do not match the TLS 1.2 nonce format. + /// Produces the same ciphertext as [`aes_128_gcm`](Self::aes_128_gcm) but + /// adds an AEAD-level nonce check. + /// + /// # Warning + /// + /// Contexts created with this algorithm are **stateful**. + /// `seal` operations must not be called concurrently on the same context. + #[corresponds(EVP_aead_aes_128_gcm_tls12)] + #[must_use] + pub fn aes_128_gcm_tls12() -> Self { + unsafe { Self(ffi::EVP_aead_aes_128_gcm_tls12()) } + } + + /// AES-256-GCM with TLS 1.2 nonce construction. + /// + /// Seal operations fail if nonces do not match the TLS 1.2 nonce format. + /// Produces the same ciphertext as [`aes_256_gcm`](Self::aes_256_gcm) but + /// adds an AEAD-level nonce check. + /// + /// # Warning + /// + /// Contexts created with this algorithm are **stateful**. + /// `seal` operations must not be called concurrently on the same context. + #[corresponds(EVP_aead_aes_256_gcm_tls12)] + #[must_use] + pub fn aes_256_gcm_tls12() -> Self { + unsafe { Self(ffi::EVP_aead_aes_256_gcm_tls12()) } + } + + /// AES-128-GCM with TLS 1.3 nonce construction. + /// + /// Seal operations fail if nonces do not match the TLS 1.3 nonce format. + /// Produces the same ciphertext as [`aes_128_gcm`](Self::aes_128_gcm) but + /// adds an AEAD-level nonce check. + /// + /// # Warning + /// + /// Contexts created with this algorithm are **stateful**. + /// `seal` operations must not be called concurrently on the same context. + #[corresponds(EVP_aead_aes_128_gcm_tls13)] + #[must_use] + pub fn aes_128_gcm_tls13() -> Self { + unsafe { Self(ffi::EVP_aead_aes_128_gcm_tls13()) } + } + + /// AES-256-GCM with TLS 1.3 nonce construction. + /// + /// Seal operations fail if nonces do not match the TLS 1.3 nonce format. + /// Produces the same ciphertext as [`aes_256_gcm`](Self::aes_256_gcm) but + /// adds an AEAD-level nonce check. + /// + /// # Warning + /// + /// Contexts created with this algorithm are **stateful**. + /// `seal` operations must not be called concurrently on the same context. + #[corresponds(EVP_aead_aes_256_gcm_tls13)] + #[must_use] + pub fn aes_256_gcm_tls13() -> Self { + unsafe { Self(ffi::EVP_aead_aes_256_gcm_tls13()) } + } + /// Returns the key length, in bytes, required by this algorithm. #[corresponds(EVP_AEAD_key_length)] #[allow(clippy::trivially_copy_pass_by_ref)] @@ -255,7 +330,7 @@ impl AeadCtxRef { /// use boring::aead::{AeadCtx, Algorithm}; /// /// let algorithm = Algorithm::chacha20_poly1305(); - /// let ctx = AeadCtx::new(&algorithm, &[7u8; 32], algorithm.max_tag_len()).unwrap(); + /// let mut ctx = AeadCtx::new(&algorithm, &[7u8; 32], algorithm.max_tag_len()).unwrap(); /// /// let nonce = [1u8; 12]; /// let aad = b"frame-header"; @@ -267,7 +342,7 @@ impl AeadCtxRef { /// let mut detached = vec![0u8; extra.len() + algorithm.max_overhead()]; /// /// let detached_written = ctx - /// .seal_scatter( + /// .seal_scatter_mut( /// &nonce, /// main.as_mut_slice(), /// detached.as_mut_slice(), @@ -285,12 +360,28 @@ impl AeadCtxRef { /// full_ciphertext.extend_from_slice(&detached_written[..extra_ct_len]); /// /// // `open_gather` takes ciphertext and detached tag separately. - /// ctx.open_gather(&nonce, full_ciphertext.as_mut_slice(), tag, aad) + /// ctx.open_gather_mut(&nonce, full_ciphertext.as_mut_slice(), tag, aad) /// .unwrap(); /// /// assert_eq!(full_ciphertext.as_slice(), b"hello world"); /// ``` #[corresponds(EVP_AEAD_CTX_seal_scatter)] + pub fn seal_scatter_mut<'a>( + &mut self, + nonce: &[u8], + in_out: &mut [u8], + out_tag: &'a mut [u8], + extra_in: Option<&[u8]>, + associated_data: &[u8], + ) -> Result<&'a mut [u8], ErrorStack> { + #[allow(deprecated)] + self.seal_scatter(nonce, in_out, out_tag, extra_in, associated_data) + } + + #[doc(hidden)] + #[deprecated( + note = "Non-thread-safe when used with TLS due to interior mutability in BoringSSL. Use `seal_scatter_mut` instead." + )] pub fn seal_scatter<'a>( &self, nonce: &[u8], @@ -341,6 +432,21 @@ impl AeadCtxRef { /// [`seal_scatter`](AeadCtxRef::seal_scatter). /// - `associated_data`: The same AAD that was passed during encryption. #[corresponds(EVP_AEAD_CTX_open_gather)] + pub fn open_gather_mut( + &mut self, + nonce: &[u8], + in_out: &mut [u8], + in_tag: &[u8], + associated_data: &[u8], + ) -> Result<(), ErrorStack> { + #[allow(deprecated)] + self.open_gather(nonce, in_out, in_tag, associated_data) + } + + #[doc(hidden)] + #[deprecated( + note = "Non-thread-safe when used with TLS due to interior mutability in BoringSSL. Use `open_gather_mut` instead." + )] pub fn open_gather( &self, nonce: &[u8], @@ -382,6 +488,20 @@ impl AeadCtxRef { /// authenticated but not encrypted. /// /// Returns the sub-slice of `tag` that was written to. + pub fn seal_in_place_mut<'a>( + &mut self, + nonce: &[u8], + buffer: &mut [u8], + tag: &'a mut [u8], + associated_data: &[u8], + ) -> Result<&'a mut [u8], ErrorStack> { + self.seal_scatter_mut(nonce, buffer, tag, None, associated_data) + } + + #[doc(hidden)] + #[deprecated( + note = "Non-thread-safe when used with TLS due to interior mutability in BoringSSL. Use `seal_in_place_mut` instead." + )] pub fn seal_in_place<'a>( &self, nonce: &[u8], @@ -389,6 +509,7 @@ impl AeadCtxRef { tag: &'a mut [u8], associated_data: &[u8], ) -> Result<&'a mut [u8], ErrorStack> { + #[allow(deprecated)] self.seal_scatter(nonce, buffer, tag, None, associated_data) } @@ -405,6 +526,20 @@ impl AeadCtxRef { /// - `tag`: The authentication tag produced by /// [`seal_in_place`](AeadCtxRef::seal_in_place). /// - `associated_data`: The same AAD that was passed during encryption. + pub fn open_in_place_mut( + &mut self, + nonce: &[u8], + buffer: &mut [u8], + tag: &[u8], + associated_data: &[u8], + ) -> Result<(), ErrorStack> { + self.open_gather_mut(nonce, buffer, tag, associated_data) + } + + #[doc(hidden)] + #[deprecated( + note = "Non-thread-safe when used with TLS due to interior mutability in BoringSSL. Use `open_in_place_mut` instead." + )] pub fn open_in_place( &self, nonce: &[u8], @@ -412,6 +547,7 @@ impl AeadCtxRef { tag: &[u8], associated_data: &[u8], ) -> Result<(), ErrorStack> { + #[allow(deprecated)] self.open_gather(nonce, buffer, tag, associated_data) } } @@ -423,16 +559,16 @@ mod tests { #[test] fn in_out() { let algorithm = Algorithm::aes_128_gcm(); - let ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); let nonce = [0u8; 12]; let associated_data = b"this is authenticated"; let mut buffer = b"ABCDE".to_vec(); let mut tag = [0u8; 16]; - ctx.seal_in_place(&nonce, buffer.as_mut_slice(), &mut tag, associated_data) + ctx.seal_in_place_mut(&nonce, buffer.as_mut_slice(), &mut tag, associated_data) .unwrap(); - ctx.open_in_place(&nonce, buffer.as_mut_slice(), &tag, associated_data) + ctx.open_in_place_mut(&nonce, buffer.as_mut_slice(), &tag, associated_data) .unwrap(); assert_eq!(b"ABCDE", buffer.as_slice()); @@ -441,18 +577,18 @@ mod tests { #[test] fn xchacha_in_out() { let algorithm = Algorithm::xchacha20_poly1305(); - let ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 32]).unwrap(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 32]).unwrap(); let nonce = [0u8; 24]; let associated_data = b"xchacha"; let mut buffer = b"payload".to_vec(); let mut tag = [0u8; 16]; let tag_written = ctx - .seal_in_place(&nonce, buffer.as_mut_slice(), &mut tag, associated_data) + .seal_in_place_mut(&nonce, buffer.as_mut_slice(), &mut tag, associated_data) .unwrap(); let tag_len = tag_written.len(); - ctx.open_in_place( + ctx.open_in_place_mut( &nonce, buffer.as_mut_slice(), &tag[..tag_len], @@ -466,7 +602,7 @@ mod tests { #[test] fn seal_scatter_with_extra_in() { let algorithm = Algorithm::chacha20_poly1305(); - let ctx = AeadCtx::new(&algorithm, &[7u8; 32], algorithm.max_tag_len()).unwrap(); + let mut ctx = AeadCtx::new(&algorithm, &[7u8; 32], algorithm.max_tag_len()).unwrap(); let nonce = [1u8; 12]; let aad = b"frame-header"; @@ -475,7 +611,7 @@ mod tests { let mut detached = vec![0u8; extra.len() + algorithm.max_overhead()]; let detached_written = ctx - .seal_scatter( + .seal_scatter_mut( &nonce, main.as_mut_slice(), detached.as_mut_slice(), @@ -489,7 +625,7 @@ mod tests { let mut full_ciphertext = main; full_ciphertext.extend_from_slice(&detached_written[..extra_ct_len]); - ctx.open_gather(&nonce, full_ciphertext.as_mut_slice(), tag, aad) + ctx.open_gather_mut(&nonce, full_ciphertext.as_mut_slice(), tag, aad) .unwrap(); assert_eq!(full_ciphertext.as_slice(), b"hello world"); @@ -516,34 +652,208 @@ mod tests { // (AES-GCM accepts variable-length nonces per spec, so it is not // suitable for testing nonce-length rejection.) let algorithm = Algorithm::chacha20_poly1305(); - let ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 32]).unwrap(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 32]).unwrap(); let mut payload = [0u8; 8]; let mut tag = [0u8; 16]; - let result = ctx.seal_in_place(&[0u8; 11], &mut payload, &mut tag, b""); + let result = ctx.seal_in_place_mut(&[0u8; 11], &mut payload, &mut tag, b""); assert!(result.is_err()); } #[test] fn seal_rejects_insufficient_tag_buffer() { let algorithm = Algorithm::aes_128_gcm(); - let ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); let mut payload = [0u8; 8]; // AES-128-GCM produces a 16-byte tag; an 8-byte buffer must be rejected. let mut short_tag = [0u8; 8]; - let result = ctx.seal_in_place(&[0u8; 12], &mut payload, &mut short_tag, b""); + let result = ctx.seal_in_place_mut(&[0u8; 12], &mut payload, &mut short_tag, b""); assert!(result.is_err()); } #[test] fn open_rejects_invalid_nonce_length() { let algorithm = Algorithm::chacha20_poly1305(); - let ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 32]).unwrap(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 32]).unwrap(); let mut payload = [0u8; 8]; let tag = [0u8; 16]; - let result = ctx.open_in_place(&[0u8; 11], &mut payload, &tag, b""); + let result = ctx.open_in_place_mut(&[0u8; 11], &mut payload, &tag, b""); + assert!(result.is_err()); + } + + /// Helper: seal with one context, open with another (TLS AEADs are + /// directional — the seal context tracks nonce state, so we use a + /// separate open context with the generic algorithm). + fn tls_seal_open_round_trip(algorithm: Algorithm, generic: Algorithm, key: &[u8]) { + let mut seal_ctx = AeadCtx::new_default_tag(&algorithm, key).unwrap(); + let mut open_ctx = AeadCtx::new_default_tag(&generic, key).unwrap(); + + let nonce = [0u8; 12]; + let aad = b"tls-record"; + let mut payload = b"hello TLS".to_vec(); + let original = payload.clone(); + + let mut tag = vec![0u8; algorithm.max_overhead()]; + seal_ctx + .seal_in_place_mut(&nonce, &mut payload, &mut tag, aad) + .unwrap(); + + // Ciphertext should differ from plaintext. + assert_ne!(payload.as_slice(), original.as_slice()); + + open_ctx + .open_in_place_mut(&nonce, &mut payload, &tag, aad) + .unwrap(); + + assert_eq!(payload.as_slice(), original.as_slice()); + } + + #[test] + fn aes_128_gcm_tls12_round_trip() { + tls_seal_open_round_trip( + Algorithm::aes_128_gcm_tls12(), + Algorithm::aes_128_gcm(), + &[0u8; 16], + ); + } + + #[test] + fn aes_256_gcm_tls12_round_trip() { + tls_seal_open_round_trip( + Algorithm::aes_256_gcm_tls12(), + Algorithm::aes_256_gcm(), + &[0u8; 32], + ); + } + + #[test] + fn aes_128_gcm_tls13_round_trip() { + tls_seal_open_round_trip( + Algorithm::aes_128_gcm_tls13(), + Algorithm::aes_128_gcm(), + &[0u8; 16], + ); + } + + #[test] + fn aes_256_gcm_tls13_round_trip() { + tls_seal_open_round_trip( + Algorithm::aes_256_gcm_tls13(), + Algorithm::aes_256_gcm(), + &[0u8; 32], + ); + } + + /// Build a 12-byte nonce with the given big-endian u64 counter in the + /// last 8 bytes (TLS 1.2 nonce layout: 4-byte implicit IV + 8-byte + /// explicit counter). + fn nonce_with_counter(counter: u64) -> [u8; 12] { + let mut nonce = [0u8; 12]; + nonce[4..].copy_from_slice(&counter.to_be_bytes()); + nonce + } + + #[test] + fn tls12_rejects_nonce_reuse() { + let algorithm = Algorithm::aes_128_gcm_tls12(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut payload = b"hello".to_vec(); + let mut tag = [0u8; 16]; + + // First seal with counter 0 succeeds. + ctx.seal_in_place_mut(&nonce_with_counter(0), &mut payload, &mut tag, b"") + .unwrap(); + + // Sealing again with the same counter (0) must fail — nonces must be + // strictly monotonically increasing. + let mut payload2 = b"world".to_vec(); + let result = ctx.seal_in_place_mut(&nonce_with_counter(0), &mut payload2, &mut tag, b""); + assert!(result.is_err()); + } + + #[test] + fn tls12_rejects_nonce_going_backwards() { + let algorithm = Algorithm::aes_128_gcm_tls12(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut tag = [0u8; 16]; + + // Seal with counter 5, then try counter 3. + let mut p1 = b"hello".to_vec(); + ctx.seal_in_place_mut(&nonce_with_counter(5), &mut p1, &mut tag, b"") + .unwrap(); + + let mut p2 = b"world".to_vec(); + let result = ctx.seal_in_place_mut(&nonce_with_counter(3), &mut p2, &mut tag, b""); assert!(result.is_err()); } + + #[test] + fn tls12_accepts_monotonic_nonces() { + let algorithm = Algorithm::aes_128_gcm_tls12(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut tag = [0u8; 16]; + + for counter in 0..5u64 { + let mut payload = b"test".to_vec(); + ctx.seal_in_place_mut(&nonce_with_counter(counter), &mut payload, &mut tag, b"") + .unwrap(); + } + } + + #[test] + fn tls13_rejects_nonce_reuse() { + let algorithm = Algorithm::aes_128_gcm_tls13(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut tag = [0u8; 16]; + + // TLS 1.3 nonce: sequence XOR mask. First call sets the mask. + let nonce0 = [0u8; 12]; + let mut p1 = b"hello".to_vec(); + ctx.seal_in_place_mut(&nonce0, &mut p1, &mut tag, b"") + .unwrap(); + + // Second call with the same nonce implies counter went backwards + // (counter 0 again), which must fail. + let mut p2 = b"world".to_vec(); + let result = ctx.seal_in_place_mut(&nonce0, &mut p2, &mut tag, b""); + assert!(result.is_err()); + } + + #[test] + fn generic_gcm_accepts_nonce_reuse() { + // Generic AES-GCM does NOT enforce nonce monotonicity — it is the + // caller's responsibility. Contrast with the tls12/tls13 variants. + let algorithm = Algorithm::aes_128_gcm(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut tag = [0u8; 16]; + let nonce = nonce_with_counter(0); + + let mut p1 = b"hello".to_vec(); + ctx.seal_in_place_mut(&nonce, &mut p1, &mut tag, b"") + .unwrap(); + + // Same nonce again — generic GCM accepts it (even though this is + // cryptographically unsafe, the AEAD layer does not reject it). + let mut p2 = b"world".to_vec(); + ctx.seal_in_place_mut(&nonce, &mut p2, &mut tag, b"") + .unwrap(); + } + + #[test] + fn generic_gcm_accepts_nonce_going_backwards() { + let algorithm = Algorithm::aes_128_gcm(); + let mut ctx = AeadCtx::new_default_tag(&algorithm, &[0u8; 16]).unwrap(); + let mut tag = [0u8; 16]; + + let mut p1 = b"hello".to_vec(); + ctx.seal_in_place_mut(&nonce_with_counter(5), &mut p1, &mut tag, b"") + .unwrap(); + + // Counter 3 after 5 — generic GCM accepts it. + let mut p2 = b"world".to_vec(); + ctx.seal_in_place_mut(&nonce_with_counter(3), &mut p2, &mut tag, b"") + .unwrap(); + } } diff --git a/boring/src/asn1.rs b/boring/src/asn1.rs index 501b4968c..e20ed666c 100644 --- a/boring/src/asn1.rs +++ b/boring/src/asn1.rs @@ -688,8 +688,8 @@ mod tests { assert!(a != c_ref); assert!(b_ref == a); assert!(c_ref != a); - assert!(a_ref == b_ref); - assert!(a_ref != c_ref); + assert_eq!(a_ref, b_ref); + assert_ne!(a_ref, c_ref); } #[test] diff --git a/boring/src/ec.rs b/boring/src/ec.rs index 9eb7a4010..aac0230fa 100644 --- a/boring/src/ec.rs +++ b/boring/src/ec.rs @@ -559,7 +559,7 @@ impl ToOwned for EcKeyRef { fn to_owned(&self) -> EcKey { unsafe { let r = ffi::EC_KEY_up_ref(self.as_ptr()); - assert!(r == 1); + assert_eq!(r, 1); EcKey::from_ptr(self.as_ptr()) } } @@ -878,7 +878,7 @@ mod test { EcKey::from_private_components(&group, key.private_key(), key.public_key()).unwrap(); dup_key.check_key().unwrap(); - assert!(key.private_key() == dup_key.private_key()); + assert_eq!(key.private_key(), dup_key.private_key()); } #[test] diff --git a/boring/src/error.rs b/boring/src/error.rs index 5087d10fb..bfb29299e 100644 --- a/boring/src/error.rs +++ b/boring/src/error.rs @@ -331,7 +331,7 @@ impl Error { } fn is_internal(&self) -> bool { - std::ptr::eq(self.file, BORING_INTERNAL.as_ptr()) + ptr::eq(self.file, BORING_INTERNAL.as_ptr()) } } diff --git a/boring/src/hkdf.rs b/boring/src/hkdf.rs new file mode 100644 index 000000000..cc7acb294 --- /dev/null +++ b/boring/src/hkdf.rs @@ -0,0 +1,95 @@ +//! HMAC-based Extract-and-Expand Key Derivation Function (HKDF) as specified by +//! [RFC 5869](https://www.rfc-editor.org/rfc/rfc5869.html). + +use crate::error::ErrorStack; +use crate::hash::{DigestBytes, MessageDigest}; +use crate::{cvt, ffi}; + +/// HKDF for a given hash function. +/// +/// The digest determines `HashLen`, the length of the pseudorandom key (PRK) +/// returned by [`HkdfSuite::extract`]. HKDF-Expand limits output to +/// `255 * HashLen` bytes, as specified by [RFC 5869, Section +/// 2.3](https://www.rfc-editor.org/rfc/rfc5869.html#section-2.3). +#[derive(Copy, Clone)] +pub struct HkdfSuite { + digest: MessageDigest, +} + +impl HkdfSuite { + /// Creates an HKDF suite using `digest`. + #[must_use] + pub fn new(digest: MessageDigest) -> Self { + Self { digest } + } + + /// Returns `HashLen`, the digest output size in bytes. + #[must_use] + pub fn prk_size(&self) -> usize { + self.digest.size() + } + + /// Computes HKDF-Extract as specified in [RFC 5869, Section + /// 2.2](https://www.rfc-editor.org/rfc/rfc5869.html#section-2.2). + /// + /// `salt` is an optional salt value. An empty `salt` is treated as an + /// omitted salt and is equivalent to a string of `HashLen` zero octets. + /// `ikm` is the input keying material. The returned pseudorandom key (PRK) + /// has length [`HkdfSuite::prk_size`]. + pub fn extract(&self, salt: &[u8], ikm: &[u8]) -> Result { + let mut prk = DigestBytes { + buf: [0u8; ffi::EVP_MAX_MD_SIZE as usize], + len: 0, + }; + ffi::init(); + + // BoringSSL's native HKDF_extract API orders these arguments as + // secret/IKM, then salt, unlike the RFC 5869 notation and this API. + unsafe { + cvt(ffi::HKDF_extract( + prk.buf.as_mut_ptr(), + &mut prk.len, + self.digest.as_ptr(), + ikm.as_ptr(), + ikm.len(), + salt.as_ptr(), + salt.len(), + ))?; + } + + debug_assert_eq!(prk.len, self.prk_size()); + + Ok(prk) + } + + /// Computes HKDF-Expand as specified in [RFC 5869, Section + /// 2.3](https://www.rfc-editor.org/rfc/rfc5869.html#section-2.3). + /// + /// `prk` must be a pseudorandom key of at least `HashLen` bytes, usually + /// the output of [`HkdfSuite::extract`]. Shorter PRKs are rejected. + /// `info` is optional context and application-specific information and may + /// be empty. The function writes `L` bytes of output keying material into + /// `okm`, where `L` is its length. `okm` may be empty. HKDF limits `L` to + /// `255 * HashLen`; output-limit errors are returned as [`ErrorStack`]. + pub fn expand(&self, prk: &[u8], info: &[u8], okm: &mut [u8]) -> Result<(), ErrorStack> { + if prk.len() < self.prk_size() { + return Err(ErrorStack::internal_error_str( + "HKDF PRK is shorter than the digest output", + )); + } + + ffi::init(); + + unsafe { + cvt(ffi::HKDF_expand( + okm.as_mut_ptr(), + okm.len(), + self.digest.as_ptr(), + prk.as_ptr(), + prk.len(), + info.as_ptr(), + info.len(), + )) + } + } +} diff --git a/boring/src/lib.rs b/boring/src/lib.rs index dc47c1f67..8c4a3af33 100644 --- a/boring/src/lib.rs +++ b/boring/src/lib.rs @@ -13,7 +13,8 @@ //! //! ## BoringSSL version //! -//! By default, the crate aims to statically link with the latest BoringSSL master branch. +//! By default, the crate statically links against a pinned BoringSSL revision, vendored as a +//! submodule at `boring-sys/deps/boringssl`. The current pin is upstream tag `0.20260929.0`. //! *Note*: any BoringSSL revision bumps will be released as a major version update of all crates. //! //! # Compilation and linking options @@ -75,26 +76,21 @@ //! The crate can be compiled with [RawPublicKey](https://datatracker.ietf.org/doc/html/rfc7250) //! support by turning on `rpk` compilation feature. //! -//! ## Experimental post-quantum cryptography +//! ## Post-quantum cryptography //! -//! The crate can be compiled with [post-quantum cryptography](https://blog.cloudflare.com/post-quantum-for-all/) -//! support by turning on `post-quantum` compilation feature. +//! Upstream BoringSSL now supports and enables `X25519MLKEM768`, the recommended +//! post-quantum key agreement from RFC 10024, by default. The `pq-experimental` +//! feature is a no-op kept only for backwards compatibility. //! -//! Upstream BoringSSL support the post-quantum hybrid key agreement `X25519Kyber768Draft00`. Most -//! users should stick to that one for now. Enabling this feature, adds a few other post-quantum key -//! agreements: -//! -//! - `X25519MLKEM768` is the successor of `X25519Kyber768Draft00`. We expect servers to switch -//! before the end of 2024. -//! - `X25519Kyber768Draft00Old` is the same as `X25519Kyber768Draft00`, but under its old codepoint. -//! - `X25519Kyber512Draft00`. Similar to `X25519Kyber768Draft00`, but uses level 1 parameter set for -//! Kyber. Not recommended. It's useful to test whether the shorter ClientHello upsets fewer middle -//! boxes. -//! - `P256Kyber768Draft00`. Similar again to `X25519Kyber768Draft00`, but uses P256 as classical -//! part. It uses a non-standard codepoint. Not recommended. +//! We patch BpringSSL to additionally support + +//! - `X25519Kyber768Draft00`, under codepoint `0x6399`. This is the pre-standard predecessor of +//! `X25519MLKEM768`. Not recommended; it's being phased out. +//! - `P256Kyber768Draft00`, under codepoint `0xfe32`, which uses P-256 as the classical part. +//! In the past we needed this for compliance reasons. Not recommended; it's being phased out. //! -//! Presently all these key agreements are deployed by Cloudflare, but we do not guarantee continued -//! support for them. +//! Presently all these key agreements are deployed by Cloudflare. We only support `X25519MLKEM768` +//! long term. #[macro_use] extern crate bitflags; @@ -135,6 +131,7 @@ pub mod error; pub mod ex_data; pub mod fips; pub mod hash; +pub mod hkdf; pub mod hmac; pub mod hpke; pub mod memcmp; diff --git a/boring/src/memcmp.rs b/boring/src/memcmp.rs index 4ac08b655..5ed48164b 100644 --- a/boring/src/memcmp.rs +++ b/boring/src/memcmp.rs @@ -62,7 +62,7 @@ use crate::ffi; /// ``` #[must_use] pub fn eq(a: &[u8], b: &[u8]) -> bool { - assert!(a.len() == b.len()); + assert_eq!(a.len(), b.len()); let ret = unsafe { ffi::CRYPTO_memcmp(a.as_ptr().cast(), b.as_ptr().cast(), a.len()) }; ret == 0 } diff --git a/boring/src/pkcs12.rs b/boring/src/pkcs12.rs index 449b3fafe..35c633720 100644 --- a/boring/src/pkcs12.rs +++ b/boring/src/pkcs12.rs @@ -118,6 +118,7 @@ pub struct ParsedPkcs12_2 { } impl ParsedPkcs12_2 { + #[must_use] pub fn chain(&self) -> Option<&StackRef> { self.ca.as_deref() } diff --git a/boring/src/pkey.rs b/boring/src/pkey.rs index 6ae2bdf10..bc5214e3a 100644 --- a/boring/src/pkey.rs +++ b/boring/src/pkey.rs @@ -237,7 +237,7 @@ where let mut size = 0; _ = cvt_0i(ffi::EVP_PKEY_get_raw_public_key( self.as_ptr(), - std::ptr::null_mut(), + ptr::null_mut(), &mut size, ))?; Ok(size) @@ -305,7 +305,7 @@ where let mut size = 0; _ = cvt_0i(ffi::EVP_PKEY_get_raw_private_key( self.as_ptr(), - std::ptr::null_mut(), + ptr::null_mut(), &mut size, ))?; Ok(size) diff --git a/boring/src/ssl/async_callbacks.rs b/boring/src/ssl/async_callbacks.rs index 42360bfbf..3ef2a3678 100644 --- a/boring/src/ssl/async_callbacks.rs +++ b/boring/src/ssl/async_callbacks.rs @@ -1,8 +1,8 @@ use super::mut_only::MutOnly; use super::{ - ClientHello, GetSessionPendingError, PrivateKeyMethod, PrivateKeyMethodError, SelectCertError, - Ssl, SslAlert, SslContextBuilder, SslRef, SslSession, SslSignatureAlgorithm, SslVerifyError, - SslVerifyMode, + ClientHello, GetSessionPendingError, PrivateKeyMethod, PrivateKeyMethodError, SelectCertAction, + SelectCertError, Ssl, SslAlert, SslContextBuilder, SslRef, SslSession, SslSignatureAlgorithm, + SslVerifyError, SslVerifyMode, }; #[cfg(feature = "credential")] use crate::error::ErrorStack; @@ -21,6 +21,14 @@ pub type BoxSelectCertFuture = ExDataFuture) -> Result<(), AsyncSelectCertError>>; +/// The type of futures to pass to [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. +pub type BoxSelectCertActionFuture = + ExDataFuture>; + +/// The type of callbacks returned by [`BoxSelectCertActionFuture`] methods. +pub type BoxSelectCertActionFinish = + Box) -> Result>; + /// The type of futures returned by [`AsyncPrivateKeyMethod`] methods. pub type BoxPrivateKeyMethodFuture = ExDataFuture>; @@ -46,10 +54,19 @@ pub type BoxCustomVerifyFinish = Box Result<(), SslAl /// Public for documentation purposes. pub type ExDataFuture = Pin + Send>>; +type BoxSelectCertFinishFor = + Box) -> Result>; +type SelectCertFutureIndex = Index< + Ssl, + MutOnly, AsyncSelectCertError>>>>, +>; + pub(crate) static TASK_WAKER_INDEX: LazyLock>> = LazyLock::new(|| Ssl::new_ex_index().unwrap()); -pub(crate) static SELECT_CERT_FUTURE_INDEX: LazyLock< - Index>>, +pub(crate) static SELECT_CERT_FUTURE_INDEX: LazyLock> = + LazyLock::new(|| Ssl::new_ex_index().unwrap()); +pub(crate) static SELECT_CERT_ACTION_FUTURE_INDEX: LazyLock< + SelectCertFutureIndex, > = LazyLock::new(|| Ssl::new_ex_index().unwrap()); pub(crate) static SELECT_PRIVATE_KEY_METHOD_FUTURE_INDEX: LazyLock< Index>>, @@ -75,6 +92,12 @@ impl SslContextBuilder { /// /// See [`SslContextBuilder::set_select_certificate_callback`] for the sync /// setter of this callback. + /// + /// A context has a single certificate selection callback. Calling this method replaces the + /// callback set by any of [`SslContextBuilder::set_select_certificate_callback`], + /// [`SslContextBuilder::set_select_certificate_callback_with_action`], + /// [`SslContextBuilder::set_async_select_certificate_callback`], or + /// [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. pub fn set_async_select_certificate_callback(&mut self, callback: F) where F: Fn(&mut ClientHello<'_>) -> Result @@ -82,24 +105,42 @@ impl SslContextBuilder { + Sync + 'static, { - self.set_select_certificate_callback(move |mut client_hello| { - let fut_poll_result = with_ex_data_future( - &mut client_hello, - *SELECT_CERT_FUTURE_INDEX, - ClientHello::ssl_mut, - &callback, - identity, - ); - - let fut_result = match fut_poll_result { - Poll::Ready(fut_result) => fut_result, - Poll::Pending => return Err(SelectCertError::RETRY), - }; - - let finish = fut_result.or(Err(SelectCertError::ERROR))?; + let callback = + async_select_certificate_callback(callback, *SELECT_CERT_FUTURE_INDEX, |()| { + SelectCertAction::Success + }); + self.set_select_certificate_callback_with_action(callback); + } - finish(client_hello).or(Err(SelectCertError::ERROR)) - }); + /// Sets an action-aware asynchronous certificate selection callback. + /// + /// This method uses a function that returns a future whose output is itself a closure that + /// will be passed [`ClientHello`] to configure the connection based on the computations done + /// in the future. + /// + /// A task waker must be set on `Ssl` values associated with the resulting `SslContext` with + /// [`SslRef::set_task_waker`]. Returning [`SelectCertAction::DisableEch`] discards an inner + /// ClientHello, invokes the callback again with the outer ClientHello, and continues without + /// retry configs. It is only valid when ECH has been accepted; returning it otherwise fails + /// the handshake. + /// The future-producing callback runs again for the outer ClientHello, so per-connection + /// state must handle both calls. + /// + /// A context has a single certificate selection callback. Calling this method replaces the + /// callback set by any of [`SslContextBuilder::set_select_certificate_callback`], + /// [`SslContextBuilder::set_select_certificate_callback_with_action`], + /// [`SslContextBuilder::set_async_select_certificate_callback`], or + /// [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. + pub fn set_async_select_certificate_callback_with_action(&mut self, callback: F) + where + F: Fn(&mut ClientHello<'_>) -> Result + + Send + + Sync + + 'static, + { + let callback = + async_select_certificate_callback(callback, *SELECT_CERT_ACTION_FUTURE_INDEX, identity); + self.set_select_certificate_callback_with_action(callback); } /// Configures a custom private key method on the context. @@ -321,6 +362,44 @@ impl PrivateKeyMethod for AsyncPrivateKeyMethodBridge { } } +fn async_select_certificate_callback( + callback: F, + index: SelectCertFutureIndex, + into_action: fn(T) -> SelectCertAction, +) -> impl Fn(ClientHello<'_>) -> Result + Send + Sync + 'static +where + T: 'static, + F: Fn( + &mut ClientHello<'_>, + ) -> Result< + ExDataFuture, AsyncSelectCertError>>, + AsyncSelectCertError, + > + Send + + Sync + + 'static, +{ + move |mut client_hello| { + let fut_poll_result = with_ex_data_future( + &mut client_hello, + index, + ClientHello::ssl_mut, + &callback, + identity, + ); + + let fut_result = match fut_poll_result { + Poll::Ready(fut_result) => fut_result, + Poll::Pending => return Err(SelectCertError::RETRY), + }; + + let finish = fut_result.or(Err(SelectCertError::ERROR))?; + + finish(client_hello) + .map(into_action) + .or(Err(SelectCertError::ERROR)) + } +} + /// Creates and drives a private key method future. /// /// This is a convenience function for the three methods of impl `PrivateKeyMethod`` diff --git a/boring/src/ssl/callbacks.rs b/boring/src/ssl/callbacks.rs index 41c08c6b9..66304a385 100644 --- a/boring/src/ssl/callbacks.rs +++ b/boring/src/ssl/callbacks.rs @@ -2,9 +2,9 @@ use super::{ AlpnError, CertificateCompressor, ClientHello, GetSessionPendingError, PrivateKeyMethod, - PrivateKeyMethodError, SelectCertError, SniError, Ssl, SslAlert, SslContext, SslContextRef, - SslInfoCallbackAlert, SslInfoCallbackMode, SslInfoCallbackValue, SslRef, SslSession, - SslSessionRef, SslSignatureAlgorithm, SslVerifyError, SESSION_CTX_INDEX, + PrivateKeyMethodError, SelectCertAction, SelectCertError, SniError, Ssl, SslAlert, SslContext, + SslContextRef, SslInfoCallbackAlert, SslInfoCallbackMode, SslInfoCallbackValue, SslRef, + SslSession, SslSessionRef, SslSignatureAlgorithm, SslVerifyError, SESSION_CTX_INDEX, }; use crate::error::ErrorStack; use crate::ffi; @@ -41,7 +41,7 @@ where // SAFETY: The callback won't outlive the context it's associated with // because there is no `X509StoreContextRef::ssl_mut(&mut self)` method. - let verify = unsafe { &*std::ptr::from_ref::(verify) }; + let verify = unsafe { &*ptr::from_ref::(verify) }; c_int::from(verify(preverify_ok != 0, ctx)) } @@ -90,7 +90,7 @@ where // SAFETY: The callback won't outlive the context it's associated with // because there is no way to get a mutable reference to the `SslContext`, // so the callback can't replace itself. - let verify = unsafe { &*std::ptr::from_ref::(verify) }; + let verify = unsafe { &*ptr::from_ref::(verify) }; c_int::from(verify(ctx)) } @@ -371,10 +371,11 @@ pub(super) unsafe extern "C" fn raw_select_cert( client_hello: *const ffi::SSL_CLIENT_HELLO, ) -> ffi::ssl_select_cert_result_t where - F: Fn(ClientHello<'_>) -> Result<(), SelectCertError> + Sync + Send + 'static, + F: Fn(ClientHello<'_>) -> Result + Sync + Send + 'static, { // SAFETY: boring provides valid inputs. let client_hello = ClientHello(unsafe { &*client_hello }); + let ech_accepted = client_hello.ssl().ech_accepted(); let ssl_context = client_hello.ssl().ssl_context().to_owned(); let callback = ssl_context @@ -382,7 +383,11 @@ where .expect("BUG: select cert callback missing"); match callback(client_hello) { - Ok(()) => ffi::ssl_select_cert_result_t::ssl_select_cert_success, + Ok(SelectCertAction::Success) => ffi::ssl_select_cert_result_t::ssl_select_cert_success, + Ok(SelectCertAction::DisableEch) if ech_accepted => { + ffi::ssl_select_cert_result_t::ssl_select_cert_disable_ech + } + Ok(SelectCertAction::DisableEch) => ffi::ssl_select_cert_result_t::ssl_select_cert_error, Err(e) => e.0, } } @@ -442,7 +447,7 @@ where // SAFETY: We can make `callback` outlive `ssl` because it is a callback // stored in the session context set in `Ssl::new` so it is always // guaranteed to outlive the lifetime of this function's scope. - let callback = unsafe { &*std::ptr::from_ref::(callback) }; + let callback = unsafe { &*ptr::from_ref::(callback) }; callback(ssl, session); @@ -495,7 +500,7 @@ where // SAFETY: We can make `callback` outlive `ssl` because it is a callback // stored in the session context set in `Ssl::new` so it is always // guaranteed to outlive the lifetime of this function's scope. - let callback = unsafe { &*std::ptr::from_ref::(callback) }; + let callback = unsafe { &*ptr::from_ref::(callback) }; match callback(ssl, data) { Ok(Some(session)) => { @@ -666,7 +671,7 @@ where .ex_data(SslContext::cached_ex_index::()) .expect("BUG: certificate compression missed"); - let input_slice = unsafe { std::slice::from_raw_parts(input, input_len) }; + let input_slice = unsafe { slice::from_raw_parts(input, input_len) }; let mut writer = CryptoByteBuilder::from_ptr(out); if compressor.compress(input_slice, &mut writer).is_err() { return 0; @@ -701,7 +706,7 @@ where return 0; }; - let input_slice = unsafe { std::slice::from_raw_parts(input, input_len) }; + let input_slice = unsafe { slice::from_raw_parts(input, input_len) }; if compressor .decompress(input_slice, decompression_buffer.as_writer()) @@ -751,11 +756,11 @@ struct CryptoBufferBuilder<'a> { impl<'a> CryptoBufferBuilder<'a> { fn with_capacity(capacity: usize) -> Result, ErrorStack> { - let mut data: *mut u8 = std::ptr::null_mut(); + let mut data: *mut u8 = ptr::null_mut(); let buffer = unsafe { crate::cvt_p(ffi::CRYPTO_BUFFER_alloc(&mut data, capacity))? }; Ok(CryptoBufferBuilder { buffer, - cursor: std::io::Cursor::new(unsafe { std::slice::from_raw_parts_mut(data, capacity) }), + cursor: std::io::Cursor::new(unsafe { slice::from_raw_parts_mut(data, capacity) }), }) } diff --git a/boring/src/ssl/credential.rs b/boring/src/ssl/credential.rs index 12e821a96..dc71ce46d 100644 --- a/boring/src/ssl/credential.rs +++ b/boring/src/ssl/credential.rs @@ -97,7 +97,7 @@ impl SslCredentialRef { if data.is_null() { None } else { - Some(&mut *(data as *mut T)) + Some(&mut *data.cast::()) } } @@ -114,7 +114,7 @@ impl SslCredentialRef { } unsafe { - let data = Box::into_raw(Box::new(data)) as *mut c_void; + let data = Box::into_raw(Box::new(data)).cast::(); ffi::SSL_CREDENTIAL_set_ex_data(self.as_ptr(), index.as_raw(), data); } diff --git a/boring/src/ssl/mod.rs b/boring/src/ssl/mod.rs index 4e3bef4df..62eee9f90 100644 --- a/boring/src/ssl/mod.rs +++ b/boring/src/ssl/mod.rs @@ -104,7 +104,8 @@ use crate::{ffi, free_data_box}; pub use self::async_callbacks::{ AsyncPrivateKeyMethod, AsyncPrivateKeyMethodError, AsyncSelectCertError, BoxCustomVerifyFinish, BoxCustomVerifyFuture, BoxGetSessionFinish, BoxGetSessionFuture, BoxPrivateKeyMethodFinish, - BoxPrivateKeyMethodFuture, BoxSelectCertFinish, BoxSelectCertFuture, ExDataFuture, + BoxPrivateKeyMethodFuture, BoxSelectCertActionFinish, BoxSelectCertActionFuture, + BoxSelectCertFinish, BoxSelectCertFuture, ExDataFuture, }; pub use self::connector::{ ConnectConfiguration, SslAcceptor, SslAcceptorBuilder, SslConnector, SslConnectorBuilder, @@ -332,6 +333,18 @@ impl SslMethod { pub fn as_ptr(&self) -> *const ffi::SSL_METHOD { self.ptr } + + #[doc(hidden)] + #[deprecated(note = "renamed to `tls()`")] + pub fn tls_server() -> Self { + Self::tls() + } + + #[doc(hidden)] + #[deprecated(note = "renamed to `tls()`")] + pub fn tls_client() -> Self { + Self::tls() + } } unsafe impl Sync for SslMethod {} @@ -565,6 +578,22 @@ impl SelectCertError { pub const RETRY: Self = Self(ffi::ssl_select_cert_result_t::ssl_select_cert_retry); } +/// An action returned from a certificate selection callback. +#[non_exhaustive] +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum SelectCertAction { + /// Complete certificate selection normally. + Success, + /// Discard ClientHelloInner and continue with ClientHelloOuter. + /// + /// BoringSSL calls the callback again with ClientHelloOuter and continues the handshake + /// without retry configs. This action is only valid when [`SslRef::ech_accepted`] is true; + /// otherwise the handshake fails. + /// Changes made to the connection while processing ClientHelloInner carry over to the outer + /// ClientHello. + DisableEch, +} + /// Extension types, to be used with `ClientHello::get_extension`. /// /// **WARNING**: The current implementation of `From` is unsound, as it's possible to create an @@ -1689,10 +1718,39 @@ impl SslContextBuilder { /// Sets a callback that is called before most ClientHello processing and before the decision whether /// to resume a session is made. The callback may inspect the ClientHello and configure the /// connection. + /// + /// A context has a single certificate selection callback. Calling this method replaces the + /// callback set by any of [`SslContextBuilder::set_select_certificate_callback`], + /// [`SslContextBuilder::set_select_certificate_callback_with_action`], + /// [`SslContextBuilder::set_async_select_certificate_callback`], or + /// [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. #[corresponds(SSL_CTX_set_select_certificate_cb)] pub fn set_select_certificate_callback(&mut self, callback: F) where F: Fn(ClientHello<'_>) -> Result<(), SelectCertError> + Sync + Send + 'static, + { + self.set_select_certificate_callback_with_action(move |client_hello| { + callback(client_hello).map(|()| SelectCertAction::Success) + }); + } + + /// Sets an action-aware callback that is called before most ClientHello processing and before + /// the decision whether to resume a session is made. The callback may inspect the ClientHello + /// and configure the connection. + /// + /// [`SelectCertAction::DisableEch`] causes BoringSSL to discard an inner ClientHello, call + /// this callback again with the outer ClientHello, and continue without retry configs. + /// It is only valid when ECH has been accepted; returning it otherwise fails the handshake. + /// + /// A context has a single certificate selection callback. Calling this method replaces the + /// callback set by any of [`SslContextBuilder::set_select_certificate_callback`], + /// [`SslContextBuilder::set_select_certificate_callback_with_action`], + /// [`SslContextBuilder::set_async_select_certificate_callback`], or + /// [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. + #[corresponds(SSL_CTX_set_select_certificate_cb)] + pub fn set_select_certificate_callback_with_action(&mut self, callback: F) + where + F: Fn(ClientHello<'_>) -> Result + Sync + Send + 'static, { unsafe { self.replace_ex_data(SslContext::cached_ex_index::(), callback); @@ -2126,7 +2184,7 @@ impl SslContextBuilder { unsafe { cvt_0i(ffi::SSL_CTX_set1_accepted_peer_cert_types( self.as_ptr(), - types.as_ptr() as *const u8, + types.as_ptr().cast::(), types.len(), )) .map(|_| ()) @@ -2434,7 +2492,7 @@ impl SslContextRef { } Some(slice::from_raw_parts( - types as *const CertificateType, + types.cast::(), types_len, )) } @@ -3024,6 +3082,7 @@ impl SslRef { } /// Returns whether the TLS 1.3 HelloRetryRequest was used + #[must_use] pub fn used_hello_retry_request(&self) -> bool { unsafe { ffi::SSL_used_hello_retry_request(self.as_ptr()) == 1 } } @@ -3956,6 +4015,7 @@ impl SslRef { /// Returns the public key sent by the other peer, `None` if there is no ongoing handshake. #[corresponds(SSL_get0_peer_pubkey)] #[cfg(feature = "rpk")] + #[must_use] pub fn peer_pubkey(&self) -> Option<&PKeyRef> { unsafe { let pubkey = ffi::SSL_get0_peer_pubkey(self.as_ptr()); @@ -3964,7 +4024,7 @@ impl SslRef { return None; } - Some(PKeyRef::from_ptr(pubkey as *mut _)) + Some(PKeyRef::from_ptr(pubkey.cast_mut())) } } @@ -3987,7 +4047,7 @@ impl SslRef { unsafe { cvt_0i(ffi::SSL_set1_accepted_peer_cert_types( self.as_ptr(), - types.as_ptr() as *const u8, + types.as_ptr().cast::(), types.len(), )) .map(|_| ()) @@ -4016,7 +4076,7 @@ impl SslRef { } Some(slice::from_raw_parts( - types as *const CertificateType, + types.cast::(), types_len, )) } diff --git a/boring/src/ssl/test/cert_verify.rs b/boring/src/ssl/test/cert_verify.rs index c1bc0922e..243397ba7 100644 --- a/boring/src/ssl/test/cert_verify.rs +++ b/boring/src/ssl/test/cert_verify.rs @@ -118,7 +118,7 @@ fn callback_receives_correct_chain() { assert!(x509.current_cert().is_some()); assert!(x509.verify_result().is_ok()); let chain = x509.chain().unwrap(); - assert!(chain.len() == 2); + assert_eq!(chain.len(), 2); let leaf_cert = chain.get(0).unwrap(); let leaf_digest = leaf_cert.digest(MessageDigest::sha1()).unwrap(); assert_eq!(hex::encode(leaf_digest), leaf_sha1); diff --git a/boring/src/ssl/test/ech.rs b/boring/src/ssl/test/ech.rs index db4d43149..3a4bba233 100644 --- a/boring/src/ssl/test/ech.rs +++ b/boring/src/ssl/test/ech.rs @@ -1,7 +1,13 @@ use crate::hpke::HpkeKey; use crate::ssl::ech::SslEchKeys; use crate::ssl::test::server::{ClientSslBuilder, Server}; -use crate::ssl::HandshakeError; +use crate::ssl::{ + BoxSelectCertActionFinish, ClientHello, HandshakeError, NameType, SelectCertAction, + SelectCertError, +}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::task::Waker; // For future reference, these configs are generated by building the bssl tool (the binary is built // alongside boringssl) and running the following command: @@ -43,6 +49,137 @@ fn ech() { assert!(ssl_stream.ssl().ech_accepted()); } +#[test] +fn ech_disable_from_select_certificate_callback() { + let calls = Arc::new(AtomicUsize::new(0)); + let observations = Arc::new(Mutex::new(Vec::new())); + let server = { + let key = HpkeKey::dhkem_p256_sha256(ECH_KEY).unwrap(); + let mut ech_keys_builder = SslEchKeys::builder().unwrap(); + ech_keys_builder.add_key(true, ECH_CONFIG, key).unwrap(); + let ech_keys = ech_keys_builder.build(); + + let mut builder = Server::builder(); + builder.ctx().set_ech_keys(&ech_keys).unwrap(); + let calls = calls.clone(); + let observations = observations.clone(); + builder + .ctx() + .set_select_certificate_callback_with_action(move |client_hello| { + calls.fetch_add(1, Ordering::Relaxed); + observations.lock().unwrap().push(( + client_hello.ssl().ech_accepted(), + client_hello + .ssl() + .servername(NameType::HOST_NAME) + .map(str::to_owned), + )); + if client_hello.ssl().ech_accepted() { + Ok(SelectCertAction::DisableEch) + } else { + Ok(SelectCertAction::Success) + } + }); + + builder.build() + }; + + let mut client = server.client_with_root_ca().build().builder(); + client.ssl().set_ech_config_list(ECH_CONFIG_LIST).unwrap(); + client.ssl().set_hostname("foobar.com").unwrap(); + let HandshakeError::Failure(failed_ssl_stream) = client.connect_err() else { + panic!("wrong HandshakeError failure variant!"); + }; + + assert!(!failed_ssl_stream.ssl().ech_accepted()); + assert!(failed_ssl_stream.ssl().get_ech_retry_configs().is_none()); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!( + *observations.lock().unwrap(), + vec![ + (true, Some("foobar.com".to_owned())), + (false, Some("ech.com".to_owned())), + ] + ); +} + +#[test] +fn ech_disable_repeatedly_fails_after_outer_client_hello() { + let calls = Arc::new(AtomicUsize::new(0)); + let server = { + let key = HpkeKey::dhkem_p256_sha256(ECH_KEY).unwrap(); + let mut ech_keys_builder = SslEchKeys::builder().unwrap(); + ech_keys_builder.add_key(true, ECH_CONFIG, key).unwrap(); + let ech_keys = ech_keys_builder.build(); + + let mut builder = Server::builder(); + builder.should_error(); + builder.ctx().set_ech_keys(&ech_keys).unwrap(); + let calls = calls.clone(); + builder + .ctx() + .set_select_certificate_callback_with_action(move |_client_hello| { + if calls.fetch_add(1, Ordering::Relaxed) < 2 { + Ok(SelectCertAction::DisableEch) + } else { + Err(SelectCertError::ERROR) + } + }); + + builder.build() + }; + + let mut client = server.client_with_root_ca().build().builder(); + client.ssl().set_ech_config_list(ECH_CONFIG_LIST).unwrap(); + client.ssl().set_hostname("foobar.com").unwrap(); + client.connect_err(); + + assert_eq!(calls.load(Ordering::Relaxed), 2); +} + +#[test] +fn ech_disable_from_async_select_certificate_callback() { + let calls = Arc::new(AtomicUsize::new(0)); + let server = { + let key = HpkeKey::dhkem_p256_sha256(ECH_KEY).unwrap(); + let mut ech_keys_builder = SslEchKeys::builder().unwrap(); + ech_keys_builder.add_key(true, ECH_CONFIG, key).unwrap(); + let ech_keys = ech_keys_builder.build(); + + let mut builder = Server::builder(); + builder.ctx().set_ech_keys(&ech_keys).unwrap(); + let calls = calls.clone(); + builder + .ctx() + .set_async_select_certificate_callback_with_action(move |_| { + let calls = calls.clone(); + Ok(Box::pin(async move { + Ok(Box::new(move |_client_hello: ClientHello<'_>| { + if calls.fetch_add(1, Ordering::Relaxed) == 0 { + Ok(SelectCertAction::DisableEch) + } else { + Ok(SelectCertAction::Success) + } + }) as BoxSelectCertActionFinish) + })) + }); + builder.ssl_cb(|ssl| ssl.set_task_waker(Some(Waker::noop().clone()))); + + builder.build() + }; + + let mut client = server.client_with_root_ca().build().builder(); + client.ssl().set_ech_config_list(ECH_CONFIG_LIST).unwrap(); + client.ssl().set_hostname("foobar.com").unwrap(); + let HandshakeError::Failure(failed_ssl_stream) = client.connect_err() else { + panic!("wrong HandshakeError failure variant!"); + }; + + assert!(!failed_ssl_stream.ssl().ech_accepted()); + assert!(failed_ssl_stream.ssl().get_ech_retry_configs().is_none()); + assert_eq!(calls.load(Ordering::Relaxed), 2); +} + #[test] fn ech_rejection() { // Server is initialized using `ECH_CONFIG_2`, so using `ECH_CONFIG_LIST` instead of diff --git a/boring/src/ssl/test/mod.rs b/boring/src/ssl/test/mod.rs index f0af8a688..3e5fed9e4 100644 --- a/boring/src/ssl/test/mod.rs +++ b/boring/src/ssl/test/mod.rs @@ -4,7 +4,8 @@ use std::io::prelude::*; use std::mem; use std::net::{TcpListener, TcpStream}; use std::path::Path; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use crate::error::ErrorStack; @@ -353,6 +354,35 @@ fn test_select_cert_ok() { client.connect(); } +#[test] +fn test_select_cert_last_setter_wins() { + let old_calls = Arc::new(AtomicUsize::new(0)); + let action_calls = Arc::new(AtomicUsize::new(0)); + let mut server = Server::builder(); + + let old_calls_clone = old_calls.clone(); + server + .ctx() + .set_select_certificate_callback(move |_client_hello| { + old_calls_clone.fetch_add(1, Ordering::Relaxed); + Ok(()) + }); + + let action_calls_clone = action_calls.clone(); + server + .ctx() + .set_select_certificate_callback_with_action(move |_client_hello| { + action_calls_clone.fetch_add(1, Ordering::Relaxed); + Ok(ssl::SelectCertAction::Success) + }); + + let server = server.build(); + server.client().connect(); + + assert_eq!(old_calls.load(Ordering::Relaxed), 0); + assert_eq!(action_calls.load(Ordering::Relaxed), 1); +} + #[test] fn test_mutable_store() { #![allow(deprecated)] @@ -412,6 +442,28 @@ fn test_select_cert_error() { client.connect_err(); } +#[test] +fn test_select_cert_disable_ech_without_ech_fails() { + let calls = Arc::new(AtomicUsize::new(0)); + let mut server = Server::builder(); + server.should_error(); + let callback_calls = calls.clone(); + server + .ctx() + .set_select_certificate_callback_with_action(move |_client_hello| { + if callback_calls.fetch_add(1, Ordering::Relaxed) == 0 { + Ok(ssl::SelectCertAction::DisableEch) + } else { + Err(ssl::SelectCertError::ERROR) + } + }); + let server = server.build(); + + let client = server.client(); + client.connect_err(); + assert_eq!(calls.load(Ordering::Relaxed), 1); +} + #[test] fn test_select_cert_unknown_extension() { let mut server = Server::builder(); @@ -622,7 +674,7 @@ fn flush_panic() { fn refcount_ssl_context() { let mut ssl = { let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ssl::Ssl::new(&ctx.build()).unwrap() + Ssl::new(&ctx.build()).unwrap() }; { @@ -1011,7 +1063,7 @@ fn psk_ciphers() { let mut server = Server::builder(); server.ctx().set_cipher_list(CIPHER).unwrap(); server.ctx().set_psk_server_callback(|_, identity, psk| { - assert!(identity.unwrap_or(&[]) == CLIENT_IDENT); + assert_eq!(identity.unwrap_or(&[]), CLIENT_IDENT); psk[..PSK.len()].copy_from_slice(PSK); SERVER_CALLED.store(true, Ordering::SeqCst); Ok(PSK.len()) @@ -1021,7 +1073,7 @@ fn psk_ciphers() { let mut client = server.client(); // This test relies on TLS 1.2 suites - client.ctx().set_options(super::SslOptions::NO_TLSV1_3); + client.ctx().set_options(SslOptions::NO_TLSV1_3); client.ctx().set_cipher_list(CIPHER).unwrap(); client .ctx() @@ -1338,7 +1390,7 @@ fn peer_signature_algorithm_mtls_server_sees_client() { // Observe from a server-side HANDSHAKE_DONE info callback so the capture // happens synchronously during the server's accept, before the client's // connect() returns. - let captured = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let captured = std::sync::Arc::new(AtomicBool::new(false)); let mut server_builder = Server::builder(); { @@ -1356,7 +1408,7 @@ fn peer_signature_algorithm_mtls_server_sees_client() { if mode == SslInfoCallbackMode::HANDSHAKE_DONE { if let Some(sa) = ssl.peer_signature_algorithm() { assert!(sa.name().is_some(), "client sig scheme should have a name"); - captured_cb.store(true, std::sync::atomic::Ordering::SeqCst); + captured_cb.store(true, Ordering::SeqCst); } } }); @@ -1375,7 +1427,7 @@ fn peer_signature_algorithm_mtls_server_sees_client() { let _ = client_builder.connect(); assert!( - captured.load(std::sync::atomic::Ordering::SeqCst), + captured.load(Ordering::SeqCst), "server should observe client signature scheme during mTLS", ); } @@ -1384,7 +1436,7 @@ fn peer_signature_algorithm_mtls_server_sees_client() { fn signature_algorithm_used_server_default() { // BoringSSL only retains signature_algorithm_used during the handshake, so we // capture it from a HANDSHAKE_DONE info callback. - let captured = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let captured = std::sync::Arc::new(AtomicBool::new(false)); let mut server_builder = Server::builder(); { @@ -1395,7 +1447,7 @@ fn signature_algorithm_used_server_default() { if mode == SslInfoCallbackMode::HANDSHAKE_DONE { if let Some(sa) = ssl.signature_algorithm_used() { assert!(sa.name().is_some()); - captured_cb.store(true, std::sync::atomic::Ordering::SeqCst); + captured_cb.store(true, Ordering::SeqCst); } } }); @@ -1404,7 +1456,7 @@ fn signature_algorithm_used_server_default() { let _ = server.client_with_root_ca().connect(); assert!( - captured.load(std::sync::atomic::Ordering::SeqCst), + captured.load(Ordering::SeqCst), "server should observe signature_algorithm_used at HANDSHAKE_DONE", ); } @@ -1437,7 +1489,7 @@ fn signature_algorithm_used_mtls_client() { } let server = server_builder.build(); - let captured = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let captured = std::sync::Arc::new(AtomicBool::new(false)); let captured_cb = std::sync::Arc::clone(&captured); let mut client_builder = server.client_with_root_ca(); @@ -1455,14 +1507,14 @@ fn signature_algorithm_used_mtls_client() { if mode == SslInfoCallbackMode::HANDSHAKE_DONE { if let Some(sa) = ssl.signature_algorithm_used() { assert!(sa.name().is_some()); - captured_cb.store(true, std::sync::atomic::Ordering::SeqCst); + captured_cb.store(true, Ordering::SeqCst); } } }); let _ = client_builder.connect(); assert!( - captured.load(std::sync::atomic::Ordering::SeqCst), + captured.load(Ordering::SeqCst), "client should observe signature_algorithm_used at HANDSHAKE_DONE in mTLS", ); } diff --git a/boring/src/symm.rs b/boring/src/symm.rs index 7067b86b5..c2e6132db 100644 --- a/boring/src/symm.rs +++ b/boring/src/symm.rs @@ -304,6 +304,7 @@ impl Cipher { /// Returns the cipher's NID. #[corresponds(EVP_CIPHER_nid)] + #[must_use] pub fn nid(&self) -> Nid { ffi::init(); let nid = unsafe { ffi::EVP_CIPHER_nid(self.as_ptr()) }; @@ -774,13 +775,7 @@ mod tests { fn test_stream_cipher_output() { let key = [0u8; 16]; let iv = [0u8; 16]; - let mut c = super::Crypter::new( - super::Cipher::aes_128_ctr(), - super::Mode::Encrypt, - &key, - Some(&iv), - ) - .unwrap(); + let mut c = Crypter::new(Cipher::aes_128_ctr(), Mode::Encrypt, &key, Some(&iv)).unwrap(); assert_eq!(c.update(&[0u8; 15], &mut [0u8; 15]).unwrap(), 15); assert_eq!(c.update(&[0u8; 1], &mut [0u8; 1]).unwrap(), 1); @@ -804,29 +799,17 @@ mod tests { 0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, 0xeau8, 0xfcu8, 0x49u8, 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8, ]; - let mut c = super::Crypter::new( - super::Cipher::aes_256_ecb(), - super::Mode::Encrypt, - &k0, - None, - ) - .unwrap(); + let mut c = Crypter::new(Cipher::aes_256_ecb(), Mode::Encrypt, &k0, None).unwrap(); c.pad(false); - let mut r0 = vec![0; c0.len() + super::Cipher::aes_256_ecb().block_size()]; + let mut r0 = vec![0; c0.len() + Cipher::aes_256_ecb().block_size()]; let count = c.update(&p0, &mut r0).unwrap(); let rest = c.finalize(&mut r0[count..]).unwrap(); r0.truncate(count + rest); assert_eq!(hex::encode(&r0), hex::encode(c0)); - let mut c = super::Crypter::new( - super::Cipher::aes_256_ecb(), - super::Mode::Decrypt, - &k0, - None, - ) - .unwrap(); + let mut c = Crypter::new(Cipher::aes_256_ecb(), Mode::Decrypt, &k0, None).unwrap(); c.pad(false); - let mut p1 = vec![0; r0.len() + super::Cipher::aes_256_ecb().block_size()]; + let mut p1 = vec![0; r0.len() + Cipher::aes_256_ecb().block_size()]; let count = c.update(&r0, &mut p1).unwrap(); let rest = c.finalize(&mut p1[count..]).unwrap(); p1.truncate(count + rest); @@ -848,15 +831,9 @@ mod tests { 0x4a_u8, 0x2e_u8, 0xe5_u8, 0x6_u8, 0xbf_u8, 0xcf_u8, 0xf2_u8, 0xd7_u8, 0xea_u8, 0x2d_u8, 0xb1_u8, 0x85_u8, 0x6c_u8, 0x93_u8, 0x65_u8, 0x6f_u8, ]; - let mut cr = super::Crypter::new( - super::Cipher::aes_256_cbc(), - super::Mode::Decrypt, - &data, - Some(&iv), - ) - .unwrap(); + let mut cr = Crypter::new(Cipher::aes_256_cbc(), Mode::Decrypt, &data, Some(&iv)).unwrap(); cr.pad(false); - let mut unciphered_data = vec![0; data.len() + super::Cipher::aes_256_cbc().block_size()]; + let mut unciphered_data = vec![0; data.len() + Cipher::aes_256_cbc().block_size()]; let count = cr.update(&ciphered_data, &mut unciphered_data).unwrap(); let rest = cr.finalize(&mut unciphered_data[count..]).unwrap(); unciphered_data.truncate(count + rest); @@ -866,13 +843,13 @@ mod tests { assert_eq!(&unciphered_data, expected_unciphered_data); } - fn cipher_test(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) { + fn cipher_test(ciphertype: Cipher, pt: &str, ct: &str, key: &str, iv: &str) { let pt = Vec::from_hex(pt).unwrap(); let ct = Vec::from_hex(ct).unwrap(); let key = Vec::from_hex(key).unwrap(); let iv = Vec::from_hex(iv).unwrap(); - let computed = super::decrypt(ciphertype, &key, Some(&iv), &ct).unwrap(); + let computed = decrypt(ciphertype, &key, Some(&iv), &ct).unwrap(); let expected = pt; if computed != expected { @@ -896,7 +873,7 @@ mod tests { let key = "97CD440324DA5FD1F7955C1C13B6B466"; let iv = ""; - cipher_test(super::Cipher::rc4(), pt, ct, key, iv); + cipher_test(Cipher::rc4(), pt, ct, key, iv); } #[test] @@ -908,7 +885,7 @@ mod tests { let key = "2B7E151628AED2A6ABF7158809CF4F3C"; let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; - cipher_test(super::Cipher::aes_128_ctr(), pt, ct, key, iv); + cipher_test(Cipher::aes_128_ctr(), pt, ct, key, iv); } #[test] @@ -920,7 +897,7 @@ mod tests { let key = "2b7e151628aed2a6abf7158809cf4f3c"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Cipher::aes_128_ofb(), pt, ct, key, iv); + cipher_test(Cipher::aes_128_ofb(), pt, ct, key, iv); } #[test] @@ -932,7 +909,7 @@ mod tests { let key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; let iv = "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"; - cipher_test(super::Cipher::aes_192_ctr(), pt, ct, key, iv); + cipher_test(Cipher::aes_192_ctr(), pt, ct, key, iv); } #[test] @@ -944,7 +921,7 @@ mod tests { let key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Cipher::aes_192_ofb(), pt, ct, key, iv); + cipher_test(Cipher::aes_192_ofb(), pt, ct, key, iv); } #[test] @@ -956,7 +933,7 @@ mod tests { let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; let iv = "000102030405060708090a0b0c0d0e0f"; - cipher_test(super::Cipher::aes_256_ofb(), pt, ct, key, iv); + cipher_test(Cipher::aes_256_ofb(), pt, ct, key, iv); } #[test] @@ -966,7 +943,7 @@ mod tests { let key = "7cb66337f3d3c0fe"; let iv = "0001020304050607"; - cipher_test(super::Cipher::des_cbc(), pt, ct, key, iv); + cipher_test(Cipher::des_cbc(), pt, ct, key, iv); } #[test] @@ -976,7 +953,7 @@ mod tests { let key = "7cb66337f3d3c0fe"; let iv = "0001020304050607"; - cipher_test(super::Cipher::des_ecb(), pt, ct, key, iv); + cipher_test(Cipher::des_ecb(), pt, ct, key, iv); } #[test] @@ -986,7 +963,7 @@ mod tests { let key = "010203040506070801020304050607080102030405060708"; let iv = "5cc118306dc702e4"; - cipher_test(super::Cipher::des_ede3(), pt, ct, key, iv); + cipher_test(Cipher::des_ede3(), pt, ct, key, iv); } #[test] @@ -996,7 +973,7 @@ mod tests { let key = "7cb66337f3d3c0fe7cb66337f3d3c0fe7cb66337f3d3c0fe"; let iv = "0001020304050607"; - cipher_test(super::Cipher::des_ede3_cbc(), pt, ct, key, iv); + cipher_test(Cipher::des_ede3_cbc(), pt, ct, key, iv); } #[test] @@ -1065,7 +1042,7 @@ mod tests { Cipher::rc4(), ] { let name = cipher.nid().short_name().unwrap_or("unknown"); - assert_eq!(Cipher::from_nid(cipher.nid()), Some(cipher), "{}", name); + assert_eq!(Cipher::from_nid(cipher.nid()), Some(cipher), "{name}"); } assert_eq!(Cipher::from_nid(Cipher::des_ede3().nid()), None); @@ -1162,7 +1139,7 @@ mod tests { }, ] { let name = t.cipher.nid().short_name().unwrap_or("unknown"); - assert_eq!(t.cipher.nid().as_raw(), t.nid, "{}", name); + assert_eq!(t.cipher.nid().as_raw(), t.nid, "{name}"); } } } diff --git a/boring/src/x509/mod.rs b/boring/src/x509/mod.rs index 01e53f12d..984e03e4f 100644 --- a/boring/src/x509/mod.rs +++ b/boring/src/x509/mod.rs @@ -39,7 +39,7 @@ use crate::string::OpensslString; use crate::try_int; use crate::util::ForeignTypeRefExt; use crate::x509::crl::X509CRL; -use crate::x509::verify::{X509VerifyParam, X509VerifyParamRef}; +use crate::x509::verify::{X509CheckFlags, X509VerifyParam, X509VerifyParamRef}; use crate::{cvt, cvt_n, cvt_p}; use crate::{ffi, free_data_box}; @@ -760,13 +760,27 @@ impl X509Ref { } } + /// Checks whether the certificate matches the given hostname. + /// + /// This uses the default hostname matching behavior. Use + /// [`X509Ref::check_host_with_flags`] to customize it. pub fn check_host(&self, host: &str) -> Result { + self.check_host_with_flags(host, X509CheckFlags::empty()) + } + + /// Checks whether the certificate matches the given hostname using the supplied flags. + #[corresponds(X509_check_host)] + pub fn check_host_with_flags( + &self, + host: &str, + flags: X509CheckFlags, + ) -> Result { unsafe { cvt_n(ffi::X509_check_host( self.as_ptr(), host.as_ptr().cast(), host.len(), - 0, + flags.bits(), ptr::null_mut(), )) .map(|n| n == 1) diff --git a/boring/src/x509/tests/mod.rs b/boring/src/x509/tests/mod.rs index a144ad42c..312288a07 100644 --- a/boring/src/x509/tests/mod.rs +++ b/boring/src/x509/tests/mod.rs @@ -13,7 +13,7 @@ use crate::x509::extension::{ SubjectKeyIdentifier, }; use crate::x509::store::X509StoreBuilder; -use crate::x509::verify::X509VerifyFlags; +use crate::x509::verify::{X509CheckFlags, X509VerifyFlags}; use crate::x509::{X509Extension, X509Name, X509Req, X509StoreContext, X509VerifyError, X509}; const TEST_CERT_DIGEST: &str = "585e3a58acfd3b4e5e2825659407244ddd93539c"; @@ -24,6 +24,16 @@ fn pkey() -> PKey { PKey::from_rsa(rsa).unwrap() } +fn cert_with_dns_name(dns_name: &str) -> X509 { + let mut builder = X509::builder().unwrap(); + let subject_alternative_name = SubjectAlternativeName::new() + .dns(dns_name) + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(&subject_alternative_name).unwrap(); + builder.build() +} + fn stack_of(item: T) -> Stack where T: Stackable, @@ -190,6 +200,41 @@ fn test_subject_alt_name_iter() { assert!(subject_alt_names_iter.next().is_none()); } +#[test] +fn check_host_uses_default_flags() { + let cert = cert_with_dns_name("*.example.com"); + + assert!(cert.check_host("www.example.com").unwrap()); + assert_eq!( + cert.check_host("www.example.com").unwrap(), + cert.check_host_with_flags("www.example.com", X509CheckFlags::empty()) + .unwrap() + ); +} + +#[test] +fn check_host_with_standard_flags() { + let cert = cert_with_dns_name("*.example.com"); + + assert!(cert + .check_host_with_flags("www.example.com", X509CheckFlags::empty()) + .unwrap()); + assert!(!cert + .check_host_with_flags("www.example.com", X509CheckFlags::NO_WILDCARDS) + .unwrap()); +} + +#[cfg(feature = "underscore-wildcards")] +#[test] +fn check_host_with_underscore_wildcards() { + let cert = cert_with_dns_name("*.example.com"); + + assert!(!cert.check_host("_service.example.com").unwrap()); + assert!(cert + .check_host_with_flags("_service.example.com", X509CheckFlags::UNDERSCORE_WILDCARDS) + .unwrap()); +} + #[test] fn test_subject_key_id() { // nid_test_cert_pem has SKI, but no AKI diff --git a/boring/src/x509/tests/trusted_first.rs b/boring/src/x509/tests/trusted_first.rs index c5ecaabf0..cccb08ac8 100644 --- a/boring/src/x509/tests/trusted_first.rs +++ b/boring/src/x509/tests/trusted_first.rs @@ -2,69 +2,35 @@ use crate::stack::Stack; use crate::x509::store::X509StoreBuilder; -use crate::x509::verify::{X509VerifyFlags, X509VerifyParamRef}; -use crate::x509::{X509Ref, X509StoreContext, X509VerifyError, X509VerifyResult, X509}; +use crate::x509::verify::X509VerifyParamRef; +use crate::x509::{X509Ref, X509StoreContext, X509VerifyResult, X509}; #[test] fn test_verify_cert() { - let root2 = X509::from_pem(include_bytes!("../../../test/root-ca-2.pem")).unwrap(); + let root2_expired = X509::from_pem(include_bytes!("../../../test/root-ca-2.pem")).unwrap(); let root1 = X509::from_pem(include_bytes!("../../../test/root-ca.pem")).unwrap(); let root1_cross = X509::from_pem(include_bytes!("../../../test/root-ca-cross.pem")).unwrap(); let intermediate = X509::from_pem(include_bytes!("../../../test/intermediate-ca.pem")).unwrap(); let leaf = X509::from_pem(include_bytes!("../../../test/cert-with-intermediate.pem")).unwrap(); + // Two paths: + // Leaf -- Intermediate -- Root1 + // \ + // Root1_cross -- Root2 (expired) + // + // In the past, X509_V_FLAG_TRUSTED_FIRST had to be set to avoid the second invalid path. This + // is now the default, and that flag no longer has any effect. assert_eq!(Ok(()), verify(&leaf, &[&root1], &[&intermediate], |_| {})); - #[cfg(not(feature = "legacy-compat-deprecated"))] assert_eq!( Ok(()), verify( &leaf, - &[&root1, &root2], + &[&root1, &root2_expired], &[&intermediate, &root1_cross], |_| {} ) ); - - #[cfg(feature = "legacy-compat-deprecated")] - assert_eq!( - Err(X509VerifyError::CERT_HAS_EXPIRED), - verify( - &leaf, - &[&root1, &root2], - &[&intermediate, &root1_cross], - |_| {} - ) - ); - - assert_eq!( - Ok(()), - verify( - &leaf, - &[&root1, &root2], - &[&intermediate, &root1_cross], - |param| param.try_set_flags(X509VerifyFlags::TRUSTED_FIRST).unwrap(), - ) - ); - - assert_eq!( - Err(X509VerifyError::CERT_HAS_EXPIRED), - verify( - &leaf, - &[&root1, &root2], - &[&intermediate, &root1_cross], - |param| param.clear_flags(X509VerifyFlags::TRUSTED_FIRST), - ) - ); - - assert_eq!( - Ok(()), - verify(&leaf, &[&root1], &[&intermediate, &root1_cross], |param| { - param - .try_clear_flags(X509VerifyFlags::TRUSTED_FIRST) - .unwrap(); - }) - ); } fn verify( diff --git a/boring/tests/hkdf.rs b/boring/tests/hkdf.rs new file mode 100644 index 000000000..db7659bb7 --- /dev/null +++ b/boring/tests/hkdf.rs @@ -0,0 +1,303 @@ +use boring::hash::{hash, MessageDigest}; +use boring::hkdf::HkdfSuite; + +const RFC5869_CASE_2_INFO: &str = concat!( + "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecf", + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeef", + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", +); +const RFC5869_CASE_2_PRK: &str = "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244"; +const RFC5869_CASE_2_OKM: &str = concat!( + "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c", + "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71", + "cc30c58179ec3e87c14c01d5c1f3434f1d87", +); + +#[derive(Copy, Clone)] +struct TestVector { + ikm: &'static str, + salt: &'static str, + info: &'static str, + prk: &'static str, + okm: &'static str, +} + +fn decode(value: &str) -> Vec { + hex::decode(value).unwrap() +} + +fn assert_vectors(digest: MessageDigest, vectors: &[TestVector]) { + let suite = HkdfSuite::new(digest); + + for vector in vectors { + let ikm = decode(vector.ikm); + let salt = decode(vector.salt); + let info = decode(vector.info); + let expected_prk = decode(vector.prk); + let expected_okm = decode(vector.okm); + + let prk = suite.extract(&salt, &ikm).unwrap(); + assert_eq!(prk.as_ref(), expected_prk.as_slice()); + assert_eq!(prk.len(), suite.prk_size()); + + let mut okm = vec![0u8; expected_okm.len()]; + suite.expand(prk.as_ref(), &info, &mut okm).unwrap(); + assert_eq!(okm, expected_okm); + } +} + +#[test] +fn rfc5869_sha256_vectors() { + // Test vectors from RFC 5869, sections A.1 through A.3. + assert_vectors( + MessageDigest::sha256(), + &[ + TestVector { + ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + salt: "000102030405060708090a0b0c", + info: "f0f1f2f3f4f5f6f7f8f9", + prk: "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", + okm: "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", + }, + TestVector { + ikm: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", + salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + info: RFC5869_CASE_2_INFO, + prk: RFC5869_CASE_2_PRK, + okm: RFC5869_CASE_2_OKM, + }, + TestVector { + ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + salt: "", + info: "", + prk: "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04", + okm: "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8", + }, + ], + ); +} + +#[test] +fn rfc5869_sha1_vectors() { + // Test vectors from RFC 5869, sections A.4 through A.7. + assert_vectors( + MessageDigest::sha1(), + &[ + TestVector { + ikm: "0b0b0b0b0b0b0b0b0b0b0b", + salt: "000102030405060708090a0b0c", + info: "f0f1f2f3f4f5f6f7f8f9", + prk: "9b6c18c432a7bf8f0e71c8eb88f4b30baa2ba243", + okm: "085a01ea1b10f36933068b56efa5ad81a4f14b822f5b091568a9cdd4f155fda2c22e422478d305f3f896", + }, + TestVector { + ikm: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", + salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + info: RFC5869_CASE_2_INFO, + prk: "8adae09a2a307059478d309b26c4115a224cfaf6", + okm: "0bd770a74d1160f7c9f12cd5912a06ebff6adcae899d92191fe4305673ba2ffe8fa3f1a4e5ad79f3f334b3b202b2173c486ea37ce3d397ed034c7f9dfeb15c5e927336d0441f4c4300e2cff0d0900b52d3b4", + }, + TestVector { + ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + salt: "", + info: "", + prk: "da8c8a73c7fa77288ec6f5e7c297786aa0d32d01", + okm: "0ac1af7002b3d761d1e55298da9d0506b9ae52057220a306e07b6b87e8df21d0ea00033de03984d34918", + }, + TestVector { + ikm: "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", + salt: "", + info: "", + prk: "2adccada18779e7c2077ad2eb19d3f3e731385dd", + okm: "2c91117204d745f3500d636a62f64f0ab3bae548aa53d423b0d1f27ebba6f5e5673a081d70cce7acfc48", + }, + ], + ); +} + +#[test] +fn independent_sha384_and_sha512_vectors() { + // These vectors were generated independently with Python 3's standard + // library `hmac` and `hashlib` modules. + assert_vectors( + MessageDigest::sha384(), + &[TestVector { + ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", + salt: "000102030405060708090a0b0c", + info: "f0f1f2f3f4f5f6f7f8f9", + prk: "704b39990779ce1dc548052c7dc39f303570dd13fb39f7acc564680bef80e8dec70ee9a7e1f3e293ef68eceb072a5ade", + okm: "9b5097a86038b805309076a44b3a9f38063e25b516dcbf369f394cfab43685f748b6457763e4f0204fc5d95d1da3e62587b22eb8943d0fab6bb631a2fe9df1a68c6ce5d56116a52005b3f122b88b39b7251fcd6c44d3ef25f20ed96802bf1b2c1d98bf74", + }], + ); + assert_vectors( + MessageDigest::sha512(), + &[TestVector { + ikm: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", + salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + info: RFC5869_CASE_2_INFO, + prk: "35672542907d4e142c00e84499e74e1de08be86535f924e022804ad775dde27ec86cd1e5b7d178c74489bdbeb30712beb82d4f97416c5a94ea81ebdf3e629e4a", + okm: "ce6c97192805b346e6161e821ed165673b84f400a2b514b2fe23d84cd189ddf1b695b48cbd1c8388441137b3ce28f16aa64ba33ba466b24df6cfcb021ecff235f6a2056ce3af1de44d572097a8505d9e7a9354e5796284151c2dd39c39b3cd3d8e50fcc383ebdec37476e03b721ef5efef873c281f018b8ca42e1245b2271f871ba6", + }], + ); +} + +#[test] +fn expand_matches_rfc5869_case_2_at_block_boundaries() { + let suite = HkdfSuite::new(MessageDigest::sha256()); + let prk = decode(RFC5869_CASE_2_PRK); + let info = decode(RFC5869_CASE_2_INFO); + let expected = decode(RFC5869_CASE_2_OKM); + + for length in [1, 31, 32, 33, 63, 64, 65] { + let mut okm = vec![0; length]; + suite.expand(&prk, &info, &mut okm).unwrap(); + assert_eq!(okm, expected[..length]); + } +} + +#[test] +fn empty_inputs_and_zero_output() { + let suite = HkdfSuite::new(MessageDigest::sha256()); + let prk = suite.extract(&[], &[]).unwrap(); + assert_eq!( + prk.as_ref(), + decode("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad").as_slice() + ); + + let mut okm = []; + suite.expand(prk.as_ref(), &[], &mut okm).unwrap(); +} + +#[test] +fn extract_accepts_empty_ikm_with_a_nonempty_salt() { + let suite = HkdfSuite::new(MessageDigest::sha256()); + let prk = suite.extract(b"salt", &[]).unwrap(); + assert_eq!( + prk.as_ref(), + decode("379d7f7966f400cb6e3c0b2cca4bf8a2db03b8c81fef8020015b5a3103c30460").as_slice() + ); +} + +#[test] +fn output_limit_is_enforced_for_each_digest() { + struct DigestCase { + digest: MessageDigest, + prk_size: usize, + prk: &'static str, + output_hash: &'static str, + output_tail: &'static str, + } + + // The output hashes and tails were generated independently with Python + // 3's standard library `hmac` and `hashlib` modules. + let cases = [ + DigestCase { + digest: MessageDigest::sha1(), + prk_size: 20, + prk: "fbdb1d1b18aa6c08324b7d64b71fb76370690e1d", + output_hash: "1a587819ead9e13e0e04def8721c723beb780740", + output_tail: "9a1fd0b1687548543fa811c5117cb8bc784634dc", + }, + DigestCase { + digest: MessageDigest::sha256(), + prk_size: 32, + prk: "b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", + output_hash: "8f06b0d3c135da7d77534048a98ce5d5ed37c379996be1c43f0b8f264ffedde7", + output_tail: "d088fc3911508c67b985be209d5e5720b9e9d4d98c145952a1aa4362caf53fce", + }, + DigestCase { + digest: MessageDigest::sha384(), + prk_size: 48, + prk: "6c1f2ee938fad2e24bd91298474382ca218c75db3d83e114b3d4367776d14d3551289e75e8209cd4b792302840234adc", + output_hash: "bdbb33e0026747dd19126067deb66fd6fa1d9e60e01d72645e935c4b571f98ad1156d48f54e140cedf64b791051467ff", + output_tail: "d298f9f97fe2ca14527503d2c47e2da0c4940702ebd12ad0dc3fbb65e44edc3e9fe8cb67fcc7da85fe9453015a3480ef", + }, + DigestCase { + digest: MessageDigest::sha512(), + prk_size: 64, + prk: "b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47", + output_hash: "3fa5497792fb0deed77e259b3fcf5a3b1fe36a1e07de8c3ffa4499224027f798a62f3a066f50be7f41a6d4a292ad1b82d2d21dbae703834121ec6bf1bc0d076b", + output_tail: "fefd61f23f2b4dc19789052152b2aebb1b4e9068a255b0b4a684efd0e99784a41242a6dfc85064bd8b13fd8be604ee34e83073619c21f3a00b5103b85f72097a", + }, + ]; + + for case in cases { + let suite = HkdfSuite::new(case.digest); + assert_eq!(suite.prk_size(), case.prk_size); + + let prk = suite.extract(&[], &[]).unwrap(); + assert_eq!(prk.as_ref(), decode(case.prk).as_slice()); + + let mut max = vec![0xa5; 255 * case.prk_size]; + suite.expand(prk.as_ref(), &[], &mut max).unwrap(); + let digest = hash(case.digest, &max).unwrap(); + assert_eq!(digest.as_ref(), decode(case.output_hash).as_slice()); + assert_eq!( + &max[max.len() - case.prk_size..], + decode(case.output_tail).as_slice() + ); + + let mut too_long = vec![0xa5; max.len() + 1]; + let error = suite.expand(prk.as_ref(), &[], &mut too_long).unwrap_err(); + assert!(!error.errors().is_empty()); + assert_eq!(error.errors()[0].reason(), Some("OUTPUT_TOO_LARGE")); + assert!(too_long.iter().all(|&byte| byte == 0xa5)); + } +} + +#[test] +fn expand_accepts_a_prk_longer_than_hash_len() { + struct DigestCase { + digest: MessageDigest, + expected: &'static str, + } + + // Expected OKM was generated independently with Python 3's standard + // library `hmac` module using a PRK of HashLen + 1 bytes. + let cases = [ + DigestCase { + digest: MessageDigest::sha1(), + expected: "9324f49000a5f860846f69d962a74fa296b3f66292a36c84132251", + }, + DigestCase { + digest: MessageDigest::sha256(), + expected: "54884956024c4667f33553b446e944d602ae41b99d61abe34da1cf2c59ee13fc3d96f8b767a227", + }, + DigestCase { + digest: MessageDigest::sha384(), + expected: "118b9db28f338f697460cb1ffe872d29bcdf8a0b3bced52053c87242f0b3efca84f748e5b0011156cb380195c412049982b0719e766594", + }, + DigestCase { + digest: MessageDigest::sha512(), + expected: "53272e5bd3bc509ffe6e1039c39390051ad5a133f01fe85b99a59e429310368721b17dc64ec7cf90b8d285cf62c1ee98e7d83d92009d8cf3e0d5c0ea75a5a9b9f08cec559d1819", + }, + ]; + + for case in cases { + let suite = HkdfSuite::new(case.digest); + let prk: Vec<_> = (0..=suite.prk_size() as u8).collect(); + let info = b"longer than HashLen PRK"; + let mut okm = vec![0; decode(case.expected).len()]; + suite.expand(&prk, info, &mut okm).unwrap(); + assert_eq!(okm, decode(case.expected)); + } +} + +#[test] +fn expand_rejects_a_prk_shorter_than_hash_len() { + for digest in [ + MessageDigest::sha1(), + MessageDigest::sha256(), + MessageDigest::sha384(), + MessageDigest::sha512(), + ] { + let suite = HkdfSuite::new(digest); + for prk_len in [0, suite.prk_size() - 1] { + let prk = vec![0; prk_len]; + let mut okm = [0xa5]; + let error = suite.expand(&prk, b"info", &mut okm).unwrap_err(); + assert!(!error.errors().is_empty()); + assert_eq!(okm, [0xa5]); + } + } +} diff --git a/tokio-boring/Cargo.toml b/tokio-boring/Cargo.toml index 1830cc175..b81f9e3ab 100644 --- a/tokio-boring/Cargo.toml +++ b/tokio-boring/Cargo.toml @@ -25,6 +25,10 @@ fips = ["boring/fips", "boring-sys/fips"] # Enables Raw public key API (https://datatracker.ietf.org/doc/html/rfc7250) rpk = ["boring/rpk"] +# **DO NOT USE** This will be removed without warning in future releases. +# Alias for 'fips', only for backwards compatibility. +fips-precompiled = ["fips"] + [dependencies] boring = { workspace = true, default-features = false } boring-sys = { workspace = true, default-features = false } diff --git a/tokio-boring/src/async_callbacks.rs b/tokio-boring/src/async_callbacks.rs index 3c18313cd..5ccb64698 100644 --- a/tokio-boring/src/async_callbacks.rs +++ b/tokio-boring/src/async_callbacks.rs @@ -1,6 +1,6 @@ use boring::ssl::{ - AsyncPrivateKeyMethod, AsyncSelectCertError, BoxGetSessionFuture, BoxSelectCertFuture, - ClientHello, SslContextBuilder, SslRef, + AsyncPrivateKeyMethod, AsyncSelectCertError, BoxGetSessionFuture, BoxSelectCertActionFuture, + BoxSelectCertFuture, ClientHello, SslContextBuilder, SslRef, }; /// Extensions to [`SslContextBuilder`]. @@ -17,6 +17,12 @@ pub trait SslContextBuilderExt: private::Sealed { /// /// See [`SslContextBuilder::set_select_certificate_callback`] for the sync /// setter of this callback. + /// + /// A context has a single certificate selection callback. Calling this method replaces the + /// callback set by any of [`SslContextBuilder::set_select_certificate_callback`], + /// [`SslContextBuilder::set_select_certificate_callback_with_action`], + /// [`SslContextBuilder::set_async_select_certificate_callback`], or + /// [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. fn set_async_select_certificate_callback(&mut self, callback: F) where F: Fn(&mut ClientHello<'_>) -> Result @@ -24,6 +30,27 @@ pub trait SslContextBuilderExt: private::Sealed { + Sync + 'static; + /// Sets an action-aware asynchronous certificate selection callback. + /// + /// A task waker must be set on `Ssl` values associated with the resulting `SslContext` with + /// [`SslRef::set_task_waker`]. Returning [`boring::ssl::SelectCertAction::DisableEch`] + /// discards an inner ClientHello and invokes the callback again with the outer ClientHello. + /// It is only valid when ECH has been accepted; returning it otherwise fails the handshake. + /// The future-producing callback runs again for the outer ClientHello, so per-connection + /// state must handle both calls. + /// + /// A context has a single certificate selection callback. Calling this method replaces the + /// callback set by any of [`SslContextBuilder::set_select_certificate_callback`], + /// [`SslContextBuilder::set_select_certificate_callback_with_action`], + /// [`SslContextBuilder::set_async_select_certificate_callback`], or + /// [`SslContextBuilder::set_async_select_certificate_callback_with_action`]. + fn set_async_select_certificate_callback_with_action(&mut self, callback: F) + where + F: Fn(&mut ClientHello<'_>) -> Result + + Send + + Sync + + 'static; + /// Configures a custom private key method on the context. /// /// See [`AsyncPrivateKeyMethod`] for more details. @@ -58,6 +85,16 @@ impl SslContextBuilderExt for SslContextBuilder { self.set_async_select_certificate_callback(callback); } + fn set_async_select_certificate_callback_with_action(&mut self, callback: F) + where + F: Fn(&mut ClientHello<'_>) -> Result + + Send + + Sync + + 'static, + { + self.set_async_select_certificate_callback_with_action(callback); + } + fn set_async_private_key_method(&mut self, method: impl AsyncPrivateKeyMethod) { self.set_async_private_key_method(method); } diff --git a/tokio-boring/src/lib.rs b/tokio-boring/src/lib.rs index 1ec00d059..b5ebe0c2b 100644 --- a/tokio-boring/src/lib.rs +++ b/tokio-boring/src/lib.rs @@ -33,8 +33,9 @@ use self::bridge::AsyncStreamBridge; pub use crate::async_callbacks::SslContextBuilderExt; pub use boring::ssl::{ AsyncPrivateKeyMethod, AsyncPrivateKeyMethodError, AsyncSelectCertError, BoxGetSessionFinish, - BoxGetSessionFuture, BoxPrivateKeyMethodFinish, BoxPrivateKeyMethodFuture, BoxSelectCertFinish, - BoxSelectCertFuture, ExDataFuture, + BoxGetSessionFuture, BoxPrivateKeyMethodFinish, BoxPrivateKeyMethodFuture, + BoxSelectCertActionFinish, BoxSelectCertActionFuture, BoxSelectCertFinish, BoxSelectCertFuture, + ExDataFuture, SelectCertAction, }; /// Asynchronously performs a client-side TLS handshake over the provided stream. diff --git a/tokio-boring/tests/async_select_certificate.rs b/tokio-boring/tests/async_select_certificate.rs index 91845f4ea..83079c266 100644 --- a/tokio-boring/tests/async_select_certificate.rs +++ b/tokio-boring/tests/async_select_certificate.rs @@ -1,11 +1,22 @@ -use boring::ssl::ClientHello; +use boring::hpke::HpkeKey; +use boring::ssl::{ClientHello, NameType, SslEchKeys}; use futures::future; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::net::TcpStream; use tokio::task::yield_now; -use tokio_boring::{AsyncSelectCertError, BoxSelectCertFinish, BoxSelectCertFuture}; +use tokio_boring::{ + AsyncSelectCertError, BoxSelectCertActionFinish, BoxSelectCertActionFuture, + BoxSelectCertFinish, BoxSelectCertFuture, SelectCertAction, +}; mod common; -use self::common::{connect, create_server, with_trivial_client_server_exchange}; +use self::common::{connect, create_connector, create_server, with_trivial_client_server_exchange}; + +static ECH_CONFIG_LIST: &[u8] = include_bytes!("../../boring/test/echconfiglist"); +static ECH_CONFIG: &[u8] = include_bytes!("../../boring/test/echconfig"); +static ECH_KEY: &[u8] = include_bytes!("../../boring/test/echkey"); #[tokio::test] async fn test_async_select_certificate_callback_trivial() { @@ -33,6 +44,116 @@ async fn test_async_select_certificate_callback_yield() { .await; } +#[tokio::test] +async fn test_async_select_certificate_callback_with_action() { + with_trivial_client_server_exchange(|builder| { + builder.set_async_select_certificate_callback_with_action(|_| { + Ok(Box::pin(async { + yield_now().await; + Ok(Box::new(|_: ClientHello<'_>| Ok(SelectCertAction::Success)) + as BoxSelectCertActionFinish) + })) + }); + }) + .await; +} + +#[tokio::test] +async fn test_async_select_certificate_callback_with_action_ech_disable() { + let calls = Arc::new(AtomicUsize::new(0)); + let future_calls = Arc::new(AtomicUsize::new(0)); + let observations = Arc::new(Mutex::new(Vec::new())); + let (stream, addr) = create_server({ + let calls = calls.clone(); + let future_calls = future_calls.clone(); + let observations = observations.clone(); + move |builder| { + let key = HpkeKey::dhkem_p256_sha256(ECH_KEY).unwrap(); + let mut ech_keys_builder = SslEchKeys::builder().unwrap(); + ech_keys_builder.add_key(true, ECH_CONFIG, key).unwrap(); + let ech_keys = ech_keys_builder.build(); + builder.set_ech_keys(&ech_keys).unwrap(); + + let calls = calls.clone(); + let future_calls = future_calls.clone(); + let observations = observations.clone(); + builder.set_async_select_certificate_callback_with_action(move |_| { + let calls = calls.clone(); + future_calls.fetch_add(1, Ordering::Relaxed); + let observations = observations.clone(); + Ok(Box::pin(async move { + yield_now().await; + Ok(Box::new(move |client_hello: ClientHello<'_>| { + observations.lock().unwrap().push(( + client_hello.ssl().ech_accepted(), + client_hello + .ssl() + .servername(NameType::HOST_NAME) + .map(str::to_owned), + )); + if calls.fetch_add(1, Ordering::Relaxed) == 0 { + Ok(SelectCertAction::DisableEch) + } else { + Ok(SelectCertAction::Success) + } + }) as BoxSelectCertActionFinish) + })) + }); + } + }); + + let server = async { + stream.await.unwrap_err(); + }; + + let client = async { + let connector = create_connector(|builder| builder.set_ca_file("tests/cert.pem")); + let mut config = connector.configure().unwrap(); + config.set_ech_config_list(ECH_CONFIG_LIST).unwrap(); + let stream = TcpStream::connect(addr).await.unwrap(); + tokio_boring::connect(config, "localhost", stream) + .await + .unwrap_err(); + }; + + future::join(server, client).await; + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(future_calls.load(Ordering::Relaxed), 2); + assert_eq!( + *observations.lock().unwrap(), + vec![ + (true, Some("localhost".to_owned())), + (false, Some("ech.com".to_owned())), + ] + ); +} + +#[tokio::test] +async fn test_async_select_certificate_callback_with_action_return_error() { + with_async_select_certificate_callback_action_error(|_| Err(AsyncSelectCertError)).await; +} + +#[tokio::test] +async fn test_async_select_certificate_callback_with_action_future_error() { + with_async_select_certificate_callback_action_error(|_| { + Ok(Box::pin(async move { Err(AsyncSelectCertError) })) + }) + .await; +} + +#[tokio::test] +async fn test_async_select_certificate_callback_with_action_finish_error() { + with_async_select_certificate_callback_action_error(|_| { + Ok(Box::pin(async move { + yield_now().await; + + Ok(Box::new(|_: ClientHello<'_>| Err(AsyncSelectCertError)) + as BoxSelectCertActionFinish) + })) + }) + .await; +} + #[tokio::test] async fn test_async_select_certificate_callback_return_error() { with_async_select_certificate_callback_error(|_| Err(AsyncSelectCertError)).await; @@ -92,3 +213,26 @@ async fn with_async_select_certificate_callback_error( future::join(server, client).await; } + +async fn with_async_select_certificate_callback_action_error( + callback: impl Fn(&mut ClientHello<'_>) -> Result + + Send + + Sync + + 'static, +) { + let (stream, addr) = create_server(|builder| { + builder.set_async_select_certificate_callback_with_action(callback); + }); + + let server = async { + let _err = stream.await.unwrap_err(); + }; + + let client = async { + let _err = connect(addr, |builder| builder.set_ca_file("tests/cert.pem")) + .await + .unwrap_err(); + }; + + future::join(server, client).await; +}