From a29e2fff0034d8612b428a8287ad58e2858351df Mon Sep 17 00:00:00 2001 From: James Mayclin Date: Thu, 25 Jul 2024 15:32:04 -0700 Subject: [PATCH 1/4] fix: new clippy lints (#4666) --- bindings/rust/s2n-tls/src/connection.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bindings/rust/s2n-tls/src/connection.rs b/bindings/rust/s2n-tls/src/connection.rs index d2e3fda5588..770c556df13 100644 --- a/bindings/rust/s2n-tls/src/connection.rs +++ b/bindings/rust/s2n-tls/src/connection.rs @@ -590,7 +590,7 @@ impl Connection { /// Safety: this function is always safe to call, and additionally: /// 1. It will never deinitialize any bytes in `buf`. /// 2. If it returns `Ok(n)`, then the first `n` bytes of `buf` - /// will have been initialized by this function. + /// will have been initialized by this function. pub fn poll_recv_uninitialized( &mut self, buf: &mut [MaybeUninit], From 3c0dfeebaf54f65276a68177c76cf64baa67750d Mon Sep 17 00:00:00 2001 From: Doug Chapman <54039637+dougch@users.noreply.github.com> Date: Fri, 26 Jul 2024 08:51:08 -0700 Subject: [PATCH 2/4] ci(nix): Setup a head build for the cross_compatibility integ test (#4567) --- codebuild/bin/install_s2n_head.sh | 52 ++++++++++++++++++++++--------- nix/shell.sh | 15 +++++---- 2 files changed, 44 insertions(+), 23 deletions(-) diff --git a/codebuild/bin/install_s2n_head.sh b/codebuild/bin/install_s2n_head.sh index ebad50d12b2..3fbb3f609be 100755 --- a/codebuild/bin/install_s2n_head.sh +++ b/codebuild/bin/install_s2n_head.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/usr/bin/env bash # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). @@ -12,31 +12,53 @@ # express or implied. See the License for the specific language governing # permissions and limitations under the License. -set -ex -pushd "$(pwd)" +set -eu usage() { echo "install_s2n_head.sh build_dir" exit 1 } +BUILD_DIR=$1 +SRC_ROOT=${SRC_ROOT:-$(pwd)} + if [ "$#" -ne "1" ]; then usage fi -BUILD_DIR=$1 -source codebuild/bin/jobs.sh -cd "$BUILD_DIR" - -# Clone the most recent s2n commit -git clone --depth=1 https://github.com/aws/s2n-tls s2n_head -cmake ./s2n_head -Bbuild -DCMAKE_PREFIX_PATH="$LIBCRYPTO_ROOT" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=on -cmake --build ./build -- -j $JOBS +clone(){ + git clone --branch main --single-branch . "$SRC_ROOT"/s2n_head +} -# Copy new executables to bin directory -cp -f "$BUILD_DIR"/build/bin/s2nc "$BASE_S2N_DIR"/bin/s2nc_head -cp -f "$BUILD_DIR"/build/bin/s2nd "$BASE_S2N_DIR"/bin/s2nd_head +# CMake(nix) and Make are using different directory structures. +set +u +if [[ "$IN_NIX_SHELL" ]]; then + export DEST_DIR="$SRC_ROOT"/build/bin + export EXTRA_BUILD_FLAGS="" +else + export DEST_DIR="$SRC_ROOT"/bin + export EXTRA_BUILD_FLAGS="-DCMAKE_PREFIX_PATH=$LIBCRYPTO_ROOT" +fi +set -u -popd +# Cleanup any stale s2n_head clones. +if [[ -d "$SRC_ROOT/s2n_head" ]]; then + now=$(date +%s) + last_modified=$(stat -c %Y s2n_head) + days_old=$(( (now - last_modified) / 86400)) + if ((days_old > 1 )); then + echo "s2n_head is $days_old days old, removing and cloning again." + rm -rf s2n_head + clone + else + echo "s2n_head already exists and is $days_old days old." + fi +else + clone +fi +cmake "$SRC_ROOT"/s2n_head -B"$BUILD_DIR" "$EXTRA_BUILD_FLAGS" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=on +cmake --build "$BUILD_DIR" -- -j "$(nproc)" +cp -f "$BUILD_DIR"/bin/s2nc "$DEST_DIR"/s2nc_head +cp -f "$BUILD_DIR"/bin/s2nd "$DEST_DIR"/s2nd_head exit 0 diff --git a/nix/shell.sh b/nix/shell.sh index bed64de1d4c..75072d244cd 100644 --- a/nix/shell.sh +++ b/nix/shell.sh @@ -28,7 +28,7 @@ libcrypto_alias libressl "${LIBRESSL_INSTALL_DIR}/bin/openssl" function clean { banner "Cleanup ./build" - rm -rf ./build + rm -rf ./build ./s2n_head } function configure { @@ -47,6 +47,10 @@ function build { banner "Running Build" javac tests/integrationv2/bin/SSLSocketClient.java cmake --build ./build -j $(nproc) + # Build s2n from HEAD + if [[ -z "${S2N_KTLS_TESTING_EXPECTED}" ]]; then + $SRC_ROOT/codebuild/bin/install_s2n_head.sh $(mktemp -d) + fi } function unit { @@ -60,21 +64,16 @@ function unit { function integ { if [ "$1" == "help" ]; then echo "The following tests are not supported:" - echo " - cross_compatibility" - echo " This test depends on s2nc_head and s2nd_head. To run" - echo " the test build s2n-tls from the main branch on github." - echo " Change the names of s2n[cd] to s2n[cd]_head and add those" - echo " binaries to \$PATH." echo "- renegotiate_apache" echo " This test requires apache to be running. See codebuild/bin/s2n_apache.sh" echo " for more info." return fi if [[ -z "$1" ]]; then - banner "Running all integ tests except cross_compatibility, renegotiate_apache." + banner "Running all integ tests except renegotiate_apache." (cd $SRC_ROOT/build; ctest -L integrationv2 -E "(integrationv2_cross_compatibility|integrationv2_renegotiate_apache)" --verbose) else - banner "Warning: cross_compatibility & renegotiate_apache are not supported in nix for various reasons integ help for more info." + banner "Warning: renegotiate_apache is not supported in nix for various reasons integ help for more info." for test in $@; do ctest --test-dir ./build -L integrationv2 --no-tests=error --output-on-failure -R "$test" --verbose if [ "$?" -ne 0 ]; then From fff7b157eb43cff62b39a34c8aa1c89145888167 Mon Sep 17 00:00:00 2001 From: kaukabrizvi <100529019+kaukabrizvi@users.noreply.github.com> Date: Fri, 26 Jul 2024 11:01:08 -0700 Subject: [PATCH 3/4] Set up regression benchmark for scalar performance (#4649) --- .gitignore | 2 + bindings/rust/s2n-tls/Cargo.toml | 1 + bindings/rust/s2n-tls/src/lib.rs | 4 +- tests/regression/Cargo.toml | 14 +++ tests/regression/README.md | 106 +++++++++++++++++++ tests/regression/src/lib.rs | 170 +++++++++++++++++++++++++++++++ 6 files changed, 295 insertions(+), 2 deletions(-) create mode 100644 tests/regression/Cargo.toml create mode 100644 tests/regression/README.md create mode 100644 tests/regression/src/lib.rs diff --git a/.gitignore b/.gitignore index ad5ed8373c1..6eecfc650fe 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,5 @@ build/ result result-* *.class +# Exclude rust build directories +*target/ diff --git a/bindings/rust/s2n-tls/Cargo.toml b/bindings/rust/s2n-tls/Cargo.toml index a678b4cd4c3..aa064a2bd04 100644 --- a/bindings/rust/s2n-tls/Cargo.toml +++ b/bindings/rust/s2n-tls/Cargo.toml @@ -15,6 +15,7 @@ unstable-ktls = ["s2n-tls-sys/unstable-ktls"] quic = ["s2n-tls-sys/quic"] fips = ["s2n-tls-sys/fips"] pq = ["s2n-tls-sys/pq"] +unstable-testing = [] [dependencies] errno = { version = "0.3" } diff --git a/bindings/rust/s2n-tls/src/lib.rs b/bindings/rust/s2n-tls/src/lib.rs index 00c58200cba..27dc0f6f534 100644 --- a/bindings/rust/s2n-tls/src/lib.rs +++ b/bindings/rust/s2n-tls/src/lib.rs @@ -27,5 +27,5 @@ pub mod security; pub use s2n_tls_sys as ffi; -#[cfg(test)] -mod testing; +#[cfg(any(feature = "unstable-testing", test))] +pub mod testing; diff --git a/tests/regression/Cargo.toml b/tests/regression/Cargo.toml new file mode 100644 index 00000000000..d8f07d9ab63 --- /dev/null +++ b/tests/regression/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "regression" +version = "0.1.0" +edition = "2021" + +[dependencies] +s2n-tls = { path = "../../bindings/rust/s2n-tls", features = ["unstable-testing"] } +bytes = { version = "1", optional = true } +errno = { version = "0.3" } +libc = "0.2" +crabgrind = "0.1" +futures-test = "0.3.30" +[profile.release] +debug = true diff --git a/tests/regression/README.md b/tests/regression/README.md new file mode 100644 index 00000000000..f79c0964da9 --- /dev/null +++ b/tests/regression/README.md @@ -0,0 +1,106 @@ +# Regression Testing for s2n-tls + +This folder contains regression tests and benchmarking tools for the `s2n-tls` library. The tests focus on various aspects of TLS connections. + +## Testing Philosophy + +Currently, s2n-tls implements a wall clock benchmarking tool which measures end-to-end handshake performance to compare s2n-tls with rustls and OpenSSL. In the past, s2n-tls has tried benchmarking to detect regressions through criterion in Rust, but the subprocess and spin-up time contributed to performance measurement which made the results inaccurate and difficult to use in CI. The project has a slightly different focus, learning from these existing tools. Performance assertion in s2n-tls focuses on a benchmarking tool that can detail performance by API path and do so with enough repeatability and accuracy to detect regressions between two versions of s2n-tls so that performance analysis can occur at PR time. This means that the scope of each harness is limited and mutually exclusive of other harnesses since we are intersted in measuring the performance of the important paths a TLS connection typically follows. +## Contents + +1. **lib.rs** + - **test_set_config**: Builds a new s2n-tls config with a security policy, host callback and certs + - **test_rsa_handshake**: Performs an RSA handshake in s2n-tls. + +2. **Cargo.toml** + - The configuration file for building and running the regression tests using Cargo. + + +## Prerequisites + +Ensure you have the following installed: +- Rust (with Cargo) +- Valgrind (for cachegrind instrumentation) + +## Running the Harnesses with Valgrind (scalar performance) +To run the harnesses with Valgrind and store the annotated results, run: + +``` +ENABLE_VALGRIND = true cargo test +``` + +This will recursively call all tests with valgrind enabled so the performance output is generated and stored +## Running the tests w/o Valgrind + +``` +cargo test +``` + +This will run the tests without valgrind to test if the process completes as expected +## Sample Output for Valgrind test + +Running the test will run all harnesses and fail if any number of harnesses exceed the performance threshold. For example, a regression test faliure could look like: +``` +---- tests::test_set_security_policy_and_build stdout ---- +Running command: valgrind --tool=cachegrind --cachegrind-out-file=cachegrind_test_set_security_policy_and_build.out /home/ubuntu/proj/s2n/tests/regression/target/debug/deps/regression-7c7d86aeafe3b426 test_set_security_policy_and_build +Running command: cg_annotate cachegrind_test_set_security_policy_and_build.out > perf_outputs/test_set_security_policy_and_build.annotated.txt +thread 'tests::test_set_security_policy_and_build' panicked at src/lib.rs:174:9: +Instruction count difference in test_set_security_policy_and_build exceeds the threshold, regression of 13975865 instructions +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + +---- tests::test_rsa_handshake stdout ---- +Running command: valgrind --tool=cachegrind --cachegrind-out-file=cachegrind_test_rsa_handshake.out /home/ubuntu/proj/s2n/tests/regression/target/debug/deps/regression-7c7d86aeafe3b426 test_rsa_handshake +Running command: cg_annotate cachegrind_test_rsa_handshake.out > perf_outputs/test_rsa_handshake.annotated.txt +thread 'tests::test_rsa_handshake' panicked at src/lib.rs:174:9: +Instruction count difference in test_rsa_handshake exceeds the threshold, regression of 51176459 instructions + + +failures: + tests::test_rsa_handshake + tests::test_set_security_policy_and_build +``` + +It also produces annotated cachegrind files stored in the `perf_ouput` directory which detail the instruction counts, how many instructions a particular file/function account for, and the contribution of individual lines of code to the overall instruction count. For example, these are the first few lines of the output generated for 'test_rsa_handshake.annotated.txt': + +``` +-------------------------------------------------------------------------------- +-- Summary +-------------------------------------------------------------------------------- +Ir_________________ + +79,270,744 (100.0%) PROGRAM TOTALS + +-------------------------------------------------------------------------------- +-- File:function summary +-------------------------------------------------------------------------------- + Ir_______________________ file:function + +< 71,798,872 (90.6%, 90.6%) /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aws-lc-sys-0.19.0/aws-lc/generated-src/linux-x86_64/crypto/fipsmodule/x86_64-mont5.S: + 54,908,926 (69.3%) aws_lc_0_19_0_bn_sqr8x_internal + 15,699,024 (19.8%) mul4x_internal + 1,114,840 (1.4%) __bn_post4x_internal + +< 1,551,316 (2.0%, 92.5%) /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aws-lc-sys-0.19.0/aws-lc/generated-src/linux-x86_64/crypto/fipsmodule/p256-x86_64-asm.S: + 676,336 (0.9%) __ecp_nistz256_mul_montq + 475,750 (0.6%) __ecp_nistz256_sqr_montq + 95,732 (0.1%) aws_lc_0_19_0_ecp_nistz256_point_double + +< 833,553 (1.1%, 93.6%) /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aws-lc-sys-0.19.0/aws-lc/generated-src/linux-x86_64/crypto/fipsmodule/sha256-x86_64.S: + 830,671 (1.0%) sha256_block_data_order_avx + +< 557,697 (0.7%, 94.3%) /home/ubuntu/.cargo/registry/src/index.crates.io-6f17d22bba15001f/aws-lc-sys-0.19.0/aws-lc/generated-src/linux-x86_64/crypto/fipsmodule/x86_64-mont.S: + 493,032 (0.6%) bn_mul4x_mont + +``` + +### Understanding the Annotated Output +The total instruction counts are listed at the top, and segmented by file:function beneath it. When comparing versions of s2n-tls (during PR workflow or otherwise) this can be useful to pinpoint the source of instruction count difference to inform you on how changes to the code impact performance. This [link](https://valgrind.org/docs/manual/cg-manual.html#cg-manual.running-cg_annotate:~:text=Information%20Source%20Code%20Documentation%20Contact%20How%20to%20Help%20Gallery,5.2.3.%C2%A0Running%20cg_annotate,-Before%20using%20cg_annotate) provides a more detailed description to fully understand the output file. + +## Test Details + +### test_set_config + +Configures and creates a new s2n-tls configuration with a specified security policy and loads a certificate key pair. Ensures the configuration is valid and can be built. + +### test_rsa_handshake + +Performs an RSA handshake in s2n-tls and validates the handshake process utilizing rsa_4096_sha512. diff --git a/tests/regression/src/lib.rs b/tests/regression/src/lib.rs new file mode 100644 index 00000000000..6a748b778ee --- /dev/null +++ b/tests/regression/src/lib.rs @@ -0,0 +1,170 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +use s2n_tls::{ + config::Builder, + security, + testing::{CertKeyPair, InsecureAcceptAllCertificatesHandler}, +}; +type Error = s2n_tls::error::Error; + +/// Function to create default config with specified parameters. +pub fn set_config( + cipher_prefs: &security::Policy, + keypair: CertKeyPair, +) -> Result { + let mut builder = Builder::new(); + builder + .set_security_policy(cipher_prefs) + .expect("Unable to set config cipher preferences"); + builder + .set_verify_host_callback(InsecureAcceptAllCertificatesHandler {}) + .expect("Unable to set a host verify callback."); + builder + .load_pem(keypair.cert(), keypair.key()) + .expect("Unable to load cert/pem"); + builder.trust_pem(keypair.cert()).expect("load cert pem"); + builder.build() +} + +#[cfg(test)] +mod tests { + use super::*; + use crabgrind as cg; + use s2n_tls::testing::TestPair; + use std::{ + env, + fs::{create_dir_all, File}, + io::{self, BufRead, Write}, + path::Path, + process::Command, + }; + + /// Configurable threshold for regression testing. + /// Tests will fail if the instruction count difference is greater than the value of this constant. + const MAX_DIFF: u64 = 1_000_000; + + struct InstrumentationControl; + + impl InstrumentationControl { + fn stop_instrumentation(&self) { + cg::cachegrind::stop_instrumentation(); + } + + fn start_instrumentation(&self) { + cg::cachegrind::start_instrumentation(); + } + } + /// Environment variable to determine whether to run under valgrind or solely test functionality. + fn is_running_under_valgrind() -> bool { + env::var("ENABLE_VALGRIND").is_ok() + } + + fn valgrind_test(test_name: &str, test_body: F) -> Result<(), s2n_tls::error::Error> + where + F: FnOnce(&InstrumentationControl) -> Result<(), s2n_tls::error::Error>, + { + if !is_running_under_valgrind() { + let ctrl = InstrumentationControl; + test_body(&ctrl) + } else { + run_valgrind_test(test_name); + Ok(()) + } + } + + /// Test to create new config, set security policy, host_callback information, load/trust certs, and build config. + #[test] + fn test_set_config() { + valgrind_test("test_set_config", |ctrl| { + ctrl.stop_instrumentation(); + ctrl.start_instrumentation(); + let keypair_rsa = CertKeyPair::default(); + let _config = + set_config(&security::DEFAULT_TLS13, keypair_rsa).expect("Failed to build config"); + Ok(()) + }) + .unwrap(); + } + + /// Test which creates a TestPair from config using `rsa_4096_sha512`. Only measures a pair handshake. + #[test] + fn test_rsa_handshake() { + valgrind_test("test_rsa_handshake", |ctrl| { + ctrl.stop_instrumentation(); + // Example usage with RSA keypair (default) + let keypair_rsa = CertKeyPair::default(); + let config = set_config(&security::DEFAULT_TLS13, keypair_rsa)?; + // Create a pair (client + server) using that config, start handshake measurement + let mut pair = TestPair::from_config(&config); + // Assert a successful handshake + ctrl.start_instrumentation(); + assert!(pair.handshake().is_ok()); + ctrl.stop_instrumentation(); + Ok(()) + }) + .unwrap(); + } + /// Function to run specified test using valgrind + fn run_valgrind_test(test_name: &str) { + let exe_path = std::env::args().next().unwrap(); + create_dir_all(Path::new("target/cg_artifacts")).unwrap(); + let output_file = format!("target/cg_artifacts/cachegrind_{}.out", test_name); + let output_command = format!("--cachegrind-out-file={}", &output_file); + let mut command = Command::new("valgrind"); + command + .args(["--tool=cachegrind", &output_command, &exe_path, test_name]) + // Ensures that the recursive call is made to the actual harness code block rather than back to this function + .env_remove("ENABLE_VALGRIND"); + + println!("Running command: {:?}", command); + let status = command.status().expect("Failed to execute valgrind"); + + if !status.success() { + panic!("Valgrind failed"); + } + + let annotate_output = Command::new("cg_annotate") + .arg(&output_file) + .output() + .expect("Failed to run cg_annotate"); + + if !annotate_output.status.success() { + panic!("cg_annotate failed"); + } + create_dir_all(Path::new("target/perf_outputs")).unwrap(); + let annotate_file = format!("target/perf_outputs/{}.annotated.txt", test_name); + let mut file = File::create(&annotate_file).expect("Failed to create annotation file"); + file.write_all(&annotate_output.stdout) + .expect("Failed to write annotation file"); + + let count = find_instruction_count(&annotate_file) + .expect("Failed to get instruction count from file"); + // This is temporary code to showcase the future diff functionality, here the code regresses by 10% each time so this test will almost always fail + let new_count = count + count / 10; + let diff = new_count - count; + assert!(diff <= self::MAX_DIFF, "Instruction count difference in {} exceeds the threshold, regression of {} instructions", test_name, diff); + } + + /// Parses the annotated file for the overall instruction count total + fn find_instruction_count(file_path: &str) -> Result { + let path = Path::new(file_path); + let file = File::open(path)?; + let reader = io::BufReader::new(file); + // Example of the line being parsed: + // "79,278,369 (100.0%) PROGRAM TOTALS" + for line in reader.lines() { + let line = line?; + if line.contains("PROGRAM TOTALS") { + if let Some(instructions) = line.split_whitespace().next() { + return instructions + .replace(',', "") + .parse::() + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)); + } + } + } + + panic!("Failed to find instruction count in annotated file"); + } +} From b483357680577fdd5f94c14cbc4e92a7563f0160 Mon Sep 17 00:00:00 2001 From: Lindsay Stewart Date: Sat, 27 Jul 2024 14:18:20 -0700 Subject: [PATCH 4/4] refactor: clean up other hex methods (#4664) --- .../proofs/s2n_hex_string_to_bytes/Makefile | 48 -------------- .../s2n_hex_string_to_bytes/cbmc-proof.txt | 1 - .../s2n_hex_string_to_bytes_harness.c | 53 --------------- tests/testlib/s2n_hex_testlib.c | 66 +++++++++++++++++++ tests/testlib/s2n_resumption_testlib.c | 2 +- tests/testlib/s2n_stuffer_testlib.c | 35 ---------- tests/testlib/s2n_testlib.h | 12 +++- tests/unit/s2n_blob_test.c | 55 ---------------- tests/unit/s2n_client_hello_retry_test.c | 2 +- .../s2n_client_key_share_extension_pq_test.c | 2 +- tests/unit/s2n_drbg_test.c | 12 ++-- tests/unit/s2n_hash_all_algs_test.c | 5 +- tests/unit/s2n_override_openssl_random_test.c | 4 +- tests/unit/s2n_rsa_pss_rsae_test.c | 4 +- tests/unit/s2n_self_talk_key_log_test.c | 4 +- .../s2n_server_key_share_extension_test.c | 14 ++-- tests/unit/s2n_testlib_test.c | 25 +++++++ tests/unit/s2n_tls13_server_cert_test.c | 7 +- tls/s2n_key_log.c | 38 +++++------ tls/s2n_key_log.h | 1 - utils/s2n_blob.c | 56 ---------------- utils/s2n_blob.h | 13 ---- 22 files changed, 142 insertions(+), 317 deletions(-) delete mode 100644 tests/cbmc/proofs/s2n_hex_string_to_bytes/Makefile delete mode 100644 tests/cbmc/proofs/s2n_hex_string_to_bytes/cbmc-proof.txt delete mode 100644 tests/cbmc/proofs/s2n_hex_string_to_bytes/s2n_hex_string_to_bytes_harness.c create mode 100644 tests/testlib/s2n_hex_testlib.c delete mode 100644 tests/testlib/s2n_stuffer_testlib.c diff --git a/tests/cbmc/proofs/s2n_hex_string_to_bytes/Makefile b/tests/cbmc/proofs/s2n_hex_string_to_bytes/Makefile deleted file mode 100644 index 0fe32ed3e37..00000000000 --- a/tests/cbmc/proofs/s2n_hex_string_to_bytes/Makefile +++ /dev/null @@ -1,48 +0,0 @@ -# -# -# Licensed under the Apache License, Version 2.0 (the "License"). You may not use -# this file except in compliance with the License. A copy of the License is -# located at -# -# http://aws.amazon.com/apache2.0/ -# -# or in the "license" file accompanying this file. This file is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. See the License for the specific language governing permissions and -# limitations under the License. - -# Enough to get full coverage with 10 seconds of runtime. -MAX_STRING_LEN = 10 -DEFINES += -DMAX_STRING_LEN=$(MAX_STRING_LEN) - -CBMCFLAGS += - -PROOF_UID = s2n_hex_string_to_bytes -HARNESS_ENTRY = $(PROOF_UID)_harness -HARNESS_FILE = $(HARNESS_ENTRY).c - -PROOF_SOURCES += $(PROOFDIR)/$(HARNESS_FILE) -PROOF_SOURCES += $(PROOF_SOURCE)/cbmc_utils.c -PROOF_SOURCES += $(PROOF_SOURCE)/make_common_datastructures.c - -PROJECT_SOURCES += $(SRCDIR)/utils/s2n_blob.c -PROJECT_SOURCES += $(SRCDIR)/utils/s2n_safety.c -PROJECT_SOURCES += $(SRCDIR)/error/s2n_errno.c -PROJECT_SOURCES += $(SRCDIR)/utils/s2n_result.c - -# We abstract this function because manual inspection demonstrates it is unreachable. -REMOVE_FUNCTION_BODY += s2n_calculate_stacktrace - -UNWINDSET += strlen.0:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes_harness.0:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.2:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.3:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.6:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.9:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.12:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.13:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.15:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.16:$(shell echo $$((1 + $(MAX_STRING_LEN)))) -UNWINDSET += s2n_hex_string_to_bytes.17:$(shell echo $$((1 + $(MAX_STRING_LEN)))) - -include ../Makefile.common diff --git a/tests/cbmc/proofs/s2n_hex_string_to_bytes/cbmc-proof.txt b/tests/cbmc/proofs/s2n_hex_string_to_bytes/cbmc-proof.txt deleted file mode 100644 index 6ed46f1258c..00000000000 --- a/tests/cbmc/proofs/s2n_hex_string_to_bytes/cbmc-proof.txt +++ /dev/null @@ -1 +0,0 @@ -# This file marks this directory as containing a CBMC proof. diff --git a/tests/cbmc/proofs/s2n_hex_string_to_bytes/s2n_hex_string_to_bytes_harness.c b/tests/cbmc/proofs/s2n_hex_string_to_bytes/s2n_hex_string_to_bytes_harness.c deleted file mode 100644 index 6a144e5bbbe..00000000000 --- a/tests/cbmc/proofs/s2n_hex_string_to_bytes/s2n_hex_string_to_bytes_harness.c +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#include -#include -#include - -#include "error/s2n_errno.h" -#include "utils/s2n_blob.h" - -#include - -void s2n_hex_string_to_bytes_harness() -{ - /* Non-deterministic inputs. */ - struct s2n_blob *blob = cbmc_allocate_s2n_blob(); - __CPROVER_assume(s2n_result_is_ok(s2n_blob_validate(blob))); - char *str = ensure_c_str_is_allocated(MAX_STRING_LEN); - - /* Save previous state. */ - struct s2n_blob old_blob = *blob; - struct store_byte_from_buffer old_byte_from_blob; - save_byte_from_blob(blob, &old_byte_from_blob); - - /* Operation under verification. */ - if (s2n_hex_string_to_bytes(str, blob) == S2N_SUCCESS) { - size_t strLength = 0; - for (size_t i = 0; i < strlen(str); i++) { - if (str[i] != ' ') { - strLength++; - } - } - assert(strLength % 2 == 0); - assert(blob->size == (strLength / 2)); - } else { - assert(blob->allocated == old_blob.allocated); - assert(blob->growable == old_blob.growable); - assert(blob->size == old_blob.size); - } - assert(s2n_result_is_ok(s2n_blob_validate(blob))); -} diff --git a/tests/testlib/s2n_hex_testlib.c b/tests/testlib/s2n_hex_testlib.c new file mode 100644 index 00000000000..0f33b871e25 --- /dev/null +++ b/tests/testlib/s2n_hex_testlib.c @@ -0,0 +1,66 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +#include + +#include "error/s2n_errno.h" +#include "stuffer/s2n_stuffer.h" +#include "testlib/s2n_testlib.h" +#include "utils/s2n_safety.h" + +S2N_RESULT s2n_stuffer_alloc_from_hex(struct s2n_stuffer *bytes_out, const char *hex_cstr) +{ + RESULT_ENSURE_REF(bytes_out); + RESULT_ENSURE_REF(hex_cstr); + + DEFER_CLEANUP(struct s2n_blob hex = { 0 }, s2n_free); + /* Copying the hex into heap memory to handle the 'const' isn't exactly efficient, + * but for a testlib method it is sufficient. + */ + RESULT_GUARD_POSIX(s2n_alloc(&hex, strlen(hex_cstr))); + RESULT_CHECKED_MEMCPY(hex.data, hex_cstr, hex.size); + + RESULT_GUARD_POSIX(s2n_stuffer_alloc(bytes_out, strlen(hex_cstr) / 2)); + RESULT_GUARD(s2n_stuffer_read_hex(bytes_out, &hex)); + return S2N_RESULT_OK; +} + +S2N_RESULT s2n_blob_alloc_from_hex_with_whitespace(struct s2n_blob *bytes_out, const char *hex_cstr) +{ + RESULT_ENSURE_REF(bytes_out); + RESULT_ENSURE_REF(hex_cstr); + + DEFER_CLEANUP(struct s2n_stuffer hex_in = { 0 }, s2n_stuffer_free); + RESULT_GUARD_POSIX(s2n_stuffer_alloc(&hex_in, strlen(hex_cstr))); + for (size_t i = 0; i < strlen(hex_cstr); i++) { + if (hex_cstr[i] == ' ') { + continue; + } + RESULT_GUARD_POSIX(s2n_stuffer_write_uint8(&hex_in, hex_cstr[i])); + } + uint32_t hex_in_size = s2n_stuffer_data_available(&hex_in); + hex_in.blob.size = hex_in_size; + + DEFER_CLEANUP(struct s2n_blob bytes_out_mem = { 0 }, s2n_free); + RESULT_GUARD_POSIX(s2n_alloc(&bytes_out_mem, hex_in_size / 2)); + + struct s2n_stuffer bytes_out_stuffer = { 0 }; + RESULT_GUARD_POSIX(s2n_stuffer_init(&bytes_out_stuffer, &bytes_out_mem)); + RESULT_GUARD(s2n_stuffer_read_hex(&bytes_out_stuffer, &hex_in.blob)); + + *bytes_out = bytes_out_mem; + ZERO_TO_DISABLE_DEFER_CLEANUP(bytes_out_mem); + return S2N_RESULT_OK; +} diff --git a/tests/testlib/s2n_resumption_testlib.c b/tests/testlib/s2n_resumption_testlib.c index 561f231a85c..c219baa8658 100644 --- a/tests/testlib/s2n_resumption_testlib.c +++ b/tests/testlib/s2n_resumption_testlib.c @@ -21,7 +21,7 @@ S2N_RESULT s2n_resumption_test_ticket_key_setup(struct s2n_config *config) *# PRK = 0x077709362c2e32df0ddc3f0dc47bba63 *# 90b6c73bb50f9c3122ec844ad7c2b3e5 (32 octets) **/ - S2N_RESULT_BLOB_FROM_HEX(ticket_key, + S2N_CHECKED_BLOB_FROM_HEX(ticket_key, RESULT_GUARD, "077709362c2e32df0ddc3f0dc47bba63" "90b6c73bb50f9c3122ec844ad7c2b3e5"); diff --git a/tests/testlib/s2n_stuffer_testlib.c b/tests/testlib/s2n_stuffer_testlib.c deleted file mode 100644 index 60e911fb854..00000000000 --- a/tests/testlib/s2n_stuffer_testlib.c +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#include - -#include "error/s2n_errno.h" -#include "stuffer/s2n_stuffer.h" -#include "testlib/s2n_testlib.h" -#include "utils/s2n_safety.h" - -int s2n_stuffer_alloc_ro_from_hex_string(struct s2n_stuffer *stuffer, const char *str) -{ - DEFER_CLEANUP(struct s2n_blob hex = { 0 }, s2n_free); - /* Copying the hex into heap memory to handle the 'const' isn't exactly efficient, - * but for a testlib method it is sufficient. - */ - POSIX_GUARD(s2n_alloc(&hex, strlen(str))); - POSIX_CHECKED_MEMCPY(hex.data, str, hex.size); - - POSIX_GUARD(s2n_stuffer_alloc(stuffer, strlen(str) / 2)); - POSIX_GUARD_RESULT(s2n_stuffer_read_hex(stuffer, &hex)); - return S2N_SUCCESS; -} diff --git a/tests/testlib/s2n_testlib.h b/tests/testlib/s2n_testlib.h index eea219b71dc..cc9d5614035 100644 --- a/tests/testlib/s2n_testlib.h +++ b/tests/testlib/s2n_testlib.h @@ -23,8 +23,11 @@ extern const struct s2n_ecc_preferences ecc_preferences_for_retry; extern const struct s2n_security_policy security_policy_test_tls13_retry; -/* Stuffer methods for testing */ -int s2n_stuffer_alloc_ro_from_hex_string(struct s2n_stuffer *stuffer, const char *str); +/* Hex methods for testing */ +S2N_RESULT s2n_stuffer_alloc_from_hex(struct s2n_stuffer *stuffer, const char *str); +/* Unlike other hex methods, the hex string read here may include spaces. + * This is useful for hex strings with odd whitespace for readability purposes. */ +S2N_RESULT s2n_blob_alloc_from_hex_with_whitespace(struct s2n_blob *bytes_out, const char *str); void s2n_print_connection(struct s2n_connection *conn, const char *marker); @@ -287,3 +290,8 @@ int s2n_kem_recv_ciphertext_fuzz_test(const uint8_t *buf, size_t len, struct s2n int s2n_kem_recv_ciphertext_fuzz_test_init(const char *kat_file_path, struct s2n_kem_params *kem_params); S2N_RESULT s2n_resumption_test_ticket_key_setup(struct s2n_config *config); + +#define S2N_BLOB_FROM_HEX(name, hex) S2N_CHECKED_BLOB_FROM_HEX(name, POSIX_GUARD_RESULT, hex) +#define S2N_CHECKED_BLOB_FROM_HEX(name, check, hex) \ + DEFER_CLEANUP(struct s2n_blob name = { 0 }, s2n_free); \ + check(s2n_blob_alloc_from_hex_with_whitespace(&name, (const char *) hex)); diff --git a/tests/unit/s2n_blob_test.c b/tests/unit/s2n_blob_test.c index 48aed4ea74f..5db247d4b32 100644 --- a/tests/unit/s2n_blob_test.c +++ b/tests/unit/s2n_blob_test.c @@ -104,60 +104,5 @@ int main(int argc, char **argv) EXPECT_EQUAL(memcmp(g8.data, world, sizeof(world)), 0); EXPECT_EQUAL(g8.size, sizeof(world)); - /* Test s2n_hex_string_to_bytes */ - { - uint8_t test_mem[10] = { 0 }; - - /* Test with output buffer too small */ - { - const uint8_t long_input_str[] = "abcdef123456"; - struct s2n_blob output_blob = { 0 }; - - /* Succeeds with output blob of the right size */ - EXPECT_SUCCESS(s2n_blob_init(&output_blob, test_mem, sizeof(long_input_str) / 2)); - EXPECT_SUCCESS(s2n_hex_string_to_bytes(long_input_str, &output_blob)); - - /* Fails with output blob that's too small */ - EXPECT_SUCCESS(s2n_blob_init(&output_blob, test_mem, 1)); - EXPECT_FAILURE_WITH_ERRNO(s2n_hex_string_to_bytes(long_input_str, &output_blob), - S2N_ERR_INVALID_HEX); - }; - - /* Test with invalid characters */ - { - struct s2n_blob output_blob = { 0 }; - EXPECT_SUCCESS(s2n_blob_init(&output_blob, test_mem, sizeof(test_mem))); - - EXPECT_SUCCESS(s2n_hex_string_to_bytes((const uint8_t *) "12", &output_blob)); - EXPECT_FAILURE_WITH_ERRNO(s2n_hex_string_to_bytes((const uint8_t *) "#2", &output_blob), - S2N_ERR_INVALID_HEX); - EXPECT_FAILURE_WITH_ERRNO(s2n_hex_string_to_bytes((const uint8_t *) "1#", &output_blob), - S2N_ERR_INVALID_HEX); - }; - - struct { - const char *input; - size_t expected_output_size; - uint8_t expected_output[sizeof(test_mem)]; - } test_cases[] = { - { .input = "abcd", .expected_output = { 171, 205 }, .expected_output_size = 2 }, - { .input = "ab cd", .expected_output = { 171, 205 }, .expected_output_size = 2 }, - { .input = " abcd", .expected_output = { 171, 205 }, .expected_output_size = 2 }, - { .input = "abcd ", .expected_output = { 171, 205 }, .expected_output_size = 2 }, - { .input = " ab cd ", .expected_output = { 171, 205 }, .expected_output_size = 2 }, - { .input = "", .expected_output = { 0 }, .expected_output_size = 0 }, - { .input = " ", .expected_output = { 0 }, .expected_output_size = 0 }, - { .input = "12 34 56 78 90", .expected_output = { 18, 52, 86, 120, 144 }, .expected_output_size = 5 }, - { .input = "1234567890", .expected_output = { 18, 52, 86, 120, 144 }, .expected_output_size = 5 }, - }; - for (size_t i = 0; i < s2n_array_len(test_cases); i++) { - struct s2n_blob actual_output = { 0 }; - EXPECT_SUCCESS(s2n_blob_init(&actual_output, test_mem, sizeof(test_mem))); - - EXPECT_SUCCESS(s2n_hex_string_to_bytes((const uint8_t *) test_cases[i].input, &actual_output)); - EXPECT_BYTEARRAY_EQUAL(actual_output.data, test_cases[i].expected_output, test_cases[i].expected_output_size); - } - }; - END_TEST(); } diff --git a/tests/unit/s2n_client_hello_retry_test.c b/tests/unit/s2n_client_hello_retry_test.c index 643e6d12bf7..222bd59c33a 100644 --- a/tests/unit/s2n_client_hello_retry_test.c +++ b/tests/unit/s2n_client_hello_retry_test.c @@ -284,7 +284,7 @@ int main(int argc, char **argv) /* Server responds with HRR indicating x25519+Kyber as choice for negotiation; * the last 6 bytes (0033 0002 2F39) are the key share extension with x25519+Kyber */ DEFER_CLEANUP(struct s2n_stuffer hrr = { 0 }, s2n_stuffer_free); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&hrr, + EXPECT_OK(s2n_stuffer_alloc_from_hex(&hrr, "0303CF21AD74E59A6111BE1D8C021E65B891C2A211167ABB8C5E079E09E2C8A8339C00130200000C002B00020304003300022F39")); EXPECT_SUCCESS(s2n_stuffer_copy(&hrr, &conn->handshake.io, s2n_stuffer_data_available(&hrr))); diff --git a/tests/unit/s2n_client_key_share_extension_pq_test.c b/tests/unit/s2n_client_key_share_extension_pq_test.c index 0308cde026a..6d397e3bfaf 100644 --- a/tests/unit/s2n_client_key_share_extension_pq_test.c +++ b/tests/unit/s2n_client_key_share_extension_pq_test.c @@ -435,7 +435,7 @@ int main() DEFER_CLEANUP(struct s2n_stuffer key_share_extension = { 0 }, s2n_stuffer_free); /* The key shares in this extension are fake - that's OK, the server should ignore the * KEM group ID and skip the share. */ - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&key_share_extension, + EXPECT_OK(s2n_stuffer_alloc_from_hex(&key_share_extension, /* Shares size: 12 bytes */ "000C" /* IANA ID for secp256r1_sikep434r3 */ diff --git a/tests/unit/s2n_drbg_test.c b/tests/unit/s2n_drbg_test.c index a90715f933b..4595ff79b6f 100644 --- a/tests/unit/s2n_drbg_test.c +++ b/tests/unit/s2n_drbg_test.c @@ -282,9 +282,9 @@ int check_drgb_version(s2n_drbg_mode mode, int (*generator)(void *, uint32_t), i DEFER_CLEANUP(struct s2n_stuffer personalization = { 0 }, s2n_stuffer_free); DEFER_CLEANUP(struct s2n_stuffer returned_bits = { 0 }, s2n_stuffer_free); DEFER_CLEANUP(struct s2n_stuffer reference_values = { 0 }, s2n_stuffer_free); - POSIX_GUARD(s2n_stuffer_alloc_ro_from_hex_string(&personalization, personalization_hex)); - POSIX_GUARD(s2n_stuffer_alloc_ro_from_hex_string(&returned_bits, returned_bits_hex)); - POSIX_GUARD(s2n_stuffer_alloc_ro_from_hex_string(&reference_values, reference_values_hex)); + POSIX_GUARD_RESULT(s2n_stuffer_alloc_from_hex(&personalization, personalization_hex)); + POSIX_GUARD_RESULT(s2n_stuffer_alloc_from_hex(&returned_bits, returned_bits_hex)); + POSIX_GUARD_RESULT(s2n_stuffer_alloc_from_hex(&reference_values, reference_values_hex)); for (int i = 0; i < 14; i++) { uint8_t ps[S2N_DRBG_MAX_SEED_SIZE] = { 0 }; @@ -428,7 +428,7 @@ int main(int argc, char **argv) EXPECT_OK(s2n_drbg_wipe(&aes256_pr_drbg)); /* Check everything against the NIST AES 128 vectors with prediction resistance */ - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&nist_aes128_reference_entropy, nist_aes128_reference_entropy_hex)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&nist_aes128_reference_entropy, nist_aes128_reference_entropy_hex)); EXPECT_SUCCESS(check_drgb_version(S2N_AES_128_CTR_NO_DF_PR, &nist_fake_128_entropy_data, 32, nist_aes128_reference_personalization_strings_hex, nist_aes128_reference_values_hex, nist_aes128_reference_returned_bits_hex)); @@ -438,8 +438,8 @@ int main(int argc, char **argv) /* Combine nist_aes256_reference_entropy_hex_part1 and nist_aes256_reference_entropy_hex_part2 to avoid C99 * string length limit. */ - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&temp1, nist_aes256_reference_entropy_hex_part1)); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&temp2, nist_aes256_reference_entropy_hex_part2)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&temp1, nist_aes256_reference_entropy_hex_part1)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&temp2, nist_aes256_reference_entropy_hex_part2)); EXPECT_SUCCESS(s2n_stuffer_alloc(&nist_aes256_reference_entropy, temp1.write_cursor + temp2.write_cursor)); EXPECT_SUCCESS(s2n_stuffer_copy(&temp1, &nist_aes256_reference_entropy, temp1.write_cursor)); EXPECT_SUCCESS(s2n_stuffer_copy(&temp2, &nist_aes256_reference_entropy, temp2.write_cursor)); diff --git a/tests/unit/s2n_hash_all_algs_test.c b/tests/unit/s2n_hash_all_algs_test.c index af4dc4963ff..f38ae72002e 100644 --- a/tests/unit/s2n_hash_all_algs_test.c +++ b/tests/unit/s2n_hash_all_algs_test.c @@ -145,10 +145,7 @@ int main(int argc, char **argv) uint8_t actual_result_data[OUTPUT_DATA_SIZE] = { 0 }; EXPECT_SUCCESS(s2n_blob_init(&actual_result, actual_result_data, OUTPUT_DATA_SIZE)); - struct s2n_blob expected_result = { 0 }; - uint8_t expected_result_data[OUTPUT_DATA_SIZE] = { 0 }; - EXPECT_SUCCESS(s2n_blob_init(&expected_result, expected_result_data, OUTPUT_DATA_SIZE)); - EXPECT_SUCCESS(s2n_hex_string_to_bytes((const uint8_t *) expected_result_hex[hash_alg], &expected_result)); + S2N_CHECKED_BLOB_FROM_HEX(expected_result, EXPECT_OK, expected_result_hex[hash_alg]); EXPECT_OK(s2n_hash_test(hash_alg, &actual_result)); EXPECT_EQUAL(expected_result.size, actual_result.size); diff --git a/tests/unit/s2n_override_openssl_random_test.c b/tests/unit/s2n_override_openssl_random_test.c index 823cecf9315..765d806b525 100644 --- a/tests/unit/s2n_override_openssl_random_test.c +++ b/tests/unit/s2n_override_openssl_random_test.c @@ -98,7 +98,7 @@ int main(int argc, char **argv) EXPECT_SUCCESS(s2n_pkcs3_to_dh_params(&dh_params, &b)); /* Set s2n_random to use a new fixed DRBG to test that other known answer tests with s2n_random and OpenSSL are deterministic */ - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&test_entropy, reference_entropy_hex)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&test_entropy, reference_entropy_hex)); struct s2n_drbg drbg; EXPECT_SUCCESS(s2n_rand_set_callbacks(s2n_entropy_init_cleanup, s2n_entropy_init_cleanup, s2n_entropy_generator, s2n_entropy_generator)); @@ -119,7 +119,7 @@ int main(int argc, char **argv) EXPECT_EQUAL(bytes_used, 352); DEFER_CLEANUP(struct s2n_stuffer dhe_key_stuffer = { 0 }, s2n_stuffer_free); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&dhe_key_stuffer, expected_dhe_key_hex)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&dhe_key_stuffer, expected_dhe_key_hex)); EXPECT_EQUAL(dhe_key_stuffer.blob.size, 519); EXPECT_EQUAL(out_blob.size, 519); diff --git a/tests/unit/s2n_rsa_pss_rsae_test.c b/tests/unit/s2n_rsa_pss_rsae_test.c index 132ffc0c5d0..fe0c46d8f6d 100644 --- a/tests/unit/s2n_rsa_pss_rsae_test.c +++ b/tests/unit/s2n_rsa_pss_rsae_test.c @@ -318,8 +318,8 @@ int main(int argc, char **argv) RSA_free(rsa_key_copy); struct s2n_stuffer message_stuffer = { 0 }, signature_stuffer = { 0 }; - s2n_stuffer_alloc_ro_from_hex_string(&message_stuffer, test_case.message); - s2n_stuffer_alloc_ro_from_hex_string(&signature_stuffer, test_case.signature); + POSIX_GUARD_RESULT(s2n_stuffer_alloc_from_hex(&message_stuffer, test_case.message)); + POSIX_GUARD_RESULT(s2n_stuffer_alloc_from_hex(&signature_stuffer, test_case.signature)); hash_state_for_alg_new(verify_hash, test_case.hash_alg, message_stuffer.blob); int ret_val = rsa_public_key.verify(&rsa_public_key, S2N_SIGNATURE_RSA_PSS_RSAE, diff --git a/tests/unit/s2n_self_talk_key_log_test.c b/tests/unit/s2n_self_talk_key_log_test.c index b0269bf0175..a74d76db310 100644 --- a/tests/unit/s2n_self_talk_key_log_test.c +++ b/tests/unit/s2n_self_talk_key_log_test.c @@ -176,7 +176,9 @@ int main(int argc, char **argv) DEFER_CLEANUP(struct s2n_stuffer encoded, s2n_stuffer_free); EXPECT_SUCCESS(s2n_stuffer_alloc(&encoded, sizeof(bytes) * 2)); - EXPECT_OK(s2n_key_log_hex_encode(&encoded, bytes, sizeof(bytes))); + struct s2n_blob raw_bytes = { 0 }; + EXPECT_SUCCESS(s2n_blob_init(&raw_bytes, bytes, sizeof(bytes))); + EXPECT_OK(s2n_stuffer_write_hex(&encoded, &raw_bytes)); DEFER_CLEANUP(struct s2n_stuffer decoded, s2n_stuffer_free); EXPECT_SUCCESS(s2n_stuffer_alloc(&decoded, sizeof(bytes))); diff --git a/tests/unit/s2n_server_key_share_extension_test.c b/tests/unit/s2n_server_key_share_extension_test.c index 962ffbd77f0..7f2d46f15fe 100644 --- a/tests/unit/s2n_server_key_share_extension_test.c +++ b/tests/unit/s2n_server_key_share_extension_test.c @@ -259,7 +259,7 @@ int main(int argc, char **argv) const char *payload = key_share_payloads[i]; EXPECT_NULL(client_conn->kex_params.server_ecc_evp_params.negotiated_curve); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&extension_stuffer, payload)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&extension_stuffer, payload)); client_conn->kex_params.client_ecc_evp_params.negotiated_curve = ecc_pref->ecc_curves[i]; EXPECT_SUCCESS(s2n_ecc_evp_generate_ephemeral_key(&client_conn->kex_params.client_ecc_evp_params)); @@ -289,7 +289,7 @@ int main(int argc, char **argv) const char *payload = key_share_payloads[0]; EXPECT_NULL(client_conn->kex_params.server_ecc_evp_params.negotiated_curve); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&extension_stuffer, payload)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&extension_stuffer, payload)); client_conn->kex_params.client_ecc_evp_params.negotiated_curve = ecc_pref->ecc_curves[0]; EXPECT_SUCCESS(s2n_ecc_evp_generate_ephemeral_key(&client_conn->kex_params.client_ecc_evp_params)); @@ -318,7 +318,7 @@ int main(int argc, char **argv) const char *p256 = "001700410474cfd75c0ab7b57247761a277e1c92b5810dacb251bb758f43e9d15aaf292c4a2be43e886425ba55653ebb7a4f32fe368bacce3df00c618645cf1eb6"; EXPECT_NULL(client_conn->kex_params.server_ecc_evp_params.negotiated_curve); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&extension_stuffer, p256)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&extension_stuffer, p256)); EXPECT_FAILURE_WITH_ERRNO(s2n_server_key_share_extension.recv(client_conn, &extension_stuffer), S2N_ERR_BAD_KEY_SHARE); @@ -339,7 +339,7 @@ int main(int argc, char **argv) const char *p256 = "001700410474cfd75c0ab7b57247761a277e1c92b5810dacb251bb758f43e9d15aaf292c4a2be43e886425ba55653ebb7a4f32fe368bacce3df00c618645cf1eb646f22552"; EXPECT_NULL(client_conn->kex_params.server_ecc_evp_params.negotiated_curve); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&extension_stuffer, p256)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&extension_stuffer, p256)); /* If s2n_is_evp_apis_supported is not supported, the ecc_prefs->ecc_curves contains only p-256, p-384 curves. */ int p_384_index = s2n_is_evp_apis_supported() ? 2 : 1; @@ -647,7 +647,7 @@ int main(int argc, char **argv) /* In the HRR, the server indicated p256+Kyber as it's choice in the key share extension */ const struct s2n_kem_group *kem_group = &s2n_secp256r1_kyber_512_r3; DEFER_CLEANUP(struct s2n_stuffer key_share_payload = { 0 }, s2n_stuffer_free); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&key_share_payload, "2F3A")); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&key_share_payload, "2F3A")); /* Client should successfully parse the indicated group */ EXPECT_SUCCESS(s2n_server_key_share_extension.recv(client_conn, &key_share_payload)); @@ -689,14 +689,14 @@ int main(int argc, char **argv) /* Server sends a named group identifier that isn't in the client's KEM preferences */ const char *bad_group = "2F2C"; /* IANA ID for secp256r1_threebears-babybear-r2 (not imported into s2n) */ DEFER_CLEANUP(struct s2n_stuffer bad_group_stuffer = { 0 }, s2n_stuffer_free); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&bad_group_stuffer, bad_group)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&bad_group_stuffer, bad_group)); EXPECT_FAILURE_WITH_ERRNO(s2n_server_key_share_extension.recv(client_conn, &bad_group_stuffer), S2N_ERR_ECDHE_UNSUPPORTED_CURVE); /* Server sends a key share that is in the client's KEM preferences, but client didn't send a key share */ const char *wrong_share = "2F1F"; /* Full extension truncated - not necessary */ DEFER_CLEANUP(struct s2n_stuffer wrong_share_stuffer = { 0 }, s2n_stuffer_free); - EXPECT_SUCCESS(s2n_stuffer_alloc_ro_from_hex_string(&wrong_share_stuffer, wrong_share)); + EXPECT_OK(s2n_stuffer_alloc_from_hex(&wrong_share_stuffer, wrong_share)); EXPECT_FAILURE_WITH_ERRNO(s2n_server_key_share_extension.recv(client_conn, &wrong_share_stuffer), S2N_ERR_ECDHE_UNSUPPORTED_CURVE); diff --git a/tests/unit/s2n_testlib_test.c b/tests/unit/s2n_testlib_test.c index 7dbd2da11e4..f5f7b8b9df0 100644 --- a/tests/unit/s2n_testlib_test.c +++ b/tests/unit/s2n_testlib_test.c @@ -43,5 +43,30 @@ int main(int argc, char **argv) EXPECT_SUCCESS(s2n_connection_free(server_conn)); }; + /* Test s2n_blob_alloc_from_hex_with_whitespace */ + { + struct { + const char *input; + size_t expected_output_size; + uint8_t expected_output[100]; + } test_cases[] = { + { .input = "abcd", .expected_output = { 171, 205 }, .expected_output_size = 2 }, + { .input = "ab cd", .expected_output = { 171, 205 }, .expected_output_size = 2 }, + { .input = " abcd", .expected_output = { 171, 205 }, .expected_output_size = 2 }, + { .input = "abcd ", .expected_output = { 171, 205 }, .expected_output_size = 2 }, + { .input = " ab cd ", .expected_output = { 171, 205 }, .expected_output_size = 2 }, + { .input = "", .expected_output = { 0 }, .expected_output_size = 0 }, + { .input = " ", .expected_output = { 0 }, .expected_output_size = 0 }, + { .input = "12 34 56 78 90", .expected_output = { 18, 52, 86, 120, 144 }, .expected_output_size = 5 }, + { .input = "1234567890", .expected_output = { 18, 52, 86, 120, 144 }, .expected_output_size = 5 }, + }; + for (size_t i = 0; i < s2n_array_len(test_cases); i++) { + DEFER_CLEANUP(struct s2n_blob actual_output = { 0 }, s2n_free); + EXPECT_OK(s2n_blob_alloc_from_hex_with_whitespace(&actual_output, test_cases[i].input)); + EXPECT_EQUAL(actual_output.size, test_cases[i].expected_output_size); + EXPECT_BYTEARRAY_EQUAL(actual_output.data, test_cases[i].expected_output, actual_output.size); + } + }; + END_TEST(); } diff --git a/tests/unit/s2n_tls13_server_cert_test.c b/tests/unit/s2n_tls13_server_cert_test.c index da9e6e6994d..c18ab419dfb 100644 --- a/tests/unit/s2n_tls13_server_cert_test.c +++ b/tests/unit/s2n_tls13_server_cert_test.c @@ -123,11 +123,8 @@ int main(int argc, char **argv) EXPECT_NOT_NULL(tls13_cert_chain_hex = malloc(S2N_MAX_TEST_PEM_SIZE)); strcpy(tls13_cert_chain_hex, tls13_cert_chain_header_hex); strcat(tls13_cert_chain_hex, tls13_cert_hex); - /* convert certificate chain hex to bytes*/ - struct s2n_blob tls13_cert = { 0 }; - EXPECT_SUCCESS(s2n_alloc(&tls13_cert, strlen(tls13_cert_chain_hex) / 2)); - POSIX_GUARD(s2n_hex_string_to_bytes((uint8_t *) tls13_cert_chain_hex, &tls13_cert)); + S2N_BLOB_FROM_HEX(tls13_cert, tls13_cert_chain_hex); S2N_BLOB_FROM_HEX(tls13_cert_chain, tls13_cert_hex); struct s2n_connection *conn = NULL; @@ -164,8 +161,6 @@ int main(int argc, char **argv) EXPECT_SUCCESS(s2n_connection_free(conn)); free(tls13_cert_chain_hex); - /* free memory allocated in s2n_alloc*/ - free(tls13_cert.data); } /* Test server sends cert and client receives cert for tls 1.3 */ diff --git a/tls/s2n_key_log.c b/tls/s2n_key_log.c index 75ef3db618f..f135ea31ba1 100644 --- a/tls/s2n_key_log.c +++ b/tls/s2n_key_log.c @@ -50,24 +50,6 @@ /* hex requires 2 chars per byte */ #define HEX_ENCODING_SIZE 2 -S2N_RESULT s2n_key_log_hex_encode(struct s2n_stuffer *output, uint8_t *bytes, size_t len) -{ - RESULT_ENSURE_MUT(output); - RESULT_ENSURE_REF(bytes); - - const uint8_t chars[] = "0123456789abcdef"; - - for (size_t i = 0; i < len; i++) { - uint8_t upper = bytes[i] >> 4; - uint8_t lower = bytes[i] & 0x0f; - - RESULT_GUARD_POSIX(s2n_stuffer_write_uint8(output, chars[upper])); - RESULT_GUARD_POSIX(s2n_stuffer_write_uint8(output, chars[lower])); - } - - return S2N_RESULT_OK; -} - S2N_RESULT s2n_key_log_tls13_secret(struct s2n_connection *conn, const struct s2n_blob *secret, s2n_secret_type_t secret_type) { RESULT_ENSURE_REF(conn); @@ -127,10 +109,14 @@ S2N_RESULT s2n_key_log_tls13_secret(struct s2n_connection *conn, const struct s2 DEFER_CLEANUP(struct s2n_stuffer output, s2n_stuffer_free); RESULT_GUARD_POSIX(s2n_stuffer_alloc(&output, len)); + struct s2n_blob client_random = { 0 }; + RESULT_GUARD_POSIX(s2n_blob_init(&client_random, conn->handshake_params.client_random, + sizeof(conn->handshake_params.client_random))); + RESULT_GUARD_POSIX(s2n_stuffer_write_bytes(&output, label, label_size)); - RESULT_GUARD(s2n_key_log_hex_encode(&output, conn->handshake_params.client_random, S2N_TLS_RANDOM_DATA_LEN)); + RESULT_GUARD(s2n_stuffer_write_hex(&output, &client_random)); RESULT_GUARD_POSIX(s2n_stuffer_write_uint8(&output, ' ')); - RESULT_GUARD(s2n_key_log_hex_encode(&output, secret->data, secret->size)); + RESULT_GUARD(s2n_stuffer_write_hex(&output, secret)); uint8_t *data = s2n_stuffer_raw_read(&output, len); RESULT_ENSURE_REF(data); @@ -162,10 +148,18 @@ S2N_RESULT s2n_key_log_tls12_secret(struct s2n_connection *conn) DEFER_CLEANUP(struct s2n_stuffer output, s2n_stuffer_free); RESULT_GUARD_POSIX(s2n_stuffer_alloc(&output, len)); + struct s2n_blob client_random = { 0 }; + RESULT_GUARD_POSIX(s2n_blob_init(&client_random, conn->handshake_params.client_random, + sizeof(conn->handshake_params.client_random))); + + struct s2n_blob master_secret = { 0 }; + RESULT_GUARD_POSIX(s2n_blob_init(&master_secret, conn->secrets.version.tls12.master_secret, + sizeof(conn->secrets.version.tls12.master_secret))); + RESULT_GUARD_POSIX(s2n_stuffer_write_bytes(&output, label, label_size)); - RESULT_GUARD(s2n_key_log_hex_encode(&output, conn->handshake_params.client_random, S2N_TLS_RANDOM_DATA_LEN)); + RESULT_GUARD(s2n_stuffer_write_hex(&output, &client_random)); RESULT_GUARD_POSIX(s2n_stuffer_write_uint8(&output, ' ')); - RESULT_GUARD(s2n_key_log_hex_encode(&output, conn->secrets.version.tls12.master_secret, S2N_TLS_SECRET_LEN)); + RESULT_GUARD(s2n_stuffer_write_hex(&output, &master_secret)); uint8_t *data = s2n_stuffer_raw_read(&output, len); RESULT_ENSURE_REF(data); diff --git a/tls/s2n_key_log.h b/tls/s2n_key_log.h index 02d39a8e704..9f07dfb5531 100644 --- a/tls/s2n_key_log.h +++ b/tls/s2n_key_log.h @@ -21,6 +21,5 @@ #include "utils/s2n_blob.h" #include "utils/s2n_safety.h" -S2N_RESULT s2n_key_log_hex_encode(struct s2n_stuffer *output, uint8_t *bytes, size_t len); S2N_RESULT s2n_key_log_tls12_secret(struct s2n_connection *conn); S2N_RESULT s2n_key_log_tls13_secret(struct s2n_connection *conn, const struct s2n_blob *secret, s2n_secret_type_t secret_type); diff --git a/utils/s2n_blob.c b/utils/s2n_blob.c index 2c3997ae746..58cd7b0a72b 100644 --- a/utils/s2n_blob.c +++ b/utils/s2n_blob.c @@ -78,59 +78,3 @@ int s2n_blob_char_to_lower(struct s2n_blob *b) POSIX_POSTCONDITION(s2n_blob_validate(b)); return S2N_SUCCESS; } - -/* An inverse map from an ascii value to a hexidecimal nibble value - * accounts for all possible char values, where 255 is invalid value */ -static const uint8_t hex_inverse[256] = { - /* clang-format off */ - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 - /* clang-format on */ -}; - -/* takes a hex string and writes values in the s2n_blob - * string needs to a valid hex and blob needs to be large enough */ -int s2n_hex_string_to_bytes(const uint8_t *str, struct s2n_blob *blob) -{ - POSIX_ENSURE_REF(str); - POSIX_PRECONDITION(s2n_blob_validate(blob)); - uint32_t len_with_spaces = strlen((const char *) str); - - size_t i = 0, j = 0; - while (j < len_with_spaces) { - if (str[j] == ' ') { - j++; - continue; - } - - uint8_t high_nibble = hex_inverse[str[j]]; - POSIX_ENSURE(high_nibble != 255, S2N_ERR_INVALID_HEX); - - uint8_t low_nibble = hex_inverse[str[j + 1]]; - POSIX_ENSURE(low_nibble != 255, S2N_ERR_INVALID_HEX); - - POSIX_ENSURE(i < blob->size, S2N_ERR_INVALID_HEX); - blob->data[i] = high_nibble << 4 | low_nibble; - - i++; - j += 2; - } - blob->size = i; - - POSIX_POSTCONDITION(s2n_blob_validate(blob)); - return S2N_SUCCESS; -} diff --git a/utils/s2n_blob.h b/utils/s2n_blob.h index 8f9481affbc..25e6b7a7646 100644 --- a/utils/s2n_blob.h +++ b/utils/s2n_blob.h @@ -43,7 +43,6 @@ S2N_RESULT s2n_blob_validate(const struct s2n_blob *b); int S2N_RESULT_MUST_USE s2n_blob_init(struct s2n_blob *b, uint8_t *data, uint32_t size); int s2n_blob_zero(struct s2n_blob *b); int S2N_RESULT_MUST_USE s2n_blob_char_to_lower(struct s2n_blob *b); -int S2N_RESULT_MUST_USE s2n_hex_string_to_bytes(const uint8_t *str, struct s2n_blob *blob); int S2N_RESULT_MUST_USE s2n_blob_slice(const struct s2n_blob *b, struct s2n_blob *slice, uint32_t offset, uint32_t size); #define s2n_stack_blob(name, requested_size, maximum) \ @@ -63,15 +62,3 @@ int S2N_RESULT_MUST_USE s2n_blob_slice(const struct s2n_blob *b, struct s2n_blob #define S2N_BLOB_LABEL(name, str) \ static uint8_t name##_data[] = str; \ const struct s2n_blob name = { .data = name##_data, .size = sizeof(name##_data) - 1 }; - -/* The S2N_BLOB_FROM_HEX macro creates a s2n_blob with the contents of a hex string. - * It is allocated on a stack so there no need to free after use. - * hex should be a const char[]. This function checks against using char*, - * because sizeof needs to refer to the buffer length rather than a pointer size */ -#define S2N_BLOB_FROM_HEX(name, hex) \ - s2n_stack_blob(name, (sizeof(hex) - 1) / 2, (sizeof(hex) - 1) / 2); \ - POSIX_GUARD(s2n_hex_string_to_bytes((const uint8_t *) hex, &name)); - -#define S2N_RESULT_BLOB_FROM_HEX(name, hex) \ - RESULT_STACK_BLOB(name, (sizeof(hex) - 1) / 2, (sizeof(hex) - 1) / 2); \ - RESULT_GUARD_POSIX(s2n_hex_string_to_bytes((const uint8_t *) hex, &name));