From 88b9faa917eab375205640c179ff7b29aadb7cb1 Mon Sep 17 00:00:00 2001 From: Emma Stensland Date: Mon, 12 Oct 2026 10:38:35 -0600 Subject: [PATCH] Add FDO client-sdk-fidoiot patch for wolfSSL Adds a wolfSSL crypto/TLS backend and optional wolfTPM attestation to the archived FDO Client SDK, based on its final commit 40e5024. --- ...024d46472020f3e7811dae9f40b0644c17f4.patch | 13384 ++++++++++++++++ client-sdk-fidoiot/README.md | 85 + 2 files changed, 13469 insertions(+) create mode 100644 client-sdk-fidoiot/2025-08-06-40e5024d46472020f3e7811dae9f40b0644c17f4.patch create mode 100644 client-sdk-fidoiot/README.md diff --git a/client-sdk-fidoiot/2025-08-06-40e5024d46472020f3e7811dae9f40b0644c17f4.patch b/client-sdk-fidoiot/2025-08-06-40e5024d46472020f3e7811dae9f40b0644c17f4.patch new file mode 100644 index 00000000..60eb6d00 --- /dev/null +++ b/client-sdk-fidoiot/2025-08-06-40e5024d46472020f3e7811dae9f40b0644c17f4.patch @@ -0,0 +1,13384 @@ +diff --git a/.github/Dockerfile b/.github/Dockerfile +index 73d903e..b47791a 100644 +--- a/.github/Dockerfile ++++ b/.github/Dockerfile +@@ -1,16 +1,28 @@ + FROM ubuntu:22.04 + ++# Select the crypto/TLS backend: "openssl" (default) or "wolfssl". ++# Build with: docker build --build-arg TLS_BACKEND=wolfssl -f .github/Dockerfile . ++ARG TLS_BACKEND=openssl ++# Promote ARG to ENV for CMD visibility. ++ENV TLS_BACKEND=${TLS_BACKEND} ++ ++# Device-attestation method used by the wolfSSL CMD branch (e.g. ecdsa384, ++# cse_ecdsa384). The openssl branch's build.sh always builds the full DA ++# matrix, including the cse_* variants, so this only affects wolfssl builds. ++# Build with: docker build --build-arg TLS_BACKEND=wolfssl --build-arg DA=cse_ecdsa384 -f .github/Dockerfile . ++ARG DA=ecdsa384 ++ENV DA=${DA} ++ + ENV DEBIAN_FRONTEND=noninteractive + ++# NOTE: openssl packages are only for the openssl backend. ++# wolfssl builds its own curl. + RUN apt-get update -y && apt-get upgrade -y && apt-get install -y \ + git \ + build-essential \ + cmake \ + libxml2-dev \ + uuid-dev \ +- libcurl4-openssl-dev \ +- openssl \ +- libssl-dev \ + wget \ + bsdmainutils \ + unzip \ +@@ -18,14 +30,25 @@ RUN apt-get update -y && apt-get upgrade -y && apt-get install -y \ + xxd \ + nghttp2 \ + libnghttp2-dev \ +- ruby ++ autoconf \ ++ libtool \ ++ ruby \ ++ $(if [ "$TLS_BACKEND" = "openssl" ]; then echo "libcurl4-openssl-dev openssl libssl-dev"; fi) + + RUN mkdir build_dir + +-# Build & Install Curl version 8.1.2 ++# Narrow COPY to preserve cache for dependency layers. ++WORKDIR /build_dir/fdoout/client-sdk/ ++COPY utils/install_wolfssl_curl.sh utils/install_wolfssl_curl.sh ++ ++# Build & Install Curl, linked against the selected TLS backend. + WORKDIR /build_dir/ +-RUN wget https://curl.se/download/curl-8.1.2.tar.gz -O - | tar -xz && cd curl-8.1.2 && \ +-./configure --with-openssl --enable-versioned-symbols --with-nghttp2 && make && make install ++RUN if [ "$TLS_BACKEND" = "wolfssl" ]; then \ ++ bash /build_dir/fdoout/client-sdk/utils/install_wolfssl_curl.sh -i -v 5.9.4; \ ++ else \ ++ wget https://curl.se/download/curl-8.1.2.tar.gz -O - | tar -xz && cd curl-8.1.2 && \ ++ ./configure --with-openssl --enable-versioned-symbols --with-nghttp2 && make && make install; \ ++ fi + + # Setup safestring + WORKDIR /build_dir +@@ -41,31 +64,53 @@ ENV TINYCBOR_ROOT /build_dir/tinycbor + WORKDIR ${TINYCBOR_ROOT} + RUN make + +-# Setup metee ++# Setup metee: required whenever DA selects CSE (regardless of TLS backend), ++# and unconditionally for the openssl backend since build.sh always builds ++# the full DA matrix, including the cse_* variants. + WORKDIR /build_dir +-RUN git clone --progress --verbose https://github.com/intel/metee.git metee ++RUN if [ "$TLS_BACKEND" = "openssl" ] || (echo "$DA" | grep -q cse); then \ ++ git clone --progress --verbose https://github.com/intel/metee.git metee && \ ++ cd metee && cmake . && make && make install; \ ++ fi + ENV METEE_ROOT /build_dir/metee +-WORKDIR ${METEE_ROOT} +-RUN cmake . && make && make install + + ENV OPENSSL3_ROOT /usr +-ENV CURL_ROOT /usr ++# CURL_ROOT/WOLFSSL_ROOT are backend-dependent, set below in CMD. + +-# Setup client-sdk-fidoiot. +-# clone client-sdk-fidoiot to the current Dockerfile directory ++# Setup client-sdk-fidoiot. Full source copy here preserves cache. + WORKDIR /build_dir/ + RUN mkdir /cse-fdoout + WORKDIR /build_dir/cse-fdoout/ +-RUN mkdir /client-sdk ++RUN mkdir /client-sdk + WORKDIR /build_dir/fdoout/client-sdk/ + COPY . . + +-# Install tpm libraries +-RUN grep -rl '/opt/openssl' ./ | xargs sed -i 's/\/opt\/openssl/\/usr/g' +-RUN grep -rl '/opt/curl' ./ | xargs sed -i 's/\/opt\/curl/\/usr/g' +-RUN sed -i 's/lib64/lib\/x86_64-linux-gnu/' utils/install_tpm_libs.sh +-RUN sed -i 's/==/-eq/' utils/tpm_make_ready_ecdsa.sh +-RUN sh utils/install_tpm_libs.sh -i ++RUN if [ "$TLS_BACKEND" = "openssl" ]; then \ ++ grep -rl '/opt/openssl' ./ | xargs sed -i 's/\/opt\/openssl/\/usr/g'; \ ++ grep -rl '/opt/curl' ./ | xargs sed -i 's/\/opt\/curl/\/usr/g'; \ ++ sed -i 's/lib64/lib\/x86_64-linux-gnu/' utils/install_tpm_libs.sh; \ ++ sh utils/install_tpm_libs.sh -i; \ ++ fi + ++# wolfTPM for TPM_STACK=wolftpm (the wolfSSL default), built against the ++# wolfSSL installed above. fwTPM is disabled: it isn't used and fails -Werror. ++WORKDIR /build_dir ++RUN if [ "$TLS_BACKEND" = "wolfssl" ]; then \ ++ git clone --depth 1 -b v4.2.0 https://github.com/wolfSSL/wolfTPM.git wolftpm && \ ++ cd wolftpm && ./autogen.sh && \ ++ ./configure --prefix=/opt/wolftpm --with-wolfcrypt=/opt/wolfssl \ ++ --enable-devtpm --disable-fwtpm && \ ++ make -j"$(nproc)" && make install; \ ++ fi ++ENV WOLFTPM_ROOT /opt/wolftpm ++WORKDIR /build_dir/fdoout/client-sdk/ ++RUN sed -i 's/==/-eq/' utils/tpm_make_ready_ecdsa.sh + +-CMD ["bash", "build.sh"] +\ No newline at end of file ++CMD if [ "$TLS_BACKEND" = "wolfssl" ]; then \ ++ export CURL_ROOT=/opt/curl WOLFSSL_ROOT=/opt/wolfssl; \ ++ make pristine || true; \ ++ cmake -DTLS=wolfssl -DDA=${DA} -DAES_MODE=gcm . && make -j$(nproc); \ ++ else \ ++ export CURL_ROOT=/usr; \ ++ bash build.sh; \ ++ fi +diff --git a/.github/build_wolfssl_ci.sh b/.github/build_wolfssl_ci.sh +new file mode 100755 +index 0000000..e9fc7dd +--- /dev/null ++++ b/.github/build_wolfssl_ci.sh +@@ -0,0 +1,42 @@ ++#!/bin/bash -x ++# ++# Copyright 2026 wolfSSL Inc. ++# SPDX-License-Identifier: Apache-2.0 ++# ++# ++# Run wolfSSL backend unit tests in CI docker. ++set -e -x -o pipefail ++ ++export CURL_ROOT=/opt/curl ++export WOLFSSL_ROOT=/opt/wolfssl ++export WOLFTPM_ROOT=/opt/wolftpm ++ ++# Keep output out of build/ to avoid wipe by pristine. ++TEST_OUTPUT="unit-test-output.txt" ++rm -f "$TEST_OUTPUT" ++COMMON_TEST_CONFIG="-Dunit-test=true -DTLS=wolfssl -DHTTPPROXY=true -DBUILD=release" ++ ++# Run unit tests ++function run_unit_test ++{ ++ make pristine || true ++ cmake ${COMMON_TEST_CONFIG} "$@" . ++ make -j"$(nproc)" | tee -a "$TEST_OUTPUT" ++} ++ ++run_unit_test -DDA=ecdsa256 -DAES_MODE=gcm ++run_unit_test -DDA=ecdsa256 -DAES_MODE=ccm ++run_unit_test -DDA=ecdsa384 -DAES_MODE=gcm ++run_unit_test -DDA=ecdsa384 -DAES_MODE=ccm ++run_unit_test -DDA=ecdsa256 -DAES_MODE=gcm -DDA_FILE=pem ++# No TPM in the container: run only the wolfTPM tests, which mock the TPM. ++# The other tests built for a TPM DA sign and HMAC through a real device. ++run_unit_test -DDA=tpm20_ecdsa256 -DAES_MODE=gcm -DUNIT_TEST_ONLY=^test_wolftpm_ ++run_unit_test -DDA=tpm20_ecdsa384 -DAES_MODE=gcm -DUNIT_TEST_ONLY=^test_wolftpm_ ++ ++# DO NOT change AWK string; spaces are intentional. ++fail_count=$(awk '/Tests Failed :/ {split($0,a,": "); count+=a[2]} END{print count+0}' "$TEST_OUTPUT") ++echo "Found $fail_count unit-test failure(s)." ++ ++# Raw counts wrap modulo 256 as exit codes. ++exit $(( fail_count > 0 ? 1 : 0 )) +diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml +index eb98a68..fa8c74c 100644 +--- a/.github/workflows/main.yaml ++++ b/.github/workflows/main.yaml +@@ -8,6 +8,17 @@ on: + permissions: + contents: read + jobs: ++ build-wolfssl: ++ runs-on: ubuntu-latest ++ steps: ++ - name: scm checkout ++ uses: actions/checkout@v4 ++ - name: Build wolfSSL backend docker image ++ run: docker build -t client-sdk-wolfssl --build-arg TLS_BACKEND=wolfssl -f '.github/Dockerfile' . ++ - name: Build and test wolfSSL backend ++ run: | ++ docker run -v $PWD:/build_dir/fdoout/client-sdk/ client-sdk-wolfssl:latest \ ++ bash .github/build_wolfssl_ci.sh + build: + runs-on: ubuntu-latest + steps: +diff --git a/.gitignore b/.gitignore +index 7d7a6df..1023cec 100644 +--- a/.gitignore ++++ b/.gitignore +@@ -148,3 +148,49 @@ outdir/ + *.dat.h + *.bin.h + *.mp.h ++ ++# Python bytecode cache # ++########################## ++__pycache__/ ++*.pyc ++/wolfssl-*-stable/ ++/wolfTPM/ ++/curl-*/ ++/wolfssl-install/ ++/wolftpm-install/ ++/curl-install/ ++/tpm2-tools-*/ ++/linux-client-* ++/report.xml ++ ++# Local dependencies cloned by utils/setup_local_dependencies.sh # ++################################################################## ++/safestringlib/ ++/tinycbor/ ++ ++# mbedOS component tree generated by mbedos/CMakeLists.txt # ++############################################################ ++# mbed deploy pulls mbed-os in from mbedos/components/fdo/mbed-os.lib ++/mbedos/components/fdo/mbed-os/ ++# The mbed-os pin itself must be tracked despite the *.lib rule above. ++!/mbedos/components/fdo/mbed-os.lib ++# Copied from mbed_app.json_fdo_only (or _pelion) at build time. ++/mbedos/components/fdo/fdo/mbed_app.json ++# create_symlink targets - these point back into the source tree ++/mbedos/components/fdo/crypto ++/mbedos/components/fdo/data ++/mbedos/components/fdo/fdo/app_main.c ++/mbedos/components/fdo/fdo/blob.c ++/mbedos/components/fdo/fdo/blob.h ++/mbedos/components/fdo/fdo_sys ++/mbedos/components/fdo/include ++/mbedos/components/fdo/lib ++/mbedos/components/fdo/network ++/mbedos/components/fdo/safestring ++/mbedos/components/fdo/storage ++/mbedos/components/fdo/tinycbor ++/mbedos/components/fdo/wolfssl ++/mbedos/components/fdo/*-src/ ++ ++# Generated by mbedos/CMakeLists.txt at configure time # ++**/.mbedignore +diff --git a/CMakeLists.txt b/CMakeLists.txt +index ba92a18..af8f875 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -16,25 +16,83 @@ include(cmake/cli_input.cmake) + include(cmake/extension.cmake) + include(cmake/blob_path.cmake) + +-if (NOT(DEFINED ENV{OPENSSL3_ROOT})) +- message(FATAL_ERROR "OPENSSL3_ROOT not set") +-endif() ++# Shared auto-discovery helper. Returns first valid path. ++macro(find_root_dir out_var error_msg) ++ set(_found FALSE) ++ foreach(_entry ${ARGN}) ++ if (NOT _found) ++ string(REPLACE "|" ";" _pair "${_entry}") ++ list(GET _pair 0 _check) ++ list(GET _pair 1 _root) ++ if (EXISTS "${_check}") ++ set(ENV{${out_var}} "${_root}") ++ set(_found TRUE) ++ endif() ++ endif() ++ endforeach() ++ if (NOT _found) ++ message(FATAL_ERROR "${error_msg}") ++ endif() ++endmacro() + +-if (NOT(DEFINED ENV{CURL_ROOT})) +- message(FATAL_ERROR "CURL_ROOT not set") +-endif() ++macro(find_wolfssl_root error_msg) ++ find_root_dir(WOLFSSL_ROOT "${error_msg}" ++ "${BASE_DIR}/../wolfssl-install|${BASE_DIR}/../wolfssl-install" ++ "/opt/wolfssl|/opt/wolfssl" ++ "/usr/local/include/wolfssl|/usr/local") ++endmacro() + +-if (NOT(DEFINED ENV{SAFESTRING_ROOT})) +- message(FATAL_ERROR "SAFESTRING_ROOT not set") +-endif() ++if(${TARGET_OS} STREQUAL linux) ++ if (${TLS} STREQUAL openssl) ++ if (NOT(DEFINED ENV{OPENSSL3_ROOT})) ++ message(FATAL_ERROR "OPENSSL3_ROOT not set") ++ endif() ++ elseif (${TLS} STREQUAL wolfssl) ++ if (NOT(DEFINED ENV{WOLFSSL_ROOT})) ++ find_wolfssl_root("WOLFSSL_ROOT not set") ++ endif() ++ else() ++ message(FATAL_ERROR "Unsupported TLS value: ${TLS} (expected openssl or wolfssl)") ++ endif() ++ ++ # wolfTPM links against wolfCrypt for its own crypto, independent of ++ # which TLS/crypto backend this project itself is using -- so ++ # WOLFSSL_ROOT is needed here too even when TLS=openssl. ++ if (${DA} MATCHES tpm AND ${TPM_STACK} STREQUAL wolftpm AND NOT(DEFINED ENV{WOLFSSL_ROOT})) ++ find_wolfssl_root("WOLFSSL_ROOT not set (required by TPM_STACK=wolftpm)") ++ endif() ++ ++ if (NOT(DEFINED ENV{CURL_ROOT})) ++ set(_curl_candidates ++ "/usr/local/include/curl|/usr/local" ++ "/usr/include/curl|/usr") ++ if (${TLS} STREQUAL wolfssl) ++ list(INSERT _curl_candidates 0 "/opt/curl|/opt/curl") ++ list(INSERT _curl_candidates 0 "${BASE_DIR}/../curl-install|${BASE_DIR}/../curl-install") ++ endif() ++ find_root_dir(CURL_ROOT "CURL_ROOT not set" ${_curl_candidates}) ++ endif() ++ ++ if (NOT(DEFINED ENV{TINYCBOR_ROOT})) ++ if (EXISTS "${BASE_DIR}/tinycbor") ++ set(ENV{TINYCBOR_ROOT} "${BASE_DIR}/tinycbor") ++ else() ++ message(FATAL_ERROR "TINYCBOR_ROOT not set") ++ endif() ++ endif() + +-if (NOT(DEFINED ENV{TINYCBOR_ROOT})) +- message(FATAL_ERROR "TINYCBOR_ROOT not set") ++ if( ${DA} MATCHES cse) ++ if (NOT(DEFINED ENV{METEE_ROOT})) ++ message(FATAL_ERROR "METEE_ROOT not set") ++ endif() ++ endif() + endif() + +-if( ${DA} MATCHES cse) +- if (NOT(DEFINED ENV{METEE_ROOT})) +- message(FATAL_ERROR "METEE_ROOT not set") ++if (NOT(DEFINED ENV{SAFESTRING_ROOT})) ++ if (EXISTS "${BASE_DIR}/safestringlib") ++ set(ENV{SAFESTRING_ROOT} "${BASE_DIR}/safestringlib") ++ else() ++ message(FATAL_ERROR "SAFESTRING_ROOT not set") + endif() + endif() + +@@ -70,20 +128,39 @@ client_sdk_compile_options( + ) + + client_sdk_compile_options( +- -fstack-protector -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -fPIE -fPIC ++ -fstack-protector-strong -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -fPIE -fPIC + ) + + +-if(${TARGET_OS} MATCHES linux) ++if(${TARGET_OS} STREQUAL linux) + # Safestring lib + client_sdk_include_directories( +- $ENV{OPENSSL3_ROOT}/include + $ENV{CURL_ROOT}/include + $ENV{SAFESTRING_ROOT}/include + $ENV{TINYCBOR_ROOT}/src + include + ) + ++if (${TLS} STREQUAL openssl) ++ client_sdk_include_directories($ENV{OPENSSL3_ROOT}/include) ++elseif (${TLS} STREQUAL wolfssl) ++ client_sdk_include_directories($ENV{WOLFSSL_ROOT}/include) ++endif() ++ ++if( ${DA} MATCHES tpm) ++ if(${TPM_STACK} STREQUAL wolftpm) ++ # wolfTPM's headers pull in wolfCrypt headers regardless of the TLS ++ # backend chosen above; make sure our own WOLFSSL_ROOT is on the ++ # include path instead of falling back to whatever wolfSSL happens to ++ # be on the system's default include path (which may be ABI-mismatched ++ # with the wolfTPM library linked in below). ++ client_sdk_include_directories($ENV{WOLFSSL_ROOT}/include) ++ endif() ++ if(DEFINED ENV{WOLFTPM_ROOT}) ++ client_sdk_include_directories($ENV{WOLFTPM_ROOT}/include) ++ endif() ++endif() ++ + if( ${DA} MATCHES cse) + client_sdk_include_directories($ENV{METEE_ROOT}/include) + add_subdirectory(cse) +@@ -101,7 +178,7 @@ endif() + + + +-if(${TARGET_OS} MATCHES linux) ++if(${TARGET_OS} STREQUAL linux) + target_link_libraries(client_sdk client_sdk_interface) + add_executable(linux-client app/main.c) + target_sources(linux-client PRIVATE app/blob.c) +@@ -130,26 +207,59 @@ if(${TARGET_OS} MATCHES linux) + -l:libtinycbor.a + -Wl,-z,noexecstack -Wl,-z,relro -Wl,-z,now + -L$ENV{CURL_ROOT}/lib ++ # Load the curl we linked against, not a system libcurl built for ++ # another TLS library. ++ -Wl,-rpath,$ENV{CURL_ROOT}/lib + -lcurl + ) + ++ if( ${DA} MATCHES tpm) ++ if(${TPM_STACK} STREQUAL wolftpm) ++ # Link wolfCrypt from our WOLFSSL_ROOT to avoid system lib collisions. ++ client_sdk_ld_options( ++ -L$ENV{WOLFSSL_ROOT}/lib64 ++ -L$ENV{WOLFSSL_ROOT}/lib ++ -Wl,-rpath,$ENV{WOLFSSL_ROOT}/lib64 ++ -Wl,-rpath,$ENV{WOLFSSL_ROOT}/lib ++ -lwolfssl ++ ) ++ if(DEFINED ENV{WOLFTPM_ROOT}) ++ client_sdk_ld_options( ++ -L$ENV{WOLFTPM_ROOT}/lib ++ -Wl,-rpath,$ENV{WOLFTPM_ROOT}/lib ++ ) ++ endif() ++ client_sdk_ld_options(-lwolftpm) ++ else() ++ client_sdk_ld_options(-ltss2-esys -ltss2-mu -ltss2-tctildr) ++ endif() ++ endif() ++ + if (${TLS} STREQUAL openssl) + client_sdk_ld_options( + -L$ENV{OPENSSL3_ROOT}/lib64 + -L$ENV{OPENSSL3_ROOT}/lib ++ -Wl,-rpath,$ENV{OPENSSL3_ROOT}/lib64 ++ -Wl,-rpath,$ENV{OPENSSL3_ROOT}/lib + -Wl,--no-whole-archive -lssl -lcrypto -ldl + ) +- elseif(${TLS} MATCHES mbedtls) ++ elseif(${TLS} STREQUAL wolfssl) ++ client_sdk_ld_options( ++ -L$ENV{WOLFSSL_ROOT}/lib64 ++ -L$ENV{WOLFSSL_ROOT}/lib ++ -Wl,-rpath,$ENV{WOLFSSL_ROOT}/lib64 ++ -Wl,-rpath,$ENV{WOLFSSL_ROOT}/lib ++ # crypto/common/fdo_key_exchange.c calls ceil(); the OpenSSL build ++ # picks libm up transitively via libcrypto, wolfSSL does not. ++ -Wl,--no-whole-archive -lwolfssl -lm ++ ) ++ elseif(${TLS} STREQUAL mbedtls) + client_sdk_ld_options( + -Wl,--no-whole-archive -lmbedcrypto + -Wl,--no-whole-archive -lmbedtls -lmbedx509 + ) + endif() + +- if( ${DA} MATCHES tpm) +- client_sdk_ld_options(-ltss2-esys -ltss2-mu -ltss2-tctildr) +- endif() +- + if( ${DA} MATCHES cse) + client_sdk_ld_options(-L$ENV{METEE_ROOT} -l:libmetee.a) + endif() +diff --git a/Jenkinsfile.yml b/Jenkinsfile.yml +index 7e5294c..1124f5d 100644 +--- a/Jenkinsfile.yml ++++ b/Jenkinsfile.yml +@@ -84,6 +84,30 @@ node('ccode'){ + archiveArtifacts artifacts: 'client-sdk/client-sdk-binaries.tar.gz', fingerprint: true, allowEmptyArchive: false + } + ++ stage('Build ClientSDK wolfSSL (compile-check)'){ ++ // Compile-check only for wolfSSL backend. ++ // TODO: run the smoke test too once the wolfSSL backend is proven stable in CI. ++ // try/catch so a failure here doesn't abort the OpenSSL smoke test below. ++ try { ++ sh ''' ++ export SAFESTRING_ROOT=$WORKSPACE/safestringlib ++ export TINYCBOR_ROOT=$WORKSPACE/tinycbor ++ cd $WORKSPACE/client-sdk ++ # Separate /opt paths so this can't clobber the OpenSSL stages' libcurl. ++ export WOLFSSL_ROOT=/opt/wolfssl-cc ++ export CURL_ROOT=/opt/curl-wolfssl ++ # sudo resets env vars, so pass them explicitly or install falls back to /opt/wolfssl,/opt/curl. ++ sudo WOLFSSL_ROOT="$WOLFSSL_ROOT" CURL_ROOT="$CURL_ROOT" bash utils/install_wolfssl_curl.sh -i -v 5.9.4 ++ make pristine || true ++ cmake -DTLS=wolfssl -DDA=ecdsa384 -DAES_MODE=gcm . ++ make -j$(nproc) ++ ''' ++ } catch (err) { ++ print "wolfSSL compile-check failed: ${err}" ++ currentBuild.result = 'UNSTABLE' ++ } ++ } ++ + try + { + stage('Run Smoketest') +diff --git a/NOTICE b/NOTICE +index 1958ce4..dbf922f 100644 +--- a/NOTICE ++++ b/NOTICE +@@ -508,3 +508,719 @@ OpenSSL + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ ++------------------------------------------------------------------------------- ++The following components are used under GPLv3 (with a GPLv2 relicensing ++exception for specific listed software, and a commercial license available ++as an alternative): ++ ++wolfSSL ++ ++ GNU GENERAL PUBLIC LICENSE ++ Version 3, 29 June 2007 ++ ++ Copyright (C) 2007 Free Software Foundation, Inc. ++ Everyone is permitted to copy and distribute verbatim copies ++ of this license document, but changing it is not allowed. ++ ++ Preamble ++ ++ The GNU General Public License is a free, copyleft license for ++software and other kinds of works. ++ ++ The licenses for most software and other practical works are designed ++to take away your freedom to share and change the works. By contrast, ++the GNU General Public License is intended to guarantee your freedom to ++share and change all versions of a program--to make sure it remains free ++software for all its users. We, the Free Software Foundation, use the ++GNU General Public License for most of our software; it applies also to ++any other work released this way by its authors. You can apply it to ++your programs, too. ++ ++ When we speak of free software, we are referring to freedom, not ++price. Our General Public Licenses are designed to make sure that you ++have the freedom to distribute copies of free software (and charge for ++them if you wish), that you receive source code or can get it if you ++want it, that you can change the software or use pieces of it in new ++free programs, and that you know you can do these things. ++ ++ To protect your rights, we need to prevent others from denying you ++these rights or asking you to surrender the rights. Therefore, you have ++certain responsibilities if you distribute copies of the software, or if ++you modify it: responsibilities to respect the freedom of others. ++ ++ For example, if you distribute copies of such a program, whether ++gratis or for a fee, you must pass on to the recipients the same ++freedoms that you received. You must make sure that they, too, receive ++or can get the source code. And you must show them these terms so they ++know their rights. ++ ++ Developers that use the GNU GPL protect your rights with two steps: ++(1) assert copyright on the software, and (2) offer you this License ++giving you legal permission to copy, distribute and/or modify it. ++ ++ For the developers' and authors' protection, the GPL clearly explains ++that there is no warranty for this free software. For both users' and ++authors' sake, the GPL requires that modified versions be marked as ++changed, so that their problems will not be attributed erroneously to ++authors of previous versions. ++ ++ Some devices are designed to deny users access to install or run ++modified versions of the software inside them, although the manufacturer ++can do so. This is fundamentally incompatible with the aim of ++protecting users' freedom to change the software. The systematic ++pattern of such abuse occurs in the area of products for individuals to ++use, which is precisely where it is most unacceptable. Therefore, we ++have designed this version of the GPL to prohibit the practice for those ++products. If such problems arise substantially in other domains, we ++stand ready to extend this provision to those domains in future versions ++of the GPL, as needed to protect the freedom of users. ++ ++ Finally, every program is threatened constantly by software patents. ++States should not allow patents to restrict development and use of ++software on general-purpose computers, but in those that do, we wish to ++avoid the special danger that patents applied to a free program could ++make it effectively proprietary. To prevent this, the GPL assures that ++patents cannot be used to render the program non-free. ++ ++ The precise terms and conditions for copying, distribution and ++modification follow. ++ ++ TERMS AND CONDITIONS ++ ++ 0. Definitions. ++ ++ "This License" refers to version 3 of the GNU General Public License. ++ ++ "Copyright" also means copyright-like laws that apply to other kinds of ++works, such as semiconductor masks. ++ ++ "The Program" refers to any copyrightable work licensed under this ++License. Each licensee is addressed as "you". "Licensees" and ++"recipients" may be individuals or organizations. ++ ++ To "modify" a work means to copy from or adapt all or part of the work ++in a fashion requiring copyright permission, other than the making of an ++exact copy. The resulting work is called a "modified version" of the ++earlier work or a work "based on" the earlier work. ++ ++ A "covered work" means either the unmodified Program or a work based ++on the Program. ++ ++ To "propagate" a work means to do anything with it that, without ++permission, would make you directly or secondarily liable for ++infringement under applicable copyright law, except executing it on a ++computer or modifying a private copy. Propagation includes copying, ++distribution (with or without modification), making available to the ++public, and in some countries other activities as well. ++ ++ To "convey" a work means any kind of propagation that enables other ++parties to make or receive copies. Mere interaction with a user through ++a computer network, with no transfer of a copy, is not conveying. ++ ++ An interactive user interface displays "Appropriate Legal Notices" ++to the extent that it includes a convenient and prominently visible ++feature that (1) displays an appropriate copyright notice, and (2) ++tells the user that there is no warranty for the work (except to the ++extent that warranties are provided), that licensees may convey the ++work under this License, and how to view a copy of this License. If ++the interface presents a list of user commands or options, such as a ++menu, a prominent item in the list meets this criterion. ++ ++ 1. Source Code. ++ ++ The "source code" for a work means the preferred form of the work ++for making modifications to it. "Object code" means any non-source ++form of a work. ++ ++ A "Standard Interface" means an interface that either is an official ++standard defined by a recognized standards body, or, in the case of ++interfaces specified for a particular programming language, one that ++is widely used among developers working in that language. ++ ++ The "System Libraries" of an executable work include anything, other ++than the work as a whole, that (a) is included in the normal form of ++packaging a Major Component, but which is not part of that Major ++Component, and (b) serves only to enable use of the work with that ++Major Component, or to implement a Standard Interface for which an ++implementation is available to the public in source code form. A ++"Major Component", in this context, means a major essential component ++(kernel, window system, and so on) of the specific operating system ++(if any) on which the executable work runs, or a compiler used to ++produce the work, or an object code interpreter used to run it. ++ ++ The "Corresponding Source" for a work in object code form means all ++the source code needed to generate, install, and (for an executable ++work) run the object code and to modify the work, including scripts to ++control those activities. However, it does not include the work's ++System Libraries, or general-purpose tools or generally available free ++programs which are used unmodified in performing those activities but ++which are not part of the work. For example, Corresponding Source ++includes interface definition files associated with source files for ++the work, and the source code for shared libraries and dynamically ++linked subprograms that the work is specifically designed to require, ++such as by intimate data communication or control flow between those ++subprograms and other parts of the work. ++ ++ The Corresponding Source need not include anything that users ++can regenerate automatically from other parts of the Corresponding ++Source. ++ ++ The Corresponding Source for a work in source code form is that ++same work. ++ ++ 2. Basic Permissions. ++ ++ All rights granted under this License are granted for the term of ++copyright on the Program, and are irrevocable provided the stated ++conditions are met. This License explicitly affirms your unlimited ++permission to run the unmodified Program. The output from running a ++covered work is covered by this License only if the output, given its ++content, constitutes a covered work. This License acknowledges your ++rights of fair use or other equivalent, as provided by copyright law. ++ ++ You may make, run and propagate covered works that you do not ++convey, without conditions so long as your license otherwise remains ++in force. You may convey covered works to others for the sole purpose ++of having them make modifications exclusively for you, or provide you ++with facilities for running those works, provided that you comply with ++the terms of this License in conveying all material for which you do ++not control copyright. Those thus making or running the covered works ++for you must do so exclusively on your behalf, under your direction ++and control, on terms that prohibit them from making any copies of ++your copyrighted material outside their relationship with you. ++ ++ Conveying under any other circumstances is permitted solely under ++the conditions stated below. Sublicensing is not allowed; section 10 ++makes it unnecessary. ++ ++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law. ++ ++ No covered work shall be deemed part of an effective technological ++measure under any applicable law fulfilling obligations under article ++11 of the WIPO copyright treaty adopted on 20 December 1996, or ++similar laws prohibiting or restricting circumvention of such ++measures. ++ ++ When you convey a covered work, you waive any legal power to forbid ++circumvention of technological measures to the extent such circumvention ++is effected by exercising rights under this License with respect to ++the covered work, and you disclaim any intention to limit operation or ++modification of the work as a means of enforcing, against the work's ++users, your or third parties' legal rights to forbid circumvention of ++technological measures. ++ ++ 4. Conveying Verbatim Copies. ++ ++ You may convey verbatim copies of the Program's source code as you ++receive it, in any medium, provided that you conspicuously and ++appropriately publish on each copy an appropriate copyright notice; ++keep intact all notices stating that this License and any ++non-permissive terms added in accord with section 7 apply to the code; ++keep intact all notices of the absence of any warranty; and give all ++recipients a copy of this License along with the Program. ++ ++ You may charge any price or no price for each copy that you convey, ++and you may offer support or warranty protection for a fee. ++ ++ 5. Conveying Modified Source Versions. ++ ++ You may convey a work based on the Program, or the modifications to ++produce it from the Program, in the form of source code under the ++terms of section 4, provided that you also meet all of these conditions: ++ ++ a) The work must carry prominent notices stating that you modified ++ it, and giving a relevant date. ++ ++ b) The work must carry prominent notices stating that it is ++ released under this License and any conditions added under section ++ 7. This requirement modifies the requirement in section 4 to ++ "keep intact all notices". ++ ++ c) You must license the entire work, as a whole, under this ++ License to anyone who comes into possession of a copy. This ++ License will therefore apply, along with any applicable section 7 ++ additional terms, to the whole of the work, and all its parts, ++ regardless of how they are packaged. This License gives no ++ permission to license the work in any other way, but it does not ++ invalidate such permission if you have separately received it. ++ ++ d) If the work has interactive user interfaces, each must display ++ Appropriate Legal Notices; however, if the Program has interactive ++ interfaces that do not display Appropriate Legal Notices, your ++ work need not make them do so. ++ ++ A compilation of a covered work with other separate and independent ++works, which are not by their nature extensions of the covered work, ++and which are not combined with it such as to form a larger program, ++in or on a volume of a storage or distribution medium, is called an ++"aggregate" if the compilation and its resulting copyright are not ++used to limit the access or legal rights of the compilation's users ++beyond what the individual works permit. Inclusion of a covered work ++in an aggregate does not cause this License to apply to the other ++parts of the aggregate. ++ ++ 6. Conveying Non-Source Forms. ++ ++ You may convey a covered work in object code form under the terms ++of sections 4 and 5, provided that you also convey the ++machine-readable Corresponding Source under the terms of this License, ++in one of these ways: ++ ++ a) Convey the object code in, or embodied in, a physical product ++ (including a physical distribution medium), accompanied by the ++ Corresponding Source fixed on a durable physical medium ++ customarily used for software interchange. ++ ++ b) Convey the object code in, or embodied in, a physical product ++ (including a physical distribution medium), accompanied by a ++ written offer, valid for at least three years and valid for as ++ long as you offer spare parts or customer support for that product ++ model, to give anyone who possesses the object code either (1) a ++ copy of the Corresponding Source for all the software in the ++ product that is covered by this License, on a durable physical ++ medium customarily used for software interchange, for a price no ++ more than your reasonable cost of physically performing this ++ conveying of source, or (2) access to copy the ++ Corresponding Source from a network server at no charge. ++ ++ c) Convey individual copies of the object code with a copy of the ++ written offer to provide the Corresponding Source. This ++ alternative is allowed only occasionally and noncommercially, and ++ only if you received the object code with such an offer, in accord ++ with subsection 6b. ++ ++ d) Convey the object code by offering access from a designated ++ place (gratis or for a charge), and offer equivalent access to the ++ Corresponding Source in the same way through the same place at no ++ further charge. You need not require recipients to copy the ++ Corresponding Source along with the object code. If the place to ++ copy the object code is a network server, the Corresponding Source ++ may be on a different server (operated by you or a third party) ++ that supports equivalent copying facilities, provided you maintain ++ clear directions next to the object code saying where to find the ++ Corresponding Source. Regardless of what server hosts the ++ Corresponding Source, you remain obligated to ensure that it is ++ available for as long as needed to satisfy these requirements. ++ ++ e) Convey the object code using peer-to-peer transmission, provided ++ you inform other peers where the object code and Corresponding ++ Source of the work are being offered to the general public at no ++ charge under subsection 6d. ++ ++ A separable portion of the object code, whose source code is excluded ++from the Corresponding Source as a System Library, need not be ++included in conveying the object code work. ++ ++ A "User Product" is either (1) a "consumer product", which means any ++tangible personal property which is normally used for personal, family, ++or household purposes, or (2) anything designed or sold for incorporation ++into a dwelling. In determining whether a product is a consumer product, ++doubtful cases shall be resolved in favor of coverage. For a particular ++product received by a particular user, "normally used" refers to a ++typical or common use of that class of product, regardless of the status ++of the particular user or of the way in which the particular user ++actually uses, or expects or is expected to use, the product. A product ++is a consumer product regardless of whether the product has substantial ++commercial, industrial or non-consumer uses, unless such uses represent ++the only significant mode of use of the product. ++ ++ "Installation Information" for a User Product means any methods, ++procedures, authorization keys, or other information required to install ++and execute modified versions of a covered work in that User Product from ++a modified version of its Corresponding Source. The information must ++suffice to ensure that the continued functioning of the modified object ++code is in no case prevented or interfered with solely because ++modification has been made. ++ ++ If you convey an object code work under this section in, or with, or ++specifically for use in, a User Product, and the conveying occurs as ++part of a transaction in which the right of possession and use of the ++User Product is transferred to the recipient in perpetuity or for a ++fixed term (regardless of how the transaction is characterized), the ++Corresponding Source conveyed under this section must be accompanied ++by the Installation Information. But this requirement does not apply ++if neither you nor any third party retains the ability to install ++modified object code on the User Product (for example, the work has ++been installed in ROM). ++ ++ The requirement to provide Installation Information does not include a ++requirement to continue to provide support service, warranty, or updates ++for a work that has been modified or installed by the recipient, or for ++the User Product in which it has been modified or installed. Access to a ++network may be denied when the modification itself materially and ++adversely affects the operation of the network or violates the rules and ++protocols for communication across the network. ++ ++ Corresponding Source conveyed, and Installation Information provided, ++in accord with this section must be in a format that is publicly ++documented (and with an implementation available to the public in ++source code form), and must require no special password or key for ++unpacking, reading or copying. ++ ++ 7. Additional Terms. ++ ++ "Additional permissions" are terms that supplement the terms of this ++License by making exceptions from one or more of its conditions. ++Additional permissions that are applicable to the entire Program shall ++be treated as though they were included in this License, to the extent ++that they are valid under applicable law. If additional permissions ++apply only to part of the Program, that part may be used separately ++under those permissions, but the entire Program remains governed by ++this License without regard to the additional permissions. ++ ++ When you convey a copy of a covered work, you may at your option ++remove any additional permissions from that copy, or from any part of ++it. (Additional permissions may be written to require their own ++removal in certain cases when you modify the work.) You may place ++additional permissions on material, added by you to a covered work, ++for which you have or can give appropriate copyright permission. ++ ++ Notwithstanding any other provision of this License, for material you ++add to a covered work, you may (if authorized by the copyright holders of ++that material) supplement the terms of this License with terms: ++ ++ a) Disclaiming warranty or limiting liability differently from the ++ terms of sections 15 and 16 of this License; or ++ ++ b) Requiring preservation of specified reasonable legal notices or ++ author attributions in that material or in the Appropriate Legal ++ Notices displayed by works containing it; or ++ ++ c) Prohibiting misrepresentation of the origin of that material, or ++ requiring that modified versions of such material be marked in ++ reasonable ways as different from the original version; or ++ ++ d) Limiting the use for publicity purposes of names of licensors or ++ authors of the material; or ++ ++ e) Declining to grant rights under trademark law for use of some ++ trade names, trademarks, or service marks; or ++ ++ f) Requiring indemnification of licensors and authors of that ++ material by anyone who conveys the material (or modified versions of ++ it) with contractual assumptions of liability to the recipient, for ++ any liability that these contractual assumptions directly impose on ++ those licensors and authors. ++ ++ All other non-permissive additional terms are considered "further ++restrictions" within the meaning of section 10. If the Program as you ++received it, or any part of it, contains a notice stating that it is ++governed by this License along with a term that is a further ++restriction, you may remove that term. If a license document contains ++a further restriction but permits relicensing or conveying under this ++License, you may add to a covered work material governed by the terms ++of that license document, provided that the further restriction does ++not survive such relicensing or conveying. ++ ++ If you add terms to a covered work in accord with this section, you ++must place, in the relevant source files, a statement of the ++additional terms that apply to those files, or a notice indicating ++where to find the applicable terms. ++ ++ Additional terms, permissive or non-permissive, may be stated in the ++form of a separately written license, or stated as exceptions; ++the above requirements apply either way. ++ ++ 8. Termination. ++ ++ You may not propagate or modify a covered work except as expressly ++provided under this License. Any attempt otherwise to propagate or ++modify it is void, and will automatically terminate your rights under ++this License (including any patent licenses granted under the third ++paragraph of section 11). ++ ++ However, if you cease all violation of this License, then your ++license from a particular copyright holder is reinstated (a) ++provisionally, unless and until the copyright holder explicitly and ++finally terminates your license, and (b) permanently, if the copyright ++holder fails to notify you of the violation by some reasonable means ++prior to 60 days after the cessation. ++ ++ Moreover, your license from a particular copyright holder is ++reinstated permanently if the copyright holder notifies you of the ++violation by some reasonable means, this is the first time you have ++received notice of violation of this License (for any work) from that ++copyright holder, and you cure the violation prior to 30 days after ++your receipt of the notice. ++ ++ Termination of your rights under this section does not terminate the ++licenses of parties who have received copies or rights from you under ++this License. If your rights have been terminated and not permanently ++reinstated, you do not qualify to receive new licenses for the same ++material under section 10. ++ ++ 9. Acceptance Not Required for Having Copies. ++ ++ You are not required to accept this License in order to receive or ++run a copy of the Program. Ancillary propagation of a covered work ++occurring solely as a consequence of using peer-to-peer transmission ++to receive a copy likewise does not require acceptance. However, ++nothing other than this License grants you permission to propagate or ++modify any covered work. These actions infringe copyright if you do ++not accept this License. Therefore, by modifying or propagating a ++covered work, you indicate your acceptance of this License to do so. ++ ++ 10. Automatic Licensing of Downstream Recipients. ++ ++ Each time you convey a covered work, the recipient automatically ++receives a license from the original licensors, to run, modify and ++propagate that work, subject to this License. You are not responsible ++for enforcing compliance by third parties with this License. ++ ++ An "entity transaction" is a transaction transferring control of an ++organization, or substantially all assets of one, or subdividing an ++organization, or merging organizations. If propagation of a covered ++work results from an entity transaction, each party to that ++transaction who receives a copy of the work also receives whatever ++licenses to the work the party's predecessor in interest had or could ++give under the previous paragraph, plus a right to possession of the ++Corresponding Source of the work from the predecessor in interest, if ++the predecessor has it or can get it with reasonable efforts. ++ ++ You may not impose any further restrictions on the exercise of the ++rights granted or affirmed under this License. For example, you may ++not impose a license fee, royalty, or other charge for exercise of ++rights granted under this License, and you may not initiate litigation ++(including a cross-claim or counterclaim in a lawsuit) alleging that ++any patent claim is infringed by making, using, selling, offering for ++sale, or importing the Program or any portion of it. ++ ++ 11. Patents. ++ ++ A "contributor" is a copyright holder who authorizes use under this ++License of the Program or a work on which the Program is based. The ++work thus licensed is called the contributor's "contributor version". ++ ++ A contributor's "essential patent claims" are all patent claims ++owned or controlled by the contributor, whether already acquired or ++hereafter acquired, that would be infringed by some manner, permitted ++by this License, of making, using, or selling its contributor version, ++but do not include claims that would be infringed only as a ++consequence of further modification of the contributor version. For ++purposes of this definition, "control" includes the right to grant ++patent sublicenses in a manner consistent with the requirements of ++this License. ++ ++ Each contributor grants you a non-exclusive, worldwide, royalty-free ++patent license under the contributor's essential patent claims, to ++make, use, sell, offer for sale, import and otherwise run, modify and ++propagate the contents of its contributor version. ++ ++ In the following three paragraphs, a "patent license" is any express ++agreement or commitment, however denominated, not to enforce a patent ++(such as an express permission to practice a patent or covenant not to ++sue for patent infringement). To "grant" such a patent license to a ++party means to make such an agreement or commitment not to enforce a ++patent against the party. ++ ++ If you convey a covered work, knowingly relying on a patent license, ++and the Corresponding Source of the work is not available for anyone ++to copy, free of charge and under the terms of this License, through a ++publicly available network server or other readily accessible means, ++then you must either (1) cause the Corresponding Source to be so ++available, or (2) arrange to deprive yourself of the benefit of the ++patent license for this particular work, or (3) arrange, in a manner ++consistent with the requirements of this License, to extend the patent ++license to downstream recipients. "Knowingly relying" means you have ++actual knowledge that, but for the patent license, your conveying the ++covered work in a country, or your recipient's use of the covered work ++in a country, would infringe one or more identifiable patents in that ++country that you have reason to believe are valid. ++ ++ If, pursuant to or in connection with a single transaction or ++arrangement, you convey, or propagate by procuring conveyance of, a ++covered work, and grant a patent license to some of the parties ++receiving the covered work authorizing them to use, propagate, modify ++or convey a specific copy of the covered work, then the patent license ++you grant is automatically extended to all recipients of the covered ++work and works based on it. ++ ++ A patent license is "discriminatory" if it does not include within ++the scope of its coverage, prohibits the exercise of, or is ++conditioned on the non-exercise of one or more of the rights that are ++specifically granted under this License. You may not convey a covered ++work if you are a party to an arrangement with a third party that is ++in the business of distributing software, under which you make payment ++to the third party based on the extent of your activity of conveying ++the work, and under which the third party grants, to any of the ++parties who would receive the covered work from you, a discriminatory ++patent license (a) in connection with copies of the covered work ++conveyed by you (or copies made from those copies), or (b) primarily ++for and in connection with specific products or compilations that ++contain the covered work, unless you entered into that arrangement, ++or that patent license was granted, prior to 28 March 2007. ++ ++ Nothing in this License shall be construed as excluding or limiting ++any implied license or other defenses to infringement that may ++otherwise be available to you under applicable patent law. ++ ++ 12. No Surrender of Others' Freedom. ++ ++ If conditions are imposed on you (whether by court order, agreement or ++otherwise) that contradict the conditions of this License, they do not ++excuse you from the conditions of this License. If you cannot convey a ++covered work so as to satisfy simultaneously your obligations under this ++License and any other pertinent obligations, then as a consequence you may ++not convey it at all. For example, if you agree to terms that obligate you ++to collect a royalty for further conveying from those to whom you convey ++the Program, the only way you could satisfy both those terms and this ++License would be to refrain entirely from conveying the Program. ++ ++ 13. Use with the GNU Affero General Public License. ++ ++ Notwithstanding any other provision of this License, you have ++permission to link or combine any covered work with a work licensed ++under version 3 of the GNU Affero General Public License into a single ++combined work, and to convey the resulting work. The terms of this ++License will continue to apply to the part which is the covered work, ++but the special requirements of the GNU Affero General Public License, ++section 13, concerning interaction through a network will apply to the ++combination as such. ++ ++ 14. Revised Versions of this License. ++ ++ The Free Software Foundation may publish revised and/or new versions of ++the GNU General Public License from time to time. Such new versions will ++be similar in spirit to the present version, but may differ in detail to ++address new problems or concerns. ++ ++ Each version is given a distinguishing version number. If the ++Program specifies that a certain numbered version of the GNU General ++Public License "or any later version" applies to it, you have the ++option of following the terms and conditions either of that numbered ++version or of any later version published by the Free Software ++Foundation. If the Program does not specify a version number of the ++GNU General Public License, you may choose any version ever published ++by the Free Software Foundation. ++ ++ If the Program specifies that a proxy can decide which future ++versions of the GNU General Public License can be used, that proxy's ++public statement of acceptance of a version permanently authorizes you ++to choose that version for the Program. ++ ++ Later license versions may give you additional or different ++permissions. However, no additional obligations are imposed on any ++author or copyright holder as a result of your choosing to follow a ++later version. ++ ++ 15. Disclaimer of Warranty. ++ ++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY ++APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT ++HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY ++OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ++THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ++PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM ++IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ++ALL NECESSARY SERVICING, REPAIR OR CORRECTION. ++ ++ 16. Limitation of Liability. ++ ++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING ++WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS ++THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY ++GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE ++USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF ++DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD ++PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), ++EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF ++SUCH DAMAGES. ++ ++ 17. Interpretation of Sections 15 and 16. ++ ++ If the disclaimer of warranty and limitation of liability provided ++above cannot be given local legal effect according to their terms, ++reviewing courts shall apply local law that most closely approximates ++an absolute waiver of all civil liability in connection with the ++Program, unless a warranty or assumption of liability accompanies a ++copy of the Program in return for a fee. ++ ++ END OF TERMS AND CONDITIONS ++ ++ How to Apply These Terms to Your New Programs ++ ++ If you develop a new program, and you want it to be of the greatest ++possible use to the public, the best way to achieve this is to make it ++free software which everyone can redistribute and change under these terms. ++ ++ To do so, attach the following notices to the program. It is safest ++to attach them to the start of each source file to most effectively ++state the exclusion of warranty; and each file should have at least ++the "copyright" line and a pointer to where the full notice is found. ++ ++ ++ Copyright (C) ++ ++ This program is free software: you can redistribute it and/or modify ++ it under the terms of the GNU General Public License as published by ++ the Free Software Foundation, either version 3 of the License, or ++ (at your option) any later version. ++ ++ This program is distributed in the hope that it will be useful, ++ but WITHOUT ANY WARRANTY; without even the implied warranty of ++ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ++ GNU General Public License for more details. ++ ++ You should have received a copy of the GNU General Public License ++ along with this program. If not, see . ++ ++Also add information on how to contact you by electronic and paper mail. ++ ++ If the program does terminal interaction, make it output a short ++notice like this when it starts in an interactive mode: ++ ++ Copyright (C) ++ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. ++ This is free software, and you are welcome to redistribute it ++ under certain conditions; type `show c' for details. ++ ++The hypothetical commands `show w' and `show c' should show the appropriate ++parts of the General Public License. Of course, your program's commands ++might be different; for a GUI interface, you would use an "about box". ++ ++ You should also get your employer (if you work as a programmer) or school, ++if any, to sign a "copyright disclaimer" for the program, if necessary. ++For more information on this, and how to apply and follow the GNU GPL, see ++. ++ ++ The GNU General Public License does not permit incorporating your program ++into proprietary programs. If your program is a subroutine library, you ++may consider it more useful to permit linking proprietary applications with ++the library. If this is what you want to do, use the GNU Lesser General ++Public License instead of this License. But first, please read ++. ++ ++The wolfSSL, Inc. software (“wolfSSL Software”) to which this text is appended ++is made available under the GNU General Public License version 3 (“GPLv3”) with ++the following exception: When this wolfSSL Software is combined with the ++software listed below (“Exception Software”), licensee may elect to license ++this wolfSSL Software under the GNU General Public License version 2 (“GPLv2”) ++instead of GPLv3. ++ ++Exception Software: ++ ++MariaDB Server ++ ++MariaDB Client Libraries ++ ++OpenVPN-NL ++ ++Fetchmail ++ ++OpenVPN ++ ++SWUpdate ++ ++RPCS3 ++ ++VDE - Virtual Distributed Ethernet ++ ++For our users who cannot use wolfSSL under GPLv3, a commercial license to ++wolfSSL and wolfCrypt is available. ++ ++Please contact wolfSSL Inc. directly at: ++ ++Email: licensing@wolfssl.com ++Phone: +1 425 245-8247 ++ ++More information can be found on the wolfSSL website at www.wolfssl.com. +diff --git a/NOTICES/wolfSSL-NOTICE b/NOTICES/wolfSSL-NOTICE +new file mode 100644 +index 0000000..202751e +--- /dev/null ++++ b/NOTICES/wolfSSL-NOTICE +@@ -0,0 +1 @@ ++"This product includes software developed by wolfSSL Inc. for use in the wolfSSL embedded SSL/TLS library and wolfCrypt cryptography library (https://www.wolfssl.com/)." +diff --git a/README.md b/README.md +index c94eb48..a6e6c2b 100644 +--- a/README.md ++++ b/README.md +@@ -7,18 +7,19 @@ credentials while porting this to different platforms. + + [ Introduction ](docs/introduction.md)
+ [ FDO Compilation Setup ](docs/setup.md) +-- [ Safestring ](docs/setup.md#safestring)
+-- [ TinyCBOR ](docs/setup.md#tinycbor)
+-- [ Manufacturer Network Address ](docs/setup.md#manuf_addr) +-- [ ECDSA Private Key Generation ](docs/setup.md#ecdsa_priv) +-- [ Setting the Maximum ServiceInfo Size](docs/setup.md#serviceinfo_mtu) ++- [ Safestring ](docs/setup.md#1-intel-safestringlib)
++- [ TinyCBOR ](docs/setup.md#2-intel-tinycbor)
++- [ Manufacturer Network Address ](docs/setup.md#3-setting-the-manufacturer-network-address) ++- [ ECDSA Private Key Generation ](docs/setup.md#4-elliptic-curve-digital-signature-algorithm-ecdsa-private-key-file-generation) ++- [ Setting the Maximum ServiceInfo Size](docs/setup.md#5-setting-the-maximum-serviceinfo-size-maximum-message-buffer-size) + - [ Setting the Manufacturer Device Serial Number](docs/setup.md#device_serial) +-- [ Configure Credential REUSE](docs/setup.md#cred_reuse) +-- [ HTTP_PROXY ](docs/setup.md#http_proxy) ++- [ Configure Credential REUSE](docs/setup.md#7-fdo-credentials-reuse-protocol) ++- [ HTTP_PROXY ](docs/setup.md#8-http-proxy-configuration-optional) + + [ Linux* TPM* Reference Implementation ](docs/tpm.md)
+ [ Linux* CSE* Reference Implementation ](docs/cse.md)
+ [ Linux* Reference Implementation ](docs/linux.md)
++[ Linux* wolfSSL* Reference Implementation ](docs/wolfssl.md)
+ [Security Implications](docs/security_implications.md) + + ***Note***: The implementation hasn't yet been updated for Arm* based platforms. This will be updated in a future release. +diff --git a/app/blob.c b/app/blob.c +index 269c680..1cd9300 100644 +--- a/app/blob.c ++++ b/app/blob.c +@@ -25,18 +25,11 @@ + #include + #include "safe_lib.h" + #include "fdo_crypto_hal.h" +-#if defined(USE_OPENSSL) +-#include +-#include +-#elif defined(USE_MBEDTLS) +-#include "mbedtls/md.h" +-#endif + #include "storage_al.h" + #include "blob.h" + #if defined(DEVICE_TPM20_ENABLED) +-#include "tpm20_Utils.h" + #include "fdo_crypto.h" +-#include "tpm2_nv_storage.h" ++#include "fdo_tpm_handles.h" + #endif + + #if !defined(DEVICE_TPM20_ENABLED) +@@ -144,20 +137,12 @@ int32_t configure_normal_blob(void) + "Malloc Failed for sealed Normal Blob buffer!\n"); + goto err; + } +-#if defined(USE_MBEDTLS) +- if (0 != mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), +- (const uint8_t *)hmac_key, +- PLATFORM_HMAC_KEY_DEFAULT_LEN, raw_normal_blob, +- raw_normal_blob_size, signed_normal_blob)) { +- goto err; +- } +-#else // USE_OPENSSL +- if (NULL == HMAC(EVP_sha256(), hmac_key, PLATFORM_HMAC_KEY_DEFAULT_LEN, +- raw_normal_blob, (int)raw_normal_blob_size, +- signed_normal_blob, NULL)) { ++ if (0 != crypto_hal_hmac(FDO_CRYPTO_HMAC_TYPE_SHA_256, raw_normal_blob, ++ raw_normal_blob_size, signed_normal_blob, ++ PLATFORM_HMAC_SIZE, hmac_key, ++ PLATFORM_HMAC_KEY_DEFAULT_LEN)) { + goto err; + } +-#endif + // copy plain-text size + signed_normal_blob[PLATFORM_HMAC_SIZE + 3] = raw_normal_blob_size >> 0; + signed_normal_blob[PLATFORM_HMAC_SIZE + 2] = raw_normal_blob_size >> 8; +diff --git a/app/main.c b/app/main.c +index c1825e9..1aed79d 100644 +--- a/app/main.c ++++ b/app/main.c +@@ -29,7 +29,6 @@ + #include "cse_tools.h" + #endif + #if defined(DEVICE_TPM20_ENABLED) +-#include "tpm20_Utils.h" + #include "fdo_crypto.h" + #endif + +diff --git a/build.sh b/build.sh +index bf0ed17..d5bd069 100755 +--- a/build.sh ++++ b/build.sh +@@ -1,5 +1,7 @@ + #!/bin/bash -x +-set -e -x ++# pipefail matters for the "make | tee" in run_unit_test below: without it the ++# pipeline reports tee's status and a failed unit-test build passes silently. ++set -e -x -o pipefail + export WORKSPACE=`pwd` + + BUILDTYPE="release" +@@ -104,7 +106,11 @@ if [ $SKIP_UNIT_TEST -eq 1 ]; then + fi + + echo " ***** Running Unit Tests *****" +-TEST_OUTPUT="build/unit-test-output.txt" ++# Keep this out of build/: run_unit_test starts with "make pristine", which ++# deletes that directory (see cmake/pristine.cmake), so results accumulated ++# there would be discarded by the next configuration and only the last run ++# would ever reach the fail_count below. ++TEST_OUTPUT="unit-test-output.txt" + rm -f $TEST_OUTPUT + COMMON_TEST_CONFIG="-Dunit-test=true -DHTTPPROXY=true -DBUILD=release" + +@@ -122,8 +128,8 @@ run_unit_test -DDA=ecdsa384 -DAES_MODE=gcm + run_unit_test -DDA=ecdsa384 -DAES_MODE=ccm + run_unit_test -DDA=ecdsa256 -DAES_MODE=gcm -DDA_FILE=pem + +-# DO NOT change the AWK search string, the spaces has been kept deliberately. +-fail_count=$(awk '/Tests Failed :/ {split($0,a,": "); count+=a[2]} END{print count}' $TEST_OUTPUT) ++fail_count=$(awk -F':' '/Tests Failed/ {count+=$2} END{print count+0}' "$TEST_OUTPUT") + echo "Found $fail_count unit-test failure(s)." + +-exit $fail_count ++# Raw counts wrap modulo 256 as exit codes. ++exit $(( fail_count > 0 ? 1 : 0 )) +diff --git a/cmake/cli_input.cmake b/cmake/cli_input.cmake +index 8a02102..7ac74be 100644 +--- a/cmake/cli_input.cmake ++++ b/cmake/cli_input.cmake +@@ -59,7 +59,7 @@ set (MANUFACTURER_DN " ") + get_property(cached_tls_value CACHE TLS PROPERTY VALUE) + + set(tls_cli_arg ${cached_tls_value}) +-if(tls_cli_arg STREQUAL CACHED_TLS) ++if(tls_cli_arg STREQUAL "${CACHED_TLS}") + unset(tls_cli_arg) + endif() + +@@ -88,7 +88,7 @@ message("Selected TLS ${TLS}") + get_property(cached_da_value CACHE DA PROPERTY VALUE) + + set(da_cli_arg ${cached_da_value}) +-if(da_cli_arg STREQUAL CACHED_DA) ++if(da_cli_arg STREQUAL "${CACHED_DA}") + unset(da_cli_arg) + endif() + +@@ -116,7 +116,7 @@ message("Selected DA ${DA}") + get_property(cached_aes_mode_value CACHE AES_MODE PROPERTY VALUE) + + set(aes_mode_cli_arg ${cached_aes_mode_value}) +-if(aes_mode_cli_arg STREQUAL CACHED_AES_MODE) ++if(aes_mode_cli_arg STREQUAL "${CACHED_AES_MODE}") + unset(aes_mode_cli_arg) + endif() + +@@ -144,7 +144,7 @@ message("Selected AES_MODE ${AES_MODE}") + get_property(cached_target_os_value CACHE TARGET_OS PROPERTY VALUE) + + set(target_os_cli_arg ${cached_target_os_value}) +-if(target_os_cli_arg STREQUAL CACHED_TARGET_OS) ++if(target_os_cli_arg STREQUAL "${CACHED_TARGET_OS}") + unset(target_os_cli_arg) + endif() + +@@ -172,7 +172,7 @@ message("Selected TARGET_OS ${TARGET_OS}") + get_property(cached_httpproxy_value CACHE HTTPPROXY PROPERTY VALUE) + + set(httpproxy_cli_arg ${cached_httpproxy_value}) +-if(httpproxy_cli_arg STREQUAL CACHED_HTTPPROXY) ++if(httpproxy_cli_arg STREQUAL "${CACHED_HTTPPROXY}") + unset(httpproxy_cli_arg) + endif() + +@@ -200,7 +200,7 @@ message("Selected HTTPPROXY ${HTTPPROXY}") + get_property(cached_proxy_discovery_value CACHE PROXY_DISCOVERY PROPERTY VALUE) + + set(proxy_discovery_cli_arg ${cached_proxy_discovery_value}) +-if(proxy_discovery_cli_arg STREQUAL CACHED_PROXY_DISCOVERY) ++if(proxy_discovery_cli_arg STREQUAL "${CACHED_PROXY_DISCOVERY}") + unset(proxy_discovery_cli_arg) + endif() + +@@ -228,7 +228,7 @@ message("Selected PROXY_DISCOVERY ${PROXY_DISCOVERY}") + get_property(cached_self_signed_certs_value CACHE SELF_SIGNED_CERTS PROPERTY VALUE) + + set(self_signed_certs_cli_arg ${cached_self_signed_certs_value}) +-if(self_signed_certs_cli_arg STREQUAL CACHED_SELF_SIGNED_CERTS) ++if(self_signed_certs_cli_arg STREQUAL "${CACHED_SELF_SIGNED_CERTS}") + unset(self_signed_certs_cli_arg) + endif() + +@@ -256,7 +256,7 @@ message("Selected SELF_SIGNED_CERTS ${SELF_SIGNED_CERTS}") + get_property(cached_server_name_indication_value CACHE SNI PROPERTY VALUE) + + set(server_name_indication_cli_arg ${cached_server_name_indication_value}) +-if(server_name_indication_cli_arg STREQUAL CACHED_SNI) ++if(server_name_indication_cli_arg STREQUAL "${CACHED_SNI}") + unset(server_name_indication_cli_arg) + endif() + +@@ -284,7 +284,7 @@ message("Selected SNI ${SNI}") + get_property(cached_da_file_value CACHE DA_FILE PROPERTY VALUE) + + set(da_file_cli_arg ${cached_da_file_value}) +-if(da_file_cli_arg STREQUAL CACHED_DA_FILE) ++if(da_file_cli_arg STREQUAL "${CACHED_DA_FILE}") + unset(da_file_cli_arg) + endif() + +@@ -312,7 +312,7 @@ message("Selected DA_FILE ${DA_FILE}") + get_property(cached_crypto_hw_value CACHE CRYPTO_HW PROPERTY VALUE) + + set(crypto_hw_cli_arg ${cached_crypto_hw_value}) +-if(crypto_hw_cli_arg STREQUAL CACHED_CRYPTO_HW) ++if(crypto_hw_cli_arg STREQUAL "${CACHED_CRYPTO_HW}") + unset(crypto_hw_cli_arg) + endif() + +@@ -340,7 +340,7 @@ message("Selected CRYPTO_HW ${CRYPTO_HW}") + get_property(cached_arch_value CACHE ARCH PROPERTY VALUE) + + set(arch_cli_arg ${cached_arch_value}) +-if(arch_cli_arg STREQUAL CACHED_ARCH) ++if(arch_cli_arg STREQUAL "${CACHED_ARCH}") + unset(arch_cli_arg) + endif() + +@@ -368,7 +368,7 @@ message("Selected ARCH ${ARCH}") + get_property(cached_unit-test_value CACHE unit-test PROPERTY VALUE) + + set(unit-test_cli_arg ${cached_unit-test_value}) +-if(unit-test_cli_arg STREQUAL CACHED_UNIT-TEST) ++if(unit-test_cli_arg STREQUAL "${CACHED_UNIT-TEST}") + unset(unit-test_cli_arg) + endif() + +@@ -398,7 +398,7 @@ endif() + get_property(cached_build_value CACHE BUILD PROPERTY VALUE) + + set(build_cli_arg ${cached_build_value}) +-if(build_cli_arg STREQUAL CACHED_BUILD) ++if(build_cli_arg STREQUAL "${CACHED_BUILD}") + unset(build_cli_arg) + endif() + +@@ -426,7 +426,7 @@ message("Selected BUILD ${BUILD}") + get_property(cached_optimize_value CACHE OPTIMIZE PROPERTY VALUE) + + set(optimize_cli_arg ${cached_optimize_value}) +-if(optimize_cli_arg STREQUAL CACHED_OPTIMIZE) ++if(optimize_cli_arg STREQUAL "${CACHED_OPTIMIZE}") + unset(optimize_cli_arg) + endif() + +@@ -454,7 +454,7 @@ message("Selected OPTIMIZE ${OPTIMIZE}") + get_property(cached_retry_value CACHE RETRY PROPERTY VALUE) + + set(retry_cli_arg ${cached_retry_value}) +-if(retry_cli_arg STREQUAL CACHED_RETRY) ++if(retry_cli_arg STREQUAL "${CACHED_RETRY}") + unset(retry_cli_arg) + endif() + +@@ -483,7 +483,7 @@ message("Selected RETRY ${RETRY}") + get_property(cached_board_value CACHE BOARD PROPERTY VALUE) + + set(board_cli_arg ${cached_board_value}) +-if(board_cli_arg STREQUAL CACHED_BOARD) ++if(board_cli_arg STREQUAL "${CACHED_BOARD}") + unset(board_cli_arg) + endif() + +@@ -513,7 +513,7 @@ endif() + get_property(cached_datastore_value CACHE DATASTORE PROPERTY VALUE) + + set(datastore_cli_arg ${cached_datastore_value}) +-if(datastore_cli_arg STREQUAL CACHED_DATASTORE) ++if(datastore_cli_arg STREQUAL "${CACHED_DATASTORE}") + unset(datastore_cli_arg) + endif() + +@@ -543,7 +543,7 @@ endif() + get_property(cached_blob_path_value CACHE BLOB_PATH PROPERTY VALUE) + + set(blob_path_cli_arg ${cached_blob_path_value}) +-if(blob_path_cli_arg STREQUAL CACHED_BLOB_PATH) ++if(blob_path_cli_arg STREQUAL "${CACHED_BLOB_PATH}") + unset(blob_path_cli_arg) + endif() + +@@ -573,7 +573,7 @@ message("Selected BLOB_PATH ${BLOB_PATH}") + get_property(cached_wifi_ssid_value CACHE WIFI_SSID PROPERTY VALUE) + + set(wifi_ssid_cli_arg ${cached_wifi_ssid_value}) +-if(wifi_ssid_cli_arg STREQUAL CACHED_WIFI_SSID) ++if(wifi_ssid_cli_arg STREQUAL "${CACHED_WIFI_SSID}") + unset(wifi_ssid_cli_arg) + endif() + +@@ -604,7 +604,7 @@ endif() + get_property(cached_wifi_pass_value CACHE WIFI_PASS PROPERTY VALUE) + + set(wifi_pass_cli_arg ${cached_wifi_pass_value}) +-if(wifi_pass_cli_arg STREQUAL CACHED_WIFI_PASS) ++if(wifi_pass_cli_arg STREQUAL "${CACHED_WIFI_PASS}") + unset(wifi_pass_cli_arg) + endif() + +@@ -634,7 +634,7 @@ endif() + get_property(cached_manufacturer_ip_value CACHE MANUFACTURER_IP PROPERTY VALUE) + + set(manufacturer_ip_cli_arg ${cached_manufacturer_ip_value}) +-if(manufacturer_ip_cli_arg STREQUAL CACHED_MANUFACTURER_IP) ++if(manufacturer_ip_cli_arg STREQUAL "${CACHED_MANUFACTURER_IP}") + unset(manufacturer_ip_cli_arg) + endif() + +@@ -664,7 +664,7 @@ endif() + get_property(cached_manufacturer_dn_value CACHE MANUFACTURER_DN PROPERTY VALUE) + + set(manufacturer_dn_cli_arg ${cached_manufacturer_dn_value}) +-if(manufacturer_dn_cli_arg STREQUAL CACHED_MANUFACTURER_DN) ++if(manufacturer_dn_cli_arg STREQUAL "${CACHED_MANUFACTURER_DN}") + unset(manufacturer_dn_cli_arg) + endif() + +@@ -695,7 +695,7 @@ endif() + get_property(cached_tpm2_tcti_type_value CACHE TPM2_TCTI_TYPE PROPERTY VALUE) + + set(tpm2_tcti_type_cli_arg ${cached_tpm2_tcti_type_value}) +-if(tpm2_tcti_type_cli_arg STREQUAL CACHED_TPM2_TCTI_TYPE) ++if(tpm2_tcti_type_cli_arg STREQUAL "${CACHED_TPM2_TCTI_TYPE}") + unset(tpm2_tcti_type_cli_arg) + endif() + +@@ -724,7 +724,7 @@ message("Selected TPM2_TCTI_TYPE ${TPM2_TCTI_TYPE}") + get_property(cached_resale_value CACHE RESALE PROPERTY VALUE) + + set(resale_cli_arg ${cached_resale_value}) +-if(resale_cli_arg STREQUAL CACHED_RESALE) ++if(resale_cli_arg STREQUAL "${CACHED_RESALE}") + unset(resale_cli_arg) + endif() + +@@ -752,7 +752,7 @@ message("Selected RESALE ${RESALE}") + get_property(cached_reuse_value CACHE REUSE PROPERTY VALUE) + + set(reuse_cli_arg ${cached_reuse_value}) +-if(reuse_cli_arg STREQUAL CACHED_REUSE) ++if(reuse_cli_arg STREQUAL "${CACHED_REUSE}") + unset(reuse_cli_arg) + endif() + +@@ -781,7 +781,7 @@ if (${DA} MATCHES cse) + get_property(cached_shutdown_value CACHE CSE_SHUTDOWN PROPERTY VALUE) + + set(shutdown_cli_arg ${cached_shutdown_value}) +- if(shutdown_cli_arg STREQUAL CACHED_CSE_SHUTDOWN) ++ if(shutdown_cli_arg STREQUAL "${CACHED_CSE_SHUTDOWN}") + unset(shutdown_cli_arg) + endif() + +@@ -809,7 +809,7 @@ if (${DA} MATCHES cse) + get_property(cached_clear_value CACHE CSE_CLEAR PROPERTY VALUE) + + set(clear_cli_arg ${cached_clear_value}) +- if(clear_cli_arg STREQUAL CACHED_CSE_CLEAR) ++ if(clear_cli_arg STREQUAL "${CACHED_CSE_CLEAR}") + unset(clear_cli_arg) + endif() + +@@ -837,7 +837,7 @@ endif() + get_property(cached_mtls_value CACHE MTLS PROPERTY VALUE) + + set(mtls_cli_arg ${cached_mtls_value}) +-if(mtls_cli_arg STREQUAL CACHED_MTLS) ++if(mtls_cli_arg STREQUAL "${CACHED_MTLS}") + unset(mtls_cli_arg) + endif() + +@@ -864,7 +864,7 @@ message("Selected MTLS ${MTLS}") + get_property(cached_get_dev_serial_value CACHE GET_DEV_SERIAL PROPERTY VALUE) + + set(get_dev_serial_cli_arg ${cached_get_dev_serial_value}) +-if(get_dev_serial_cli_arg STREQUAL CACHED_GET_DEV_SERIAL) ++if(get_dev_serial_cli_arg STREQUAL "${CACHED_GET_DEV_SERIAL}") + unset(get_dev_serial_cli_arg) + endif() + +@@ -892,7 +892,7 @@ if (${DA} MATCHES tpm) + get_property(cached_lock_tpm_value CACHE LOCK_TPM PROPERTY VALUE) + + set(lock_tpm_cli_arg ${cached_lock_tpm_value}) +- if(lock_tpm_cli_arg STREQUAL CACHED_LOCK_TPM) ++ if(lock_tpm_cli_arg STREQUAL "${CACHED_LOCK_TPM}") + unset(lock_tpm_cli_arg) + endif() + +@@ -919,7 +919,7 @@ endif() + # FOR BUILD MFG TOOLKIT + get_property(cached_build_mfg_toolkit_value CACHE BUILD_MFG_TOOLKIT PROPERTY VALUE) + set(build_mfg_toolkit_cli_arg ${cached_build_mfg_toolkit_value}) +-if(build_mfg_toolkit_cli_arg STREQUAL CACHED_BUILD_MFG_TOOLKIT) ++if(build_mfg_toolkit_cli_arg STREQUAL "${CACHED_BUILD_MFG_TOOLKIT}") + unset(build_mfg_toolkit_cli_arg) + endif() + +@@ -941,3 +941,45 @@ endif() + + set(CACHED_BUILD_MFG_TOOLKIT ${BUILD_MFG_TOOLKIT} CACHE STRING "Selected BUILD_MFG_TOOLKIT") + message("Selected BUILD_MFG_TOOLKIT ${BUILD_MFG_TOOLKIT}") ++ ++########################################### ++# FOR TPM_STACK ++get_property(cached_tpm_stack_value CACHE TPM_STACK PROPERTY VALUE) ++ ++set(tpm_stack_cli_arg ${cached_tpm_stack_value}) ++if(tpm_stack_cli_arg STREQUAL "${CACHED_TPM_STACK}") ++ unset(tpm_stack_cli_arg) ++endif() ++ ++set(tpm_stack_app_cmake_lists ${TPM_STACK}) ++if(cached_tpm_stack_value STREQUAL TPM_STACK) ++ unset(tpm_stack_app_cmake_lists) ++endif() ++ ++if(DEFINED CACHED_TPM_STACK) ++ if ((DEFINED tpm_stack_cli_arg) AND (NOT(CACHED_TPM_STACK STREQUAL tpm_stack_cli_arg))) ++ message(WARNING "Need to do make pristine before cmake args can change.") ++ endif() ++ set(TPM_STACK ${CACHED_TPM_STACK}) ++elseif(DEFINED tpm_stack_cli_arg) ++ set(TPM_STACK ${tpm_stack_cli_arg}) ++elseif(DEFINED tpm_stack_app_cmake_lists) ++ set(TPM_STACK ${tpm_stack_app_cmake_lists}) ++else() ++ # Default based on TLS backend ++ if(${TLS} STREQUAL wolfssl) ++ set(TPM_STACK "wolftpm") ++ else() ++ set(TPM_STACK "tpm2") ++ endif() ++endif() ++ ++if(NOT "${TPM_STACK}" MATCHES "^(tpm2|wolftpm)$") ++ message(FATAL_ERROR "Invalid TPM_STACK '${TPM_STACK}'. Supported values are 'tpm2' and 'wolftpm'.") ++endif() ++ ++set(CACHED_TPM_STACK ${TPM_STACK} CACHE STRING "Selected TPM_STACK") ++set_property(CACHE CACHED_TPM_STACK PROPERTY STRINGS tpm2 wolftpm) ++if(${DA} MATCHES tpm) ++ message("Selected TPM_STACK ${TPM_STACK}") ++endif() +diff --git a/cmake/extension.cmake b/cmake/extension.cmake +index 42e6cf6..ba505f3 100644 +--- a/cmake/extension.cmake ++++ b/cmake/extension.cmake +@@ -154,8 +154,10 @@ elseif(DA STREQUAL tpm20_ecdsa256) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"device:/dev/tpmrm0\") + elseif(${TPM2_TCTI_TYPE} MATCHES tabrmd) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") ++ elseif(${TPM2_TCTI_TYPE} MATCHES swtpm) ++ client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"swtpm:port=2321\") + else() +- message(WARNING "Incorrect TPM2_TCTI_TYPE selected. Supported values are 'tabrmd' and 'tpmrm0'. \ ++ message(WARNING "Incorrect TPM2_TCTI_TYPE selected. Supported values are 'tabrmd', 'tpmrm0', and 'swtpm'. \ + Defaulting to 'tabrmd'") + set (TPM2_TCTI_TYPE tabrmd) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") +@@ -166,8 +168,10 @@ elseif(DA STREQUAL tpm20_ecdsa384) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"device:/dev/tpmrm0\") + elseif(${TPM2_TCTI_TYPE} MATCHES tabrmd) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") ++ elseif(${TPM2_TCTI_TYPE} MATCHES swtpm) ++ client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"swtpm:port=2321\") + else() +- message(WARNING "Incorrect TPM2_TCTI_TYPE selected. Supported values are 'tabrmd' and 'tpmrm0'. \ ++ message(WARNING "Incorrect TPM2_TCTI_TYPE selected. Supported values are 'tabrmd', 'tpmrm0', and 'swtpm'. \ + Defaulting to 'tabrmd'") + set (TPM2_TCTI_TYPE tabrmd) + client_sdk_compile_definitions(-DTPM2_TCTI_TYPE=\"tabrmd\") +@@ -179,6 +183,17 @@ else() + client_sdk_compile_definitions(-DECDSA384_DA) + endif() + ++# TPM2_TCTI_TYPE only selects a tpm2-tss TCTI. wolfTPM ignores it and uses the ++# transport it was built with (with --enable-devtpm: /dev/tpmrm0, then /dev/tpm0). ++if((DA MATCHES tpm) AND (TPM_STACK STREQUAL wolftpm)) ++ client_sdk_compile_definitions(-DFDO_TPM_STACK_WOLFTPM) ++ if(TPM2_TCTI_TYPE MATCHES swtpm) ++ message(WARNING "TPM2_TCTI_TYPE=swtpm has no effect with TPM_STACK=wolftpm; build wolfTPM with --enable-swtpm to talk to a software TPM.") ++ else() ++ message(STATUS "TPM_STACK=wolftpm ignores TPM2_TCTI_TYPE; wolfTPM opens /dev/tpmrm0 (falling back to /dev/tpm0) when built with --enable-devtpm.") ++ endif() ++endif() ++ + if(TLS MATCHES openssl) + client_sdk_compile_definitions( + -DUSE_OPENSSL) +@@ -186,6 +201,13 @@ if(TLS MATCHES openssl) + client_sdk_ld_options(-L$ENV{OPENSSL_BIN_ROOT}/lib) + client_sdk_compile_options(-I$ENV{OPENSSL_BIN_ROOT}/include) + endif() ++elseif(TLS MATCHES wolfssl) ++ client_sdk_compile_definitions( ++ -DUSE_WOLFSSL) ++ if (DEFINED ENV{WOLFSSL_ROOT}) ++ client_sdk_ld_options(-L$ENV{WOLFSSL_ROOT}/lib) ++ client_sdk_compile_options(-I$ENV{WOLFSSL_ROOT}/include) ++ endif() + elseif(TLS MATCHES mbedtls) + client_sdk_compile_definitions( + -DUSE_MBEDTLS) +diff --git a/crypto/CMakeLists.txt b/crypto/CMakeLists.txt +index f47024b..3b02131 100644 +--- a/crypto/CMakeLists.txt ++++ b/crypto/CMakeLists.txt +@@ -3,11 +3,6 @@ + # SPDX-License-Identifier: Apache 2.0 + # + +- +-file(GLOB FDO_CRYPTO_COMMON_SOURCES common/*.c) +-file(GLOB FDO_CRYPTO_OPENSSL_SOURCES openssl/openssl*.c) +-file(GLOB FDO_CRYPTO_MBEDTLS_SOURCES mbedtls/mbedtls*.c) +- + client_sdk_include_directories( + include + ecdsa +@@ -26,6 +21,27 @@ client_sdk_sources_with_lib( + common/fdo_dev_attest.c + ) + ++# cse_crypto_support.c only talks to the CSE/HECI hardware interface (no TLS ++# backend API), so it is shared across every TLS backend rather than being ++# duplicated per backend directory. ++if (${DA} STREQUAL cse_ecdsa384) ++ client_sdk_sources_with_lib( crypto common/cse_crypto_support.c) ++endif() ++ ++# TPM sign-routine selection: same for every TLS backend, so pick it once ++# here instead of duplicating the TPM_STACK check per backend below. ++if (${DA} MATCHES tpm) ++ if (${TPM_STACK} STREQUAL wolftpm) ++ client_sdk_sources_with_lib ( crypto ++ tpm/wolftpm_ECDSA_sign_routines.c ++ tpm/wolftpm_hmac.c) ++ else() ++ client_sdk_sources_with_lib ( crypto ++ tpm/tpm20_ECDSA_sign_routines.c ++ tpm/tpm20_Utils.c) ++ endif() ++endif() ++ + + ################################################################# + #openssl build +@@ -42,20 +58,11 @@ if (${TLS} STREQUAL openssl) + client_sdk_sources_with_lib( crypto openssl/openssl_ECDSA_verify_routines.c) + endif() + +- if (${DA} STREQUAL cse_ecdsa384) +- client_sdk_sources_with_lib ( crypto +- openssl/cse_crypto_support.c +- ) +- endif() +- +- + if (${DA} MATCHES tpm) +- client_sdk_sources_with_lib ( crypto +- openssl/tpm20_ECDSA_sign_routines.c +- openssl/tpm20_Utils.c +- openssl/openssl_csr.c +- openssl/ec_key.c +- ecdsa/ecdsa_privkey.c) ++ client_sdk_sources_with_lib ( crypto ++ openssl/openssl_csr.c ++ openssl/ec_key.c ++ ecdsa/ecdsa_privkey.c) + + elseif (${DA} MATCHES ecdsa) + if (${CRYPTO_HW} MATCHES false) +@@ -110,6 +117,45 @@ if (${TLS} STREQUAL mbedtls) + endif() + endif() + ++################################################################# ++#wolfssl build ++if (${TLS} STREQUAL wolfssl) ++ client_sdk_sources_with_lib ( crypto ++ wolfssl/wolfssl_AESRoutines.c ++ wolfssl/wolfssl_cryptoSupport.c ++ wolfssl/wolfssl_SSLRoutines.c ++ wolfssl/wolfssl_key_exchange_ecdh.c ++ wolfssl/BN_support.c) ++ ++ ### Signature verifications types ++ ++ if (${CRYPTO_HW} STREQUAL false) ++ client_sdk_sources_with_lib( crypto wolfssl/wolfssl_ECDSAVerifyRoutines.c) ++ endif() ++ ++ if (${DA} MATCHES tpm) ++ # wolfssl_ec_csr.c is compiled in but unused here: DA=tpm always ++ # defines DEVICE_TPM20_ENABLED, and ps_get_m_string() (lib/m-string.c) ++ # reads the device CSR from TPM NV storage in that case rather than ++ # calling crypto_hal_get_device_csr(). ++ client_sdk_sources_with_lib ( crypto ++ wolfssl/wolfssl_ec_csr.c ++ ecdsa/ecdsa_privkey.c) ++ ++ elseif (${DA} MATCHES ecdsa) ++ if (${CRYPTO_HW} MATCHES false) ++ client_sdk_sources_with_lib ( crypto ++ wolfssl/wolfssl_ECDSASignRoutines.c ++ wolfssl/wolfssl_ec_csr.c ++ ecdsa/ecdsa_privkey.c) ++ endif() ++ endif() ++ ++ if (${CRYPTO_HW} MATCHES true) ++ client_sdk_sources_with_lib( crypto wolfssl/wolfssl_DERRoutines.c) ++ endif() ++endif() ++ + ################################################################# + #SE build + +diff --git a/crypto/common/cse_crypto_support.c b/crypto/common/cse_crypto_support.c +new file mode 100644 +index 0000000..3b0d440 +--- /dev/null ++++ b/crypto/common/cse_crypto_support.c +@@ -0,0 +1,119 @@ ++/* ++ * Copyright 2022 Intel Corporation ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Abstraction of CSE crypto services required by FDO ++ * library. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "cse_utils.h" ++ ++/** ++ * Generate random bytes of data of size num_bytes passed as paramater, else ++ * return error. ++ * @param random_buffer - Pointer rand_data of type uint8_t to be filled with, ++ * @param num_bytes - Number of bytes to be filled. ++ * @return 0 if succeeds, else -1. ++ */ ++int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) ++{ ++ FDO_STATUS fdo_status; ++ ++ if (NULL == random_buffer) { ++ return -1; ++ } else if (TEE_SUCCESS != fdo_heci_generate_random( ++ &fdo_cse_handle, random_buffer, ++ (uint32_t)num_bytes, &fdo_status) || ++ FDO_STATUS_SUCCESS != fdo_status) { ++ LOG(LOG_ERROR, "FDO CSE generate ranom bytes failed!!\n"); ++ return -1; ++ } ++ ++ return 0; ++} ++ ++/** ++ * crypto_hal_hmac function calculate hmac on input data ++ * ++ * @param buffer - pointer to input data buffer of uint8_t type. ++ * @param buffer_length - input data buffer size ++ * @param output - pointer to output data buffer of uint8_t type. ++ * @param output_length - output data buffer size ++ * @return return 0 on success. -ve value on failure. ++ */ ++int32_t crypto_hal_hmac_cse(uint8_t *buffer, size_t buffer_length, ++ uint8_t *output, size_t output_length) ++{ ++ if (NULL == output || 0 == output_length || NULL == buffer || ++ 0 == buffer_length) { ++ return -1; ++ } ++ ++ FDO_STATUS fdo_status; ++ ++ if (TEE_SUCCESS != ++ fdo_heci_load_file(&fdo_cse_handle, OVH_FILE_ID, &fdo_status) || ++ FDO_STATUS_SUCCESS != fdo_status) { ++ LOG(LOG_ERROR, "FDO HECI LOAD failed!! %u\n", fdo_status); ++ return -1; ++ } ++ ++ if (TEE_SUCCESS != fdo_heci_update_file(&fdo_cse_handle, OVH_FILE_ID, ++ buffer, buffer_length, output, ++ output_length, &fdo_status) || ++ FDO_STATUS_SUCCESS != fdo_status) { ++ LOG(LOG_ERROR, "FDO HECI UPDATE failed!! %u\n", fdo_status); ++ return -1; ++ } ++ LOG(LOG_DEBUG, "FDO HECI UPDATE succeeded %u\n", fdo_status); ++ ++ return 0; ++} ++ ++/** ++ * Sign a message using CSE API. ++ * @param data - pointer of type uint8_t, holds the plaintext message. ++ * @param data_len - size of message, type size_t. ++ * @param message_signature - pointer of type unsigned char, which will be ++ * by filled with signature. ++ * @param message_sig_len - size of signature, type unsigned int. ++ * @param eat_maroe - pointer of type uint8_t, which will be ++ * by filled with maroeprefix. ++ * @param maroe_length - size of maroeprefix, type unsigned int. ++ * @return 0 if true, else -1. ++ */ ++int32_t crypto_hal_ecdsa_sign_cse(const uint8_t *data, size_t data_len, ++ uint8_t *message_signature, ++ size_t message_sig_len, uint8_t *eat_maroe, ++ size_t *maroe_length) ++{ ++ if (!data || !data_len || !message_signature || !message_sig_len || ++ !eat_maroe || !maroe_length) { ++ LOG(LOG_ERROR, "fdo_cryptoECDSASign params not valid\n"); ++ return -1; ++ } ++ ++ FDO_STATUS fdo_status; ++ uint32_t mp_len = 0; ++ ++ if (TEE_SUCCESS != fdo_heci_ecdsa_device_sign_challenge( ++ &fdo_cse_handle, (uint8_t *)data, ++ (uint32_t)data_len, message_signature, ++ message_sig_len, eat_maroe, &mp_len, ++ &fdo_status) || ++ FDO_STATUS_SUCCESS != fdo_status) { ++ LOG(LOG_ERROR, "FDO HECI ECDSA DEVICE SIGN failed!! %u\n", ++ fdo_status); ++ return -1; ++ } ++ LOG(LOG_DEBUG, "FDO HECI ECDSA DEVICE SIGN compelete!! %u\n", ++ fdo_status); ++ ++ *maroe_length = mp_len; ++ ++ return 0; ++} +diff --git a/crypto/common/fdo_aes.c b/crypto/common/fdo_aes.c +index c5b4698..40202eb 100644 +--- a/crypto/common/fdo_aes.c ++++ b/crypto/common/fdo_aes.c +@@ -80,7 +80,7 @@ int32_t fdo_msg_encrypt(const uint8_t *clear_text, uint32_t clear_text_length, + uint8_t *sek; + uint8_t sek_len; + +- if (!keyset) { ++ if (!keyset || !keyset->sek) { + goto error; + } + +@@ -164,7 +164,7 @@ int32_t fdo_msg_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, + uint8_t *sek; + uint8_t sek_len; + +- if (!keyset) { ++ if (!keyset || !keyset->sek) { + goto error; + } + sek = keyset->sek->bytes; +diff --git a/crypto/common/fdo_crypto_common.c b/crypto/common/fdo_crypto_common.c +index 9f357db..b93b50a 100644 +--- a/crypto/common/fdo_crypto_common.c ++++ b/crypto/common/fdo_crypto_common.c +@@ -10,9 +10,6 @@ + #include "stdlib.h" + #include "fdo_crypto_ctx.h" + #include "fdo_crypto.h" +-#if defined(DEVICE_TPM20_ENABLED) +-#include "tpm20_Utils.h" +-#endif + + static fdo_crypto_context_t crypto_ctx; + static void cleanup_ctx(void); +diff --git a/crypto/common/fdo_hmac.c b/crypto/common/fdo_hmac.c +index db82fa1..06ddb98 100644 +--- a/crypto/common/fdo_hmac.c ++++ b/crypto/common/fdo_hmac.c +@@ -13,8 +13,7 @@ + #include "platform_utils.h" + + #if defined(DEVICE_TPM20_ENABLED) +-#include "tpm20_Utils.h" +-#include "tpm2_nv_storage.h" ++#include "fdo_tpm_handles.h" + #endif + + #if defined(DEVICE_CSE_ENABLED) +diff --git a/crypto/common/fdo_ov_verify.c b/crypto/common/fdo_ov_verify.c +index efc3b50..ff9cf08 100644 +--- a/crypto/common/fdo_ov_verify.c ++++ b/crypto/common/fdo_ov_verify.c +@@ -5,7 +5,8 @@ + + /*! + * \file +- * \brief Abstraction layer for RSA encryption routines of openssl library. ++ * \brief Ownership Voucher signature verification, backend-agnostic (calls ++ * crypto_hal_sig_verify()). + */ + + #include "fdotypes.h" +diff --git a/crypto/include/BN_support.h b/crypto/include/BN_support.h +index 23ec60f..84b808f 100644 +--- a/crypto/include/BN_support.h ++++ b/crypto/include/BN_support.h +@@ -10,6 +10,9 @@ + #ifdef USE_OPENSSL + #include + #include ++#elif defined(USE_WOLFSSL) ++#include ++#include + #else + #include + #include +@@ -18,16 +21,57 @@ + + #ifdef USE_OPENSSL + typedef BIGNUM bignum_t; ++typedef BN_CTX bn_ctx_t; ++#elif defined(USE_WOLFSSL) ++typedef mp_int bignum_t; ++/* mp_exptmod() takes no context; void here only for signature parity ++ * with the other backends. Always NULL; bn_mod_exp() ignores it. */ ++typedef void bn_ctx_t; + #else + typedef mbedtls_mpi bignum_t; + typedef mbedtls_mpi BN_CTX; ++typedef BN_CTX bn_ctx_t; + #endif + ++/* Implemented for USE_OPENSSL and USE_WOLFSSL; not implemented for ++ * USE_MBEDTLS. ++ * Caller must initialize and free bignum_t (e.g., mp_init). ++ */ + int bn_rand(bignum_t *rnd, int size); + int byte_array_to_bn(bignum_t *bn, fdo_byte_array_t *in); + fdo_byte_array_t *bn_to_byte_array(bignum_t *in); + +-#ifdef USE_MBEDTLS ++#ifdef USE_WOLFSSL ++ ++static inline int bn_bin2bn(const unsigned char *s, int len, bignum_t *bn) ++{ ++ return (mp_read_unsigned_bin(bn, s, len) == 0) ? 0 : -1; ++} ++ ++static inline int bn_bn2bin(const bignum_t *a, unsigned char *to) ++{ ++ int len = mp_unsigned_bin_size((bignum_t *)a); ++ ++ if (mp_to_unsigned_bin((bignum_t *)a, to) != 0) { ++ return 0; ++ } ++ return len; ++} ++ ++/* Compute r = a^p mod m */ ++static inline int bn_mod_exp(bignum_t *r, bignum_t *a, const bignum_t *p, ++ const bignum_t *m, bn_ctx_t *ctx) ++{ ++ (void)ctx; ++ return (mp_exptmod(a, (bignum_t *)p, (bignum_t *)m, r) == 0) ? 0 : -1; ++} ++ ++static inline int bn_num_bytes(const bignum_t *a) ++{ ++ return mp_unsigned_bin_size((bignum_t *)a); ++} ++ ++#elif defined(USE_MBEDTLS) + static inline int bn_bin2bn(const unsigned char *s, int len, bignum_t *bn) + { + return mbedtls_mpi_read_binary(bn, s, len); +@@ -46,7 +90,7 @@ static inline int bn_bn2bin(const bignum_t *a, unsigned char *to) + + /* Compute r = a^p mod m */ + static inline int bn_mod_exp(bignum_t *r, bignum_t *a, const bignum_t *p, +- const bignum_t *m, BN_CTX *ctx) ++ const bignum_t *m, bn_ctx_t *ctx) + { + return mbedtls_mpi_exp_mod(r, a, p, m, ctx); + } +@@ -72,7 +116,7 @@ static inline int bn_bn2bin(const bignum_t *a, unsigned char *to) + + /* Compute r = a^p mod m */ + static inline int bn_mod_exp(bignum_t *r, bignum_t *a, const bignum_t *p, +- const bignum_t *m, BN_CTX *ctx) ++ const bignum_t *m, bn_ctx_t *ctx) + { + int ret = BN_mod_exp(r, a, p, m, ctx); + +diff --git a/crypto/include/ec_key.h b/crypto/include/ec_key.h +index 3fc8ca8..ba4fa13 100644 +--- a/crypto/include/ec_key.h ++++ b/crypto/include/ec_key.h +@@ -5,7 +5,9 @@ + #ifndef __EC_KEY_H__ + #define __EC_KEY_H__ + ++#ifdef USE_OPENSSL + #include + + EVP_PKEY *get_evp_key(void); + #endif ++#endif +diff --git a/crypto/include/fdo_crypto_commons.h b/crypto/include/fdo_crypto_commons.h +index 2aa9215..b01f7f7 100644 +--- a/crypto/include/fdo_crypto_commons.h ++++ b/crypto/include/fdo_crypto_commons.h +@@ -66,4 +66,4 @@ + #define COSE_ENC_TYPE FDO_CRYPTO_A256CCM + #endif + +-#endif +\ No newline at end of file ++#endif +diff --git a/crypto/include/fdo_crypto_hal.h b/crypto/include/fdo_crypto_hal.h +index bc2a150..f42f481 100644 +--- a/crypto/include/fdo_crypto_hal.h ++++ b/crypto/include/fdo_crypto_hal.h +@@ -28,13 +28,26 @@ extern "C" { + #include + #include + #include ++#elif defined(USE_WOLFSSL) ++/* Must be included before any other wolfSSL header. */ ++#include ++#include + #endif + + #define PLAIN_TEXT_SIZE BUFF_SIZE_1K_BYTES + ++/* wolfSSL's headers (pulled in above) already define SHA*_DIGEST_SIZE as ++ * OpenSSL-compat macros; avoid redefining them under -Werror. ++ */ ++#ifndef SHA256_DIGEST_SIZE + #define SHA256_DIGEST_SIZE BUFF_SIZE_32_BYTES ++#endif ++#ifndef SHA384_DIGEST_SIZE + #define SHA384_DIGEST_SIZE BUFF_SIZE_48_BYTES ++#endif ++#ifndef SHA512_DIGEST_SIZE + #define SHA512_DIGEST_SIZE BUFF_SIZE_64_BYTES ++#endif + #define HMACSHA256_KEY_SIZE BUFF_SIZE_32_BYTES + #define ECDSA_SIGNATURE_MAX_LEN BUFF_SIZE_256_BYTES + +@@ -145,8 +158,11 @@ int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, + * FDO. + * raw_sig: input a 64 Byte r and s format signature. + * message_signature: outputs a DER encoded signature value +- * signature_length: outputs the size of the signature after converting to DER +- * format. ++ * signature_length: in/out. On entry, the capacity of message_signature; on ++ * return, the size of the DER encoding actually written. Implementations must ++ * fail rather than write past the stated capacity -- callers such as ++ * fdo_dev_sign() pass the allocated buffer size here, so it is the only bound ++ * available. + */ + int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + uint8_t *message_signature, +@@ -177,7 +193,7 @@ int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr); + int fdo_ssl_read(void *ssl, void *buf, int num); + int fdo_ssl_write(void *ssl, const void *buf, int num); + +-#ifdef USE_OPENSSL ++#if defined(USE_OPENSSL) || defined(USE_WOLFSSL) + void *fdo_ssl_setup(int sock); + int fdo_ssl_connect(void *ssl); + int fdo_ssl_close(void *ssl); +diff --git a/crypto/include/wolftpm_utils.h b/crypto/include/wolftpm_utils.h +new file mode 100644 +index 0000000..790c972 +--- /dev/null ++++ b/crypto/include/wolftpm_utils.h +@@ -0,0 +1,37 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Shared setup helper for the wolfTPM backend routines. ++ */ ++ ++#ifndef __WOLFTPM_UTILS_H__ ++#define __WOLFTPM_UTILS_H__ ++ ++#include ++ ++/* wolfTPM disables transparent resubmit-on-TPM_RC_RETRY by default. */ ++#define WOLFTPM_MAX_RETRIES_ON_BUSY 3 ++ ++/* Finish auth setup if already initialized. */ ++static inline int wolftpm_init_dev(WOLFTPM2_DEV *dev) ++{ ++ int rc = wolfTPM2_Init(dev, NULL, NULL); ++ ++ if (rc == TPM_RC_INITIALIZE) { ++ XMEMSET(dev->session, 0, sizeof(dev->session)); ++ wolfTPM2_SetAuthPassword(dev, 0, NULL); ++ rc = TPM_RC_SUCCESS; ++ } ++ if (rc != TPM_RC_SUCCESS) { ++ return rc; ++ } ++ ++ TPM2_SetCommandRetries(&dev->ctx, WOLFTPM_MAX_RETRIES_ON_BUSY); ++ return TPM_RC_SUCCESS; ++} ++ ++#endif /* #ifndef __WOLFTPM_UTILS_H__ */ +diff --git a/crypto/mbedtls/mbedtls_DERRoutines.c b/crypto/mbedtls/mbedtls_DERRoutines.c +index 030d10b..767aaf4 100644 +--- a/crypto/mbedtls/mbedtls_DERRoutines.c ++++ b/crypto/mbedtls/mbedtls_DERRoutines.c +@@ -21,8 +21,9 @@ + * FDO. + * raw_sig: input a 64 Byte r and s format signature. + * message_signature: outputs a DER encoded signature value +- * signature_length: outputs the size of the signature after converting to DER +- * format. ++ * signature_length: in/out, the capacity of message_signature on entry and the ++ * size of the DER encoding on return. See crypto_hal_der_encode() in ++ * fdo_crypto_hal.h for the full contract. + */ + int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + uint8_t *message_signature, +@@ -91,7 +92,15 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + } + len += ret; + +- if (0 != memcpy_s(message_signature, BUFF_SIZE_256_BYTES, p, len)) { ++ /* Bound by the caller's stated capacity rather than a fixed size: the ++ * buffer is not guaranteed to be BUFF_SIZE_256_BYTES. */ ++ if (len > *signature_length) { ++ LOG(LOG_ERROR, "signature does not fit the output buffer\n"); ++ ret = -1; ++ goto err; ++ } ++ ++ if (0 != memcpy_s(message_signature, *signature_length, p, len)) { + LOG(LOG_ERROR, "Memcpy to message_signature failed\n"); + ret = -1; + goto err; +diff --git a/crypto/openssl/ec_key.c b/crypto/openssl/ec_key.c +index 86e3849..3934a5a 100644 +--- a/crypto/openssl/ec_key.c ++++ b/crypto/openssl/ec_key.c +@@ -13,6 +13,7 @@ + #include + #include + #include ++#include + #include "fdotypes.h" + #include "storage_al.h" + #include "util.h" +@@ -85,6 +86,9 @@ EVP_PKEY *get_evp_key(void) + int32_t curve = NID_X9_62_prime256v1; + EVP_PKEY *evp_key_ec = NULL; + EVP_PKEY_CTX *evp_ctx = NULL; ++ BIGNUM *priv_bn = NULL; ++ OSSL_PARAM_BLD *param_bld = NULL; ++ OSSL_PARAM *params = NULL; + + #ifdef ECDSA384_DA + curve = NID_secp384r1; +@@ -103,12 +107,25 @@ EVP_PKEY *get_evp_key(void) + goto err; + } + +- const char *group_name = OBJ_nid2sn(curve); +- OSSL_PARAM params[] = { +- OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, privkey, privkey_size), +- OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, +- (char *)group_name, strlen(group_name)), +- OSSL_PARAM_END}; ++ /* The stored key is a big-endian scalar (see utils/keys_gen.sh). ++ * OSSL_PARAM_BN() would read raw bytes in native byte order, so ++ * convert through a BIGNUM and let the param builder encode it. */ ++ priv_bn = BN_bin2bn(privkey, (int)privkey_size, NULL); ++ param_bld = OSSL_PARAM_BLD_new(); ++ if (!priv_bn || !param_bld || ++ !OSSL_PARAM_BLD_push_utf8_string(param_bld, ++ OSSL_PKEY_PARAM_GROUP_NAME, ++ OBJ_nid2sn(curve), 0) || ++ !OSSL_PARAM_BLD_push_BN(param_bld, OSSL_PKEY_PARAM_PRIV_KEY, ++ priv_bn)) { ++ LOG(LOG_ERROR, "Failed to build the ec key params\n"); ++ goto err; ++ } ++ params = OSSL_PARAM_BLD_to_param(param_bld); ++ if (!params) { ++ LOG(LOG_ERROR, "Failed to build the ec key params\n"); ++ goto err; ++ } + if (EVP_PKEY_fromdata_init(evp_ctx) <= 0) { + LOG(LOG_ERROR, "Failed to init the ec key from data object\n"); + goto err; +@@ -128,6 +145,9 @@ err: + EVP_PKEY_CTX_free(evp_ctx); + evp_ctx = NULL; + } ++ OSSL_PARAM_free(params); ++ OSSL_PARAM_BLD_free(param_bld); ++ BN_clear_free(priv_bn); + if (privkey) { + if (memset_s(privkey, privkey_size, 0) != 0) { + LOG(LOG_ERROR, "Memset Failed\n"); +diff --git a/crypto/openssl/openssl_DER_routines.c b/crypto/openssl/openssl_DER_routines.c +index 3e8d836..9900130 100644 +--- a/crypto/openssl/openssl_DER_routines.c ++++ b/crypto/openssl/openssl_DER_routines.c +@@ -18,8 +18,9 @@ + * FDO. + * raw_sig: input a 64 Byte r and s format signature. + * message_signature: outputs a DER encoded signature value +- * signature_length: outputs the size of the signature after converting to DER +- * format. ++ * signature_length: in/out, the capacity of message_signature on entry and the ++ * size of the DER encoding on return. See crypto_hal_der_encode() in ++ * fdo_crypto_hal.h for the full contract. + */ + int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + uint8_t *message_signature, +@@ -27,10 +28,14 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + { + /* Encode */ + int ret = 0; ++ int der_length = 0; + BIGNUM *r = BN_new(); + BIGNUM *s = BN_new(); + ECDSA_SIG *sig = ECDSA_SIG_new(); + uint8_t *msg = (uint8_t *)message_signature; ++ /* ECDSA_SIG_set0() takes ownership of r and s on success; until then ++ * this function still has to free them itself. */ ++ bool sig_owns_rs = false; + + if ((NULL == raw_sig) || (BUFF_SIZE_64_BYTES != raw_sig_length) || + (NULL == message_signature) || (NULL == signature_length)) { +@@ -59,6 +64,17 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + ret = -1; + goto err; + } ++ sig_owns_rs = true; ++ ++ /* Size the encoding before writing it: i2d_ECDSA_SIG() has no way to ++ * observe the destination capacity, so an oversized signature would ++ * otherwise run past the caller's buffer. */ ++ der_length = i2d_ECDSA_SIG(sig, NULL); ++ if (der_length <= 0 || (size_t)der_length > *signature_length) { ++ LOG(LOG_ERROR, "signature does not fit the output buffer!\n"); ++ ret = -1; ++ goto err; ++ } + + /* Convert from an internal rep i.e r and S format to DER format */ + if (0 == i2d_ECDSA_SIG(sig, &msg)) { +@@ -68,11 +84,15 @@ int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, + } + + /* Return the length of the encoded DER signature */ +- *signature_length = (size_t)i2d_ECDSA_SIG(sig, NULL); ++ *signature_length = (size_t)der_length; + + err: +- /* Frees up sig, r and s variables */ ++ /* Frees up sig, and r and s once sig has taken ownership of them */ + ECDSA_SIG_free(sig); ++ if (!sig_owns_rs) { ++ BN_free(r); ++ BN_free(s); ++ } + + return ret; + } +diff --git a/crypto/openssl/openssl_crypto_support.c b/crypto/openssl/openssl_crypto_support.c +index 6845d85..6f5c120 100644 +--- a/crypto/openssl/openssl_crypto_support.c ++++ b/crypto/openssl/openssl_crypto_support.c +@@ -102,8 +102,10 @@ int32_t inc_rollover_ctr(uint8_t *first_iv, uint8_t *new_iv, uint8_t iv_len, + goto err; + } + +- /* Write bn to binary data */ +- if (BN_bn2bin(iv_bn_new, new_iv) > iv_len) { ++ /* Write bn to binary data, right-justified in iv_len bytes. Check the ++ * size first: BN_bn2bin() would write past new_iv on overflow. */ ++ if (BN_num_bytes(iv_bn_new) > iv_len || ++ BN_bn2binpad(iv_bn_new, new_iv, iv_len) != iv_len) { + LOG(LOG_ERROR, "New iv from BN write failed\n"); + goto err; + } +diff --git a/crypto/openssl/openssl_key_exchange_ecdh.c b/crypto/openssl/openssl_key_exchange_ecdh.c +index d500655..cde05aa 100644 +--- a/crypto/openssl/openssl_key_exchange_ecdh.c ++++ b/crypto/openssl/openssl_key_exchange_ecdh.c +@@ -403,17 +403,43 @@ int32_t crypto_hal_set_peer_random(void *context, + #if LOG_LEVEL == LOG_MAX_LEVEL + hexdump("Public A(bn)", temp, peer_rand_length); + #endif ++ /* Each field is a 2-byte length followed by that many bytes; bound ++ * every read by peer_rand_length. */ + size = 0; ++ if (peer_rand_length - size < 2) { ++ LOG(LOG_ERROR, "Peer random truncated before Ax\n"); ++ goto error; ++ } + size_Ax = (temp[size] << 8) | temp[size + 1]; + size += 2; ++ if (size_Ax > peer_rand_length - size) { ++ LOG(LOG_ERROR, "Peer random Ax length out of bounds\n"); ++ goto error; ++ } + BN_bin2bn(&temp[size], size_Ax, Ax_bn); + size += size_Ax; ++ if (peer_rand_length - size < 2) { ++ LOG(LOG_ERROR, "Peer random truncated before Ay\n"); ++ goto error; ++ } + size_Ay = (temp[size] << 8) | temp[size + 1]; + size += 2; ++ if (size_Ay > peer_rand_length - size) { ++ LOG(LOG_ERROR, "Peer random Ay length out of bounds\n"); ++ goto error; ++ } + BN_bin2bn(&temp[size], size_Ay, Ay_bn); + size += size_Ay; ++ if (peer_rand_length - size < 2) { ++ LOG(LOG_ERROR, "Peer random truncated before owner random\n"); ++ goto error; ++ } + size_owner_random = (temp[size] << 8) | temp[size + 1]; + size += 2; ++ if (size_owner_random > peer_rand_length - size) { ++ LOG(LOG_ERROR, "Peer random owner random length out of bounds\n"); ++ goto error; ++ } + BN_bin2bn(&temp[size], size_owner_random, owner_random_bn); + + #if LOG_LEVEL == LOG_MAX_LEVEL +@@ -446,8 +472,14 @@ int32_t crypto_hal_set_peer_random(void *context, + LOG(LOG_ERROR, "Error curve parameters are NULL\n"); + goto error; + } +- EC_POINT_set_affine_coordinates(group, point, Ax_bn, Ay_bn, ctx); +- shx = fdo_alloc(bn_num_bytes(Ax_bn)); ++ if (EC_POINT_set_affine_coordinates(group, point, Ax_bn, Ay_bn, ctx) != ++ 1) { ++ LOG(LOG_ERROR, "Peer public key is not a point on the curve\n"); ++ goto error; ++ } ++ /* Sized for the curve, not Ax: shx receives the shared X coordinate, ++ * which can be longer than a peer Ax with leading zeros. */ ++ shx = fdo_alloc((EC_GROUP_get_degree(group) + 7) / 8); + if (!shx) { + goto error; + } +diff --git a/crypto/se/se_AES_GCM_routines.c b/crypto/se/se_AES_GCM_routines.c +index 1734fe8..e5e949e 100644 +--- a/crypto/se/se_AES_GCM_routines.c ++++ b/crypto/se/se_AES_GCM_routines.c +@@ -7,6 +7,10 @@ + * \file + * \brief Abstraction layer for AES_GCM (authenticated- encryption) routines of + * openssl library. ++ * ++ * TODO(se-cryptoauthlib): fdo_crypto_aes_gcm_encrypt/decrypt don't match ++ * crypto_hal_aes_encrypt/decrypt and are unused; needs ATECC608 hardware ++ * to fix. + */ + + #include "fdo_crypto_hal.h" +@@ -14,7 +18,12 @@ + #include "crypto_utils.h" + #include "safe_lib.h" + #include ++/* Newer CryptoAuthLib folds this into atca_basic.h and no longer ships it. */ ++#if defined(__has_include) ++#if __has_include() + #include ++#endif ++#endif + #include "se_config.h" + + /** +diff --git a/crypto/se/se_crypto_support.c b/crypto/se/se_crypto_support.c +index fd90635..98c86ad 100644 +--- a/crypto/se/se_crypto_support.c ++++ b/crypto/se/se_crypto_support.c +@@ -115,7 +115,7 @@ int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) + * @return + * return 0 on success. -ve value on failure. + */ +-int32_t crypto_hal_hash(uint8_t hash_type, const uint8_t *buffer, ++int32_t crypto_hal_hash(int hash_type, const uint8_t *buffer, + size_t buffer_length, uint8_t *output, + size_t output_length) + { +@@ -161,55 +161,77 @@ int32_t crypto_hal_hash(uint8_t hash_type, const uint8_t *buffer, + static int32_t se_key_write(const uint8_t *key) + { + #if (HMAC_KEY_SLOT != ATCA_TEMPKEY_KEYID) +- bool data_locked, config_locked; +- int32_t ret = 0; +- uint8_t key_extend[36]; +- uint8_t write_key_for_encryption[32] = WRITE_KEY; +- +- ret = atcab_is_locked(LOCK_ZONE_DATA, &data_locked); +- ret |= atcab_is_locked(LOCK_ZONE_CONFIG, &config_locked); +- if (ATCA_SUCCESS != ret) { +- LOG(LOG_ERROR, "Failed to retrieve locked information\n"); +- } +- +- if (true == data_locked) { +- if (ATCA_SUCCESS != atcab_write_enc(HMAC_KEY_SLOT, 0, key, +- write_key_for_encryption, +- WRITE_KEY_ID)) { +- +- LOG(LOG_ERROR, "Encrypted key write to SE failed\n"); +- return -1; +- } +- } else { +- /* priv write expects a key of 36Bytes to be written to the +- * given slot. It also expects the first 4 Bytes to be 0. +- * Therefore a new buffer is created with size of 36 bytes +- * with leading 4 bytes as 0 and remaining 32Bytes is the +- * the key. +- */ +- if (0 != memset_s(key_extend, 0, 4)) { +- LOG(LOG_ERROR, "memset failed\n"); +- return -1; +- } +- if (0 != memcpy_s((key_extend + 4), 32, key, 32)) { +- LOG(LOG_ERROR, "memcpy failed\n"); ++ { ++ bool data_locked, config_locked; ++ int32_t ret = 0; ++ uint8_t key_extend[36]; ++ uint8_t write_key_for_encryption[32] = WRITE_KEY; ++#if !defined(ATCA_USE_CONSTANT_HOST_NONCE) ++ /* Fresh nonce seed for the write session key. */ ++ uint8_t num_in[NONCE_NUMIN_SIZE]; ++ ++ if (0 != crypto_hal_random_bytes(num_in, sizeof(num_in))) { ++ LOG(LOG_ERROR, "Failed to generate nonce for SE key write\n"); + return -1; + } ++#endif + +- /* priv_write wirte_key and write_key_id are NULL and 0 because +- * the data zone is unlocked. Therefore we can do clear text +- * write on these slots. +- */ +- if (ATCA_SUCCESS != +- atcab_priv_write(HMAC_KEY_SLOT, key_extend, 0x0, NULL)) { +- LOG(LOG_ERROR, "Encrypted key write to SE failed\n"); +- return -1; ++ ret = atcab_is_locked(LOCK_ZONE_DATA, &data_locked); ++ ret |= atcab_is_locked(LOCK_ZONE_CONFIG, &config_locked); ++ if (ATCA_SUCCESS != ret) { ++ LOG(LOG_ERROR, "Failed to retrieve locked information\n"); + } +- } + +- return 0; ++ if (true == data_locked) { ++#if defined(ATCA_USE_CONSTANT_HOST_NONCE) ++ if (ATCA_SUCCESS != atcab_write_enc(HMAC_KEY_SLOT, 0, key, ++ write_key_for_encryption, ++ WRITE_KEY_ID)) { ++#else ++ if (ATCA_SUCCESS != atcab_write_enc(HMAC_KEY_SLOT, 0, key, ++ write_key_for_encryption, ++ WRITE_KEY_ID, num_in)) { ++#endif ++ ++ LOG(LOG_ERROR, "Encrypted key write to SE failed\n"); ++ return -1; ++ } ++ } else { ++ /* priv write expects a key of 36Bytes to be written to the ++ * given slot. It also expects the first 4 Bytes to be 0. ++ * Therefore a new buffer is created with size of 36 bytes ++ * with leading 4 bytes as 0 and remaining 32Bytes is the ++ * the key. ++ */ ++ if (0 != memset_s(key_extend, 0, 4)) { ++ LOG(LOG_ERROR, "memset failed\n"); ++ return -1; ++ } ++ if (0 != memcpy_s((key_extend + 4), 32, key, 32)) { ++ LOG(LOG_ERROR, "memcpy failed\n"); ++ return -1; ++ } ++ ++ /* priv_write wirte_key and write_key_id are NULL and 0 because ++ * the data zone is unlocked. Therefore we can do clear text ++ * write on these slots. ++ */ ++#if defined(ATCA_USE_CONSTANT_HOST_NONCE) ++ if (ATCA_SUCCESS != ++ atcab_priv_write(HMAC_KEY_SLOT, key_extend, 0x0, NULL)) { + #else ++ if (ATCA_SUCCESS != ++ atcab_priv_write(HMAC_KEY_SLOT, key_extend, 0x0, NULL, ++ num_in)) { ++#endif ++ LOG(LOG_ERROR, "Encrypted key write to SE failed\n"); ++ return -1; ++ } ++ } + ++ return 0; ++ } ++#else + if (ATCA_SUCCESS != atcab_nonce_load(NONCE_MODE_TARGET_TEMPKEY, key, + BUFF_SIZE_32_BYTES)) { + LOG(LOG_ERROR, "Encrypted key write to SE failed\n"); +@@ -217,8 +239,7 @@ static int32_t se_key_write(const uint8_t *key) + } + + return 0; +- +-#endif /* (HMAC_KEY_SLOT != ATCA_TEMPKEY_KEYID) */ ++#endif + } + + /** +diff --git a/crypto/tpm/tpm20_ECDSA_sign_routines.c b/crypto/tpm/tpm20_ECDSA_sign_routines.c +new file mode 100644 +index 0000000..2de0aa9 +--- /dev/null ++++ b/crypto/tpm/tpm20_ECDSA_sign_routines.c +@@ -0,0 +1,162 @@ ++/* ++ * Copyright 2020 Intel Corporation ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Backend-agnostic ECDSA signing routine using tpm2.0 (tpm-tss). ++ */ ++ ++#include "safe_lib.h" ++#include "util.h" ++#include "fdo_crypto_hal.h" ++#include "tpm20_Utils.h" ++#include "tpm2_nv_storage.h" ++ ++/** ++ * Sign a message using provided ECDSA Private Keys. ++ * @param data - pointer of type uint8_t, holds the plaintext message. ++ * @param data_len - size of message, type size_t. ++ * @param message_signature - pointer of type unsigned char, which will be ++ * by filled with signature. ++ * @param signature_length - size of signature, pointer of type size_t. ++ * @return 0 if success, else -1. ++ */ ++int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, ++ unsigned char *message_signature, ++ size_t *signature_length) ++{ ++ ++ int32_t ret = -1; ++ TSS2_RC ret_val = TPM2_RC_FAILURE; ++ ESYS_CONTEXT *esys_context = NULL; ++ ESYS_TR primary_key_handle = ESYS_TR_NONE; ++ ESYS_TR auth_session_handle = ESYS_TR_NONE; ++ ESYS_TR tpm_ec_key_handle = ESYS_TR_NONE; ++ int sig_r_len = 0; ++ int sig_s_len = 0; ++ TPM2B_DIGEST *digest = NULL; ++ TPMT_TK_HASHCHECK *validation = NULL; ++ TPMT_SIGNATURE *signature = NULL; ++ TPM2B_MAX_BUFFER input_data; ++ size_t out_buf_len = 0; ++ // Set the signature scheme to ECDSA with SHA256 ++ TPMT_SIG_SCHEME inScheme = { ++ .scheme = TPM2_ALG_ECDSA, ++ .details = {.rsapss = {.hashAlg = FDO_TPM2_ALG_SHA}}}; ++ ++ if (!data || !data_len || !message_signature || !signature_length || ++ data_len > sizeof(input_data.buffer)) { ++ LOG(LOG_ERROR, "Invalid parameters received.\n"); ++ goto error; ++ } ++ ++ /* Caller's actual output buffer capacity. *signature_length gets ++ * overwritten below with the TPM-reported signature length, so it ++ * can no longer be used as memcpy_s's destsz by that point. */ ++ out_buf_len = *signature_length; ++ ++ input_data.size = data_len; ++ if (memcpy_s(input_data.buffer, sizeof(input_data.buffer), (char *)data, ++ (size_t)data_len) != 0) { ++ LOG(LOG_ERROR, "Memcpy Failed\n"); ++ goto error; ++ } ++ ++ if (0 != fdoTPMGenerate_primary_key_context(&esys_context, ++ &primary_key_handle, ++ &auth_session_handle)) { ++ LOG(LOG_ERROR, ++ "Failed to create primary key context from TPM.\n"); ++ goto error; ++ } ++ ++ ret_val = Esys_TR_FromTPMPublic( ++ esys_context, TPM_DEVICE_KEY_PERSISTANT_HANDLE, ESYS_TR_NONE, ++ ESYS_TR_NONE, ESYS_TR_NONE, &tpm_ec_key_handle); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to load EC Key Context.\n"); ++ goto error; ++ } ++ ++ ret_val = Esys_Hash(esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ++ ESYS_TR_NONE, &input_data, FDO_TPM2_ALG_SHA, ++ ESYS_TR_RH_OWNER, &digest, &validation); ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to create hash.\n"); ++ goto error; ++ } ++ ret_val = Esys_Sign(esys_context, tpm_ec_key_handle, ++ auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, ++ digest, &inScheme, validation, &signature); ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to create Sign Key.\n"); ++ goto error; ++ } ++ ++ sig_r_len = signature->signature.ecdsa.signatureR.size; ++ if (sig_r_len <= 0) { ++ LOG(LOG_ERROR, "Sig r len invalid\n"); ++ goto error; ++ } ++ ++ sig_s_len = signature->signature.ecdsa.signatureS.size; ++ if (sig_s_len <= 0) { ++ LOG(LOG_ERROR, "Sig s len invalid\n"); ++ goto error; ++ } ++ ++ *signature_length = sig_r_len + sig_s_len; ++ if (*signature_length > ECDSA_SIGNATURE_MAX_LEN || ++ *signature_length > out_buf_len) { ++ LOG(LOG_ERROR, "Invalid signature length\n"); ++ goto error; ++ } ++ ++ if (memcpy_s(message_signature, out_buf_len, ++ (char *)signature->signature.ecdsa.signatureR.buffer, ++ (size_t)sig_r_len) != 0) { ++ LOG(LOG_ERROR, "Memcpy Failed\n"); ++ goto error; ++ } ++ if (memcpy_s(message_signature + sig_r_len, out_buf_len - sig_r_len, ++ (char *)signature->signature.ecdsa.signatureS.buffer, ++ (size_t)sig_s_len) != 0) { ++ LOG(LOG_ERROR, "Memcpy Failed\n"); ++ goto error; ++ } ++ ret = 0; ++ ++error: ++ if (esys_context) { ++ if (tpm_ec_key_handle != ESYS_TR_NONE) { ++ if (Esys_TR_Close(esys_context, &tpm_ec_key_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush HMAC key handle.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, ++ "HMAC key handle flushed successfully.\n"); ++ tpm_ec_key_handle = ESYS_TR_NONE; ++ } ++ } ++ if (0 != fdoTPMTSSContext_clean_up(&esys_context, ++ &auth_session_handle, ++ &primary_key_handle)) { ++ LOG(LOG_ERROR, ++ "Failed to tear down all the TSS context.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, "TSS context flushed successfully.\n"); ++ } ++ } ++ ++ TPM2_ZEROISE_FREE(digest); ++ TPM2_ZEROISE_FREE(validation); ++ TPM2_ZEROISE_FREE(signature); ++ ++ return ret; ++} +diff --git a/crypto/tpm/tpm20_Utils.c b/crypto/tpm/tpm20_Utils.c +new file mode 100644 +index 0000000..91dc105 +--- /dev/null ++++ b/crypto/tpm/tpm20_Utils.c +@@ -0,0 +1,662 @@ ++/* ++ * Copyright 2020 Intel Corporation ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \ brief Abstraction layer for TPM Operations using ++ * \ tpm2.0(tpm-tools & tpm-tss-engine) and openssl library. ++ */ ++#include "util.h" ++#include "safe_lib.h" ++#include "tpm2_nv_storage.h" ++#include "tpm20_Utils.h" ++#include "fdo_crypto_hal.h" ++#include "storage_al.h" ++ ++/** ++ * Generates HMAC using TPM ++ * ++ * @param data: pointer to the input data ++ * @param data_length: length of the input data ++ * @param hmac: output buffer to save the HMAC ++ * @param hmac_length: length of the output HMAC buffer ++ *hash length ++ * @param persistent_handle: Persistent handle of the TPM HMAC public key ++ * @return ++ * 0, on success ++ * -1, on failure ++ */ ++int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, ++ size_t hmac_length, ++ TPMI_DH_PERSISTENT persistent_handle) ++{ ++ int32_t ret = -1, ret_val = -1; ++ size_t hashed_length = 0; ++ ESYS_CONTEXT *esys_context = NULL; ++ ESYS_TR primary_key_handle = ESYS_TR_NONE; ++ ESYS_TR auth_session_handle = ESYS_TR_NONE; ++ ESYS_TR hmac_key_handle = ESYS_TR_NONE; ++ ESYS_TR sequence_handle = ESYS_TR_NONE; ++ TPMT_TK_HASHCHECK *validation = NULL; ++ TPM2B_DIGEST *outHMAC = NULL; ++ TPM2B_MAX_BUFFER block = {0}; ++ TPM2B_AUTH null_auth = {0}; ++ ++ LOG(LOG_DEBUG, "HMAC generation from TPM function called.\n"); ++ ++ /* Validating all input parameters are passed in the function call*/ ++ ++ if (!data || !data_length || !persistent_handle || !hmac || ++ (hmac_length != PLATFORM_HMAC_SIZE)) { ++ LOG(LOG_ERROR, ++ "Failed to generate HMAC from TPM, invalid parameter" ++ " received.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "All required function parameters available.\n"); ++ ++ /*Creating TPM Primary Key Context*/ ++ ++ if (0 != fdoTPMGenerate_primary_key_context(&esys_context, ++ &primary_key_handle, ++ &auth_session_handle)) { ++ LOG(LOG_ERROR, ++ "Failed to create primary key context from TPM.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "TPM Primary Key Context created successfully.\n"); ++ ++ /* Loading the TPM Primary key, HMAC public key and HMAC Private Key to ++ * generate the HMAC Key Context */ ++ ++ ret_val = ++ Esys_TR_FromTPMPublic(esys_context, persistent_handle, ESYS_TR_NONE, ++ ESYS_TR_NONE, ESYS_TR_NONE, &hmac_key_handle); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to load HMAC Key Context.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "TPM HMAC Key Context generated successfully.\n"); ++ ++ /* Generating HMAC for input data, blockwise*/ ++ ++ if (data_length <= TPM2_MAX_DIGEST_BUFFER) { ++ ++ block.size = data_length; ++ ret_val = memcpy_s(block.buffer, sizeof(block.buffer), data, ++ data_length); ++ ++ if (ret_val != 0) { ++ LOG(LOG_ERROR, "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "Data copied from input buffer to TPM data" ++ " structure.\n"); ++ ++ ret_val = ++ Esys_HMAC(esys_context, hmac_key_handle, ++ auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, ++ &block, FDO_TPM2_ALG_SHA, &outHMAC); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "HMAC created successfully.\n"); ++ ++ } else { ++ ++ ret_val = Esys_HMAC_Start(esys_context, hmac_key_handle, ++ auth_session_handle, ESYS_TR_NONE, ++ ESYS_TR_NONE, &null_auth, ++ FDO_TPM2_ALG_SHA, &sequence_handle); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, ++ "HMAC generation initiated for data sequence.\n"); ++ ++ while (hashed_length != data_length) { ++ ++ if ((data_length - hashed_length) <= ++ TPM2_MAX_DIGEST_BUFFER) { ++ ++ block.size = (data_length - hashed_length); ++ ret_val = ++ memcpy_s(block.buffer, sizeof(block.buffer), ++ data + hashed_length, ++ (data_length - hashed_length)); ++ ++ if (ret_val != 0) { ++ LOG(LOG_ERROR, ++ "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "Data copied from input buffer " ++ "sequence to TPM" ++ " data structure.\n"); ++ ++ ret_val = Esys_SequenceComplete( ++ esys_context, sequence_handle, ++ auth_session_handle, ESYS_TR_NONE, ++ ESYS_TR_NONE, &block, TPM2_RH_NULL, ++ &outHMAC, &validation); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "HMAC generation for data " ++ "sequence completed" ++ " successfully.\n"); ++ /* Prevent err block from flushing consumed sequence. */ ++ sequence_handle = ESYS_TR_NONE; ++ hashed_length = data_length; ++ ++ } else { ++ ++ block.size = TPM2_MAX_DIGEST_BUFFER; ++ ret_val = ++ memcpy_s(block.buffer, sizeof(block.buffer), ++ data + hashed_length, ++ TPM2_MAX_DIGEST_BUFFER); ++ ++ if (ret_val != 0) { ++ LOG(LOG_ERROR, ++ "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, ++ "Data copied from input buffer sequence" ++ " to TPM data structure.\n"); ++ ++ ret_val = Esys_SequenceUpdate( ++ esys_context, sequence_handle, ++ auth_session_handle, ESYS_TR_NONE, ++ ESYS_TR_NONE, &block); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to create HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, ++ "Sequence handle updated successfully.\n"); ++ ++ hashed_length = ++ hashed_length + TPM2_MAX_DIGEST_BUFFER; ++ } ++ } ++ } ++ ++ if (!outHMAC || (hmac_length != outHMAC->size)) { ++ LOG(LOG_ERROR, "Incorrect HMAC Generated\n"); ++ goto err; ++ } ++ ++ ret_val = memcpy_s(hmac, hmac_length, outHMAC->buffer, outHMAC->size); ++ ++ if (ret_val != 0) { ++ LOG(LOG_ERROR, "Failed to copy HMAC.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, ++ "HMAC generation for data sequence completed successfully." ++ "\n"); ++ ++ ret = 0; ++ ++err: ++ if (esys_context) { ++ /* Flush unconsumed TRANSIENT sequence objects on error paths. */ ++ if (sequence_handle != ESYS_TR_NONE) { ++ if (Esys_FlushContext(esys_context, sequence_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush sequence handle.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, ++ "Sequence handle flushed successfully.\n"); ++ sequence_handle = ESYS_TR_NONE; ++ } ++ } ++ if (hmac_key_handle != ESYS_TR_NONE) { ++ if (Esys_TR_Close(esys_context, &hmac_key_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush HMAC key handle.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, ++ "HMAC key handle flushed successfully.\n"); ++ hmac_key_handle = ESYS_TR_NONE; ++ } ++ } ++ if (0 != fdoTPMTSSContext_clean_up(&esys_context, ++ &auth_session_handle, ++ &primary_key_handle)) { ++ LOG(LOG_ERROR, ++ "Failed to tear down all the TSS context.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, "TSS context flushed successfully.\n"); ++ } ++ } ++ TPM2_ZEROISE_FREE(validation); ++ TPM2_ZEROISE_FREE(outHMAC); ++ ++ return ret; ++} ++ ++/** ++ * Generates HMAC Key inside TPM ++ * ++ * @param persistent_handle: Persistent handle of the TPM HMAC key ++ * @return ++ * 0, on success ++ * -1, on failure ++ */ ++int32_t fdo_tpm_generate_hmac_key(TPMI_DH_PERSISTENT persistent_handle) ++{ ++ int32_t ret = -1; ++ TSS2_RC ret_val = TPM2_RC_FAILURE; ++ ESYS_CONTEXT *esys_context = NULL; ++ ESYS_TR primary_key_handle = ESYS_TR_NONE; ++ ESYS_TR auth_session_handle = ESYS_TR_NONE; ++ ESYS_TR object_handle = ESYS_TR_NONE; ++ ESYS_TR pub_object_handle = ESYS_TR_NONE; ++ ESYS_TR persistentHandle = ESYS_TR_NONE; ++ TPM2B_PUBLIC *out_public = NULL; ++ TPM2B_PRIVATE *out_private = NULL; ++ TPM2B_CREATION_DATA *creation_data = NULL; ++ TPM2B_DIGEST *creation_hash = NULL; ++ TPMT_TK_CREATION *creation_ticket = NULL; ++ TPMS_CAPABILITY_DATA *capability_data = NULL; ++ TPM2B_PUBLIC in_public = in_publicHMACKey_template; ++ TPM2B_SENSITIVE_CREATE in_sensitive_primary = {0}; ++ TPM2B_DATA outside_info = {0}; ++ TPML_PCR_SELECTION creationPCR = {0}; ++ /* Using same buffer for both public and private context, ++ private context size > public context size */ ++ ++ if (!persistent_handle) { ++ LOG(LOG_ERROR, "Failed to generate HMAC Key," ++ "invalid parameters received.\n"); ++ goto err; ++ } ++ ++ if (0 != fdoTPMGenerate_primary_key_context(&esys_context, ++ &primary_key_handle, ++ &auth_session_handle)) { ++ LOG(LOG_ERROR, ++ "Failed to create primary key context from TPM.\n"); ++ goto err; ++ } ++ ++ ret_val = Esys_Create(esys_context, primary_key_handle, ++ auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, ++ &in_sensitive_primary, &in_public, &outside_info, ++ &creationPCR, &out_private, &out_public, ++ &creation_data, &creation_hash, &creation_ticket); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to create HMAC Key.\n"); ++ goto err; ++ } ++ ++ ret_val = Esys_Load(esys_context, primary_key_handle, ++ auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, ++ out_private, out_public, &object_handle); ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Esys_Load failed: 0x%x\n", ret_val); ++ goto err; ++ } ++ ++ // Search the persistent Handle ++ ret_val = Esys_GetCapability( ++ esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ++ TPM2_CAP_HANDLES, persistent_handle, 1, NULL, &capability_data); ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Esys_GetCapability failed!\n"); ++ goto err; ++ } ++ ++ int exists = ++ (capability_data->data.handles.count > 0 && ++ capability_data->data.handles.handle[0] == persistent_handle); ++ if (exists == 1) { ++ ret_val = Esys_TR_FromTPMPublic( ++ esys_context, persistent_handle, ESYS_TR_NONE, ESYS_TR_NONE, ++ ESYS_TR_NONE, &persistentHandle); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to load HMAC Key Context.\n"); ++ goto err; ++ } ++ ++ ret_val = Esys_EvictControl( ++ esys_context, ESYS_TR_RH_OWNER, persistentHandle, ++ auth_session_handle, ESYS_TR_NONE, ESYS_TR_NONE, 0, ++ &pub_object_handle); ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Esys_EvictControl failed: 0x%x\n", ++ ret_val); ++ goto err; ++ } ++ } ++ ++ ret_val = Esys_EvictControl( ++ esys_context, ESYS_TR_RH_OWNER, object_handle, auth_session_handle, ++ ESYS_TR_NONE, ESYS_TR_NONE, persistent_handle, &pub_object_handle); ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Esys_EvictControl failed: 0x%x\n", ret_val); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, ++ "Saved HMAC private key context inside persistance memory at " ++ "%d.\n", ++ persistent_handle); ++ LOG(LOG_DEBUG, "HMAC Key generated successfully!.\n"); ++ ++ ret = 0; ++ ++err: ++ TPM2_ZEROISE_FREE(out_public); ++ TPM2_ZEROISE_FREE(out_private); ++ TPM2_ZEROISE_FREE(creation_data); ++ TPM2_ZEROISE_FREE(creation_hash); ++ TPM2_ZEROISE_FREE(creation_ticket); ++ TPM2_ZEROISE_FREE(capability_data); ++ ++ if (esys_context) { ++ if (object_handle != ESYS_TR_NONE) { ++ /* Flush transient object from Esys_Load to release TPM slot. */ ++ if (Esys_FlushContext(esys_context, object_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush object_handle.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, ++ "object_handle flushed successfully.\n"); ++ object_handle = ESYS_TR_NONE; ++ } ++ } ++ ++ if (pub_object_handle != ESYS_TR_NONE) { ++ if (Esys_TR_Close(esys_context, &pub_object_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush pub_object_handle.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, "pub_object_handle flushed " ++ "successfully.\n"); ++ pub_object_handle = ESYS_TR_NONE; ++ } ++ } ++ ++ if (persistentHandle != ESYS_TR_NONE) { ++ if (Esys_TR_Close(esys_context, &persistentHandle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush persistent handle.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, "persistent handle flushed " ++ "successfully.\n"); ++ persistentHandle = ESYS_TR_NONE; ++ } ++ } ++ if (0 != fdoTPMTSSContext_clean_up(&esys_context, ++ &auth_session_handle, ++ &primary_key_handle)) { ++ LOG(LOG_ERROR, ++ "Failed to tear down all the TSS context.\n"); ++ ret = -1; ++ } else { ++ LOG(LOG_DEBUG, "TSS context flushed successfully.\n"); ++ } ++ } ++ ++ return ret; ++} ++ ++/** ++ * Generate TPM Primary key Context from endorsement Hierarchy ++ * ++ * @param esys_context : output Esys Context ++ * @param primary_key_handle : output primary key handle ++ * @param auth_session_handle : output auth sesson handle for Esys API ++ * @return ++ * 0, on success ++ * -1, on failure ++ */ ++int32_t fdoTPMGenerate_primary_key_context(ESYS_CONTEXT **esys_context, ++ ESYS_TR *primary_key_handle, ++ ESYS_TR *auth_session_handle) ++{ ++ int ret = -1; ++ TSS2_RC ret_val = TPM2_RC_FAILURE; ++ TPM2B_SENSITIVE_CREATE in_sensitive_primary = {0}; ++ TPM2B_DATA outside_info = {0}; ++ TPML_PCR_SELECTION creationPCR = {0}; ++ TPM2B_PUBLIC *out_public = NULL; ++ TPM2B_CREATION_DATA *creation_data = NULL; ++ TPM2B_DIGEST *creation_hash = NULL; ++ TPMT_TK_CREATION *creation_ticket = NULL; ++ TPM2B_PUBLIC in_public = in_public_primary_key_template; ++ ++ if (!esys_context || !primary_key_handle || !auth_session_handle) { ++ LOG(LOG_ERROR, "Invalid parameter received.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "Generate Primary key context.\n"); ++ ++ if (0 != fdoTPMEsys_context_init(esys_context) || (!*esys_context)) { ++ LOG(LOG_ERROR, "Failed to Create Esys Context.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "Esys Context created succesfully!!\n"); ++ ++ if (0 != ++ fdoTPMEsys_auth_session_init(*esys_context, auth_session_handle)) { ++ LOG(LOG_ERROR, "Failed to create Auth Session for Esys API.\n"); ++ goto err; ++ } ++ ++ ret_val = Esys_CreatePrimary( ++ *esys_context, ESYS_TR_RH_ENDORSEMENT, *auth_session_handle, ++ ESYS_TR_NONE, ESYS_TR_NONE, &in_sensitive_primary, &in_public, ++ &outside_info, &creationPCR, primary_key_handle, &out_public, ++ &creation_data, &creation_hash, &creation_ticket); ++ ++ if (ret_val != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to create primary key.\n"); ++ goto err; ++ } ++ ++ ret = 0; ++ goto out; ++ ++err: ++ if (esys_context && *esys_context) { ++ fdoTPMTSSContext_clean_up(esys_context, auth_session_handle, ++ primary_key_handle); ++ } ++ ++out: ++ TPM2_ZEROISE_FREE(out_public); ++ TPM2_ZEROISE_FREE(creation_data); ++ TPM2_ZEROISE_FREE(creation_hash); ++ TPM2_ZEROISE_FREE(creation_ticket); ++ ++ return ret; ++} ++ ++/** ++ * Initialize Esys context. ++ * ++ * @param esys_context : output Esys Context ++ * ++ * @return ++ * 0, on success ++ * -1, on failure ++ */ ++int32_t fdoTPMEsys_context_init(ESYS_CONTEXT **esys_context) ++{ ++ int ret = -1; ++ TSS2_TCTI_CONTEXT *tcti_context = NULL; ++ ++ if (!esys_context) { ++ LOG(LOG_ERROR, "Invalid parameter received.\n"); ++ goto err; ++ } ++ ++ /* Define out-param on failure paths. */ ++ *esys_context = NULL; ++ ++ if ((TSS2_RC_SUCCESS != ++ Tss2_TctiLdr_Initialize(TPM2_TCTI_TYPE, &tcti_context)) || ++ (!tcti_context)) { ++ LOG(LOG_ERROR, "TCTI Context initialization failed.\n"); ++ goto err; ++ } ++ ++ LOG(LOG_DEBUG, "TCTI Initialized succesfully!!\n"); ++ ++ if (Esys_Initialize(esys_context, tcti_context, NULL) != ++ TPM2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to intitialize Esys context.\n"); ++ goto err; ++ } ++ ++ return 0; ++ ++err: ++ if (tcti_context) { ++ Tss2_TctiLdr_Finalize(&tcti_context); ++ } ++ return ret; ++} ++ ++/** ++ * Create HMAC based auth session for Esys Context ++ * ++ * @param esys_context : input Esys Context ++ * @param session_handle : output authentication session Handle ++ * ++ * @return ++ * 0, on success ++ * -1, on failure ++ */ ++int32_t fdoTPMEsys_auth_session_init(ESYS_CONTEXT *esys_context, ++ ESYS_TR *session_handle) ++{ ++ int ret = -1; ++ TPMT_SYM_DEF symmetric = {0}; ++ symmetric.algorithm = TPM2_ALG_NULL; ++ ++ TSS2_RC rval = Esys_StartAuthSession( ++ esys_context, ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, ++ ESYS_TR_NONE, ESYS_TR_NONE, NULL, TPM2_SE_HMAC, &symmetric, ++ FDO_TPM2_ALG_SHA, session_handle); ++ ++ if (rval != TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to start the auth session.\n"); ++ return ret; ++ } ++ ++ return 0; ++} ++ ++/** ++ * Clear Esys, TCTI, contexts and Auth Session, Primary Key handles. ++ * ++ * @param esys_context : Esys Context to be cleared ++ * @param auth_session_handle : Auth session Handle to be flushed ++ * @param primary_handle : Primary key handle to be cleared ++ * @return ++ * 0, on success ++ * -1, on failure ++ */ ++int32_t fdoTPMTSSContext_clean_up(ESYS_CONTEXT **esys_context, ++ ESYS_TR *auth_session_handle, ++ ESYS_TR *primary_handle) ++{ ++ int ret = -1, is_failed = 0; ++ TSS2_TCTI_CONTEXT *tcti_context = NULL; ++ TSS2_RC rc = TPM2_RC_FAILURE; ++ ++ if (!esys_context || !*esys_context) { ++ LOG(LOG_ERROR, "Invalid parameter received.\n"); ++ return ret; ++ } ++ ++ if (auth_session_handle && (*auth_session_handle != ESYS_TR_NONE)) { ++ if (Esys_FlushContext(*esys_context, *auth_session_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "Failed to flush auth session handle.\n"); ++ is_failed = 1; ++ } else { ++ LOG(LOG_DEBUG, ++ "Auth session handle flushed successfully.\n"); ++ *auth_session_handle = ESYS_TR_NONE; ++ } ++ } ++ ++ if (primary_handle && (*primary_handle != ESYS_TR_NONE)) { ++ if (Esys_FlushContext(*esys_context, *primary_handle) != ++ TSS2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to flush primary key handle.\n"); ++ is_failed = 1; ++ } else { ++ LOG(LOG_DEBUG, ++ "Primary key handle flushed successfully.\n"); ++ *primary_handle = ESYS_TR_NONE; ++ } ++ } ++ ++ rc = Esys_GetTcti(*esys_context, &tcti_context); ++ if (rc != TPM2_RC_SUCCESS) { ++ LOG(LOG_ERROR, "Failed to cleanup TCTI.\n"); ++ is_failed = 1; ++ } ++ Esys_Finalize(esys_context); ++ ++ if (tcti_context) { ++ Tss2_TctiLdr_Finalize(&tcti_context); ++ if (tcti_context) { ++ LOG(LOG_ERROR, "Failed to finalize context.\n"); ++ is_failed = 1; ++ } ++ } ++ ++ if (is_failed) { ++ return ret; ++ } ++ ++ return 0; ++} +diff --git a/crypto/tpm/wolftpm_ECDSA_sign_routines.c b/crypto/tpm/wolftpm_ECDSA_sign_routines.c +new file mode 100644 +index 0000000..7753970 +--- /dev/null ++++ b/crypto/tpm/wolftpm_ECDSA_sign_routines.c +@@ -0,0 +1,147 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Backend-agnostic ECDSA signing routine using wolfTPM. ++ */ ++ ++#include "safe_lib.h" ++#include "util.h" ++#include "fdo_tpm_handles.h" ++#include "wolftpm_utils.h" ++ ++#include ++ ++/* No fdo_crypto_hal.h: under USE_OPENSSL it pulls in , which ++ * collides with wolfTPM's OpenSSL-compat shims. Hash on the TPM instead. */ ++#if defined(ECDSA256_DA) ++#define FDO_WOLFTPM_ECDSA_HASH_ALG TPM_ALG_SHA256 ++#define FDO_WOLFTPM_ECDSA_HASH_SIZE 32 ++#elif defined(ECDSA384_DA) ++#define FDO_WOLFTPM_ECDSA_HASH_ALG TPM_ALG_SHA384 ++#define FDO_WOLFTPM_ECDSA_HASH_SIZE 48 ++#else ++#error "No supported ECDSA curve defined (ECDSA256_DA or ECDSA384_DA)" ++#endif ++ ++/* Prototype matches fdo_crypto_hal.h (not included, see above). */ ++int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, ++ unsigned char *message_signature, ++ size_t *signature_length); ++ ++/* Max raw R||S size across supported curves (P-521: 2 * 66 bytes = 132), ++ * rounded up. fdo_crypto_hal.h can't be included here (see above), but its ++ * ECDSA_SIGNATURE_MAX_LEN resolves to this same BUFF_SIZE_256_BYTES from ++ * util.h, so derive from that instead of a second hardcoded literal. */ ++#define FDO_WOLFTPM_ECDSA_SIG_MAX_LEN BUFF_SIZE_256_BYTES ++ ++/** ++ * Sign a message using the device's ECDSA private key via wolfTPM. ++ */ ++int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, ++ unsigned char *message_signature, ++ size_t *signature_length) ++{ ++ int32_t ret_val = -1; ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_KEY eccKey; ++ WOLFTPM2_HASH hashCtx; ++ byte hash[FDO_WOLFTPM_ECDSA_HASH_SIZE]; ++ word32 hashSz = sizeof(hash); ++ byte sig_buffer[FDO_WOLFTPM_ECDSA_SIG_MAX_LEN]; /* Sized for up to ECDSA521 */ ++ int sigSz = sizeof(sig_buffer); ++ int dev_inited = 0; ++ int eccKey_loaded = 0; ++ int hashCtx_started = 0; ++ ++ if (!data || !data_len || !message_signature || !signature_length) { ++ LOG(LOG_ERROR, "Invalid Parameters received.\n"); ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ dev_inited = 1; ++ ++ /* Load the persistent key's public info and validate its type first, ++ * before paying for a TPM hash round trip on a key we'd reject anyway. */ ++ XMEMSET(&eccKey, 0, sizeof(eccKey)); ++ rc = wolfTPM2_ReadPublicKey(&dev, &eccKey, TPM_DEVICE_KEY_PERSISTANT_HANDLE); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_ReadPublicKey failed: %d\n", rc); ++ goto done; ++ } ++ eccKey_loaded = 1; ++ ++ if (eccKey.pub.publicArea.type != TPM_ALG_ECC) { ++ LOG(LOG_ERROR, "Persistent key handle does not hold an ECC key\n"); ++ goto done; ++ } ++ ++ /* wolfTPM2_SignHash signs a digest, not the raw message. */ ++ XMEMSET(&hashCtx, 0, sizeof(hashCtx)); ++ rc = wolfTPM2_HashStart(&dev, &hashCtx, FDO_WOLFTPM_ECDSA_HASH_ALG, ++ NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_HashStart failed: %d\n", rc); ++ goto done; ++ } ++ hashCtx_started = 1; ++ ++ rc = wolfTPM2_HashUpdate(&dev, &hashCtx, data, (word32)data_len); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_HashUpdate failed: %d\n", rc); ++ goto done; ++ } ++ rc = wolfTPM2_HashFinish(&dev, &hashCtx, hash, &hashSz); ++ hashCtx_started = 0; /* HashFinish unloads the sequence object either way */ ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_HashFinish failed: %d\n", rc); ++ goto done; ++ } ++ ++ /* FDO expects raw R||S, which wolfTPM produces for ECC keys. Pass the ++ * scheme explicitly: for a key with a NULL scheme (as provisioned by ++ * tpm_make_ready_ecdsa.sh), wolfTPM2_SignHash() reads the hash from the ++ * unmarshalled-but-unset scheme details, which can hold stack garbage. */ ++ rc = wolfTPM2_SignHashScheme(&dev, &eccKey, hash, sizeof(hash), ++ sig_buffer, &sigSz, TPM_ALG_ECDSA, ++ FDO_WOLFTPM_ECDSA_HASH_ALG); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_SignHashScheme failed: %d\n", rc); ++ goto done; ++ } ++ ++ if ((size_t)sigSz > *signature_length) { ++ LOG(LOG_ERROR, "Signature buffer too small\n"); ++ goto done; ++ } ++ ++ /* Copy signature to output buffer */ ++ if (memcpy_s(message_signature, *signature_length, sig_buffer, sigSz) != 0) { ++ LOG(LOG_ERROR, "memcpy_s failed\n"); ++ goto done; ++ } ++ *signature_length = (size_t)sigSz; ++ ++ ret_val = 0; /* Success */ ++ ++done: ++ if (hashCtx_started) { ++ wolfTPM2_UnloadHandle(&dev, &hashCtx.handle); ++ } ++ if (eccKey_loaded) { ++ wolfTPM2_UnloadHandle(&dev, &eccKey.handle); ++ } ++ if (dev_inited) { ++ wolfTPM2_Cleanup(&dev); ++ } ++ return ret_val; ++} +diff --git a/crypto/tpm/wolftpm_hmac.c b/crypto/tpm/wolftpm_hmac.c +new file mode 100644 +index 0000000..786c948 +--- /dev/null ++++ b/crypto/tpm/wolftpm_hmac.c +@@ -0,0 +1,196 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Backend-agnostic TPM HMAC routines using wolfTPM. ++ */ ++ ++#include ++#include ++#include "safe_lib.h" ++#include "util.h" ++#include "fdo_tpm_handles.h" ++#include "wolftpm_utils.h" ++#include ++ ++#if defined(ECDSA256_DA) ++#define FDO_WOLFTPM_HMAC_ALG TPM_ALG_SHA256 ++#elif defined(ECDSA384_DA) ++#define FDO_WOLFTPM_HMAC_ALG TPM_ALG_SHA384 ++#else ++#error "No supported ECDSA curve defined (ECDSA256_DA or ECDSA384_DA)" ++#endif ++ ++int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, ++ size_t hmac_length, uint32_t persistent_handle) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_HMAC hmacCtx; ++ word32 outSz = (word32)hmac_length; ++ ++ if (!data || !data_length || !hmac || !hmac_length || !persistent_handle) { ++ LOG(LOG_ERROR, "Invalid Parameters received.\n"); ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ XMEMSET(&hmacCtx, 0, sizeof(hmacCtx)); ++ ++ /* Load persistent HMAC key public info. */ ++ rc = wolfTPM2_ReadPublicKey(&dev, &hmacCtx.key, persistent_handle); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_ReadPublicKey failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ hmacCtx.hmacKeyLoaded = 1; ++ hmacCtx.hmacKeyKeep = 1; ++ ++ rc = wolfTPM2_HmacStart(&dev, &hmacCtx, NULL, FDO_WOLFTPM_HMAC_ALG, ++ NULL, 0, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_HmacStart failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ rc = wolfTPM2_HmacUpdate(&dev, &hmacCtx, data, (word32)data_length); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_HmacUpdate failed: %d\n", rc); ++ /* Unload transient sequence object hmacCtx.hash. */ ++ wolfTPM2_UnloadHandle(&dev, &hmacCtx.hash.handle); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ rc = wolfTPM2_HmacFinish(&dev, &hmacCtx, hmac, &outSz); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_HmacFinish failed: %d\n", rc); ++ wolfTPM2_UnloadHandle(&dev, &hmacCtx.hash.handle); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ if ((size_t)outSz != hmac_length) { ++ LOG(LOG_ERROR, "Incorrect HMAC length generated\n"); ++ wolfTPM2_UnloadHandle(&dev, &hmacCtx.key.handle); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_UnloadHandle(&dev, &hmacCtx.key.handle); ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++} ++ ++int32_t fdo_tpm_generate_hmac_key(uint32_t persistent_handle) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_KEY srk; ++ WOLFTPM2_KEY existingKey; ++ WOLFTPM2_KEY hmacKey; ++ TPMT_PUBLIC publicTemplate; ++ ++ if (!persistent_handle) { ++ LOG(LOG_ERROR, "Invalid parameters received.\n"); ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ XMEMSET(&srk, 0, sizeof(srk)); ++ rc = wolfTPM2_CreateSRK(&dev, &srk, TPM_ALG_ECC, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_CreateSRK failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ /* Build the KeyedHash template ourselves (rather than ++ * wolfTPM2_GetKeyTemplate_KeyedHash(), which is meant for importing ++ * externally-supplied key material) so we can set ++ * TPMA_OBJECT_sensitiveDataOrigin. That tells the TPM to generate the ++ * HMAC key's sensitive data with its own internal RNG, so the secret ++ * never exists in host process memory. */ ++ XMEMSET(&publicTemplate, 0, sizeof(publicTemplate)); ++ publicTemplate.type = TPM_ALG_KEYEDHASH; ++ /* Attributes and nameAlg match the tpm2 backend's ++ * in_publicHMACKey_template, binding the key to this TPM and SRK. */ ++ publicTemplate.nameAlg = FDO_WOLFTPM_HMAC_ALG; ++ publicTemplate.objectAttributes = (TPMA_OBJECT_fixedTPM | ++ TPMA_OBJECT_fixedParent | ++ TPMA_OBJECT_sensitiveDataOrigin | ++ TPMA_OBJECT_userWithAuth | ++ TPMA_OBJECT_noDA | ++ TPMA_OBJECT_sign); ++ publicTemplate.parameters.keyedHashDetail.scheme.scheme = ++ TPM_ALG_HMAC; ++ publicTemplate.parameters.keyedHashDetail.scheme.details.hmac.hashAlg ++ = FDO_WOLFTPM_HMAC_ALG; ++ /* TPM2_Create ignores unique when generating; a nonzero size larger ++ * than the TPM's largest digest is rejected with TPM_RC_SIZE. */ ++ publicTemplate.unique.keyedHash.size = 0; ++ ++ XMEMSET(&hmacKey, 0, sizeof(hmacKey)); ++ rc = wolfTPM2_CreateAndLoadKey(&dev, &hmacKey, &srk.handle, ++ &publicTemplate, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_CreateAndLoadKey failed: %d\n", rc); ++ wolfTPM2_UnloadHandle(&dev, &srk.handle); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ /* Free handle before storing new key, retrying to minimize empty window. */ ++ XMEMSET(&existingKey, 0, sizeof(existingKey)); ++ if (wolfTPM2_ReadPublicKey(&dev, &existingKey, persistent_handle) == ++ TPM_RC_SUCCESS) { ++ rc = wolfTPM2_NVDeleteKey(&dev, TPM_RH_OWNER, &existingKey); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVDeleteKey failed: %d\n", ++ rc); ++ /* Old key remains on delete failure. */ ++ wolfTPM2_UnloadHandle(&dev, &hmacKey.handle); ++ wolfTPM2_UnloadHandle(&dev, &srk.handle); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ } ++ ++ /* wolftpm_init_dev() already configures the transport to retry ++ * TPM_RC_RETRY (TPM momentarily busy) up to WOLFTPM_MAX_RETRIES_ON_BUSY ++ * times internally, so a single call here gets that retry behavior ++ * without stacking a redundant outer retry loop on top of it. */ ++ rc = wolfTPM2_NVStoreKey(&dev, TPM_RH_OWNER, &hmacKey, ++ persistent_handle); ++ if (rc != TPM_RC_SUCCESS) { ++ /* Handle empty; manual reset required. */ ++ LOG(LOG_ERROR, ++ "wolfTPM2_NVStoreKey failed: %d; " ++ "persistent_handle 0x%x now holds no HMAC key\n", ++ rc, persistent_handle); ++ wolfTPM2_UnloadHandle(&dev, &hmacKey.handle); ++ wolfTPM2_UnloadHandle(&dev, &srk.handle); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_UnloadHandle(&dev, &hmacKey.handle); ++ wolfTPM2_UnloadHandle(&dev, &srk.handle); ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++} +diff --git a/crypto/wolfssl/BN_support.c b/crypto/wolfssl/BN_support.c +new file mode 100644 +index 0000000..56249a7 +--- /dev/null ++++ b/crypto/wolfssl/BN_support.c +@@ -0,0 +1,94 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++#include "BN_support.h" ++#include "fdo_crypto_hal.h" ++#include ++#include "safe_lib.h" ++#include "util.h" ++#include ++#include ++#include ++ ++/* Convert FDOBits to bignum_t */ ++int byte_array_to_bn(bignum_t *bn, fdo_byte_array_t *in) ++{ ++ ++ if (in == NULL || bn == NULL) { ++ return -1; ++ } ++ if (in->byte_sz == 0 || in->bytes == NULL) { ++ return -1; ++ } ++ ++ return bn_bin2bn(in->bytes, in->byte_sz, bn); ++} ++ ++/* Convert FDOBits to bignum_t (Java compat). */ ++fdo_byte_array_t *bn_to_byte_array(bignum_t *in) ++{ ++ int len; ++ fdo_byte_array_t *ba; ++ ++ if (in == NULL) { ++ return NULL; ++ } ++ ++ len = bn_num_bytes(in); ++ ba = fdo_byte_array_alloc(len + 1); ++ if (ba == NULL) { ++ return NULL; ++ } ++ ++ if (bn_bn2bin(in, ba->bytes) == 0) { ++ fdo_byte_array_free(ba); ++ return NULL; ++ } ++ ++ /* Add zero byte if upper bit is set. */ ++ if (ba->bytes[0] & 0x80) { ++ if (memmove_s(&ba->bytes[1], ba->byte_sz, ba->bytes, len) != ++ 0) { ++ LOG(LOG_ERROR, "Memmove Failed\n"); ++ fdo_byte_array_free(ba); ++ return NULL; ++ } ++ ba->bytes[0] = 0; ++ } else { ++ ba->byte_sz--; ++ } ++ ++ return ba; ++} ++ ++int bn_rand(bignum_t *rnd, int size) ++{ ++ int bytes; ++ unsigned char *buf; ++ int ret = -1; ++ ++ if (NULL == rnd) { ++ return -1; ++ } ++ ++ bytes = size; ++ buf = fdo_alloc(bytes); ++ if (buf == NULL) { ++ return -1; ++ } ++ ++ if (0 == crypto_hal_random_bytes(buf, bytes)) { ++ /* Force MSB so result is `size` bytes wide. */ ++ if (bytes > 0) { ++ buf[0] |= 0x80; ++ } ++ if (mp_read_unsigned_bin(rnd, buf, bytes) == 0) { ++ ret = 0; ++ } ++ } ++ wc_ForceZero(buf, bytes); ++ fdo_free(buf); ++ return ret; ++} +diff --git a/crypto/wolfssl/wolfssl_AESRoutines.c b/crypto/wolfssl/wolfssl_AESRoutines.c +new file mode 100644 +index 0000000..363ab00 +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_AESRoutines.c +@@ -0,0 +1,159 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief AES encrypt/decrypt abstraction over wolfCrypt. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "safe_lib.h" ++#include ++#include ++ ++/* Validate AES-GCM/CCM params. */ ++static int aes_params_valid(size_t block_size, const uint8_t *iv, ++ const uint8_t *key, uint32_t key_length, ++ uint8_t *tag, size_t tag_length, ++ const uint8_t *aad, size_t aad_length) ++{ ++ if (FDO_AES_BLOCK_SIZE == block_size && iv != NULL && key != NULL && ++ FDO_AES_KEY_LENGTH == key_length && tag != NULL && ++ AES_TAG_LEN == tag_length && ++ ((aad == NULL && aad_length == 0) || (aad != NULL && aad_length != 0))) { ++ return 0; ++ } ++ return -1; ++} ++ ++/* Run AES-GCM/CCM cipher. */ ++static int32_t aes_gcm_ccm_crypt(int do_encrypt, const uint8_t *in, ++ uint32_t in_len, uint8_t *out, ++ uint32_t *out_len, const uint8_t *iv, ++ const uint8_t *key, uint32_t key_length, ++ uint8_t *tag, size_t tag_length, ++ const uint8_t *aad, size_t aad_length) ++{ ++ Aes aes; ++ int ret; ++ ++ if (wc_AesInit(&aes, NULL, INVALID_DEVID) != 0) { ++ LOG(LOG_ERROR, "wc_AesInit failed\n"); ++ return -1; ++ } ++ ++#if defined(AES_MODE_CCM_ENABLED) ++ ret = wc_AesCcmSetKey(&aes, key, key_length); ++ if (ret != 0) { ++ LOG(LOG_ERROR, "wc_AesCcmSetKey failed: %d\n", ret); ++ ret = -1; ++ } else { ++ ret = do_encrypt ++ ? wc_AesCcmEncrypt(&aes, out, in, in_len, iv, ++ AES_IV_LEN, tag, tag_length, aad, ++ aad_length) ++ : wc_AesCcmDecrypt(&aes, out, in, in_len, iv, ++ AES_IV_LEN, tag, tag_length, aad, ++ aad_length); ++ if (ret != 0) { ++ LOG(LOG_ERROR, "wc_AesCcm%s failed: %d\n", ++ do_encrypt ? "Encrypt" : "Decrypt", ret); ++ } ++ } ++#else ++ ret = wc_AesGcmSetKey(&aes, key, key_length); ++ if (ret != 0) { ++ LOG(LOG_ERROR, "wc_AesGcmSetKey failed: %d\n", ret); ++ ret = -1; ++ } else { ++ ret = do_encrypt ++ ? wc_AesGcmEncrypt(&aes, out, in, in_len, iv, ++ AES_IV_LEN, tag, tag_length, aad, ++ aad_length) ++ : wc_AesGcmDecrypt(&aes, out, in, in_len, iv, ++ AES_IV_LEN, tag, tag_length, aad, ++ aad_length); ++ if (ret != 0) { ++ LOG(LOG_ERROR, "wc_AesGcm%s failed: %d\n", ++ do_encrypt ? "Encrypt" : "Decrypt", ret); ++ } ++ } ++#endif ++ ++ wc_AesFree(&aes); ++ memset_s(&aes, sizeof(aes), 0); ++ ++ if (ret != 0) { ++ return -1; ++ } ++ *out_len = in_len; ++ return 0; ++} ++ ++/* Encrypt clear_text using key. */ ++int32_t crypto_hal_aes_encrypt(const uint8_t *clear_text, ++ uint32_t clear_text_length, uint8_t *cypher_text, ++ uint32_t *cypher_length, size_t block_size, ++ const uint8_t *iv, const uint8_t *key, ++ uint32_t key_length, uint8_t *tag, ++ size_t tag_length, const uint8_t *aad, ++ size_t aad_length) ++{ ++ if (clear_text == NULL || clear_text_length == 0 || ++ cypher_text == NULL || cypher_length == NULL || ++ aes_params_valid(block_size, iv, key, key_length, tag, ++ tag_length, aad, aad_length) != 0) { ++ LOG(LOG_ERROR, "Invalid parameters received\n"); ++ return -1; ++ } ++ ++ if (*cypher_length < clear_text_length) { ++ LOG(LOG_ERROR, "Output buffer is not sufficient\n"); ++ return -1; ++ } ++ ++ if (aes_gcm_ccm_crypt(1, clear_text, clear_text_length, cypher_text, ++ cypher_length, iv, key, key_length, tag, ++ tag_length, aad, aad_length) != 0) { ++ memset_s(cypher_text, *cypher_length, 0); ++ return -1; ++ } ++ ++ return 0; ++} ++ ++/* Decrypt cypher_text using key. */ ++int32_t crypto_hal_aes_decrypt(uint8_t *clear_text, uint32_t *clear_text_length, ++ const uint8_t *cypher_text, ++ uint32_t cypher_length, size_t block_size, ++ const uint8_t *iv, const uint8_t *key, ++ uint32_t key_length, uint8_t *tag, ++ size_t tag_length, const uint8_t *aad, ++ size_t aad_length) ++{ ++ if (clear_text == NULL || clear_text_length == NULL || ++ cypher_text == NULL || cypher_length == 0 || ++ aes_params_valid(block_size, iv, key, key_length, tag, ++ tag_length, aad, aad_length) != 0) { ++ LOG(LOG_ERROR, "Invalid parameters received\n"); ++ return -1; ++ } ++ ++ if (*clear_text_length < cypher_length) { ++ LOG(LOG_ERROR, "Output buffer is not sufficient\n"); ++ return -1; ++ } ++ ++ if (aes_gcm_ccm_crypt(0, cypher_text, cypher_length, clear_text, ++ clear_text_length, iv, key, key_length, tag, ++ tag_length, aad, aad_length) != 0) { ++ memset_s(clear_text, *clear_text_length, 0); ++ *clear_text_length = 0; ++ return -1; ++ } ++ ++ return 0; ++} +diff --git a/crypto/wolfssl/wolfssl_DERRoutines.c b/crypto/wolfssl/wolfssl_DERRoutines.c +new file mode 100644 +index 0000000..8fceafd +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_DERRoutines.c +@@ -0,0 +1,121 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Abstraction layer for raw r||s <-> DER ECDSA signature conversion, ++ * used by the Secure Element (CRYPTO_HW=true) hardware path. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "storage_al.h" ++#include "safe_lib.h" ++#include ++#include ++#include "wolfssl_ecdsa_util.h" ++ ++/* Convert raw r||s ECDSA signature to DER. */ ++int32_t crypto_hal_der_encode(uint8_t *raw_sig, size_t raw_sig_length, ++ uint8_t *message_signature, ++ size_t *signature_length) ++{ ++ word32 sigLen; ++ ++ if (raw_sig == NULL || (BUFF_SIZE_64_BYTES != raw_sig_length && BUFF_SIZE_96_BYTES != raw_sig_length) || ++ message_signature == NULL || signature_length == NULL) { ++ return -1; ++ } ++ ++ sigLen = (word32)*signature_length; ++ if (wc_ecc_rs_raw_to_sig(raw_sig, raw_sig_length / 2, ++ raw_sig + (raw_sig_length / 2), raw_sig_length / 2, ++ message_signature, &sigLen) != 0) { ++ return -1; ++ } ++ *signature_length = sigLen; ++ ++ return 0; ++} ++ ++/* Convert DER-encoded EC pubkey and signature to raw r||s. */ ++int32_t crypto_hal_der_decode(uint8_t *raw_key, uint8_t *raw_sig, ++ const unsigned char *pub_key, size_t key_length, ++ const uint8_t *message_signature, ++ size_t signature_length, size_t raw_key_length, ++ size_t raw_sig_length) ++{ ++ ecc_key key; ++ int ret = -1; ++ word32 pubKeyIdx = 0; ++ word32 xLen; ++ word32 yLen; ++ word32 rLen; ++ word32 sLen; ++ /* +1 for 0x00 sign-padding byte */ ++ unsigned char r[(BUFF_SIZE_96_BYTES / 2) + 1] = {0}; ++ unsigned char s[(BUFF_SIZE_96_BYTES / 2) + 1] = {0}; ++ ++ if (raw_key == NULL || raw_sig == NULL || pub_key == NULL || key_length == 0 || ++ message_signature == NULL || signature_length == 0 || ++ (BUFF_SIZE_64_BYTES != raw_sig_length && BUFF_SIZE_96_BYTES != raw_sig_length) || ++ (BUFF_SIZE_64_BYTES != raw_key_length && BUFF_SIZE_96_BYTES != raw_key_length)) { ++ return -1; ++ } ++ ++ xLen = (word32)(raw_key_length / 2); ++ yLen = (word32)(raw_key_length / 2); ++ ++ /* Zero caller-supplied output buffers up front so every failure path ++ * below (including ones that break before either buffer is ever ++ * written) leaves them zeroed rather than holding stale content. */ ++ memset_s(raw_key, raw_key_length, 0); ++ memset_s(raw_sig, raw_sig_length, 0); ++ ++ if (wc_ecc_init(&key) != 0) { ++ return -1; ++ } ++ ++ do { ++ if (wc_EccPublicKeyDecode(pub_key, &pubKeyIdx, &key, ++ (word32)key_length) != 0) { ++ break; ++ } ++ ++ if (wc_ecc_export_public_raw(&key, raw_key, &xLen, ++ raw_key + (raw_key_length / 2), &yLen) != 0) { ++ break; ++ } ++ if (xLen != raw_key_length / 2 || yLen != raw_key_length / 2) { ++ break; ++ } ++ ++ rLen = sizeof(r); ++ sLen = sizeof(s); ++ if (wc_ecc_sig_to_rs(message_signature, ++ (word32)signature_length, r, &rLen, ++ s, &sLen) != 0) { ++ break; ++ } ++ ++ size_t half_sig = raw_sig_length / 2; ++ ++ if (wolfssl_ecdsa_place_coord(raw_sig, half_sig, r, rLen) != 0) { ++ LOG(LOG_ERROR, "Invalid r length\n"); ++ break; ++ } ++ if (wolfssl_ecdsa_place_coord(raw_sig + half_sig, half_sig, s, sLen) != 0) { ++ LOG(LOG_ERROR, "Invalid s length\n"); ++ break; ++ } ++ ++ ret = 0; ++ } while (0); ++ ++ wc_ecc_free(&key); ++ memset_s(r, sizeof(r), 0); ++ memset_s(s, sizeof(s), 0); ++ return ret; ++} +diff --git a/crypto/wolfssl/wolfssl_ECDSASignRoutines.c b/crypto/wolfssl/wolfssl_ECDSASignRoutines.c +new file mode 100644 +index 0000000..2653ecb +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_ECDSASignRoutines.c +@@ -0,0 +1,124 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief ECDSA signing abstraction over wolfCrypt, for the software ++ * (non-TPM, non-CSE) device-attestation path. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "safe_lib.h" ++#include ++#include ++#include ++#include "wolfssl_ecdsa_util.h" ++#include "wolfssl_rng_util.h" ++ ++#if defined(ECDSA256_DA) ++#define FDO_ECDSA_SIGN_COORD_SIZE FDO_ECDSA_P256_COORD_SIZE ++#elif defined(ECDSA384_DA) ++#define FDO_ECDSA_SIGN_COORD_SIZE FDO_ECDSA_P384_COORD_SIZE ++#endif ++ ++/* Sign a message using ECDSA private key. */ ++int32_t crypto_hal_ecdsa_sign(const uint8_t *message, size_t message_len, ++ unsigned char *signature, size_t *signature_len) ++{ ++ unsigned char hash[FDO_SHA_DIGEST_SIZE_USED] = {0}; ++ ecc_key key; ++ int ret = -1; ++ word32 sig_len; ++ unsigned char der_sig[ECDSA_SIGNATURE_MAX_LEN] = {0}; ++ word32 r_len = 0, s_len = 0; ++ unsigned char r[BUFF_SIZE_64_BYTES] = {0}; ++ unsigned char s[BUFF_SIZE_64_BYTES] = {0}; ++ WC_RNG *rng = NULL; ++ int key_inited = 0; ++ /* Coordinate half-size for the compiled-in curve, not derived from ++ * the hash size (see wolfssl_ecdsa_coord_size() for the verify-side ++ * counterpart, which is the same value keyed off key_algorithm). */ ++ uint32_t expected_half = FDO_ECDSA_SIGN_COORD_SIZE; ++ ++ if (!message || 0 == message_len || !signature || !signature_len || ++ 0 == *signature_len) { ++ return -1; ++ } ++ ++#if !defined(ECDSA256_DA) && !defined(ECDSA384_DA) ++ LOG(LOG_ERROR, "No supported ECDSA curve defined\n"); ++ return -1; ++#endif ++ ++ if (wc_ecc_init(&key) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_init failed\n"); ++ return -1; ++ } ++ key_inited = 1; ++ ++ do { ++ rng = wolfssl_shared_rng(); ++ if (!rng) { ++ LOG(LOG_ERROR, "Shared RNG not initialized\n"); ++ break; ++ } ++ ++ if (0 != crypto_hal_hash(FDO_CRYPTO_HASH_TYPE_USED, message, message_len, ++ hash, FDO_SHA_DIGEST_SIZE_USED)) { ++ LOG(LOG_ERROR, "crypto_hal_hash failed\n"); ++ break; ++ } ++ ++ if (wolfssl_ecdsa_load_privkey(&key) != 0) { ++ LOG(LOG_ERROR, "wolfssl_ecdsa_load_privkey failed\n"); ++ break; ++ } ++ ++ sig_len = sizeof(der_sig); ++ if (wc_ecc_sign_hash(hash, FDO_SHA_DIGEST_SIZE_USED, der_sig, ++ &sig_len, rng, &key) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_sign_hash failed\n"); ++ break; ++ } ++ ++ r_len = sizeof(r); ++ s_len = sizeof(s); ++ if (wc_ecc_sig_to_rs(der_sig, sig_len, r, &r_len, s, &s_len) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_sig_to_rs failed\n"); ++ break; ++ } ++ ++ if ((expected_half * 2) > *signature_len) { ++ LOG(LOG_ERROR, "Signature buffer too small\n"); ++ break; ++ } ++ ++ *signature_len = expected_half * 2; ++ ++ memset_s(signature, *signature_len, 0); ++ ++ if (wolfssl_ecdsa_place_coord(signature, expected_half, r, r_len) != 0) { ++ LOG(LOG_ERROR, "Invalid r length\n"); ++ break; ++ } ++ if (wolfssl_ecdsa_place_coord(signature + expected_half, expected_half, ++ s, s_len) != 0) { ++ LOG(LOG_ERROR, "Invalid s length\n"); ++ break; ++ } ++ ++ ret = 0; ++ } while (0); ++ ++ if (key_inited) { ++ wc_ecc_free(&key); ++ } ++ memset_s(hash, sizeof(hash), 0); ++ memset_s(der_sig, sizeof(der_sig), 0); ++ memset_s(r, sizeof(r), 0); ++ memset_s(s, sizeof(s), 0); ++ return ret; ++} +diff --git a/crypto/wolfssl/wolfssl_ECDSAVerifyRoutines.c b/crypto/wolfssl/wolfssl_ECDSAVerifyRoutines.c +new file mode 100644 +index 0000000..d1e218e +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_ECDSAVerifyRoutines.c +@@ -0,0 +1,148 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief ECDSA signature verification abstraction over wolfCrypt, used ++ * to verify the Ownership Voucher signature chain. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "safe_lib.h" ++#include "wolfssl_ecdsa_util.h" ++#include ++#include ++#include ++ ++/* Verify ECDSA signature using public key. */ ++int32_t crypto_hal_sig_verify(uint8_t key_encoding, int key_algorithm, ++ const uint8_t *message, uint32_t message_length, ++ const uint8_t *message_signature, ++ uint32_t signature_length, ++ const uint8_t *key_param1, ++ uint32_t key_param1Length, ++ const uint8_t *key_param2, ++ uint32_t key_param2Length) ++{ ++ /* Validate encoding and algo. */ ++ if ((key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_X509 && ++ key_encoding != FDO_CRYPTO_PUB_KEY_ENCODING_COSEKEY) || ++ (key_algorithm != FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256 && ++ key_algorithm != FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384)) { ++ LOG(LOG_ERROR, "Incorrect key type\n"); ++ return -1; ++ } ++ ++ if (!message_signature || 0 == signature_length || ++ 0 != (signature_length % 2) || !message || 0 == message_length) { ++ LOG(LOG_ERROR, "Invalid arguments!\n"); ++ return -1; ++ } ++ ++ if (key_encoding == FDO_CRYPTO_PUB_KEY_ENCODING_X509) { ++ if (!key_param1 || 0 == key_param1Length) { ++ LOG(LOG_ERROR, "Invalid params!\n"); ++ return -1; ++ } ++ } else { ++ if (!key_param1 || 0 == key_param1Length || !key_param2 || ++ 0 == key_param2Length) { ++ LOG(LOG_ERROR, "Invalid params!\n"); ++ return -1; ++ } ++ } ++ ++ ecc_key key; ++ int ret = -1; ++ unsigned char hash[SHA512_DIGEST_SIZE] = {0}; ++ int curve_id = 0; ++ int hash_type = 0; ++ size_t hash_len = 0; ++ int stat = 0; ++ unsigned char der_sig[ECDSA_SIGNATURE_MAX_LEN] = {0}; ++ word32 der_sig_len = sizeof(der_sig); ++ int key_inited = 0; ++ ++ switch (key_algorithm) { ++ case FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256: ++ curve_id = ECC_SECP256R1; ++ hash_type = FDO_CRYPTO_HASH_TYPE_SHA_256; ++ hash_len = SHA256_DIGEST_SIZE; ++ break; ++ case FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384: ++ curve_id = ECC_SECP384R1; ++ hash_type = FDO_CRYPTO_HASH_TYPE_SHA_384; ++ hash_len = SHA384_DIGEST_SIZE; ++ break; ++ default: ++ LOG(LOG_ERROR, "Unsupported curve\n"); ++ return -1; ++ } ++ ++ if (wc_ecc_init(&key) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_init failed\n"); ++ return -1; ++ } ++ key_inited = 1; ++ ++ do { ++ if (key_encoding == FDO_CRYPTO_PUB_KEY_ENCODING_X509) { ++ word32 idx = 0; ++ if (wc_EccPublicKeyDecode(key_param1, &idx, &key, key_param1Length) != 0) { ++ LOG(LOG_ERROR, "wc_EccPublicKeyDecode failed\n"); ++ break; ++ } ++ /* Enforce the declared algorithm's curve on the decoded key. */ ++ if (key.dp == NULL || key.dp->id != curve_id) { ++ LOG(LOG_ERROR, "Public key curve does not match key algorithm\n"); ++ break; ++ } ++ } else { ++ /* Right-align COSEKEY coordinates into fixed-width slot. */ ++ size_t coord_size = wolfssl_ecdsa_coord_size(key_algorithm); ++ uint8_t qx[FDO_ECDSA_P384_COORD_SIZE] = {0}; ++ uint8_t qy[FDO_ECDSA_P384_COORD_SIZE] = {0}; ++ ++ if (wolfssl_ecdsa_place_coord(qx, coord_size, key_param1, ++ key_param1Length) != 0 || ++ wolfssl_ecdsa_place_coord(qy, coord_size, key_param2, ++ key_param2Length) != 0) { ++ LOG(LOG_ERROR, "Failed to pad COSEKEY coordinates\n"); ++ break; ++ } ++ if (wc_ecc_import_unsigned(&key, qx, qy, NULL, curve_id) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_import_unsigned failed\n"); ++ break; ++ } ++ } ++ ++ if (0 != crypto_hal_hash(hash_type, message, message_length, hash, hash_len)) { ++ LOG(LOG_ERROR, "crypto_hal_hash failed\n"); ++ break; ++ } ++ ++ if (wc_ecc_rs_raw_to_sig(message_signature, signature_length / 2, ++ message_signature + signature_length / 2, signature_length / 2, ++ der_sig, &der_sig_len) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_rs_to_sig failed\n"); ++ break; ++ } ++ ++ if (wc_ecc_verify_hash(der_sig, der_sig_len, hash, hash_len, &stat, &key) != 0 || stat != 1) { ++ LOG(LOG_ERROR, "wc_ecc_verify_hash failed\n"); ++ break; ++ } ++ ++ ret = 0; ++ } while (0); ++ ++ if (key_inited) { ++ wc_ecc_free(&key); ++ } ++ memset_s(hash, sizeof(hash), 0); ++ memset_s(der_sig, sizeof(der_sig), 0); ++ return ret; ++} +diff --git a/crypto/wolfssl/wolfssl_SSLRoutines.c b/crypto/wolfssl/wolfssl_SSLRoutines.c +new file mode 100644 +index 0000000..7c65492 +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_SSLRoutines.c +@@ -0,0 +1,216 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief TLS connection abstraction over wolfSSL, used for the HTTPS ++ * transport to the rendezvous/owner servers. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "fdo.h" ++#include "util.h" ++#include "safe_lib.h" ++#include ++#include ++#include ++ ++/* Trust store for server cert validation. */ ++#ifndef CA_CERT_FILE ++#define CA_CERT_FILE NULL ++#endif ++#ifndef CA_CERT_DIR ++#define CA_CERT_DIR "/etc/ssl/certs" ++#endif ++ ++/* Session owns WOLFSSL_CTX. */ ++typedef struct { ++ WOLFSSL_CTX *ctx; ++ WOLFSSL *ssl; ++} fdo_ssl_session_t; ++ ++/* Set up wolfSSL session on connected socket. */ ++void *fdo_ssl_setup(int sock) ++{ ++ fdo_ssl_session_t *session = NULL; ++ WOLFSSL_METHOD *method = NULL; ++ const long flags = ++ WOLFSSL_OP_NO_SSLv2 | WOLFSSL_OP_NO_SSLv3 | WOLFSSL_OP_NO_COMPRESSION; ++ const char *const PREFERRED_CIPHERS = ++ "HIGH:!aNULL:!NULL:!EXT:!DSS:!kRSA:!PSK:!SRP:!MD5:!RC4"; ++ ++ if (sock < 0) { ++ return NULL; ++ } ++ ++ session = fdo_alloc(sizeof(*session)); ++ if (!session) { ++ return NULL; ++ } ++ session->ctx = NULL; ++ session->ssl = NULL; ++ ++ if (wolfSSL_Init() != WOLFSSL_SUCCESS) { ++ LOG(LOG_ERROR, "wolfSSL_Init failed\n"); ++ fdo_free(session); ++ return NULL; ++ } ++ ++ method = wolfSSLv23_client_method(); ++ if (method == NULL) { ++ goto err; ++ } ++ ++ session->ctx = wolfSSL_CTX_new(method); ++ if (session->ctx == NULL) { ++ goto err; ++ } ++ ++ wolfSSL_CTX_set_options(session->ctx, flags); ++ if (WOLFSSL_SUCCESS != ++ wolfSSL_CTX_set_cipher_list(session->ctx, PREFERRED_CIPHERS)) { ++ LOG(LOG_ERROR, "SSL cipher suite set failed\n"); ++ goto err; ++ } ++ ++ /* Load CA store or relax verification if self-signed. */ ++#if defined(SELF_SIGNED_CERTS_SUPPORTED) ++ if (useSelfSignedCerts) { ++ wolfSSL_CTX_set_verify(session->ctx, WOLFSSL_VERIFY_NONE, NULL); ++ } else ++#endif ++ { ++ wolfSSL_CTX_set_verify(session->ctx, WOLFSSL_VERIFY_PEER, NULL); ++ if (WOLFSSL_SUCCESS != ++ wolfSSL_CTX_load_verify_locations(session->ctx, CA_CERT_FILE, ++ CA_CERT_DIR)) { ++ LOG(LOG_ERROR, "Failed to load CA certificates\n"); ++ goto err; ++ } ++ } ++ ++ session->ssl = wolfSSL_new(session->ctx); ++ if (!session->ssl) { ++ goto err; ++ } ++ ++ if (WOLFSSL_SUCCESS != wolfSSL_set_fd(session->ssl, sock)) { ++ goto err; ++ } ++ ++ return (void *)session; ++err: ++ if (session->ssl) { ++ wolfSSL_free(session->ssl); ++ } ++ if (session->ctx) { ++ wolfSSL_CTX_free(session->ctx); ++ } ++ fdo_free(session); ++ wolfSSL_Cleanup(); ++ return NULL; ++} ++ ++/* Perform TLS handshake. */ ++int fdo_ssl_connect(void *ssl) ++{ ++ int ret = 0; ++ WOLFSSL *wssl = NULL; ++ ++ if (!ssl) { ++ return -1; ++ } ++ wssl = ((fdo_ssl_session_t *)ssl)->ssl; ++ ++ ret = wolfSSL_connect(wssl); ++ if (ret != WOLFSSL_SUCCESS) { ++ LOG(LOG_ERROR, "SSL Connection error: %d\n", ++ wolfSSL_get_error(wssl, ret)); ++ return -1; ++ } ++ ++ LOG(LOG_DEBUG, "ssl connection successful\n"); ++ return 0; ++} ++ ++/* Tear down wolfSSL session. */ ++int fdo_ssl_close(void *ssl) ++{ ++ int ret = 0; ++ int result = 0; ++ fdo_ssl_session_t *session = NULL; ++ ++ if (!ssl) { ++ return -1; ++ } ++ session = (fdo_ssl_session_t *)ssl; ++ ++ ret = wolfSSL_shutdown(session->ssl); ++ if (ret != WOLFSSL_SUCCESS) { ++ if (ret == WOLFSSL_SHUTDOWN_NOT_DONE) { ++ /* close_notify sent but peer's not yet received; retry ++ * once for bidirectional shutdown. */ ++ ret = wolfSSL_shutdown(session->ssl); ++ } ++ /* Peer not answering close_notify is not an error here. */ ++ if (ret != WOLFSSL_SUCCESS && ret != WOLFSSL_SHUTDOWN_NOT_DONE) { ++ LOG(LOG_ERROR, "SSL Connection shutdown error: %d, ret = %d\n", ++ wolfSSL_get_error(session->ssl, ret), ret); ++ result = -1; ++ } ++ } ++ ++ wolfSSL_free(session->ssl); ++ if (session->ctx) { ++ wolfSSL_CTX_free(session->ctx); ++ } ++ fdo_free(session); ++ ++ wolfSSL_Cleanup(); ++ ++ return result; ++} ++ ++/* Read up to num bytes from TLS session. */ ++int fdo_ssl_read(void *ssl, void *buf, int num) ++{ ++ int ret = 0; ++ WOLFSSL *wssl = NULL; ++ ++ if (!ssl || !buf || num <= 0) { ++ return -1; ++ } ++ wssl = ((fdo_ssl_session_t *)ssl)->ssl; ++ ++ ret = wolfSSL_read(wssl, buf, num); ++ if (ret <= 0) { ++ LOG(LOG_ERROR, "SSL Connection read error: %d\n", ++ wolfSSL_get_error(wssl, ret)); ++ return -1; ++ } ++ ++ return ret; ++} ++ ++/* Write num bytes to TLS session. */ ++int fdo_ssl_write(void *ssl, const void *buf, int num) ++{ ++ int ret = 0; ++ WOLFSSL *wssl = NULL; ++ ++ if (!ssl || !buf || num <= 0) { ++ return -1; ++ } ++ wssl = ((fdo_ssl_session_t *)ssl)->ssl; ++ ++ ret = wolfSSL_write(wssl, buf, num); ++ if (ret <= 0) { ++ LOG(LOG_ERROR, "SSL Connection write error: %d\n", ++ wolfSSL_get_error(wssl, ret)); ++ return -1; ++ } ++ ++ return ret; ++} +diff --git a/crypto/wolfssl/wolfssl_cryptoSupport.c b/crypto/wolfssl/wolfssl_cryptoSupport.c +new file mode 100644 +index 0000000..16d85ad +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_cryptoSupport.c +@@ -0,0 +1,353 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Abstraction of wolfSSL library for crypto services required by FDO ++ * library. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "safe_lib.h" ++#include "wolfssl_rng_util.h" ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++static bool g_crypto_initialized = false; ++ ++/* Initialize wolfCrypt library state. */ ++int32_t crypto_init(void) ++{ ++ if (g_crypto_initialized) { ++ return 0; ++ } ++ ++ if (wolfCrypt_Init() != 0) { ++ LOG(LOG_ERROR, "wolfCrypt_Init failed\n"); ++ return -1; ++ } ++ ++ /* With SECURE_ELEMENT, random_init() comes from se_crypto_support.c. */ ++ if (0 != random_init()) { ++ LOG(LOG_ERROR, "random_init failed\n"); ++ wolfCrypt_Cleanup(); ++ return -1; ++ } ++ ++#ifdef SECURE_ELEMENT ++ if (0 != crypto_hal_se_init()) { ++ LOG(LOG_ERROR, "crypto_hal_se_init failed\n"); ++ wolfCrypt_Cleanup(); ++ return -1; ++ } ++#endif /* SECURE_ELEMENT */ ++ ++ g_crypto_initialized = true; ++ ++ return 0; ++} ++ ++/* Tear down wolfCrypt library state. */ ++int32_t crypto_close(void) ++{ ++ int32_t ret = 0; ++ ++ if (!g_crypto_initialized) { ++ return -1; ++ } ++ ++ /* With SECURE_ELEMENT, this also releases the SE (atcab_release). */ ++ if (0 != random_close()) { ++ LOG(LOG_ERROR, "random_close failed\n"); ++ ret = -1; ++ } ++ ++ if (wolfCrypt_Cleanup() != 0) { ++ LOG(LOG_ERROR, "wolfCrypt_Cleanup failed\n"); ++ ret = -1; ++ } ++ ++ g_crypto_initialized = false; ++ ++ return ret; ++} ++ ++#ifndef SECURE_ELEMENT ++static bool g_random_initialized = false; ++static WC_RNG g_rng; ++ ++/* Initialize randomization library. */ ++int random_init(void) ++{ ++ if (g_random_initialized) { ++ return 0; ++ } ++ ++ if (wolfCrypt_Init() != 0) { ++ LOG(LOG_ERROR, "wolfCrypt_Init failed\n"); ++ return -1; ++ } ++ ++ if (memset_s(&g_rng, sizeof(g_rng), 0) != 0) { ++ LOG(LOG_ERROR, "memset_s failed\n"); ++ wolfCrypt_Cleanup(); ++ return -1; ++ } ++ ++ if (wc_InitRng(&g_rng) != 0) { ++ LOG(LOG_ERROR, "wc_InitRng failed\n"); ++ wolfCrypt_Cleanup(); ++ return -1; ++ } ++ ++ g_random_initialized = true; ++ return 0; ++} ++ ++/* Uninitialize randomization library. */ ++int random_close(void) ++{ ++ int ret = 0; ++ ++ if (!g_random_initialized) { ++ return -1; ++ } ++ ++ if (wc_FreeRng(&g_rng) != 0) { ++ LOG(LOG_ERROR, "wc_FreeRng failed\n"); ++ ret = -1; ++ } ++ ++ if (wolfCrypt_Cleanup() != 0) { ++ LOG(LOG_ERROR, "wolfCrypt_Cleanup failed\n"); ++ ret = -1; ++ } ++ ++ g_random_initialized = false; ++ ++ return ret; ++} ++ ++/* Return shared RNG. */ ++WC_RNG *wolfssl_shared_rng(void) ++{ ++ return g_random_initialized ? &g_rng : NULL; ++} ++#endif /* SECURE_ELEMENT */ ++ ++#if !defined(SECURE_ELEMENT) && !defined(DEVICE_CSE_ENABLED) ++/* Generate random data. */ ++int32_t crypto_hal_random_bytes(uint8_t *random_buffer, size_t num_bytes) ++{ ++ if (!random_buffer || 0 == num_bytes) { ++ return -1; ++ } ++ ++ if (num_bytes > (size_t)0xFFFFFFFFu) { ++ LOG(LOG_ERROR, "num_bytes exceeds word32 range\n"); ++ return -1; ++ } ++ ++ if (!g_random_initialized) { ++ LOG(LOG_ERROR, "RNG not initialized\n"); ++ return -1; ++ } ++ ++ if (wc_RNG_GenerateBlock(&g_rng, random_buffer, num_bytes) != 0) { ++ LOG(LOG_ERROR, "wc_RNG_GenerateBlock failed\n"); ++ return -1; ++ } ++ ++ return 0; ++} ++#endif /* DEVICE_CSE_ENABLED */ ++ ++#ifndef SECURE_ELEMENT ++/* Calculate hash. */ ++int32_t crypto_hal_hash(int hash_type, const uint8_t *buffer, ++ size_t buffer_length, uint8_t *output, ++ size_t output_length) ++{ ++ if (!output || 0 == output_length || !buffer || 0 == buffer_length) { ++ return -1; ++ } ++ ++ int ret; ++ ++ if (buffer_length > (size_t)0xFFFFFFFFu) { ++ LOG(LOG_ERROR, "buffer_length exceeds word32 range\n"); ++ return -1; ++ } ++ ++ switch (hash_type) { ++ case FDO_CRYPTO_HASH_TYPE_SHA_256: ++ if (output_length < BUFF_SIZE_32_BYTES) { ++ return -1; ++ } ++ ret = wc_Sha256Hash(buffer, buffer_length, output); ++ break; ++ case FDO_CRYPTO_HASH_TYPE_SHA_384: ++ if (output_length < BUFF_SIZE_48_BYTES) { ++ return -1; ++ } ++ ret = wc_Sha384Hash(buffer, buffer_length, output); ++ break; ++ default: ++ LOG(LOG_ERROR, "Unsupported hash type %d\n", hash_type); ++ return -1; ++ } ++ ++ if (ret != 0) { ++ LOG(LOG_ERROR, "wolfCrypt hash computation failed\n"); ++ return -1; ++ } ++ ++ return 0; ++} ++ ++/* Calculate HMAC. */ ++int32_t crypto_hal_hmac(uint8_t hmac_type, const uint8_t *buffer, ++ size_t buffer_length, uint8_t *output, ++ size_t output_length, const uint8_t *key, ++ size_t key_length) ++{ ++ if (!output || 0 == output_length || !buffer || 0 == buffer_length || ++ !key || 0 == key_length) { ++ return -1; ++ } ++ ++#ifdef WOLFSSL_SMALL_STACK ++ Hmac *hmac = NULL; ++#else ++ Hmac hmac_obj; ++ Hmac *hmac = &hmac_obj; ++#endif ++ int wc_type = 0; ++ int ret; ++ ++ if (buffer_length > (size_t)0xFFFFFFFFu || ++ key_length > (size_t)0xFFFFFFFFu) { ++ LOG(LOG_ERROR, "buffer_length/key_length exceeds word32 range\n"); ++ return -1; ++ } ++ ++#ifdef WOLFSSL_SMALL_STACK ++ hmac = (Hmac *)XMALLOC(sizeof(Hmac), NULL, DYNAMIC_TYPE_TMP_BUFFER); ++ if (hmac == NULL) { ++ LOG(LOG_ERROR, "XMALLOC failed\n"); ++ return -1; ++ } ++#endif ++ ++ switch (hmac_type) { ++ case FDO_CRYPTO_HMAC_TYPE_SHA_256: ++ if (output_length < BUFF_SIZE_32_BYTES) { ++ ret = -1; ++ } else { ++ wc_type = WC_SHA256; ++ ret = 0; ++ } ++ break; ++ case FDO_CRYPTO_HMAC_TYPE_SHA_384: ++ if (output_length < BUFF_SIZE_48_BYTES) { ++ ret = -1; ++ } else { ++ wc_type = WC_SHA384; ++ ret = 0; ++ } ++ break; ++ default: ++ LOG(LOG_ERROR, "Unsupported hmac type %d\n", hmac_type); ++ ret = -1; ++ break; ++ } ++ ++ if (ret == 0) { ++ int hmac_inited = 0; ++ ++ do { ++ if (wc_HmacInit(hmac, NULL, INVALID_DEVID) != 0) { ++ LOG(LOG_ERROR, "wc_HmacInit failed\n"); ++ ret = -1; ++ break; ++ } ++ hmac_inited = 1; ++ ++ if (wc_HmacSetKey(hmac, wc_type, key, key_length) != 0) { ++ LOG(LOG_ERROR, "wc_HmacSetKey failed\n"); ++ ret = -1; ++ break; ++ } ++ if (wc_HmacUpdate(hmac, buffer, buffer_length) != 0) { ++ LOG(LOG_ERROR, "wc_HmacUpdate failed\n"); ++ ret = -1; ++ break; ++ } ++ if (wc_HmacFinal(hmac, output) != 0) { ++ LOG(LOG_ERROR, "wc_HmacFinal failed\n"); ++ ret = -1; ++ break; ++ } ++ ret = 0; ++ } while (0); ++ ++ if (hmac_inited) { ++ wc_HmacFree(hmac); ++ } ++ } ++ ++ if (hmac != NULL) { ++ /* Zero HMAC structure. */ ++ memset_s(hmac, sizeof(Hmac), 0); ++#ifdef WOLFSSL_SMALL_STACK ++ XFREE(hmac, NULL, DYNAMIC_TYPE_TMP_BUFFER); ++#endif ++ } ++ return ret; ++} ++#endif /* SECURE_ELEMENT */ ++ ++/* Increment IV counter. */ ++int32_t inc_rollover_ctr(uint8_t *first_iv, uint8_t *new_iv, uint8_t iv_len, ++ size_t aesblocks) ++{ ++ uint16_t inc = (aesblocks <= 0xFFFFFFFF) ? 1 : 2; ++ int carry; ++ int i; ++ int diff; ++ uint16_t j; ++ ++ if (first_iv == NULL || new_iv == NULL || iv_len == 0) { ++ return -1; ++ } ++ ++ for (j = 0; j < inc; j++) { ++ carry = 1; ++ for (i = iv_len - 1; i >= 0 && carry; i--) { ++ carry += new_iv[i]; ++ new_iv[i] = (uint8_t)carry; ++ carry >>= 8; ++ } ++ ++ if (carry) { ++ LOG(LOG_ERROR, "IV counter overflow\n"); ++ return -1; ++ } ++ ++ /* Check for unsupported IV wrap-around. */ ++ if (0 == memcmp_s(first_iv, iv_len, new_iv, iv_len, &diff) && 0 == diff) { ++ LOG(LOG_ERROR, "Roll over iv not supported\n"); ++ return -1; ++ } ++ } ++ ++ return 0; ++} +diff --git a/crypto/wolfssl/wolfssl_ec_csr.c b/crypto/wolfssl/wolfssl_ec_csr.c +new file mode 100644 +index 0000000..a715f04 +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_ec_csr.c +@@ -0,0 +1,128 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Device CSR generation over wolfCrypt, software-ECDSA only. ++ * For DA=tpm the CSR is read from TPM NV instead; only provisioning ++ * (utils/tpm_make_ready_ecdsa.sh) still generates it with OpenSSL. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include ++#include "safe_lib.h" ++#include "fdocred.h" ++#include "ecdsa_privkey.h" ++#include ++#include ++#include ++#include ++#include ++#include "wolfssl_ecdsa_util.h" ++ ++/* Build and sign device CSR. */ ++int32_t crypto_hal_get_device_csr(fdo_byte_array_t **csr) ++{ ++ int32_t ret = -1; ++ ecc_key key; ++ WC_RNG rng; ++ Cert cert; ++ uint8_t *csr_der = NULL; ++ fdo_byte_array_t *result = NULL; ++ int derSz = 0; ++ int sigSz = 0; ++ ++ if (csr == NULL) { ++ return -1; ++ } ++ *csr = NULL; ++ ++#if !defined(ECDSA256_DA) && !defined(ECDSA384_DA) ++ LOG(LOG_ERROR, "No supported ECDSA curve defined\n"); ++ return -1; ++#endif ++ ++ if (wc_ecc_init(&key) != 0) { ++ return -1; ++ } ++ ++ if (wc_InitRng(&rng) != 0) { ++ wc_ecc_free(&key); ++ return -1; ++ } ++ ++ do { ++ if (wolfssl_ecdsa_load_privkey(&key) != 0) { ++ break; ++ } ++ ++ if (wc_ecc_make_pub(&key, NULL) != 0) { ++ break; ++ } ++ ++ wc_InitCert(&cert); ++ ++ if (strncpy_s(cert.subject.country, CTC_NAME_SIZE, "IN", 2) != 0) { ++ break; ++ } ++ if (strncpy_s(cert.subject.commonName, CTC_NAME_SIZE, "fdo", 3) != 0) { ++ break; ++ } ++ if (strncpy_s(cert.subject.locality, CTC_NAME_SIZE, "Blr", 3) != 0) { ++ break; ++ } ++ if (strncpy_s(cert.subject.org, CTC_NAME_SIZE, "Intel", 5) != 0) { ++ break; ++ } ++ ++#if defined(ECDSA384_DA) ++ cert.sigType = CTC_SHA384wECDSA; ++#else ++ cert.sigType = CTC_SHA256wECDSA; ++#endif ++ ++ csr_der = fdo_alloc(4096); ++ if (!csr_der) { ++ break; ++ } ++ ++ derSz = wc_MakeCertReq(&cert, csr_der, 4096, NULL, &key); ++ if (derSz <= 0) { ++ break; ++ } ++ ++ sigSz = wc_SignCert(cert.bodySz, cert.sigType, csr_der, 4096, NULL, &key, &rng); ++ if (sigSz <= 0) { ++ break; ++ } ++ ++ result = fdo_byte_array_alloc(sigSz); ++ if (result == NULL) { ++ break; ++ } ++ ++ if (memcpy_s(result->bytes, result->byte_sz, csr_der, sigSz) != 0) { ++ break; ++ } ++ ++ *csr = result; ++ result = NULL; ++ ret = 0; ++ ++ } while (0); ++ ++ if (result) { ++ fdo_byte_array_free(result); ++ } ++ if (csr_der) { ++ fdo_free(csr_der); ++ } ++ ++ wc_FreeRng(&rng); ++ wc_ecc_free(&key); ++ ++ return ret; ++} +diff --git a/crypto/wolfssl/wolfssl_ecdsa_util.h b/crypto/wolfssl/wolfssl_ecdsa_util.h +new file mode 100644 +index 0000000..92fbe10 +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_ecdsa_util.h +@@ -0,0 +1,125 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Shared helpers for wolfCrypt ECDSA operations. ++ */ ++ ++#ifndef WOLFSSL_ECDSA_UTIL_H ++#define WOLFSSL_ECDSA_UTIL_H ++ ++#include ++#include ++#include "safe_lib.h" ++#include "util.h" ++#include "ecdsa_privkey.h" ++#include ++#include ++#include ++ ++/* Single source of truth for ECDSA coordinate (R/S, Qx/Qy) half-sizes, so ++ * the sign path (curve fixed at compile time) and the verify path (curve ++ * chosen at runtime from key_algorithm) can't derive different values for ++ * the same curve. */ ++#define FDO_ECDSA_P256_COORD_SIZE 32 ++#define FDO_ECDSA_P384_COORD_SIZE 48 ++ ++/* Runtime lookup for the verify path, which handles both curves in one ++ * binary regardless of the device's own compiled-in curve. */ ++static inline size_t wolfssl_ecdsa_coord_size(int key_algorithm) ++{ ++ return (key_algorithm == FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384) ++ ? FDO_ECDSA_P384_COORD_SIZE ++ : FDO_ECDSA_P256_COORD_SIZE; ++} ++ ++/* Strip 0x00 padding and copy right-aligned coordinate. */ ++static inline int32_t wolfssl_ecdsa_place_coord(uint8_t *dst, size_t half, ++ const uint8_t *src, ++ uint32_t src_len) ++{ ++ const uint8_t *p = src; ++ ++ if (src_len > half) { ++ if (src_len == half + 1 && src[0] == 0x00) { ++ p++; ++ src_len--; ++ } else { ++ return -1; ++ } ++ } ++ ++ if (src_len == 0) { ++ /* Slot is already zeroed. */ ++ return 0; ++ } ++ ++ if (memcpy_s(dst + (half - src_len), src_len, p, src_len) != 0) { ++ return -1; ++ } ++ ++ return 0; ++} ++ ++/* ++ * Load device ECDSA private key from storage into initialized ecc_key. ++ * Return 0 on success, -1 on failure. ++ */ ++static inline int32_t wolfssl_ecdsa_load_privkey(ecc_key *key) ++{ ++ uint8_t *privkey = NULL; ++ size_t privkeysize = 0; ++ int32_t ret = -1; ++ ++ if (load_ecdsa_privkey(&privkey, &privkeysize) != 0 || privkey == NULL) { ++ return -1; ++ } ++ ++ do { ++#if defined(ECDSA_PEM) ++ { ++ DerBuffer *der = NULL; ++ word32 idx = 0; ++ if (wc_PemToDer(privkey, privkeysize, ECC_PRIVATEKEY_TYPE, ++ &der, NULL, NULL, NULL) != 0 || !der) { ++ LOG(LOG_ERROR, "wc_PemToDer failed\n"); ++ if (der) { ++ wc_FreeDer(&der); ++ } ++ break; ++ } ++ if (wc_EccPrivateKeyDecode(der->buffer, &idx, key, ++ der->length) != 0) { ++ LOG(LOG_ERROR, "wc_EccPrivateKeyDecode failed\n"); ++ wc_FreeDer(&der); ++ break; ++ } ++ wc_FreeDer(&der); ++ } ++#else ++ { ++ int curve_id = 0; ++#if defined(ECDSA256_DA) ++ curve_id = ECC_SECP256R1; ++#elif defined(ECDSA384_DA) ++ curve_id = ECC_SECP384R1; ++#endif ++ if (wc_ecc_import_private_key_ex(privkey, privkeysize, NULL, ++ 0, key, curve_id) != 0) { ++ LOG(LOG_ERROR, "wc_ecc_import_private_key_ex failed\n"); ++ break; ++ } ++ } ++#endif ++ ret = 0; ++ } while (0); ++ ++ wc_ForceZero(privkey, privkeysize); ++ fdo_free(privkey); ++ return ret; ++} ++ ++#endif /* WOLFSSL_ECDSA_UTIL_H */ +diff --git a/crypto/wolfssl/wolfssl_key_exchange_ecdh.c b/crypto/wolfssl/wolfssl_key_exchange_ecdh.c +new file mode 100644 +index 0000000..0207d2e +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_key_exchange_ecdh.c +@@ -0,0 +1,483 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief ECDH key exchange abstraction over wolfCrypt. ++ */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "safe_lib.h" ++#include "wolfssl_ecdsa_util.h" ++#include ++#include ++#include ++#include ++ ++#if defined(KEX_ECDH_ENABLED) || defined(KEX_ECDH384_ENABLED) ++ ++#if defined(KEX_ECDH_ENABLED) ++#define AX_AY_SIZE_DEF BUFF_SIZE_32_BYTES ++#define OWNERRAND_SIZE_DEF BUFF_SIZE_16_BYTES ++#define CURVE_ID ECC_SECP256R1 ++#define DEVICE_RANDOM_SIZE FDO_ECDH256_DEV_RANDOM ++#elif defined(KEX_ECDH384_ENABLED) ++#define AX_AY_SIZE_DEF BUFF_SIZE_48_BYTES ++#define OWNERRAND_SIZE_DEF BUFF_SIZE_48_BYTES ++#define CURVE_ID ECC_SECP384R1 ++#define DEVICE_RANDOM_SIZE FDO_ECDH384_DEV_RANDOM ++#endif ++ ++/* Device public random blob wire format: Ax, Ay, DevRand with 2-byte lengths. */ ++#define LEN_PREFIX_SIZE 2 ++#define NUM_LEN_PREFIXED_FIELDS 3 /* Ax, Ay, DevRand */ ++ ++static void write_be16_len(uint8_t *dst, uint32_t value) ++{ ++ dst[0] = (value >> 8) & 0xFF; ++ dst[1] = value & 0xFF; ++} ++ ++typedef struct { ++ uint8_t *_Device_random; ++ uint16_t _Dev_rand_size; ++ uint8_t *_publicA; ++ uint8_t *_shared_secret; ++ uint32_t _shared_secret_length; ++ ecc_key key; ++ /* Keep alive for wc_ecc_shared_secret */ ++ WC_RNG rng; ++ int rng_inited; ++ uint8_t *_publicB; ++ uint32_t _publicB_length; ++} ecdh_context_t; ++ ++int32_t crypto_hal_kex_close(void **context) ++{ ++ if (!context) { ++ return -1; ++ } ++ ecdh_context_t *key_ex_data = *(ecdh_context_t **)context; ++ if (!key_ex_data) { ++ return -1; ++ } ++ ++ wc_ecc_free(&(key_ex_data->key)); ++ if (key_ex_data->rng_inited) { ++ wc_FreeRng(&(key_ex_data->rng)); ++ } ++ ++ if (key_ex_data->_shared_secret) { ++ memset_s(key_ex_data->_shared_secret, ++ key_ex_data->_shared_secret_length, 0); ++ fdo_free(key_ex_data->_shared_secret); ++ } ++ if (key_ex_data->_publicA) { ++ fdo_free(key_ex_data->_publicA); ++ } ++ if (key_ex_data->_publicB) { ++ fdo_free(key_ex_data->_publicB); ++ } ++ if (key_ex_data->_Device_random) { ++ memset_s(key_ex_data->_Device_random, ++ key_ex_data->_Dev_rand_size, 0); ++ fdo_free(key_ex_data->_Device_random); ++ } ++ fdo_free(key_ex_data); ++ *context = NULL; ++ return 0; ++} ++ ++int32_t crypto_hal_kex_init(void **context) ++{ ++ ecdh_context_t *key_ex_data = NULL; ++ uint32_t size = 0; ++ uint32_t allocbytes = 0; ++ uint8_t *temp = NULL; ++ uint32_t pub_x_len = AX_AY_SIZE_DEF; ++ uint32_t pub_y_len = AX_AY_SIZE_DEF; ++ ++ if (!context) { ++ LOG(LOG_ERROR, "Invalid parameters\n"); ++ return -1; ++ } ++ ++ key_ex_data = fdo_alloc(sizeof(ecdh_context_t)); ++ if (!key_ex_data) { ++ return -1; ++ } ++ ++ if (wc_ecc_init(&(key_ex_data->key)) != 0) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ ++ key_ex_data->_Dev_rand_size = DEVICE_RANDOM_SIZE; ++ key_ex_data->_Device_random = fdo_alloc(key_ex_data->_Dev_rand_size); ++ if (!key_ex_data->_Device_random) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ ++ if (crypto_hal_random_bytes(key_ex_data->_Device_random, key_ex_data->_Dev_rand_size) != 0) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ ++ if (wc_InitRng(&(key_ex_data->rng)) != 0) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ key_ex_data->rng_inited = 1; ++ ++ /* Select the curve explicitly; the peer key is imported with ++ * CURVE_ID, and a size alone may match another enabled curve. */ ++ if (wc_ecc_make_key_ex(&(key_ex_data->rng), AX_AY_SIZE_DEF, &(key_ex_data->key), CURVE_ID) != 0) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ ++ /* Kept for wc_ecc_shared_secret blinding */ ++ if (wc_ecc_set_rng(&(key_ex_data->key), &(key_ex_data->rng)) != 0) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ ++ allocbytes = pub_x_len + pub_y_len + key_ex_data->_Dev_rand_size + ++ (LEN_PREFIX_SIZE * NUM_LEN_PREFIXED_FIELDS); ++ temp = fdo_alloc(allocbytes); ++ if (!temp) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ goto error; ++ } ++ ++ word32 xLen = pub_x_len; ++ word32 yLen = pub_y_len; ++ if (wc_ecc_export_public_raw(&(key_ex_data->key), ++ &temp[LEN_PREFIX_SIZE], &xLen, ++ &temp[LEN_PREFIX_SIZE + xLen + LEN_PREFIX_SIZE], ++ &yLen) != 0) { ++ LOG(LOG_ERROR, "failed at %d\n", __LINE__); ++ fdo_free(temp); ++ goto error; ++ } ++ if (xLen != pub_x_len || yLen != pub_y_len) { ++ LOG(LOG_ERROR, "wc_ecc_export_public_raw returned unexpected coordinate length at %d\n", __LINE__); ++ fdo_free(temp); ++ goto error; ++ } ++ ++ /* X */ ++ write_be16_len(&temp[0], xLen); ++ size = LEN_PREFIX_SIZE + xLen; ++ ++ /* Y */ ++ write_be16_len(&temp[size], yLen); ++ size += LEN_PREFIX_SIZE; ++ ++ size += yLen; ++ ++ /* DevRand */ ++ write_be16_len(&temp[size], key_ex_data->_Dev_rand_size); ++ size += LEN_PREFIX_SIZE; ++ if (memcpy_s(&temp[size], allocbytes - size, key_ex_data->_Device_random, key_ex_data->_Dev_rand_size) != 0) { ++ fdo_free(temp); ++ goto error; ++ } ++ size += key_ex_data->_Dev_rand_size; ++ ++ key_ex_data->_publicB = temp; ++ key_ex_data->_publicB_length = size; ++ ++ *context = (void *)key_ex_data; ++ return 0; ++ ++error: ++ crypto_hal_kex_close((void **)&key_ex_data); ++ return -1; ++} ++ ++int32_t crypto_hal_get_device_random(void *context, uint8_t *dev_rand_value, ++ uint32_t *dev_rand_length) ++{ ++ ecdh_context_t *key_ex_data = (ecdh_context_t *)context; ++ if (!key_ex_data || !dev_rand_length) { ++ return -1; ++ } ++ if (!dev_rand_value) { ++ *dev_rand_length = key_ex_data->_publicB_length; ++ return 0; ++ } ++ if (*dev_rand_length < key_ex_data->_publicB_length) { ++ return -1; ++ } ++ if (memcpy_s(dev_rand_value, *dev_rand_length, key_ex_data->_publicB, key_ex_data->_publicB_length) != 0) { ++ return -1; ++ } ++ *dev_rand_length = key_ex_data->_publicB_length; ++ return 0; ++} ++ ++/** ++ * Parse the wire-format peer-random blob (2-byte-length-prefixed Ax, Ay, ++ * owner-random) out of `temp`/`temp_length`. Returns 0 and sets the out ++ * parameters to point inside `temp` on success, -1 on any malformed/ ++ * out-of-bounds field. ++ */ ++static int32_t parse_peer_random_fields(uint8_t *temp, uint32_t temp_length, ++ uint32_t *size_Ax, uint8_t **Ax, ++ uint32_t *size_Ay, uint8_t **Ay, ++ uint32_t *size_owner_random, ++ uint8_t **owner_random) ++{ ++ uint32_t size = 0; ++ ++ if (size + 2 > temp_length) { ++ return -1; ++ } ++ *size_Ax = (temp[size] << 8) | temp[size + 1]; ++ size += 2; ++ *Ax = &temp[size]; ++ if (*size_Ax > temp_length - size) { ++ return -1; ++ } ++ size += *size_Ax; ++ ++ if (size + 2 > temp_length) { ++ return -1; ++ } ++ *size_Ay = (temp[size] << 8) | temp[size + 1]; ++ size += 2; ++ *Ay = &temp[size]; ++ if (*size_Ay > temp_length - size) { ++ return -1; ++ } ++ size += *size_Ay; ++ ++ if (size + 2 > temp_length) { ++ return -1; ++ } ++ *size_owner_random = (temp[size] << 8) | temp[size + 1]; ++ size += 2; ++ *owner_random = &temp[size]; ++ if (*size_owner_random > temp_length - size) { ++ return -1; ++ } ++ size += *size_owner_random; ++ ++ /* ++ * A peer may serialise Ax/Ay with leading zero bytes stripped (the ++ * OpenSSL back end does exactly that via BN_bn2bin), so a short ++ * coordinate is legal and must be left-padded by the caller before ++ * being handed to wc_ecc_import_unsigned(), which takes no length ++ * argument and always reads a fixed curve-size number of bytes. ++ */ ++ if (size > temp_length || *size_Ax > AX_AY_SIZE_DEF || ++ *size_Ay > AX_AY_SIZE_DEF || ++ *size_owner_random > OWNERRAND_SIZE_DEF) { ++ return -1; ++ } ++ ++ return 0; ++} ++ ++int32_t crypto_hal_set_peer_random(void *context, ++ const uint8_t *peer_rand_value, ++ uint32_t peer_rand_length) ++{ ++ ecdh_context_t *key_ex_data = (ecdh_context_t *)context; ++ uint32_t size_Ax = 0, size_Ay = 0, size_owner_random = 0; ++ uint8_t *Ax = NULL, *Ay = NULL, *owner_random = NULL; ++ ++ if (context == NULL || peer_rand_value == NULL || peer_rand_length == 0) { ++ return -1; ++ } ++ ++ /* A prior call on this context would otherwise be leaked here. */ ++ if (key_ex_data->_publicA) { ++ fdo_free(key_ex_data->_publicA); ++ key_ex_data->_publicA = NULL; ++ } ++ ++ key_ex_data->_publicA = fdo_alloc(peer_rand_length); ++ if (key_ex_data->_publicA == NULL) { ++ return -1; ++ } ++ if (memcpy_s(key_ex_data->_publicA, peer_rand_length, peer_rand_value, peer_rand_length) != 0 || ++ parse_peer_random_fields(key_ex_data->_publicA, peer_rand_length, ++ &size_Ax, &Ax, &size_Ay, &Ay, ++ &size_owner_random, &owner_random) != 0) { ++ fdo_free(key_ex_data->_publicA); ++ key_ex_data->_publicA = NULL; ++ return -1; ++ } ++ ++ ecc_key peer_key; ++ if (wc_ecc_init(&peer_key) != 0) { ++ fdo_free(key_ex_data->_publicA); ++ key_ex_data->_publicA = NULL; ++ return -1; ++ } ++ ++ /* ++ * wc_ecc_import_unsigned() reads exactly AX_AY_SIZE_DEF bytes per ++ * coordinate, so right-align whatever the peer sent into fixed-width ++ * slots first. ++ */ ++ uint8_t Ax_padded[AX_AY_SIZE_DEF] = {0}; ++ uint8_t Ay_padded[AX_AY_SIZE_DEF] = {0}; ++ ++ if (wolfssl_ecdsa_place_coord(Ax_padded, AX_AY_SIZE_DEF, Ax, size_Ax) != 0 || ++ wolfssl_ecdsa_place_coord(Ay_padded, AX_AY_SIZE_DEF, Ay, size_Ay) != 0) { ++ wc_ecc_free(&peer_key); ++ fdo_free(key_ex_data->_publicA); ++ key_ex_data->_publicA = NULL; ++ return -1; ++ } ++ ++ if (wc_ecc_import_unsigned(&peer_key, Ax_padded, Ay_padded, NULL, ++ CURVE_ID) != 0) { ++ wc_ecc_free(&peer_key); ++ fdo_free(key_ex_data->_publicA); ++ key_ex_data->_publicA = NULL; ++ return -1; ++ } ++ ++ uint8_t secret[BUFF_SIZE_512_BYTES] = {0}; ++ word32 secret_size = sizeof(secret); ++ ++ if (wc_ecc_shared_secret(&(key_ex_data->key), &peer_key, secret, &secret_size) != 0) { ++ memset_s(secret, sizeof(secret), 0); ++ wc_ecc_free(&peer_key); ++ fdo_free(key_ex_data->_publicA); ++ key_ex_data->_publicA = NULL; ++ return -1; ++ } ++ wc_ecc_free(&peer_key); ++ ++ /* ++ * wc_ecc_shared_secret() always zero-pads its output to the full ++ * curve width (e.g. 32/48 bytes), unlike OpenSSL's BN_bn2bin used by ++ * the openssl back end, which strips leading zero bytes. Strip the ++ * same leading zeros here so ShSe (and the session keys derived from ++ * it) match byte-for-byte with an OpenSSL-based peer whenever the ++ * shared secret's high-order byte(s) happen to be zero. ++ */ ++ uint8_t *secret_trimmed = secret; ++ word32 secret_trimmed_size = secret_size; ++ while (secret_trimmed_size > 1 && secret_trimmed[0] == 0) { ++ secret_trimmed++; ++ secret_trimmed_size--; ++ } ++ ++ uint32_t custom_shse_size = key_ex_data->_Dev_rand_size + size_owner_random + secret_trimmed_size; ++ uint8_t *shse = fdo_alloc(custom_shse_size); ++ if (!shse) { ++ memset_s(secret, sizeof(secret), 0); ++ return -1; ++ } ++ ++ uint32_t offset = 0; ++ if (memcpy_s(&shse[offset], custom_shse_size - offset, secret_trimmed, secret_trimmed_size) != 0) { ++ memset_s(secret, sizeof(secret), 0); ++ memset_s(shse, custom_shse_size, 0); ++ fdo_free(shse); ++ return -1; ++ } ++ offset += secret_trimmed_size; ++ if (memcpy_s(&shse[offset], custom_shse_size - offset, key_ex_data->_Device_random, key_ex_data->_Dev_rand_size) != 0) { ++ memset_s(secret, sizeof(secret), 0); ++ memset_s(shse, custom_shse_size, 0); ++ fdo_free(shse); ++ return -1; ++ } ++ offset += key_ex_data->_Dev_rand_size; ++ if (memcpy_s(&shse[offset], custom_shse_size - offset, owner_random, size_owner_random) != 0) { ++ memset_s(secret, sizeof(secret), 0); ++ memset_s(shse, custom_shse_size, 0); ++ fdo_free(shse); ++ return -1; ++ } ++ ++ memset_s(secret, sizeof(secret), 0); ++ ++ if (key_ex_data->_shared_secret) { ++ memset_s(key_ex_data->_shared_secret, ++ key_ex_data->_shared_secret_length, 0); ++ fdo_free(key_ex_data->_shared_secret); ++ key_ex_data->_shared_secret = NULL; ++ } ++ ++ key_ex_data->_shared_secret = shse; ++ key_ex_data->_shared_secret_length = custom_shse_size; ++ ++ return 0; ++} ++ ++int32_t crypto_hal_get_secret(void *context, uint8_t *secret, ++ uint32_t *secret_length) ++{ ++ ecdh_context_t *key_ex_data = (ecdh_context_t *)context; ++ if (!key_ex_data || !secret_length) { ++ return -1; ++ } ++ if (!secret) { ++ *secret_length = key_ex_data->_shared_secret_length; ++ return 0; ++ } ++ if (*secret_length < key_ex_data->_shared_secret_length) { ++ return -1; ++ } ++ if (memcpy_s(secret, *secret_length, key_ex_data->_shared_secret, key_ex_data->_shared_secret_length) != 0) { ++ return -1; ++ } ++ *secret_length = key_ex_data->_shared_secret_length; ++ return 0; ++} ++ ++#else /* !(KEX_ECDH_ENABLED || KEX_ECDH384_ENABLED) */ ++ ++int32_t crypto_hal_kex_close(void **context) ++{ ++ (void)context; ++ return -1; ++} ++ ++int32_t crypto_hal_kex_init(void **context) ++{ ++ (void)context; ++ return -1; ++} ++ ++int32_t crypto_hal_get_device_random(void *context, uint8_t *dev_rand_value, ++ uint32_t *dev_rand_length) ++{ ++ (void)context; ++ (void)dev_rand_value; ++ (void)dev_rand_length; ++ return -1; ++} ++ ++int32_t crypto_hal_set_peer_random(void *context, ++ const uint8_t *peer_rand_value, ++ uint32_t peer_rand_length) ++{ ++ (void)context; ++ (void)peer_rand_value; ++ (void)peer_rand_length; ++ return -1; ++} ++ ++int32_t crypto_hal_get_secret(void *context, uint8_t *secret, ++ uint32_t *secret_length) ++{ ++ (void)context; ++ (void)secret; ++ (void)secret_length; ++ return -1; ++} ++ ++#endif /* KEX_ECDH_ENABLED || KEX_ECDH384_ENABLED */ +diff --git a/crypto/wolfssl/wolfssl_rng_util.h b/crypto/wolfssl/wolfssl_rng_util.h +new file mode 100644 +index 0000000..2d32849 +--- /dev/null ++++ b/crypto/wolfssl/wolfssl_rng_util.h +@@ -0,0 +1,27 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Accessor for the process-lifetime wolfCrypt RNG owned by ++ * wolfssl_cryptoSupport.c, so short-lived operations (e.g. a single ECDSA ++ * sign) don't pay for their own wc_InitRng()/wc_FreeRng() pair - each of ++ * which reseeds from the OS entropy source - on every call. ++ */ ++ ++#ifndef WOLFSSL_RNG_UTIL_H ++#define WOLFSSL_RNG_UTIL_H ++ ++#include ++ ++/** ++ * @return the shared RNG initialized by random_init(), or NULL if ++ * random_init() hasn't been called (or random_close() already ran). ++ * Callers must not wc_FreeRng() the returned pointer - it is owned ++ * by wolfssl_cryptoSupport.c for the life of the process. ++ */ ++WC_RNG *wolfssl_shared_rng(void); ++ ++#endif /* WOLFSSL_RNG_UTIL_H */ +diff --git a/docs/build_conf.md b/docs/build_conf.md +index 8927763..5eb8a33 100644 +--- a/docs/build_conf.md ++++ b/docs/build_conf.md +@@ -56,11 +56,20 @@ DA=ecdsa256 # Use ECDSA P256 based device attestation + DA=ecdsa384 # Use ECDSA-P384 based device attestation(default) + DA=tpm20_ecdsa256 # Use ECDSA-P256 based device attestation with TPM2.0 support + DA=tpm20_ecdsa384 # Use ECDSA-P384 based device attestation with TPM2.0 support ++DA=cse_ecdsa384 # Use ECDSA-P384 based device attestation with Intel CSE (see docs/cse.md) + DA_FILE=pem # only Use if ECDSA private keys are PEM encoded + ++TPM Software Stack (valid when DA=tpm20_...): ++TPM_STACK=tpm2 # Use the tpm2-tss backend for TPM operations (default when TLS=openssl) ++TPM_STACK=wolftpm # Use the wolfTPM backend for TPM operations (default when TLS=wolfssl) ++# TPM_STACK is independent of TLS; wolftpm may be combined with TLS=openssl. ++# Provisioning (utils/tpm_make_ready_ecdsa.sh) requires tpm2-tools and the ++# tpm2 OpenSSL provider for either stack. ++ + Underlying crypto library to be used: + TLS=openssl # (Linux default, not supported for other TARGET_OS) + TLS=mbedtls # (Mbed OS default, not supported for other TARGET_OS) ++TLS=wolfssl # (Linux only; see docs/wolfssl.md) + CRYPTO_HW=true # Use Secure element for some of the crypto operations(default = false) + + Option to enable network-proxy: +@@ -109,15 +118,40 @@ Option to lock TPM for futher reads and writes: + LOCK_TPM=true # TPM Locked for futher reads and writes (default) + LOCK_TPM=false # TPM not locked for futher reads and writes + ++Option to select the TPM TCTI (valid when DA=tpm20_... and TPM_STACK=tpm2). ++Passed verbatim to Tss2_TctiLdr_Initialize(), so any name tpm2-tss knows works: ++TPM2_TCTI_TYPE=tabrmd # Use the tpm2-abrmd resource manager (default) ++TPM2_TCTI_TYPE=tpmrm0 # Use the in-kernel resource manager /dev/tpmrm0 ++ ++Option to build the unit tests: ++unit-test=true # Build the unit test binaries under build/ ++unit-test=false # (default) ++ + List of options to clean targets: + pristine # cleanup by remove generated files + + Supported values for C standard are: C90 and C99 + ``` + ++## Environment Variables ++ ++CMake locates dependencies through these variables. Each one that says "probed" is only ++required when the library is installed somewhere outside the listed search paths. ++ ++| Variable | Required when | Notes | ++| --- | --- | --- | ++| `SAFESTRING_ROOT` | always | Probed: `./safestringlib` | ++| `TINYCBOR_ROOT` | `TARGET_OS=linux` | Probed: `./tinycbor` | ++| `CURL_ROOT` | `TARGET_OS=linux` | Probed: `/usr/local`, `/usr`, plus `../curl-install` and `/opt/curl` when `TLS=wolfssl` | ++| `OPENSSL3_ROOT` | `TLS=openssl` | Not probed; must be set | ++| `WOLFSSL_ROOT` | `TLS=wolfssl`, or `TPM_STACK=wolftpm` on any backend | Probed: `../wolfssl-install`, `/opt/wolfssl`, `/usr/local` | ++| `WOLFTPM_ROOT` | `TPM_STACK=wolftpm` | Optional; only needed if wolfTPM is outside the default compiler/linker paths | ++| `METEE_ROOT` | `DA=cse_*` | Not probed; must be set | ++ + ## Crypto Library Support + a. TARGET_OS=linux supports + - openssl ++ - wolfssl (see [docs/wolfssl.md](wolfssl.md)) + (`linux` denotes the Linux* OS.) + + b. TARGET_OS=mbedos supports +diff --git a/docs/cse.md b/docs/cse.md +index 4dcd840..7cf2a99 100644 +--- a/docs/cse.md ++++ b/docs/cse.md +@@ -4,6 +4,10 @@ The development and execution OS used was `Ubuntu* OS version [20.04|22.04] / RH + + The Intel® CSE (Intel® Converged Security Engine) enabled FDO Client SDK execution depends on OpenSSL* toolkit 3.0.14 version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. + ++> ***NOTE***: This page covers CSE with the OpenSSL backend. CSE also works with wolfSSL ++> (`TLS=wolfssl`); the hardware/firmware prerequisites above still apply, see ++> [docs/wolfssl.md](wolfssl.md#9-cse-support) for the build details. ++ + # Prerequisites for Intel® CSE support + The system hardware should have the support for Intel® CSE FDO client with UUID: 125405e0-fca9-4110-8f88-b4dbcdcb876f + +@@ -222,7 +226,6 @@ make -j$(nproc) + > + Refer to the section [FDO Build configurations](build_conf.md) for more build options. + +- + + ## 8. Running the Application + The Intel® CSE enabled FDO Client SDK Linux device is compatible with FDO PRI components namely: Manufacturer, Rendezvous, and Owner. +diff --git a/docs/linux.md b/docs/linux.md +index 37f9247..c0d2dba 100644 +--- a/docs/linux.md ++++ b/docs/linux.md +@@ -4,6 +4,9 @@ The development and execution OS used was `Ubuntu* OS version [20.04|22.04] / RH + + The FDO Client SDK execution depends on OpenSSL* toolkit 3.0.14 version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. + ++> ***NOTE***: This page covers the OpenSSL backend (`TLS=openssl`, the default). For wolfSSL ++> (`TLS=wolfssl`), see [docs/wolfssl.md](wolfssl.md). ++ + ## 1. Packages Requirements when Building Binaries: + * For Ubuntu* OS version [20.04|22.04] / Debian 11.4: + ```shell +@@ -201,7 +204,6 @@ bash utils/keys_gen.sh . + Several other options to choose when building the device are, but not limited to, the following: device-attestation (DA) methods, Advanced Encryption Standard (AES) encryption modes (AES_MODE), and underlying cryptography library to use (TLS). + Refer to the section. [FDO Build configurations](build_conf.md) + +- + + ## 7. Running the Application + The FDO Client SDK Linux device is compatible with FDO PRI components namely: Manufacturer, Rendezvous, and Owner. +diff --git a/docs/mbed_linux.md b/docs/mbed_linux.md +index 233d2b5..d527a96 100644 +--- a/docs/mbed_linux.md ++++ b/docs/mbed_linux.md +@@ -64,4 +64,4 @@ To flash the WaRP7 device with the build image, follow the steps in [this](https + After the device is flashed, use the [Setting up a WI-FI* connection](https://github.com/ARMmbed/mbl-docs/blob/v0.9/Docs/install_mbl_on_device/connect_network_and_pelion/connect_network.md) connect the device to the Wi-Fi* network for the first time. + + ## Running FDO Client SDK +-After a successful flash, the FDO Client SDK Cortex-A7 device executable can be found at `/opt/fdo/linux-client`. Follow the steps in the [Execution](./linux.md#run_linux_fdo) section of [this](./linux.md) document to run the FDO Cortex-A7 application against the FDO PRI implementation. ++After a successful flash, the FDO Client SDK Cortex-A7 device executable can be found at `/opt/fdo/linux-client`. Follow the steps in the [Execution](./linux.md#7-running-the-application) section of [this](./linux.md) document to run the FDO Cortex-A7 application against the FDO PRI implementation. +diff --git a/docs/secure_element.md b/docs/secure_element.md +index 6921d64..1284cec 100644 +--- a/docs/secure_element.md ++++ b/docs/secure_element.md +@@ -37,6 +37,10 @@ FDO implementation for ARM devices uses Microchip AT608A as the secure element. + $ cd ~ + $ git clone https://github.com/MicrochipTech/cryptoauthlib.git cryptoauthlib + ``` ++ CryptoAuthLib 20191122 or newer is required. The SDK follows the library's ++ `ATCA_USE_CONSTANT_HOST_NONCE` setting: by default it passes a fresh host nonce to ++ `atcab_write_enc()`/`atcab_priv_write()`, and falls back to the older constant-nonce ++ calls only if CryptoAuthLib was built with that option. + + 3. Install the shared binary object. Prerequisite for this step is cmake should be available. + And note this has to be build for Raspberry Pi(RPI) which is an ARM platform. Cross compile or native build +diff --git a/docs/security_implications.md b/docs/security_implications.md +index 808e637..56dd908 100644 +--- a/docs/security_implications.md ++++ b/docs/security_implications.md +@@ -40,6 +40,19 @@ L=2 could also be used. N=13 MUST be used in this case. + Affected file(s):
+ - `base.mk` + ++## Linux* OS (wolfSSL as the cryptography library) ++ ++1. The random number needs to be seeded with an entropy source, same as the OpenSSL backend. ++ Affected file(s): ++ - `crypto/wolfssl/wolfssl_cryptoSupport.c` ++ ++2. wolfSSL's `--enable-harden` build option (used by [install_wolfssl_curl.sh](../utils/install_wolfssl_curl.sh)) ++ enables timing/side-channel hardening and is recommended for production builds. ++ ++3. Same caveat as the OpenSSL backend (see item 2 above): in the reference implementation, ++ the device key and the keys that encrypt or protect FDO data integrity are stored in ++ clear text on the file system. ++ + ***NOTE***: The configurations mentioned for below platforms are not supported yet. They will be updated in a future release. + + ## NUCLEO-F429ZI board: Arm Cortex* -M4/Arm Mbed* OS (mbedTLS as the cryptography library) +@@ -132,7 +145,6 @@ L=2 could also be used. N=13 MUST be used in this case. + MBEDTLS_SSL_EXTENDED_MASTER_SECRET + ``` + +- + ## mbedTLS Hardware Entropy Source + To enable the TRNG hardware as the entropy source, the + `MBEDTLS_ENTROPY_HARDWARE_ALT` macro must be uncommented in +diff --git a/docs/setup.md b/docs/setup.md +index c29dd8a..5735a83 100644 +--- a/docs/setup.md ++++ b/docs/setup.md +@@ -1,19 +1,21 @@ + + + # FIDO Device Onboard (FDO) Compilation Setup +- ++ ++> ***NOTE***: This page's steps (safestring, TinyCBOR, key generation, etc.) apply regardless of ++> crypto backend. Where a step is OpenSSL-specific (e.g. ECDSA Private Key Generation below), ++> see [docs/wolfssl.md](wolfssl.md) for the wolfSSL equivalent. ++ + ## 1. Intel safestringlib + FDO Client SDK uses safestringlib for string and memory operations to prevent serious security vulnerabilities (For example, buffer overflows). + + * For Linux*/ Arm Mbed* OS/ Arm Mbed* Linux* OS builds, download safestring from intel-safestringlib. + +- + ## 2. Intel TinyCBOR + FDO Client SDK uses TinyCBOR library for Concise Binary Object Representation (CBOR) encoding and decoding. + + * For Linux* OS builds, download TinyCBOR from tinycbor. + +- + ## 3. Setting the Manufacturer Network Address + To set the manufacturer network address(transport protocol, DNS/IP and/or port) that FDO Client SDK Linux device uses during Device Initialization (DI) protocol: + +@@ -37,7 +39,6 @@ $ echo -n https://127.0.0.1:12345 > data/manufacturer_addr.bin + + > ***NOTE***: By default, `manufacturer_addr.bin` is configured with `http://host.docker.internal:8039` + +- + ## 4. Elliptic Curve Digital Signature Algorithm (ECDSA) Private Key File Generation + The following are steps to generate the private key file for ECDSA-based devices, only EC Curve `P-256` and `P-384` are supported. + +@@ -74,7 +75,6 @@ The following are steps to generate the private key file for ECDSA-based devices + + * **Option2:** To use the private key in PEM format, rename key.pem to ecdsaXXXprivkey.pem (`ecdsa256privkey.pem` for EC curve P-256 and `ecdsa384privkey.pem` for EC curve P-384). Use the compilation flag `DA_FILE=pem` during binary creation. + +- + ## 5. Setting the Maximum ServiceInfo Size (Maximum Message Buffer Size) + + The maximum permissible ServiceInfo size (both Device and Owner) size that FDO Client SDK can process should be set in the file `max_serviceinfo_sz.bin`. The maximum Message buffer size can also be set using the same `max_serviceinfo_sz.bin` file. The value must lie between 256 and 64000 (both inclusive). If the set value of ServiceInfo is less than 256, the value would default to 256. Similarly, if the value is greater than 64000, the value would default to 64000. +@@ -99,7 +99,6 @@ $ echo -n > data/manufacturer_sn.bin + + > ***NOTE***: By default, `manufacturer_sn.bin` is not there and the device serial is configured with "abcdef". + +- + ## 7. FDO Credentials REUSE Protocol + + The FDO credentials REUSE feature allows FDO devices to reuse their ownership credentials across multiple device onboardings. This feature only gets enabled if the owner sends down the same rendezvous info, device GUID information, and public key at the end of the Transfer of Ownership, Step 2 (TO2) protocol. +@@ -113,7 +112,6 @@ $ cmake -DREUSE=true + ``` + Activating the device credentials will in turn, activate the FDO device and configure the FDO device to run multiple onboarding(s). This can be useful in several test and development environments, where multiple onboardings are common. + +- + ## 8. HTTP-proxy Configuration (Optional) + If the device is located behind a proxy server, the proxy server details must be provided to the device. For the same purpose, there are three files (each for the manufacturer, rendezvous, and owner servers) in which the proxy server details should be specified in the required format, before connecting to the respective server. These files can be created or removed as required. + +diff --git a/docs/tpm.md b/docs/tpm.md +index 8fb926a..ef9e3bc 100644 +--- a/docs/tpm.md ++++ b/docs/tpm.md +@@ -5,6 +5,8 @@ + + The FDO Client SDK execution depends on OpenSSL* toolkit 3.0.14 version. Users must install or upgrade the toolkit before compilation if the toolkit is not available by default in the environment. + ++> ***NOTE***: This page covers TPM using the `tpm2-tss` library stack (`TPM_STACK=tpm2`, the default when `TLS=openssl`). `TPM_STACK=wolftpm` selects the lighter-weight wolfTPM library for runtime attestation instead, and works with either TLS backend; see [docs/wolfssl.md](wolfssl.md#8-tpm-support). The provisioning steps on this page (Sections 5 onward, `tpm_make_ready_ecdsa.sh`) apply to **both** stacks — they use `tpm2-tools` and the tpm2 OpenSSL provider regardless of `TPM_STACK`. ++ + ## 1. Packages Requirements when Building Binaries with TPM* 2.0: + + * For Ubuntu* OS version [20.04|22.04] / Debian 11.4: +@@ -182,6 +184,15 @@ To compile and execute TPM* enabled FDO Client SDK use one of the appropriate co + ``` + sudo ./install_tpm_libs.sh -u + ``` ++ ++ * Command to install TPM* libraries skipping tpm2-openssl ++ ``` ++ sudo ./install_tpm_libs.sh -i -s ++ ``` ++ > ***NOTE***: `-s` is only appropriate for devices that will not be provisioned locally. ++ [tpm_make_ready_ecdsa.sh](../utils/tpm_make_ready_ecdsa.sh) generates the device CSR with ++ `openssl req -provider tpm2` and therefore needs tpm2-openssl on **every** crypto backend, ++ including `TLS=wolfssl` with `TPM_STACK=wolftpm`. + > ***NOTE***: [TPM-Library-Installation-Script](../utils/install_tpm_libs.sh) will use OpenSSL and Curl from /opt/ by default. If you have installed OpenSSL and Curl other than `/opt` path, use `openssl version -a` and `which curl` commands to get the exact path of OpenSSL and Curl and modify these variables in the script OPENSSL3_INCLUDE=/opt/openssl/include (can be /usr/include or /usr/local/include) + CURL_INCLUDE=/opt/curl/include (can be /usr/include or /usr/local/include) + OPENSSL3_LIB=/opt/openssl/lib64 (can be /usr/lib or /usr/local/lib or /usr/lib/x86_64-linux-gnu) +@@ -331,7 +342,6 @@ Several other options to choose when building the device are, but not limited to + Refer to the section [FDO Build configurations](build_conf.md) + + +- + + ## 7. Running the Application + The TPM* enabled FDO Client SDK Linux device is compatible with FDO PRI components - Manufacturer, Reseller, Rendezvous, and Owner. +diff --git a/docs/wolfssl.md b/docs/wolfssl.md +new file mode 100644 +index 0000000..c15d906 +--- /dev/null ++++ b/docs/wolfssl.md +@@ -0,0 +1,207 @@ ++ ++# wolfSSL* Crypto Backend ++ ++The FDO Client SDK's crypto operations can be backed by [wolfSSL](https://www.wolfssl.com/), ++a TLS/crypto library for resource-constrained and embedded devices, as an alternative to ++the OpenSSL and mbedTLS backends. Select it at configure time with `TLS=wolfssl`. ++ ++The development and execution OS used was `Ubuntu* OS version [20.04|22.04] / RHEL* OS ++version [8.4|8.6|8.8] / Debian 11.4` on x86, same as the other Linux reference builds. ++ ++## 1. Packages Requirements when Building Binaries: ++ ++Same base package set as the [Linux reference build](linux.md#1-packages-requirements-when-building-binaries), ++plus autotools for building wolfSSL from source: ++ ++* For Ubuntu* OS version [20.04|22.04] / Debian 11.4: ++```shell ++sudo apt-get install build-essential python-setuptools clang-format dos2unix ruby \ ++ libglib2.0-dev libpcap-dev autoconf libtool libproxy-dev doxygen cmake mercurial nghttp2 libnghttp2-dev ++``` ++ ++* For RHEL* OS version [8.4|8.6|8.8]: ++```shell ++sudo subscription-manager repos --enable codeready-builder-for-rhel-8-x86_64-rpms ++sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm ++``` ++```shell ++sudo yum -y install gcc gcc-c++ python3-setuptools git-clang-format dos2unix ruby perl glibc-static \ ++ glib2-devel libpcap-devel autoconf libtool libproxy-devel mozjs52-devel doxygen cmake make mercurial perl nghttp2 libnghttp2-devel ++``` ++ ++## 2. Building wolfSSL and wolfSSL-linked curl ++ ++With `TLS=wolfssl`, curl is built against wolfSSL too, so the whole stack runs on ++wolfSSL with no OpenSSL dependency. The [Installation-Script](../utils/install_wolfssl_curl.sh) ++handles both steps; it configures wolfSSL with `--enable-curl`, which provides the ++APIs curl's wolfSSL backend requires. ++ ++> ***NOTE***: [Installation-Script](../utils/install_wolfssl_curl.sh) installs wolfSSL and ++> curl at `/opt/wolfssl` and `/opt/curl` by default. To use different paths, export ++> `WOLFSSL_ROOT` and/or `CURL_ROOT` before running it; the script honours both. ++ ++**Script usage command** ++ ++* Command to install wolfSSL and a wolfSSL-linked curl (defaults to pinned wolfSSL v5.9.4-stable): ++ ```shell ++ ./utils/install_wolfssl_curl.sh -i ++ ``` ++ You can also specify a specific version with `-v` (e.g. `./utils/install_wolfssl_curl.sh -i -v 5.9.4`). ++ ++The script calls `sudo` itself for the steps that write outside the build tree (`make ++install`, `ldconfig`), so run it as your normal user. Invoking the whole script under ++`sudo` also works, but `sudo` drops your environment by default, so exported ++`WOLFSSL_ROOT`/`CURL_ROOT` overrides would be silently ignored and the defaults used ++instead. ++ ++If you are building in a dedicated development environment (like a Docker container) and ++have a system OpenSSL-linked curl installed, you can remove it first so the linker ++doesn't pick up the wrong one. ++ ++> ***WARNING***: On a general-purpose desktop or shared server, removing `curl` or `libcurl` ++> packages may unintentionally uninstall other system utilities or desktop environments that ++> depend on them. If you prefer not to remove them, skip this step; see Section 6 for how ++> the binaries still find the right curl. ++ ++```shell ++# Ubuntu / Debian ++sudo apt remove curl libcurl4-openssl-dev ++ ++# RHEL ++sudo yum remove libcurl-devel ++``` ++ ++To verify the install, `$CURL_ROOT/bin/curl -V` should report wolfSSL, not OpenSSL, as its SSL backend. ++ ++## 3. Compiling Local Dependencies (safestringlib and tinycbor) ++ ++The SDK requires `safestringlib` and `tinycbor`. To simplify setup, we provide an automated script that clones, patches (for modern GCC compatibility), builds, and outputs the necessary `export` paths. ++ ++Run the following from the root of the repository: ++```shell ++./utils/setup_local_dependencies.sh ++``` ++ ++## 4. Environment Variables ++ ++Add these environment variables to your terminal session or `~/.bashrc` (replace with actual paths as output by the script in Step 3): ++```shell ++# Defaults if you used the install script in Step 2 ++export WOLFSSL_ROOT=/opt/wolfssl ++export CURL_ROOT=/opt/curl ++export SAFESTRING_ROOT=path/to/safestringlib ++export TINYCBOR_ROOT=path/to/tinycbor ++``` ++ ++`WOLFSSL_ROOT` and `CURL_ROOT` may be omitted if wolfSSL and curl are in a location CMake ++probes automatically (`../wolfssl-install`, `/opt/wolfssl`, `/usr/local` for wolfSSL; ++`../curl-install`, `/opt/curl`, `/usr/local`, `/usr` for curl). Set them explicitly if you ++installed anywhere else, or to be sure of which copy gets linked. ++ ++`WOLFTPM_ROOT` is only needed for `TPM_STACK=wolftpm` (see Section 8), and only if wolfTPM ++is installed outside the default linker search path. ++ ++`OPENSSL3_ROOT` is **not** required here; it's only checked when `TLS=openssl`. ++ ++## 5. Compiling FDO Client SDK ++ ++We recommend using an out-of-source build (`cmake -B build`) to keep your root directory clean of CMake artifacts. See [FDO Compilation Setup](setup.md) and [FDO Build configurations](build_conf.md) for the full set of options. ++ ++Select the wolfSSL backend with `TLS=wolfssl`: ++ ++```shell ++cmake -B build -DTLS=wolfssl ++cmake --build build -j$(nproc) ++bash utils/keys_gen.sh build ++``` ++ ++## 6. Runtime Library Paths ++ ++`linux-client` and the unit test binaries are linked with an rpath to `$CURL_ROOT/lib` ++and `$WOLFSSL_ROOT/lib`, so they load the wolfSSL-linked curl even when a system ++OpenSSL-linked `libcurl` is still installed. No `LD_LIBRARY_PATH` is needed. ++ ++Do not export `LD_LIBRARY_PATH=$CURL_ROOT/lib` in the shell you build from: tools such as ++`cmake` and `ctest` link the system `libcurl` themselves and will fail to start ++(`version 'CURL_OPENSSL_4' not found`) if pointed at the wolfSSL-linked one. ++ ++## 7. Running the Application ++ ++Running against FDO PRI Manufacturer, Rendezvous, and Owner components follows the same ++steps as the [Linux reference build](linux.md#7-running-the-application). ++ ++## 8. TPM* Support ++ ++Currently, TPM hardware attestation is supported for both OpenSSL and wolfSSL backends. Set ++`TPM_STACK=wolftpm` during CMake configuration to use the lightweight wolfTPM library for ++device attestation instead of the legacy `tpm2-tss` dependencies. wolfTPM links against ++wolfCrypt regardless of which `TLS` backend is selected, so `TPM_STACK=wolftpm` works with ++either `TLS=wolfssl` or `TLS=openssl`: ++ ++```shell ++cmake -DTLS=wolfssl -DTPM_STACK=wolftpm -DDA=tpm20_ecdsa384 -DAES_MODE=gcm . ++# or, TPM_STACK=wolftpm with the OpenSSL TLS backend: ++cmake -DTLS=openssl -DTPM_STACK=wolftpm -DDA=tpm20_ecdsa384 -DAES_MODE=gcm . ++``` ++ ++With `TLS=openssl`, wolfSSL is only used by wolfTPM: TLS and curl stay on OpenSSL, so use ++your system's OpenSSL-linked curl. Both OpenSSL and wolfSSL end up linked into ++`linux-client`, which is safe because wolfSSL exports only `wolfSSL_`/`wc_`-prefixed ++symbols; its OpenSSL-compatible names (from `--enable-curl` or `--enable-opensslextra`) are ++header macros and never reach the linker. ++ ++The wolfSSL built by `utils/install_wolfssl_curl.sh` (step 2, above) already includes the ++flags wolfTPM needs (`--enable-wolftpm --enable-pkcallbacks`, plus the ++`-DWC_RNG_SEED_CB -DWOLFSSL_CUSTOM_OID -DHAVE_OID_ENCODING` defines) - if you built wolfSSL ++that way, no extra steps are needed. If you're linking against a wolfSSL built some other ++way (e.g. a system package, or your own from-source build), it must be configured with ++those same flags or `linux-client` will fail to link against `libwolftpm.so` with undefined ++references such as `wc_CryptoCb_RegisterDevice`, `wolfSSL_CTX_SetEccSignCb`, or ++`wc_AesCfbEncrypt`. ++ ++Build wolfTPM itself (against that same wolfSSL) using the install script (pinned to ++wolfTPM `v4.2.0`): ++ ++```shell ++./utils/install_wolfssl_curl.sh -t ++``` ++ ++Or build it manually per its own [README](https://github.com/wolfSSL/wolfTPM#building-wolfssl). ++If you install it somewhere the compiler and linker don't search by default, export `WOLFTPM_ROOT` ++so CMake picks up its headers and `libwolftpm`: ++ ++```shell ++export WOLFTPM_ROOT=/opt/wolftpm ++``` ++ ++`TPM2_TCTI_TYPE` only applies to `TPM_STACK=tpm2`. wolfTPM uses the transport it was ++built with: with `--enable-devtpm` it opens `/dev/tpmrm0` (the kernel resource manager), ++falling back to `/dev/tpm0`. Because `/dev/tpm0` is held exclusively by `tpm2-abrmd` when ++that service is running, make sure `/dev/tpmrm0` is available and that your user can open ++it (typically membership of the `tss` group). ++ ++> ***NOTE***: TPM provisioning is not yet backend-independent. `TPM_STACK=wolftpm` covers ++> the *runtime* attestation path (signing during TO1/TO2) only. The one-time provisioning ++> step, [`utils/tpm_make_ready_ecdsa.sh`](../utils/tpm_make_ready_ecdsa.sh), still generates ++> the device CSR with `openssl req -provider tpm2`, so it requires OpenSSL 3 and the ++> `tpm2-openssl` provider (plus the `tpm2-tools` package) even when the SDK itself is built ++> with `TLS=wolfssl` and `TPM_STACK=wolftpm`. Do not pass `-s` to ++> [`utils/install_tpm_libs.sh`](../utils/install_tpm_libs.sh) if you intend to provision on ++> the same machine. A wolfCrypt-native replacement is tracked as a TODO in that script. ++ ++## 9. CSE* Support ++ ++Build with `-DDA=cse_ecdsa384`, same as the [CSE reference implementation](cse.md). The CSE ++implementation (`crypto/common/cse_crypto_support.c`, reused as-is) talks to Intel's Converged ++Security Engine over HECI and has no crypto-backend dependency. It still needs the Intel ++platform hardware/firmware with the FDO CSE client enabled, see [docs/cse.md](cse.md) for ++prerequisites, which apply regardless of `TLS=` backend. ++ ++## 10. Licensing ++ ++The FDO Client SDK is Apache-2.0, but wolfSSL and wolfTPM are distributed under **GPLv3** ++(with a commercial license available from wolfSSL Inc.), unlike the Apache-2.0 OpenSSL 3 ++used by the default backend. Building with `TLS=wolfssl` — or with `TPM_STACK=wolftpm` ++under any TLS backend — links GPLv3 code into `linux-client`, which carries obligations for ++anything you redistribute. See the [NOTICE](../NOTICE) file for the full terms, including ++the GPLv2 relicensing exception and commercial licensing contact. +diff --git a/lib/credentials_from_file.c b/lib/credentials_from_file.c +index 406c83d..26dfcf5 100644 +--- a/lib/credentials_from_file.c ++++ b/lib/credentials_from_file.c +@@ -22,7 +22,7 @@ + #include "cse_tools.h" + #endif + #if defined(DEVICE_TPM20_ENABLED) +-#include "tpm2_nv_storage.h" ++#include "fdo_tpm_handles.h" + #endif + + static bool validate_state(fdo_sdk_device_status current_status); +diff --git a/lib/fdoblockio.c b/lib/fdoblockio.c +index 22b3b0c..a61dc03 100644 +--- a/lib/fdoblockio.c ++++ b/lib/fdoblockio.c +@@ -22,6 +22,8 @@ + * contents to 0, upto the internal block size. + * + * @param fdo_block_t - struct containg the buffer and its size ++ * @note This zeroes the buffer contents only; it does not free the block. ++ * Use fdor_flush()/fdow_flush() to release the memory. + */ + void fdo_block_reset(fdo_block_t *fdob) + { +@@ -1050,4 +1052,4 @@ void fdor_flush(fdor_t *fdor) + fdo_free(fdor->current); + } + } +-} +\ No newline at end of file ++} +diff --git a/lib/fdocred.c b/lib/fdocred.c +index d28030f..8f7d378 100644 +--- a/lib/fdocred.c ++++ b/lib/fdocred.c +@@ -847,4 +847,4 @@ void fdo_owner_supplied_credentials_free(fdo_owner_supplied_credentials_t *osc) + osc->rvlst = NULL; + fdo_free(osc); + } +-} +\ No newline at end of file ++} +diff --git a/lib/fdoprotctx.c b/lib/fdoprotctx.c +index 8c41e7a..ba9a05e 100644 +--- a/lib/fdoprotctx.c ++++ b/lib/fdoprotctx.c +@@ -354,7 +354,7 @@ int fdo_prot_ctx_run(fdo_prot_ctx_t *prot_ctx) + n = fdo_con_send_recv_message( + FDO_PROT_SPEC_VERSION, fdow->msg_type, + &fdow->b.block[0], size, prot_ctx->tls, hdr_buf, +- body_buf); ++ sizeof(hdr_buf), body_buf, sizeof(body_buf)); + + if (n < 0) { + if (fdo_con_disconnect()) { +diff --git a/lib/include/util.h b/lib/include/util.h +index 2d2efc6..811f6de 100644 +--- a/lib/include/util.h ++++ b/lib/include/util.h +@@ -84,6 +84,7 @@ typedef enum log_level { + #define BUFF_SIZE_32_BYTES 32 + #define BUFF_SIZE_48_BYTES 48 + #define BUFF_SIZE_64_BYTES 64 ++#define BUFF_SIZE_96_BYTES 96 + #define BUFF_SIZE_128_BYTES 128 + #define BUFF_SIZE_256_BYTES 256 + #define BUFF_SIZE_512_BYTES 512 +diff --git a/lib/m-string.c b/lib/m-string.c +index 633c538..951b6ae 100644 +--- a/lib/m-string.c ++++ b/lib/m-string.c +@@ -21,13 +21,13 @@ + #include "cse_tools.h" + #endif + #if defined(DEVICE_TPM20_ENABLED) +-#include "tpm20_Utils.h" + #include "fdo_crypto.h" +-#include "tpm2_nv_storage.h" ++#include "fdo_tpm_handles.h" + #endif + + #include + #include ++#include + + /* + * Generate the "m" string value. +@@ -280,6 +280,16 @@ int ps_get_m_string(fdo_prot_t *ps) + #if defined(DEVICE_TPM20_ENABLED) + size_t m_string_sz = fdo_tpm_nvread_size(TPM_DEVICE_CSR_NV_IDX); + ++ /* 0 means the CSR index is absent or unreadable. Check it here rather ++ * than letting it reach fdo_byte_array_alloc(), which succeeds for a ++ * zero size and returns an array with a NULL payload. The size also ++ * has to fit the int parameter that allocator takes. */ ++ if (m_string_sz == 0 || m_string_sz > INT_MAX) { ++ LOG(LOG_ERROR, ++ "Device CSR is missing or unreadable from the TPM.\n"); ++ goto err; ++ } ++ + csr = fdo_byte_array_alloc(m_string_sz); + if (!csr) { + LOG(LOG_ERROR, +diff --git a/mbedos/CMakeLists.txt b/mbedos/CMakeLists.txt +index 4c7e724..22d16f0 100644 +--- a/mbedos/CMakeLists.txt ++++ b/mbedos/CMakeLists.txt +@@ -27,6 +27,7 @@ if (NOT(${MANUFACTURER_DN} STREQUAL " " )) + endif() + + # Create links ++file(MAKE_DIRECTORY ${MBED_OS_DIR}/fdo) + + execute_process(COMMAND + ${CMAKE_COMMAND} -E create_symlink +@@ -97,17 +98,19 @@ else() + list (APPEND MBEDOS_STORAGE_IGNORE "storage_if_mbedSD.cpp\n") + endif() + +-if (${KEX} MATCHES ecdh) ++list (APPEND COMMON_IGNORE "cse_crypto_support.c\n") ++ ++if ("${KEX}" MATCHES "ecdh") + list (APPEND MBEDTLS_IGNORE "mbedtls_key_exchange_dh.c\n") + list (APPEND MBEDTLS_IGNORE "mbedtls_RSARoutines.c\n") + list (APPEND COMMON_IGNORE "fdokeyexchange_asym.c\n") + endif() + +-if (${PK_ENC} STREQUAL ecdsa) ++if ("${PK_ENC}" STREQUAL "ecdsa") + list (APPEND MBEDTLS_IGNORE "mbedtls_RSAVerifyRoutines.c\n") + endif() + +-if (${CRYPTO_HW} STREQUAL false) ++if ("${CRYPTO_HW}" STREQUAL "false") + list (APPEND MBEDTLS_IGNORE "mbedtls_DERRoutines.c\n") + endif() + +@@ -126,10 +129,24 @@ set(GP_STORAGE_IGNORE "*_optee.c\n") + set(FREERTOS_STORAGE_IGNORE "*_esp.c\n") + + file(WRITE ${MBED_OS_DIR}/safestring/.mbedignore ${SAFESTRING_IGNORE}) +-file(WRITE ${MBED_OS_DIR}/crypto/mbedtls/.mbedignore ${MBEDTLS_IGNORE}) + file(WRITE ${MBED_OS_DIR}/crypto/common/.mbedignore ${COMMON_IGNORE}) + +-file(WRITE ${MBED_OS_DIR}/crypto/openssl/.mbedignore "*.c\n") ++if ("${TLS}" STREQUAL "wolfssl") ++ file(WRITE ${MBED_OS_DIR}/crypto/mbedtls/.mbedignore "*.c\n") ++ file(WRITE ${MBED_OS_DIR}/crypto/openssl/.mbedignore "*.c\n") ++ file(WRITE ${MBED_OS_DIR}/crypto/wolfssl/.mbedignore "") ++else() ++ file(WRITE ${MBED_OS_DIR}/crypto/mbedtls/.mbedignore ${MBEDTLS_IGNORE}) ++ file(WRITE ${MBED_OS_DIR}/crypto/openssl/.mbedignore "*.c\n") ++ file(WRITE ${MBED_OS_DIR}/crypto/wolfssl/.mbedignore "*.c\n") ++endif() ++ ++if (${DA} MATCHES tpm) ++ file(WRITE ${MBED_OS_DIR}/crypto/tpm/.mbedignore "") ++else() ++ file(WRITE ${MBED_OS_DIR}/crypto/tpm/.mbedignore "*.c\n") ++endif() ++ + file(WRITE ${MBED_OS_DIR}/crypto/gp/.mbedignore "*.c\n") + file(WRITE ${MBED_OS_DIR}/crypto/se/.mbedignore "*.c\n") + file(WRITE ${MBED_OS_DIR}/crypto/epid/.mbedignore "*.c\n") +diff --git a/mbedos/components/fdo/.mbed b/mbedos/components/fdo/.mbed +new file mode 100644 +index 0000000..0db1449 +--- /dev/null ++++ b/mbedos/components/fdo/.mbed +@@ -0,0 +1,3 @@ ++TARGET=NUCLEO_F429ZI ++TOOLCHAIN=GCC_ARM ++ROOT=. +diff --git a/mbedos/components/fdo/fdo/main.cpp b/mbedos/components/fdo/fdo/main.cpp +new file mode 100644 +index 0000000..7b259ca +--- /dev/null ++++ b/mbedos/components/fdo/fdo/main.cpp +@@ -0,0 +1,146 @@ ++/* ++ * Copyright 2020 Intel Corporation ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Main application. This file has implementation for entry point into ++ * the platform and necessary things to initialize FDO, run it and exit ++ * gracefully. ++ */ ++ ++#include "mbed.h" ++#if DEBUG_LEVEL > 0 ++#include "mbedtls/debug.h" ++#endif ++ ++#include "mbedtls/platform.h" ++ ++#if defined(MBEDOS_SD_DATA) || defined(CLOUD_CLIENT) ++#include "SDBlockDevice.h" ++#include "FATFileSystem.h" ++#endif ++#include "EthernetInterface.h" ++ ++extern "C" int TO2_done; ++extern "C" void app_main(bool is_resale); ++ ++// TO-DO : Look at the usage of this flag and remove later ++// since this flag has been removed from the source. ++#ifdef MODULES_ENABLED ++extern void cloud_main(SDBlockDevice *bd, FATFileSystem *fs); ++#endif ++ ++#if defined(MBEDOS_SD_DATA) || defined(CLOUD_CLIENT) ++#define SD_MOUNT_POINT "sd" ++SDBlockDevice bd(PE_6, PE_5, PE_2, PE_4); ++FATFileSystem fs(SD_MOUNT_POINT, &bd); ++#endif // defined(MBEDOS_SD_DATA) ++ ++InterruptIn button(USER_BUTTON); ++DigitalOut led(LED1); ++double delay = 1000; // 1000 ms ++ ++#if !defined(MBEDOS_SD_DATA) ++extern int initiate_files_firsttime(void); ++#endif ++ ++int init_eth(void); // initializes Ethernet ++void end_eth(void); // closes Ethernet socket ++ ++// Network interface ++EthernetInterface net; ++nsapi_error_t status; ++ ++EthernetInterface *getNetinterface(void) ++{ ++ return &net; ++} ++ ++int init_eth(void) ++{ ++ // net = NetworkInterface::get_default_instance(); ++ nsapi_error_t status = net.connect(); ++ ++ if (status != 0) { ++ printf("Error! net->connect() returned: %d\n", status); ++ return status; ++ } ++ ++ // Show the network address ++ const char *ip = net.get_ip_address(); ++ const char *netmask = net.get_netmask(); ++ const char *gateway = net.get_gateway(); ++ printf("IP address: %s\n", ip ? ip : "None"); ++ printf("Netmask: %s\n", netmask ? netmask : "None"); ++ printf("Gateway: %s\n", gateway ? gateway : "None"); ++ if (!ip && !netmask && !gateway) { ++ return 1; ++ } else { ++ return 0; ++ } ++ ++} // end init_eth() ++ ++void end_eth(void) ++{ ++ // Bring down the ethernet interface ++ net.disconnect(); ++ // delete &net; ++} // end end_eth ++ ++int do_onboarding(bool is_resale) ++{ ++ int exit_code = MBEDTLS_EXIT_FAILURE; ++#ifdef MBED_MAJOR_VERSION ++ printf("Mbed OS version: %d.%d.%d\n\n", MBED_MAJOR_VERSION, ++ MBED_MINOR_VERSION, MBED_PATCH_VERSION); ++#endif ++ ++ init_eth(); ++#if !defined(MBEDOS_SD_DATA) ++ initiate_files_firsttime(); ++#endif ++ if ((exit_code = mbedtls_platform_setup(NULL)) != 0) { ++ printf("Platform initialization failed with error %d\n", ++ exit_code); ++ return MBEDTLS_EXIT_FAILURE; ++ } ++ app_main(is_resale); ++ if (TO2_done == 1) { ++#ifdef CLOUD_CLIENT ++ cloud_main(&bd, &fs); ++#endif ++ } ++ end_eth(); ++ if (exit_code != 0) { ++ mbedtls_printf("Example failed with error %d\n", exit_code); ++ exit_code = MBEDTLS_EXIT_FAILURE; ++ } ++ ++ mbedtls_platform_teardown(NULL); ++ printf("Done\n"); ++ return 0; ++ ++} ++ ++void butn_released() ++{ ++ do_onboarding(true); ++ delay = 200; ++ printf("Ready for resale -----\n"); ++} ++ ++int main() ++{ ++ ++ do_onboarding(false); //standard onboarding ++ ++ button.rise(&butn_released); ++ ++ while (1) { ++ led = !led; ++ thread_sleep_for(delay); ++ } ++} +diff --git a/mbedos/components/fdo/fdo/mbed_app.json_fdo_only b/mbedos/components/fdo/fdo/mbed_app.json_fdo_only +new file mode 100644 +index 0000000..ffa5cb8 +--- /dev/null ++++ b/mbedos/components/fdo/fdo/mbed_app.json_fdo_only +@@ -0,0 +1,27 @@ ++{ ++ "config": { ++ "main-stack-size": { ++ "value": 16000 ++ } ++ }, ++ "target_overrides": { ++ "*": { ++ "platform.stdio-baud-rate": 115200, ++ "platform.stdio-convert-newlines": true, ++ "target.network-default-interface-type": "ETHERNET", ++ "target.features_add": ["STORAGE"], ++ "target.components_add": ["SD"] ++ } ++ }, ++ "macros": [ ++ "NDEBUG=1", ++ "MBEDTLS_PEM_WRITE_C", ++ "MBEDTLS_X509_CREATE_C", ++ "MBEDTLS_X509_CSR_PARSE_C", ++ "MBEDTLS_X509_CSR_WRITE_C", ++ "MBEDTLS_ENTROPY_HARDWARE_ALT", ++ "DEVICE_TRNG=1", ++ "MBEDTLS_DHM_C=1", ++ "MBEDTLS_USER_CONFIG_FILE=\"mbedtls_user_config.h\"" ++ ] ++} +diff --git a/mbedos/components/fdo/fdo/mbedtls_user_config.h b/mbedos/components/fdo/fdo/mbedtls_user_config.h +new file mode 100644 +index 0000000..abcd740 +--- /dev/null ++++ b/mbedos/components/fdo/fdo/mbedtls_user_config.h +@@ -0,0 +1,30 @@ ++/* ++ * Copyright (C) 2006-2019, Arm Limited, All Rights Reserved ++ * SPDX-License-Identifier: Apache-2.0 ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); you may ++ * not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License 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. ++ * ++ * This file is part of Mbed TLS (https://tls.mbed.org) ++ */ ++ ++/* Enable PSA APIs, which this example depends on. */ ++#if !defined(MBEDTLS_PSA_CRYPTO_C) ++#define MBEDTLS_PSA_CRYPTO_C ++#endif ++ ++/* Enable the default implementation of the PSA entropy injection API if we are ++ * building for an SPE. */ ++#if defined(COMPONENT_PSA_SRV_IMPL) || defined(COMPONENT_PSA_SRV_EMUL) ++#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbed_default_seed_read ++#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbed_default_seed_write ++#endif +diff --git a/mbedos/components/fdo/mbed-os.lib b/mbedos/components/fdo/mbed-os.lib +new file mode 100644 +index 0000000..660582d +--- /dev/null ++++ b/mbedos/components/fdo/mbed-os.lib +@@ -0,0 +1 @@ ++https://github.com/ARMmbed/mbed-os/#679d24833acf0a0b5b0d528576bb37c70863bc4e +diff --git a/mbedos/components/fdo/mbed_settings.py b/mbedos/components/fdo/mbed_settings.py +new file mode 100644 +index 0000000..494f60d +--- /dev/null ++++ b/mbedos/components/fdo/mbed_settings.py +@@ -0,0 +1,45 @@ ++""" ++mbed SDK ++Copyright (c) 2016 ARM Limited ++ ++Licensed under the Apache License, Version 2.0 (the "License"); ++you may not use this file except in compliance with the License. ++You may obtain a copy of the License at ++ ++http://www.apache.org/licenses/LICENSE-2.0 ++ ++Unless required by applicable law or agreed to in writing, software ++distributed under the License 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. ++""" ++ ++from os.path import join, abspath, dirname ++ ++#ROOT = abspath(join(dirname(__file__), ".")) ++ ++############################################################################## ++# Build System Settings ++############################################################################## ++#BUILD_DIR = abspath(join(ROOT, "build")) ++ ++# ARM ++#ARM_PATH = "C:/Program Files/ARM" ++ ++# GCC ARM ++#GCC_ARM_PATH = "" ++ ++# IAR ++#IAR_PATH = "C:/Program Files (x86)/IAR Systems/Embedded Workbench 7.0/arm" ++ ++# Goanna static analyser. Please overload it in private_settings.py ++#GOANNA_PATH = "c:/Program Files (x86)/RedLizards/Goanna Central 3.2.3/bin" ++ ++#BUILD_OPTIONS = [] ++ ++# mbed.org username ++#MBED_ORG_USER = "" ++ ++# Print compiler warnings and errors as link format ++#PRINT_COMPILER_OUTPUT_AS_LINK = False +diff --git a/network/include/network_al.h b/network/include/network_al.h +index b5b83be..d71a2a2 100644 +--- a/network/include/network_al.h ++++ b/network/include/network_al.h +@@ -95,13 +95,13 @@ bool get_msg_length(char *curl_buf, size_t *cur_offset, uint32_t *msglen); + /* + * Receive(read) length of incoming FDO packet. + * +- * @param[out] protocol_version: FDO protocol version ++ * @param[out] prot_version: FDO protocol version + * @param[out] message_type: message type of incoming FDO message. + * @param[out] msglen: length of incoming message. + * @param[in] hdr_buf: data buffer to parse msg received by curl. + * @retval -1 on failure, 0 on success. + */ +-int32_t fdo_con_parse_msg_header(uint32_t *protocol_version, ++int32_t fdo_con_parse_msg_header(uint32_t *prot_version, + uint32_t *message_type, uint32_t *msglen, + char *hdr_buf); + +@@ -118,19 +118,22 @@ int32_t fdo_con_parse_msg_body(uint8_t *buf, size_t length, char *body_buf); + /* + * Send(write) and receive(read) data. + * +- * @param[in] protocol_version: FDO protocol version ++ * @param[in] prot_version: FDO protocol version + * @param[in] message_type: message type of outgoing FDO message. + * @param[in] buf: data buffer to write from. + * @param[in] length: Number of sent bytes. + * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is + * @param[in] header_buf: header data buffer to read into msg received by curl. ++ * @param[in] header_buf_sz: capacity of header_buf, in bytes. + * @param[in] body_buf: body data buffer to read into msg received by curl. ++ * @param[in] body_buf_sz: capacity of body_buf, in bytes. + * @retval -1 on failure, 0 on success. + */ +-int32_t fdo_con_send_recv_message(uint32_t protocol_version, ++int32_t fdo_con_send_recv_message(uint32_t prot_version, + uint32_t message_type, const uint8_t *buf, + size_t length, bool tls, char *header_buf, +- char *body_buf); ++ size_t header_buf_sz, char *body_buf, ++ size_t body_buf_sz); + + /* + * Network Connection tear down. +diff --git a/network/include/rest_interface.h b/network/include/rest_interface.h +index bbaa00c..c80afe1 100644 +--- a/network/include/rest_interface.h ++++ b/network/include/rest_interface.h +@@ -48,6 +48,12 @@ typedef struct Rest_ctx_s { + struct MemoryStruct { + char *memory; + size_t size; ++ /* ++ * Upper bound on "size", including the trailing NUL. The response is ++ * ultimately copied into a fixed-size caller buffer, so growth has to ++ * be bounded here by that buffer's capacity. ++ */ ++ size_t capacity; + }; + + extern CURL *curl; +diff --git a/network/network_if_linux.c b/network/network_if_linux.c +index 1d2f858..2fa7c1a 100644 +--- a/network/network_if_linux.c ++++ b/network/network_if_linux.c +@@ -13,6 +13,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -30,9 +31,10 @@ + + // Function used by libcurl to allocate memory to data received from the HTTP + // response +-static void init_string(struct MemoryStruct *s) ++static void init_string(struct MemoryStruct *s, size_t capacity) + { + s->size = 0; ++ s->capacity = capacity; + s->memory = malloc(s->size + 1); + if (s->memory == NULL) { + LOG(LOG_ERROR, "malloc() failed\n"); +@@ -45,8 +47,26 @@ static void init_string(struct MemoryStruct *s) + static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, + void *userp) + { +- size_t realsize = size * nmemb; + struct MemoryStruct *mem = (struct MemoryStruct *)userp; ++ size_t realsize; ++ ++ if (size && nmemb > SIZE_MAX / size) { ++ LOG(LOG_ERROR, "error: response chunk size overflow\n"); ++ return 0; ++ } ++ realsize = size * nmemb; ++ ++ /* ++ * Returning short aborts the transfer with CURLE_WRITE_ERROR, which ++ * curl_easy_perform() reports to the caller. Refusing here rather than ++ * truncating keeps the copy into the caller's fixed buffer safe. ++ */ ++ if (realsize >= mem->capacity - mem->size) { ++ LOG(LOG_ERROR, ++ "error: response exceeds the %zu byte buffer capacity\n", ++ mem->capacity); ++ return 0; ++ } + + char *ptr = (char *)realloc(mem->memory, mem->size + realsize + 1); + if (ptr == NULL) { +@@ -574,7 +594,7 @@ int32_t fdo_con_connect(fdo_ip_address_t *ip_addr, const char *dn, + } + #endif + +-#if defined(USE_OPENSSL) ++#if defined(USE_OPENSSL) || defined(USE_WOLFSSL) + connect_ok = fdo_curl_connect(ip_addr, dn, port, tls); + if (connect_ok < 0) { + goto end; +@@ -712,13 +732,13 @@ err: + /** + * Receive(read) protocol version, message type and length of rest body + * +- * @param protocol_version - out FDO protocol version ++ * @param prot_version - out FDO protocol version + * @param message_type - out message type of incoming FDO message. + * @param msglen - out Number of received bytes. + * @param hdr_buf: header data buffer to parse msg received by curl. + * @retval -1 on failure, 0 on success. + */ +-int32_t fdo_con_parse_msg_header(uint32_t *protocol_version, ++int32_t fdo_con_parse_msg_header(uint32_t *prot_version, + uint32_t *message_type, uint32_t *msglen, + char *hdr_buf) + { +@@ -730,7 +750,7 @@ int32_t fdo_con_parse_msg_header(uint32_t *protocol_version, + size_t tmplen; + size_t hdrlen; + +- if (!protocol_version || !message_type || !msglen || !hdr_buf) { ++ if (!prot_version || !message_type || !msglen || !hdr_buf) { + goto err; + } + +@@ -790,7 +810,7 @@ int32_t fdo_con_parse_msg_header(uint32_t *protocol_version, + } + + // copy protver from REST context +- *protocol_version = rest->prot_ver; ++ *prot_version = rest->prot_ver; + *message_type = rest->msg_type; + + ret = 0; +@@ -827,19 +847,22 @@ err: + + /** + * Send and Receive data. +- * @param[in] protocol_version: FDO protocol version ++ * @param[in] prot_version: FDO protocol version + * @param[in] message_type: message type of outgoing FDO message. + * @param[in] buf: data buffer to write from. + * @param[in] length: Number of sent bytes. + * @param[in] tls: flag describing whether HTTP (false) or HTTPS (true) is + * @param[in] header_buf: header data buffer to read into msg received by curl. ++ * @param[in] header_buf_sz: capacity of header_buf, in bytes. + * @param[in] body_buf: body data buffer to read into msg received by curl. ++ * @param[in] body_buf_sz: capacity of body_buf, in bytes. + * @retval -1 on failure, 0 on success. + */ +-int32_t fdo_con_send_recv_message(uint32_t protocol_version, ++int32_t fdo_con_send_recv_message(uint32_t prot_version, + uint32_t message_type, const uint8_t *buf, + size_t length, bool tls, char *header_buf, +- char *body_buf) ++ size_t header_buf_sz, char *body_buf, ++ size_t body_buf_sz) + { + int ret = -1; + rest_ctx_t *rest = NULL; +@@ -849,8 +872,13 @@ int32_t fdo_con_send_recv_message(uint32_t protocol_version, + struct MemoryStruct temp_header_buf; + struct MemoryStruct temp_body_buf; + +- init_string(&temp_header_buf); +- init_string(&temp_body_buf); ++ if (!header_buf || !header_buf_sz || !body_buf || !body_buf_sz) { ++ LOG(LOG_ERROR, "Invalid response buffer supplied!\n"); ++ return -1; ++ } ++ ++ init_string(&temp_header_buf, header_buf_sz); ++ init_string(&temp_body_buf, body_buf_sz); + + if (!buf || !length) { + goto err; +@@ -863,7 +891,7 @@ int32_t fdo_con_send_recv_message(uint32_t protocol_version, + } + + // supply info to REST for POST-URL construction +- rest->prot_ver = protocol_version; ++ rest->prot_ver = prot_version; + rest->msg_type = message_type; + rest->content_length = length; + if (tls) { +@@ -997,7 +1025,21 @@ int32_t fdo_con_send_recv_message(uint32_t protocol_version, + goto err; + } + +- if (memcpy_s(header_buf, temp_header_buf.size, temp_header_buf.memory, ++ /* ++ * The destination is a fixed-size buffer owned by the caller, so its ++ * capacity -- not the length of the response -- has to bound the copy. ++ * WriteMemoryCallback() already refuses to accumulate this much, so ++ * reaching either check means the two limits have drifted apart. ++ */ ++ if (temp_header_buf.size >= header_buf_sz) { ++ LOG(LOG_ERROR, ++ "Response header of %zu bytes exceeds the %zu byte " ++ "buffer\n", ++ temp_header_buf.size, header_buf_sz); ++ goto err; ++ } ++ ++ if (memcpy_s(header_buf, header_buf_sz, temp_header_buf.memory, + temp_header_buf.size)) { + LOG(LOG_ERROR, "Failed to copy msg data in byte array\n"); + goto err; +@@ -1005,7 +1047,15 @@ int32_t fdo_con_send_recv_message(uint32_t protocol_version, + + if ((message_type >= FDO_DI_APP_START) && + (message_type < FDO_TYPE_ERROR)) { +- if (memcpy_s(body_buf, temp_body_buf.size, temp_body_buf.memory, ++ if (temp_body_buf.size >= body_buf_sz) { ++ LOG(LOG_ERROR, ++ "Response body of %zu bytes exceeds the %zu byte " ++ "buffer\n", ++ temp_body_buf.size, body_buf_sz); ++ goto err; ++ } ++ ++ if (memcpy_s(body_buf, body_buf_sz, temp_body_buf.memory, + temp_body_buf.size)) { + LOG(LOG_ERROR, + "Failed to copy msg data in byte array\n"); +diff --git a/storage/CMakeLists.txt b/storage/CMakeLists.txt +index 94fab87..f8b9703 100644 +--- a/storage/CMakeLists.txt ++++ b/storage/CMakeLists.txt +@@ -17,9 +17,15 @@ client_sdk_sources_with_lib( storage + ) + + if (${DA} MATCHES tpm) +- client_sdk_sources_with_lib( storage +- linux/tpm2_nv_storage.c +- ) ++ if(${TPM_STACK} STREQUAL wolftpm) ++ client_sdk_sources_with_lib( storage ++ linux/wolftpm_nv_storage.c ++ ) ++ else() ++ client_sdk_sources_with_lib( storage ++ linux/tpm2_nv_storage.c ++ ) ++ endif() + endif() + + target_link_libraries(storage PUBLIC client_sdk_interface) +diff --git a/storage/include/fdo_tpm_handles.h b/storage/include/fdo_tpm_handles.h +new file mode 100644 +index 0000000..f7cf93a +--- /dev/null ++++ b/storage/include/fdo_tpm_handles.h +@@ -0,0 +1,52 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/* ++ * TPM NV index / persistent-object handles and entry points. ++ * Uses plain uint32_t to avoid TPM stack dependencies. ++ */ ++ ++#ifndef __FDO_TPM_HANDLES_H__ ++#define __FDO_TPM_HANDLES_H__ ++ ++#include ++#include ++ ++#define FDO_DCActive_NV_IDX 0x01D10000 ++#define FDO_CRED_NV_IDX 0x01D10001 ++#define TPM_DEVICE_KEY_PERSISTANT_HANDLE 0x81020002 ++#define TPM_HMAC_KEY_PERSISTANT_HANDLE 0x81020003 ++#define TPM_DEVICE_CSR_NV_IDX 0x01D10005 ++ ++#ifdef __cplusplus ++extern "C" { ++#endif ++ ++int32_t fdo_tpm_get_hmac(const uint8_t *data, size_t data_length, uint8_t *hmac, ++ size_t hmac_length, uint32_t persistent_handle); ++int32_t fdo_tpm_generate_hmac_key(uint32_t persistent_handle); ++ ++int fdo_tpm_nvdefine(uint32_t nv, size_t data_size); ++int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, uint32_t nv); ++int fdo_tpm_nvwrite_lock(uint32_t nv); ++ ++/* ++ * Size in bytes of the data stored at NV index nv. ++ * ++ * Returns 0 if the index is undefined or could not be read. Callers cannot ++ * distinguish those cases and must treat 0 as "no usable data". Every backend ++ * must agree on this: the return type is size_t, so a -1 sentinel becomes ++ * SIZE_MAX and flows into allocation sizes rather than being caught. ++ */ ++size_t fdo_tpm_nvread_size(uint32_t nv); ++int fdo_tpm_nvread(uint32_t nv, size_t data_size, uint8_t **data); ++int fdo_tpm_nvread_lock(uint32_t nv); ++int fdo_tpm_nvdel(uint32_t nv); ++ ++#ifdef __cplusplus ++} ++#endif ++ ++#endif /* __FDO_TPM_HANDLES_H__ */ +diff --git a/storage/include/storage_al.h b/storage/include/storage_al.h +index f6c7e69..f71cd3f 100644 +--- a/storage/include/storage_al.h ++++ b/storage/include/storage_al.h +@@ -18,7 +18,7 @@ + #include + #include + #if defined(DEVICE_TPM20_ENABLED) +-#include "tpm2_nv_storage.h" ++#include "fdo_tpm_handles.h" + #endif + + // platform HMAC and blob size +@@ -50,12 +50,12 @@ size_t fdo_blob_size(const char *blob_name, fdo_sdk_blob_flags flags); + int32_t create_hmac_normal_blob(void); + + #if defined(DEVICE_TPM20_ENABLED) +-int32_t fdo_tpm_read_nv(TPMI_RH_NV_INDEX nv, uint8_t *buffer, uint32_t length); ++int32_t fdo_tpm_read_nv(uint32_t nv, uint8_t *buffer, uint32_t length); + +-int32_t fdo_tpm_write_nv(TPMI_RH_NV_INDEX nv, const uint8_t *buffer, ++int32_t fdo_tpm_write_nv(uint32_t nv, const uint8_t *buffer, + uint32_t length); + +-size_t fdo_tpm_size_nv(TPMI_RH_NV_INDEX nv); ++size_t fdo_tpm_size_nv(uint32_t nv); + #endif + #ifdef __cplusplus + } // endof externc (CPP code) +diff --git a/storage/include/tpm2_nv_storage.h b/storage/include/tpm2_nv_storage.h +index 2a833b2..53d06c9 100644 +--- a/storage/include/tpm2_nv_storage.h ++++ b/storage/include/tpm2_nv_storage.h +@@ -5,81 +5,12 @@ + #include + #include + +-#define FDO_DCActive_NV_IDX 0x01D10000 +-#define FDO_CRED_NV_IDX 0x01D10001 +-#define TPM_DEVICE_KEY_PERSISTANT_HANDLE 0x81020002 +-#define TPM_HMAC_KEY_PERSISTANT_HANDLE 0x81020003 +-#define TPM_DEVICE_CSR_NV_IDX 0x01D10005 ++/* NV index / persistent handle values and fdo_tpm_nv* prototypes, shared ++ * with the wolfTPM backend. */ ++#include "fdo_tpm_handles.h" + + #if defined(ECDSA256_DA) + #define FDO_TPM2_ALG_SHA TPM2_ALG_SHA256 + #else + #define FDO_TPM2_ALG_SHA TPM2_ALG_SHA384 +-#endif +- +-/** Define space at NV index. +- * +- * @param[in] nv NV index to delete. +- * @retval 0 on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-int fdo_tpm_nvdefine(TPMI_RH_NV_INDEX nv, size_t data_size); +- +-/** Store a data in a NV index. +- * +- * @param[in] data Key to store to NVRAM. +- * @param[in] data_size Size of the data. +- * @param[in] nv NV index to store the data. +- * @retval 0 on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, TPMI_RH_NV_INDEX nv); +- +-/** Lock the NV index for further writes. +- * +- * @param[in] nv NV index to store the data. +- * @retval 0 on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-int fdo_tpm_nvwrite_lock(TPMI_RH_NV_INDEX nv); +- +-/** Load data size from a NV index. +- * +- * @param[in] nv NV index of the data. +- * @retval data size on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-size_t fdo_tpm_nvread_size(TPMI_RH_NV_INDEX nv); +- +-/** Load a data from a NV index. +- * +- * @param[in] nv NV index of the data. +- * @param[out] data Loaded data. +- * @param[out] data_size Size of the data. +- * @retval 0 on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-int fdo_tpm_nvread(TPMI_RH_NV_INDEX nv, size_t data_size, uint8_t **data); +- +-/** Lock the NV index for further reads. +- * +- * @param[in] nv NV index to store the data. +- * @retval 0 on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-int fdo_tpm_nvread_lock(TPMI_RH_NV_INDEX nv); +- +-/** Delete data from a NV index. +- * +- * @param[in] nv NV index to delete. +- * @retval 0 on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. +- */ +-int fdo_tpm_nvdel(TPMI_RH_NV_INDEX nv); +\ No newline at end of file ++#endif +\ No newline at end of file +diff --git a/storage/linux/storage_if_linux.c b/storage/linux/storage_if_linux.c +index 1aaa299..19b4d4c 100644 +--- a/storage/linux/storage_if_linux.c ++++ b/storage/linux/storage_if_linux.c +@@ -20,9 +20,6 @@ + #include "fdo_crypto.h" + #include "crypto_utils.h" + #include "platform_utils.h" +-#if defined(DEVICE_TPM20_ENABLED) +-#include "tpm20_Utils.h" +-#endif + + /**************************************************** + * +@@ -573,7 +570,7 @@ exit: + * @return file size on success, 0 if file does not exist or on other failure + */ + +-size_t fdo_tpm_size_nv(TPMI_RH_NV_INDEX nv) ++size_t fdo_tpm_size_nv(uint32_t nv) + { + size_t retval = 0; + const size_t NORMAL_NV_OVERHEAD = +@@ -623,7 +620,7 @@ end: + * @param n_bytes - length of data(in bytes) to be read + * @return num of bytes read if success, -1 on error + */ +-int32_t fdo_tpm_read_nv(TPMI_RH_NV_INDEX nv, uint8_t *buf, uint32_t n_bytes) ++int32_t fdo_tpm_read_nv(uint32_t nv, uint8_t *buf, uint32_t n_bytes) + { + int retval = -1; + uint8_t *data = NULL; +@@ -750,7 +747,7 @@ exit: + * @return num of bytes write if success, -1 on error + */ + +-int32_t fdo_tpm_write_nv(TPMI_RH_NV_INDEX nv, const uint8_t *buf, ++int32_t fdo_tpm_write_nv(uint32_t nv, const uint8_t *buf, + uint32_t n_bytes) + { + int retval = -1; +@@ -839,4 +836,4 @@ exit: + } + return retval; + } +-#endif +\ No newline at end of file ++#endif +diff --git a/storage/linux/tpm2_nv_storage.c b/storage/linux/tpm2_nv_storage.c +index 9e67dca..6ce65f4 100644 +--- a/storage/linux/tpm2_nv_storage.c ++++ b/storage/linux/tpm2_nv_storage.c +@@ -16,6 +16,20 @@ static int32_t fdo_tpm_esys_context_init(ESYS_CONTEXT **esys_context) + int ret = -1; + TSS2_TCTI_CONTEXT *tcti_context = NULL; + ++ if (!esys_context) { ++ return ret; ++ } ++ ++ /* Define the out-param before anything can fail. Callers test `ctx` in ++ * their err: cleanup path, and on the failure paths below we never ++ * reach Esys_Initialize(), which is what would otherwise assign it. A ++ * caller whose `ctx` still held indeterminate stack contents would pass ++ * its `if (ctx && ...)` guard and hand the garbage pointer to ++ * fdo_tpm_context_clean_up(), segfaulting instead of reporting the ++ * error -- e.g. when TPM2_TCTI_TYPE names a TCTI that is not running. ++ */ ++ *esys_context = NULL; ++ + if ((TSS2_RC_SUCCESS != + Tss2_TctiLdr_Initialize(TPM2_TCTI_TYPE, &tcti_context)) || + (!tcti_context)) { +@@ -166,7 +180,7 @@ int fdo_tpm_nvdefine(TPMI_RH_NV_INDEX nv, size_t data_size) + + int ret = -1; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_AUTH emptyAuth = { +@@ -220,6 +234,8 @@ int fdo_tpm_nvdefine(TPMI_RH_NV_INDEX nv, size_t data_size) + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); ++ Esys_Free(capability_data); ++ capability_data = NULL; + if (exists == 1) { + LOG(LOG_DEBUG, "NV index already exist.\n"); + ret = 0; +@@ -264,7 +280,7 @@ int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, TPMI_RH_NV_INDEX nv) + + int ret = -1; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_AUTH emptyAuth = { +@@ -329,6 +345,8 @@ int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, TPMI_RH_NV_INDEX nv) + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); ++ Esys_Free(capability_data); ++ capability_data = NULL; + if (exists == 1) { + LOG(LOG_DEBUG, "NV index already exist. Deleting it.\n"); + rc = Esys_TR_FromTPMPublic(ctx, nv, auth_session_handle, +@@ -390,7 +408,7 @@ int fdo_tpm_nvwrite_lock(TPMI_RH_NV_INDEX nv) + + int ret = -1; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + +@@ -442,21 +460,25 @@ err: + * + * @param[in] nv NV index of the data. + * @retval data size on success. +- * @retval -1 on undefined/general failure. +- * @retval TSS2_RC response code for failures relayed from the TSS library. ++ * @retval 0 if the index is undefined or could not be read. ++ * ++ * Failures return 0 rather than -1: the return type is size_t, so -1 would ++ * reach callers as SIZE_MAX and be used as an allocation size. See the ++ * contract on fdo_tpm_nvread_size() in storage/include/fdo_tpm_handles.h, ++ * which the wolfTPM backend implements identically. + */ + size_t fdo_tpm_nvread_size(TPMI_RH_NV_INDEX nv) + { +- int ret = -1; ++ size_t ret = 0; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_NV_PUBLIC *publicInfo = NULL; + size_t data_size; + + if (!nv) { +- return -1; ++ return 0; + } + + rc = fdo_tpm_esys_context_init(&ctx); +@@ -489,6 +511,8 @@ size_t fdo_tpm_nvread_size(TPMI_RH_NV_INDEX nv) + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); ++ Esys_Free(capability_data); ++ capability_data = NULL; + if (exists != 1) { + LOG(LOG_DEBUG, "NV index doesn't exist.\n"); + ret = 0; +@@ -522,7 +546,7 @@ err: + if (ctx && (0 != fdo_tpm_context_clean_up(&ctx, &auth_session_handle, + &nvHandle))) { + LOG(LOG_ERROR, "Failed to tear down all the TSS context.\n"); +- ret = -1; ++ ret = 0; + } + return ret; + } +@@ -540,7 +564,7 @@ int fdo_tpm_nvread(TPMI_RH_NV_INDEX nv, size_t data_size, uint8_t **data) + { + int ret = -1; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + TPM2B_MAX_NV_BUFFER *blob; +@@ -614,7 +638,7 @@ int fdo_tpm_nvread_lock(TPMI_RH_NV_INDEX nv) + + int ret = -1; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + +@@ -673,7 +697,7 @@ int fdo_tpm_nvdel(TPMI_RH_NV_INDEX nv) + { + int ret = -1; + TSS2_RC rc; +- ESYS_CONTEXT *ctx; ++ ESYS_CONTEXT *ctx = NULL; + ESYS_TR nvHandle = ESYS_TR_NONE; + ESYS_TR auth_session_handle = ESYS_TR_NONE; + +@@ -711,6 +735,8 @@ int fdo_tpm_nvdel(TPMI_RH_NV_INDEX nv) + + int exists = (capability_data->data.handles.count > 0 && + capability_data->data.handles.handle[0] == nv); ++ Esys_Free(capability_data); ++ capability_data = NULL; + if (exists != 1) { + LOG(LOG_DEBUG, "NV index doesn't exist.\n"); + ret = 0; +diff --git a/storage/linux/wolftpm_nv_storage.c b/storage/linux/wolftpm_nv_storage.c +new file mode 100644 +index 0000000..eba4710 +--- /dev/null ++++ b/storage/linux/wolftpm_nv_storage.c +@@ -0,0 +1,358 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/* Backend-agnostic TPM NV storage routines using wolfTPM. */ ++ ++#include ++#include ++#include "safe_lib.h" ++#include "util.h" ++#include "fdo_tpm_handles.h" ++#include "wolftpm_utils.h" ++#include ++ ++/* Returns 1 if the NV index is already defined, 0 otherwise. */ ++static int nv_exists(WOLFTPM2_DEV *dev, word32 nvIndex, TPMS_NV_PUBLIC *pub) ++{ ++ TPMS_NV_PUBLIC local; ++ ++ if (!pub) { ++ pub = &local; ++ } ++ XMEMSET(pub, 0, sizeof(*pub)); ++ return (wolfTPM2_NVReadPublic(dev, nvIndex, pub) == TPM_RC_SUCCESS); ++} ++ ++/* Set NV attributes */ ++static int fdo_tpm_get_nv_attributes(word32 *nvAttributes) ++{ ++ int rc = wolfTPM2_GetNvAttributesTemplate(TPM_RH_OWNER, nvAttributes); ++ ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "wolfTPM2_GetNvAttributesTemplate failed: %d\n", rc); ++ return rc; ++ } ++ *nvAttributes |= TPMA_NV_OWNERWRITE | TPMA_NV_READ_STCLEAR | ++ TPMA_NV_WRITE_STCLEAR | TPMA_NV_WRITEDEFINE; ++ return TPM_RC_SUCCESS; ++} ++ ++int fdo_tpm_nvdefine(uint32_t nv, size_t data_size) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_HANDLE parent; ++ WOLFTPM2_NV nvObj; ++ word32 nvAttributes; ++ ++ if (!nv) { ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ if (nv_exists(&dev, (word32)nv, NULL)) { ++ /* Already provisioned. */ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++ } ++ ++ rc = fdo_tpm_get_nv_attributes(&nvAttributes); ++ if (rc != TPM_RC_SUCCESS) { ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ XMEMSET(&parent, 0, sizeof(parent)); ++ parent.hndl = TPM_RH_OWNER; ++ XMEMSET(&nvObj, 0, sizeof(nvObj)); ++ ++ rc = wolfTPM2_NVCreateAuth(&dev, &parent, &nvObj, (word32)nv, ++ nvAttributes, (word32)data_size, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVCreateAuth failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++} ++ ++int fdo_tpm_nvwrite(const uint8_t *data, size_t data_size, uint32_t nv) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_HANDLE parent; ++ WOLFTPM2_NV nvObj; ++ word32 nvAttributes; ++ TPMS_NV_PUBLIC nvPublic; ++ int exists; ++ ++ if (!data || !nv || data_size == 0) { ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ XMEMSET(&parent, 0, sizeof(parent)); ++ parent.hndl = TPM_RH_OWNER; ++ XMEMSET(&nvObj, 0, sizeof(nvObj)); ++ ++ exists = nv_exists(&dev, (word32)nv, &nvPublic); ++ ++ /* Avoid delete/recreate to save NV endurance if index matches size and unlocked. */ ++ if (exists && (size_t)nvPublic.dataSize == data_size && ++ !(nvPublic.attributes & TPMA_NV_WRITELOCKED)) { ++ rc = wolfTPM2_NVOpen(&dev, &nvObj, (word32)nv, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVOpen failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ } else { ++ if (exists) { ++ rc = wolfTPM2_NVDeleteAuth(&dev, &parent, (word32)nv); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, ++ "wolfTPM2_NVDeleteAuth failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ } ++ ++ rc = fdo_tpm_get_nv_attributes(&nvAttributes); ++ if (rc != TPM_RC_SUCCESS) { ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ rc = wolfTPM2_NVCreateAuth(&dev, &parent, &nvObj, (word32)nv, ++ nvAttributes, (word32)data_size, ++ NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVCreateAuth failed: %d\n", ++ rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ } ++ ++ rc = wolfTPM2_NVWriteAuth(&dev, &nvObj, (word32)nv, (byte *)data, ++ (word32)data_size, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVWriteAuth failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++} ++ ++int fdo_tpm_nvwrite_lock(uint32_t nv) ++{ ++#if defined(LOCK_TPM) ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_NV nvObj; ++ ++ if (!nv) { ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ XMEMSET(&nvObj, 0, sizeof(nvObj)); ++ rc = wolfTPM2_NVOpen(&dev, &nvObj, (word32)nv, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVOpen failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ rc = wolfTPM2_NVWriteLock(&dev, &nvObj); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVWriteLock failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++#else ++ (void)nv; ++ return 0; ++#endif ++} ++ ++size_t fdo_tpm_nvread_size(uint32_t nv) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ TPMS_NV_PUBLIC nvPublic; ++ size_t ret = 0; ++ ++ if (!nv) { ++ return 0; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return 0; ++ } ++ ++ if (nv_exists(&dev, (word32)nv, &nvPublic)) { ++ ret = (size_t)nvPublic.dataSize; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return ret; ++} ++ ++int fdo_tpm_nvread(uint32_t nv, size_t data_size, uint8_t **data) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_NV nvObj; ++ word32 readSz; ++ ++ if (!nv || !data || !*data || data_size == 0) { ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ XMEMSET(&nvObj, 0, sizeof(nvObj)); ++ if (data_size > UINT32_MAX) { ++ LOG(LOG_ERROR, "data_size exceeds UINT32_MAX\n"); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ readSz = (word32)data_size; ++ ++ /* nvObj is zeroed (name not loaded), so NVReadAuth opens nv itself. */ ++ rc = wolfTPM2_NVReadAuth(&dev, &nvObj, (word32)nv, *data, &readSz, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVReadAuth failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ if ((size_t)readSz != data_size) { ++ LOG(LOG_ERROR, "Incorrect NV data length read\n"); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++} ++ ++int fdo_tpm_nvread_lock(uint32_t nv) ++{ ++#if defined(LOCK_TPM) ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_NV nvObj; ++ NV_ReadLock_In in; ++ ++ if (!nv) { ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ XMEMSET(&nvObj, 0, sizeof(nvObj)); ++ rc = wolfTPM2_NVOpen(&dev, &nvObj, (word32)nv, NULL, 0); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVOpen failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ if (wolfTPM2_SetAuthHandleName(&dev, 0, &nvObj.handle) != 0 || ++ wolfTPM2_SetAuthHandleName(&dev, 1, &nvObj.handle) != 0) { ++ LOG(LOG_ERROR, "Setting NV index name failed\n"); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ XMEMSET(&in, 0, sizeof(in)); ++ in.authHandle = nvObj.handle.hndl; ++ in.nvIndex = (word32)nv; ++ ++ rc = TPM2_NV_ReadLock(&in); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "TPM2_NV_ReadLock failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++#else ++ (void)nv; ++ return 0; ++#endif ++} ++ ++int fdo_tpm_nvdel(uint32_t nv) ++{ ++ int rc; ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_HANDLE parent; ++ ++ if (!nv) { ++ return -1; ++ } ++ ++ rc = wolftpm_init_dev(&dev); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_Init failed: %d\n", rc); ++ return -1; ++ } ++ ++ if (!nv_exists(&dev, (word32)nv, NULL)) { ++ /* Nothing to delete. */ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++ } ++ ++ XMEMSET(&parent, 0, sizeof(parent)); ++ parent.hndl = TPM_RH_OWNER; ++ ++ rc = wolfTPM2_NVDeleteAuth(&dev, &parent, (word32)nv); ++ if (rc != TPM_RC_SUCCESS) { ++ LOG(LOG_ERROR, "wolfTPM2_NVDeleteAuth failed: %d\n", rc); ++ wolfTPM2_Cleanup(&dev); ++ return -1; ++ } ++ ++ wolfTPM2_Cleanup(&dev); ++ return 0; ++} +diff --git a/storage/util.c b/storage/util.c +index a26c526..e8a506d 100644 +--- a/storage/util.c ++++ b/storage/util.c +@@ -364,4 +364,4 @@ end: + } + return ret; + } +-#endif +\ No newline at end of file ++#endif +diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt +index 1bfa14e..302fa72 100644 +--- a/tests/unit/CMakeLists.txt ++++ b/tests/unit/CMakeLists.txt +@@ -30,7 +30,6 @@ set (UNIT_TEST_SOURCES + test_hal_os.c + test_fdotypes.c + test_fdonet.c +- test_credentials.c + test_cryptoSupport.c + test_bn_support.c + test_utils.c +@@ -40,8 +39,71 @@ set (UNIT_TEST_SOURCES + test_SSLRoutines.c + test_ECDSASignRoutines.c + test_fdoblockio.c ++ test_ECDH.c + ) + ++# test_credentials.c covers the normal/secure credential functions, which ++# only compile when neither DEVICE_CSE_ENABLED nor DEVICE_TPM20_ENABLED is ++# set. Build it only where those symbols exist. ++# TODO: no unit coverage for the TPM device-credential path ++# (write/read_tpm_device_credentials() in credentials_from_file.c) -- ++# add a test_credentials_tpm.c. ++if (NOT ${DA} MATCHES tpm AND NOT ${DA} MATCHES cse) ++ list(APPEND UNIT_TEST_SOURCES test_credentials.c) ++endif() ++ ++# wolfssl/wolfssl_DERRoutines.c is only compiled for the Secure Element ++# (CRYPTO_HW=true) hardware path; test it under the same condition. ++if (${TLS} MATCHES wolfssl AND ${CRYPTO_HW} MATCHES true) ++ list(APPEND UNIT_TEST_SOURCES test_DERRoutines.c) ++endif() ++ ++# crypto/tpm/wolftpm_{ECDSA_sign_routines,hmac}.c and ++# storage/linux/wolftpm_nv_storage.c are compiled for the wolfTPM Device ++# Attestation path; test them under the same condition their sources use. ++# That condition is TLS-independent (see crypto/CMakeLists.txt and ++# storage/CMakeLists.txt), because wolfTPM links against wolfCrypt on its own ++# -- TPM_STACK=wolftpm is supported with TLS=openssl too, and that config ++# already pulls in the wolfTPM headers and -lwolftpm. So this must not be ++# gated on TLS, or these three tests silently vanish from that build. ++if (${DA} MATCHES tpm AND ${TPM_STACK} STREQUAL wolftpm) ++ # test_crypto.h pulls in the wolfTPM headers for every test here, and they ++ # use usleep(), which glibc hides under -std=c99 without this. ++ add_definitions(-D_DEFAULT_SOURCE) ++ list(APPEND UNIT_TEST_SOURCES test_wolftpm_ECDSA_sign_routines.c) ++ set (test_wolftpm_ecdsa_sign_routines_flags ++ -D_DEFAULT_SOURCE ++ -Wl,-wrap,wolfTPM2_Init ++ -Wl,-wrap,wolfTPM2_HashStart -Wl,-wrap,wolfTPM2_HashUpdate ++ -Wl,-wrap,wolfTPM2_HashFinish ++ -Wl,-wrap,wolfTPM2_ReadPublicKey -Wl,-wrap,wolfTPM2_SignHashScheme ++ -Wl,-wrap,wolfTPM2_UnloadHandle ++ -Wl,-wrap,wolfTPM2_Cleanup) ++ ++ list(APPEND UNIT_TEST_SOURCES test_wolftpm_nv_storage.c) ++ set (test_wolftpm_nv_storage_flags ++ -D_DEFAULT_SOURCE ++ -Wl,-wrap,wolfTPM2_Init ++ -Wl,-wrap,wolfTPM2_NVReadPublic ++ -Wl,-wrap,wolfTPM2_GetNvAttributesTemplate ++ -Wl,-wrap,wolfTPM2_NVCreateAuth -Wl,-wrap,wolfTPM2_NVWriteAuth ++ -Wl,-wrap,wolfTPM2_NVReadAuth -Wl,-wrap,wolfTPM2_NVDeleteAuth ++ -Wl,-wrap,wolfTPM2_NVWriteLock -Wl,-wrap,wolfTPM2_NVOpen ++ -Wl,-wrap,wolfTPM2_SetAuthHandleName -Wl,-wrap,TPM2_NV_ReadLock ++ -Wl,-wrap,wolfTPM2_Cleanup) ++ ++ list(APPEND UNIT_TEST_SOURCES test_wolftpm_hmac.c) ++ set (test_wolftpm_hmac_flags ++ -D_DEFAULT_SOURCE ++ -Wl,-wrap,wolfTPM2_Init ++ -Wl,-wrap,wolfTPM2_ReadPublicKey ++ -Wl,-wrap,wolfTPM2_HmacStart -Wl,-wrap,wolfTPM2_HmacUpdate ++ -Wl,-wrap,wolfTPM2_HmacFinish -Wl,-wrap,wolfTPM2_UnloadHandle ++ -Wl,-wrap,wolfTPM2_CreateSRK ++ -Wl,-wrap,wolfTPM2_CreateAndLoadKey -Wl,-wrap,wolfTPM2_NVStoreKey ++ -Wl,-wrap,wolfTPM2_NVDeleteKey -Wl,-wrap,wolfTPM2_Cleanup) ++endif() ++ + set (test_sample_flags -Wl,-wrap,fdo_read_string_sz) + + set (test_cryptosupport_flags -Wl,-wrap,crypto_init -Wl,-wrap,crypto_close +@@ -72,11 +134,20 @@ set (test_credentials_flags -Wl,-wrap,fdoDeviceCredentialRead + -Wl,-wrap,new_buffer_from_file + -Wl,-wrap,fdo_alloc) + +-set (test_sslroutines_flags -Wl,-wrap,TLS_method +- -Wl,-wrap,SSL_CTX_new -Wl,-wrap,SSL_new +- -Wl,-wrap,SSL_connect -Wl,-wrap,SSL_shutdown +- -Wl,-wrap,SSL_CTX_set_cipher_list +- -Wl,-wrap,SSL_read -Wl,-wrap,SSL_write -Wl,-wrap,SSL_free) ++if (${TLS} MATCHES wolfssl) ++ set (test_sslroutines_flags -Wl,-wrap,wolfSSLv23_client_method ++ -Wl,-wrap,wolfSSL_CTX_new -Wl,-wrap,wolfSSL_new ++ -Wl,-wrap,wolfSSL_connect -Wl,-wrap,wolfSSL_shutdown ++ -Wl,-wrap,wolfSSL_CTX_set_cipher_list ++ -Wl,-wrap,wolfSSL_CTX_load_verify_locations ++ -Wl,-wrap,wolfSSL_read -Wl,-wrap,wolfSSL_write -Wl,-wrap,wolfSSL_free) ++else() ++ set (test_sslroutines_flags -Wl,-wrap,TLS_method ++ -Wl,-wrap,SSL_CTX_new -Wl,-wrap,SSL_new ++ -Wl,-wrap,SSL_connect -Wl,-wrap,SSL_shutdown ++ -Wl,-wrap,SSL_CTX_set_cipher_list ++ -Wl,-wrap,SSL_read -Wl,-wrap,SSL_write -Wl,-wrap,SSL_free) ++endif() + + set (test_cryptoutils_flags -Wl,-wrap,malloc -Wl,-wrap,memset_s + -Wl,-wrap,memcpy_s -Wl,-wrap,crypto_hal_hmac +@@ -108,13 +179,77 @@ elseif (${TLS} MATCHES openssl) + set (test_bn_support_flags -Wl,-wrap,fdo_byte_array_alloc -Wl,-wrap,crypto_hal_random_bytes + -Wl,-wrap,BN_num_bits -Wl,-wrap,BN_bin2bn + -Wl,-wrap,BN_bn2bin -Wl,-wrap,BN_mod_exp -Wl,-wrap,BN_rand) ++elseif (${TLS} MATCHES wolfssl) ++ # Detect wolfSSL math type to set correct wrapper symbols (mp_* vs sp_*). ++ # See WOLFSSL_MP_IS_SP_ALIAS in test_bn_support.c. ++ # We check options.h first, then fallback to sp_int.h. ++ set (wolfssl_options_header "$ENV{WOLFSSL_ROOT}/include/wolfssl/options.h") ++ set (wolfssl_sp_int_header "$ENV{WOLFSSL_ROOT}/include/wolfssl/wolfcrypt/sp_int.h") ++ set (wolfssl_mp_is_sp_alias false) ++ set (wolfssl_sp_alias_detected false) ++ ++ if (EXISTS ${wolfssl_options_header}) ++ # options.h presence lets us confidently check if SP math is enabled. ++ set (wolfssl_sp_alias_detected true) ++ file(STRINGS ${wolfssl_options_header} wolfssl_sp_math_option ++ REGEX "^[ \t]*#[ \t]*define[ \t]+WOLFSSL_SP_MATH(_ALL)?([ \t]|$)") ++ if (wolfssl_sp_math_option) ++ set (wolfssl_mp_is_sp_alias true) ++ endif() ++ endif() ++ ++ if (NOT ${wolfssl_sp_alias_detected} AND EXISTS ${wolfssl_sp_int_header}) ++ set (wolfssl_sp_alias_detected true) ++ file(STRINGS ${wolfssl_sp_int_header} wolfssl_sp_math_check ++ REGEX "^[ \t]*#[ \t]*define[ \t]+mp_read_unsigned_bin[ \t]+sp_read_unsigned_bin") ++ if (wolfssl_sp_math_check) ++ set (wolfssl_mp_is_sp_alias true) ++ endif() ++ endif() ++ ++ if (NOT ${wolfssl_sp_alias_detected}) ++ message(FATAL_ERROR "Could not determine wolfSSL math symbol aliasing. " ++ "Please update SP-math detection for this wolfSSL version.") ++ endif() ++ ++ if (${wolfssl_mp_is_sp_alias}) ++ set (test_bn_support_flags -Wl,-wrap,fdo_byte_array_alloc -Wl,-wrap,crypto_hal_random_bytes ++ -Wl,-wrap,sp_read_unsigned_bin -Wl,-wrap,sp_to_unsigned_bin ++ -Wl,-wrap,sp_unsigned_bin_size -Wl,-wrap,sp_exptmod ++ -DWOLFSSL_MP_IS_SP_ALIAS) ++ else() ++ set (test_bn_support_flags -Wl,-wrap,fdo_byte_array_alloc -Wl,-wrap,crypto_hal_random_bytes ++ -Wl,-wrap,mp_read_unsigned_bin -Wl,-wrap,mp_to_unsigned_bin ++ -Wl,-wrap,mp_unsigned_bin_size -Wl,-wrap,mp_exptmod) ++ endif() + endif() + + ############### + #need to check the need for this. + +-foreach(unit_test ${UNIT_TEST_SOURCES}) ++# The test binaries append to one shared report log, which parse_output.rb ++# turns into the failure count the CI scripts exit on. Clear it as a build ++# step (not at configure time) so that re-running `make` without a fresh ++# `cmake` cannot double-count results from the previous run. Seeding ++# test_case_lists chains this ahead of the first test, since each test already ++# DEPENDS on the ones before it. ++set(report_log ${EXECUTABLE_OUTPUT_PATH}/report.log) ++add_custom_command( ++ OUTPUT reset_report_log ++ COMMAND ${CMAKE_COMMAND} -E remove -f ${report_log} ++ COMMENT "Resetting unit-test report log" ++ VERBATIM ++ ) ++set(test_case_lists reset_report_log) + ++# Optional regex limiting which test files are built and run, e.g. ++# -DUNIT_TEST_ONLY=^test_wolftpm_ in CI, where no real TPM is available. ++set(UNIT_TEST_ONLY "" CACHE STRING "Regex of unit-test sources to build and run (empty: all)") ++ ++foreach(unit_test ${UNIT_TEST_SOURCES}) ++ if (NOT "${UNIT_TEST_ONLY}" STREQUAL "" AND NOT unit_test MATCHES "${UNIT_TEST_ONLY}") ++ continue() ++ endif() + + STRING(REPLACE ".c" "" unit_test_match ${unit_test}) + STRING(TOLOWER ${unit_test_match} unit_test_lower) +@@ -127,6 +262,10 @@ foreach(unit_test ${UNIT_TEST_SOURCES}) + target_include_directories(${unit_test_exe}_lib PUBLIC + ${c_inc_lists} + unity/include ++ # The generated runner lives in EXECUTABLE_OUTPUT_PATH, not beside the ++ # test file, so test headers (test_crypto.h, ...) must be on the include ++ # path explicitly; the binary dir only covers in-source builds. ++ ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + ) + +@@ -141,10 +280,18 @@ foreach(unit_test ${UNIT_TEST_SOURCES}) + + set (unity_runner ${EXECUTABLE_OUTPUT_PATH}/${unit_test_exe}_runner.c) + # add_custom_target(unit_runner_target DEPENDS ${unity_runner}) ++ # Without DEPENDS the runner is generated once and then never refreshed, so a ++ # test function added to an existing file is silently left out of the run ++ # until someone clears build/. + add_custom_command( OUTPUT ${unity_runner} + COMMAND + ruby +- ${BASE_DIR}/tests/unit/unity/auto/generate_test_runner.rb ${unit_test} ${unity_runner} ++ ${BASE_DIR}/tests/unit/unity/auto/generate_test_runner.rb ++ ${CMAKE_CURRENT_SOURCE_DIR}/${unit_test} ${unity_runner} ++ DEPENDS ++ ${CMAKE_CURRENT_SOURCE_DIR}/${unit_test} ++ ${BASE_DIR}/tests/unit/unity/auto/generate_test_runner.rb ++ COMMENT "Generating Unity runner for ${unit_test_exe}" + ) + + +@@ -168,9 +315,10 @@ foreach(unit_test ${UNIT_TEST_SOURCES}) + set (execute_${unit_test_exe} ${unit_test_exe}.log) + add_custom_command( + OUTPUT ${execute_${unit_test_exe}} +- COMMAND +- # ${EXECUTABLE_OUTPUT_PATH}/${unit_test_exe} > ${EXECUTABLE_OUTPUT_PATH}/${execute_${unit_test_exe}} +- ${EXECUTABLE_OUTPUT_PATH}/${unit_test_exe} >> ${EXECUTABLE_OUTPUT_PATH}/report.log || exit 0 ++ COMMAND ${CMAKE_COMMAND} ++ -DTEST_EXE=${EXECUTABLE_OUTPUT_PATH}/${unit_test_exe} ++ -DREPORT_LOG=${report_log} ++ -P ${BASE_DIR}/tests/unit/run_unit_test.cmake + WORKING_DIRECTORY ${BASE_DIR}/ + DEPENDS ${unit_test_exe} ${test_case_lists} + COMMENT "Executing test file ${unit_test_exe}" +@@ -192,7 +340,7 @@ add_custom_target(test_case_exe ALL DEPENDS ${test_case_lists}) #working + add_custom_command( + OUTPUT unit_test_exe_report.xml + COMMAND +- ruby tests/unit/unity/auto/parse_output.rb -xml ${EXECUTABLE_OUTPUT_PATH}/report.log ++ ruby tests/unit/unity/auto/parse_output.rb -xml ${report_log} + DEPENDS test_case_exe + WORKING_DIRECTORY ${BASE_DIR} + COMMENT "report generate" +diff --git a/tests/unit/run_unit_test.cmake b/tests/unit/run_unit_test.cmake +new file mode 100644 +index 0000000..4858df9 +--- /dev/null ++++ b/tests/unit/run_unit_test.cmake +@@ -0,0 +1,52 @@ ++# ++# Copyright 2026 wolfSSL Inc. ++# SPDX-License-Identifier: Apache-2.0 ++# ++# Runs a single unit-test binary as a build step. ++# ++# This exists instead of a plain shell redirect in add_custom_command because ++# that command uses VERBATIM, which escapes shell metacharacters -- ">>" and ++# "||" would be handed to the test binary as argv rather than interpreted, ++# leaving report.log empty and the failure count silently zero. ++# ++# A non-zero exit status is Unity's failure count and is deliberately *not* ++# fatal here: every test must still get a chance to run so that report.log is ++# complete. The aggregate is enforced by the caller (build.sh and ++# .github/build_wolfssl_ci.sh) from the parsed report. Abnormal termination is ++# fatal, though, because a crashed binary writes no Unity summary and would ++# otherwise leave nothing for the parser to count. So is a binary that exits ++# (e.g. via exit()) without printing Unity's summary line, for the same reason. ++ ++if(NOT DEFINED TEST_EXE OR NOT DEFINED REPORT_LOG) ++ message(FATAL_ERROR "run_unit_test.cmake requires -DTEST_EXE and -DREPORT_LOG") ++endif() ++ ++execute_process( ++ COMMAND "${TEST_EXE}" ++ OUTPUT_VARIABLE test_stdout ++ ERROR_VARIABLE test_stderr ++ RESULT_VARIABLE test_result ++ ) ++ ++file(APPEND "${REPORT_LOG}" "${test_stdout}${test_stderr}") ++ ++message("${test_stdout}") ++if(NOT "${test_stderr}" STREQUAL "") ++ message("${test_stderr}") ++endif() ++ ++if(NOT "${test_result}" MATCHES "^[0-9]+$") ++ message(FATAL_ERROR ++ "${TEST_EXE} terminated abnormally (${test_result}); no Unity summary was " ++ "written, so its failures cannot be counted.") ++endif() ++ ++if(NOT "${test_stdout}" MATCHES "[0-9]+ Tests [0-9]+ Failures [0-9]+ Ignored") ++ message(FATAL_ERROR ++ "${TEST_EXE} exited (status ${test_result}) without a Unity summary, so its " ++ "failures cannot be counted.") ++endif() ++ ++if(NOT "${test_result}" STREQUAL "0") ++ message("${TEST_EXE}: ${test_result} failing test(s); see ${REPORT_LOG}") ++endif() +diff --git a/tests/unit/test_AESRoutines.h b/tests/unit/test_AESRoutines.h +index e11f451..73d2d63 100644 +--- a/tests/unit/test_AESRoutines.h ++++ b/tests/unit/test_AESRoutines.h +@@ -30,4 +30,10 @@ + #define KEY_SIZE 2048 + #define EXPONENT 65537 + #endif ++ ++#ifdef USE_WOLFSSL ++#include ++#include ++#include ++#endif + #endif /* __TEST_AESROUTINES_H__ */ +diff --git a/tests/unit/test_DERRoutines.c b/tests/unit/test_DERRoutines.c +new file mode 100644 +index 0000000..4dd4f26 +--- /dev/null ++++ b/tests/unit/test_DERRoutines.c +@@ -0,0 +1,141 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/* Unit tests for the wolfSSL raw r||s <-> DER ECDSA conversion routines. */ ++ ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "unity.h" ++ ++#if defined(USE_WOLFSSL) ++ ++#include ++#include ++#include ++ ++/*** Unity Declarations. ***/ ++void set_up(void); ++void tear_down(void); ++void test_der_encode_decode_roundtrip(void); ++void test_der_encode_decode_roundtrip_p384(void); ++void test_der_decode_rejects_bad_lengths(void); ++void test_der_encode_rejects_bad_lengths(void); ++ ++void set_up(void) ++{ ++} ++ ++void tear_down(void) ++{ ++} ++ ++/* Round trip sign/decode/encode/decode */ ++static void der_encode_decode_roundtrip(int curve_size, size_t raw_len) ++{ ++ WC_RNG rng; ++ ecc_key key; ++ uint8_t hash[48] = {0x11, 0x22, 0x33, 0x44, 0x55}; ++ uint8_t der_pubkey[256] = {0}; ++ word32 der_pubkey_len = 0; ++ uint8_t der_sig[128] = {0}; ++ word32 der_sig_len = sizeof(der_sig); ++ uint8_t orig_r[48] = {0}, orig_s[48] = {0}; ++ word32 orig_r_len = sizeof(orig_r), orig_s_len = sizeof(orig_s); ++ uint8_t raw_key[96] = {0}; ++ uint8_t raw_sig[96] = {0}; ++ uint8_t reencoded_der_sig[128] = {0}; ++ size_t reencoded_der_sig_len = sizeof(reencoded_der_sig); ++ uint8_t decoded_r[48] = {0}, decoded_s[48] = {0}; ++ word32 decoded_r_len = sizeof(decoded_r), decoded_s_len = sizeof(decoded_s); ++ int ret; ++ ++ TEST_ASSERT_EQUAL(0, wc_InitRng(&rng)); ++ TEST_ASSERT_EQUAL(0, wc_ecc_init(&key)); ++ TEST_ASSERT_EQUAL(0, wc_ecc_make_key(&rng, curve_size, &key)); ++ ++ der_pubkey_len = (word32)sizeof(der_pubkey); ++ ret = wc_EccPublicKeyToDer(&key, der_pubkey, der_pubkey_len, 1); ++ TEST_ASSERT_TRUE(ret > 0); ++ der_pubkey_len = (word32)ret; ++ ++ TEST_ASSERT_EQUAL(0, wc_ecc_sign_hash(hash, (word32)curve_size, der_sig, ++ &der_sig_len, &rng, &key)); ++ ++ /* What wolfCrypt actually signed, for comparison after round trip. */ ++ TEST_ASSERT_EQUAL(0, wc_ecc_sig_to_rs(der_sig, der_sig_len, orig_r, ++ &orig_r_len, orig_s, &orig_s_len)); ++ ++ ret = crypto_hal_der_decode(raw_key, raw_sig, der_pubkey, der_pubkey_len, ++ der_sig, der_sig_len, raw_len, raw_len); ++ TEST_ASSERT_EQUAL(0, ret); ++ ++ ret = crypto_hal_der_encode(raw_sig, raw_len, reencoded_der_sig, ++ &reencoded_der_sig_len); ++ TEST_ASSERT_EQUAL(0, ret); ++ ++ TEST_ASSERT_EQUAL(0, wc_ecc_sig_to_rs(reencoded_der_sig, ++ (word32)reencoded_der_sig_len, ++ decoded_r, &decoded_r_len, ++ decoded_s, &decoded_s_len)); ++ ++ TEST_ASSERT_EQUAL(orig_r_len, decoded_r_len); ++ TEST_ASSERT_EQUAL(orig_s_len, decoded_s_len); ++ TEST_ASSERT_EQUAL_UINT8_ARRAY(orig_r, decoded_r, orig_r_len); ++ TEST_ASSERT_EQUAL_UINT8_ARRAY(orig_s, decoded_s, orig_s_len); ++ ++ wc_ecc_free(&key); ++ wc_FreeRng(&rng); ++} ++ ++void test_der_encode_decode_roundtrip(void) ++{ ++ der_encode_decode_roundtrip(32, BUFF_SIZE_64_BYTES); ++} ++ ++/* Same round trip, but for P-384. */ ++void test_der_encode_decode_roundtrip_p384(void) ++{ ++ der_encode_decode_roundtrip(48, BUFF_SIZE_96_BYTES); ++} ++ ++void test_der_decode_rejects_bad_lengths(void) ++{ ++ uint8_t raw_key[64] = {0}; ++ uint8_t raw_sig[64] = {0}; ++ uint8_t dummy_pubkey[16] = {0}; ++ uint8_t dummy_sig[16] = {0}; ++ ++ /* Neither BUFF_SIZE_64_BYTES nor BUFF_SIZE_96_BYTES. */ ++ TEST_ASSERT_EQUAL(-1, crypto_hal_der_decode( ++ raw_key, raw_sig, dummy_pubkey, sizeof(dummy_pubkey), ++ dummy_sig, sizeof(dummy_sig), 48, BUFF_SIZE_64_BYTES)); ++ ++ TEST_ASSERT_EQUAL(-1, crypto_hal_der_decode( ++ raw_key, raw_sig, dummy_pubkey, sizeof(dummy_pubkey), ++ dummy_sig, sizeof(dummy_sig), BUFF_SIZE_64_BYTES, 48)); ++ ++ TEST_ASSERT_EQUAL(-1, crypto_hal_der_decode( ++ NULL, raw_sig, dummy_pubkey, sizeof(dummy_pubkey), ++ dummy_sig, sizeof(dummy_sig), BUFF_SIZE_64_BYTES, ++ BUFF_SIZE_64_BYTES)); ++} ++ ++void test_der_encode_rejects_bad_lengths(void) ++{ ++ uint8_t raw_sig[64] = {0}; ++ uint8_t message_signature[128] = {0}; ++ size_t signature_length = sizeof(message_signature); ++ ++ /* Neither BUFF_SIZE_64_BYTES nor BUFF_SIZE_96_BYTES. */ ++ TEST_ASSERT_EQUAL(-1, crypto_hal_der_encode(raw_sig, 48, ++ message_signature, ++ &signature_length)); ++ ++ TEST_ASSERT_EQUAL(-1, crypto_hal_der_encode(NULL, sizeof(raw_sig), ++ message_signature, ++ &signature_length)); ++} ++ ++#endif /* USE_WOLFSSL */ +diff --git a/tests/unit/test_ECDH.c b/tests/unit/test_ECDH.c +new file mode 100644 +index 0000000..71f59cb +--- /dev/null ++++ b/tests/unit/test_ECDH.c +@@ -0,0 +1,440 @@ ++/* ++ * Copyright 2026 wolfSSL Inc. ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Unit tests for ECDH routines. ++ */ ++ ++#include "unity.h" ++#include "test_crypto.h" ++#include "fdo_crypto_hal.h" ++#include "util.h" ++#include "safe_lib.h" ++ ++#ifdef TARGET_OS_LINUX ++/*** Unity Declarations ***/ ++void set_up(void); ++void tear_down(void); ++void test_ecdh_key_exchange_round_trip(void); ++void test_ecdh_short_peer_coordinate(void); ++void test_ecdh_invalid_args(void); ++ ++/*** Unity functions. ***/ ++void set_up(void) ++{ ++} ++ ++void tear_down(void) ++{ ++} ++#endif ++ ++/** ++ * Test ECDH round trip by playing owner via wolfCrypt. ++ */ ++#ifdef USE_WOLFSSL ++#ifndef TARGET_OS_FREERTOS ++void test_ecdh_key_exchange_round_trip(void) ++#else ++TEST_CASE("ecdh_key_exchange_round_trip", "[ECDH][fdo]") ++#endif ++{ ++ void *device_ctx = NULL; ++ uint8_t *device_public = NULL; ++ uint32_t device_public_len = 0; ++ uint8_t *device_secret = NULL; ++ uint32_t device_secret_len = 0; ++ uint8_t *owner_response = NULL; ++ ecc_key owner_key; ++ ecc_key device_pub_key; ++ WC_RNG owner_rng; ++ int owner_key_inited = 0; ++ int device_pub_key_inited = 0; ++ int owner_rng_inited = 0; ++ ++ TEST_ASSERT_EQUAL(0, random_init()); ++ ++ TEST_ASSERT_EQUAL(0, crypto_hal_kex_init(&device_ctx)); ++ TEST_ASSERT_NOT_NULL(device_ctx); ++ ++ /* Fetch device public random. */ ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_device_random(device_ctx, NULL, ++ &device_public_len)); ++ TEST_ASSERT_TRUE(device_public_len > 4); ++ device_public = fdo_alloc(device_public_len); ++ TEST_ASSERT_NOT_NULL(device_public); ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_device_random( ++ device_ctx, device_public, &device_public_len)); ++ ++ /* Parse out the device's raw EC public point (X, Y). */ ++ uint32_t idx = 0; ++ uint32_t dev_x_len = (device_public[idx] << 8) | device_public[idx + 1]; ++ idx += 2; ++ uint8_t *dev_x = &device_public[idx]; ++ idx += dev_x_len; ++ uint32_t dev_y_len = (device_public[idx] << 8) | device_public[idx + 1]; ++ idx += 2; ++ uint8_t *dev_y = &device_public[idx]; ++ idx += dev_y_len; ++ /* Read the device's randlen field directly. */ ++ uint32_t dev_rand_len = (device_public[idx] << 8) | device_public[idx + 1]; ++ ++ /* Owner side: gen keypair and derive ECDH secret. */ ++ TEST_ASSERT_EQUAL(0, wc_ecc_init(&owner_key)); ++ owner_key_inited = 1; ++ TEST_ASSERT_EQUAL(0, wc_InitRng(&owner_rng)); ++ owner_rng_inited = 1; ++ TEST_ASSERT_EQUAL(0, wc_ecc_make_key(&owner_rng, (int)dev_x_len, &owner_key)); ++ TEST_ASSERT_EQUAL(0, wc_ecc_set_rng(&owner_key, &owner_rng)); ++ ++ TEST_ASSERT_EQUAL(0, wc_ecc_init(&device_pub_key)); ++ device_pub_key_inited = 1; ++ TEST_ASSERT_EQUAL(0, wc_ecc_import_unsigned(&device_pub_key, dev_x, dev_y, ++ NULL, owner_key.dp->id)); ++ ++ uint8_t reference_secret[BUFF_SIZE_512_BYTES] = {0}; ++ word32 reference_secret_len = sizeof(reference_secret); ++ TEST_ASSERT_EQUAL(0, wc_ecc_shared_secret(&owner_key, &device_pub_key, ++ reference_secret, ++ &reference_secret_len)); ++ ++ /* Build owner response. */ ++ uint8_t owner_x[BUFF_SIZE_64_BYTES] = {0}; ++ uint8_t owner_y[BUFF_SIZE_64_BYTES] = {0}; ++ word32 owner_x_len = sizeof(owner_x); ++ word32 owner_y_len = sizeof(owner_y); ++ TEST_ASSERT_EQUAL(0, wc_ecc_export_public_raw(&owner_key, owner_x, ++ &owner_x_len, owner_y, ++ &owner_y_len)); ++ ++ uint8_t owner_random[BUFF_SIZE_64_BYTES] = {0}; ++ uint32_t owner_random_len = dev_rand_len; ++ TEST_ASSERT_EQUAL(0, crypto_hal_random_bytes(owner_random, owner_random_len)); ++ ++ uint32_t owner_response_len = ++ 2 + owner_x_len + 2 + owner_y_len + 2 + owner_random_len; ++ owner_response = fdo_alloc(owner_response_len); ++ TEST_ASSERT_NOT_NULL(owner_response); ++ uint32_t off = 0; ++ owner_response[off] = (owner_x_len >> 8) & 0xFF; ++ owner_response[off + 1] = owner_x_len & 0xFF; ++ off += 2; ++ TEST_ASSERT_EQUAL(0, memcpy_s(&owner_response[off], owner_response_len - off, ++ owner_x, owner_x_len)); ++ off += owner_x_len; ++ owner_response[off] = (owner_y_len >> 8) & 0xFF; ++ owner_response[off + 1] = owner_y_len & 0xFF; ++ off += 2; ++ TEST_ASSERT_EQUAL(0, memcpy_s(&owner_response[off], owner_response_len - off, ++ owner_y, owner_y_len)); ++ off += owner_y_len; ++ owner_response[off] = (owner_random_len >> 8) & 0xFF; ++ owner_response[off + 1] = owner_random_len & 0xFF; ++ off += 2; ++ TEST_ASSERT_EQUAL(0, memcpy_s(&owner_response[off], owner_response_len - off, ++ owner_random, owner_random_len)); ++ ++ TEST_ASSERT_EQUAL(0, crypto_hal_set_peer_random(device_ctx, owner_response, ++ owner_response_len)); ++ ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_secret(device_ctx, NULL, &device_secret_len)); ++ TEST_ASSERT_TRUE(device_secret_len >= reference_secret_len); ++ device_secret = fdo_alloc(device_secret_len); ++ TEST_ASSERT_NOT_NULL(device_secret); ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_secret(device_ctx, device_secret, ++ &device_secret_len)); ++ ++ /* Device secret must start with expected raw ECDH secret. */ ++ int result_memcmp = 0; ++ TEST_ASSERT_EQUAL(0, memcmp_s(device_secret, reference_secret_len, ++ reference_secret, reference_secret_len, ++ &result_memcmp)); ++ TEST_ASSERT_EQUAL_MESSAGE( ++ 0, result_memcmp, ++ "Device-derived secret does not start with the expected raw " ++ "ECDH shared secret"); ++ ++ if (device_public) { ++ fdo_free(device_public); ++ } ++ if (device_secret) { ++ fdo_free(device_secret); ++ } ++ if (owner_response) { ++ fdo_free(owner_response); ++ } ++ if (device_pub_key_inited) { ++ wc_ecc_free(&device_pub_key); ++ } ++ if (owner_key_inited) { ++ wc_ecc_free(&owner_key); ++ } ++ if (owner_rng_inited) { ++ wc_FreeRng(&owner_rng); ++ } ++ crypto_hal_kex_close(&device_ctx); ++ TEST_ASSERT_EQUAL(0, random_close()); ++} ++#else ++#ifndef TARGET_OS_FREERTOS ++void test_ecdh_key_exchange_round_trip(void) ++#else ++TEST_CASE("ecdh_key_exchange_round_trip", "[ECDH][fdo]") ++#endif ++{ ++ TEST_IGNORE(); ++} ++#endif // USE_WOLFSSL ++ ++/** ++ * Verify device accepts short coordinate and derives correct secret. ++ */ ++#ifdef USE_WOLFSSL ++#ifndef TARGET_OS_FREERTOS ++void test_ecdh_short_peer_coordinate(void) ++#else ++TEST_CASE("ecdh_short_peer_coordinate", "[ECDH][fdo]") ++#endif ++{ ++ void *device_ctx = NULL; ++ uint8_t *device_public = NULL; ++ uint32_t device_public_len = 0; ++ uint8_t *device_secret = NULL; ++ uint32_t device_secret_len = 0; ++ uint8_t *owner_response = NULL; ++ ecc_key owner_key; ++ ecc_key device_pub_key; ++ WC_RNG owner_rng; ++ int owner_key_inited = 0; ++ int device_pub_key_inited = 0; ++ int owner_rng_inited = 0; ++ uint8_t owner_x[BUFF_SIZE_64_BYTES] = {0}; ++ uint8_t owner_y[BUFF_SIZE_64_BYTES] = {0}; ++ word32 owner_x_len = 0; ++ word32 owner_y_len = 0; ++ /* ~2/256 of keys have a stripped coordinate, so this all but always ++ * succeeds well inside the cap. */ ++ const int max_attempts = 4000; ++ int attempt = 0; ++ ++ TEST_ASSERT_EQUAL(0, random_init()); ++ ++ TEST_ASSERT_EQUAL(0, crypto_hal_kex_init(&device_ctx)); ++ TEST_ASSERT_NOT_NULL(device_ctx); ++ ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_device_random(device_ctx, NULL, ++ &device_public_len)); ++ device_public = fdo_alloc(device_public_len); ++ TEST_ASSERT_NOT_NULL(device_public); ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_device_random( ++ device_ctx, device_public, &device_public_len)); ++ ++ uint32_t idx = 0; ++ uint32_t dev_x_len = (device_public[idx] << 8) | device_public[idx + 1]; ++ idx += 2; ++ uint8_t *dev_x = &device_public[idx]; ++ idx += dev_x_len; ++ uint32_t dev_y_len = (device_public[idx] << 8) | device_public[idx + 1]; ++ idx += 2; ++ uint8_t *dev_y = &device_public[idx]; ++ idx += dev_y_len; ++ uint32_t dev_rand_len = (device_public[idx] << 8) | device_public[idx + 1]; ++ ++ TEST_ASSERT_EQUAL(0, wc_InitRng(&owner_rng)); ++ owner_rng_inited = 1; ++ ++ /* Hunt for keypair with leading zero byte. */ ++ for (attempt = 0; attempt < max_attempts; attempt++) { ++ if (owner_key_inited) { ++ wc_ecc_free(&owner_key); ++ owner_key_inited = 0; ++ } ++ TEST_ASSERT_EQUAL(0, wc_ecc_init(&owner_key)); ++ owner_key_inited = 1; ++ TEST_ASSERT_EQUAL(0, wc_ecc_make_key(&owner_rng, (int)dev_x_len, ++ &owner_key)); ++ TEST_ASSERT_EQUAL(0, wc_ecc_set_rng(&owner_key, &owner_rng)); ++ ++ owner_x_len = sizeof(owner_x); ++ owner_y_len = sizeof(owner_y); ++ TEST_ASSERT_EQUAL(0, wc_ecc_export_public_raw(&owner_key, owner_x, ++ &owner_x_len, ++ owner_y, ++ &owner_y_len)); ++ if (owner_x[0] == 0x00 || owner_y[0] == 0x00) { ++ break; ++ } ++ } ++ if (attempt == max_attempts) { ++ if (owner_key_inited) { ++ wc_ecc_free(&owner_key); ++ } ++ wc_FreeRng(&owner_rng); ++ fdo_free(device_public); ++ crypto_hal_kex_close(&device_ctx); ++ TEST_ASSERT_EQUAL(0, random_close()); ++ TEST_IGNORE_MESSAGE("No keypair with a leading zero coordinate " ++ "found"); ++ return; ++ } ++ ++ TEST_ASSERT_EQUAL(0, wc_ecc_init(&device_pub_key)); ++ device_pub_key_inited = 1; ++ TEST_ASSERT_EQUAL(0, wc_ecc_import_unsigned(&device_pub_key, dev_x, dev_y, ++ NULL, owner_key.dp->id)); ++ ++ uint8_t reference_secret[BUFF_SIZE_512_BYTES] = {0}; ++ word32 reference_secret_len = sizeof(reference_secret); ++ TEST_ASSERT_EQUAL(0, wc_ecc_shared_secret(&owner_key, &device_pub_key, ++ reference_secret, ++ &reference_secret_len)); ++ ++ /* Strip the leading zero bytes, the way BN_bn2bin() would. */ ++ uint8_t *x_p = owner_x; ++ uint8_t *y_p = owner_y; ++ uint32_t x_len = owner_x_len; ++ uint32_t y_len = owner_y_len; ++ while (x_len > 1 && x_p[0] == 0x00) { ++ x_p++; ++ x_len--; ++ } ++ while (y_len > 1 && y_p[0] == 0x00) { ++ y_p++; ++ y_len--; ++ } ++ TEST_ASSERT_TRUE(x_len < owner_x_len || y_len < owner_y_len); ++ ++ uint8_t owner_random[BUFF_SIZE_64_BYTES] = {0}; ++ uint32_t owner_random_len = dev_rand_len; ++ TEST_ASSERT_EQUAL(0, crypto_hal_random_bytes(owner_random, owner_random_len)); ++ ++ uint32_t owner_response_len = 2 + x_len + 2 + y_len + 2 + owner_random_len; ++ owner_response = fdo_alloc(owner_response_len); ++ TEST_ASSERT_NOT_NULL(owner_response); ++ uint32_t off = 0; ++ owner_response[off] = (x_len >> 8) & 0xFF; ++ owner_response[off + 1] = x_len & 0xFF; ++ off += 2; ++ TEST_ASSERT_EQUAL(0, memcpy_s(&owner_response[off], owner_response_len - off, ++ x_p, x_len)); ++ off += x_len; ++ owner_response[off] = (y_len >> 8) & 0xFF; ++ owner_response[off + 1] = y_len & 0xFF; ++ off += 2; ++ TEST_ASSERT_EQUAL(0, memcpy_s(&owner_response[off], owner_response_len - off, ++ y_p, y_len)); ++ off += y_len; ++ owner_response[off] = (owner_random_len >> 8) & 0xFF; ++ owner_response[off + 1] = owner_random_len & 0xFF; ++ off += 2; ++ TEST_ASSERT_EQUAL(0, memcpy_s(&owner_response[off], owner_response_len - off, ++ owner_random, owner_random_len)); ++ ++ TEST_ASSERT_EQUAL_MESSAGE( ++ 0, ++ crypto_hal_set_peer_random(device_ctx, owner_response, ++ owner_response_len), ++ "Peer coordinate with stripped leading zero was rejected"); ++ ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_secret(device_ctx, NULL, &device_secret_len)); ++ device_secret = fdo_alloc(device_secret_len); ++ TEST_ASSERT_NOT_NULL(device_secret); ++ TEST_ASSERT_EQUAL(0, crypto_hal_get_secret(device_ctx, device_secret, ++ &device_secret_len)); ++ ++ int result_memcmp = 0; ++ TEST_ASSERT_EQUAL(0, memcmp_s(device_secret, reference_secret_len, ++ reference_secret, reference_secret_len, ++ &result_memcmp)); ++ TEST_ASSERT_EQUAL_MESSAGE( ++ 0, result_memcmp, ++ "Device-derived secret does not start with the expected raw " ++ "ECDH shared secret"); ++ ++ if (device_public) { ++ fdo_free(device_public); ++ } ++ if (device_secret) { ++ fdo_free(device_secret); ++ } ++ if (owner_response) { ++ fdo_free(owner_response); ++ } ++ if (device_pub_key_inited) { ++ wc_ecc_free(&device_pub_key); ++ } ++ if (owner_key_inited) { ++ wc_ecc_free(&owner_key); ++ } ++ if (owner_rng_inited) { ++ wc_FreeRng(&owner_rng); ++ } ++ crypto_hal_kex_close(&device_ctx); ++ TEST_ASSERT_EQUAL(0, random_close()); ++} ++#else ++#ifndef TARGET_OS_FREERTOS ++void test_ecdh_short_peer_coordinate(void) ++#else ++TEST_CASE("ecdh_short_peer_coordinate", "[ECDH][fdo]") ++#endif ++{ ++ TEST_IGNORE(); ++} ++#endif // USE_WOLFSSL ++ ++/** ++ * Verify rejection of invalid arguments. ++ */ ++#ifndef TARGET_OS_FREERTOS ++void test_ecdh_invalid_args(void) ++#else ++TEST_CASE("ecdh_invalid_args", "[ECDH][fdo]") ++#endif ++{ ++ TEST_ASSERT_NOT_EQUAL(0, crypto_hal_kex_init(NULL)); ++ TEST_ASSERT_NOT_EQUAL(0, crypto_hal_kex_close(NULL)); ++ TEST_ASSERT_NOT_EQUAL(0, ++ crypto_hal_set_peer_random(NULL, NULL, 0)); ++ ++ TEST_ASSERT_EQUAL(0, random_init()); ++ ++ void *ctx = NULL; ++ TEST_ASSERT_EQUAL(0, crypto_hal_kex_init(&ctx)); ++ TEST_ASSERT_NOT_NULL(ctx); ++ TEST_ASSERT_NOT_EQUAL( ++ 0, crypto_hal_set_peer_random(ctx, NULL, 0)); ++ ++ /* Ax length field claims more bytes than are actually present. */ ++ uint8_t truncated_ax[] = {0x00, 0x40, 0x01, 0x02}; ++ TEST_ASSERT_NOT_EQUAL(0, crypto_hal_set_peer_random( ++ ctx, truncated_ax, sizeof(truncated_ax))); ++ ++ /* Buffer ends right after the Ax length field, before any Ax data ++ * or the Ay/owner-random fields that must follow it. */ ++ uint8_t missing_ay[] = {0x00, 0x00}; ++ TEST_ASSERT_NOT_EQUAL(0, crypto_hal_set_peer_random( ++ ctx, missing_ay, sizeof(missing_ay))); ++ ++ /* Ax/Ay lengths are internally consistent and short enough to be ++ * accepted by the parser, but the padded coordinates are not a point ++ * on the curve, so the import must still fail. */ ++ uint8_t short_ax_ay[] = {0x00, 0x01, 0xAA, 0x00, 0x01, 0xBB, ++ 0x00, 0x00}; ++ TEST_ASSERT_NOT_EQUAL(0, crypto_hal_set_peer_random( ++ ctx, short_ax_ay, sizeof(short_ax_ay))); ++ ++ /* Owner-random length field points past the end of the buffer. */ ++ uint8_t oversized_owner_random[] = {0x00, 0x00, 0x00, 0x00, ++ 0xFF, 0xFF}; ++ TEST_ASSERT_NOT_EQUAL( ++ 0, crypto_hal_set_peer_random(ctx, oversized_owner_random, ++ sizeof(oversized_owner_random))); ++ ++ crypto_hal_kex_close(&ctx); ++ ++ TEST_ASSERT_EQUAL(0, random_close()); ++} +diff --git a/tests/unit/test_ECDSASignRoutines.c b/tests/unit/test_ECDSASignRoutines.c +index 29b43af..ad1011f 100644 +--- a/tests/unit/test_ECDSASignRoutines.c ++++ b/tests/unit/test_ECDSASignRoutines.c +@@ -13,14 +13,7 @@ + #include "fdo_crypto_hal.h" + #include "storage_al.h" + #include "unity.h" +-#include "openssl/core_names.h" +-#include +-#include +-#include +-#include +-#include +-#include +-#include ++#include "test_crypto.h" + + // #define HEXDEBUG 1 + +@@ -34,6 +27,7 @@ + void set_up(void); + void tear_down(void); + void test_fdo_cryptoECDSASign(void); ++void test_crypto_hal_get_device_csr(void); + + /*** Unity functions. ***/ + void set_up(void) +@@ -178,6 +172,24 @@ static int generateECDSA_key(mbedtls_ecdsa_context *ctx_sign) + } + + #endif // USE_MBEDTLS ++ ++#ifdef USE_WOLFSSL ++static int generateECDSA_key(ecc_key *key, WC_RNG *rng) ++{ ++ int curve_id = ECC_SECP256R1; ++ ++#if defined(ECDSA384_DA) ++ curve_id = ECC_SECP384R1; ++#endif ++ if (wc_InitRng(rng) != 0) { ++ return -1; ++ } ++ if (wc_ecc_init(key) != 0) { ++ return -1; ++ } ++ return wc_ecc_make_key_ex(rng, 0, key, curve_id); ++} ++#endif // USE_WOLFSSL + #endif // PK_ENC_ECDSA || ECDSA256_DA || ECDSA384_DA + /*** Test functions. ***/ + +@@ -205,11 +217,18 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + size_t siglen = ECDSA_SIG_MAX_LENGTH; + unsigned char *sigtestdata = fdo_alloc(ECDSA_SIG_MAX_LENGTH); + TEST_ASSERT_NOT_NULL(sigtestdata); ++#ifdef USE_OPENSSL + EVP_MD_CTX *mdctx = NULL; ++#endif ++#ifdef USE_WOLFSSL ++ uint8_t wolfssl_hash[WC_SHA512_DIGEST_SIZE] = {0}; ++#endif + unsigned char *sig_r = NULL; + unsigned char *sig_s = NULL; ++#ifdef USE_OPENSSL + uint32_t der_sig_len = 0; + uint8_t *der_sig = NULL; ++#endif + size_t hash_length = 0; + + #if defined(ECDSA256_DA) +@@ -232,85 +251,48 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + result = generateECDSA_key(&ctx_sign); + TEST_ASSERT_EQUAL(0, result); + int privatekey_buflen = mbedtls_mpi_size(&ctx_sign.d); ++#endif ++#ifdef USE_WOLFSSL ++ ecc_key wolfssl_key; ++ WC_RNG wolfssl_rng; ++ result = generateECDSA_key(&wolfssl_key, &wolfssl_rng); ++ TEST_ASSERT_EQUAL(0, result); ++ int privatekey_buflen = wc_ecc_size(&wolfssl_key); + #endif + // Extracting private key from mbedtls structure + unsigned char *privatekey = fdo_alloc(privatekey_buflen); + TEST_ASSERT_NOT_NULL(privatekey); +- memset_s(privatekey, 0, privatekey_buflen); ++ memset_s(privatekey, privatekey_buflen, 0); + + // store private key for later use in pem /bin format + #if defined(ECDSA_PEM) ++#if defined(USE_WOLFSSL) ++ unsigned char der_buf[256]; ++ unsigned char pem_buf[512]; ++ int der_len = wc_EccKeyToDer(&wolfssl_key, der_buf, sizeof(der_buf)); ++ TEST_ASSERT_TRUE(der_len > 0); ++ int pem_len = wc_DerToPem(der_buf, (word32)der_len, pem_buf, ++ sizeof(pem_buf), ECC_PRIVATEKEY_TYPE); ++ TEST_ASSERT_TRUE(pem_len > 0); ++ result = fdo_blob_write((char *)ECDSA_PRIVKEY, FDO_SDK_RAW_DATA, ++ pem_buf, pem_len); ++ TEST_ASSERT_NOT_EQUAL(-1, result); ++#else ++ /* Store the key generated above, so the signature can be checked ++ * against avalidkey below. */ + BIO *outbio = BIO_new(BIO_s_mem()); + TEST_ASSERT_NOT_NULL(outbio); +- EVP_PKEY *privkey = EVP_PKEY_new(); +- TEST_ASSERT_NOT_NULL(privkey); +- +- BIGNUM *priv; +- OSSL_PARAM_BLD *param_bld; +- OSSL_PARAM *params = NULL; +- EVP_PKEY_CTX *ctx; // Creating new EVP_PKEY context +- +- priv = BN_bin2bn(privatekey, privatekey_buflen, NULL); +- param_bld = OSSL_PARAM_BLD_new(); +- +- if (priv != NULL && param_bld != NULL && +- OSSL_PARAM_BLD_push_utf8_string(param_bld, "group", "prime256v1", +- 0) && +- OSSL_PARAM_BLD_push_BN(param_bld, "priv", priv) && +- OSSL_PARAM_BLD_push_octet_string(param_bld, "pub", NULL, 0)) { +- params = OSSL_PARAM_BLD_to_param(param_bld); +- } +- +- ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); +- +- if (ctx == NULL || params == NULL || EVP_PKEY_fromdata_init(ctx) <= 0 || +- EVP_PKEY_fromdata(ctx, &privkey, EVP_PKEY_KEYPAIR, params) <= 0) { +- exit(1); +- } +- +- size_t group_name_size; +- char group_name[64]; +- +- EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, +- NULL, 0, &group_name_size); +- if (group_name_size >= sizeof(group_name)) { +- LOG(LOG_ERROR, "Unexpected long group name : %zu for EC key\n", +- group_name_size); +- exit(1); +- } +- +- if (!EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, +- group_name, sizeof(group_name), +- &group_name_size)) { +- LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); +- exit(1); +- } +- +- int group_nid = OBJ_sn2nid(group_name); +- const EC_GROUP *group = EC_GROUP_new_by_curve_name(group_nid); +- +- if (group == NULL) { +- LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); +- exit(1); +- } +- +- if (!PEM_write_bio_Parameters(outbio, privkey)) { +- BIO_printf(outbio, "Error writing parameters in PEM format"); +- } +- +- if (PEM_write_bio_PrivateKey(outbio, privkey, NULL, NULL, 0, 0, NULL) == +- 0) { +- BIO_printf(outbio, +- "Error writing private key data in PEM format"); +- } ++ TEST_ASSERT_EQUAL(1, PEM_write_bio_PrivateKey(outbio, avalidkey, NULL, ++ NULL, 0, NULL, NULL)); + + BUF_MEM *bptr = NULL; + BIO_get_mem_ptr(outbio, &bptr); +- +- printf("buffer :\n %s", bptr->data); ++ TEST_ASSERT_NOT_NULL(bptr); + result = fdo_blob_write((char *)ECDSA_PRIVKEY, FDO_SDK_RAW_DATA, + (const uint8_t *)bptr->data, bptr->length); + TEST_ASSERT_NOT_EQUAL(-1, result); ++ BIO_free(outbio); ++#endif // USE_WOLFSSL + + #else // save in bin format + +@@ -321,13 +303,25 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + LOG(LOG_ERROR, "Failed to get private key bn\n"); + result = -1; + } +- if (BN_bn2bin(privkey_bn, privatekey)) ++ /* Fixed width: BN_bn2bin() drops leading zero bytes. */ ++ if (BN_bn2binpad(privkey_bn, privatekey, privatekey_buflen) == ++ privatekey_buflen) + result = 0; ++ BN_clear_free(privkey_bn); + #endif + #ifdef USE_MBEDTLS + result = mbedtls_mpi_write_binary(&ctx_sign.d, privatekey, + privatekey_buflen); + #endif ++#ifdef USE_WOLFSSL ++ word32 wolfssl_privkey_len = (word32)privatekey_buflen; ++ if (wc_ecc_export_private_only(&wolfssl_key, privatekey, ++ &wolfssl_privkey_len) == 0) { ++ result = 0; ++ } else { ++ result = -1; ++ } ++#endif + + TEST_ASSERT_EQUAL(0, result); + +@@ -416,7 +410,7 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + TEST_ASSERT_EQUAL(0, result); + + // Negative test case +- sigtestdata[4] = 'a'; ++ sigtestdata[4] ^= 0xFF; + memcpy_s(sig_r, siglen / 2, sigtestdata, siglen / 2); + ECDSA_SIG_free(sig); + r = BN_bin2bn((const unsigned char *)sig_r, siglen / 2, NULL); +@@ -477,7 +471,7 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + TEST_ASSERT_EQUAL(0, result); + + // Negative test case +- sigtestdata[4] = 'a'; ++ sigtestdata[4] ^= 0xFF; + if ((result = mbedtls_ecdsa_read_signature(&ctx_sign, hash, hash_length, + sigtestdata, siglen)) != 0) { + LOG(LOG_ERROR, "mbedtls_ecdsa_read_signature failed\n"); +@@ -485,16 +479,81 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + } + TEST_ASSERT_NOT_EQUAL(0, result); + #endif ++ ++#ifdef USE_WOLFSSL ++ { ++ mp_int wolfssl_r, wolfssl_s; ++ int wolfssl_verify_stat = 0; ++ ++#if defined(ECDSA256_DA) ++ result = wc_Sha256Hash((const byte *)testdata->bytes, ++ testdata->byte_sz, wolfssl_hash); ++#elif defined(ECDSA384_DA) ++ result = wc_Sha384Hash((const byte *)testdata->bytes, ++ testdata->byte_sz, wolfssl_hash); ++#endif ++ TEST_ASSERT_EQUAL(0, result); ++ ++ sig_r = fdo_alloc(siglen / 2); ++ TEST_ASSERT_NOT_NULL(sig_r); ++ memcpy_s(sig_r, siglen / 2, sigtestdata, siglen / 2); ++ sig_s = fdo_alloc(siglen / 2); ++ TEST_ASSERT_NOT_NULL(sig_s); ++ memcpy_s(sig_s, siglen / 2, sigtestdata + siglen / 2, ++ siglen / 2); ++ ++ mp_init(&wolfssl_r); ++ mp_init(&wolfssl_s); ++ mp_read_unsigned_bin(&wolfssl_r, sig_r, (int)(siglen / 2)); ++ mp_read_unsigned_bin(&wolfssl_s, sig_s, (int)(siglen / 2)); ++ ++#if defined(FDO_TPM_STACK_WOLFTPM) ++ /* With a TPM DA the signature comes from the TPM's device key, ++ * not the software key generated above: verify against the ++ * public half read back from the TPM. */ ++ { ++ WOLFTPM2_DEV dev; ++ WOLFTPM2_KEY tpm_key; ++ ++ XMEMSET(&tpm_key, 0, sizeof(tpm_key)); ++ TEST_ASSERT_EQUAL(TPM_RC_SUCCESS, wolftpm_init_dev(&dev)); ++ TEST_ASSERT_EQUAL(TPM_RC_SUCCESS, ++ wolfTPM2_ReadPublicKey( ++ &dev, &tpm_key, ++ TPM_DEVICE_KEY_PERSISTANT_HANDLE)); ++ wc_ecc_free(&wolfssl_key); ++ TEST_ASSERT_EQUAL(0, wc_ecc_init(&wolfssl_key)); ++ TEST_ASSERT_EQUAL(0, wolfTPM2_EccKey_TpmToWolf( ++ &dev, &tpm_key, &wolfssl_key)); ++ wolfTPM2_Cleanup(&dev); ++ } ++#endif ++ result = wc_ecc_verify_hash_ex( ++ &wolfssl_r, &wolfssl_s, wolfssl_hash, (word32)hash_length, ++ &wolfssl_verify_stat, &wolfssl_key); ++ TEST_ASSERT_EQUAL(0, result); ++ TEST_ASSERT_EQUAL(1, wolfssl_verify_stat); ++ ++ /* Negative test case */ ++ sigtestdata[4] ^= 0xFF; ++ memcpy_s(sig_r, siglen / 2, sigtestdata, siglen / 2); ++ mp_read_unsigned_bin(&wolfssl_r, sig_r, (int)(siglen / 2)); ++ ++ result = wc_ecc_verify_hash_ex( ++ &wolfssl_r, &wolfssl_s, wolfssl_hash, (word32)hash_length, ++ &wolfssl_verify_stat, &wolfssl_key); ++ TEST_ASSERT_FALSE(result == 0 && wolfssl_verify_stat == 1); ++ ++ mp_clear(&wolfssl_r); ++ mp_clear(&wolfssl_s); ++ } ++#endif + // Negative test case + result = crypto_hal_ecdsa_sign(NULL, testdata->byte_sz, sigtestdata, + &siglen); + TEST_ASSERT_NOT_EQUAL(0, result); + + #ifdef USE_OPENSSL +-#if defined(ECDSA_PEM) +- EVP_PKEY_free(privkey); +- BIO_free_all(outbio); +-#endif + if (avalidkey) { + EVP_PKEY_free(avalidkey); + avalidkey = NULL; +@@ -511,9 +570,38 @@ TEST_CASE("crypto_hal_ecdsa_sign", "[ECDSARoutines][fdo]") + #endif + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&ctx_sign); ++#endif ++#ifdef USE_WOLFSSL ++ if (sig_r) { ++ fdo_free(sig_r); ++ } ++ if (sig_s) { ++ fdo_free(sig_s); ++ } ++ wc_ecc_free(&wolfssl_key); ++ wc_FreeRng(&wolfssl_rng); + #endif + free(sigtestdata); + free(privatekey); + fdo_byte_array_free(testdata); + } ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_hal_get_device_csr(void) ++#else ++TEST_CASE("crypto_hal_get_device_csr", "[ECDSARoutines][fdo]") ++#endif ++{ ++ /* Relies on the ECDSA private key blob written to storage by ++ * test_fdo_cryptoECDSASign(), which the test runner executes first. ++ */ ++ fdo_byte_array_t *csr = NULL; ++ int result = crypto_hal_get_device_csr(&csr); ++ TEST_ASSERT_EQUAL(0, result); ++ TEST_ASSERT_NOT_NULL(csr); ++ TEST_ASSERT_TRUE(csr->byte_sz > 0); ++ /* A DER-encoded CSR is a SEQUENCE, tag 0x30. */ ++ TEST_ASSERT_EQUAL(0x30, csr->bytes[0]); ++ fdo_byte_array_free(csr); ++} + #endif +diff --git a/tests/unit/test_ECDSAVerifyRoutines.c b/tests/unit/test_ECDSAVerifyRoutines.c +index 73207b0..f5ffb20 100644 +--- a/tests/unit/test_ECDSAVerifyRoutines.c ++++ b/tests/unit/test_ECDSAVerifyRoutines.c +@@ -14,7 +14,7 @@ + #include "fdo_crypto.h" + #include "storage_al.h" + #include "unity.h" +-#include "openssl/core_names.h" ++#include "test_crypto.h" + + //#define HEXDEBUG 1 + +@@ -480,6 +480,105 @@ static fdo_public_key_t *getFDOpk(int curve, mbedtls_ecdsa_context *ctx_sign) + } + #endif // USE_MBEDTLS + ++#ifdef USE_WOLFSSL ++static int generateECDSA_key(int curve, ecc_key *key, WC_RNG *rng) ++{ ++ int curve_id; ++ ++ if (curve == 256) { ++ curve_id = ECC_SECP256R1; ++ } else if (curve == 384) { ++ curve_id = ECC_SECP384R1; ++ } else { ++ return -1; ++ } ++ if (wc_InitRng(rng) != 0) { ++ return -1; ++ } ++ if (wc_ecc_init(key) != 0) { ++ return -1; ++ } ++ return wc_ecc_make_key_ex(rng, 0, key, curve_id); ++} ++ ++/* Returns 1 on success, 0/-1 on error. Produces a raw r||s signature (not ++ * DER), as crypto_hal_sig_verify() expects for this backend. ++ */ ++static int sha_ECCsign(int curve, unsigned char *msg, unsigned int mlen, ++ unsigned char *out, unsigned int *outlen, ecc_key *key, ++ WC_RNG *rng) ++{ ++ uint8_t hash[WC_SHA512_DIGEST_SIZE] = {0}; ++ size_t hash_length = (curve == 256) ? SHA256_DIGEST_SIZE ++ : SHA384_DIGEST_SIZE; ++ mp_int r, s; ++ int coord = wc_ecc_size(key); ++ int ret; ++ ++ if (curve == 256) { ++ ret = wc_Sha256Hash((const byte *)msg, mlen, hash); ++ } else { ++ ret = wc_Sha384Hash((const byte *)msg, mlen, hash); ++ } ++ if (ret != 0) { ++ return 0; ++ } ++ ++ mp_init(&r); ++ mp_init(&s); ++ if (wc_ecc_sign_hash_ex(hash, (word32)hash_length, rng, key, &r, &s) != ++ 0) { ++ mp_clear(&r); ++ mp_clear(&s); ++ return 0; ++ } ++ ++ /* Pad r and s to the coordinate size: mp_to_unsigned_bin() strips ++ * leading zeros, which would misplace s and give an odd length. */ ++ if (coord <= 0 || mp_to_unsigned_bin_len(&r, out, coord) != MP_OKAY || ++ mp_to_unsigned_bin_len(&s, out + coord, coord) != MP_OKAY) { ++ mp_clear(&r); ++ mp_clear(&s); ++ return 0; ++ } ++ *outlen = (unsigned int)(2 * coord); ++ mp_clear(&r); ++ mp_clear(&s); ++ return 1; ++} ++ ++static fdo_public_key_t *getFDOpk(int curve, ecc_key *key) ++{ ++ unsigned char key_buf[DER_PUBKEY_LEN_MAX]; ++ int key_buf_len; ++ fdo_public_key_t *pk = NULL; ++ ++ /* DER-encode the full X.509 SubjectPublicKeyInfo, matching the ++ * format crypto_hal_sig_verify() expects for ++ * FDO_CRYPTO_PUB_KEY_ENCODING_X509. ++ */ ++ key_buf_len = wc_EccPublicKeyToDer(key, key_buf, sizeof(key_buf), 1); ++ if (key_buf_len <= 0) { ++ return NULL; ++ } ++ ++ if (curve == 256) { ++ pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256, ++ FDO_CRYPTO_PUB_KEY_ENCODING_X509, ++ key_buf_len, key_buf); ++ } else { ++ pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384, ++ FDO_CRYPTO_PUB_KEY_ENCODING_X509, ++ key_buf_len, key_buf); ++ } ++ if (!pk || !pk->key1) { ++ return NULL; ++ } ++ pk->key2 = NULL; ++ return pk; ++} ++#endif // USE_WOLFSSL ++ + static void ec_sig_verification(int curve) + { + int result = -1; +@@ -507,6 +606,22 @@ static void ec_sig_verification(int curve) + pk = getFDOpk(curve, avalidkey); + #endif + ++#ifdef USE_WOLFSSL ++ ecc_key wolfssl_key; ++ WC_RNG wolfssl_rng; ++ (void)key_buf; ++ (void)key_buf_len; ++ result = generateECDSA_key(curve, &wolfssl_key, &wolfssl_rng); ++ TEST_ASSERT_EQUAL(0, result); ++ ++ LOG(LOG_INFO, "Signing message...\n"); ++ if (1 == (result = sha_ECCsign(curve, testdata->bytes, ++ testdata->byte_sz, sigtestdata, &siglen, ++ &wolfssl_key, &wolfssl_rng))) { ++ TEST_ASSERT_EQUAL(1, result); ++ pk = getFDOpk(curve, &wolfssl_key); ++#endif ++ + #ifdef USE_MBEDTLS + mbedtls_ecdsa_context avalidkey; + result = generateECDSA_key(curve, &avalidkey); +@@ -584,6 +699,13 @@ static void ec_sig_verification(int curve) + result = generateECDSA_key(curve, &anotherkey); + TEST_ASSERT_EQUAL(0, result); + anotherpk = getFDOpk(curve, &anotherkey); ++#endif ++#ifdef USE_WOLFSSL ++ ecc_key anotherkey; ++ WC_RNG anotherkey_rng; ++ result = generateECDSA_key(curve, &anotherkey, &anotherkey_rng); ++ TEST_ASSERT_EQUAL(0, result); ++ anotherpk = getFDOpk(curve, &anotherkey); + #endif + TEST_ASSERT_NOT_NULL(anotherpk); + result = crypto_hal_sig_verify( +@@ -615,6 +737,10 @@ static void ec_sig_verification(int curve) + #endif + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&anotherkey); ++#endif ++#ifdef USE_WOLFSSL ++ wc_ecc_free(&anotherkey); ++ wc_FreeRng(&anotherkey_rng); + #endif + fdo_public_key_free(pk); + } +@@ -627,6 +753,10 @@ static void ec_sig_verification(int curve) + #endif + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&avalidkey); ++#endif ++#ifdef USE_WOLFSSL ++ wc_ecc_free(&wolfssl_key); ++ wc_FreeRng(&wolfssl_rng); + #endif + fdo_byte_array_free(testdata); + free(sigtestdata); +diff --git a/tests/unit/test_SSLRoutines.c b/tests/unit/test_SSLRoutines.c +index 53b4eb1..3b4b65b 100644 +--- a/tests/unit/test_SSLRoutines.c ++++ b/tests/unit/test_SSLRoutines.c +@@ -17,7 +17,7 @@ + #include + #include //hostent + #include +-#include ++#include "test_crypto.h" + #include "util.h" + #include "fdo_crypto_hal.h" + #include "unity.h" +@@ -26,6 +26,7 @@ + /*** Unity Declarations ***/ + void set_up(void); + void tear_down(void); ++#ifdef USE_OPENSSL + void __wrap_SSL_free(SSL *ssl); + int __wrap_SSL_connect(void); + int __wrap_SSL_shutdown(void); +@@ -36,6 +37,20 @@ SSL_CTX *__wrap_SSL_CTX_new(void); + SSL_METHOD *__wrap_TLS_method(void); + SSL *__wrap_SSL_new(void); + SSL *test_ssl_init(void); ++#elif defined(USE_WOLFSSL) ++void __wrap_wolfSSL_free(WOLFSSL *ssl); ++int __wrap_wolfSSL_connect(void); ++int __wrap_wolfSSL_shutdown(void); ++int __wrap_wolfSSL_read(void); ++int __wrap_wolfSSL_write(void); ++int __wrap_wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX *ctx, const char *str); ++int __wrap_wolfSSL_CTX_load_verify_locations(WOLFSSL_CTX *ctx, const char *file, ++ const char *path); ++WOLFSSL_CTX *__wrap_wolfSSL_CTX_new(void); ++WOLFSSL_METHOD *__wrap_wolfSSLv23_client_method(void); ++WOLFSSL *__wrap_wolfSSL_new(void); ++WOLFSSL *test_wolfssl_init(void); ++#endif + void test_ssl_setup(void); + void test_ssl_connect(void); + void test_ssl_close(void); +@@ -155,39 +170,201 @@ SSL *test_ssl_init(void) + + SSL_load_error_strings(); + method = SSLv23_method(); +- if (!(NULL != method)) { +- goto err; ++ int success = 0; ++ ++ do { ++ if (!(NULL != method)) { ++ break; ++ } ++ ++ test_ctx = SSL_CTX_new(method); ++ if (!(test_ctx != NULL)) { ++ break; ++ } ++ ++ SSL_CTX_set_options(test_ctx, flags); ++ if (0 == SSL_CTX_set_cipher_list(test_ctx, PREFERRED_CIPHERS)) { ++ LOG(LOG_ERROR, "SSL cipher suite set failed"); ++ break; ++ } ++ ++ ssl = SSL_new(test_ctx); ++ if (ssl == NULL) { ++ break; ++ } ++ ++ success = 1; ++ } while (0); ++ ++ if (!success) { ++ if (test_ctx) { ++ SSL_CTX_free(test_ctx); ++ test_ctx = NULL; ++ } ++ if (ssl != NULL) { ++ SSL_free(ssl); ++ ssl = NULL; ++ } + } + +- test_ctx = SSL_CTX_new(method); +- if (!(test_ctx != NULL)) { +- goto err; +- } ++ return ssl; ++} + +- SSL_CTX_set_options(test_ctx, flags); +- if (0 == SSL_CTX_set_cipher_list(test_ctx, PREFERRED_CIPHERS)) { +- LOG(LOG_ERROR, "SSL cipher suite set failed"); +- goto err; ++#endif /* TARGET_OS_LINUX (openssl wrapper block) */ ++#elif defined(USE_WOLFSSL) ++#ifdef TARGET_OS_LINUX ++uint32_t wolfssl_free; ++uint32_t wolfssl_shutdown; ++/* WOLFSSL_SUCCESS(1) unless a test wants the CA store load to fail. */ ++uint32_t ret_load_ca = 1; ++ ++void __real_wolfSSL_free(WOLFSSL *ssl); ++void __wrap_wolfSSL_free(WOLFSSL *ssl) ++{ ++ if (wolfssl_free) { ++ __real_wolfSSL_free(ssl); ++ return; + } ++ (void)ssl; ++ return; ++} ++ ++int __wrap_wolfSSL_connect(void) ++{ ++ return ret_connect; ++} ++ ++int __real_wolfSSL_shutdown(void); ++int __wrap_wolfSSL_shutdown(void) ++{ ++ if (wolfssl_shutdown) ++ return __real_wolfSSL_shutdown(); ++ else ++ return ret_shutdown; ++} + +- ssl = SSL_new(test_ctx); +- if (ssl == NULL) { +- goto err; ++int __wrap_wolfSSL_read(void) ++{ ++ return ret_read; ++} ++ ++int __wrap_wolfSSL_write(void) ++{ ++ return ret_write; ++} ++ ++int __wrap_wolfSSL_CTX_set_cipher_list(WOLFSSL_CTX *ctx, const char *str) ++{ ++ (void)ctx; ++ (void)str; ++ return 1; ++} ++ ++int __wrap_wolfSSL_CTX_load_verify_locations(WOLFSSL_CTX *ctx, const char *file, ++ const char *path) ++{ ++ (void)ctx; ++ (void)file; ++ (void)path; ++ return ret_load_ca; ++} ++ ++WOLFSSL_CTX *__real_wolfSSL_CTX_new(void); ++WOLFSSL_CTX *__wrap_wolfSSL_CTX_new(void) ++{ ++ if (ret_ctx) ++ return __real_wolfSSL_CTX_new(); ++ else ++ return NULL; ++} ++ ++WOLFSSL_METHOD *__real_wolfSSLv23_client_method(void); ++WOLFSSL_METHOD *__wrap_wolfSSLv23_client_method(void) ++{ ++ if (ret_method) ++ return __real_wolfSSLv23_client_method(); ++ else ++ return NULL; ++} ++ ++WOLFSSL *__real_wolfSSL_new(void); ++WOLFSSL *__wrap_wolfSSL_new(void) ++{ ++ if (ret_ssl) ++ return __real_wolfSSL_new(); ++ else ++ return NULL; ++} ++ ++WOLFSSL_CTX *test_wolfssl_ctx = NULL; ++WOLFSSL *test_wolfssl_init(void) ++{ ++ WOLFSSL *ssl = NULL; ++ WOLFSSL_METHOD *method; ++ const char *const PREFERRED_CIPHERS = ++ "HIGH:!aNULL:!NULL:!EXT:!DSS:!kRSA:!PSK:!SRP:!MD5:!RC4"; ++ ++ int success = 0; ++ ++ do { ++ if (WOLFSSL_SUCCESS != wolfSSL_Init()) { ++ break; ++ } ++ ++ method = wolfSSLv23_client_method(); ++ if (method == NULL) { ++ break; ++ } ++ ++ test_wolfssl_ctx = wolfSSL_CTX_new(method); ++ if (test_wolfssl_ctx == NULL) { ++ break; ++ } ++ ++ if (0 == wolfSSL_CTX_set_cipher_list(test_wolfssl_ctx, PREFERRED_CIPHERS)) { ++ LOG(LOG_ERROR, "SSL cipher suite set failed"); ++ break; ++ } ++ ++ ssl = wolfSSL_new(test_wolfssl_ctx); ++ if (ssl == NULL) { ++ break; ++ } ++ ++ success = 1; ++ } while (0); ++ ++ if (!success) { ++ if (test_wolfssl_ctx) { ++ wolfSSL_CTX_free(test_wolfssl_ctx); ++ test_wolfssl_ctx = NULL; ++ } ++ if (ssl != NULL) { ++ wolfSSL_free(ssl); ++ ssl = NULL; ++ } + } + + return ssl; +-err: +- if (test_ctx) { +- SSL_CTX_free(test_ctx); +- test_ctx = NULL; +- } +- if (ssl != NULL) { +- SSL_free(ssl); ++} ++ ++/* Mirrors private fdo_ssl_session_t for test wrapper. */ ++typedef struct { ++ WOLFSSL_CTX *ctx; ++ WOLFSSL *ssl; ++} test_wolfssl_session_t; ++ ++static void *wrap_wolfssl_session(WOLFSSL *ssl) ++{ ++ test_wolfssl_session_t *session = malloc(sizeof(*session)); ++ if (session) { ++ session->ctx = test_wolfssl_ctx; ++ session->ssl = ssl; + } +- return NULL; ++ return session; + } + +-#endif ++#endif /* TARGET_OS_LINUX */ + #endif + + void cleanup_ssl_struct(void *ssl); +@@ -196,11 +373,23 @@ void cleanup_ssl_struct(void *ssl) + if (ssl) { + // This causes the test to get stuck. TO-DO : Fix + // fdo_ssl_close(ssl); ++#if defined(USE_WOLFSSL) ++ wolfSSL_free(((test_wolfssl_session_t *)ssl)->ssl); ++ free(ssl); ++#else + SSL_free((SSL *)ssl); ++#endif ++ } ++#if defined(USE_WOLFSSL) ++ if (test_wolfssl_ctx) { ++ wolfSSL_CTX_free(test_wolfssl_ctx); ++ test_wolfssl_ctx = NULL; + } ++#elif defined(USE_OPENSSL) + if (test_ctx) { + SSL_CTX_free(test_ctx); + } ++#endif + } + + #ifndef TARGET_OS_FREERTOS +@@ -246,6 +435,53 @@ TEST_CASE("ssl_setup", "[SSLRoutines][fdo]") + cleanup_ssl_struct(ssl); + ret_ssl = 1; + ++#elif defined(USE_WOLFSSL) ++ int sock = 3; ++ void *ssl = NULL; ++ ++ ret_method = 1; ++ ret_ctx = 1; ++ ret_ssl = 1; ++ wolfssl_free = 1; ++ wolfssl_shutdown = 1; ++ ssl = fdo_ssl_setup(sock); ++ TEST_ASSERT_NOT_EQUAL_MESSAGE(NULL, ssl, "SSL Setup Failed"); ++ cleanup_ssl_struct(ssl); ++ ++ /* Negative Test Cases */ ++ ret_method = 0; ++ ret_ctx = 1; ++ ret_ssl = 1; ++ ssl = fdo_ssl_setup(sock); ++ TEST_ASSERT_EQUAL_MESSAGE(NULL, ssl, "-ve:1 SSL Setup Failed"); ++ cleanup_ssl_struct(ssl); ++ ++ ret_method = 1; ++ ret_ctx = 0; ++ ret_ssl = 1; ++ ssl = fdo_ssl_setup(sock); ++ TEST_ASSERT_EQUAL_MESSAGE(NULL, ssl, "-ve:2 SSL Setup Failed"); ++ cleanup_ssl_struct(ssl); ++ ++ ret_method = 1; ++ ret_ctx = 1; ++ ret_ssl = 0; ++ ssl = fdo_ssl_setup(sock); ++ TEST_ASSERT_EQUAL_MESSAGE(NULL, ssl, "-ve:3 SSL Setup Failed"); ++ cleanup_ssl_struct(ssl); ++ ret_ssl = 1; ++ ++ /* Without a usable CA store the handshake could only fail later with ++ * ASN_NO_SIGNER_E, so setup must refuse up front. */ ++ ret_method = 1; ++ ret_ctx = 1; ++ ret_ssl = 1; ++ ret_load_ca = 0; ++ ssl = fdo_ssl_setup(sock); ++ TEST_ASSERT_EQUAL_MESSAGE(NULL, ssl, "-ve:4 SSL Setup Failed"); ++ cleanup_ssl_struct(ssl); ++ ret_load_ca = 1; ++ + #endif + } + +@@ -258,20 +494,37 @@ TEST_CASE("ssl_connect", "[SSLRoutines][fdo]") + #ifdef USE_OPENSSL + int ret; + SSL *ssl = test_ssl_init(); +- if (ssl == NULL) +- goto err; ++ if (ssl != NULL) { + +- ret_connect = 1; +- ret = fdo_ssl_connect((void *)ssl); +- TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL connect Failed"); ++ ret_connect = 1; ++ ret = fdo_ssl_connect((void *)ssl); ++ TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL connect Failed"); + +- /* Negative Test Cases */ +- ret_connect = -1; +- ret = fdo_ssl_connect((void *)ssl); +- TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL Setup Failed"); ++ /* Negative Test Cases */ ++ ret_connect = -1; ++ ret = fdo_ssl_connect((void *)ssl); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL Setup Failed"); + +-err: +- cleanup_ssl_struct(ssl); ++ cleanup_ssl_struct(ssl); ++ } ++#elif defined(USE_WOLFSSL) ++ int ret; ++ WOLFSSL *ssl = test_wolfssl_init(); ++ TEST_ASSERT_NOT_NULL_MESSAGE(ssl, "test_wolfssl_init failed"); ++ if (ssl != NULL) { ++ void *session = wrap_wolfssl_session(ssl); ++ ++ ret_connect = 1; ++ ret = fdo_ssl_connect(session); ++ TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL connect Failed"); ++ ++ /* Negative Test Cases */ ++ ret_connect = -1; ++ ret = fdo_ssl_connect(session); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL Setup Failed"); ++ ++ cleanup_ssl_struct(session); ++ } + #endif + } + +@@ -286,23 +539,65 @@ TEST_CASE("ssl_close", "[SSLRoutines][fdo]") + TEST_IGNORE(); + int ret; + SSL *ssl = test_ssl_init(); +- if (ssl == NULL) +- goto err; ++ if (ssl != NULL) { + +- ret_shutdown = 1; +- ssl_shutdown = 0; +- ret = fdo_ssl_close((void *)ssl); +- TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL shutdown Failed"); ++ ret_shutdown = 1; ++ ssl_shutdown = 0; ++ ret = fdo_ssl_close((void *)ssl); ++ TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL shutdown Failed"); + +- /* Negative Test Cases */ +- ret_shutdown = -1; +- ret = fdo_ssl_close((void *)ssl); +- TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL shutdown Failed"); +-err: ++ /* Negative Test Cases */ ++ ret_shutdown = -1; ++ ret = fdo_ssl_close((void *)ssl); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL shutdown Failed"); ++ } + ssl_shutdown = 1; + if (test_ctx) { + SSL_CTX_free(test_ctx); + } ++#elif defined(USE_WOLFSSL) ++ int ret; ++ WOLFSSL *ssl = NULL; ++ void *session = NULL; ++ ++ ret_method = 1; ++ ret_ctx = 1; ++ ret_ssl = 1; ++ wolfssl_shutdown = 0; ++ ++ /* Each fdo_ssl_close() frees its session and ctx, so every case ++ * needs a fresh one. */ ++ ssl = test_wolfssl_init(); ++ TEST_ASSERT_NOT_NULL_MESSAGE(ssl, "test_wolfssl_init failed"); ++ session = wrap_wolfssl_session(ssl); ++ ret_shutdown = WOLFSSL_SUCCESS; ++ ret = fdo_ssl_close(session); ++ TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL shutdown Failed"); ++ test_wolfssl_ctx = NULL; ++ ++ /* Peer has not answered close_notify: still a clean close. */ ++ ssl = test_wolfssl_init(); ++ TEST_ASSERT_NOT_NULL_MESSAGE(ssl, "test_wolfssl_init failed"); ++ session = wrap_wolfssl_session(ssl); ++ ret_shutdown = WOLFSSL_SHUTDOWN_NOT_DONE; ++ ret = fdo_ssl_close(session); ++ TEST_ASSERT_EQUAL_MESSAGE(0, ret, "SSL shutdown not-done Failed"); ++ test_wolfssl_ctx = NULL; ++ ++ /* Negative Test Case: new session for failure path. */ ++ ssl = test_wolfssl_init(); ++ TEST_ASSERT_NOT_NULL_MESSAGE(ssl, "test_wolfssl_init failed"); ++ session = wrap_wolfssl_session(ssl); ++ ret_shutdown = WOLFSSL_FATAL_ERROR; ++ ret = fdo_ssl_close(session); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL shutdown Failed"); ++ test_wolfssl_ctx = NULL; ++ ++ wolfssl_shutdown = 1; ++ if (test_wolfssl_ctx) { ++ wolfSSL_CTX_free(test_wolfssl_ctx); ++ test_wolfssl_ctx = NULL; ++ } + #endif + } + +@@ -315,23 +610,43 @@ TEST_CASE("ssl_read", "[SSLRoutines][fdo]") + #ifdef USE_OPENSSL + int ret; + SSL *ssl = test_ssl_init(); +- if (ssl == NULL) +- goto err; +- char buf[20] = { +- 0, +- }; +- int num = 20; +- +- ret_read = 20; +- ret = fdo_ssl_read((void *)ssl, buf, num); +- TEST_ASSERT_EQUAL_MESSAGE(20, ret, "SSL read Failed"); +- +- /* Negative Test Cases */ +- ret_read = 0; +- ret = fdo_ssl_read((void *)ssl, buf, num); +- TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL read Failed"); +-err: +- cleanup_ssl_struct(ssl); ++ if (ssl != NULL) { ++ char buf[20] = { ++ 0, ++ }; ++ int num = 20; ++ ++ ret_read = 20; ++ ret = fdo_ssl_read((void *)ssl, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(20, ret, "SSL read Failed"); ++ ++ /* Negative Test Cases */ ++ ret_read = 0; ++ ret = fdo_ssl_read((void *)ssl, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL read Failed"); ++ cleanup_ssl_struct(ssl); ++ } ++#elif defined(USE_WOLFSSL) ++ int ret; ++ WOLFSSL *ssl = test_wolfssl_init(); ++ TEST_ASSERT_NOT_NULL_MESSAGE(ssl, "test_wolfssl_init failed"); ++ if (ssl != NULL) { ++ void *session = wrap_wolfssl_session(ssl); ++ char buf[20] = { ++ 0, ++ }; ++ int num = 20; ++ ++ ret_read = 20; ++ ret = fdo_ssl_read(session, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(20, ret, "SSL read Failed"); ++ ++ /* Negative Test Cases */ ++ ret_read = 0; ++ ret = fdo_ssl_read(session, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL read Failed"); ++ cleanup_ssl_struct(session); ++ } + #endif + } + +@@ -349,18 +664,37 @@ TEST_CASE("ssl_write", "[SSLRoutines][fdo]") + int num = 20; + SSL *ssl = test_ssl_init(); + +- if (ssl == NULL) +- goto err; ++ if (ssl != NULL) { ++ ret_write = 20; ++ ret = fdo_ssl_write((void *)&ssl, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(20, ret, "SSL write Failed"); ++ ++ /* Negative Test Cases */ ++ ret_write = 0; ++ ret = fdo_ssl_write((void *)&ssl, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL write Failed"); ++ cleanup_ssl_struct(ssl); ++ } ++#elif defined(USE_WOLFSSL) ++ int ret; ++ char buf[20] = { ++ 0, ++ }; ++ int num = 20; ++ WOLFSSL *ssl = test_wolfssl_init(); ++ TEST_ASSERT_NOT_NULL_MESSAGE(ssl, "test_wolfssl_init failed"); ++ if (ssl != NULL) { ++ void *session = wrap_wolfssl_session(ssl); + +- ret_write = 20; +- ret = fdo_ssl_write((void *)&ssl, buf, num); +- TEST_ASSERT_EQUAL_MESSAGE(20, ret, "SSL write Failed"); ++ ret_write = 20; ++ ret = fdo_ssl_write(session, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(20, ret, "SSL write Failed"); + +- /* Negative Test Cases */ +- ret_write = 0; +- ret = fdo_ssl_write((void *)&ssl, buf, num); +- TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL write Failed"); +-err: +- cleanup_ssl_struct(ssl); ++ /* Negative Test Cases */ ++ ret_write = 0; ++ ret = fdo_ssl_write(session, buf, num); ++ TEST_ASSERT_EQUAL_MESSAGE(-1, ret, "-ve:1 SSL write Failed"); ++ cleanup_ssl_struct(session); ++ } + #endif + } +diff --git a/tests/unit/test_bn_support.c b/tests/unit/test_bn_support.c +index c0dbe62..679a4f9 100644 +--- a/tests/unit/test_bn_support.c ++++ b/tests/unit/test_bn_support.c +@@ -51,14 +51,35 @@ bool simul_crypto_hal_random_bytes = false; + /*** Unity Declarations ***/ + void set_up(void); + void tear_down(void); ++#ifndef USE_WOLFSSL + int __wrap_BN_num_bits(const bignum_t *a); + fdo_byte_array_t *__wrap_fdo_byte_array_alloc(int byte_sz); + bignum_t *__wrap_BN_bin2bn(const unsigned char *s, int len, bignum_t *ret); + int __wrap_BN_bn2bin(const bignum_t *a, unsigned char *to); + int __wrap_BN_mod_exp(bignum_t *r, bignum_t *a, const bignum_t *p, +- const bignum_t *m, BN_CTX *ctx); ++ const bignum_t *m, bn_ctx_t *ctx); + int __wrap_crypto_hal_random_bytes(const uint8_t *rand_data, size_t num_bytes); + int __wrap_BN_rand(BIGNUM *rnd, int bits, int top, int bottom); ++#else ++fdo_byte_array_t *__wrap_fdo_byte_array_alloc(int byte_sz); ++int __wrap_crypto_hal_random_bytes(const uint8_t *rand_data, size_t num_bytes); ++/* Wraps wolfSSL's SP (single-precision) or normal math backend based on ++ * WOLFSSL_MP_IS_SP_ALIAS (detected by CMakeLists.txt), as -Wl,-wrap needs ++ * the exact symbol name (sp_* vs mp_*). ++ */ ++#ifdef WOLFSSL_MP_IS_SP_ALIAS ++int __wrap_sp_unsigned_bin_size(const bignum_t *a); ++int __wrap_sp_read_unsigned_bin(bignum_t *a, const unsigned char *b, word32 c); ++int __wrap_sp_to_unsigned_bin(const bignum_t *a, unsigned char *b); ++int __wrap_sp_exptmod(const bignum_t *g, const bignum_t *x, const bignum_t *p, ++ bignum_t *y); ++#else ++int __wrap_mp_unsigned_bin_size(const bignum_t *a); ++int __wrap_mp_read_unsigned_bin(bignum_t *a, const unsigned char *b, int c); ++int __wrap_mp_to_unsigned_bin(const bignum_t *a, unsigned char *b); ++int __wrap_mp_exptmod(bignum_t *g, bignum_t *x, bignum_t *p, bignum_t *y); ++#endif ++#endif + void test_bn_bin2bn(void); + void test_bn_bn2bin(void); + void test_bn_rand(void); +@@ -86,7 +107,31 @@ void tear_down(void) + #endif + /*** Wrapper functions (function stubbing). ***/ + +-#ifdef USE_MBEDTLS ++#if defined(USE_WOLFSSL) && defined(WOLFSSL_MP_IS_SP_ALIAS) ++ ++/* Wraps wolfCrypt's sp_unsigned_bin_size() (SP-math alias). */ ++int __real_sp_unsigned_bin_size(const bignum_t *a); ++int __wrap_sp_unsigned_bin_size(const bignum_t *a) ++{ ++ if (simul_bn_mbedtls_mpi_size) ++ return sizeof(tab_8); ++ else ++ return __real_sp_unsigned_bin_size(a); ++} ++ ++#elif defined(USE_WOLFSSL) ++ ++/* Wraps wolfCrypt's mp_unsigned_bin_size() (classic math backend). */ ++int __real_mp_unsigned_bin_size(const bignum_t *a); ++int __wrap_mp_unsigned_bin_size(const bignum_t *a) ++{ ++ if (simul_bn_mbedtls_mpi_size) ++ return sizeof(tab_8); ++ else ++ return __real_mp_unsigned_bin_size(a); ++} ++ ++#elif defined(USE_MBEDTLS) + + /* Needed by bn_bn2bin */ + int __real_mbedtls_mpi_size(const bignum_t *a); +@@ -143,7 +188,65 @@ fdo_byte_array_t *__wrap_fdo_byte_array_alloc(int byte_sz) + return a; + } + +-#ifdef USE_MBEDTLS ++#if defined(USE_WOLFSSL) && defined(WOLFSSL_MP_IS_SP_ALIAS) ++ ++/* Wraps wolfCrypt's sp_read/to_unsigned_bin() (SP-math alias). */ ++int __real_sp_read_unsigned_bin(bignum_t *a, const unsigned char *b, word32 c); ++int __wrap_sp_read_unsigned_bin(bignum_t *a, const unsigned char *b, word32 c) ++{ ++ if (real_bin2bn_enabled) ++ return __real_sp_read_unsigned_bin(a, b, c); ++ if (simul_bn_bin2bn_error) { ++ return -1; ++ } else { ++ /* Success */ ++ return 0; ++ } ++} ++ ++int __real_sp_to_unsigned_bin(const bignum_t *a, unsigned char *b); ++int __wrap_sp_to_unsigned_bin(const bignum_t *a, unsigned char *b) ++{ ++ if (real_bn2bin_enabled) ++ return __real_sp_to_unsigned_bin(a, b); ++ if (simul_out_of_mem || simul_bn_bn2bin_error) { ++ return -1; ++ } else { ++ /* Success */ ++ return 0; ++ } ++} ++ ++#elif defined(USE_WOLFSSL) ++ ++/* Wraps wolfCrypt's mp_read/to_unsigned_bin() (classic math backend). */ ++int __real_mp_read_unsigned_bin(bignum_t *a, const unsigned char *b, int c); ++int __wrap_mp_read_unsigned_bin(bignum_t *a, const unsigned char *b, int c) ++{ ++ if (real_bin2bn_enabled) ++ return __real_mp_read_unsigned_bin(a, b, c); ++ if (simul_bn_bin2bn_error) { ++ return -1; ++ } else { ++ /* Success */ ++ return 0; ++ } ++} ++ ++int __real_mp_to_unsigned_bin(const bignum_t *a, unsigned char *b); ++int __wrap_mp_to_unsigned_bin(const bignum_t *a, unsigned char *b) ++{ ++ if (real_bn2bin_enabled) ++ return __real_mp_to_unsigned_bin(a, b); ++ if (simul_out_of_mem || simul_bn_bn2bin_error) { ++ return -1; ++ } else { ++ /* Success */ ++ return 0; ++ } ++} ++ ++#elif defined(USE_MBEDTLS) + + /* Needed by bn_bin2bn */ + int __wrap_mbedtls_mpi_read_binary(bignum_t *n, const unsigned char *s, int len) +@@ -199,9 +302,40 @@ int __wrap_BN_bn2bin(const bignum_t *a, unsigned char *to) + #endif /* USE_OPENSSL */ + + /* Needed for bn_mod_exp */ +-#ifdef USE_MBEDTLS ++#if defined(USE_WOLFSSL) && defined(WOLFSSL_MP_IS_SP_ALIAS) ++/* Wraps wolfCrypt's sp_exptmod() (SP-math alias). */ ++int __wrap_sp_exptmod(const bignum_t *g, const bignum_t *x, const bignum_t *p, ++ bignum_t *y) ++{ ++ (void)g; ++ (void)x; ++ (void)p; ++ (void)y; ++ if (simul_bn_mod_exp_error) { ++ return -1; ++ } ++ ++ /* Success */ ++ return 0; ++} ++#elif defined(USE_WOLFSSL) ++/* Wraps wolfCrypt's mp_exptmod() (classic math backend). */ ++int __wrap_mp_exptmod(bignum_t *g, bignum_t *x, bignum_t *p, bignum_t *y) ++{ ++ (void)g; ++ (void)x; ++ (void)p; ++ (void)y; ++ if (simul_bn_mod_exp_error) { ++ return -1; ++ } ++ ++ /* Success */ ++ return 0; ++} ++#elif defined(USE_MBEDTLS) + int __wrap_mbedtls_mpi_exp_mod(bignum_t *r, bignum_t *a, const bignum_t *p, +- const bignum_t *m, BN_CTX *ctx) ++ const bignum_t *m, bn_ctx_t *ctx) + { + if (simul_bn_mod_exp_error) { + return MBEDTLS_ERR_MPI_ALLOC_FAILED; +@@ -212,7 +346,7 @@ int __wrap_mbedtls_mpi_exp_mod(bignum_t *r, bignum_t *a, const bignum_t *p, + } + #else /* USE_OPENSSL */ + int __wrap_BN_mod_exp(bignum_t *r, bignum_t *a, const bignum_t *p, +- const bignum_t *m, BN_CTX *ctx) ++ const bignum_t *m, bn_ctx_t *ctx) + { + (void)r; + (void)a; +@@ -373,7 +507,7 @@ TEST_CASE("bn_mod_exp", "[bn_support][fdo]") + { + simul_bn_mbedtls_mpi_size = true; + int ret; +- BN_CTX *ctx = NULL; ++ bn_ctx_t *ctx = NULL; + bignum_t *r = NULL, *a = NULL, *p = NULL, *m = NULL; + + /* Error case. */ +diff --git a/tests/unit/test_crypto.h b/tests/unit/test_crypto.h +index 3d03b5a..63e38f5 100644 +--- a/tests/unit/test_crypto.h ++++ b/tests/unit/test_crypto.h +@@ -1,4 +1,31 @@ ++/* ++ * Shared home for backend-specific crypto/SSL headers needed across the ++ * unit tests. Test .c files should include only this file to prevent ++ * Unity's generate_test_runner.rb from flattening incompatible #includes ++ * together into the generated runner. ++ */ + #ifdef USE_OPENSSL + #include + #include ++#include ++#include ++#include ++#include ++#include ++#include ++#elif defined(USE_WOLFSSL) ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#if defined(FDO_TPM_STACK_WOLFTPM) ++#include "wolftpm_utils.h" ++#include "fdo_tpm_handles.h" ++#endif + #endif +diff --git a/tests/unit/test_cryptoSupport.c b/tests/unit/test_cryptoSupport.c +index a4dbf5d..7025fd7 100644 +--- a/tests/unit/test_cryptoSupport.c ++++ b/tests/unit/test_cryptoSupport.c +@@ -18,14 +18,7 @@ + #include "ecdsa_privkey.h" + #include "safe_lib.h" + #include "fdotypes.h" +-#include "openssl/core_names.h" +-#include +-#include +-#include +-#include +-#include +-#include +-#include ++#include "test_crypto.h" + + #define PLAIN_TEXT_SIZE BUFF_SIZE_1K_BYTES + #define DER_PUBKEY_LEN_MAX 512 +@@ -60,10 +53,17 @@ uint8_t pub_key[] = { + 0x83, 0x7d, 0x3e, 0x31, 0xee, 0x11, 0x40, 0xa9}; + + /*** Function Declarations ***/ ++#ifdef USE_OPENSSL + EVP_PKEY *generateECDSA_key(int curve); + int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, + uint32_t *outlen, EVP_PKEY *eckey); + fdo_public_key_t *getFDOpk(int curve, EVP_PKEY *eckey); ++#elif defined(USE_WOLFSSL) ++ecc_key *generateECDSA_key(int curve, WC_RNG *rng); ++int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, ++ uint32_t *outlen, ecc_key *key, WC_RNG *rng); ++fdo_public_key_t *getFDOpk(int curve, ecc_key *key); ++#endif + void set_up(void); + void tear_down(void); + int32_t __wrap_crypto_hal_set_peer_random(void *context, +@@ -84,7 +84,9 @@ int __wrap_crypto_hal_sig_verify( + uint32_t key_param1Length, const uint8_t *key_param2, + uint32_t key_param2Length); + // int __wrap_get_ec_key(void); ++#ifdef USE_OPENSSL + int __wrap_ECDSA_size(const EC_KEY *eckey); ++#endif + int __wrap_memcpy_s(void *dest, size_t dmax, const void *src, size_t smax); + void test_crypto_support_random(void); + void test_crypto_support_Private_key(void); +@@ -146,6 +148,12 @@ void test_memcpy_s_fail_case(void); + void test_crypto_support_make_hash(void); + void test_crypto_support_make_hmac(void); + void test_crypto_support_make_hmac_chained(void); ++void test_crypto_support_inc_rollover_ctr_basic(void); ++void test_crypto_support_inc_rollover_ctr_carry(void); ++void test_crypto_support_inc_rollover_ctr_overflow(void); ++void test_crypto_support_inc_rollover_ctr_rollover_rejected(void); ++void test_crypto_support_inc_rollover_ctr_invalid_params(void); ++void test_crypto_support_inc_rollover_ctr_rollover_rejected_inc2(void); + int32_t __wrap_fdo_blob_read(char *name, fdo_sdk_blob_flags flags, uint8_t *buf, + uint32_t n_bytes); + int32_t __wrap_fdo_blob_size(char *name, uint32_t flags); +@@ -229,6 +237,24 @@ static int Private_key(mbedtls_ecdsa_context *ctx_sign) + } + #endif + ++#ifdef USE_WOLFSSL ++static int Private_key(ecc_key *key, WC_RNG *rng) ++{ ++ int curve_id = ECC_SECP256R1; ++ ++#if !defined(ECDSA256_DA) ++ curve_id = ECC_SECP384R1; ++#endif ++ if (wc_InitRng(rng) != 0) { ++ return -1; ++ } ++ if (wc_ecc_init(key) != 0) { ++ return -1; ++ } ++ return wc_ecc_make_key_ex(rng, 0, key, curve_id); ++} ++#endif ++ + #ifdef USE_OPENSSL + EVP_PKEY *generateECDSA_key(int curve) + { +@@ -363,10 +389,7 @@ done: + EVP_MD_CTX_free(mdctx); + mdctx = NULL; + } +- if (evpKey) { +- EVP_PKEY_free(evpKey); +- evpKey = NULL; +- } ++ /* evpKey belongs to the caller, which frees it. */ + return result; + } + +@@ -429,10 +452,7 @@ fdo_public_key_t *getFDOpk(int curve, EVP_PKEY *evpKey) + if (y) { + BN_free(y); + } +- if (evpKey) { +- EVP_PKEY_free(evpKey); +- evpKey = NULL; +- } ++ /* evpKey belongs to the caller, which frees it. */ + return pk; + } + #endif // USE_OPENSSL +@@ -561,6 +581,103 @@ fdo_public_key_t *getFDOpk(int curve, mbedtls_ecdsa_context *ctx_sign) + #endif // PK_ENC_ECDSA + #endif // USE_MBEDTLS + ++#ifdef USE_WOLFSSL ++ecc_key *generateECDSA_key(int curve, WC_RNG *rng) ++{ ++ int curve_id; ++ ecc_key *key = fdo_alloc(sizeof(ecc_key)); ++ ++ if (!key) { ++ return NULL; ++ } ++ curve_id = (curve == 256) ? ECC_SECP256R1 : ECC_SECP384R1; ++ if (wc_InitRng(rng) != 0 || wc_ecc_init(key) != 0 || ++ wc_ecc_make_key_ex(rng, 0, key, curve_id) != 0) { ++ fdo_free(key); ++ return NULL; ++ } ++ return key; ++} ++ ++/* Returns 1 on success, 0/-1 on failure. Produces a raw r||s signature ++ * (not DER), as crypto_hal_sig_verify() expects for this backend. */ ++int sha_ECCsign(int curve, uint8_t *msg, uint32_t mlen, uint8_t *out, ++ uint32_t *outlen, ecc_key *key, WC_RNG *rng) ++{ ++ uint8_t hash[WC_SHA512_DIGEST_SIZE] = {0}; ++ size_t hash_length = ++ (curve == 256) ? SHA256_DIGEST_SIZE : SHA384_DIGEST_SIZE; ++ mp_int r, s; ++ int result = -1; ++ int coord = wc_ecc_size(key); ++ int ret; ++ ++ if (curve == 256) { ++ ret = wc_Sha256Hash((const byte *)msg, mlen, hash); ++ } else { ++ ret = wc_Sha384Hash((const byte *)msg, mlen, hash); ++ } ++ if (ret != 0) { ++ goto done; ++ } ++ ++ mp_init(&r); ++ mp_init(&s); ++ if (wc_ecc_sign_hash_ex(hash, (word32)hash_length, rng, key, &r, &s) != ++ 0) { ++ mp_clear(&r); ++ mp_clear(&s); ++ goto done; ++ } ++ ++ /* Pad r and s to the coordinate size: mp_to_unsigned_bin() strips ++ * leading zeros, which would misplace s and give an odd length. */ ++ if (coord <= 0 || mp_to_unsigned_bin_len(&r, out, coord) != MP_OKAY || ++ mp_to_unsigned_bin_len(&s, out + coord, coord) != MP_OKAY) { ++ mp_clear(&r); ++ mp_clear(&s); ++ goto done; ++ } ++ *outlen = (uint32_t)(2 * coord); ++ mp_clear(&r); ++ mp_clear(&s); ++ result = 1; ++ ++done: ++ /* NOTE: `key` is not freed here; caller retains ownership for getFDOpk(). */ ++ return result; ++} ++ ++fdo_public_key_t *getFDOpk(int curve, ecc_key *key) ++{ ++ unsigned char key_buf[DER_PUBKEY_LEN_MAX]; ++ int key_buf_len; ++ fdo_public_key_t *pk = NULL; ++ ++ /* X509 encoding means a DER SubjectPublicKeyInfo, which is what ++ * crypto_hal_sig_verify() decodes. */ ++ key_buf_len = wc_EccPublicKeyToDer(key, key_buf, sizeof(key_buf), 1); ++ if (key_buf_len <= 0) { ++ return NULL; ++ } ++ ++ if (curve == 256) { ++ pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp256, ++ FDO_CRYPTO_PUB_KEY_ENCODING_X509, ++ key_buf_len, key_buf); ++ } else { ++ pk = fdo_public_key_alloc(FDO_CRYPTO_PUB_KEY_ALGO_ECDSAp384, ++ FDO_CRYPTO_PUB_KEY_ENCODING_X509, ++ key_buf_len, key_buf); ++ } ++ if (!pk || !pk->key1) { ++ return NULL; ++ } ++ pk->key2 = NULL; ++ return pk; ++} ++#endif // USE_WOLFSSL ++ + #define SHA256_DIGEST_SZ SHA256_DIGEST_SIZE + #define SHA384_DIGEST_SZ SHA384_DIGEST_SIZE + #define TEST_BUFF_SZ BUFF_SIZE_8_BYTES // random buffer +@@ -801,6 +918,10 @@ TEST_CASE("crypto_support_random", "[crypto_support][fdo]") + ret = random_init(); + TEST_ASSERT_EQUAL_INT(0, ret); + ++ /* random_init() must be safe to call multiple times */ ++ ret = random_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + /* Valid input. */ + ret = fdo_crypto_random_bytes(random_data, TEST_BUFF_SZ); + TEST_ASSERT_EQUAL_INT(0, ret); +@@ -812,6 +933,11 @@ TEST_CASE("crypto_support_random", "[crypto_support][fdo]") + /* End. */ + ret = random_close(); + TEST_ASSERT_EQUAL_INT(0, ret); ++ ++ /* A second random_close() without an intervening random_init() must ++ * fail rather than silently no-op. */ ++ ret = random_close(); ++ TEST_ASSERT_NOT_EQUAL(0, ret); + #ifdef TARGET_OS_FREERTOS + simulcrypto_hal_random_bytes = false; + #endif +@@ -844,80 +970,46 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") + TEST_ASSERT_EQUAL(0, ret); + privatekey_buflen = mbedtls_mpi_size(&ctx_sign.d); + #endif ++ ++#ifdef USE_WOLFSSL ++ ecc_key wolfssl_key; ++ WC_RNG wolfssl_rng; ++ ret = Private_key(&wolfssl_key, &wolfssl_rng); ++ TEST_ASSERT_EQUAL(0, ret); ++ privatekey_buflen = wc_ecc_size(&wolfssl_key); ++#endif + uint8_t *privatekey = fdo_alloc(privatekey_buflen); + TEST_ASSERT_NOT_NULL(privatekey); +- memset_s(privatekey, 0, privatekey_buflen); ++ memset_s(privatekey, privatekey_buflen, 0); + + // store private key for later use in pem /bin format + #if defined(ECDSA_PEM) ++#if defined(USE_WOLFSSL) ++ unsigned char der_buf[256]; ++ unsigned char pem_buf[512]; ++ int der_len = wc_EccKeyToDer(&wolfssl_key, der_buf, sizeof(der_buf)); ++ TEST_ASSERT_TRUE(der_len > 0); ++ int pem_len = wc_DerToPem(der_buf, (word32)der_len, pem_buf, ++ sizeof(pem_buf), ECC_PRIVATEKEY_TYPE); ++ TEST_ASSERT_TRUE(pem_len > 0); ++ ret = fdo_blob_write((char *)ECDSA_PRIVKEY, FDO_SDK_RAW_DATA, ++ pem_buf, pem_len); ++ TEST_ASSERT_NOT_EQUAL(-1, ret); ++#else ++ /* Store the key generated above. */ + BIO *outbio = BIO_new(BIO_s_mem()); + TEST_ASSERT_NOT_NULL(outbio); +- EVP_PKEY *privkey = EVP_PKEY_new(); +- TEST_ASSERT_NOT_NULL(privkey); +- +- BIGNUM *priv; +- OSSL_PARAM_BLD *param_bld; +- OSSL_PARAM *params = NULL; +- EVP_PKEY_CTX *ctx; +- +- priv = BN_bin2bn(privatekey, privatekey_buflen, NULL); +- param_bld = OSSL_PARAM_BLD_new(); +- +- if (priv != NULL && param_bld != NULL && +- OSSL_PARAM_BLD_push_utf8_string(param_bld, "group", "prime256v1", +- 0) && +- OSSL_PARAM_BLD_push_BN(param_bld, "priv", priv) && +- OSSL_PARAM_BLD_push_octet_string(param_bld, "pub", NULL, 0)) { +- params = OSSL_PARAM_BLD_to_param(param_bld); +- } +- +- ctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL); +- +- if (ctx == NULL || params == NULL || EVP_PKEY_fromdata_init(ctx) <= 0 || +- EVP_PKEY_fromdata(ctx, &privkey, EVP_PKEY_KEYPAIR, params) <= 0) { +- exit(1); +- } +- +- size_t group_name_size; +- char group_name[64]; +- +- EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, +- NULL, 0, &group_name_size); +- if (group_name_size >= sizeof(group_name)) { +- LOG(LOG_ERROR, "Unexpected long group name : %zu for EC key\n", +- group_name_size); +- exit(1); +- } +- +- if (!EVP_PKEY_get_utf8_string_param(privkey, OSSL_PKEY_PARAM_GROUP_NAME, +- group_name, sizeof(group_name), +- &group_name_size)) { +- LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); +- exit(1); +- } +- +- int group_nid = OBJ_sn2nid(group_name); +- const EC_GROUP *group = EC_GROUP_new_by_curve_name(group_nid); +- +- if (group == NULL) { +- LOG(LOG_ERROR, "Failed to get the group name fo EC EVP key\n"); +- exit(1); +- } +- +- if (!PEM_write_bio_Parameters(outbio, privkey)) { +- BIO_printf(outbio, "Error writing parameters in PEM format"); +- } +- +- if(PEM_write_bio_PrivateKey(outbio, privkey, NULL, NULL, 0, 0, NULL) == 0) { +- BIO_printf(outbio, "Error writing private key data in PEM format"); +- } ++ TEST_ASSERT_EQUAL(1, PEM_write_bio_PrivateKey(outbio, validkey, NULL, ++ NULL, 0, NULL, NULL)); + + BUF_MEM *bptr = NULL; + BIO_get_mem_ptr(outbio, &bptr); +- ++ TEST_ASSERT_NOT_NULL(bptr); + ret = fdo_blob_write((char *)ECDSA_PRIVKEY, FDO_SDK_RAW_DATA, + (const uint8_t *)bptr->data, bptr->length); + TEST_ASSERT_NOT_EQUAL(-1, ret); ++ BIO_free(outbio); ++#endif // USE_WOLFSSL + + #else + +@@ -929,12 +1021,24 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") + ret = -1; + } + +- if (BN_bn2bin(privkey_bn, privatekey)) ++ /* Fixed width: BN_bn2bin() drops leading zero bytes. */ ++ if (BN_bn2binpad(privkey_bn, privatekey, privatekey_buflen) == ++ privatekey_buflen) + ret = 0; ++ BN_clear_free(privkey_bn); + #endif + #ifdef USE_MBEDTLS + ret = mbedtls_mpi_write_binary(&ctx_sign.d, privatekey, + privatekey_buflen); ++#endif ++#ifdef USE_WOLFSSL ++ word32 wolfssl_privatekey_len = (word32)privatekey_buflen; ++ if (wc_ecc_export_private_only(&wolfssl_key, privatekey, ++ &wolfssl_privatekey_len) == 0) { ++ ret = 0; ++ } else { ++ ret = -1; ++ } + #endif + TEST_ASSERT_EQUAL(0, ret); + +@@ -945,19 +1049,15 @@ TEST_CASE("crypto_support_Private_key", "[crypto_support][fdo]") + #endif + + #ifdef USE_OPENSSL +-#if defined(ECDSA_PEM) +- EVP_PKEY_free(privkey); +- EVP_PKEY_CTX_free(ctx); +- BIO_free_all(outbio); +- OSSL_PARAM_free(params); +- OSSL_PARAM_BLD_free(param_bld); +- BN_free(priv); +-#endif + if (validkey) + EVP_PKEY_free(validkey); + #endif + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&ctx_sign); ++#endif ++#ifdef USE_WOLFSSL ++ wc_ecc_free(&wolfssl_key); ++ wc_FreeRng(&wolfssl_rng); + #endif + fdo_free(privatekey); + } +@@ -980,9 +1080,25 @@ TEST_CASE("crypto_support_crypto", "[crypto_support][fdo]") + ret = fdo_crypto_init(); + TEST_ASSERT_EQUAL_INT(0, ret); + ++ /* fdo_crypto_init() must be safe to call multiple times: calling it again while ++ * already initialized should succeed without side effects. */ ++ ret = fdo_crypto_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ ++ /* fdo_crypto_init() alone (without a separate random_init() call) ++ * must be sufficient for fdo_crypto_random_bytes() to succeed. */ ++ uint8_t random_data[TEST_BUFF_SZ] = {0}; ++ ret = fdo_crypto_random_bytes(random_data, TEST_BUFF_SZ); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + /* End. */ + ret = fdo_crypto_close(); + TEST_ASSERT_EQUAL_INT(0, ret); ++ ++ /* A second fdo_crypto_close() without an intervening fdo_crypto_init() ++ * must fail rather than silently no-op. */ ++ ret = fdo_crypto_close(); ++ TEST_ASSERT_NOT_EQUAL(0, ret); + } + + #ifndef TARGET_OS_FREERTOS +@@ -1346,6 +1462,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_verify", "[crypto_support][fdo]") + uint8_t *tag = NULL; + uint8_t *aad = NULL; + ++ ret = fdo_kex_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + ret = fdo_msg_encrypt_get_cipher_len(clear_length, &cipher_length); + TEST_ASSERT_EQUAL_INT(0, ret); + cipher = fdo_alloc(cipher_length * sizeof(char)); +@@ -1376,6 +1495,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_verify", "[crypto_support][fdo]") + TEST_ASSERT_EQUAL_MESSAGE(0, result_memcmp, + "Decrypted doesn't match with cleartxt"); + ++ ret = fdo_kex_close(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + if (cipher) { + fdo_free(cipher); + } +@@ -1400,6 +1522,8 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_valid", "[crypto_support][fdo]") + #endif + { + int ret = -1; ++ ret = fdo_kex_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); + uint8_t *cipher = NULL; + uint8_t *decrypted_txt = NULL; + uint32_t cipher_length = 0; +@@ -1434,6 +1558,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_valid", "[crypto_support][fdo]") + cipher_length, iv1, tag, AES_TAG_LEN, aad, 16); + TEST_ASSERT_EQUAL_INT(0, ret); + ++ ret = fdo_kex_close(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + if (cipher) { + fdo_free(cipher); + } +@@ -1459,6 +1586,8 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_cipher", + #endif + { + int ret = -1; ++ ret = fdo_kex_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); + uint8_t *cipher = NULL; + uint8_t *decrypted_txt = NULL; + uint32_t cipher_length = 0; +@@ -1493,6 +1622,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_cipher", + cipher_length, iv1, tag, AES_TAG_LEN, aad, 16); + TEST_ASSERT_EQUAL_INT(-1, ret); + ++ ret = fdo_kex_close(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + if (cipher) { + fdo_free(cipher); + } +@@ -1518,6 +1650,8 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_cipher_length", + #endif + { + int ret = -1; ++ ret = fdo_kex_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); + uint8_t *cipher = NULL; + uint8_t *decrypted_txt = NULL; + uint32_t cipher_length = 0; +@@ -1552,6 +1686,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_cipher_length", + tag, AES_TAG_LEN, aad, 16); + TEST_ASSERT_EQUAL_INT(-1, ret); + ++ ret = fdo_kex_close(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + if (cipher) { + fdo_free(cipher); + } +@@ -1631,6 +1768,8 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_tag", "[crypto_support][fdo]") + #endif + { + int ret = -1; ++ ret = fdo_kex_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); + uint8_t *cipher = NULL; + uint8_t *decrypted_txt = NULL; + uint32_t cipher_length = 0; +@@ -1667,6 +1806,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_tag", "[crypto_support][fdo]") + cipher_length, iv1, tag, AES_TAG_LEN, aad, 16); + TEST_ASSERT_EQUAL_INT(-1, ret); + ++ ret = fdo_kex_close(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + if (cipher) { + fdo_free(cipher); + } +@@ -1688,6 +1830,8 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_aad", "[crypto_support][fdo]") + #endif + { + int ret = -1; ++ ret = fdo_kex_init(); ++ TEST_ASSERT_EQUAL_INT(0, ret); + uint8_t *cipher = NULL; + uint8_t *decrypted_txt = NULL; + uint32_t cipher_length = 0; +@@ -1725,6 +1869,9 @@ TEST_CASE("crypto_support_fdo_msg_decrypt_invalid_aad", "[crypto_support][fdo]") + cipher_length, iv1, tag, AES_TAG_LEN, aad, 16); + TEST_ASSERT_EQUAL_INT(-1, ret); + ++ ret = fdo_kex_close(); ++ TEST_ASSERT_EQUAL_INT(0, ret); ++ + if (cipher) { + fdo_free(cipher); + } +@@ -1965,6 +2112,11 @@ TEST_CASE("fdo_ov_verify", "[crypto_support][fdo]") + bool *result = &val; + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; ++#ifdef USE_WOLFSSL ++ /* Test is currently ignored (TODO above). Suppress unused warnings. */ ++ (void)curve; ++ (void)message; ++#endif + + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) +@@ -2051,6 +2203,9 @@ TEST_CASE("fdo_ov_verify", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++ /* USE_WOLFSSL: nothing to free here - this whole test is ++ * TEST_IGNORE()'d above, no wolfSSL key was ever generated. ++ */ + + if (message_signature) { + fdo_free(message_signature); +@@ -2085,6 +2240,22 @@ TEST_CASE("fdo_ov_verify_invalid_message", "[crypto_support][fdo]") + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -2164,6 +2335,13 @@ TEST_CASE("fdo_ov_verify_invalid_message", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -2196,6 +2374,22 @@ TEST_CASE("fdo_ov_verify_invalid_message_length", "[crypto_support][fdo]") + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -2275,6 +2469,13 @@ TEST_CASE("fdo_ov_verify_invalid_message_length", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -2307,6 +2508,22 @@ TEST_CASE("fdo_ov_verify_invalid_message_signature", "[crypto_support][fdo]") + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -2386,6 +2603,13 @@ TEST_CASE("fdo_ov_verify_invalid_message_signature", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -2418,6 +2642,22 @@ TEST_CASE("fdo_ov_verify_invalid_signature_len", "[crypto_support][fdo]") + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -2497,6 +2737,13 @@ TEST_CASE("fdo_ov_verify_invalid_signature_len", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -2529,6 +2776,31 @@ TEST_CASE("fdo_ov_verify_invalid_pubkey", "[crypto_support][fdo]") + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++ ++ /* Positive control: the same signature verifies with the real key, ++ * so the NULL-key failure below is down to the key alone. */ ++ ret = fdo_ov_verify(message, message_length, message_signature, ++ signature_len, pubkey, result); ++ TEST_ASSERT_EQUAL(0, ret); ++ TEST_ASSERT_TRUE(*result); ++ fdo_public_key_free(pubkey); ++ pubkey = NULL; ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -2607,6 +2879,13 @@ TEST_CASE("fdo_ov_verify_invalid_pubkey", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -2637,6 +2916,22 @@ TEST_CASE("fdo_ov_verify_invalid_result", "[crypto_support][fdo]") + bool *result = NULL; + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -2718,6 +3013,13 @@ TEST_CASE("fdo_ov_verify_invalid_result", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -2955,6 +3257,12 @@ TEST_CASE("fdo_device_ov_hmac", "[crypto_support][fdo]") + TEST_ASSERT_EQUAL(0, ret); + ret = set_ov_key(OVkey, OVKey_len); + TEST_ASSERT_EQUAL(0, ret); ++#if defined(DEVICE_TPM20_ENABLED) ++ /* With a TPM DA the OV HMAC key lives in the TPM and is normally ++ * created during DI; create it here. */ ++ ret = fdo_generate_ov_hmac_key(); ++ TEST_ASSERT_EQUAL(0, ret); ++#endif + ret = fdo_device_ov_hmac(OVHdr, OVHdr_len, hmac, hmac_len, false); + TEST_ASSERT_EQUAL(0, ret); + +@@ -3117,6 +3425,22 @@ TEST_CASE("crypto_hal_sig_verify_fail_case", "[crypto_support][fdo]") + TEST_ASSERT_NOT_NULL(result); + fdo_public_key_t *pubkey = NULL; + ++#ifdef USE_WOLFSSL ++#if defined(ECDSA256_DA) ++ curve = 256; ++#else ++ curve = 384; ++#endif ++ WC_RNG wolfssl_ov_rng; ++ ecc_key *wolfssl_ov_validkey = generateECDSA_key(curve, &wolfssl_ov_rng); ++ TEST_ASSERT_NOT_NULL(wolfssl_ov_validkey); ++ ret = sha_ECCsign(curve, message, message_length, message_signature, ++ &signature_len, wolfssl_ov_validkey, &wolfssl_ov_rng); ++ TEST_ASSERT_EQUAL(1, ret); ++ pubkey = getFDOpk(curve, wolfssl_ov_validkey); ++ TEST_ASSERT_NOT_NULL(pubkey); ++#endif ++ + #ifdef USE_OPENSSL + #if defined(ECDSA256_DA) + curve = 256; +@@ -3197,6 +3521,13 @@ TEST_CASE("crypto_hal_sig_verify_fail_case", "[crypto_support][fdo]") + #ifdef USE_MBEDTLS + mbedtls_ecdsa_free(&validkey); + #endif ++#ifdef USE_WOLFSSL ++ if (pubkey) ++ fdo_public_key_free(pubkey); ++ wc_ecc_free(wolfssl_ov_validkey); ++ fdo_free(wolfssl_ov_validkey); ++ wc_FreeRng(&wolfssl_ov_rng); ++#endif + + if (message_signature) { + fdo_free(message_signature); +@@ -3215,6 +3546,9 @@ TEST_CASE("get_ec_key_fail_case", "[crypto_support][fdo]") + #endif + { + #ifdef USE_OPENSSL ++ /* fdo_device_sign() no longer calls get_ec_key(), so the injected ++ * failure is never reached. */ ++ TEST_IGNORE(); + int ret; + const uint8_t *message = test_buff1; + size_t message_len = sizeof(test_buff1); +@@ -3237,6 +3571,9 @@ TEST_CASE("ECDSA_size_fail_case", "[crypto_support][fdo]") + #endif + { + #ifdef USE_OPENSSL ++ /* fdo_device_sign() no longer calls ECDSA_size(), so the injected ++ * failure is never reached. */ ++ TEST_IGNORE(); + int ret; + const uint8_t *message = test_buff1; + size_t message_len = sizeof(test_buff1); +@@ -3494,3 +3831,124 @@ TEST_CASE("crypto_support_make_hmac_chained", "[crypto_support][fdo]") + fdo_hash_free(chain1); + fdo_crypto_close(); + } ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_support_inc_rollover_ctr_basic(void) ++#else ++TEST_CASE("crypto_support_inc_rollover_ctr_basic", "[crypto_support][fdo]") ++#endif ++{ ++ uint8_t first_iv[16] = {0}; ++ uint8_t new_iv[16] = {0}; ++ int ret; ++ ++ ret = inc_rollover_ctr(first_iv, new_iv, sizeof(new_iv), 1); ++ TEST_ASSERT_EQUAL(0, ret); ++ TEST_ASSERT_EQUAL_UINT8(1, new_iv[15]); ++ for (int i = 0; i < 15; i++) { ++ TEST_ASSERT_EQUAL_UINT8(0, new_iv[i]); ++ } ++} ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_support_inc_rollover_ctr_carry(void) ++#else ++TEST_CASE("crypto_support_inc_rollover_ctr_carry", "[crypto_support][fdo]") ++#endif ++{ ++ uint8_t first_iv[16] = {0}; ++ uint8_t new_iv[16] = {0}; ++ int ret; ++ ++ /* Least-significant byte is already at its max; incrementing must ++ * ripple the carry into the next byte instead of wrapping silently. ++ */ ++ new_iv[15] = 0xFF; ++ ++ ret = inc_rollover_ctr(first_iv, new_iv, sizeof(new_iv), 1); ++ TEST_ASSERT_EQUAL(0, ret); ++ TEST_ASSERT_EQUAL_UINT8(0, new_iv[15]); ++ TEST_ASSERT_EQUAL_UINT8(1, new_iv[14]); ++} ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_support_inc_rollover_ctr_overflow(void) ++#else ++TEST_CASE("crypto_support_inc_rollover_ctr_overflow", "[crypto_support][fdo]") ++#endif ++{ ++ uint8_t first_iv[16] = {0}; ++ uint8_t new_iv[16]; ++ int ret; ++ ++ /* IV is already all-0xFF; any increment must overflow past the top ++ * of the buffer and fail rather than silently wrap to all-zero. ++ */ ++ for (int i = 0; i < 16; i++) { ++ new_iv[i] = 0xFF; ++ } ++ ++ ret = inc_rollover_ctr(first_iv, new_iv, sizeof(new_iv), 1); ++ TEST_ASSERT_EQUAL(-1, ret); ++} ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_support_inc_rollover_ctr_rollover_rejected(void) ++#else ++TEST_CASE("crypto_support_inc_rollover_ctr_rollover_rejected", ++ "[crypto_support][fdo]") ++#endif ++{ ++ uint8_t first_iv[16] = {0}; ++ uint8_t new_iv[16] = {0}; ++ int ret; ++ ++ /* first_iv's value is 1; new_iv is one below it (0), so incrementing ++ * by 1 lands exactly back on first_iv - the unsupported roll-over ++ * case - without overflowing the buffer. ++ */ ++ first_iv[15] = 1; ++ ++ ret = inc_rollover_ctr(first_iv, new_iv, sizeof(new_iv), 1); ++ TEST_ASSERT_EQUAL(-1, ret); ++} ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_support_inc_rollover_ctr_invalid_params(void) ++#else ++TEST_CASE("crypto_support_inc_rollover_ctr_invalid_params", ++ "[crypto_support][fdo]") ++#endif ++{ ++ uint8_t first_iv[16] = {0}; ++ uint8_t new_iv[16] = {0}; ++ int ret; ++ ++ ret = inc_rollover_ctr(NULL, new_iv, sizeof(new_iv), 1); ++ TEST_ASSERT_EQUAL(-1, ret); ++ ++ ret = inc_rollover_ctr(first_iv, NULL, sizeof(new_iv), 1); ++ TEST_ASSERT_EQUAL(-1, ret); ++ ++ ret = inc_rollover_ctr(first_iv, new_iv, 0, 1); ++ TEST_ASSERT_EQUAL(-1, ret); ++} ++ ++#ifndef TARGET_OS_FREERTOS ++void test_crypto_support_inc_rollover_ctr_rollover_rejected_inc2(void) ++#else ++TEST_CASE("crypto_support_inc_rollover_ctr_rollover_rejected_inc2", ++ "[crypto_support][fdo]") ++#endif ++{ ++ uint8_t first_iv[16] = {0}; ++ uint8_t new_iv[16] = {0}; ++ int ret; ++ ++ if (sizeof(size_t) > 4) { ++ first_iv[15] = 1; ++ ++ ret = inc_rollover_ctr(first_iv, new_iv, sizeof(new_iv), (size_t)0x100000000ULL); ++ TEST_ASSERT_EQUAL(-1, ret); ++ } ++} +diff --git a/tests/unit/test_hal_os.c b/tests/unit/test_hal_os.c +index 14dc671..3e6ec31 100644 +--- a/tests/unit/test_hal_os.c ++++ b/tests/unit/test_hal_os.c +@@ -14,7 +14,6 @@ + #include "fdo_crypto_hal.h" + #include "fdoprotctx.h" + #include "rest_interface.h" +-#include + #include "safe_str_lib.h" + #include "unity.h" + #include "util.h" +@@ -254,13 +253,21 @@ void test_fdo_con_send_message(void) + { + uint8_t buf[42]; + ssize_t nbytes = 42; ++ char hdr_buf[64]; ++ char body_buf[64]; + curl = curl_easy_init(); + + // setup rest protocol + TEST_ASSERT_EQUAL_INT(0, fdo_con_setup(NULL, NULL, 0)); + ++ TEST_ASSERT_EQUAL_INT(-1, fdo_con_send_recv_message(0, 0, buf, nbytes, ++ false, NULL, 0, ++ NULL, 0)); ++ ++ // A capacity of zero must be rejected rather than overflowed. + TEST_ASSERT_EQUAL_INT( +- -1, fdo_con_send_recv_message(0, 0, buf, nbytes, NULL, NULL, NULL)); ++ -1, fdo_con_send_recv_message(0, 0, buf, nbytes, false, hdr_buf, 0, ++ body_buf, sizeof(body_buf))); + + // undo setup rest protocol + fdo_con_teardown(); +diff --git a/tests/unit/test_wolftpm_ECDSA_sign_routines.c b/tests/unit/test_wolftpm_ECDSA_sign_routines.c +new file mode 100644 +index 0000000..3946e70 +--- /dev/null ++++ b/tests/unit/test_wolftpm_ECDSA_sign_routines.c +@@ -0,0 +1,305 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Unit tests for crypto_hal_ecdsa_sign(). ++ */ ++ ++/* tpm2_types.h needs usleep(). */ ++ ++#include "util.h" ++#include "unity.h" ++ ++#if defined(TARGET_OS_LINUX) ++ ++#include ++ ++/* Prototype for tested function. */ ++int32_t crypto_hal_ecdsa_sign(const uint8_t *data, size_t data_len, ++ unsigned char *message_signature, ++ size_t *signature_length); ++ ++/*** Unity Declarations. ***/ ++void setUp(void); ++void tearDown(void); ++void test_crypto_hal_ecdsa_sign_null_params(void); ++void test_crypto_hal_ecdsa_sign_init_failure(void); ++void test_crypto_hal_ecdsa_sign_hashstart_failure(void); ++void test_crypto_hal_ecdsa_sign_hashfinish_failure(void); ++void test_crypto_hal_ecdsa_sign_readpublickey_failure(void); ++void test_crypto_hal_ecdsa_sign_signhash_failure(void); ++void test_crypto_hal_ecdsa_sign_buffer_too_small(void); ++void test_crypto_hal_ecdsa_sign_success(void); ++ ++/* Linker-wrapped mocks. */ ++int __wrap_wolfTPM2_Init(WOLFTPM2_DEV *dev, TPM2HalIoCb ioCb, void *userCtx); ++int __wrap_wolfTPM2_HashStart(WOLFTPM2_DEV *dev, WOLFTPM2_HASH *hash, ++ TPMI_ALG_HASH hashAlg, const byte *usageAuth, ++ word32 usageAuthSz); ++int __wrap_wolfTPM2_HashUpdate(WOLFTPM2_DEV *dev, WOLFTPM2_HASH *hash, ++ const byte *data, word32 dataSz); ++int __wrap_wolfTPM2_HashFinish(WOLFTPM2_DEV *dev, WOLFTPM2_HASH *hash, ++ byte *digest, word32 *digestSz); ++int __wrap_wolfTPM2_ReadPublicKey(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ const TPM_HANDLE handle); ++int __wrap_wolfTPM2_SignHashScheme(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ const byte *digest, int digestSz, byte *sig, ++ int *sigSz, TPMI_ALG_SIG_SCHEME sigAlg, ++ TPMI_ALG_HASH hashAlg); ++int __wrap_wolfTPM2_UnloadHandle(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *handle); ++int __wrap_wolfTPM2_Cleanup(WOLFTPM2_DEV *dev); ++ ++/* Mock control state, reset in setUp(). */ ++static int mock_init_rc; ++static int mock_hashstart_rc; ++static int mock_hashfinish_rc; ++static int mock_readpublickey_rc; ++static int mock_signhash_rc; ++static int mock_signhash_sz; ++static byte mock_sig_bytes[BUFF_SIZE_64_BYTES]; ++static int mock_hashstart_called; ++static int mock_hashfinish_called; ++static int mock_readpublickey_called; ++static int mock_signhash_called; ++ ++void setUp(void) ++{ ++ mock_init_rc = TPM_RC_SUCCESS; ++ mock_hashstart_rc = TPM_RC_SUCCESS; ++ mock_hashfinish_rc = TPM_RC_SUCCESS; ++ mock_readpublickey_rc = TPM_RC_SUCCESS; ++ mock_signhash_rc = TPM_RC_SUCCESS; ++ mock_signhash_sz = sizeof(mock_sig_bytes); ++ mock_hashstart_called = 0; ++ mock_hashfinish_called = 0; ++ mock_readpublickey_called = 0; ++ mock_signhash_called = 0; ++ memset(mock_sig_bytes, 0xAB, sizeof(mock_sig_bytes)); ++} ++ ++void tearDown(void) ++{ ++} ++ ++int __wrap_wolfTPM2_Init(WOLFTPM2_DEV *dev, TPM2HalIoCb ioCb, void *userCtx) ++{ ++ (void)dev; ++ (void)ioCb; ++ (void)userCtx; ++ return mock_init_rc; ++} ++ ++int __wrap_wolfTPM2_HashStart(WOLFTPM2_DEV *dev, WOLFTPM2_HASH *hash, ++ TPMI_ALG_HASH hashAlg, const byte *usageAuth, ++ word32 usageAuthSz) ++{ ++ (void)dev; ++ (void)hash; ++ (void)hashAlg; ++ (void)usageAuth; ++ (void)usageAuthSz; ++ mock_hashstart_called = 1; ++ return mock_hashstart_rc; ++} ++ ++int __wrap_wolfTPM2_HashUpdate(WOLFTPM2_DEV *dev, WOLFTPM2_HASH *hash, ++ const byte *data, word32 dataSz) ++{ ++ (void)dev; ++ (void)hash; ++ (void)data; ++ (void)dataSz; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_HashFinish(WOLFTPM2_DEV *dev, WOLFTPM2_HASH *hash, ++ byte *digest, word32 *digestSz) ++{ ++ (void)dev; ++ (void)hash; ++ mock_hashfinish_called = 1; ++ if (mock_hashfinish_rc != TPM_RC_SUCCESS) { ++ return mock_hashfinish_rc; ++ } ++ memset(digest, 0x11, *digestSz); ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_ReadPublicKey(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ const TPM_HANDLE handle) ++{ ++ (void)dev; ++ (void)handle; ++ mock_readpublickey_called = 1; ++ if (mock_readpublickey_rc == TPM_RC_SUCCESS) { ++ /* Real wolfTPM2_ReadPublicKey fills in the key's public ++ * area, including its algorithm type. Mirror that here so ++ * the type check in crypto_hal_ecdsa_sign() behaves as it ++ * would against a real ECC key. */ ++ key->pub.publicArea.type = TPM_ALG_ECC; ++ } ++ return mock_readpublickey_rc; ++} ++ ++int __wrap_wolfTPM2_SignHashScheme(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ const byte *digest, int digestSz, byte *sig, ++ int *sigSz, TPMI_ALG_SIG_SCHEME sigAlg, ++ TPMI_ALG_HASH hashAlg) ++{ ++ (void)dev; ++ (void)key; ++ (void)digest; ++ (void)digestSz; ++ mock_signhash_called = 1; ++ /* The scheme must be explicit, not taken from the key's details. */ ++ TEST_ASSERT_EQUAL(TPM_ALG_ECDSA, sigAlg); ++#if defined(ECDSA384_DA) ++ TEST_ASSERT_EQUAL(TPM_ALG_SHA384, hashAlg); ++#else ++ TEST_ASSERT_EQUAL(TPM_ALG_SHA256, hashAlg); ++#endif ++ if (mock_signhash_rc != TPM_RC_SUCCESS) { ++ return mock_signhash_rc; ++ } ++ TEST_ASSERT_TRUE(mock_signhash_sz <= *sigSz); ++ memcpy(sig, mock_sig_bytes, mock_signhash_sz); ++ *sigSz = mock_signhash_sz; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_UnloadHandle(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *handle) ++{ ++ (void)dev; ++ (void)handle; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_Cleanup(WOLFTPM2_DEV *dev) ++{ ++ (void)dev; ++ return TPM_RC_SUCCESS; ++} ++ ++void test_crypto_hal_ecdsa_sign_null_params(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ TEST_ASSERT_EQUAL(-1, crypto_hal_ecdsa_sign(NULL, sizeof(data), sig, ++ &sig_len)); ++ TEST_ASSERT_EQUAL(-1, crypto_hal_ecdsa_sign(data, 0, sig, &sig_len)); ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), NULL, &sig_len)); ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, NULL)); ++ TEST_ASSERT_FALSE(mock_hashstart_called); ++ TEST_ASSERT_FALSE(mock_readpublickey_called); ++ TEST_ASSERT_FALSE(mock_signhash_called); ++} ++ ++void test_crypto_hal_ecdsa_sign_init_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_init_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++ TEST_ASSERT_FALSE(mock_hashstart_called); ++ TEST_ASSERT_FALSE(mock_readpublickey_called); ++ TEST_ASSERT_FALSE(mock_signhash_called); ++} ++ ++void test_crypto_hal_ecdsa_sign_hashstart_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_hashstart_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++ TEST_ASSERT_TRUE(mock_hashstart_called); ++ /* Key type is validated before hashing, so ReadPublicKey runs first. */ ++ TEST_ASSERT_TRUE(mock_readpublickey_called); ++ TEST_ASSERT_FALSE(mock_signhash_called); ++} ++ ++void test_crypto_hal_ecdsa_sign_hashfinish_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_hashfinish_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++ TEST_ASSERT_TRUE(mock_hashfinish_called); ++ /* Key type is validated before hashing, so ReadPublicKey runs first. */ ++ TEST_ASSERT_TRUE(mock_readpublickey_called); ++ TEST_ASSERT_FALSE(mock_signhash_called); ++} ++ ++void test_crypto_hal_ecdsa_sign_readpublickey_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_readpublickey_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++ TEST_ASSERT_TRUE(mock_readpublickey_called); ++ TEST_ASSERT_FALSE(mock_signhash_called); ++} ++ ++void test_crypto_hal_ecdsa_sign_signhash_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_signhash_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++ TEST_ASSERT_TRUE(mock_signhash_called); ++} ++ ++/* Must reject signature larger than buffer. */ ++void test_crypto_hal_ecdsa_sign_buffer_too_small(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[8] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_signhash_sz = BUFF_SIZE_64_BYTES; ++ ++ TEST_ASSERT_EQUAL(-1, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++} ++ ++void test_crypto_hal_ecdsa_sign_success(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ unsigned char sig[BUFF_SIZE_64_BYTES] = {0}; ++ size_t sig_len = sizeof(sig); ++ ++ mock_signhash_sz = BUFF_SIZE_64_BYTES; ++ ++ TEST_ASSERT_EQUAL(0, ++ crypto_hal_ecdsa_sign(data, sizeof(data), sig, &sig_len)); ++ TEST_ASSERT_EQUAL(BUFF_SIZE_64_BYTES, sig_len); ++ TEST_ASSERT_EQUAL_UINT8_ARRAY(mock_sig_bytes, sig, BUFF_SIZE_64_BYTES); ++} ++ ++#endif /* TARGET_OS_LINUX */ +diff --git a/tests/unit/test_wolftpm_hmac.c b/tests/unit/test_wolftpm_hmac.c +new file mode 100644 +index 0000000..cc4cf07 +--- /dev/null ++++ b/tests/unit/test_wolftpm_hmac.c +@@ -0,0 +1,367 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Unit tests for wolftpm_hmac.c. ++ */ ++ ++#include "util.h" ++#include "unity.h" ++ ++#if defined(TARGET_OS_LINUX) ++ ++#include ++#include "fdo_tpm_handles.h" ++ ++/*** Unity Declarations. ***/ ++void setUp(void); ++void tearDown(void); ++void test_fdo_tpm_get_hmac_null_params(void); ++void test_fdo_tpm_get_hmac_readpublickey_failure(void); ++void test_fdo_tpm_get_hmac_hmacstart_failure(void); ++void test_fdo_tpm_get_hmac_hmacfinish_failure(void); ++void test_fdo_tpm_get_hmac_length_mismatch(void); ++void test_fdo_tpm_get_hmac_success(void); ++void test_fdo_tpm_generate_hmac_key_null_param(void); ++void test_fdo_tpm_generate_hmac_key_createsrk_failure(void); ++void test_fdo_tpm_generate_hmac_key_loadkey_failure(void); ++void test_fdo_tpm_generate_hmac_key_originates_in_tpm(void); ++void test_fdo_tpm_generate_hmac_key_deletes_existing(void); ++void test_fdo_tpm_generate_hmac_key_success_no_existing(void); ++ ++/* Prototypes for the linker-wrapped mocks. */ ++int __wrap_wolfTPM2_Init(WOLFTPM2_DEV *dev, TPM2HalIoCb ioCb, void *userCtx); ++int __wrap_wolfTPM2_ReadPublicKey(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ const TPM_HANDLE handle); ++int __wrap_wolfTPM2_HmacStart(WOLFTPM2_DEV *dev, WOLFTPM2_HMAC *hmac, ++ WOLFTPM2_HANDLE *parent, TPMI_ALG_HASH hashAlg, ++ const byte *keyBuf, word32 keySz, ++ const byte *usageAuth, word32 usageAuthSz); ++int __wrap_wolfTPM2_HmacUpdate(WOLFTPM2_DEV *dev, WOLFTPM2_HMAC *hmac, ++ const byte *data, word32 dataSz); ++int __wrap_wolfTPM2_HmacFinish(WOLFTPM2_DEV *dev, WOLFTPM2_HMAC *hmac, ++ byte *digest, word32 *digestSz); ++int __wrap_wolfTPM2_UnloadHandle(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *handle); ++int __wrap_wolfTPM2_CreateSRK(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *srkKey, ++ TPM_ALG_ID alg, const byte *auth, int authSz); ++int __wrap_wolfTPM2_CreateAndLoadKey(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ WOLFTPM2_HANDLE *parent, ++ TPMT_PUBLIC *publicTemplate, ++ const byte *auth, int authSz); ++int __wrap_wolfTPM2_NVStoreKey(WOLFTPM2_DEV *dev, TPM_HANDLE primaryHandle, ++ WOLFTPM2_KEY *key, TPM_HANDLE persistentHandle); ++int __wrap_wolfTPM2_NVDeleteKey(WOLFTPM2_DEV *dev, TPM_HANDLE primaryHandle, ++ WOLFTPM2_KEY *key); ++int __wrap_wolfTPM2_Cleanup(WOLFTPM2_DEV *dev); ++ ++/* Mock control state, reset in setUp(). */ ++static int mock_init_rc; ++static int mock_readpublickey_rc; ++static int mock_hmacstart_rc; ++static int mock_hmacfinish_rc; ++static word32 mock_hmac_out_sz; ++static int mock_createsrk_rc; ++static int mock_createandloadkey_rc; ++static int mock_createandloadkey_called; ++static int mock_createandloadkey_origin_ok; ++static int mock_nvstorekey_rc; ++static int mock_nvdeletekey_rc; ++static int mock_existing_key; ++static int mock_nvdeletekey_called; ++static int mock_nvstorekey_called; ++ ++void setUp(void) ++{ ++ mock_init_rc = TPM_RC_SUCCESS; ++ mock_readpublickey_rc = TPM_RC_SUCCESS; ++ mock_hmacstart_rc = TPM_RC_SUCCESS; ++ mock_hmacfinish_rc = TPM_RC_SUCCESS; ++ mock_hmac_out_sz = 0; /* set per test to match hmac_length */ ++ mock_createsrk_rc = TPM_RC_SUCCESS; ++ mock_createandloadkey_rc = TPM_RC_SUCCESS; ++ mock_createandloadkey_called = 0; ++ mock_createandloadkey_origin_ok = 0; ++ mock_nvstorekey_rc = TPM_RC_SUCCESS; ++ mock_nvdeletekey_rc = TPM_RC_SUCCESS; ++ mock_existing_key = 0; ++ mock_nvdeletekey_called = 0; ++ mock_nvstorekey_called = 0; ++} ++ ++void tearDown(void) ++{ ++} ++ ++int __wrap_wolfTPM2_Init(WOLFTPM2_DEV *dev, TPM2HalIoCb ioCb, void *userCtx) ++{ ++ (void)dev; ++ (void)ioCb; ++ (void)userCtx; ++ return mock_init_rc; ++} ++ ++int __wrap_wolfTPM2_ReadPublicKey(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ const TPM_HANDLE handle) ++{ ++ (void)dev; ++ (void)key; ++ (void)handle; ++ if (handle == TPM_HMAC_KEY_PERSISTANT_HANDLE && !mock_existing_key) { ++ return TPM_RC_FAILURE; ++ } ++ return mock_readpublickey_rc; ++} ++ ++int __wrap_wolfTPM2_HmacStart(WOLFTPM2_DEV *dev, WOLFTPM2_HMAC *hmac, ++ WOLFTPM2_HANDLE *parent, TPMI_ALG_HASH hashAlg, ++ const byte *keyBuf, word32 keySz, ++ const byte *usageAuth, word32 usageAuthSz) ++{ ++ (void)dev; ++ (void)hmac; ++ (void)parent; ++ (void)hashAlg; ++ (void)keyBuf; ++ (void)keySz; ++ (void)usageAuth; ++ (void)usageAuthSz; ++ return mock_hmacstart_rc; ++} ++ ++int __wrap_wolfTPM2_HmacUpdate(WOLFTPM2_DEV *dev, WOLFTPM2_HMAC *hmac, ++ const byte *data, word32 dataSz) ++{ ++ (void)dev; ++ (void)hmac; ++ (void)data; ++ (void)dataSz; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_HmacFinish(WOLFTPM2_DEV *dev, WOLFTPM2_HMAC *hmac, ++ byte *digest, word32 *digestSz) ++{ ++ (void)dev; ++ (void)hmac; ++ if (mock_hmacfinish_rc != TPM_RC_SUCCESS) { ++ return mock_hmacfinish_rc; ++ } ++ memset(digest, 0x33, mock_hmac_out_sz); ++ *digestSz = mock_hmac_out_sz; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_UnloadHandle(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *handle) ++{ ++ (void)dev; ++ (void)handle; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_CreateSRK(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *srkKey, ++ TPM_ALG_ID alg, const byte *auth, int authSz) ++{ ++ (void)dev; ++ (void)srkKey; ++ (void)alg; ++ (void)auth; ++ (void)authSz; ++ return mock_createsrk_rc; ++} ++ ++int __wrap_wolfTPM2_CreateAndLoadKey(WOLFTPM2_DEV *dev, WOLFTPM2_KEY *key, ++ WOLFTPM2_HANDLE *parent, ++ TPMT_PUBLIC *publicTemplate, ++ const byte *auth, int authSz) ++{ ++ (void)dev; ++ (void)key; ++ (void)parent; ++ (void)auth; ++ (void)authSz; ++ mock_createandloadkey_called = 1; ++ /* ++ * The key material must originate inside the TPM; if this attribute is ++ * ever dropped the secret would be generated on the host instead. The ++ * key must also stay bound to this TPM and its parent. ++ */ ++ mock_createandloadkey_origin_ok = ++ (publicTemplate != NULL) && ++ ((publicTemplate->objectAttributes & ++ (TPMA_OBJECT_sensitiveDataOrigin | TPMA_OBJECT_fixedTPM | ++ TPMA_OBJECT_fixedParent)) == ++ (TPMA_OBJECT_sensitiveDataOrigin | TPMA_OBJECT_fixedTPM | ++ TPMA_OBJECT_fixedParent)); ++ return mock_createandloadkey_rc; ++} ++ ++int __wrap_wolfTPM2_NVStoreKey(WOLFTPM2_DEV *dev, TPM_HANDLE primaryHandle, ++ WOLFTPM2_KEY *key, TPM_HANDLE persistentHandle) ++{ ++ (void)dev; ++ (void)primaryHandle; ++ (void)key; ++ (void)persistentHandle; ++ mock_nvstorekey_called = 1; ++ return mock_nvstorekey_rc; ++} ++ ++int __wrap_wolfTPM2_NVDeleteKey(WOLFTPM2_DEV *dev, TPM_HANDLE primaryHandle, ++ WOLFTPM2_KEY *key) ++{ ++ (void)dev; ++ (void)primaryHandle; ++ (void)key; ++ mock_nvdeletekey_called = 1; ++ return mock_nvdeletekey_rc; ++} ++ ++int __wrap_wolfTPM2_Cleanup(WOLFTPM2_DEV *dev) ++{ ++ (void)dev; ++ return TPM_RC_SUCCESS; ++} ++ ++void test_fdo_tpm_get_hmac_null_params(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ uint8_t hmac[32] = {0}; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_get_hmac(NULL, sizeof(data), hmac, ++ sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_get_hmac(data, 0, hmac, sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_get_hmac(data, sizeof(data), NULL, ++ sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_get_hmac(data, sizeof(data), hmac, 0, ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_get_hmac(data, sizeof(data), hmac, sizeof(hmac), 0)); ++} ++ ++void test_fdo_tpm_get_hmac_readpublickey_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ uint8_t hmac[32] = {0}; ++ ++ mock_existing_key = 0; ++ ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_get_hmac(data, sizeof(data), hmac, sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++} ++ ++void test_fdo_tpm_get_hmac_hmacstart_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ uint8_t hmac[32] = {0}; ++ ++ mock_existing_key = 1; ++ mock_hmacstart_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_get_hmac(data, sizeof(data), hmac, sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++} ++ ++void test_fdo_tpm_get_hmac_hmacfinish_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ uint8_t hmac[32] = {0}; ++ ++ mock_existing_key = 1; ++ mock_hmacfinish_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_get_hmac(data, sizeof(data), hmac, sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++} ++ ++void test_fdo_tpm_get_hmac_length_mismatch(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ uint8_t hmac[32] = {0}; ++ ++ mock_existing_key = 1; ++ mock_hmac_out_sz = sizeof(hmac) - 1; ++ ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_get_hmac(data, sizeof(data), hmac, sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++} ++ ++void test_fdo_tpm_get_hmac_success(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ uint8_t hmac[32] = {0}; ++ uint8_t expected[32]; ++ ++ mock_existing_key = 1; ++ mock_hmac_out_sz = sizeof(hmac); ++ memset(expected, 0x33, sizeof(expected)); ++ ++ TEST_ASSERT_EQUAL(0, ++ fdo_tpm_get_hmac(data, sizeof(data), hmac, sizeof(hmac), ++ TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_EQUAL_UINT8_ARRAY(expected, hmac, sizeof(expected)); ++} ++ ++void test_fdo_tpm_generate_hmac_key_null_param(void) ++{ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_generate_hmac_key(0)); ++} ++ ++void test_fdo_tpm_generate_hmac_key_createsrk_failure(void) ++{ ++ mock_createsrk_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_FALSE(mock_nvstorekey_called); ++} ++ ++void test_fdo_tpm_generate_hmac_key_loadkey_failure(void) ++{ ++ mock_createandloadkey_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, ++ fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_TRUE(mock_createandloadkey_called); ++ TEST_ASSERT_FALSE(mock_nvstorekey_called); ++} ++ ++/* The HMAC key must be generated by the TPM, never on the host. */ ++void test_fdo_tpm_generate_hmac_key_originates_in_tpm(void) ++{ ++ TEST_ASSERT_EQUAL(0, ++ fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_TRUE(mock_createandloadkey_origin_ok); ++} ++ ++/* Test delete-before-store of existing key. */ ++void test_fdo_tpm_generate_hmac_key_deletes_existing(void) ++{ ++ mock_existing_key = 1; ++ ++ TEST_ASSERT_EQUAL(0, ++ fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_TRUE(mock_nvdeletekey_called); ++ TEST_ASSERT_TRUE(mock_nvstorekey_called); ++} ++ ++void test_fdo_tpm_generate_hmac_key_success_no_existing(void) ++{ ++ mock_existing_key = 0; ++ ++ TEST_ASSERT_EQUAL(0, ++ fdo_tpm_generate_hmac_key(TPM_HMAC_KEY_PERSISTANT_HANDLE)); ++ TEST_ASSERT_FALSE(mock_nvdeletekey_called); ++ TEST_ASSERT_TRUE(mock_nvstorekey_called); ++} ++ ++#endif /* TARGET_OS_LINUX */ +diff --git a/tests/unit/test_wolftpm_nv_storage.c b/tests/unit/test_wolftpm_nv_storage.c +new file mode 100644 +index 0000000..653301d +--- /dev/null ++++ b/tests/unit/test_wolftpm_nv_storage.c +@@ -0,0 +1,452 @@ ++/* ++ * Copyright 2026 ++ * SPDX-License-Identifier: Apache 2.0 ++ */ ++ ++/*! ++ * \file ++ * \brief Unit tests for storage/linux/wolftpm_nv_storage.c. ++ */ ++ ++#include "util.h" ++#include "unity.h" ++ ++#if defined(TARGET_OS_LINUX) ++ ++#include ++#include "fdo_tpm_handles.h" ++ ++/*** Unity Declarations. ***/ ++void setUp(void); ++void tearDown(void); ++void test_fdo_tpm_nvdefine_already_exists(void); ++void test_fdo_tpm_nvdefine_create_failure(void); ++void test_fdo_tpm_nvdefine_success(void); ++void test_fdo_tpm_nvwrite_null_params(void); ++void test_fdo_tpm_nvwrite_deletes_existing(void); ++void test_fdo_tpm_nvwrite_create_failure(void); ++void test_fdo_tpm_nvwrite_success(void); ++void test_fdo_tpm_nvread_null_params(void); ++void test_fdo_tpm_nvread_failure(void); ++void test_fdo_tpm_nvread_success(void); ++void test_fdo_tpm_nvdel_not_present(void); ++void test_fdo_tpm_nvdel_failure(void); ++void test_fdo_tpm_nvdel_success(void); ++void test_fdo_tpm_nvwrite_lock_failure(void); ++void test_fdo_tpm_nvwrite_lock_success(void); ++void test_fdo_tpm_nvread_lock_open_failure(void); ++void test_fdo_tpm_nvread_lock_set_auth_failure(void); ++void test_fdo_tpm_nvread_lock_readlock_failure(void); ++void test_fdo_tpm_nvread_lock_success(void); ++ ++/* Prototypes for the linker-wrapped mocks. */ ++int __wrap_wolfTPM2_Init(WOLFTPM2_DEV *dev, TPM2HalIoCb ioCb, void *userCtx); ++int __wrap_wolfTPM2_NVReadPublic(WOLFTPM2_DEV *dev, word32 nvIndex, ++ TPMS_NV_PUBLIC *nvPublic); ++int __wrap_wolfTPM2_GetNvAttributesTemplate(TPM_HANDLE auth, ++ word32 *nvAttributes); ++int __wrap_wolfTPM2_NVCreateAuth(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *parent, ++ WOLFTPM2_NV *nv, word32 nvIndex, ++ word32 nvAttributes, word32 maxSize, ++ const byte *auth, int authSz); ++int __wrap_wolfTPM2_NVWriteAuth(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv, ++ word32 nvIndex, byte *dataBuf, word32 dataSz, ++ word32 offset); ++int __wrap_wolfTPM2_NVReadAuth(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv, ++ word32 nvIndex, byte *dataBuf, word32 *pDataSz, ++ word32 offset); ++int __wrap_wolfTPM2_NVDeleteAuth(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *parent, ++ word32 nvIndex); ++int __wrap_wolfTPM2_NVWriteLock(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv); ++int __wrap_wolfTPM2_NVOpen(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv, word32 nvIndex, ++ const byte *auth, word32 authSz); ++int __wrap_wolfTPM2_SetAuthHandleName(WOLFTPM2_DEV *dev, int index, ++ const WOLFTPM2_HANDLE *handle); ++TPM_RC __wrap_TPM2_NV_ReadLock(NV_ReadLock_In *in); ++int __wrap_wolfTPM2_Cleanup(WOLFTPM2_DEV *dev); ++ ++/* Mock control state, reset in setUp(). */ ++static int mock_init_rc; ++static int mock_nv_exists; ++static int mock_readpublic_rc; ++static int mock_attrtemplate_rc; ++static int mock_create_rc; ++static int mock_write_rc; ++static int mock_read_rc; ++static int mock_delete_rc; ++static byte mock_read_bytes[16]; ++static word32 mock_read_sz; ++static int mock_create_called; ++static int mock_write_called; ++static int mock_read_called; ++static int mock_delete_called; ++static int mock_writelock_rc; ++static int mock_nvopen_rc; ++static int mock_setauthhandlename_rc; ++static int mock_readlock_rc; ++static int mock_writelock_called; ++static int mock_nvopen_called; ++static int mock_setauthhandlename_called; ++static int mock_readlock_called; ++ ++void setUp(void) ++{ ++ mock_init_rc = TPM_RC_SUCCESS; ++ mock_nv_exists = 0; ++ mock_readpublic_rc = TPM_RC_SUCCESS; ++ mock_attrtemplate_rc = TPM_RC_SUCCESS; ++ mock_create_rc = TPM_RC_SUCCESS; ++ mock_write_rc = TPM_RC_SUCCESS; ++ mock_read_rc = TPM_RC_SUCCESS; ++ mock_delete_rc = TPM_RC_SUCCESS; ++ mock_read_sz = sizeof(mock_read_bytes); ++ memset(mock_read_bytes, 0x22, sizeof(mock_read_bytes)); ++ mock_create_called = 0; ++ mock_write_called = 0; ++ mock_read_called = 0; ++ mock_delete_called = 0; ++ mock_writelock_rc = TPM_RC_SUCCESS; ++ mock_nvopen_rc = TPM_RC_SUCCESS; ++ mock_setauthhandlename_rc = 0; ++ mock_readlock_rc = TPM_RC_SUCCESS; ++ mock_writelock_called = 0; ++ mock_nvopen_called = 0; ++ mock_setauthhandlename_called = 0; ++ mock_readlock_called = 0; ++} ++ ++void tearDown(void) ++{ ++} ++ ++int __wrap_wolfTPM2_Init(WOLFTPM2_DEV *dev, TPM2HalIoCb ioCb, void *userCtx) ++{ ++ (void)dev; ++ (void)ioCb; ++ (void)userCtx; ++ return mock_init_rc; ++} ++ ++int __wrap_wolfTPM2_NVReadPublic(WOLFTPM2_DEV *dev, word32 nvIndex, ++ TPMS_NV_PUBLIC *nvPublic) ++{ ++ (void)dev; ++ (void)nvIndex; ++ memset(nvPublic, 0, sizeof(*nvPublic)); ++ if (!mock_nv_exists) { ++ return TPM_RC_FAILURE; ++ } ++ if (mock_readpublic_rc != TPM_RC_SUCCESS) { ++ return mock_readpublic_rc; ++ } ++ nvPublic->dataSize = mock_read_sz; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_GetNvAttributesTemplate(TPM_HANDLE auth, ++ word32 *nvAttributes) ++{ ++ (void)auth; ++ *nvAttributes = 0; ++ return mock_attrtemplate_rc; ++} ++ ++int __wrap_wolfTPM2_NVCreateAuth(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *parent, ++ WOLFTPM2_NV *nv, word32 nvIndex, ++ word32 nvAttributes, word32 maxSize, ++ const byte *auth, int authSz) ++{ ++ (void)dev; ++ (void)parent; ++ (void)nv; ++ (void)nvIndex; ++ (void)nvAttributes; ++ (void)maxSize; ++ (void)auth; ++ (void)authSz; ++ mock_create_called = 1; ++ return mock_create_rc; ++} ++ ++int __wrap_wolfTPM2_NVWriteAuth(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv, ++ word32 nvIndex, byte *dataBuf, word32 dataSz, ++ word32 offset) ++{ ++ (void)dev; ++ (void)nv; ++ (void)nvIndex; ++ (void)dataBuf; ++ (void)dataSz; ++ (void)offset; ++ mock_write_called = 1; ++ return mock_write_rc; ++} ++ ++int __wrap_wolfTPM2_NVReadAuth(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv, ++ word32 nvIndex, byte *dataBuf, word32 *pDataSz, ++ word32 offset) ++{ ++ (void)dev; ++ (void)nv; ++ (void)nvIndex; ++ (void)offset; ++ mock_read_called = 1; ++ if (mock_read_rc != TPM_RC_SUCCESS) { ++ return mock_read_rc; ++ } ++ TEST_ASSERT_TRUE(mock_read_sz <= *pDataSz); ++ memcpy(dataBuf, mock_read_bytes, mock_read_sz); ++ *pDataSz = mock_read_sz; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_NVDeleteAuth(WOLFTPM2_DEV *dev, WOLFTPM2_HANDLE *parent, ++ word32 nvIndex) ++{ ++ (void)dev; ++ (void)parent; ++ (void)nvIndex; ++ mock_delete_called = 1; ++ return mock_delete_rc; ++} ++ ++int __wrap_wolfTPM2_NVWriteLock(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv) ++{ ++ (void)dev; ++ (void)nv; ++ mock_writelock_called = 1; ++ return mock_writelock_rc; ++} ++ ++int __wrap_wolfTPM2_NVOpen(WOLFTPM2_DEV *dev, WOLFTPM2_NV *nv, word32 nvIndex, ++ const byte *auth, word32 authSz) ++{ ++ (void)dev; ++ (void)auth; ++ (void)authSz; ++ mock_nvopen_called = 1; ++ if (mock_nvopen_rc != TPM_RC_SUCCESS) { ++ return mock_nvopen_rc; ++ } ++ nv->handle.hndl = nvIndex; ++ return TPM_RC_SUCCESS; ++} ++ ++int __wrap_wolfTPM2_SetAuthHandleName(WOLFTPM2_DEV *dev, int index, ++ const WOLFTPM2_HANDLE *handle) ++{ ++ (void)dev; ++ (void)index; ++ (void)handle; ++ mock_setauthhandlename_called = 1; ++ return mock_setauthhandlename_rc; ++} ++ ++TPM_RC __wrap_TPM2_NV_ReadLock(NV_ReadLock_In *in) ++{ ++ (void)in; ++ mock_readlock_called = 1; ++ return mock_readlock_rc; ++} ++ ++int __wrap_wolfTPM2_Cleanup(WOLFTPM2_DEV *dev) ++{ ++ (void)dev; ++ return TPM_RC_SUCCESS; ++} ++ ++void test_fdo_tpm_nvdefine_already_exists(void) ++{ ++ mock_nv_exists = 1; ++ ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvdefine(FDO_CRED_NV_IDX, 16)); ++ TEST_ASSERT_FALSE(mock_create_called); ++} ++ ++void test_fdo_tpm_nvdefine_create_failure(void) ++{ ++ mock_nv_exists = 0; ++ mock_create_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvdefine(FDO_CRED_NV_IDX, 16)); ++ TEST_ASSERT_TRUE(mock_create_called); ++} ++ ++void test_fdo_tpm_nvdefine_success(void) ++{ ++ mock_nv_exists = 0; ++ ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvdefine(FDO_CRED_NV_IDX, 16)); ++ TEST_ASSERT_TRUE(mock_create_called); ++} ++ ++void test_fdo_tpm_nvwrite_null_params(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvwrite(NULL, sizeof(data), FDO_CRED_NV_IDX)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvwrite(data, 0, FDO_CRED_NV_IDX)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvwrite(data, sizeof(data), 0)); ++ TEST_ASSERT_FALSE(mock_write_called); ++} ++ ++void test_fdo_tpm_nvwrite_deletes_existing(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ ++ mock_nv_exists = 1; ++ mock_delete_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvwrite(data, sizeof(data), FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_delete_called); ++ TEST_ASSERT_FALSE(mock_write_called); ++} ++ ++void test_fdo_tpm_nvwrite_create_failure(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ ++ mock_nv_exists = 0; ++ mock_create_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvwrite(data, sizeof(data), FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_create_called); ++ TEST_ASSERT_FALSE(mock_write_called); ++} ++ ++void test_fdo_tpm_nvwrite_success(void) ++{ ++ uint8_t data[4] = {1, 2, 3, 4}; ++ ++ mock_nv_exists = 0; ++ ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvwrite(data, sizeof(data), FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_create_called); ++ TEST_ASSERT_TRUE(mock_write_called); ++} ++ ++void test_fdo_tpm_nvread_null_params(void) ++{ ++ uint8_t buf[16]; ++ uint8_t *pbuf = buf; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread(0, sizeof(buf), &pbuf)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread(FDO_CRED_NV_IDX, sizeof(buf), NULL)); ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread(FDO_CRED_NV_IDX, 0, &pbuf)); ++ TEST_ASSERT_FALSE(mock_read_called); ++} ++ ++void test_fdo_tpm_nvread_failure(void) ++{ ++ uint8_t buf[16]; ++ uint8_t *pbuf = buf; ++ ++ mock_read_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread(FDO_CRED_NV_IDX, sizeof(buf), &pbuf)); ++ TEST_ASSERT_TRUE(mock_read_called); ++} ++ ++void test_fdo_tpm_nvread_success(void) ++{ ++ uint8_t buf[16] = {0}; ++ uint8_t *pbuf = buf; ++ ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvread(FDO_CRED_NV_IDX, sizeof(buf), &pbuf)); ++ TEST_ASSERT_EQUAL_UINT8_ARRAY(mock_read_bytes, buf, sizeof(mock_read_bytes)); ++} ++ ++void test_fdo_tpm_nvdel_not_present(void) ++{ ++ mock_nv_exists = 0; ++ ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvdel(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_FALSE(mock_delete_called); ++} ++ ++void test_fdo_tpm_nvdel_failure(void) ++{ ++ mock_nv_exists = 1; ++ mock_delete_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvdel(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_delete_called); ++} ++ ++void test_fdo_tpm_nvdel_success(void) ++{ ++ mock_nv_exists = 1; ++ ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvdel(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_delete_called); ++} ++ ++/* Without LOCK_TPM the lock calls compile to no-ops that return 0, so ++ * check that instead of the TPM interactions. */ ++#if defined(LOCK_TPM) ++#define EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(call) do { } while (0) ++#else ++#define EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(call) \ ++ do { \ ++ TEST_ASSERT_EQUAL(0, (call)); \ ++ return; \ ++ } while (0) ++#endif ++ ++void test_fdo_tpm_nvwrite_lock_failure(void) ++{ ++ EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(fdo_tpm_nvwrite_lock(FDO_CRED_NV_IDX)); ++ mock_writelock_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvwrite_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_writelock_called); ++} ++ ++void test_fdo_tpm_nvwrite_lock_success(void) ++{ ++ EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(fdo_tpm_nvwrite_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvwrite_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_writelock_called); ++} ++ ++void test_fdo_tpm_nvread_lock_open_failure(void) ++{ ++ EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ mock_nvopen_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_nvopen_called); ++ TEST_ASSERT_FALSE(mock_setauthhandlename_called); ++ TEST_ASSERT_FALSE(mock_readlock_called); ++} ++ ++void test_fdo_tpm_nvread_lock_set_auth_failure(void) ++{ ++ EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ mock_setauthhandlename_rc = -1; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_nvopen_called); ++ TEST_ASSERT_TRUE(mock_setauthhandlename_called); ++ TEST_ASSERT_FALSE(mock_readlock_called); ++} ++ ++void test_fdo_tpm_nvread_lock_readlock_failure(void) ++{ ++ EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ mock_readlock_rc = TPM_RC_FAILURE; ++ ++ TEST_ASSERT_EQUAL(-1, fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_readlock_called); ++} ++ ++void test_fdo_tpm_nvread_lock_success(void) ++{ ++ EXPECT_LOCK_NOOP_UNLESS_LOCK_TPM(fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_EQUAL(0, fdo_tpm_nvread_lock(FDO_CRED_NV_IDX)); ++ TEST_ASSERT_TRUE(mock_nvopen_called); ++ TEST_ASSERT_TRUE(mock_setauthhandlename_called); ++ TEST_ASSERT_TRUE(mock_readlock_called); ++} ++ ++#endif /* TARGET_OS_LINUX */ +diff --git a/utils/install_tpm_libs.sh b/utils/install_tpm_libs.sh +index 7f41967..1808173 100755 +--- a/utils/install_tpm_libs.sh ++++ b/utils/install_tpm_libs.sh +@@ -1,3 +1,6 @@ ++# NOTE: tpm2 tools link against OpenSSL for internal crypto (unrelated to FDO ++# SDK TLS backend). OpenSSL dependency is required for tpm2-tss. Only ++# tpm2-openssl is skippable for wolfSSL users (via -s flag). + export OPENSSL3_INCLUDE=/opt/openssl/include + export CURL_INCLUDE=/opt/curl/include + export OPENSSL3_LIB=/opt/openssl/lib64 +@@ -173,7 +176,12 @@ install() + install_tpm2tss + install_tpm2abrmd + install_tpm2tools +- install_tpm2openssl ++ if [ "$SKIP_TPM2OPENSSL" != "1" ]; then ++ install_tpm2openssl ++ else ++ echo "Skipping tpm2-openssl (-s). NOTE: tpm_make_ready_ecdsa.sh needs it to" \ ++ "generate the device CSR; provision on a machine that has it installed." ++ fi + } + + uninstall() +@@ -182,7 +190,9 @@ uninstall() + uninstall_tpm2tss + uninstall_tpm2abrmd + uninstall_tpm2tools +- uninstall_tpm2openssl ++ if [ "$SKIP_TPM2OPENSSL" != "1" ]; then ++ uninstall_tpm2openssl ++ fi + cd $PARENT_DIR + rm -rf tpm2* + } +@@ -196,6 +206,10 @@ usage() + -u - Uninstall all tpm2 libraries. + -t - Install only tpm2-tss library. + -d - Uninstall only tpm2-tss library. ++ -s - Skip tpm2-openssl (OpenSSL provider plugin). Only safe on ++ runtime-only devices: tpm_make_ready_ecdsa.sh still needs ++ the tpm2 provider to generate the device CSR, on every ++ crypto backend. + -h - Help." + } + +@@ -209,13 +223,15 @@ parse_args() + UNINSTALL_TPM2_TSS_ONLY=8 + + mode=0 ++ SKIP_TPM2OPENSSL=0 + +- while getopts "iutdh" opt; do ++ while getopts "iutdsh" opt; do + case $opt in + (i) mode=$(($mode | $INSTALL_ALL));; + (u) mode=$(($mode | $UNINSTALL_ALL));; + (t) mode=$(($mode | $INSTALL_TPM2_TSS_ONLY));; +- (d) mode=$(($mode | $UNINSTALL_TPM2_TSS_ONLY_SHIFT));; ++ (d) mode=$(($mode | $UNINSTALL_TPM2_TSS_ONLY));; ++ (s) SKIP_TPM2OPENSSL=1;; + (h | *) usage; + exit;; + esac +diff --git a/utils/install_tpm_libs_rhel.sh b/utils/install_tpm_libs_rhel.sh +index 0f6881f..61ba655 100755 +--- a/utils/install_tpm_libs_rhel.sh ++++ b/utils/install_tpm_libs_rhel.sh +@@ -129,7 +129,12 @@ install() + install_tpm2tss + install_tpm2abrmd + install_tpm2tools +- install_tpm2openssl ++ if [ "$SKIP_TPM2OPENSSL" != "1" ]; then ++ install_tpm2openssl ++ else ++ echo "Skipping tpm2-openssl (-s). NOTE: tpm_make_ready_ecdsa.sh needs it to" \ ++ "generate the device CSR; provision on a machine that has it installed." ++ fi + } + + uninstall() +@@ -138,7 +143,9 @@ uninstall() + uninstall_tpm2tss + uninstall_tpm2abrmd + uninstall_tpm2tools +- uninstall_tpm2openssl ++ if [ "$SKIP_TPM2OPENSSL" != "1" ]; then ++ uninstall_tpm2openssl ++ fi + cd $PARENT_DIR + rm -rf tpm2* + } +@@ -152,6 +159,10 @@ usage() + -u - Uninstall all tpm2 libraries. + -t - Install only tpm2-tss library. + -d - Uninstall only tpm2-tss library. ++ -s - Skip tpm2-openssl (OpenSSL provider plugin). Only safe on ++ runtime-only devices: tpm_make_ready_ecdsa.sh still needs ++ the tpm2 provider to generate the device CSR, on every ++ crypto backend. + -h - Help." + } + +@@ -165,13 +176,15 @@ parse_args() + UNINSTALL_TPM2_TSS_ONLY=8 + + mode=0 ++ SKIP_TPM2OPENSSL=0 + +- while getopts "iutdh" opt; do ++ while getopts "iutdsh" opt; do + case $opt in + (i) mode=$(($mode | $INSTALL_ALL));; + (u) mode=$(($mode | $UNINSTALL_ALL));; + (t) mode=$(($mode | $INSTALL_TPM2_TSS_ONLY));; +- (d) mode=$(($mode | $UNINSTALL_TPM2_TSS_ONLY_SHIFT));; ++ (d) mode=$(($mode | $UNINSTALL_TPM2_TSS_ONLY));; ++ (s) SKIP_TPM2OPENSSL=1;; + (h | *) usage; + exit;; + esac +diff --git a/utils/install_wolfssl_curl.sh b/utils/install_wolfssl_curl.sh +new file mode 100755 +index 0000000..1ae2e0c +--- /dev/null ++++ b/utils/install_wolfssl_curl.sh +@@ -0,0 +1,385 @@ ++#!/bin/bash ++# ++# Copyright 2026 wolfSSL Inc. ++# SPDX-License-Identifier: Apache-2.0 ++# ++set -e -o pipefail ++ ++WOLFSSL_ROOT="${WOLFSSL_ROOT:-/opt/wolfssl}" ++CURL_ROOT="${CURL_ROOT:-/opt/curl}" ++WOLFTPM_ROOT="${WOLFTPM_ROOT:-/opt/wolftpm}" ++CURL_VER="8.8.0" ++WOLFSSL_VER="5.9.4" ++WOLFTPM_VER="v4.2.0" ++# Derived from $CURL_VER to prevent URL mismatch. ++CURL_LINK="https://curl.se/download/curl-$CURL_VER.tar.gz" ++ ++PARENT_DIR=$(pwd) ++cd "$PARENT_DIR" ++ ++# Installs target $WOLFSSL_ROOT and $CURL_ROOT (both default under /opt), which ++# are not writable by an unprivileged user. Resolved once here so that every ++# `make install` / `make uninstall` below is covered. ++SUDO="" ++if [ "$(id -u)" -ne 0 ]; then ++ SUDO="sudo" ++fi ++ ++# Pinned release-signing key fingerprints. ++WOLFSSL_GPG_FPR="A2A48E7BCB96C5BECB987314EBC80E415CA29677" # wolfSSL ++CURL_GPG_FPR="27EDEAF22F3ABCEB50DB9A125CC908FDB71E12C2" # Daniel Stenberg ++ ++WOLFSSL_PUBKEY='-----BEGIN PGP PUBLIC KEY BLOCK----- ++ ++mQENBFS0RN8BCADHW/seLuKGtSFkzHjYguo6lASp3HjVpVKNetvafxbFIYB5xV3K ++0kDoGta9r/2kYRzxv5XSbOTjKfUHXLOLL8212DQcA4sAzhVXUkBynhrkLtg73NAG ++HKI0huQeHXlIS5fHpmKjy+feAS5YNdAR3IuekQqMG/l2ezZHJhpj8y8bjbZbczhi ++pjJbihNya0Zr2kfdfQvm2q4vcN1LR3TeePSgoK1n8ZtJNN3pcGKgpyG3TMGCFj9w ++19b1m8tNlJgeniIC5+4+Y6Y0AQp9ewrxayJAzDlfgE7KFIw4gY28/GJ3RVps5QPa ++/+B9yp3TqWCL6S0U6KHdjrGPxZIMHpEBWCPrABEBAAG0L0phY29iIEJhcnRoZWxt ++ZWggKHdvbGZTU0wpIDxzZWN1cmVAd29sZnNzbC5jb20+iQFVBBMBCAA/AhsDBgsJ ++CAcDAgYVCAIJCgsEFgIDAQIeAQIXgBYhBKKkjnvLlsW+y5hzFOvIDkFcopZ3BQJn ++K+z7BQklQ6sPAAoJEOvIDkFcopZ3/hIIAKacXn5tprjIWK2SY94WIog63N4XP4ip ++fR7Xp/0wERzHHyW/sN5KJ1Og2o7BlfTmBuSNFkVu50w6Z2cr4Mi8NlQIJKPsHpak ++0uDpVt5IT+sj8l4IWnZDpF3eL1o8PsQdPiGiht6aDjH4Lw3z3Mu5d8+pGwEbqgud ++R/UynIAWwgTRC1fXKK4LYaV/Yc8H+Y+z9wBe5Doy6MeWSR2xKl0oAB6M1xiB9vEo ++syGccFNli9gBUm/XHV7IjyWTkngnQKl7EsI/ZcadoFjhVILfkQVaL4LepLwd51DC ++6yX+bTFpHjMUoUPZwimccr8878g+4J5u/R+eHtxhoHa6KjxLOwykRYeJAVUEEwEI ++AD8CGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAFiEEoqSOe8uWxb7LmHMU68gO ++QVyilncFAl/Hn7IFCRKYKMYACgkQ68gOQVyilneKcAf/aa4H8+v1jqRuwTdJafpX ++J5eHHonnTKHCrksu6kJVxhN5ZKV5/VGrTfyxr6p/toEHOaoVJ8YMWQraBT/wfFjy ++PpL1ninQx9feOkTV+7Pi11qd3Z7IFGLtiCmkXus58o80Z96MC0iW9GP2/XA0qer3 ++fmr99sWgGybJrQWJ3cltuo8K3PiEG0Mea1MBh/Jky/ysMXdaEK5cV5QTldw7L/i8 +++mIak9yqdyvzyuEub2xdrXg9v+Wz6glrChm87GQKjoaBru5LZ/1Qwl5pGr/n1uA7 ++bhl38iMdZgrnKcuNDn9en0OMHhlK18uUTBcASQdtcx6VjK7jmnEMQkVym7feicXL ++XokBVQQTAQIAKAIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFCQsPp/YFAlg/ ++IKgAIQkQ68gOQVyilncWIQSipI57y5bFvsuYcxTryA5BXKKWdxByB/sEXatljZnK ++ha7ByoBRiWQtRbZqvOSIddwEWgn8SIb0+MVqYl1eASWSJTP+4u6hfXmALwIXoVaQ ++W7yY4S5tMG0VgJ98OJWL8p/6XcBUFECp85BaUt5Z1TRQN77yjKvzESkGRNjTvVYe ++x7ECkS/G4D1Y/eclvUSEffW5vEFSn/cl8GBx7/XFjnaCoTCde/nfUJ3jPa6adEmz ++HhGFFl14hmxckVwscL+LhSb4JtCe0739JP/YSjgz3v76pjGe9L9jP1bHEiTbf5rV +++vCBHXzJDkZGxRnW0kWFZF0VWXxlhQBTACc4LVC82v8twDgh5KSxAGTgEvXUql2I ++x7PTEXeHPtaAiQFVBBMBAgAoAhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAUC ++WD8e7QUJCw+n9gAhCRDryA5BXKKWdxYhBKKkjnvLlsW+y5hzFOvIDkFcopZ3BssH ++/3uR+JOHxbpAaYGrS2AQ//dwrmEiuXIHD6F3k2N3AgP3sO04N0UEfOgbQEUQ/fRm ++L88KF9JdDaE/jLZrvKON+dn3aZ+oUeEHosOwH/cqzVEkXZC3OWvksMIhrYT+yd+S ++gWB7jshvLm08HXV+6UH51kU/RkQPrg7cGWj8kt1jSiC2tKcXZ0DQFVTA1zbDeilC ++e6yedQR12CMFoWaDny0DhOyZY/xAcodaPk0Pf6BBq06TS1CERgwy8bf/dKrbGCDR ++b9pIL8IeEEMG90irIK2R3gTLj0oLbUmx6Shc8mER+qDZdrOn7DKRnTmi+znCfi5U ++V2SDnMl+tWEMwDj/4k48UYaJAVUEEwECACgFAlS0RN8CGwMFCQPCZwAGCwkIBwMC ++BhUIAgkKCwQWAgMBAh4BAheAACEJEOvIDkFcopZ3FiEEoqSOe8uWxb7LmHMU68gO ++QVyilncntQf/Z7SH2o+2Cjaa99FcRTCkaFgnsCCux8/Y5YTKqgK7NZ2xPa1fBz+N ++ABtxl3tfnqnvqtpJMNXacisTkJk47/BsRauFxp5hc9ywo40T/Z5N0OMhNkbHGM0z ++3nYqjfSOHZ3gHR8YTBJzytS2dTK/oO+5d8xL1V/N7Si30eG6S8W1KUJ90D0hGpk8 ++/IuIl9GyYiLt+dc7IPWwm6T3b5vDBrpyzFcSd8OlMEJ1TikrSgZtlzpySfz19p7h ++FFOLCq75lVNIHSQoiklw2OYe2V7zJuWztrtYemUVvC11Vt9EBg1fJ4cHwAEmpAqv ++ahES9BEL7131Z7SZmBE3N3xnxnZl0V9PPrQcd29sZlNTTCA8c2VjdXJlQHdvbGZz ++c2wuY29tPokBWQQTAQgAQwIbAwcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAAhkB ++FiEEoqSOe8uWxb7LmHMU68gOQVyilncFAmcr7O4FCSVDqw8ACgkQ68gOQVyilncT ++Tgf/X3czpnD5l1jMVpobz4v+4vQK6h0tbAuWbNLBBCtrPNoTFDGl016RVB+8BUxE ++3Q+3Jf5gND0bT2gTCOC4k+G5nbH/VMg1XClh3uDJeR7TjuZk3628geIuX/cOEqwk ++A7C6IcB4MQfyOGw5k3PVAFTlzmzfLIi4VGbxelTDZU7qoNe1Z7fLf8q09JsSxDS6 ++Y5wESRS0WnnZIlOEA+MGS7abeQ23JkD2bZO7qwithw2R1WQ3EZnMym0w4WA6v6i6 ++MSa4a2lu9WpBzc/bjUwZjDeII2EWgKk2cuR5CL9gHQgAZC0S/vKAQNJBvGWlDVwx ++1Hq50Q+fO0QZtGuKvhQReu3ZfokBWQQTAQgAQwIbAwcLCQgHAwIBBhUIAgkKCwQW ++AgMBAh4BAheAAhkBFiEEoqSOe8uWxb7LmHMU68gOQVyilncFAl/Hn6UFCRKYKMYA ++CgkQ68gOQVyilncWuwf/YBFjh6+BE7ZISfZAP1W7+bUUEY7DqNXENm9W4Sb/cqlB ++rHlJN5uh2081GZ8gODP4FLBtTXJnMJMLHAFo4uZXTUgOHpvze3/Smw7cLLjtNgjW ++FcCrKn0Qg4wzdSYplO2D5xBfjuA2w2C4QF5DD8iaEk+4bKhl+4kem80PhoamhaM5 ++XMTO7Pfc0yy4+qIzff5MRWyVJqdbNIAeVH1G1g+BPlb5Pr1wnk6fAWUhh8hkwcxl ++Qe23otQTEbwbmggZLlXkczC1RC/yQiAEO2mKZLuEIl7Jdw2Zv2a3LYbevlWW758r ++XHc0HKkMemd8GxMruruESgf+gMOCsqVffXotckBWuYkBWQQTAQgALAIbAwUJCw+n ++9gcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheABQJYPyCoAhkBACEJEOvIDkFcopZ3 ++FiEEoqSOe8uWxb7LmHMU68gOQVyilnctTgf9GqkkGnoojTYsWHK3Q9s6WIEv90Hu ++Ad0uBWudcMoy/b6wCHje5GPf29WhuUjfucMQ+5RI1xnIc/8/oSjXQA+I23524Iy7 ++TM1YsKffQnbxZIR7cjuLDjn37f/7BscUYChc6bh3XsFkEl+f8CetGyBXVGntISlL ++WWz6tgzzQrLrwIREBwdLF5g7QbKWrDhNa2RPyYrTXL2AmCFcNqc+stDVlYBUldEI +++kygx1q0hDjluMB4pKNTE+lL7yPXKEbtBeHHkCmnheVexk5E7NH0gXRoMFdrspFv ++cDUFwtfJLADZZ+yDsnNf26VjIg3mK255RDD9US+rAoNXZkTiq7KKmHFg6okBVgQT ++AQgAKQUCWD8gkgIbAwUJCw+n9gcLCQgHAwIBBhUIAgkKCwQWAgMBAh4BAheAACEJ ++EOvIDkFcopZ3FiEEoqSOe8uWxb7LmHMU68gOQVyilndwugf/TRZD7uB9Zvx/TtGa ++VHivQLZHQk3IAvdDbs1ItTz2Oyf9g4Vo65rIi0Ulfp+KQMtWTcheinxiaFMKRuNJ ++FSym0dkTUEPXAC/b3j5kERyxfmeM9yfP0GzRECnLUtHxPPXn7nCG1LyyEkk2CO4l ++sVQph7tx10f0/SMT0yPprKihDUgVT36n6chtZl9wXrpn+xN28aS4PUq4NIsSVtot ++ktrDHFRcsm9XRkFMiVgFVDw7fU6V/BDW2QUkV3In7Lz6L4ve6zbnaKE92aZXbZxw ++eBjg+4nAYXvYU5qLiTVdl9A5goQN10O5pMxXNDQnyIPpQaz1s9ajs+BDbP7pGrf8 ++Ch4RnLkBDQRUtETfAQgAxTEERDbyB4WS1kreiBxQcmlKomv4/hrXxL38hyL6H62Q ++Ew1bhk4HM7UcZzX40so+mBptAY3+hBfz/GxGvuGHzVI8iRTnyFaYzuNQp1xwoSVg ++LMcHR3wrbjXFtuHDBzXz58iO7EEezEa0hTu/SDZ6y/dZFO9u1A6mOgUFoPNz0sHc ++oNpZPyQEeTRmlePqlzWLbdxlFwGUcZJrKaIQkl1IFFlQCKXQhwWV+TjbSw/XCvm/ ++eegJL6hDTlcwFyQ2tp5ksqToGoRN7J1JlOFx00IkIop4DsLY+i9ySWE2SFTSc0NW ++NeaWWtLOmroUg90lXXD8Po02a3I0xHCDhR/3w6n2DwARAQABiQE2BBgBCAAgAhsM ++FiEEoqSOe8uWxb7LmHMU68gOQVyilncFAmdKOM8ACgkQ68gOQVyilncP5gf/Udzr ++b5dZXfIdR34OQ7m9GO5UJEqFyPsZir8DJdUSAZBSEzykWTfdLaCj1xljHsCkuQzx ++TCSA+gTiAy9+jigrYU5Y+jii96/9U5cINWTT8BLSpO0DScigJgs+X8kohxwhLi7f ++lCca366b+HjeWqlOfBk+ui9c9wkjFliqy+9NpX2xV4VLOfSdm4VkVW/4kQdEHzrS ++ipFYNa+MOpnDhf3FXmBQRUEAvEMnqMqlEFehvnV2/Bq6Eq1keyrHNOaj4IDBCM97 ++d87qzBGMdZ6GUCQ1RmdVOrpj610pP5HuJdil5eWBrK+ynkZc9/uJ6GtrCq9QFraw ++Cri5Of8bfQWr8nl6YQ== ++=bgTp ++-----END PGP PUBLIC KEY BLOCK-----' ++ ++CURL_PUBKEY='-----BEGIN PGP PUBLIC KEY BLOCK----- ++ ++mQENBFcGiPEBCAC7sCnaZqWxfXNgBC7P28BSDUs9w4y/PEFsOv9bpgbgZagX1Fnh ++G0eV71nm0p8v9T8Bft1eXaBd977Dq9pgk5qKO0xZo8fC8prFqB5db7fMUvPZCuJT ++Tb6lGMz4OdfT6aHqUvJ+LFF1mKn8Eqt1Q4snHGSL1PI3/+435qDRQsU15GdYrj1w ++aNJKk79aes9oguaI2/OTQqzIcOFK5tJjlSOD1ryOIH1e8vD+5MMpGvsRxv3sQHeT ++ZkfZbkzSLFg/LKpoiQkyql1+BLNhBYq8oaE/jlvQrTEkbAyKpMScdyHwmkWWKjyZ ++tXTrAtlComnki4yC2lAV9MXINHHvNJBcIXvVABEBAAG0IERhbmllbCBTdGVuYmVy ++ZyA8ZGFuaWVsQGhheHguc2U+iQFOBBMBCgAhBQJXBojxAhsDBQsJCAcDBRUKCQgL ++BRYCAwEAAh4BAheAACEJEFzJCP23HhLCFiEEJ+3q8i86vOtQ25oSXMkI/bceEsI4 ++qQf/ULKgqI3Y8KBOVahhCym/8ACayP5wXBmhsjXrsqjAD6jfPFCrGDQxXd2zwb6K ++KD04i5i6uVAvkmvcJsOW1qJd1a1W15GH9UqnrUTDJervu+MlvHzWG865pdZYtKVT ++QoHfDsePpoP+a3XoOk5xj0DD3SYrK9p9FOowXtNxPsnkd4afY0vjl0+QCGIwMSAS ++fD3IFPEr/HpShAY+CI5bFJI3sWiPeaFQ5+WnxbSueQtsniJynKbpa4spEwoB58O+ ++TwZWUBa5cBv2CWgvU/q7e40eWWr8g4NHZtlQEjRA0qG+3SJKPtYqxz+RqqxyX4AT ++2N3/qRd3q+FM0VZ3N5yj/aYaVrkBDQRXBojxAQgA7FAAS8XeJ3FyfzS1tSEmDUn3 ++x8BLsfHdaGUUbvi4CKRlCXUpmumsG7vRFZNvs2bW29l5dbrkiVjuSTjZuF9gOzUm ++sg9Y5Yq9XApYPGgRtiBb/K/LVM65cfbvrNvEuXk4QTyxC459dmwVJfYg8X2GyA0Z ++o3Oivwp7tjkG4JAtwZlZbl0sVtspEqNcbwJpaawlWghzafJcICyzar2gInXdf/nP ++4SLf3avCLV3c3EBiRKINBqf5+RaQK9kf50eYWNDUA0MqJ6XFxbVV+KUrWG73OIEE ++N/xMIS53+rTCggAfuu8h+3iLcKqPKaicHITj86N8fyPgS15DyqiScwKOPA1WqQAR ++AQABiQE2BBgBCgAJBQJXBojxAhsMACEJEFzJCP23HhLCFiEEJ+3q8i86vOtQ25oS ++XMkI/bceEsLqYwf/U1eGp22SufGze0Ceahp1NxjY5b1hWVzMNbtcVXO2mwycqphX ++iXCeKi1JLwQNDrL5VZzFpngps7F4ZUFTOAb+iFsq+yQVoJCuatgllQefVe7+853+ ++ZFpzBhYQxT5S7Bm8Q1izKGRh/iMvOMITCRYH3q8AictXTQ/2x1z87X4bxV4vDTZS ++VBSWvF7ZroJu/Avp8DR3BaVQu9Bz696GvFNTg1zKey/Fv3S93i2F5kQjXdLqx4GK ++8w7elf83+cprz5OcOBwaHJ9qEQiY/xVyoRQFKbZqUxN4Ncr2FC5rhXDRgJzwBMZg ++JnejarApm4/6seMrY7ebsbeiZuiF1fXK8vIusQ== ++=7dzs ++-----END PGP PUBLIC KEY BLOCK-----' ++ ++# verify_signature ++verify_signature() ++{ ++ local tarball="$1" sig_url="$2" pubkey="$3" expected_fpr="$4" ++ local gnupg_home sig_file ++ ++ gnupg_home=$(mktemp -d) ++ sig_file=$(mktemp) ++ trap 'rm -rf "$gnupg_home" "$sig_file"' RETURN ++ ++ wget -O "$sig_file" "$sig_url" ++ ++ GNUPGHOME="$gnupg_home" gpg --batch --quiet --import <<<"$pubkey" ++ ++ local verify_output ++ verify_output=$(GNUPGHOME="$gnupg_home" gpg --batch --status-fd 1 \ ++ --verify "$sig_file" "$tarball" 2>&1) ++ ++ if ! grep -q "^\[GNUPG:\] GOODSIG " <<<"$verify_output"; then ++ echo "ERROR: GPG signature verification FAILED for $tarball" >&2 ++ echo "$verify_output" >&2 ++ return 1 ++ fi ++ if ! grep -q "^\[GNUPG:\] VALIDSIG $expected_fpr " <<<"$verify_output"; then ++ echo "ERROR: $tarball was signed by an unexpected key (expected fingerprint $expected_fpr)" >&2 ++ echo "$verify_output" >&2 ++ return 1 ++ fi ++ echo "GPG signature OK: $tarball (verified against $expected_fpr)" ++} ++ ++install() ++{ ++ # The release publishes only signatures; they sign GitHub's tag archive. ++ WOLFSSL_LINK="https://github.com/wolfSSL/wolfssl/archive/refs/tags/v$WOLFSSL_VER-stable.tar.gz" ++ WOLFSSL_SIG_LINK="https://github.com/wolfSSL/wolfssl/releases/download/v$WOLFSSL_VER-stable/wolfssl-$WOLFSSL_VER-stable.tar.gz.asc" ++ echo "Build & Install wolfSSL version : $WOLFSSL_VER" ++ cd "$PARENT_DIR" ++ rm -f "wolfssl-$WOLFSSL_VER-stable.tar.gz" ++ wget -O "wolfssl-$WOLFSSL_VER-stable.tar.gz" "$WOLFSSL_LINK" ++ verify_signature "wolfssl-$WOLFSSL_VER-stable.tar.gz" "$WOLFSSL_SIG_LINK" \ ++ "$WOLFSSL_PUBKEY" "$WOLFSSL_GPG_FPR" ++ tar -xvzf "wolfssl-$WOLFSSL_VER-stable.tar.gz" ++ cd "wolfssl-$WOLFSSL_VER-stable" ++ ++ ./autogen.sh ++ # Feature set for FDO SDK. ++ ./configure --prefix="$WOLFSSL_ROOT" \ ++ --enable-ecc --enable-keygen --enable-certgen --enable-certreq \ ++ --enable-certext --enable-aesgcm --enable-aesccm --enable-aescfb \ ++ --enable-sha --enable-sha256 --enable-sha384 --enable-tls13 \ ++ --enable-harden --enable-wolftpm --enable-pkcallbacks --enable-curl \ ++ C_EXTRA_FLAGS="-DWOLFSSL_PUBLIC_MP -DWC_RNG_SEED_CB -DWOLFSSL_CUSTOM_OID -DHAVE_OID_ENCODING" ++ make -j"$(nproc)" ++ $SUDO make install ++ ++ echo "$WOLFSSL_ROOT/lib/" | $SUDO tee /etc/ld.so.conf.d/wolfssl.conf ++ $SUDO ldconfig ++ ++ echo "Build & Install Curl version : $CURL_VER, linked against wolfSSL" ++ cd "$PARENT_DIR" ++ rm -f "curl-$CURL_VER.tar.gz" ++ wget "$CURL_LINK" ++ verify_signature "curl-$CURL_VER.tar.gz" "$CURL_LINK.asc" \ ++ "$CURL_PUBKEY" "$CURL_GPG_FPR" ++ tar -xvzf "curl-$CURL_VER.tar.gz" ++ cd "curl-$CURL_VER" ++ ++ # Configure curl. ++ ./configure --prefix="$CURL_ROOT" --with-wolfssl="$WOLFSSL_ROOT" \ ++ --with-nghttp2 --enable-versioned-symbols --without-libpsl \ ++ --disable-aws ++ make -j"$(nproc)" ++ $SUDO make install ++ ++ # Exclude $CURL_ROOT/lib from ld.so.conf to avoid breaking system tools. ++ LD_LIBRARY_PATH="$CURL_ROOT/lib:$LD_LIBRARY_PATH" $CURL_ROOT/bin/curl -V ++} ++ ++ ++uninstall() ++{ ++ # The release publishes only signatures; they sign GitHub's tag archive. ++ WOLFSSL_LINK="https://github.com/wolfSSL/wolfssl/archive/refs/tags/v$WOLFSSL_VER-stable.tar.gz" ++ WOLFSSL_SIG_LINK="https://github.com/wolfSSL/wolfssl/releases/download/v$WOLFSSL_VER-stable/wolfssl-$WOLFSSL_VER-stable.tar.gz.asc" ++ echo "Uninstall wolfSSL version : $WOLFSSL_VER" ++ ++ cd "$PARENT_DIR" ++ rm -f "wolfssl-$WOLFSSL_VER-stable.tar.gz" ++ wget -O "wolfssl-$WOLFSSL_VER-stable.tar.gz" "$WOLFSSL_LINK" ++ verify_signature "wolfssl-$WOLFSSL_VER-stable.tar.gz" "$WOLFSSL_SIG_LINK" \ ++ "$WOLFSSL_PUBKEY" "$WOLFSSL_GPG_FPR" ++ tar -xvzf "wolfssl-$WOLFSSL_VER-stable.tar.gz" ++ cd "wolfssl-$WOLFSSL_VER-stable" ++ ++ ./autogen.sh ++ # Configure flags must match install() for `make uninstall` to remove all files. ++ ./configure --prefix="$WOLFSSL_ROOT" \ ++ --enable-ecc --enable-keygen --enable-certgen --enable-certreq \ ++ --enable-certext --enable-aesgcm --enable-aesccm --enable-aescfb \ ++ --enable-sha --enable-sha256 --enable-sha384 --enable-tls13 \ ++ --enable-harden --enable-wolftpm --enable-pkcallbacks --enable-curl \ ++ C_EXTRA_FLAGS="-DWOLFSSL_PUBLIC_MP -DWC_RNG_SEED_CB -DWOLFSSL_CUSTOM_OID -DHAVE_OID_ENCODING" ++ make -j"$(nproc)" ++ $SUDO make uninstall ++ cd "$PARENT_DIR" ++ rm -rf "wolfssl-$WOLFSSL_VER-stable" ++ rm -f "wolfssl-$WOLFSSL_VER-stable.tar.gz" ++ ++ $SUDO rm -f /etc/ld.so.conf.d/wolfssl.conf ++ $SUDO ldconfig ++ ++ echo "Uninstall Curl version : $CURL_VER" ++ # CURL_ROOT is removed wholesale, so it must be a prefix dedicated to ++ # this curl install, never a shared system prefix. ++ case "${CURL_ROOT%/}" in ++ ""|/|/usr|/usr/local|/opt|/home|"${HOME%/}") ++ echo "ERROR: refusing to remove shared prefix CURL_ROOT='$CURL_ROOT'" >&2 ++ exit 1 ++ ;; ++ esac ++ if [ ! -x "$CURL_ROOT/bin/curl" ]; then ++ echo "ERROR: no curl install found at CURL_ROOT='$CURL_ROOT'" >&2 ++ exit 1 ++ fi ++ $SUDO rm -rf "$CURL_ROOT" ++ rm -rf "$PARENT_DIR/curl-$CURL_VER" ++ rm -f "$PARENT_DIR/curl-$CURL_VER.tar.gz" ++} ++ ++install_wolftpm() ++{ ++ echo "Build & Install wolfTPM version : $WOLFTPM_VER" ++ cd "$PARENT_DIR" ++ rm -rf "wolftpm" ++ git clone --depth 1 -b "$WOLFTPM_VER" https://github.com/wolfSSL/wolfTPM.git wolftpm ++ cd wolftpm ++ ./autogen.sh ++ ./configure --prefix="$WOLFTPM_ROOT" --with-wolfcrypt="$WOLFSSL_ROOT" \ ++ --enable-devtpm --disable-fwtpm ++ make -j"$(nproc)" ++ $SUDO make install ++ cd "$PARENT_DIR" ++ rm -rf "wolftpm" ++} ++ ++uninstall_wolftpm() ++{ ++ echo "Uninstall wolfTPM version : $WOLFTPM_VER" ++ case "${WOLFTPM_ROOT%/}" in ++ ""|/|/usr|/usr/local|/opt|/home|"${HOME%/}") ++ echo "ERROR: refusing to remove shared prefix WOLFTPM_ROOT='$WOLFTPM_ROOT'" >&2 ++ exit 1 ++ ;; ++ esac ++ if [ ! -d "$WOLFTPM_ROOT" ]; then ++ echo "ERROR: no wolfTPM install found at WOLFTPM_ROOT='$WOLFTPM_ROOT'" >&2 ++ exit 1 ++ fi ++ $SUDO rm -rf "$WOLFTPM_ROOT" ++} ++ ++usage() ++{ ++ echo -e "Usage: ++ $0