diff --git a/.github/actions/tpm-interop/action.yml b/.github/actions/tpm-interop/action.yml new file mode 100644 index 00000000..d64aa191 --- /dev/null +++ b/.github/actions/tpm-interop/action.yml @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +name: tpm-interop +description: > + Build wolfSSL (config `wolftpm`, cached), wolfTPM with its fwTPM at + `wolftpm-ref`, and wolfCert with the examples, then run + tests/interop/tpm_wolftpm.sh. + +inputs: + wolfssl-ref: + description: "wolfSSL git ref to build" + required: false + default: master + wolftpm-ref: + description: "wolfTPM git ref to build (branch, tag or SHA)" + required: true + save: + description: "Save the wolfSSL cache after a miss" + required: false + default: "false" + +runs: + using: composite + steps: + - name: Install build dependencies + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y build-essential autoconf automake libtool \ + cmake pkg-config python3 + + - name: Build/restore wolfSSL (wolftpm) + uses: ./.github/actions/build-wolfssl + with: + config: wolftpm + ref: ${{ inputs.wolfssl-ref }} + save: ${{ inputs.save }} + + - name: Build wolfTPM and its fwTPM + shell: bash + run: | + set -euo pipefail + scripts/ci/build-wolftpm.sh --wolfssl "$WOLFSSL_PREFIX" \ + --ref "${{ inputs.wolftpm-ref }}" \ + --prefix "$RUNNER_TEMP/wolftpm" --src "$RUNNER_TEMP/wolftpm-src" + echo "WOLFTPM_PREFIX=$RUNNER_TEMP/wolftpm" >> "$GITHUB_ENV" + + - name: Build wolfCert with the TPM example + shell: bash + run: | + set -euo pipefail + cmake -S . -B build \ + -DWITH_WOLFSSL="$WOLFSSL_PREFIX" \ + -DWOLFCERT_ENABLE_EXAMPLES=ON -DWOLFCERT_WERROR=ON \ + -Dwolftpm_DIR="$WOLFTPM_PREFIX/lib/cmake/wolftpm" + cmake --build build -j "$(nproc)" + test -x build/examples/example_enroll_tpm + + - name: Run tpm_wolftpm.sh + shell: bash + run: | + set -euo pipefail + export LD_LIBRARY_PATH="$WOLFSSL_PREFIX/lib:$WOLFTPM_PREFIX/lib:${LD_LIBRARY_PATH:-}" + FWTPM_SERVER="$WOLFTPM_PREFIX/bin/fwtpm_server" \ + WOLFCERT_BUILD="$PWD/build" bash tests/interop/tpm_wolftpm.sh diff --git a/.github/workflows/interop.yml b/.github/workflows/interop.yml index a901c163..1353f226 100644 --- a/.github/workflows/interop.yml +++ b/.github/workflows/interop.yml @@ -143,3 +143,15 @@ jobs: bash tests/interop/est_stepca.sh; rc=$? [ "$rc" -eq 77 ] && { echo "::notice::step-ca skipped (dep missing)"; exit 0; } exit "$rc" + + wolftpm-fwtpm: + name: wolfTPM fwTPM (wolfTPM master) + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/tpm-interop + with: + wolfssl-ref: ${{ env.WOLFSSL_REF }} + wolftpm-ref: master + save: "true" # the only job on config wolftpm; pr.yml restores it diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 337de177..105f672c 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -44,8 +44,9 @@ jobs: - { name: cmake-mldsa-44off, os: ubuntu-latest, build: cmake, wolfssl: mldsa-44off } - { name: cmake-mldsa-65off, os: ubuntu-latest, build: cmake, wolfssl: mldsa-65off } - { name: cmake-mldsa-87off, os: ubuntu-latest, build: cmake, wolfssl: mldsa-87off } - # Platform pieces compiled out (transport/store gates) - - { name: cmake-no-builtin-transport, os: ubuntu-latest, build: cmake, wolfssl: full, cmake_extra: "-DWOLFCERT_ENABLE_BUILTIN_TRANSPORT=OFF -DWOLFCERT_ENABLE_POSIX_STORE=OFF -DWOLFCERT_ENABLE_CLI=OFF -DWOLFCERT_ENABLE_SERVER=OFF" } + - { name: cmake-no-cryptocb, os: ubuntu-latest, build: cmake, wolfssl: no-cryptocb, cmake_extra: "-DWOLFCERT_WERROR=ON -DWOLFCERT_ENABLE_EXAMPLES=ON" } + # Platform pieces compiled out (transport gate) + - { name: cmake-no-builtin-transport, os: ubuntu-latest, build: cmake, wolfssl: full, cmake_extra: "-DWOLFCERT_ENABLE_BUILTIN_TRANSPORT=OFF -DWOLFCERT_ENABLE_CLI=OFF -DWOLFCERT_ENABLE_SERVER=OFF" } # Constrained builds (unit tests only: single-thread / no-malloc) - { name: cmake-static-mem, os: ubuntu-latest, build: cmake, wolfssl: static-mem, cmake_extra: -DWOLFCERT_ENABLE_SERVER=OFF, ctest_exclude: "http|tls|roundtrip" } # No TLS and no test server over a static pool; stop_idle and get_cert diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 0212ae8d..20d60dd9 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -34,7 +34,7 @@ jobs: os: ubuntu-latest build: cmake wolfssl: full - cmake_extra: -DWOLFCERT_WERROR=ON + cmake_extra: -DWOLFCERT_WERROR=ON -DWOLFCERT_ENABLE_EXAMPLES=ON - name: cmake-full-opensslextra os: ubuntu-latest build: cmake @@ -94,6 +94,11 @@ jobs: os: ubuntu-latest build: cmake wolfssl: rsa-min + - name: cmake-no-cryptocb + os: ubuntu-latest + build: cmake + wolfssl: no-cryptocb + cmake_extra: -DWOLFCERT_WERROR=ON -DWOLFCERT_ENABLE_EXAMPLES=ON - name: cmake-no-des3 os: ubuntu-latest build: cmake @@ -115,7 +120,7 @@ jobs: os: ubuntu-latest build: cmake wolfssl: mldsa-87off - # Platform pieces compiled out (the transport/store gates) + # Platform pieces compiled out (the transport gate) - name: cmake-no-builtin-transport os: ubuntu-latest build: cmake @@ -124,7 +129,6 @@ jobs: # skip themselves. cmake_extra: >- -DWOLFCERT_ENABLE_BUILTIN_TRANSPORT=OFF - -DWOLFCERT_ENABLE_POSIX_STORE=OFF -DWOLFCERT_ENABLE_CLI=OFF -DWOLFCERT_ENABLE_SERVER=OFF # Constrained builds (unit tests only: single-thread / no-malloc) @@ -285,3 +289,15 @@ jobs: run: | scripts/ci/assert-configure-fails.sh \ --wolfssl-base "${{ github.workspace }}/.wolfssl-install" + + tpm-interop: + name: wolfTPM fwTPM interop (pinned wolfTPM) + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/tpm-interop + with: + wolfssl-ref: ${{ env.WOLFSSL_REF }} + # Merge of wolfTPM #638 (key ids); no release has it before v4.3.0. + wolftpm-ref: fe01b8ee096c862897c7efb4aa963c312e2bcc46 diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml index 08e9b559..b05d3810 100644 --- a/.github/workflows/sanitizers.yml +++ b/.github/workflows/sanitizers.yml @@ -117,7 +117,7 @@ jobs: # No roundtrips: wolfSSL's asm crypto gives false Memcheck reports # without a suppression file. rc=0 - for bin in test_smoke test_keygen test_csr test_store test_parse_negative \ + for bin in test_smoke test_keygen test_csr test_parse_negative \ test_scep_msg; do path="build/tests/$bin" [ -x "$path" ] || { echo "skip (not built): $bin"; continue; } diff --git a/.github/workflows/zephyr.yml b/.github/workflows/zephyr.yml index 69a04adf..10e9945a 100644 --- a/.github/workflows/zephyr.yml +++ b/.github/workflows/zephyr.yml @@ -74,7 +74,7 @@ jobs: "${{ github.workspace }}/scripts/ci/twister-assert-ran.py" \ "$HOME/twister-unit/twister.json" \ wolfcert.unit.smoke wolfcert.unit.keygen wolfcert.unit.csr \ - wolfcert.unit.csr_attrs wolfcert.unit.store \ + wolfcert.unit.csr_attrs \ wolfcert.unit.parse_negative wolfcert.unit.scep_msg - name: Start the host EST server diff --git a/AGENTS.md b/AGENTS.md index db1f6222..86453880 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ file. Changes to wolfCert itself follow `CONTRIBUTING.md`. Most integration failures are a wolfSSL built without what wolfCert needs. wolfCert requires **wolfSSL >= 5.9.4** and **hard-fails at configure time** if the wolfSSL it finds lacks any of `HAVE_PKCS7`, `WOLFSSL_CERT_GEN`, -`WOLFSSL_CERT_REQ`, `WOLFSSL_CERT_EXT`, `WOLFSSL_KEY_GEN`, `WOLF_CRYPTO_CB`, +`WOLFSSL_CERT_REQ`, `WOLFSSL_CERT_EXT`, `WOLFSSL_KEY_GEN`, `WOLFSSL_BASE64_ENCODE`, `WOLFSSL_ALT_NAMES` or `WOLFSSL_CERT_NAME_ALL`, was built with `NO_AES` / `NO_SHA256`, or provides neither TLS 1.2 nor TLS 1.3. @@ -41,6 +41,8 @@ built with `NO_AES` / `NO_SHA256`, or provides neither TLS 1.2 nor TLS 1.3. `OPENSSL_EXTRA`, `OPENSSL_EXTRA_X509_SMALL` or `WOLFSSL_TEST_CERT`. A static libwolfssl links them regardless. The OpenSSL compatibility layer itself is not required. +- **Hardware keys** need `WOLF_CRYPTO_CB` (`--enable-cryptocb`). Without it + wolfCert builds, but keys always run in software. - **ML-DSA** additionally needs `WOLFSSL_MLDSA_CHECK_KEY`, which `--enable-mldsa` gives by default; it is lost with `WOLFSSL_DILITHIUM_NO_CHECK_KEY` or `WOLFSSL_MLDSA_VERIFY_ONLY`. @@ -91,12 +93,11 @@ install provides the library, the public headers, a generated | `WOLFCERT_ENABLE_SERVER` | `--enable-server` | on | Minimal EST/SCEP test server | | `WOLFCERT_ENABLE_CLI` | `--enable-cli` | on | `wolfcert-client`, `wolfcert-server` | | `WOLFCERT_ENABLE_BUILTIN_TRANSPORT` | `--enable-builtin-transport` | on | POSIX socket transport; turn off on targets with no sockets | -| `WOLFCERT_ENABLE_POSIX_STORE` | `--enable-posix-store` | on | File-based cert/key store | | `WOLFCERT_BUILD_SHARED` | (libtool `--enable-shared`) | on | Shared vs static library | | `WOLFCERT_USER_SETTINGS` | `--enable-user-settings` | off | Read features from `user_settings.h` instead of the generated `options.h` | A device build usually turns off the server and CLI, and the built-in -transport and POSIX store where the target has no sockets or filesystem. +transport where the target has no sockets. ## Configuration model @@ -148,7 +149,7 @@ WolfCertServerCfg srv = { .verify_server = 1, }; WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=device-0001" }; WolfCertKey* key = NULL; WolfCertBuffer cert = { 0 }; @@ -176,7 +177,8 @@ wolfcert_cleanup(); `wolfcert_client_reenroll` return `WOLFCERT_ERR_PENDING`. - **Renewal:** `wolfcert_client_reenroll` (EST, authenticates with the certificate being renewed) or `wolfcert_scep_renewal_req`. -- **Hardware keys:** `examples/enroll_cryptocb.c`. +- **Hardware keys:** `examples/enroll_cryptocb.c`, and `examples/enroll_tpm.c` + for a TPM through wolfTPM. ## Where to look @@ -185,12 +187,11 @@ wolfcert_cleanup(); | `wolfcert/wolfcert.h` | Umbrella header, `wolfcert_init` / `wolfcert_cleanup` | | `wolfcert/client.h` | High-level `wolfcert_client_*` API | | `wolfcert/est.h`, `wolfcert/scep.h` | Protocol one-shots, sessions, non-blocking `_nb` sessions | -| `wolfcert/types.h` | `WolfCertServerCfg`, `WolfCertKeyCfg`, `WolfCertCertMeta`, `WolfCertEncoding` (PEM or DER output), `WolfCertTransport`, `wolfcert_buffer_free` | +| `wolfcert/types.h` | `WolfCertServerCfg`, `WolfCertKeyCfg`, `WolfCertCertMeta`, `WolfCertEncoding` (PEM or DER output), `WolfCertTransport`, `wolfcert_buffer_free` / `_secure` | | `wolfcert/keygen.h`, `wolfcert/csr.h` | Key generation, import / export, CSR building | -| `wolfcert/store.h` | `WolfCertStoreOps` storage vtable, POSIX and in-memory backends | | `wolfcert/errors.h`, `wolfcert/status.h`, `wolfcert/log.h` | Error codes, last-error detail, log callback | | `wolfcert/memory.h` | Default heap hint, allocation macros | -| `examples/` | `enroll_est.c`, `enroll_scep.c`, `enroll_cryptocb.c`, `user_settings.h.example` | +| `examples/` | `enroll_est.c`, `enroll_scep.c`, `enroll_cryptocb.c`, `enroll_tpm.c`, `user_settings.h.example` | | `examples/certs/` | Test credentials; never ship them | | `zephyr/samples/wolfcert_est_client/` | EST client on Zephyr (qemu_x86, FRDM-MCXN947) | | `src/` | Implementation; `src/internal.h` is not for applications | @@ -204,9 +205,10 @@ contract, alone or in a group comment. |---|---|---| | Static memory / custom heap | `wolfcert_init(heap)` sets the default heap hint; per-call `heap` fields override it, and the hint reaches every wolfSSL call | `wolfcert/memory.h`, README "Integrating with a wolfSSL static-memory pool" | | Network stack without BSD sockets (lwIP, NetX, FreeRTOS+TCP, wolfIP) | Fill `WolfCertServerCfg.transport` (`WolfCertTransport`); TLS records go through it too | `wolfcert/types.h`, `docs/EMBEDDED.md` section 7 | -| Persistence in flash / NVM | Implement `WolfCertStoreOps` (`read` / `write` / `remove`) | `wolfcert/store.h` | -| Keys in a TPM, HSM, PKCS#11 token or secure element | Register a backend with `wc_CryptoCb_RegisterDevice`, pass its id as `WolfCertKeyCfg.dev_id` | `docs/ARCHITECTURE.md` section 4.2, `examples/enroll_cryptocb.c` | +| Persistence in flash / NVM | Store the buffers from `wolfcert_key_to_pem` / `_to_der` and the enroll result; wolfCert does no storage | `wolfcert/keygen.h` | +| Keys in a TPM, HSM, PKCS#11 token or secure element | Register a backend with `wc_CryptoCb_RegisterDevice`, pass its id as `WolfCertKeyCfg.dev_id`, and the key's backend id as `key_id`; a key handle in `WolfCertServerCfg.client_key_obj` uses such a key for mTLS | `docs/ARCHITECTURE.md` section 4.2, `examples/enroll_cryptocb.c` | | Event loop / no blocking | `wolfcert_est_session_open` / `wolfcert_scep_session_open`, then the `_nb` calls until they stop returning `WOLFCERT_ERR_WANT_READ` / `_WANT_WRITE`; `*_session_fd` gives the descriptor to poll | `wolfcert/est.h`, `wolfcert/scep.h` | +| Crypto accelerator for TLS and PKCS#7 | `wolfcert_set_default_dev_id`, starting at `WOLFCERT_DEFAULT_DEVID` (wolfSSL's `WC_USE_DEVID` when set); a key uses it with `dev_id = wolfcert_default_dev_id()` | `wolfcert/types.h`, `docs/ARCHITECTURE.md` section 4.2 | | Logging | `wolfcert_set_log_cb` (e.g. to a UART) | `wolfcert/log.h` | | RAM budget | `max_response_bytes`, HTTP stack buffers, wolfSSL `Cert` / `CertName` sizing | `docs/EMBEDDED.md` | @@ -237,6 +239,9 @@ contract, alone or in a group comment. which every EST call and SCEP over `https://` refuse with `WOLFCERT_ERR_TLS`. Plain-HTTP SCEP ignores it and relies on the CA fingerprint check instead. +- **Set `dev_id` on every `WolfCertKeyCfg`.** `INVALID_DEVID` is software; + a zero-initialized config names CryptoCb device 0, which keygen refuses + with `WOLFCERT_ERR_BAD_ARG` unless such a device is registered. - **The `wolfcert_client_*` calls are EST-only except `get_ca`.** For SCEP they return `WOLFCERT_ERR_UNSUPPORTED`; use `wolfcert_scep_*`. - **SCEP rejects non-RSA keys** with `WOLFCERT_ERR_UNSUPPORTED`, and an ECC diff --git a/CMakeLists.txt b/CMakeLists.txt index 34a2c926..5b530def 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,7 +32,6 @@ option(WOLFCERT_ENABLE_SERVER "Build the minimal EST/SCEP test server" ON) option(WOLFCERT_ENABLE_CLI "Build wolfcert-client / wolfcert-server" ON) option(WOLFCERT_ENABLE_TESTS "Build unit and integration tests" OFF) option(WOLFCERT_ENABLE_EXAMPLES "Build example programs" OFF) -option(WOLFCERT_ENABLE_POSIX_STORE "Build the POSIX file storage backend" ON) option(WOLFCERT_ENABLE_BUILTIN_TRANSPORT "Build the built-in POSIX socket transport" ON) option(WOLFCERT_WERROR "Treat warnings as errors" OFF) @@ -85,7 +84,7 @@ if(NOT wolfssl_FOUND) "wolfSSL >= 5.9.4 not found via CMake config or pkg-config. " "wolfCert requires wolfSSL 5.9.4 or newer, built with: HAVE_PKCS7, " "WOLFSSL_CERT_GEN, WOLFSSL_CERT_REQ, WOLFSSL_CERT_EXT, " - "WOLFSSL_KEY_GEN, HAVE_ECC, WOLF_CRYPTO_CB, WOLFSSL_BASE64_ENCODE, " + "WOLFSSL_KEY_GEN, HAVE_ECC, WOLFSSL_BASE64_ENCODE, " "WOLFSSL_ALT_NAMES, WOLFSSL_CERT_NAME_ALL; a shared wolfSSL also " "needs WOLFSSL_PUBLIC_ASN.") endif() @@ -120,7 +119,7 @@ if(NOT _have_wolfssl_floor) message(FATAL_ERROR "wolfCert requires wolfSSL 5.9.4 or newer.") endif() foreach(sym IN ITEMS HAVE_PKCS7 WOLFSSL_CERT_GEN WOLFSSL_CERT_REQ WOLFSSL_CERT_EXT - WOLFSSL_KEY_GEN WOLF_CRYPTO_CB WOLFSSL_BASE64_ENCODE + WOLFSSL_KEY_GEN WOLFSSL_BASE64_ENCODE WOLFSSL_ALT_NAMES WOLFSSL_CERT_NAME_ALL) unset(_have_${sym} CACHE) check_c_source_compiles("${_wc_wolfssl_prologue} @@ -134,11 +133,18 @@ foreach(sym IN ITEMS HAVE_PKCS7 WOLFSSL_CERT_GEN WOLFSSL_CERT_REQ WOLFSSL_CERT_E "wolfSSL was built without ${sym}. Rebuild with the appropriate " "wolfSSL configure flag. For all the symbols wolfCert requires: " "./configure --enable-pkcs7 --enable-certgen --enable-certreq " - "--enable-certext --enable-keygen --enable-ecc --enable-cryptocb " + "--enable-certext --enable-keygen --enable-ecc " "--enable-base64encode " "CPPFLAGS=\"-DWOLFSSL_ALT_NAMES -DWOLFSSL_CERT_NAME_ALL\"") endif() endforeach() +unset(_have_WOLF_CRYPTO_CB CACHE) +check_c_source_compiles("${_wc_wolfssl_prologue} + #ifndef WOLF_CRYPTO_CB + #error missing + #endif + int main(void) { return 0; } +" _have_WOLF_CRYPTO_CB) # Link the WOLFSSL_ASN_API helpers wolfCert calls, without wolfSSL's headers. if(TARGET PkgConfig::WOLFSSL) @@ -312,8 +318,6 @@ if(NOT WOLFCERT_USER_SETTINGS) _wc_opt(WOLFCERT_OPT_EST "${WOLFCERT_ENABLE_EST}" WOLFCERT_HAVE_EST) _wc_opt(WOLFCERT_OPT_SCEP "${WOLFCERT_ENABLE_SCEP}" WOLFCERT_HAVE_SCEP) _wc_opt(WOLFCERT_OPT_SERVER "${WOLFCERT_ENABLE_SERVER}" WOLFCERT_HAVE_SERVER) - _wc_plat(WOLFCERT_OPT_POSIX_STORE "${WOLFCERT_ENABLE_POSIX_STORE}" - WOLFCERT_HAVE_POSIX_STORE WOLFCERT_NO_POSIX_STORE) _wc_plat(WOLFCERT_OPT_BUILTIN_TRANSPORT "${WOLFCERT_ENABLE_BUILTIN_TRANSPORT}" WOLFCERT_HAVE_BUILTIN_TRANSPORT WOLFCERT_NO_BUILTIN_TRANSPORT) @@ -335,7 +339,6 @@ set(WOLFCERT_SOURCES src/key_algs.c src/keygen.c src/csr.c - src/store.c src/http.c src/client.c) @@ -370,8 +373,8 @@ endif() add_library(wolfCert::wolfcert ALIAS wolfcert) set_target_properties(wolfcert PROPERTIES - VERSION ${PROJECT_VERSION} - SOVERSION ${PROJECT_VERSION_MAJOR} + VERSION 1.0.0 + SOVERSION 1 C_VISIBILITY_PRESET hidden) target_include_directories(wolfcert @@ -641,6 +644,6 @@ endif() message(STATUS "wolfCert ${PROJECT_VERSION}: EST=${WOLFCERT_ENABLE_EST}, " "SCEP=${WOLFCERT_ENABLE_SCEP}, server=${WOLFCERT_ENABLE_SERVER}, " - "cli=${WOLFCERT_ENABLE_CLI}, posix_store=${WOLFCERT_ENABLE_POSIX_STORE}, " + "cli=${WOLFCERT_ENABLE_CLI}, " "builtin_transport=${WOLFCERT_ENABLE_BUILTIN_TRANSPORT}, " "user_settings=${WOLFCERT_USER_SETTINGS}") diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4640c67f..d6483f97 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -102,10 +102,10 @@ Email **support@wolfssl.com** instead, and please keep the issue private until a `README.md` has the build and test steps, `docs/ARCHITECTURE.md` the module layout, and `AGENTS.md` the wolfSSL features wolfCert needs. On top of the rules above, wolfCert asks for: - **Heap hints on every allocation.** Allocate through `WOLFCERT_XMALLOC`, `WOLFCERT_XREALLOC` and `WOLFCERT_XFREE` from `wolfcert/memory.h` and pass the hint on to wolfSSL. A public API takes an optional `heap`, directly or in its config struct, and falls back to `wolfcert_default_heap()` when it is NULL. -- **No CryptoCb registration.** wolfCert never calls `wc_CryptoCb_RegisterDevice`; the application registers its backend and passes the `dev_id` in `WolfCertKeyCfg`. +- **No CryptoCb registration.** wolfCert never calls `wc_CryptoCb_RegisterDevice`; the application registers its backend and passes the `dev_id` in `WolfCertKeyCfg`. A backend-resident key is named by `WolfCertKeyCfg.key_id` (`wc_*_init_id`), never by a label, and is never exported. - **A closed set of error codes.** Report every error with `WOLFCERT_ERR`, `WOLFCERT_ERR_WC` or `WOLFCERT_ERR_RC_WC` from `src/internal.h`, and keep `wolfcert_strerror` covering every code in `wolfcert/errors.h`. - **Visibility.** Public and internal functions both use the `wolfcert_` prefix. The CMake build hides every symbol by default, so public prototypes in `wolfcert/*.h` carry `WOLFCERT_API`. Mark an internal function that the in-tree tests call `WOLFCERT_TEST_VIS`, which exports it only in a `WOLFCERT_BUILD_TESTING` build. -- **Append-only public structs.** The v0.1.0 ABI is released, so a new field in a public struct goes at its end. +- **Append-only public structs.** Within one shared library version, a new field in a public struct goes at its end; removing or moving a field needs a version bump. - **License header.** Every `.c` and `.h` file opens with the full GPL copyright block, copied from an existing source file; the Lint workflow checks it. Build files (`CMakeLists.txt`, `configure.ac`, `Makefile.am`) use the `SPDX-License-Identifier: GPL-3.0-or-later` line instead. - **Include order.** The module's own headers (``, `"internal.h"`) first, then wolfSSL, then system headers. - **Both build systems.** CMake and autoconf are kept at parity. A new source file goes into `CMakeLists.txt` and `Makefile.am` (or `zephyr/include.am` for Zephyr files), and a new non-source file into `EXTRA_DIST`. `scripts/ci/check-buildsystem-parity.sh` checks the library source lists. diff --git a/Makefile.am b/Makefile.am index 5b5ae968..d6d53355 100644 --- a/Makefile.am +++ b/Makefile.am @@ -19,7 +19,6 @@ libwolfcert_la_SOURCES = \ src/key_algs.h \ src/keygen.c \ src/csr.c \ - src/store.c \ src/http.c \ src/client.c @@ -53,7 +52,7 @@ endif endif libwolfcert_la_LIBADD = $(WOLFSSL_LIBS) -libwolfcert_la_LDFLAGS = -version-info 0:0:0 -no-undefined +libwolfcert_la_LDFLAGS = -version-info 1:0:0 -no-undefined wolfcertincludedir = $(includedir)/wolfcert wolfcertinclude_HEADERS = \ @@ -68,7 +67,6 @@ wolfcertinclude_HEADERS = \ wolfcert/types.h \ wolfcert/keygen.h \ wolfcert/csr.h \ - wolfcert/store.h \ wolfcert/http.h \ wolfcert/est.h \ wolfcert/scep.h \ @@ -106,7 +104,7 @@ endif if WOLFCERT_BUILD_TESTS check_PROGRAMS = \ - test_smoke test_keygen test_csr test_store test_http test_transport \ + test_smoke test_keygen test_csr test_http test_transport \ test_parse_negative test_tls_http if WOLFCERT_HAVE_BUILTIN_TRANSPORT check_PROGRAMS += test_net @@ -115,12 +113,11 @@ endif test_smoke_SOURCES = tests/unit/test_smoke.c test_smoke_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread test_keygen_SOURCES = tests/unit/test_keygen.c +test_keygen_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/src test_keygen_LDADD = libwolfcert.la $(WOLFSSL_LIBS) test_csr_SOURCES = tests/unit/test_csr.c test_csr_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/src test_csr_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -test_store_SOURCES = tests/unit/test_store.c -test_store_LDADD = libwolfcert.la $(WOLFSSL_LIBS) test_transport_SOURCES = tests/unit/test_transport.c test_transport_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/src test_transport_LDADD = libwolfcert.la $(WOLFSSL_LIBS) @@ -151,7 +148,8 @@ check_PROGRAMS += test_est_roundtrip test_est_tls_roundtrip test_est_mtls_roundt test_est_pha_roundtrip test_est_async_roundtrip \ test_est_csr_attrs_roundtrip test_est_csr_attrs_apply_roundtrip \ test_est_csr_attrs_enforce test_est_chunked_robustness \ - test_est_pending_roundtrip test_est_mldsa_roundtrip + test_est_pending_roundtrip test_est_mldsa_roundtrip \ + test_est_devid_roundtrip test_est_roundtrip_SOURCES = tests/integration/test_est_roundtrip.c test_est_roundtrip_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread test_est_tls_roundtrip_SOURCES = tests/integration/test_est_tls_roundtrip.c @@ -160,6 +158,8 @@ test_est_mtls_roundtrip_SOURCES = tests/integration/test_est_mtls_roundtrip.c test_est_mtls_roundtrip_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread test_est_mldsa_roundtrip_SOURCES = tests/integration/test_est_mldsa_roundtrip.c test_est_mldsa_roundtrip_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread +test_est_devid_roundtrip_SOURCES = tests/integration/test_est_devid_roundtrip.c +test_est_devid_roundtrip_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread test_est_pha_roundtrip_SOURCES = tests/integration/test_est_pha_roundtrip.c test_est_pha_roundtrip_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread test_est_async_roundtrip_SOURCES = tests/integration/test_est_async_roundtrip.c @@ -201,13 +201,13 @@ endif # Protocol-agnostic server tests. if WOLFCERT_HAVE_SERVER -check_PROGRAMS += test_server_stop_idle test_server_ca_store +check_PROGRAMS += test_server_stop_idle test_server_ca test_server_stop_idle_SOURCES = tests/integration/test_server_stop_idle.c test_server_stop_idle_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/src test_server_stop_idle_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread -test_server_ca_store_SOURCES = tests/unit/test_server_ca_store.c -test_server_ca_store_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/src -test_server_ca_store_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread +test_server_ca_SOURCES = tests/unit/test_server_ca.c +test_server_ca_CPPFLAGS = $(AM_CPPFLAGS) -I$(top_srcdir)/src +test_server_ca_LDADD = libwolfcert.la $(WOLFSSL_LIBS) -lpthread endif TESTS = $(check_PROGRAMS) diff --git a/README.md b/README.md index 1ba93fed..ecf85b92 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,11 @@ Start the bundled test server (issues from an auto-generated local CA): # listen address; SCEP authenticates at the pkiMessage layer instead. # EST also needs --basic USER:PASS, --tls-client-ca PEM, or # --est-allow-anonymous to issue to any client; /simplereenroll -# also needs --tls-client-ca and the KEEP_PEER_CERT build above. +# also needs --tls-client-ca or --tls-trust-issued (accept certificates +# this CA issued; --ca-dir DIR keeps the CA across restarts) and the +# KEEP_PEER_CERT build above. --tls-trust-issued with a --ca-dir that +# already holds the CA, and no other option, gives a server that only +# renews. ./wolfcert-server --proto est --listen 127.0.0.1:8443 \ --tls-cert server.crt --tls-key server.key --est-allow-anonymous ./wolfcert-server --proto scep --listen 127.0.0.1:8088 @@ -179,7 +183,11 @@ trusted. The signature digest floors at SHA-256 and needs no such override. To call the library directly, see `examples/enroll_est.c`, -`examples/enroll_scep.c`, and `examples/enroll_cryptocb.c`. +`examples/enroll_scep.c`, `examples/enroll_cryptocb.c` and +`examples/enroll_tpm.c`. CMake builds the TPM example as +`example_enroll_tpm` when it finds a wolfTPM with its CryptoCb (pass +`-Dwolftpm_DIR=/lib/cmake/wolftpm`). See +[wolfTPM](https://github.com/wolfSSL/wolfTPM). ### Integrating with a wolfSSL static-memory pool @@ -193,7 +201,7 @@ wolfcert_init(my_static_heap_hint); /* Per-object override (here: force a specific pool for a device key): */ WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE, + .dev_id = INVALID_DEVID, .heap = slow_path_pool }; wolfcert_key_generate(&cfg, &key); ``` @@ -219,8 +227,9 @@ All `WolfCertBuffer` outputs remember which heap they came from, so the same included, so a non-BSD-sockets stack (FreeRTOS+TCP, NetX, lwIP, wolfIP) needs one small glue file and no wolfCert change; the POSIX transport is the default instance and can be compiled out. -- **Storage:** file-based cert/key store with atomic writes and 0600 key-file - mode; pluggable via the `WolfCertStoreOps` vtable. +- **Storage is the application's:** keys export as PEM or DER + (`wolfcert_key_to_pem` / `_to_der`) and certificates come back as buffers, + to keep in a file, flash slot or secure element as the device requires. - **Test servers + CLIs** for Linux/macOS (`wolfcert-server`, `wolfcert-client`). The servers are for development and interop testing, not production CA use. diff --git a/cli/wolfcert_client.c b/cli/wolfcert_client.c index cbb85e54..1d396ab2 100644 --- a/cli/wolfcert_client.c +++ b/cli/wolfcert_client.c @@ -1451,7 +1451,7 @@ static int cmd_enroll(int argc, char** argv) WolfCertKey* key = NULL; WolfCertBuffer csr = { 0 }; WolfCertBuffer issued = { 0 }; - WolfCertKeyCfg kcfg = { .dev_id = WOLFCERT_DEVID_SOFTWARE }; + WolfCertKeyCfg kcfg = { .dev_id = INVALID_DEVID }; WolfCertProtocol p = 0; #ifdef WOLFCERT_HAVE_SCEP CaPin pin = { 0 }; diff --git a/cli/wolfcert_server.c b/cli/wolfcert_server.c index af68c096..71573d2a 100644 --- a/cli/wolfcert_server.c +++ b/cli/wolfcert_server.c @@ -19,8 +19,8 @@ /* * wolfcert-server - minimal EST/SCEP test server. Issues certificates - * against a local CA generated on startup. EST needs --tls-cert/--tls-key - * (RFC 7030); SCEP may be served over plaintext HTTP. + * against a local CA generated on startup or kept in --ca-dir. EST needs + * --tls-cert/--tls-key (RFC 7030); SCEP may be served over plaintext HTTP. */ #define _POSIX_C_SOURCE 200809L @@ -47,12 +47,16 @@ # define SCEP_FAULT_USAGE "" #endif +#include +#include #include #include #include #include #include #include +#include +#include static WolfCertServer* g_server = NULL; @@ -79,11 +83,13 @@ static void print_usage(FILE* out) " [--tls-cert PEM --tls-key PEM [--tls-client-ca PEM]]\n" " [--scep-require-approval] [--scep-enable-next-ca]\n" " [--scep-enable-get-cert] [--scep-split-ra]\n" - " [--est-allow-anonymous]\n" + " [--est-allow-anonymous] [--ca-dir DIR]\n" + " [--tls-trust-issued]\n" "\n" "Options:\n" " --proto est|scep Protocol to serve (required)\n" - " --listen ADDR:PORT Numeric IPv4 bind address (default 0.0.0.0:8080)\n" + " --listen ADDR:PORT Numeric IPv4 bind address (default 0.0.0.0:8080);\n" + " port 0 picks a free one\n" " --basic USER:PASS Require HTTP Basic auth (EST enroll); both non-empty\n" " --challenge PASS Require this SCEP challengePassword in the CSR\n" " --tls-cert PEMFILE Terminate TLS with this server certificate (PEM);\n" @@ -91,9 +97,16 @@ static void print_usage(FILE* out) " --tls-key PEMFILE Private key for --tls-cert (PEM)\n" " --tls-client-ca PEMFILE Require mutual TLS; verify clients against this CA\n" " --est-allow-anonymous Issue EST certificates to any client; --proto est\n" - " needs this, --basic or --tls-client-ca.\n" - " /simplereenroll also needs --tls-client-ca and a\n" - " KEEP_PEER_CERT wolfSSL\n" + " needs this, --basic, --tls-client-ca or\n" + " --tls-trust-issued with --ca-dir (renewal only).\n" + " /simplereenroll also needs --tls-client-ca or\n" + " --tls-trust-issued, and a KEEP_PEER_CERT wolfSSL\n" + " --ca-dir DIR Keep the CA in DIR, an existing directory, across\n" + " restarts\n" + " --tls-trust-issued Accept a TLS client certificate this server's CA\n" + " issued, to renew it (EST); it enrolls only with\n" + " --basic or --est-allow-anonymous, and any other\n" + " client certificate must chain to --tls-client-ca\n" " --scep-require-approval Defer SCEP PKCSReq/RenewalReq (pkiStatus=PENDING); issue\n" " on the first accepted GetCertInitial\n" " --scep-enable-next-ca Advertise + answer GetNextCACert (RFC 8894 section 4.7),\n" @@ -136,8 +149,9 @@ static int parse_listen(const char* arg, char** host, uint16_t* port) return 0; } - long p = strtol(colon + 1, NULL, 10); - if (p <= 0 || p > 65535) + char* end = NULL; + long p = strtol(colon + 1, &end, 10); + if (end == colon + 1 || *end != '\0' || p < 0 || p > 65535) return -1; *host = strndup(arg, (size_t)(colon - arg)); @@ -198,6 +212,119 @@ static uint8_t* slurp(const char* path, size_t* len) return b; } +/* DIR/name, or with tmp a mkstemp template next to it. */ +static int ca_dir_path(char* path, size_t cap, const char* dir, + const char* name, int tmp) +{ + int n = tmp ? snprintf(path, cap, "%s/.%s.XXXXXX", dir, name) + : snprintf(path, cap, "%s/%s", dir, name); + + return (n < 0 || (size_t)n >= cap) ? -1 : 0; +} + +/* Read DIR/name, a regular file of this user's with no `deny` mode bits; 1 + * when it does not exist, -2 for another owner, type or mode. */ +static int ca_dir_read(const char* dir, const char* name, mode_t deny, + uint8_t** out, size_t* len) +{ + char path[4096]; + struct stat st; + uint8_t* b = NULL; + size_t off = 0; + int fd; + + if (ca_dir_path(path, sizeof(path), dir, name, 0) != 0) + return -1; + fd = open(path, O_RDONLY); + if (fd < 0) + return errno == ENOENT ? 1 : -1; + if (fstat(fd, &st) != 0) { + close(fd); + return -1; + } + if (!S_ISREG(st.st_mode) || st.st_uid != geteuid() || + (st.st_mode & deny) != 0) { + close(fd); + return -2; + } + if (st.st_size > 0) + b = malloc((size_t)st.st_size); + while (b != NULL && off < (size_t)st.st_size) { + ssize_t n = read(fd, b + off, (size_t)st.st_size - off); + if (n < 0 && errno == EINTR) + continue; + if (n <= 0) + break; + off += (size_t)n; + } + close(fd); + if (b == NULL || off != (size_t)st.st_size) { + if (b != NULL) + wc_ForceZero(b, (word32)off); + free(b); + return -1; + } + *out = b; + *len = off; + return 0; +} + +/* Replace DIR/name with data through a temporary file and a rename. */ +static int ca_dir_write(const char* dir, const char* name, const uint8_t* data, + size_t len, mode_t mode) +{ + char path[4096]; + char tmp[4096]; + size_t off = 0; + int ok; + int fd; + + if (ca_dir_path(path, sizeof(path), dir, name, 0) != 0 || + ca_dir_path(tmp, sizeof(tmp), dir, name, 1) != 0) + return -1; + fd = mkstemp(tmp); + if (fd < 0) + return -1; + ok = fchmod(fd, mode) == 0; + while (ok && off < len) { + ssize_t n = write(fd, data + off, len - off); + if (n < 0 && errno == EINTR) + continue; + ok = n > 0; + if (ok) + off += (size_t)n; + } + ok = ok && fsync(fd) == 0; + ok = close(fd) == 0 && ok; + if (ok && rename(tmp, path) == 0) + return 0; + unlink(tmp); + return -1; +} + +/* Keep a CA the server generated in DIR, key first. */ +static int ca_dir_save(const char* dir, WolfCertServer* srv) +{ + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + int rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &cert, &key); + + if (rc == WOLFCERT_OK && + ca_dir_write(dir, "ca.key.der", key.data, key.len, 0600) != 0) + rc = WOLFCERT_ERR_IO; + if (rc == WOLFCERT_OK && + ca_dir_write(dir, "ca.cert.der", cert.data, cert.len, 0644) != 0) { + char path[4096]; + + if (ca_dir_path(path, sizeof(path), dir, "ca.key.der", 0) == 0) + unlink(path); + rc = WOLFCERT_ERR_IO; + } + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + return rc; +} + int main(int argc, char** argv) { static const struct option opts[] = { @@ -222,6 +349,8 @@ int main(int argc, char** argv) { "csrattrs-file", required_argument, NULL, 'F' }, { "est-require-csrattrs", no_argument, NULL, 'Q' }, { "est-allow-anonymous", no_argument, NULL, 'Y' }, + { "ca-dir", required_argument, NULL, 'D' }, + { "tls-trust-issued", no_argument, NULL, 'I' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { 0 } @@ -254,6 +383,8 @@ int main(int argc, char** argv) size_t csr_attrs_blob_len = 0; int est_require_csr_attrs = 0; int est_allow_anonymous = 0; + const char* ca_dir = NULL; + int tls_trust_issued = 0; int basic_rc; int c; @@ -380,6 +511,12 @@ int main(int argc, char** argv) case 'Y': est_allow_anonymous = 1; break; + case 'D': + ca_dir = optarg; + break; + case 'I': + tls_trust_issued = 1; + break; case 'V': printf("wolfcert-server %s\n", wolfcert_version_string()); return 0; @@ -417,12 +554,34 @@ int main(int argc, char** argv) } if (sel == WOLFCERT_PROTO_EST && user == NULL && tls_ca == NULL && - !est_allow_anonymous) { + !est_allow_anonymous && !tls_trust_issued) { fprintf(stderr, "wolfcert-server: --proto est requires --basic, " - "--tls-client-ca or --est-allow-anonymous\n"); + "--tls-client-ca, --est-allow-anonymous or " + "--tls-trust-issued\n"); return 1; } + /* DIR holds the CA private key. */ + if (ca_dir != NULL) { + struct stat st; + + if (stat(ca_dir, &st) != 0) { + fprintf(stderr, "wolfcert-server: --ca-dir %s: %s\n", ca_dir, + strerror(errno)); + return 1; + } + if (!S_ISDIR(st.st_mode)) { + fprintf(stderr, "wolfcert-server: --ca-dir %s is not a directory\n", + ca_dir); + return 1; + } + if (st.st_uid != geteuid() || (st.st_mode & (S_IWGRP | S_IWOTH)) != 0) { + fprintf(stderr, "wolfcert-server: --ca-dir %s must be owned by this " + "user and not writable by others\n", ca_dir); + return 1; + } + } + if (host == NULL) host = strdup("0.0.0.0"); @@ -484,9 +643,45 @@ int main(int argc, char** argv) .csr_attributes_len = csr_attrs_blob_len, .est_require_csr_attributes = est_require_csr_attrs, .est_allow_anonymous_enroll = est_allow_anonymous, + .tls_client_trust_issued = tls_trust_issued, }; - int rc = wolfcert_server_start(&cfg, &g_server); + int rc = WOLFCERT_OK; + uint8_t* ca_cert = NULL; + uint8_t* ca_key = NULL; + size_t ca_cert_len = 0; + size_t ca_key_len = 0; + int ca_new = 0; + + if (ca_dir != NULL) { + int cr = ca_dir_read(ca_dir, "ca.cert.der", S_IWGRP | S_IWOTH, + &ca_cert, &ca_cert_len); + int kr = ca_dir_read(ca_dir, "ca.key.der", S_IRWXG | S_IRWXO, + &ca_key, &ca_key_len); + + if (cr == -2 || kr == -2) { + fprintf(stderr, "wolfcert-server: --ca-dir %s: %s must be a " + "regular file owned by this user and not %s by others\n", + ca_dir, cr == -2 ? "ca.cert.der" : "ca.key.der", + cr == -2 ? "writable" : "accessible"); + rc = WOLFCERT_ERR_IO; + goto out; + } + if (cr < 0 || kr < 0 || cr != kr) { + fprintf(stderr, "wolfcert-server: --ca-dir %s: %s is missing or " + "unreadable\n", ca_dir, + cr != 0 ? "ca.cert.der" : "ca.key.der"); + rc = WOLFCERT_ERR_IO; + goto out; + } + ca_new = (cr == 1); + cfg.ca_cert = ca_cert; + cfg.ca_cert_len = ca_cert_len; + cfg.ca_key = ca_key; + cfg.ca_key_len = ca_key_len; + } + + rc = wolfcert_server_start(&cfg, &g_server); if (rc != WOLFCERT_OK) { const char* m = wolfcert_last_error_message(); fprintf(stderr, "wolfcert-server: start failed (%s)\n", wolfcert_strerror(rc)); @@ -494,6 +689,14 @@ int main(int argc, char** argv) fprintf(stderr, "wolfcert-server: %s\n", m); goto out; } + if (ca_new) { + rc = ca_dir_save(ca_dir, g_server); + if (rc != WOLFCERT_OK) { + fprintf(stderr, "wolfcert-server: cannot save the CA in --ca-dir " + "%s\n", ca_dir); + goto out; + } + } #ifdef CLI_SCEP_FAULTS if (sel == WOLFCERT_PROTO_SCEP) wolfcert_scep_server_set_caps_fault(g_server, scep_caps_status); @@ -521,6 +724,11 @@ int main(int argc, char** argv) out: wolfcert_server_free(g_server); g_server = NULL; + free(ca_cert); + if (ca_key != NULL) { + wc_ForceZero(ca_key, (word32)ca_key_len); + free(ca_key); + } free(host); free(user); free_secret(pass); diff --git a/configure.ac b/configure.ac index d1b98956..6295bcda 100644 --- a/configure.ac +++ b/configure.ac @@ -79,12 +79,6 @@ cannot supply a custom one])]) round-trip tests drive the client over real sockets])]) ]) -# Only the POSIX backend inside store.c is gated, so no AM_CONDITIONAL. -AC_ARG_ENABLE([posix-store], - [AS_HELP_STRING([--disable-posix-store], - [do not build the POSIX file storage backend])], - [enable_posix_store=$enableval], [enable_posix_store=yes]) - AC_ARG_ENABLE([tests], [AS_HELP_STRING([--enable-tests], [build unit and integration tests])], [enable_tests=$enableval], [enable_tests=no]) @@ -138,9 +132,8 @@ PKG_CHECK_MODULES([WOLFSSL], [wolfssl >= 5.9.4], [AC_MSG_ERROR([wolfssl >= 5.9.4 not found via pkg-config. wolfCert requires a wolfSSL build with HAVE_PKCS7, WOLFSSL_CERT_GEN, WOLFSSL_CERT_REQ, WOLFSSL_CERT_EXT, WOLFSSL_KEY_GEN, HAVE_ECC, - WOLF_CRYPTO_CB, WOLFSSL_BASE64_ENCODE, WOLFSSL_ALT_NAMES, - WOLFSSL_CERT_NAME_ALL; a shared wolfSSL also needs - WOLFSSL_PUBLIC_ASN.])]) + WOLFSSL_BASE64_ENCODE, WOLFSSL_ALT_NAMES, WOLFSSL_CERT_NAME_ALL; + a shared wolfSSL also needs WOLFSSL_PUBLIC_ASN.])]) AM_CONDITIONAL([HAVE_WOLFSSL], [test "x$have_wolfssl" = "xyes"]) # Probe wolfSSL's feature set the way wolfcert/check_config.h resolves it, so @@ -182,10 +175,10 @@ AC_DEFUN([WOLFCERT_PLAT], save_CPPFLAGS="$CPPFLAGS" CPPFLAGS="$CPPFLAGS $WOLFSSL_CFLAGS" AC_CHECK_DECLS([HAVE_PKCS7, WOLFSSL_CERT_GEN, WOLFSSL_CERT_REQ, WOLFSSL_CERT_EXT, - WOLFSSL_KEY_GEN, WOLF_CRYPTO_CB, WOLFSSL_BASE64_ENCODE, + WOLFSSL_KEY_GEN, WOLFSSL_BASE64_ENCODE, WOLFSSL_ALT_NAMES, WOLFSSL_CERT_NAME_ALL], [], [AC_MSG_ERROR([wolfSSL is missing a required feature (see above). - Rebuild wolfSSL with --enable-pkcs7 --enable-ecc --enable-cryptocb + Rebuild wolfSSL with --enable-pkcs7 --enable-ecc --enable-certgen --enable-certreq --enable-certext --enable-keygen --enable-base64encode CPPFLAGS="-DWOLFSSL_ALT_NAMES -DWOLFSSL_CERT_NAME_ALL".])], @@ -307,8 +300,6 @@ AS_IF([test "x$have_rsa" = "xno" && test "x$have_ecc" = "xno" \ WOLFCERT_OPT([WOLFCERT_OPT_EST], [$enable_est], [WOLFCERT_HAVE_EST]) WOLFCERT_OPT([WOLFCERT_OPT_SCEP], [$enable_scep], [WOLFCERT_HAVE_SCEP]) WOLFCERT_OPT([WOLFCERT_OPT_SERVER], [$enable_server], [WOLFCERT_HAVE_SERVER]) -WOLFCERT_PLAT([WOLFCERT_OPT_POSIX_STORE], [$enable_posix_store], - [WOLFCERT_HAVE_POSIX_STORE], [WOLFCERT_NO_POSIX_STORE]) WOLFCERT_PLAT([WOLFCERT_OPT_BUILTIN_TRANSPORT], [$enable_builtin_transport], [WOLFCERT_HAVE_BUILTIN_TRANSPORT], [WOLFCERT_NO_BUILTIN_TRANSPORT]) WOLFCERT_OPT([WOLFCERT_OPT_RSA], [$have_rsa], [WOLFCERT_HAVE_RSA]) @@ -363,7 +354,6 @@ AC_MSG_NOTICE([ Ed448=$have_ed448 ML-DSA=$have_mldsa TLS 1.2/1.3 : $have_tls12 / $have_tls13 Test server : $enable_server - POSIX store : $enable_posix_store Builtin transp: $enable_builtin_transport User settings : $enable_user_settings CLI tools : $enable_cli diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f70d7dbd..cb09a36f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -44,7 +44,7 @@ A few constraints shape the whole library: CryptoCb itself. The application registers its own (TPM, HSM, PKCS#11, custom) and passes the resulting `devId` through `WolfCertKeyCfg.dev_id`; wolfCert threads that into every wolfSSL crypto call on the key. -4. **Pluggable storage and protocol handling via vtables** (see +4. **Pluggable algorithms, transport and protocol handling via vtables** (see [section 5](#5-extension-points)). 5. **Event-loop-friendly I/O.** Every keep-alive session (HTTP, EST, SCEP) takes non-blocking `_nb` calls that surface `WOLFCERT_ERR_WANT_READ` / @@ -80,7 +80,7 @@ wolfCert is organised in four layers, top to bottom: +----------------------------------------------------------------------+ | public API headers (wolfcert/*.h) | | wolfcert.h (umbrella) client.h est.h scep.h http.h | - | keygen.h csr.h store.h server.h memory.h errors.h status.h | + | keygen.h csr.h server.h memory.h errors.h status.h | +----------------------------------------------------------------------+ | +----------------------------------------------------------------------+ @@ -91,7 +91,7 @@ wolfCert is organised in four layers, top to bottom: +----------------------------------------------------------------------+ | subsystem layer | | keygen / key_algs csr http (TLS + keep-alive + async) | - | store pkcs7_util server + ca_issue memory / errors / logging | + | pkcs7_util server + ca_issue memory / errors / logging | +----------------------------------------------------------------------+ | +----------------------------------------------------------------------+ @@ -323,29 +323,82 @@ hosts. ### 4.2 CryptoCb offload (TPM / HSM / PKCS#11 / custom) wolfCert uses wolfSSL's CryptoCb `devId` as an opaque token. The application -registers the backend; wolfCert threads the devId through every crypto call: +registers the backend; wolfCert threads the devId into every key it creates: ```c /* Application startup: register the CryptoCb with wolfSSL. */ wc_CryptoCb_RegisterDevice(MY_DEVID, my_callback, my_ctx); -/* Generate a key that lives behind the CryptoCb. */ +/* Generate a key inside the backend, under an id the backend defines. */ +static const uint8_t id[] = { 0x01, 0x80, 0x00, 0x01 }; WolfCertKeyCfg cfg = { - .type = WOLFCERT_KEY_ECC, - .param = 256, - .dev_id = MY_DEVID, - .key_label = "tpm:/handles/0x01800001", /* optional */ + .type = WOLFCERT_KEY_ECC, + .param = 256, + .dev_id = MY_DEVID, + .key_id = id, + .key_id_len = sizeof(id), }; WolfCertKey* key; wolfcert_key_generate(&cfg, &key); ``` -From there, every wolfSSL crypto call on the key — CSR signing, TLS handshake -client-auth, SCEP pkiMessage signing — routes through `my_callback`. Pass -`WOLFCERT_DEVID_SOFTWARE` (`-1`) to force software operation. CryptoCb-resident -keys typically can't be exported in PEM, so `wolfcert_key_to_pem` will fail; -persist the key by its `key_label` instead and resolve it against your backend -on the next boot. See `examples/enroll_cryptocb.c` for a full example. +`dev_id` and `key_id` answer different questions. `dev_id` picks the +registered CryptoCb device that runs an operation; `key_id` names one key +inside that device. Together they decide where each operation runs: + +| | `INVALID_DEVID` | `dev_id` only | `dev_id` + `key_id` | +|---|---|---|---| +| Key generation | software | device | device; the key stays there | +| CSR signature | software | key's device | key's device | +| TLS client-auth signature (`client_key_obj`) | default devId | default devId (loaded as DER) | key's device | +| Export, SCEP signing | yes | only if the private half is in host memory | `WOLFCERT_ERR_UNSUPPORTED` | +| Reload in a later run | from PEM or DER | from PEM or DER | `wolfcert_key_from_id` | +| TLS connection, SCEP PKCS#7 and RNGs | default devId | default devId | default devId | + +The last row is work wolfCert sets up itself, with no caller field to pick +a device, so it runs on `wolfcert_default_dev_id()` whatever key is used. + +The `key_id` bytes are opaque to wolfCert. They reach the backend in the +wolfCrypt key's `id` field, as with wolfPKCS11, wolfHSM and the hardware +ports, and the backend decides what they mean (a PKCS#11 `CKA_ID`, a TPM +handle, a key-store slot). The backend may rename the key, as a TPM does +when it picks a transient handle; `wolfcert_key_id` returns the id in use. +wolfSSL also hands the backend public-key operations on that id, such as +the check of its own RSA signature in TLS, so the backend must serve those +too. + +The default devId starts as `WOLFCERT_DEFAULT_DEVID`: `WC_USE_DEVID` when +wolfSSL defines it, as the NXP EdgeLock port does, else `INVALID_DEVID`. A +build may define it in `user_settings.h`. `wolfcert_set_default_dev_id` +changes it at run time and `wolfcert_cleanup` restores it. With +`INVALID_DEVID`, TLS still keeps a devId wolfSSL picks itself (CAAM, ARIA, +MAXQ10xx). The built-in test server always runs in software. + +For TLS client authentication, give the key as PEM or DER in `client_key`, +or as a handle in `client_key_obj`; only a handle can carry a `key_id`. EST +`/simplereenroll` passes the key being renewed as the handle. + +A key with a `key_id` is never exported, so persist its id and the issued +certificate. `wolfcert_key_from_id` rebuilds the handle from those two, +taking the public half from the certificate, and the handle then serves for +TLS client authentication and re-enrollment. + +RSA, ECC and ML-DSA keys take a `key_id`; Ed25519 and Ed448 need a wolfSSL +newer than 5.9.4 (`wc_ed25519_init_id`, `wc_ed448_init_id`). SCEP does not +take one, because its PKCS#7 code needs the private key as DER. A `key_id` +needs wolfSSL built with `WOLF_CRYPTO_CB` and `WOLF_PRIVATE_KEY_ID`; +`examples/enroll_cryptocb.c` shows the registration. + +`examples/enroll_tpm.c` enrolls and re-enrolls over EST with an ECC, RSA or +ML-DSA key in a TPM. It needs a wolfTPM whose CryptoCb reads a 4-byte +`key_id` as a persistent or transient handle. A key generated under a +persistent handle is stored there. Under `0x80000000` +(`WOLFTPM2_KEYID_TRANSIENT`) the TPM picks a transient handle, and a TPM +reset drops the key, as does `/dev/tpmrm0` when the process exits. An older +wolfTPM generates the key in software, which `wolfcert_key_generate` +refuses. ML-DSA needs a TPM with the v1.85 commands, such as wolfTPM's +fwTPM. For a test CA that renews the certificates it issued, start the EST +server from README.md with `--ca-dir DIR --tls-trust-issued` added. ### 4.3 Keep-alive sessions and non-blocking I/O @@ -432,27 +485,16 @@ Key points: its in-flight state; don't mutate the request/response between calls. - **One in-flight request per session** — pipelining is not supported. -### 4.4 Pluggable storage for flash / NVM +### 4.4 Persisting keys and certificates -Populate a `WolfCertStoreOps` with your backend and hand it to the store -helpers: - -```c -WolfCertStoreOps flash_ops = { - .read = flash_read, - .write = flash_write, - .remove = flash_remove, - .heap = my_heap, - .ctx = &my_flash_state, -}; -wolfcert_store_write_cert(&flash_ops, "device.crt", cert.data, cert.len); -``` - -Keys are opaque strings — map them to flash slots, handles, or paths however -your storage layer prefers. `sensitive = 1` on a write tells you the blob is -private-key material; enforce whatever access-control or encryption policy the -device needs. `wolfcert_store_write_key` / `_read_key` round-trip a -`WolfCertKey` via PEM and always mark the write sensitive. +wolfCert does not store anything. An enroll returns the certificate in a +`WolfCertBuffer`, `wolfcert_key_to_pem` / `_to_der` export a software key, and +`wolfcert_key_from_pem` reads one back. Write them wherever the device keeps +credentials. A renewal replaces the certificate and, on a rekey, the key, so +keep the old pair until both new halves are written. Keep exported keys +readable only by the device's own process, and free their buffers with +`wolfcert_buffer_free_secure()`. A key that stays in a CryptoCb backend is not +exported; keep the reference the backend needs. ### 4.5 Logging & errors on targets without stdio @@ -586,7 +628,8 @@ wolfcert_set_log_cb(my_log, NULL); /* 2. Key generation (stays in hardware) */ WolfCertKey* key; WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = MY_DEVID }; + .dev_id = MY_DEVID, + .key_id = my_key_id, .key_id_len = my_key_id_len }; wolfcert_key_generate(&kcfg, &key); /* 3. CSR build */ @@ -613,9 +656,9 @@ wolfcert_est_session_open(&srv, &s); run_nb_loop(s); /* pattern from section 4.3 */ wolfcert_est_session_close(s); -/* 5. Persist to flash through our storage backend */ -wolfcert_store_write_cert(&flash_ops, "device.crt", cert.data, cert.len); -/* key stays behind the CryptoCb; persist its label instead */ +/* 5. Persist the certificate; the key stays behind the CryptoCb, and + * wolfcert_key_from_id rebuilds the handle for re-enrollment */ +flash_write("device.crt", cert.data, cert.len); /* 6. Shutdown */ wolfcert_key_free(key); @@ -626,7 +669,7 @@ wolfcert_cleanup(); ## 5. Extension points -Four small vtables carry all of wolfCert's pluggability. Each is a "fill in a +Three small vtables carry all of wolfCert's pluggability. Each is a "fill in a struct, no library changes" extension: - **`WolfCertKeyAlg`** (`src/key_algs.c`) — algorithm dispatch. Adding a key @@ -634,10 +677,6 @@ struct, no library changes" extension: wolfSSL constants and `alloc_init` / `make` / `priv_decode` / `priv_to_der` / `free_` callbacks, plus an optional `WOLFCERT_HAVE_` compile guard. No edits to `keygen.c`, `csr.c`, or `ca_issue.c`. -- **`WolfCertStoreOps`** (`wolfcert/store.h`) — storage backend. Supply - `read` / `write` / `remove` callbacks and a private `ctx`; keys are opaque - strings. Shipped backends: POSIX files (atomic write, 0600 key mode) and - in-memory. See [section 4.4](#44-pluggable-storage-for-flash--nvm). - **`WolfCertTransport`** (`wolfcert/types.h`) — the bytes on the wire. Supply `connect` / `read` / `write` / `disconnect` and a private `ctx` to run wolfCert on a non-BSD-sockets stack; TLS rides the same callbacks through an @@ -676,8 +715,9 @@ time `#error`s. See [`EMBEDDED.md`](EMBEDDED.md#configuring-wolfcert-without-its **Required wolfSSL features** (build hard-fails with a "rebuild wolfSSL with --enable-X" diagnostic if missing): `HAVE_PKCS7`, `WOLFSSL_CERT_GEN`, -`WOLFSSL_CERT_REQ`, `WOLFSSL_CERT_EXT`, `WOLFSSL_KEY_GEN`, `WOLF_CRYPTO_CB`, -`WOLFSSL_BASE64_ENCODE`, `WOLFSSL_ALT_NAMES`, `WOLFSSL_CERT_NAME_ALL`. A +`WOLFSSL_CERT_REQ`, `WOLFSSL_CERT_EXT`, `WOLFSSL_KEY_GEN`, +`WOLFSSL_BASE64_ENCODE`, `WOLFSSL_ALT_NAMES`, `WOLFSSL_CERT_NAME_ALL`. +`WOLF_CRYPTO_CB` is optional; without it keys run in software. A `NO_RSA` build hard-fails unless SCEP is disabled, and so does one without AES-128-CBC encrypt and decrypt (`NO_AES_128`, `NO_AES_CBC` or `NO_AES_DECRYPT`), which RFC 8894 makes mandatory. CMake and autoconf also @@ -704,4 +744,5 @@ one key algorithm must be present. - `wolfcert/*.h` — the authoritative API reference; each public function and field states its contract, alone or in a group comment. - `examples/enroll_est.c`, `examples/enroll_scep.c`, - `examples/enroll_cryptocb.c` — runnable minimal integrations. + `examples/enroll_cryptocb.c`, `examples/enroll_tpm.c` - runnable minimal + integrations. diff --git a/docs/CI.md b/docs/CI.md index 4fe270ba..c308ebe2 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -11,12 +11,12 @@ set skips the wolfSSL build entirely. | Workflow | Trigger | What it does | |----------|---------|--------------| -| `pr.yml` | PR + push | Merge gate: CMake (`-Werror`) + autoconf + ASan/UBSan on the canonical config, the same config against the minimum wolfSSL release (`cmake-full-floor`), plus per-PR feature/config gating — EST-only, SCEP-only, server-off, the key-alg variants (NO_RSA, ECC-only, RSA-only, no-3DES), TLS 1.3-only, the three ML-DSA per-level builds, the static-memory and no-malloc constrained builds, the platform-pieces-off build (`cmake-no-builtin-transport`), the freestanding ARM compile and config-resolution check (`no-posix-arm`), the header-only (`WOLFCERT_USER_SETTINGS`) build, a macOS build, and the two cheapest configure-must-fail assertions. | -| `lint.yml` | PR + push | GPL license-header check and CMake↔autoconf parity of both the library and test source lists, plus the Zephyr module's library list and the version in `configure.ac`, `CMakeLists.txt` and `wolfcert/version.h` (`scripts/ci/check-buildsystem-parity.sh`). No wolfSSL build, so it fails in seconds. | +| `pr.yml` | PR + push | Merge gate: CMake (`-Werror`) + autoconf + ASan/UBSan on the canonical config, the same config against the minimum wolfSSL release (`cmake-full-floor`), plus per-PR feature/config gating - EST-only, SCEP-only, server-off, the key-alg variants (NO_RSA, ECC-only, RSA-only, no-3DES), TLS 1.3-only, the three ML-DSA per-level builds, the static-memory and no-malloc constrained builds, the platform-pieces-off build (`cmake-no-builtin-transport`), the freestanding ARM compile and config-resolution check (`no-posix-arm`), the header-only (`WOLFCERT_USER_SETTINGS`) build, a macOS build, the two cheapest configure-must-fail assertions, and `tests/interop/tpm_wolftpm.sh` against wolfTPM's fwTPM at a pinned wolfTPM commit. | +| `lint.yml` | PR + push | GPL license-header check and CMake↔autoconf parity of both the library and test source lists and of the shared library version, plus the Zephyr module's library list and the version in `configure.ac`, `CMakeLists.txt` and `wolfcert/version.h` (`scripts/ci/check-buildsystem-parity.sh`). No wolfSSL build, so it fails in seconds. | | `sbom.yml` | PR + push | Generates the SBOM with `make sbom` and `cmake --build --target sbom` against the `full` wolfSSL config, from `options.h` and from `examples/user_settings.h.example`, checks each with `tools/sbom/validate_sbom.py`, `pyspdxtools` and `scripts/ci/check-sbom.py` (identity, license, hash source, that the library hash matches a real `make install` / `cmake --install`, the `options.h` feature set, the wolfSSL dependency version, no host paths), checks that a second run is byte-identical and that both build systems and both configuration modes record the same configuration, and checks `tools/sbom/` against its pinned wolfssl-compliance-tooling commit. See [`SBOM.md`](SBOM.md). | | `nightly.yml` | schedule + dispatch | Re-runs the wolfSSL-variant build matrix against fresh wolfSSL `master`, the macOS extras, and the full negative-config set. Also **reseeds the wolfSSL prefix caches** so the next day's PRs restore instead of build. The feature/config gating itself now runs per-PR (see `pr.yml`). | | `sanitizers.yml` | schedule + dispatch | ASan+UBSan over the full test suite, ThreadSanitizer over the threaded integration roundtrips (against a TSAN-instrumented wolfSSL), and valgrind over a representative subset. | -| `interop.yml` | schedule + dispatch | Third-party EST/SCEP interop (openssl, micromdm/scep, globalsign/est, cisco/libest, smallstep/step-ca). Best-effort: a dependency that fails to install makes its script exit 77, which is treated as a neutral skip; a real interop regression fails. | +| `interop.yml` | schedule + dispatch | Third-party EST/SCEP interop (openssl, micromdm/scep, globalsign/est, cisco/libest, smallstep/step-ca), and `tpm_wolftpm.sh` against wolfTPM `master`, which also reseeds the `wolftpm` wolfSSL cache the PR job restores. Best-effort: a dependency that fails to install makes its script exit 77, which is treated as a neutral skip; a real interop regression fails. | | `zephyr.yml` | PR + push, schedule + dispatch | Three jobs sharing the west workspace setup (`.github/actions/zephyr-workspace`), each run once per Zephyr release in its matrix (v4.4.2 and v4.5.0). Each job saves its own ccache and restores it, or else the newest one for its toolchain. Only runs on the default branch save caches; the workspace cache is saved by the `qemu_x86` job alone. The `qemu_x86` job runs the Zephyr module on `qemu_x86`: the unit suites, and an EST enrollment gate plus the sample against a host `wolfcert-server`, including a build of the sample with a custom trust anchor. The `qemu_x86 build-only` job builds the rows for off-default Kconfig combinations (tagged `wolfcert_build`). The `mcxn` job builds the EST sample for `frdm_mcxn947/mcxn947/cpu0` with the SDK's `arm-zephyr-eabi` toolchain and checks the sample's `wolfcert-sbom` output; [`zephyr/README.md`](../zephyr/README.md#est-client-sample) lists what CI covers per board. `scripts/ci/twister-assert-ran.py` checks that each step's suites actually ran. | ## wolfSSL configurations @@ -37,8 +37,9 @@ Config names include `full` (all algorithms), `full-tsan`, `full-opensslextra` setups stay covered), `full-all` (`full` plus `--enable-all`, which brings `OPENSSL_ALL` and its compatible defaults), `est-only-nonrsa` (NO_RSA), `rsa-min`, `ecc-only-est`, `no-des3`, `tls13-only`, `mldsa-{44,65,87}off`, -`static-mem`, `no-malloc`, and the `neg-*` configs used by the negative-config -gate. +`static-mem`, `no-malloc`, `no-cryptocb` (no `WOLF_CRYPTO_CB`), `wolftpm` +(`full` plus what wolfTPM's fwTPM needs), and the `neg-*` configs used by the +negative-config gate. ## Reproducing a CI job locally diff --git a/docs/EMBEDDED.md b/docs/EMBEDDED.md index 24f2e881..9e8a3abc 100644 --- a/docs/EMBEDDED.md +++ b/docs/EMBEDDED.md @@ -35,9 +35,10 @@ clear `#error` rather than a confusing downstream error. It enforces the same rules the configure step does: at least one key algorithm, SCEP requires RSA and AES-128-CBC (both RFC 8894, so `NO_AES_128`, `NO_AES_CBC` and `NO_AES_DECRYPT` rule SCEP out), and the wolfSSL feature set wolfCert depends -on (PKCS#7, cert gen/req/ext, key gen, CryptoCb, base64 encode, alt names, -`WOLFSSL_CERT_NAME_ALL`, AES, SHA-256, and TLS 1.2 or 1.3). The header you copy -documents the matching wolfSSL configure flags. +on (PKCS#7, cert gen/req/ext, key gen, base64 encode, alt names, +`WOLFSSL_CERT_NAME_ALL`, AES, SHA-256, and TLS 1.2 or 1.3). CryptoCb is +optional and only needed for hardware keys. The header you copy documents the +matching wolfSSL configure flags. A **shared** libwolfssl must also export the ASN helpers wolfCert calls, which takes `WOLFSSL_PUBLIC_ASN` (the lean choice) or the OpenSSL compatibility layer; @@ -303,17 +304,17 @@ with ECC or a PQC algorithm, disabling SCEP avoids pulling in RSA. ## 7. Targets without BSD sockets or a filesystem -Two platform pieces can be compiled out entirely, so a target that has -neither a socket API nor a filesystem links neither. +The one platform piece, the socket transport, can be compiled out entirely, +so a target without a socket API does not link it. wolfCert never touches a +filesystem. | Macro | Off means | Build flags | `user_settings.h` | |---|---|---|---| | `WOLFCERT_HAVE_BUILTIN_TRANSPORT` | `src/net_posix.c` is not compiled | `-DWOLFCERT_ENABLE_BUILTIN_TRANSPORT=OFF` / `--disable-builtin-transport` | `#define WOLFCERT_NO_BUILTIN_TRANSPORT` | -| `WOLFCERT_HAVE_POSIX_STORE` | the POSIX file store backend is stubbed out | `-DWOLFCERT_ENABLE_POSIX_STORE=OFF` / `--disable-posix-store` | `#define WOLFCERT_NO_POSIX_STORE` | -Each pair is mandatory-one-of: `check_config.h` fails the build when a +The pair is mandatory-one-of: `check_config.h` fails the build when a config defines neither the `WOLFCERT_HAVE_*` nor the `WOLFCERT_NO_*` form, -so compiling a backend out is always an explicit decision. The configure +so compiling the transport out is always an explicit decision. The configure builds emit the right macro automatically; only a `user_settings.h` build writes it by hand. @@ -322,8 +323,6 @@ leaving it NULL is `WOLFCERT_ERR_BAD_ARG`. Writing one is a small glue file in your own tree - `connect` / `read` / `write` / `disconnect` over your stack, no TLS code - described in [`ARCHITECTURE.md` section 4.6](ARCHITECTURE.md#46-pluggable-transport). -With the store off, `wolfcert_store_posix_open()` returns NULL and the -in-memory backend or your own `WolfCertStoreOps` carries persistence. The CLI tools and the built-in test server both need real sockets, so both build systems reject enabling them alongside `--disable-builtin-transport`. diff --git a/docs/INTEROP.md b/docs/INTEROP.md index 33667d17..6430b38e 100644 --- a/docs/INTEROP.md +++ b/docs/INTEROP.md @@ -17,10 +17,12 @@ Because a failed dependency *build* also ends in a 77 skip (the binary never lan | `est_globalsign.sh` | globalsign/est (Go) | wolfcert-client <-> globalsign estserver/estclient, both directions. | | `est_libest.sh` | cisco/libest (built from source) | wolfcert-client -> libest estserver, libest estclient -> wolfcert-server. | | `est_stepca.sh` | smallstep/step-ca (Go) | EST probe + SCEP enrollment against step-ca, plus a `--ca-id` GetCACert check. | +| `tpm_wolftpm.sh` | wolfTPM's fwTPM (`scripts/ci/build-wolftpm.sh`) | `examples/enroll_tpm` with keys in the fwTPM against wolfcert-server, for ECC P-256 and P-384, RSA-2048 and ML-DSA-44/65/87: enroll, renew in place, rekey, cleanup after a failure, a restart of both servers, and transient handles. Also runs in `pr.yml` at a pinned wolfTPM commit. | ## Dependency build notes - **cisco/libest** is archived and written for OpenSSL 1.x. On a modern OpenSSL 3.0 host it needs two build tweaks (applied in `interop.yml`): `--disable-safec` (its configure now demands an explicit safec choice) and a force-included compat header defining `FIPS_mode()` / `FIPS_mode_set()` as no-ops (OpenSSL 3.0 removed both symbols, which libest still references). +- **wolfTPM** needs a wolfSSL built with `--enable-wolftpm` (the `wolftpm` config of `build-wolfssl.sh`). `build-wolftpm.sh` builds the library and `fwtpm_server` with `WOLFTPM_V185=yes`, so ML-DSA cannot drop out unnoticed. The fwTPM holds 8 persistent objects, so `tpm_wolftpm.sh` gives each key type its own NV state. - **smallstep/step-ca** links `libpcsclite` via cgo (PC/SC, for its PIV/YubiKey provisioners); install `libpcsclite-dev` before `go install`, or the build aborts at pkg-config. ## Notes diff --git a/docs/MIGRATING-FROM-WOLFSCEP.md b/docs/MIGRATING-FROM-WOLFSCEP.md index 09c96c95..df0452bf 100644 --- a/docs/MIGRATING-FROM-WOLFSCEP.md +++ b/docs/MIGRATING-FROM-WOLFSCEP.md @@ -98,7 +98,7 @@ wolfcert_scep_get_ca_caps(&srv, &caps); /* 3) Key and CSR. */ WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; wolfcert_key_generate(&kcfg, &key); @@ -190,8 +190,7 @@ Link against `libwolfcert` and include ``, which pulls in t - **EST (RFC 7030)** for the same lifecycle over TLS, with ECC, Ed25519, Ed448 and ML-DSA keys, none of which SCEP permits. - **Keep-alive sessions with `_nb` calls**, so several operations share one connection and an event loop can drive them through `WOLFCERT_ERR_WANT_READ` and `WOLFCERT_ERR_WANT_WRITE`. -- **CryptoCb offload.** Register your TPM, HSM or PKCS#11 backend with wolfSSL and pass the resulting `dev_id` in `WolfCertKeyCfg`; the private key never has to be in memory. -- **Pluggable storage** through `WolfCertStoreOps` for flash and NVM targets. +- **CryptoCb offload.** Register your TPM, HSM or PKCS#11 backend with wolfSSL and pass the resulting `dev_id` in `WolfCertKeyCfg`. With the key's `key_id` as well, the private key stays in the backend (`docs/ARCHITECTURE.md` section 4.2). SCEP itself still needs a software key. - **Static memory.** Every allocation carries a heap hint, so wolfCert runs on a wolfSSL built `WOLFSSL_NO_MALLOC` with a static pool. - **A tested interop matrix**, described in `INTEROP.md`. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 083244fa..32f33b34 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -4,8 +4,38 @@ if(WOLFCERT_ENABLE_EST) add_executable(example_enroll_est enroll_est.c) target_link_libraries(example_enroll_est PRIVATE wolfcert) - add_executable(example_enroll_cryptocb enroll_cryptocb.c) - target_link_libraries(example_enroll_cryptocb PRIVATE wolfcert) + if(_have_WOLF_CRYPTO_CB) + add_executable(example_enroll_cryptocb enroll_cryptocb.c) + target_link_libraries(example_enroll_cryptocb PRIVATE wolfcert) + + if(TARGET PkgConfig::WOLFSSL) + set(_wc_example_wolfssl PkgConfig::WOLFSSL) + else() + set(_wc_example_wolfssl wolfssl::wolfssl) + endif() + + find_package(wolftpm CONFIG QUIET) + unset(_have_tpm_key_id CACHE) + if(TARGET wolfssl::wolftpm) + set(CMAKE_REQUIRED_LIBRARIES wolfssl::wolftpm ${_wc_example_wolfssl}) + check_c_source_compiles("${_wc_wolfssl_prologue} + #include + #if !defined(WOLFTPM_CRYPTOCB) || !defined(WOLF_PRIVATE_KEY_ID) + #error missing + #endif + int main(void) { return 0; } + " _have_tpm_key_id) + unset(CMAKE_REQUIRED_LIBRARIES) + endif() + if(_have_tpm_key_id) + add_executable(example_enroll_tpm enroll_tpm.c) + target_link_libraries(example_enroll_tpm + PRIVATE wolfcert wolfssl::wolftpm) + else() + message(STATUS "wolfCert: wolfTPM not found or without its " + "CryptoCb, skipping examples/enroll_tpm.c") + endif() + endif() endif() if(WOLFCERT_ENABLE_SCEP) diff --git a/examples/enroll_cryptocb.c b/examples/enroll_cryptocb.c index ed92f099..80e071f4 100644 --- a/examples/enroll_cryptocb.c +++ b/examples/enroll_cryptocb.c @@ -33,6 +33,9 @@ #include #include +#ifndef WOLF_CRYPTO_CB +# error "examples/enroll_cryptocb.c needs wolfSSL built with --enable-cryptocb" +#endif #include #include @@ -63,10 +66,10 @@ int main(int argc, char** argv) return 1; } - /* Pass the device id; the rest matches the software path. */ + /* Pass the device id. A backend that stores keys also takes .key_id, + * which this pass-through one cannot serve. */ WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = MY_DEV_ID, - .key_label = "demo/device-key" }; + .dev_id = MY_DEV_ID }; WolfCertKey* key = NULL; if (wolfcert_key_generate(&kcfg, &key) != WOLFCERT_OK) { fprintf(stderr, "keygen failed\n"); diff --git a/examples/enroll_est.c b/examples/enroll_est.c index cd56b571..8bbb326d 100644 --- a/examples/enroll_est.c +++ b/examples/enroll_est.c @@ -75,10 +75,10 @@ int main(int argc, char** argv) /* 1) Generate an Ed25519 key, or P-256 when wolfSSL lacks Ed25519. */ #ifdef WOLFCERT_HAVE_ED25519 WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ED25519, .param = 0, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; #else WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; #endif WolfCertKey* key = NULL; if (wolfcert_key_generate(&kcfg, &key) != WOLFCERT_OK) diff --git a/examples/enroll_scep.c b/examples/enroll_scep.c index 2f7f3a42..1dbcde3c 100644 --- a/examples/enroll_scep.c +++ b/examples/enroll_scep.c @@ -112,7 +112,7 @@ int main(int argc, char** argv) /* 3) Generate RSA key + CSR. */ WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; if (wolfcert_key_generate(&kcfg, &key) != WOLFCERT_OK) return 2; diff --git a/examples/enroll_tpm.c b/examples/enroll_tpm.c new file mode 100644 index 00000000..1f316534 --- /dev/null +++ b/examples/enroll_tpm.c @@ -0,0 +1,432 @@ +/* + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfCert. + * + * wolfCert 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. + * + * wolfCert 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 wolfCert. If not, see . + */ + +/* + * EST enrollment and re-enrollment with a private key that stays in a TPM. + * The key_id is the key's 4-byte TPM handle, persistent (0x81xxxxxx) or + * transient (0x80xxxxxx). A new key goes to a free persistent handle, or for + * 0x80000000 to a transient handle the TPM picks. A TPM resource manager such + * as /dev/tpmrm0 flushes a transient key when the process exits. + * + * Usage: + * enroll_tpm enroll URL TRUST_PEM SUBJECT KEY_TYPE HANDLE OUT_CERT + * enroll_tpm reenroll URL TRUST_PEM KEY_TYPE HANDLE CERT OUT_CERT + * [NEW_HANDLE] + * KEY_TYPE is ecc:256, ecc:384, rsa:2048 or, with a wolfTPM built for + * TPM 2.0 v1.85, mldsa:44, mldsa:65 or mldsa:87. e.g. + * ./enroll_tpm enroll https://127.0.0.1:8443/.well-known/est ca.pem \ + * "CN=device-42" ecc:256 0x81000100 dev.crt + * ./enroll_tpm reenroll https://127.0.0.1:8443/.well-known/est ca.pem \ + * ecc:256 0x81000100 dev.crt dev2.crt 0x81000101 + */ + +#define _POSIX_C_SOURCE 200809L + +#include +#ifndef WOLFCERT_HAVE_EST +# error "examples/enroll_tpm.c needs wolfCert built with EST enabled" +#endif + +#include +#if !defined(WOLFTPM_CRYPTOCB) || !defined(WOLF_PRIVATE_KEY_ID) +# error "examples/enroll_tpm.c needs wolfTPM's CryptoCb and wolfSSL key ids" +#endif +/* An older wolfTPM lacks it, and keygen then fails at run time */ +#ifndef WOLFTPM2_KEYID_TRANSIENT +# define WOLFTPM2_KEYID_TRANSIENT TRANSIENT_FIRST +#endif + +#include +#include +#include +#include + +typedef struct { + WOLFTPM2_DEV dev; + WOLFTPM2_KEY srk; + TpmCryptoDevCtx ctx; + int dev_id; +} Tpm; + +static uint8_t* read_whole(const char* path, size_t* out_len) +{ + FILE* f = fopen(path, "rb"); + if (!f) + return NULL; + + long len = -1; + if (fseek(f, 0, SEEK_END) == 0) + len = ftell(f); + if (len <= 0 || fseek(f, 0, SEEK_SET) != 0) { + fclose(f); + return NULL; + } + uint8_t* b = (uint8_t*)malloc((size_t)len); + if (!b || fread(b, 1, (size_t)len, f) != (size_t)len) { + free(b); + fclose(f); + return NULL; + } + + fclose(f); + *out_len = (size_t)len; + return b; +} + +/* Writes through a synced temporary file, so a failure keeps the old file. */ +static int write_whole(const char* path, const WolfCertBuffer* b) +{ + char tmp[4096]; + + if (snprintf(tmp, sizeof(tmp), "%s.tmp", path) >= (int)sizeof(tmp)) + return -1; + remove(tmp); + FILE* f = fopen(tmp, "wbx"); + if (!f) + return -1; + + int ok = fwrite(b->data, 1, b->len, f) == b->len; + ok = ok && fflush(f) == 0 && fsync(fileno(f)) == 0; + ok = fclose(f) == 0 && ok; + if (ok && rename(tmp, path) == 0) + return 0; + remove(tmp); + return -1; +} + +static const struct { + const char* name; + WolfCertKeyType type; + int param; +} key_types[] = { + { "ecc:256", WOLFCERT_KEY_ECC, 256 }, + { "ecc:384", WOLFCERT_KEY_ECC, 384 }, + { "rsa:2048", WOLFCERT_KEY_RSA, 2048 }, +#ifdef WOLFTPM_MLDSA_SIGN + { "mldsa:44", WOLFCERT_KEY_MLDSA44, 0 }, + { "mldsa:65", WOLFCERT_KEY_MLDSA65, 0 }, + { "mldsa:87", WOLFCERT_KEY_MLDSA87, 0 }, +#endif +}; + +static int parse_key_type(const char* s, WolfCertKeyCfg* cfg) +{ + for (size_t i = 0; i < sizeof(key_types) / sizeof(key_types[0]); i++) { + if (strcmp(s, key_types[i].name) == 0) { + cfg->type = key_types[i].type; + cfg->param = key_types[i].param; + return 0; + } + } + fprintf(stderr, "unknown KEY_TYPE %s\n", s); + return -1; +} + +static int parse_handle(const char* s, TPM_HANDLE* h, uint8_t id[4]) +{ + char* end = NULL; + unsigned long v = strtoul(s, &end, 0); + + if (end == s || *end != '\0' || + ((v >> HR_SHIFT) != TPM_HT_PERSISTENT && + (v >> HR_SHIFT) != TPM_HT_TRANSIENT)) { + fprintf(stderr, "HANDLE %s is not a persistent (0x81xxxxxx) or " + "transient (0x80xxxxxx) handle\n", s); + return -1; + } + *h = (TPM_HANDLE)v; + id[0] = (uint8_t)(v >> 24); + id[1] = (uint8_t)(v >> 16); + id[2] = (uint8_t)(v >> 8); + id[3] = (uint8_t)v; + return 0; +} + +static void tpm_close(Tpm* t) +{ + if (t->dev_id != INVALID_DEVID) + wolfTPM2_ClearCryptoDevCb(&t->dev, t->dev_id); + if (t->srk.handle.hndl != 0) + wolfTPM2_UnloadHandle(&t->dev, &t->srk.handle); + wolfTPM2_Cleanup(&t->dev); +} + +static int tpm_open(Tpm* t) +{ + memset(t, 0, sizeof(*t)); + t->dev_id = INVALID_DEVID; + + /* /dev/tpmrm0 and socket TPMs such as the fwTPM take no I/O callback. */ + int rc = wolfTPM2_Init(&t->dev, NULL, NULL); + if (rc != 0) { + fprintf(stderr, "TPM: %s\n", wolfTPM2_GetRCString(rc)); + return rc; + } + rc = wolfTPM2_CreateSRK(&t->dev, &t->srk, TPM_ALG_ECC, NULL, 0); + if (rc == 0) { + t->ctx.storageKey = &t->srk; + rc = wolfTPM2_SetCryptoDevCb(&t->dev, wolfTPM2_CryptoDevCb, &t->ctx, + &t->dev_id); + } + if (rc != 0) { + fprintf(stderr, "TPM: %s\n", wolfTPM2_GetRCString(rc)); + tpm_close(t); + } + return rc; +} + +static int new_handle_ok(Tpm* t, TPM_HANDLE handle) +{ + WOLFTPM2_KEY k; + int ok; + + memset(&k, 0, sizeof(k)); + if ((handle >> HR_SHIFT) == TPM_HT_TRANSIENT) + ok = handle == WOLFTPM2_KEYID_TRANSIENT; + else { + int rc = wolfTPM2_ReadPublicKey(&t->dev, &k, handle); + + ok = rc > 0 && (rc & RC_MAX_FMT1) == TPM_RC_HANDLE; + if (rc != 0 && !ok) { + fprintf(stderr, "cannot check TPM handle 0x%08x (%s)\n", + (unsigned)handle, wolfTPM2_GetRCString(rc)); + return 0; + } + } + if (!ok) + fprintf(stderr, "a new key needs a free persistent handle or 0x%08x, " + "not 0x%08x\n", (unsigned)WOLFTPM2_KEYID_TRANSIENT, + (unsigned)handle); + return ok; +} + +/* The handle the TPM holds a key under, 0 if it has no key_id */ +static TPM_HANDLE key_handle(const WolfCertKey* key) +{ + const uint8_t* id = NULL; + size_t len = 0; + + if (key == NULL || wolfcert_key_id(key, &id, &len) != WOLFCERT_OK || + len != 4) + return 0; + return ((TPM_HANDLE)id[0] << 24) | ((TPM_HANDLE)id[1] << 16) | + ((TPM_HANDLE)id[2] << 8) | (TPM_HANDLE)id[3]; +} + +static int evict(Tpm* t, TPM_HANDLE handle) +{ + WOLFTPM2_KEY k; + + memset(&k, 0, sizeof(k)); + int rc = wolfTPM2_ReadPublicKey(&t->dev, &k, handle); + if (rc == 0 && (handle >> HR_SHIFT) == TPM_HT_PERSISTENT) + rc = wolfTPM2_NVDeleteKey(&t->dev, TPM_RH_OWNER, &k); + else if (rc == 0) + rc = wolfTPM2_UnloadHandle(&t->dev, &k.handle); + if (rc != 0) + fprintf(stderr, "cannot evict TPM handle 0x%08x (%s); clear it by " + "hand\n", (unsigned)handle, wolfTPM2_GetRCString(rc)); + return rc; +} + +static void report(const char* what, int rc) +{ + const char* m = wolfcert_last_error_message(); + fprintf(stderr, "%s failed: %s%s%s\n", what, wolfcert_strerror(rc), + m != NULL && *m != '\0' ? ": " : "", m != NULL ? m : ""); +} + +/* Shows a certificate that was issued but could not be kept. */ +static void show_cert(const char* why, const WolfCertBuffer* cert) +{ + fprintf(stderr, "%s:\n", why); + fwrite(cert->data, 1, cert->len, stderr); +} + +/* URL TRUST_PEM SUBJECT KEY_TYPE HANDLE OUT_CERT */ +static int cmd_enroll(Tpm* t, const WolfCertServerCfg* srv, char** argv) +{ + WolfCertKeyCfg kcfg = { .dev_id = t->dev_id }; + WolfCertCertMeta meta = { .subject_dn = argv[2] }; + WolfCertClient* client = NULL; + WolfCertKey* key = NULL; + WolfCertBuffer cert = { 0 }; + TPM_HANDLE handle; + uint8_t id[4]; + + if (parse_key_type(argv[3], &kcfg) != 0 || + parse_handle(argv[4], &handle, id) != 0) + return 1; + kcfg.key_id = id; + kcfg.key_id_len = sizeof(id); + if (!new_handle_ok(t, handle)) + return 1; + + int rc = wolfcert_client_new(&client); + if (rc == WOLFCERT_OK) + rc = wolfcert_client_enroll(client, srv, &kcfg, &meta, &key, &cert); + if (rc != WOLFCERT_OK) { + report("enroll", rc); + } + else if (write_whole(argv[5], &cert) != 0) { + fprintf(stderr, "cannot write %s\n", argv[5]); + rc = WOLFCERT_ERR_IO; + } + else { + printf("enrolled: key in TPM handle 0x%08x, certificate in %s\n", + (unsigned)key_handle(key), argv[5]); + } + /* A key under a key_id comes back on failure too. */ + if (rc != WOLFCERT_OK && key_handle(key) != 0 && + evict(t, key_handle(key)) == 0 && cert.data != NULL) + show_cert("revoke this certificate, its key is evicted", &cert); + + wolfcert_buffer_free(&cert); + wolfcert_key_free(key); + wolfcert_client_free(client); + return rc == WOLFCERT_OK ? 0 : 2; +} + +/* URL TRUST_PEM KEY_TYPE HANDLE CERT OUT_CERT [NEW_HANDLE] */ +static int cmd_reenroll(Tpm* t, const WolfCertServerCfg* srv, int argc, + char** argv) +{ + WolfCertKeyCfg cur_cfg = { .dev_id = t->dev_id }; + WolfCertKeyCfg new_cfg; + WolfCertCertMeta meta = { 0 }; + WolfCertClient* client = NULL; + WolfCertKey* cur_key = NULL; + WolfCertKey* new_key = NULL; + WolfCertBuffer renewed = { 0 }; + TPM_HANDLE handle; + TPM_HANDLE new_handle = 0; + uint8_t id[4]; + uint8_t new_id[4]; + size_t cert_len = 0; + uint8_t* cert = NULL; + int rekey = argc > 6; + + if (parse_key_type(argv[2], &cur_cfg) != 0 || + parse_handle(argv[3], &handle, id) != 0 || + (rekey && parse_handle(argv[6], &new_handle, new_id) != 0)) + return 1; + if (rekey && !new_handle_ok(t, new_handle)) + return 1; + if (rekey && (handle >> HR_SHIFT) == TPM_HT_PERSISTENT && + (new_handle >> HR_SHIFT) == TPM_HT_TRANSIENT) { + fprintf(stderr, "NEW_HANDLE must be persistent when HANDLE is; a " + "transient key does not survive a TPM reset\n"); + return 1; + } + cur_cfg.key_id = id; + cur_cfg.key_id_len = sizeof(id); + new_cfg = cur_cfg; + new_cfg.key_id = new_id; + + cert = read_whole(argv[4], &cert_len); + if (cert == NULL) { + fprintf(stderr, "cannot read %s\n", argv[4]); + return 1; + } + + /* The certificate supplies the public half of the TPM key. */ + int rc = wolfcert_key_from_id(&cur_cfg, cert, cert_len, &cur_key); + if (rc == WOLFCERT_OK) + rc = wolfcert_client_new(&client); + if (rc == WOLFCERT_OK) + rc = wolfcert_client_reenroll(client, srv, cert, cert_len, cur_key, + rekey ? &new_cfg : NULL, &meta, + &new_key, &renewed); + if (rc != WOLFCERT_OK) { + report("reenroll", rc); + } + else if (write_whole(argv[5], &renewed) != 0) { + fprintf(stderr, "cannot write %s\n", argv[5]); + if (!rekey) + show_cert("the renewed certificate", &renewed); + rc = WOLFCERT_ERR_IO; + } + else if (rekey) { + printf("re-enrolled: new key in TPM handle 0x%08x, certificate in %s\n", + (unsigned)key_handle(new_key), argv[5]); + if (evict(t, handle) == 0) + printf("old key at TPM handle 0x%08x evicted\n", (unsigned)handle); + } + else { + printf("re-enrolled: key in TPM handle 0x%08x, certificate in %s\n", + (unsigned)handle, argv[5]); + } + if (rc != WOLFCERT_OK && key_handle(new_key) != 0 && + evict(t, key_handle(new_key)) == 0 && renewed.data != NULL) + show_cert("revoke this certificate, its key is evicted", &renewed); + + wolfcert_buffer_free(&renewed); + wolfcert_key_free(new_key); + wolfcert_key_free(cur_key); + wolfcert_client_free(client); + free(cert); + return rc == WOLFCERT_OK ? 0 : 2; +} + +int main(int argc, char** argv) +{ + int enroll = argc == 8 && strcmp(argv[1], "enroll") == 0; + int reenroll = (argc == 8 || argc == 9) && strcmp(argv[1], "reenroll") == 0; + + if (!enroll && !reenroll) { + fprintf(stderr, + "usage: %s enroll URL TRUST_PEM SUBJECT KEY_TYPE HANDLE " + "OUT_CERT\n" + " %s reenroll URL TRUST_PEM KEY_TYPE HANDLE CERT OUT_CERT " + "[NEW_HANDLE]\n" + "KEY_TYPE: ecc:256, ecc:384, rsa:2048" +#ifdef WOLFTPM_MLDSA_SIGN + ", mldsa:44, mldsa:65, mldsa:87" +#endif + "\n", argv[0], argv[0]); + return 1; + } + + size_t trust_len = 0; + uint8_t* trust = read_whole(argv[3], &trust_len); + if (trust == NULL) { + fprintf(stderr, "cannot read %s\n", argv[3]); + return 1; + } + + WolfCertServerCfg srv = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = argv[2], + .trust_anchors = trust, + .trust_anchors_len = trust_len, + .verify_server = 1, + }; + Tpm tpm; + int ret = 1; + + if (wolfcert_init(NULL) == WOLFCERT_OK && tpm_open(&tpm) == 0) { + ret = enroll ? cmd_enroll(&tpm, &srv, argv + 2) + : cmd_reenroll(&tpm, &srv, argc - 2, argv + 2); + tpm_close(&tpm); + } + + wolfcert_cleanup(); + free(trust); + return ret; +} diff --git a/examples/user_settings.h.example b/examples/user_settings.h.example index abbf035a..63394fb1 100644 --- a/examples/user_settings.h.example +++ b/examples/user_settings.h.example @@ -38,9 +38,8 @@ #define WOLFCERT_HAVE_SCEP 1 /* SCEP (RFC 8894) - requires WOLFCERT_HAVE_RSA */ #define WOLFCERT_HAVE_SERVER 1 /* built-in EST/SCEP test server */ -/* Platform: each needs its HAVE or WOLFCERT_NO_* form; NO_* compiles the - * backend out and the application supplies its own transport / store ops. */ -#define WOLFCERT_HAVE_POSIX_STORE 1 +/* Platform: needs its HAVE or WOLFCERT_NO_* form; NO_* compiles the + * transport out and the application supplies its own. */ #define WOLFCERT_HAVE_BUILTIN_TRANSPORT 1 /* Key algorithms (at least one) */ diff --git a/scripts/ci/build-wolfssl.sh b/scripts/ci/build-wolfssl.sh index 1072bd6e..1ffd1281 100755 --- a/scripts/ci/build-wolfssl.sh +++ b/scripts/ci/build-wolfssl.sh @@ -39,7 +39,7 @@ KNOWN_CONFIGS=( est-only-nonrsa rsa-min ecc-only-est no-des3 tls13-only mldsa-44off mldsa-65off mldsa-87off - static-mem no-malloc + static-mem no-malloc no-cryptocb wolftpm # Negative configs for assert-configure-fails.sh. neg-no-rsa neg-no-pkcs7 neg-no-public-asn neg-no-aes128 ) @@ -119,6 +119,15 @@ resolve_flags() { _base_flags printf '%s\n' --enable-staticmemory \ 'CPPFLAGS=-DWOLFSSL_ALT_NAMES -DWOLFSSL_CERT_NAME_ALL -DKEEP_PEER_CERT -DWOLFSSL_HAVE_TLS_UNIQUE -DWOLFSSL_PUBLIC_ASN -DWOLFSSL_NO_MALLOC -DMAX_SIGNED_ATTRIBS_SZ=9' ;; + no-cryptocb) + # No WOLF_CRYPTO_CB, so no WOLF_PRIVATE_KEY_ID either. + _base_flags + printf '%s\n' --disable-cryptocb ;; + wolftpm) + # wolfTPM's fwTPM links the sp_* API and needs raw RSA. + _base_flags + printf '%s\n' --enable-wolftpm --enable-pkcallbacks \ + 'CPPFLAGS=-DWOLFSSL_ALT_NAMES -DWOLFSSL_CERT_NAME_ALL -DKEEP_PEER_CERT -DWOLFSSL_HAVE_TLS_UNIQUE -DWOLFSSL_PUBLIC_ASN -DWC_RSA_NO_PADDING' ;; # Negative configs: buildable wolfSSL builds that wolfCert rejects neg-no-rsa) diff --git a/scripts/ci/build-wolftpm.sh b/scripts/ci/build-wolftpm.sh new file mode 100755 index 00000000..6ef929e0 --- /dev/null +++ b/scripts/ci/build-wolftpm.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Build and install wolfTPM with its fwTPM for the TPM interop test. +# +# Usage: +# build-wolftpm.sh --wolfssl PREFIX [--prefix DIR] [--ref REF] [--jobs N] +# [--src DIR] +# +# Defaults: --ref master, --prefix $PWD/.wolftpm-install, --src +# $PWD/.wolftpm-src. Installs lib/cmake/wolftpm and bin/fwtpm_server. + +set -euo pipefail + +WOLFTPM_REPO="${WOLFTPM_REPO:-https://github.com/wolfSSL/wolfTPM.git}" + +WOLFSSL="" +PREFIX="$PWD/.wolftpm-install" +REF="${WOLFTPM_REF:-master}" +JOBS="" +SRC="$PWD/.wolftpm-src" + +while [ "$#" -gt 0 ]; do + case "$1" in + --wolfssl) WOLFSSL="$2"; shift 2 ;; + --prefix) PREFIX="$2"; shift 2 ;; + --ref) REF="$2"; shift 2 ;; + --jobs) JOBS="$2"; shift 2 ;; + --src) SRC="$2"; shift 2 ;; + *) echo "ERROR: unknown argument '$1'." >&2; exit 2 ;; + esac +done +if [ -z "$WOLFSSL" ] || [ ! -d "$WOLFSSL/include/wolfssl" ]; then + echo "ERROR: --wolfssl must name a wolfSSL install prefix." >&2 + exit 2 +fi +: "${JOBS:=$( (command -v nproc >/dev/null && nproc) || sysctl -n hw.ncpu 2>/dev/null || echo 2)}" + +echo "==> Building wolfTPM $REF against $WOLFSSL" +if [ -d "$SRC/.git" ]; then + git -C "$SRC" fetch -q origin "$REF" + git -C "$SRC" checkout -q --detach FETCH_HEAD +else + rm -rf "$SRC" + # A raw SHA cannot go through --branch, so fall back to a full clone. + git clone --depth 1 --branch "$REF" "$WOLFTPM_REPO" "$SRC" 2>/dev/null \ + || { git clone "$WOLFTPM_REPO" "$SRC" && git -C "$SRC" checkout "$REF"; } +fi +git -C "$SRC" log -1 --format=' commit: %H %s' + +# v1.85 is forced on, so a wolfSSL without ML-DSA fails here, not as missing +# ML-DSA in the test. +cmake -S "$SRC" -B "$SRC/build" \ + -DWITH_WOLFSSL="$WOLFSSL" \ + -DCMAKE_INSTALL_PREFIX="$PREFIX" \ + -DCMAKE_INSTALL_RPATH="$PREFIX/lib;$WOLFSSL/lib" \ + -DWOLFTPM_FWTPM=yes -DWOLFTPM_INTERFACE=SWTPM \ + -DWOLFTPM_V185=yes -DWOLFTPM_EXAMPLES=no +cmake --build "$SRC/build" -j "$JOBS" --target wolftpm fwtpm_server +cmake --install "$SRC/build" + +echo "==> Installed wolfTPM to $PREFIX" +echo "$PREFIX" diff --git a/scripts/ci/check-buildsystem-parity.sh b/scripts/ci/check-buildsystem-parity.sh index d4f1f71b..d952c4db 100755 --- a/scripts/ci/check-buildsystem-parity.sh +++ b/scripts/ci/check-buildsystem-parity.sh @@ -2,7 +2,8 @@ # SPDX-License-Identifier: GPL-3.0-or-later # # Fail on library or test source drift between CMake and autoconf, Zephyr -# module sources that differ from the client set, or a version mismatch. +# module sources that differ from the client set, or a version or shared +# library version mismatch. set -euo pipefail @@ -84,10 +85,25 @@ if [ -z "$am_ver" ] || [ "$am_ver" != "$cmake_ver" ] || \ status=1 fi +# Libtool's -version-info C:R:A installs libwolfcert.so.... +lt="$(sed -n 's/.*-version-info \([0-9]*:[0-9]*:[0-9]*\).*/\1/p' "$ROOT/Makefile.am")" +IFS=: read -r lt_c lt_r lt_a <<<"$lt" +lt_so=$((lt_c - lt_a)) +lt_ver="$lt_so.$lt_a.$lt_r" +props="$(sed -n '/^set_target_properties(wolfcert PROPERTIES/,/)/p' \ + "$ROOT/CMakeLists.txt")" +cm_ver="$(sed -n 's/^ *VERSION *\([^ ]*\)$/\1/p' <<<"$props")" +cm_so="$(sed -n 's/^ *SOVERSION *\([^ ]*\)$/\1/p' <<<"$props")" +if [ -z "$lt" ] || [ "$cm_ver" != "$lt_ver" ] || [ "$cm_so" != "$lt_so" ]; then + echo "ERROR: CMakeLists.txt VERSION ${cm_ver:-?} SOVERSION ${cm_so:-?} does"\ + "not match Makefile.am -version-info ${lt:-?}" + status=1 +fi + if [ "$status" -eq 0 ]; then echo "build-system parity OK: $(echo "$cmake_srcs" | wc -l | tr -d ' ') library"\ "sources, $(echo "$zephyr_srcs" | wc -l | tr -d ' ') of them in the Zephyr"\ - "module, $(echo "$cmake_tests" | wc -l | tr -d ' ') test sources and the"\ - "version ($am_ver) match." + "module, $(echo "$cmake_tests" | wc -l | tr -d ' ') test sources, the"\ + "version ($am_ver) and the library version $lt_ver match." fi exit "$status" diff --git a/scripts/ci/compile-freestanding.sh b/scripts/ci/compile-freestanding.sh index 5e879176..8f54a809 100755 --- a/scripts/ci/compile-freestanding.sh +++ b/scripts/ci/compile-freestanding.sh @@ -2,9 +2,9 @@ # SPDX-License-Identifier: GPL-3.0-or-later # # Compile every portable wolfCert source for a bare-metal ARM target: no POSIX -# headers, no built-in transport, no POSIX store, no test server. This keeps -# src/http.c, src/csr.c and src/store.c free of syscalls, so wolfCert can run on -# a non-BSD-sockets stack through a caller-supplied WolfCertTransport. +# headers, no built-in transport, no test server. This keeps src/http.c and +# src/csr.c free of syscalls, so wolfCert can run on a non-BSD-sockets stack +# through a caller-supplied WolfCertTransport. # # Compile-only, so it wants a wolfSSL checkout for headers rather than a build, # and finishes in seconds. Feature set: freestanding-user_settings.h alongside. diff --git a/scripts/ci/freestanding-user_settings.h b/scripts/ci/freestanding-user_settings.h index 7e423a77..33d6e5eb 100644 --- a/scripts/ci/freestanding-user_settings.h +++ b/scripts/ci/freestanding-user_settings.h @@ -18,7 +18,7 @@ */ /* Combined wolfSSL + wolfCert config for compile-freestanding.sh. The - * built-in transport, POSIX store, server and HAVE_SNI stay out on purpose. */ + * built-in transport, server and HAVE_SNI stay out on purpose. */ #ifndef WOLFSSL_USER_SETTINGS_H #define WOLFSSL_USER_SETTINGS_H @@ -67,7 +67,6 @@ /* wolfCert: no sockets, no filesystem */ #define WOLFCERT_NO_SNI #define WOLFCERT_NO_BUILTIN_TRANSPORT -#define WOLFCERT_NO_POSIX_STORE #define WOLFCERT_HAVE_EST 1 /* EST (RFC 7030) */ #define WOLFCERT_HAVE_SCEP 1 /* SCEP (RFC 8894) - requires WOLFCERT_HAVE_RSA */ #define WOLFCERT_HAVE_RSA 1 diff --git a/scripts/ci/wolfcert-only-user_settings.h b/scripts/ci/wolfcert-only-user_settings.h index 2d022d83..d25f5962 100644 --- a/scripts/ci/wolfcert-only-user_settings.h +++ b/scripts/ci/wolfcert-only-user_settings.h @@ -30,7 +30,6 @@ #define WOLFCERT_HAVE_SCEP 1 #define WOLFCERT_HAVE_SERVER 1 -#define WOLFCERT_HAVE_POSIX_STORE 1 #define WOLFCERT_HAVE_BUILTIN_TRANSPORT 1 #define WOLFCERT_HAVE_RSA 1 diff --git a/src/ca_issue.c b/src/ca_issue.c index f9da5cd2..1d3f0c36 100644 --- a/src/ca_issue.c +++ b/src/ca_issue.c @@ -17,7 +17,7 @@ * along with wolfCert. If not, see . */ -/* Test-server CA: generation, persistence and issuance from a CSR. */ +/* Test-server CA: generation, loading and issuance from a CSR. */ #define _POSIX_C_SOURCE 200809L #define _DEFAULT_SOURCE @@ -51,7 +51,7 @@ static WolfCertKey* ca_as_key(WolfCertCa* ca, WolfCertKey* shim) memset(shim, 0, sizeof(*shim)); shim->type = ca->type; shim->heap = ca->heap; - shim->dev_id = WOLFCERT_DEVID_SOFTWARE; + shim->dev_id = INVALID_DEVID; shim->impl = ca->impl; return shim; } @@ -61,6 +61,19 @@ static void ca_sync_from_shim(WolfCertCa* ca, const WolfCertKey* shim) ca->impl = shim->impl; } +/* Non-zero when wolfSSL copies the CA's subject key id unhashed to an AKID */ +int wolfcert_ca_skid_copies(const WolfCertCa* ca) +{ + DecodedCert dc; + int ok; + + wc_InitDecodedCert(&dc, ca->cert_der, (word32)ca->cert_der_len, ca->heap); + ok = wc_ParseCert(&dc, CERT_TYPE, NO_VERIFY, NULL) == 0 && + dc.extSubjKeyIdSet && dc.extSubjKeyIdSz == KEYID_SIZE; + wc_FreeDecodedCert(&dc); + return ok; +} + static int gen_self_signed_cert(WolfCertCa* ca) { const WolfCertKeyAlg* alg = wolfcert_key_alg(ca->type); @@ -71,7 +84,7 @@ static int gen_self_signed_cert(WolfCertCa* ca) if (cert == NULL) return WOLFCERT_ERR_MEMORY; - wc_InitCert_ex(cert, ca->heap, WOLFCERT_DEVID_SOFTWARE); + wc_InitCert_ex(cert, ca->heap, INVALID_DEVID); snprintf(cert->subject.commonName, sizeof(cert->subject.commonName), "%s", "wolfCert Test CA"); @@ -96,8 +109,16 @@ static int gen_self_signed_cert(WolfCertCa* ca) return WOLFCERT_ERR_WC(ku, "ca", "SetKeyUsage"); } + /* Every generated CA has the same subject; the key id tells them apart. */ + int kid = wc_SetSubjectKeyIdFromPublicKey_ex(cert, alg->wc_keytype_enum, + ca->impl); + if (kid != 0) { + wc_CertFree(cert); + return WOLFCERT_ERR_WC(kid, "ca", "SetSubjectKeyId"); + } + WC_RNG rng; - if (wc_InitRng_ex(&rng, ca->heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRng_ex(&rng, ca->heap, INVALID_DEVID) != 0) { wc_CertFree(cert); return WOLFCERT_ERR_CRYPTO; } @@ -131,6 +152,7 @@ static int gen_self_signed_cert(WolfCertCa* ca) ca->cert_der = der; ca->cert_der_len = (size_t)sz; + ca->skid_copies = wolfcert_ca_skid_copies(ca); return WOLFCERT_OK; } @@ -165,14 +187,14 @@ int wolfcert_ca_generate(WolfCertCa* ca, WolfCertKeyType type, int param, void* ca_sync_from_shim(ca, &shim); WC_RNG rng; - if (wc_InitRng_ex(&rng, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRng_ex(&rng, heap, INVALID_DEVID) != 0) { alg->free_(&shim); ca->impl = NULL; return WOLFCERT_ERR_CRYPTO; } WolfCertKeyCfg cfg = { .type = ca->type, .param = p, - .dev_id = WOLFCERT_DEVID_SOFTWARE, .heap = heap }; + .dev_id = INVALID_DEVID, .heap = heap }; rc = alg->make(&shim, &cfg, &rng); @@ -183,7 +205,7 @@ int wolfcert_ca_generate(WolfCertCa* ca, WolfCertKeyType type, int param, void* return rc; } - /* Kept as DER for wolfcert_ca_save and the SCEP server's PKCS#7 calls. */ + /* Kept as DER for wolfcert_ca_export and the SCEP server's PKCS#7 calls. */ size_t kcap = alg->der_cap_hint + 2048; ca->key_der = (uint8_t*)WOLFCERT_XMALLOC(kcap, heap); if (ca->key_der == NULL) { @@ -210,10 +232,9 @@ int wolfcert_ca_generate(WolfCertCa* ca, WolfCertKeyType type, int param, void* return WOLFCERT_OK; } -/* Check the stored cert is a CA holding the public half of the stored key. */ -static int ca_check_stored_pair(const WolfCertKeyAlg* alg, WolfCertKey* key, - const uint8_t* cert_der, size_t cert_len, - void* heap) +/* Check the cert is a CA holding the public half of the key. */ +static int ca_check_pair(const WolfCertKeyAlg* alg, WolfCertKey* key, + const uint8_t* cert_der, size_t cert_len, void* heap) { DecodedCert* dc = (DecodedCert*)WOLFCERT_XMALLOC(sizeof(*dc), heap); if (dc == NULL) @@ -222,25 +243,28 @@ static int ca_check_stored_pair(const WolfCertKeyAlg* alg, WolfCertKey* key, wc_InitDecodedCert(dc, cert_der, (word32)cert_len, heap); int rc = wc_ParseCert(dc, CERT_TYPE, NO_VERIFY, NULL); - if (rc != 0) { + if (rc == MEMORY_E) { + rc = WOLFCERT_ERR_MEMORY; + } + else if (rc != 0) { rc = WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "ca", - "stored CA certificate does not parse"); + "CA certificate does not parse"); } else if (!dc->isCA || (dc->extKeyUsageSet && (dc->extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0)) { rc = WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "ca", - "stored CA certificate is not a CA " + "CA certificate is not a CA " "(basicConstraints/keyUsage)"); } else if (dc->keyOID != (word32)alg->key_oid || dc->publicKey == NULL) { rc = WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "ca", - "stored CA certificate and key use different algorithms"); + "CA certificate and key use different algorithms"); } else { rc = alg->pub_check(key, dc->publicKey, dc->pubKeySize); - if (rc != WOLFCERT_OK) + if (rc != WOLFCERT_OK && rc != WOLFCERT_ERR_MEMORY) rc = WOLFCERT_ERR(rc, "ca", - "stored CA certificate does not match the stored key"); + "CA certificate does not match the CA key"); } wc_FreeDecodedCert(dc); @@ -248,103 +272,144 @@ static int ca_check_stored_pair(const WolfCertKeyAlg* alg, WolfCertKey* key, return rc; } -int wolfcert_ca_load(WolfCertCa* ca, WolfCertStoreOps* store, void* heap) +static int ca_copy(const uint8_t* in, size_t in_len, WolfCertBuffer* out, + void* heap) +{ + out->data = (uint8_t*)WOLFCERT_XMALLOC(in_len, heap); + if (out->data == NULL) + return WOLFCERT_ERR_MEMORY; + + memcpy(out->data, in, in_len); + out->len = in_len; + out->heap = heap; + return WOLFCERT_OK; +} + +/* 1 when in is exactly one DER element. */ +static int ca_der_single(const uint8_t* in, size_t in_len) +{ + word32 idx = 1; + int len = 0; + + return (size_t)(word32)in_len == in_len && + GetLength(in, &idx, &len, (word32)in_len) >= 0 && + (size_t)idx + (size_t)len == in_len; +} + +static int ca_cert_der(const uint8_t* in, size_t in_len, WolfCertBuffer* out, + void* heap) { - if (ca == NULL || store == NULL) + if (!wolfcert_buffer_is_der(in, in_len)) + return wolfcert_pem_cert_to_der(in, in_len, out, heap); + + if (!ca_der_single(in, in_len)) + return WOLFCERT_ERR_PARSE; + + return ca_copy(in, in_len, out, heap); +} + +int wolfcert_ca_load(WolfCertCa* ca, const uint8_t* cert, size_t cert_len, + const uint8_t* key, size_t key_len, void* heap) +{ + if (ca == NULL || cert == NULL || cert_len == 0 || key == NULL || + key_len == 0) return WOLFCERT_ERR_BAD_ARG; + if (heap == NULL) + heap = wolfcert_default_heap(); + memset(ca, 0, sizeof(*ca)); ca->heap = heap; WolfCertBuffer cert_buf = { .heap = heap }; WolfCertBuffer key_buf = { .heap = heap }; + WolfCertKey* k = NULL; + const WolfCertKeyAlg* alg = NULL; - int cert_rc = store->read(store->ctx, "ca.cert.der", &cert_buf); - int key_rc = store->read(store->ctx, "ca.key.der", &key_buf); - int rc; - - if (cert_rc != WOLFCERT_OK || key_rc != WOLFCERT_OK) { - wolfcert_buffer_free(&cert_buf); - wolfcert_buffer_free_secure(&key_buf); + int rc = ca_cert_der(cert, cert_len, &cert_buf, heap); + if (rc != WOLFCERT_OK && rc != WOLFCERT_ERR_MEMORY) + rc = WOLFCERT_ERR(rc, "ca", "ca_cert is not a PEM or DER certificate"); - if (cert_rc == WOLFCERT_ERR_NOT_FOUND && key_rc == WOLFCERT_ERR_NOT_FOUND) - return WOLFCERT_ERR_NOT_FOUND; - - /* An absent half is only damage once the other half read back. */ - if (cert_rc != WOLFCERT_OK && cert_rc != WOLFCERT_ERR_NOT_FOUND) - return WOLFCERT_ERR(cert_rc, "ca", "CA store read failed"); - if (key_rc != WOLFCERT_OK && key_rc != WOLFCERT_ERR_NOT_FOUND) - return WOLFCERT_ERR(key_rc, "ca", "CA store read failed"); - - /* Reporting NOT_FOUND for half a pair would let the caller mint a - * new CA over the survivor. */ - return WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "ca", - "CA store is incomplete: %s is missing", - cert_rc == WOLFCERT_ERR_NOT_FOUND ? "ca.cert.der" : "ca.key.der"); + if (rc == WOLFCERT_OK) { + if (wolfcert_buffer_is_der(key, key_len) && + !ca_der_single(key, key_len)) + rc = WOLFCERT_ERR_PARSE; + else + rc = wolfcert_key_from_pem(key, key_len, heap, &k); + if (rc != WOLFCERT_OK && rc != WOLFCERT_ERR_MEMORY) + rc = WOLFCERT_ERR(rc, "ca", "ca_key is not a supported PEM or " + "DER private key"); } - /* Find the algorithm whose private-key decoder accepts the stored key. */ - const WolfCertKeyAlg* const* list = wolfcert_key_algs_all(); - - for (; *list != NULL; ++list) { - const WolfCertKeyAlg* a = *list; - WolfCertKey shim; - - memset(&shim, 0, sizeof(shim)); - shim.type = a->type; - shim.heap = heap; - shim.dev_id = WOLFCERT_DEVID_SOFTWARE; - - if (a->alloc_init(&shim) != WOLFCERT_OK) - continue; - - if (a->priv_decode(&shim, key_buf.data, (word32)key_buf.len) == WOLFCERT_OK) { - rc = ca_check_stored_pair(a, &shim, cert_buf.data, cert_buf.len, heap); - if (rc != WOLFCERT_OK) { - a->free_(&shim); - wolfcert_buffer_free(&cert_buf); - wolfcert_buffer_free_secure(&key_buf); - return rc; - } - - ca->type = a->type; - ca->impl = shim.impl; - ca->cert_der = cert_buf.data; - ca->cert_der_len = cert_buf.len; - ca->key_der = key_buf.data; - ca->key_der_len = key_buf.len; - cert_buf.data = NULL; - key_buf.data = NULL; - return WOLFCERT_OK; - } - a->free_(&shim); + /* The pair check restores an ECC public point that the re-encode needs. */ + if (rc == WOLFCERT_OK) { + alg = wolfcert_key_alg(k->type); + rc = (alg == NULL) ? WOLFCERT_ERR_UNSUPPORTED + : ca_check_pair(alg, k, cert_buf.data, cert_buf.len, + heap); } + /* Re-encode so a PKCS#8 key matches alg->pem_type. */ + if (rc == WOLFCERT_OK) + rc = wolfcert_key_to_der(k, &key_buf); + + if (rc == WOLFCERT_OK) { + ca->type = k->type; + ca->impl = k->impl; + ca->cert_der = cert_buf.data; + ca->cert_der_len = cert_buf.len; + ca->key_der = key_buf.data; + ca->key_der_len = key_buf.len; + ca->skid_copies = wolfcert_ca_skid_copies(ca); + k->impl = NULL; + cert_buf.data = NULL; + key_buf.data = NULL; + } + + wolfcert_key_free(k); wolfcert_buffer_free(&cert_buf); wolfcert_buffer_free_secure(&key_buf); - return WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "ca", - "stored CA key does not decode as any supported algorithm"); + return rc; } -int wolfcert_ca_save(const WolfCertCa* ca, WolfCertStoreOps* store) +static int ca_encode(const uint8_t* der, size_t der_len, WolfCertEncoding enc, + int pem_type, WolfCertBuffer* out, void* heap) { - if (ca == NULL || store == NULL) - return WOLFCERT_ERR_BAD_ARG; + if (enc == WOLFCERT_ENCODING_DER) + return ca_copy(der, der_len, out, heap); - int rc = store->write(store->ctx, "ca.cert.der", ca->cert_der, ca->cert_der_len, 0); - if (rc != WOLFCERT_OK) - return rc; + size_t cap = der_len * 2 + 256; + uint8_t* pem = (uint8_t*)WOLFCERT_XMALLOC(cap, heap); + if (pem == NULL) + return WOLFCERT_ERR_MEMORY; - rc = store->write(store->ctx, "ca.key.der", ca->key_der, ca->key_der_len, 1); - if (rc == WOLFCERT_OK) - return rc; + int n = wc_DerToPem(der, (word32)der_len, pem, (word32)cap, pem_type); + if (n <= 0) { + wc_ForceZero(pem, (word32)cap); + WOLFCERT_XFREE(pem, heap); + return WOLFCERT_ERR_RC_WC(WOLFCERT_ERR_CRYPTO, n, "ca", "DerToPem"); + } + + out->data = pem; + out->len = (size_t)n; + out->heap = heap; + return WOLFCERT_OK; +} + +int wolfcert_ca_export(const WolfCertCa* ca, WolfCertEncoding enc, + WolfCertBuffer* out_cert, WolfCertBuffer* out_key) +{ + const WolfCertKeyAlg* alg = wolfcert_key_alg(ca->type); + int rc; - /* A certificate without its key is a store every later load rejects. */ - if (store->remove == NULL || - store->remove(store->ctx, "ca.cert.der") != WOLFCERT_OK) - return WOLFCERT_ERR(rc, "ca", - "CA key write failed and ca.cert.der could not be rolled back: " - "the store is left incomplete and must be cleared before restart"); + rc = ca_encode(ca->cert_der, ca->cert_der_len, enc, CERT_TYPE, out_cert, + ca->heap); + if (rc == WOLFCERT_OK && out_key != NULL) { + rc = ca_encode(ca->key_der, ca->key_der_len, enc, alg->pem_type, + out_key, ca->heap); + if (rc != WOLFCERT_OK) + wolfcert_buffer_free(out_cert); + } return rc; } @@ -421,7 +486,7 @@ static int decode_subject_pubkey(word32 keyOID, if (rk == NULL) return WOLFCERT_ERR_MEMORY; - if (wc_InitRsaKey_ex(rk, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRsaKey_ex(rk, heap, INVALID_DEVID) != 0) { WOLFCERT_XFREE(rk, heap); return WOLFCERT_ERR_CRYPTO; } @@ -444,7 +509,7 @@ static int decode_subject_pubkey(word32 keyOID, if (ek == NULL) return WOLFCERT_ERR_MEMORY; - if (wc_ecc_init_ex(ek, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_ecc_init_ex(ek, heap, INVALID_DEVID) != 0) { WOLFCERT_XFREE(ek, heap); return WOLFCERT_ERR_CRYPTO; } @@ -467,7 +532,7 @@ static int decode_subject_pubkey(word32 keyOID, if (ek == NULL) return WOLFCERT_ERR_MEMORY; - if (wc_ed25519_init_ex(ek, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_ed25519_init_ex(ek, heap, INVALID_DEVID) != 0) { WOLFCERT_XFREE(ek, heap); return WOLFCERT_ERR_CRYPTO; } @@ -490,7 +555,7 @@ static int decode_subject_pubkey(word32 keyOID, if (ek == NULL) return WOLFCERT_ERR_MEMORY; - if (wc_ed448_init_ex(ek, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_ed448_init_ex(ek, heap, INVALID_DEVID) != 0) { WOLFCERT_XFREE(ek, heap); return WOLFCERT_ERR_CRYPTO; } @@ -522,7 +587,7 @@ static int decode_subject_pubkey(word32 keyOID, if (dk == NULL) return WOLFCERT_ERR_MEMORY; - if (wc_MlDsaKey_Init(dk, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_MlDsaKey_Init(dk, heap, INVALID_DEVID) != 0) { WOLFCERT_XFREE(dk, heap); return WOLFCERT_ERR_CRYPTO; } @@ -771,7 +836,7 @@ int wolfcert_ca_issue(WolfCertCa* ca, } if (rc == 0) { - wc_InitCert_ex(nc, heap, WOLFCERT_DEVID_SOFTWARE); + wc_InitCert_ex(nc, heap, INVALID_DEVID); rc = wolfcert_copy_csr_subject(&dc, nc); if (rc == WOLFCERT_OK && @@ -779,6 +844,13 @@ int wolfcert_ca_issue(WolfCertCa* ca, rc = WOLFCERT_ERR_CRYPTO; } + if (rc == 0 && ca->skid_copies) { + int akid = wc_SetAuthKeyIdFromCert(nc, ca->cert_der, + (int)ca->cert_der_len); + if (akid != 0) + rc = WOLFCERT_ERR_WC(akid, "ca", "SetAuthKeyIdFromCert"); + } + if (rc == 0) { nc->sigType = ca_alg->ctc_sig_default; nc->daysValid = 365; @@ -800,7 +872,7 @@ int wolfcert_ca_issue(WolfCertCa* ca, } if (rc == 0) { - if (wc_InitRng_ex(&rng, heap, WOLFCERT_DEVID_SOFTWARE) != 0) + if (wc_InitRng_ex(&rng, heap, INVALID_DEVID) != 0) rc = WOLFCERT_ERR_CRYPTO; else rng_ok = 1; diff --git a/src/client.c b/src/client.c index b8441c65..0a25229a 100644 --- a/src/client.c +++ b/src/client.c @@ -136,6 +136,29 @@ int wolfcert_client_fetch_meta(WolfCertClient* client, const WolfCertServerCfg* return WOLFCERT_ERR_UNSUPPORTED; } +/* Only EST enrolls here; SCEP needs the RA cert, which this API lacks. */ +static int client_proto_check(const WolfCertServerCfg* srv) +{ +#ifdef WOLFCERT_HAVE_EST + if (srv->protocol == WOLFCERT_PROTO_EST) + return WOLFCERT_OK; +#endif + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "client", + "protocol %d cannot enroll through wolfcert_client", + (int)srv->protocol); +} + +/* On failure, a key with a key_id still goes to the caller to delete. */ +static int hand_back(WolfCertKey* key, int rc, WolfCertKey** out_key) +{ + if (rc != WOLFCERT_OK && key != NULL && key->id_len == 0) { + wolfcert_key_free(key); + key = NULL; + } + *out_key = key; + return rc; +} + int wolfcert_client_enroll(WolfCertClient* client, const WolfCertServerCfg* srv, const WolfCertKeyCfg* key_cfg, const WolfCertCertMeta* meta, @@ -145,6 +168,11 @@ int wolfcert_client_enroll(WolfCertClient* client, const WolfCertServerCfg* srv, if (srv == NULL || key_cfg == NULL || meta == NULL || out_key == NULL || out_cert_pem == NULL) return WOLFCERT_ERR_BAD_ARG; + *out_key = NULL; + + int rc = client_proto_check(srv); + if (rc != WOLFCERT_OK) + return rc; /* Shallow copies; csr_attrs_apply writes only scalar fields. */ WolfCertKeyCfg eff_key = *key_cfg; @@ -153,51 +181,33 @@ int wolfcert_client_enroll(WolfCertClient* client, const WolfCertServerCfg* srv, #ifdef WOLFCERT_HAVE_EST /* proto_opts is a union; test the protocol before reading its EST arm. */ if (srv->protocol == WOLFCERT_PROTO_EST && srv->proto_opts.est.auto_csrattrs) { - int rc = wolfcert_client_auto_csrattrs(srv, &eff_key, &eff_meta); + rc = wolfcert_client_auto_csrattrs(srv, &eff_key, &eff_meta); if (rc != WOLFCERT_OK) return rc; } #endif WolfCertKey* key = NULL; - int rc = wolfcert_key_generate(&eff_key, &key); + rc = wolfcert_key_generate(&eff_key, &key); if (rc != WOLFCERT_OK) - return rc; + return hand_back(key, rc, out_key); WolfCertBuffer csr = { 0 }; rc = wolfcert_csr_build(key, &eff_meta, &csr); - if (rc != WOLFCERT_OK) { - wolfcert_key_free(key); - return rc; - } + if (rc != WOLFCERT_OK) + return hand_back(key, rc, out_key); #ifdef WOLFCERT_HAVE_EST - if (srv->protocol == WOLFCERT_PROTO_EST) { - WolfCertEstResult r; + WolfCertEstResult r; - rc = wolfcert_est_simple_enroll(srv, csr.data, csr.len, &r); - rc = wolfcert_client_take_cert(rc, &r, out_cert_pem); - } - else -#endif -#ifdef WOLFCERT_HAVE_SCEP - if (srv->protocol == WOLFCERT_PROTO_SCEP) { - rc = WOLFCERT_ERR_UNSUPPORTED; - /* SCEP enrollment needs the RA cert, which this API does not take. */ - } - else + rc = wolfcert_est_simple_enroll(srv, csr.data, csr.len, &r); + rc = wolfcert_client_take_cert(rc, &r, out_cert_pem); +#else + rc = WOLFCERT_ERR_UNSUPPORTED; #endif - { - rc = WOLFCERT_ERR_UNSUPPORTED; - } wolfcert_buffer_free(&csr); - if (rc != WOLFCERT_OK) { - wolfcert_key_free(key); - return rc; - } - *out_key = key; - return WOLFCERT_OK; + return hand_back(key, rc, out_key); } int wolfcert_client_reenroll(WolfCertClient* client, const WolfCertServerCfg* srv, @@ -211,48 +221,39 @@ int wolfcert_client_reenroll(WolfCertClient* client, const WolfCertServerCfg* sr if (srv == NULL || current_cert == NULL || current_key == NULL || meta == NULL || out_key == NULL || out_cert_pem == NULL) return WOLFCERT_ERR_BAD_ARG; + *out_key = NULL; if (wolfcert_csr_meta_sets_identity(meta)) return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "client", "a renewal keeps the certificate's subject and SAN"); + int rc = client_proto_check(srv); + if (rc != WOLFCERT_OK) + return rc; + WolfCertKey* nk = NULL; - int rc; if (new_key_cfg != NULL) { rc = wolfcert_key_generate(new_key_cfg, &nk); if (rc != WOLFCERT_OK) - return rc; + return hand_back(nk, rc, out_key); } const WolfCertKey* signing_key = nk ? nk : current_key; WolfCertBuffer csr = { 0 }; rc = wolfcert_csr_build_ex(signing_key, meta, current_cert, current_cert_len, &csr); - if (rc != WOLFCERT_OK) { - if (nk) - wolfcert_key_free(nk); - return rc; - } + if (rc != WOLFCERT_OK) + return hand_back(nk, rc, out_key); #ifdef WOLFCERT_HAVE_EST - if (srv->protocol == WOLFCERT_PROTO_EST) { - WolfCertEstResult r; + WolfCertEstResult r; - rc = wolfcert_est_simple_reenroll(srv, current_cert, current_cert_len, - current_key, csr.data, csr.len, &r); - rc = wolfcert_client_take_cert(rc, &r, out_cert_pem); - } - else + rc = wolfcert_est_simple_reenroll(srv, current_cert, current_cert_len, + current_key, csr.data, csr.len, &r); + rc = wolfcert_client_take_cert(rc, &r, out_cert_pem); +#else + rc = WOLFCERT_ERR_UNSUPPORTED; #endif - { - rc = WOLFCERT_ERR_UNSUPPORTED; - } wolfcert_buffer_free(&csr); - if (rc != WOLFCERT_OK) { - if (nk) - wolfcert_key_free(nk); - return rc; - } - *out_key = nk ? nk : NULL; - return WOLFCERT_OK; + return hand_back(nk, rc, out_key); } diff --git a/src/est/est_client.c b/src/est/est_client.c index d8e3eaa4..f00bd6d1 100644 --- a/src/est/est_client.c +++ b/src/est/est_client.c @@ -192,7 +192,8 @@ int wolfcert_est_session_open(const WolfCertServerCfg* srv, memset(s, 0, sizeof(*s)); s->heap = heap; s->has_client_identity = srv->client_cert != NULL && - srv->client_key != NULL; + (srv->client_key != NULL || + srv->client_key_obj != NULL); s->base_url = wolfcert_strdup(srv->server_url, heap); if (s->base_url == NULL) { wolfcert_est_session_close(s); @@ -222,6 +223,7 @@ int wolfcert_est_session_open(const WolfCertServerCfg* srv, .client_cert_len = srv->client_cert_len, .client_key = srv->client_key, .client_key_len = srv->client_key_len, + .client_key_obj = srv->client_key_obj, .allow_post_handshake_auth = srv->proto_opts.est.allow_post_handshake_auth, .transport = srv->transport, .heap = heap, @@ -528,8 +530,8 @@ int wolfcert_est_get_cacerts(const WolfCertServerCfg* srv, WolfCertEncoding enc, int wolfcert_est_get_csr_attrs(const WolfCertServerCfg* srv, WolfCertBuffer* out_attrs_der) { - return est_one_shot(srv, EST_OP_GET_CSRATTRS, NULL, 0, - WOLFCERT_ENCODING_DER, out_attrs_der, NULL); + return est_one_shot(srv, EST_OP_GET_CSRATTRS, + NULL, 0, WOLFCERT_ENCODING_DER, out_attrs_der, NULL); } int wolfcert_est_simple_enroll(const WolfCertServerCfg* srv, @@ -539,8 +541,9 @@ int wolfcert_est_simple_enroll(const WolfCertServerCfg* srv, if (out == NULL) return WOLFCERT_ERR_BAD_ARG; - return est_one_shot(srv, EST_OP_SIMPLE_ENROLL, csr_der, csr_der_len, - WOLFCERT_ENCODING_PEM, &out->cert_pem, out); + return est_one_shot(srv, EST_OP_SIMPLE_ENROLL, + csr_der, csr_der_len, WOLFCERT_ENCODING_PEM, + &out->cert_pem, out); } int wolfcert_est_simple_reenroll(const WolfCertServerCfg* srv, @@ -550,8 +553,6 @@ int wolfcert_est_simple_reenroll(const WolfCertServerCfg* srv, WolfCertEstResult* out) { WolfCertServerCfg cfg; - WolfCertBuffer key_pem = { 0 }; - int rc; if (out == NULL) return WOLFCERT_ERR_BAD_ARG; @@ -563,19 +564,12 @@ int wolfcert_est_simple_reenroll(const WolfCertServerCfg* srv, return WOLFCERT_ERR_BAD_ARG; /* The TLS identity is the cert being renewed. */ - rc = wolfcert_key_to_pem(current_key, &key_pem); - if (rc == WOLFCERT_OK) { - cfg = *srv; - cfg.client_cert = current_cert; - cfg.client_cert_len = current_cert_len; - cfg.client_key = key_pem.data; - cfg.client_key_len = key_pem.len; - rc = est_one_shot(&cfg, EST_OP_SIMPLE_REENROLL, csr_der, csr_der_len, - WOLFCERT_ENCODING_PEM, &out->cert_pem, out); - } - - if (key_pem.data != NULL) - wc_ForceZero(key_pem.data, (word32)key_pem.len); - wolfcert_buffer_free(&key_pem); - return rc; + cfg = *srv; + cfg.client_cert = current_cert; + cfg.client_cert_len = current_cert_len; + cfg.client_key = NULL; + cfg.client_key_len = 0; + cfg.client_key_obj = current_key; + return est_one_shot(&cfg, EST_OP_SIMPLE_REENROLL, csr_der, csr_der_len, + WOLFCERT_ENCODING_PEM, &out->cert_pem, out); } diff --git a/src/est/est_server.c b/src/est/est_server.c index 2fc8ce01..b6358220 100644 --- a/src/est/est_server.c +++ b/src/est/est_server.c @@ -747,6 +747,43 @@ static int reenroll_identity_check(WolfCertServer* s, #endif } +#ifdef KEEP_PEER_CERT +/* 1 when this server's CA issued the TLS client certificate, 0 when another + * CA did, an error when there is none to check, as after a resumption. */ +static int peer_issued_here(WolfCertServer* s) +{ + WOLFSSL_X509* peer = NULL; + const unsigned char* der = NULL; + int der_len = 0; + int rc; + + if (s->issued_cm == NULL || s->tls_current == NULL) + return 0; + peer = wolfSSL_get_peer_certificate(s->tls_current); + if (peer != NULL) + der = wolfSSL_X509_get_der(peer, &der_len); + if (der == NULL || der_len <= 0) { + rc = WOLFCERT_ERR(WOLFCERT_ERR_TLS, "est", + "enroll: cannot read the client certificate"); + } + else { + rc = wolfSSL_CertManagerVerifyBuffer(s->issued_cm, der, der_len, + WOLFSSL_FILETYPE_ASN1); + if (rc == WOLFSSL_SUCCESS) + rc = 1; + else if (rc == ASN_NO_SIGNER_E || rc == ASN_SIG_CONFIRM_E || + rc == ASN_SELF_SIGNED_E || rc == ASN_SIG_OID_E) + rc = 0; + else + rc = WOLFCERT_ERR(WOLFCERT_ERR_TLS, "est", + "enroll: cannot check the client certificate (%d)", rc); + } + if (peer != NULL) + wolfSSL_FreeX509(peer); + return rc; +} +#endif + static int handler_enroll(WolfCertServer* s, int fd, const EstRequest* req, int reenroll) { @@ -767,6 +804,29 @@ static int handler_enroll(WolfCertServer* s, int fd, const EstRequest* req, "enroll: no Basic credentials or TLS client on this connection"); } + if (!reenroll && s->renew_only) { + send_error(s, fd, 403, "Forbidden", + "this server only renews certificates\n"); + return WOLFCERT_ERR(WOLFCERT_ERR_AUTH, "est", + "enroll: the server only renews certificates"); + } + +#ifdef KEEP_PEER_CERT + int here = (reenroll || s->cfg_basic_user != NULL || + s->cfg.est_allow_anonymous_enroll) ? 0 : peer_issued_here(s); + if (here == 1) { + send_error(s, fd, 403, "Forbidden", + "a certificate issued here can only renew\n"); + return WOLFCERT_ERR(WOLFCERT_ERR_AUTH, "est", + "enroll: client certificate was issued here, not by the client CA"); + } + if (here != 0) { + send_error(s, fd, 500, "Server Error", + "cannot check the client certificate\n"); + return here; + } +#endif + if (req->body == NULL || req->body_len == 0) { send_error(s, fd, 400, "Bad Request", "request body is empty\n"); return WOLFCERT_ERR_HTTP; diff --git a/src/http.c b/src/http.c index 89fbc1fc..ad2d2df0 100644 --- a/src/http.c +++ b/src/http.c @@ -919,14 +919,15 @@ int wolfcert_http_chunked_decode(const uint8_t* in, size_t in_len, } typedef struct { - const uint8_t* trust_anchors; - size_t trust_anchors_len; - int verify_server; - const uint8_t* client_cert; - size_t client_cert_len; - const uint8_t* client_key; - size_t client_key_len; - int allow_post_handshake_auth; + const uint8_t* trust_anchors; + size_t trust_anchors_len; + int verify_server; + const uint8_t* client_cert; + size_t client_cert_len; + const uint8_t* client_key; + size_t client_key_len; + const WolfCertKey* client_key_obj; + int allow_post_handshake_auth; } TlsDials; static int buf_filetype(const uint8_t* buf, size_t len) @@ -935,12 +936,79 @@ static int buf_filetype(const uint8_t* buf, size_t len) : WOLFSSL_FILETYPE_PEM; } +static int check_client_key(const uint8_t* cert, size_t cert_len, + const uint8_t* key, const WolfCertKey* key_obj) +{ + if (key_obj == NULL) + return WOLFCERT_OK; + if (key != NULL) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "http", + "set client_key or client_key_obj, not both"); + if (cert == NULL || cert_len == 0) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "http", + "client_key_obj needs client_cert"); + return WOLFCERT_OK; +} + +/* A key with an id signs in its device; any other key loads as DER. */ +static int use_client_key_obj(WOLFSSL_CTX* ctx, const WolfCertKey* k) +{ + WolfCertBuffer der = { 0 }; + int rc; + + if (k->id_len > 0) { +#ifdef WOLFCERT_USE_KEY_ID + rc = wolfSSL_CTX_use_PrivateKey_Id(ctx, k->id, (long)k->id_len, + k->dev_id); +#else + rc = WOLFSSL_FAILURE; +#endif + } + else { + rc = wolfcert_key_to_der(k, &der); + if (rc != WOLFCERT_OK) + return rc; + rc = wolfSSL_CTX_use_PrivateKey_buffer(ctx, der.data, (long)der.len, + WOLFSSL_FILETYPE_ASN1); + wolfcert_buffer_free_secure(&der); + } + + if (rc != WOLFSSL_SUCCESS) + return WOLFCERT_ERR(WOLFCERT_ERR_TLS, "http", + "loading client_key_obj failed (%d)", rc); + return WOLFCERT_OK; +} + +static int use_client_key(WOLFSSL_CTX* ctx, const TlsDials* d) +{ + int rc; + + if (d->client_key_obj != NULL) + return use_client_key_obj(ctx, d->client_key_obj); + + rc = wolfSSL_CTX_use_PrivateKey_buffer(ctx, d->client_key, + (long)d->client_key_len, + buf_filetype(d->client_key, d->client_key_len)); + if (rc != WOLFSSL_SUCCESS) + return WOLFCERT_ERR(WOLFCERT_ERR_TLS, "http", + "loading the client key failed (%d)", rc); + return WOLFCERT_OK; +} + static int setup_tls_ex(WolfCertConn* c, const TlsDials* dials, const char* sni_host, WOLFSSL_CTX** out_ctx) { WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfTLS_client_method()); + int dev_id = wolfcert_default_dev_id(); + if (ctx == NULL) return WOLFCERT_ERR_TLS; + /* Keeps the devId wolfSSL_CTX_new picks itself, such as CAAM's. */ + if (dev_id != INVALID_DEVID && + wolfSSL_CTX_SetDevId(ctx, dev_id) != WOLFSSL_SUCCESS) { + wolfSSL_CTX_free(ctx); + return WOLFCERT_ERR_TLS; + } #ifdef WOLFSSL_NO_TLS12 (void)wolfSSL_CTX_SetMinVersion(ctx, WOLFSSL_TLSV1_3); @@ -975,7 +1043,8 @@ static int setup_tls_ex(WolfCertConn* c, const TlsDials* dials, wolfSSL_CTX_set_verify(ctx, dials->verify_server ? WOLFSSL_VERIFY_PEER : WOLFSSL_VERIFY_NONE, NULL); - if (dials->client_cert != NULL && dials->client_key != NULL) { + if (dials->client_cert != NULL && + (dials->client_key != NULL || dials->client_key_obj != NULL)) { /* Load the identity on the CTX so a PHA request can still use it. */ int rc = wolfSSL_CTX_use_certificate_buffer(ctx, dials->client_cert, (long)dials->client_cert_len, @@ -985,12 +1054,10 @@ static int setup_tls_ex(WolfCertConn* c, const TlsDials* dials, return WOLFCERT_ERR_TLS; } - rc = wolfSSL_CTX_use_PrivateKey_buffer(ctx, dials->client_key, - (long)dials->client_key_len, - buf_filetype(dials->client_key, dials->client_key_len)); - if (rc != WOLFSSL_SUCCESS) { + rc = use_client_key(ctx, dials); + if (rc != WOLFCERT_OK) { wolfSSL_CTX_free(ctx); - return WOLFCERT_ERR_TLS; + return rc; } } @@ -1041,6 +1108,11 @@ int wolfcert_http_session_open(const WolfCertHttpSessionCfg* cfg, if (cfg == NULL || cfg->base_url == NULL || out == NULL) return WOLFCERT_ERR_BAD_ARG; + int rc = check_client_key(cfg->client_cert, cfg->client_cert_len, + cfg->client_key, cfg->client_key_obj); + if (rc != WOLFCERT_OK) + return rc; + void* heap = cfg->heap ? cfg->heap : wolfcert_default_heap(); WolfCertHttpSession* s = (WolfCertHttpSession*)WOLFCERT_XMALLOC(sizeof(*s), heap); @@ -1053,11 +1125,17 @@ int wolfcert_http_session_open(const WolfCertHttpSessionCfg* cfg, s->max_body = cfg->max_response_bytes ? cfg->max_response_bytes : WOLFCERT_HTTP_DEFAULT_MAX_BODY; - int rc = wolfcert_http_url_parse(cfg->base_url, &s->base, heap); + rc = wolfcert_http_url_parse(cfg->base_url, &s->base, heap); if (rc != WOLFCERT_OK) { WOLFCERT_XFREE(s, heap); return rc; } + if (cfg->client_key_obj != NULL && !s->base.tls) { + wolfcert_http_url_free(&s->base); + WOLFCERT_XFREE(s, heap); + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "http", + "client_key_obj needs an https:// URL"); + } rc = dial(&s->conn, s->base.host, s->base.port, cfg->timeout_ms, &cfg->transport); @@ -1075,6 +1153,7 @@ int wolfcert_http_session_open(const WolfCertHttpSessionCfg* cfg, .client_cert_len = cfg->client_cert_len, .client_key = cfg->client_key, .client_key_len = cfg->client_key_len, + .client_key_obj = cfg->client_key_obj, .allow_post_handshake_auth = cfg->allow_post_handshake_auth, }; @@ -1878,6 +1957,7 @@ int wolfcert_http_request(const WolfCertHttpRequest* req, WolfCertHttpResponse* cfg.client_cert_len = req->client_cert_len; cfg.client_key = req->client_key; cfg.client_key_len = req->client_key_len; + cfg.client_key_obj = req->client_key_obj; cfg.heap = req->heap; cfg.transport = req->transport; diff --git a/src/internal.c b/src/internal.c index f266ae36..d2c2d3e1 100644 --- a/src/internal.c +++ b/src/internal.c @@ -22,12 +22,16 @@ #include #include +#ifdef WOLF_CRYPTO_CB +#include +#endif #include #include #include static void* g_default_heap = NULL; +static int g_default_dev_id = WOLFCERT_DEFAULT_DEVID; static WolfCertLogCb g_log_cb = NULL; static void* g_log_ctx = NULL; static WolfCertLogLevel g_log_level = WOLFCERT_LOG_WARN; @@ -51,6 +55,44 @@ void* wolfcert_default_heap(void) return g_default_heap; } +int wolfcert_dev_id_check(int dev_id, const char* module) +{ + if (dev_id == INVALID_DEVID) + return WOLFCERT_OK; +#ifndef WOLF_CRYPTO_CB + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, module, + "wolfSSL lacks WOLF_CRYPTO_CB"); +#else +#ifndef WOLF_CRYPTO_CB_FIND + if (!wc_CryptoCb_IsDeviceRegistered(dev_id)) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, module, + "no CryptoCb device %d is registered", dev_id); +#else + (void)module; +#endif + return WOLFCERT_OK; +#endif +} + +int wolfcert_set_default_dev_id(int dev_id) +{ + int rc = wolfcert_dev_id_check(dev_id, "wolfcert"); + + if (rc == WOLFCERT_OK) + g_default_dev_id = dev_id; + return rc; +} + +int wolfcert_default_dev_id(void) +{ + return g_default_dev_id; +} + +void wolfcert_default_dev_id_reset(void) +{ + g_default_dev_id = WOLFCERT_DEFAULT_DEVID; +} + void wolfcert_set_log_cb(WolfCertLogCb cb, void* ctx) { g_log_cb = cb; @@ -348,6 +390,7 @@ int wolfcert_map_wc_err(int wc_rc) return WOLFCERT_ERR_PARSE; case NOT_COMPILED_IN: case ALGO_ID_E: + case NO_VALID_DEVID: return WOLFCERT_ERR_UNSUPPORTED; default: return WOLFCERT_ERR_CRYPTO; @@ -355,24 +398,41 @@ int wolfcert_map_wc_err(int wc_rc) } #ifdef WOLFCERT_HAVE_ECC +static const struct { + int param; + int curve_id; + int key_size; +} ecc_curves[] = { + { 256, ECC_SECP256R1, 32 }, + { 384, ECC_SECP384R1, 48 }, + { 521, ECC_SECP521R1, 66 }, +}; + int wolfcert_ecc_curve_from_param(int param, int* out_curve_id, int* out_key_size) { - switch (param) { - case 256: - *out_curve_id = ECC_SECP256R1; - *out_key_size = 32; - return WOLFCERT_OK; - case 384: - *out_curve_id = ECC_SECP384R1; - *out_key_size = 48; + size_t i; + + for (i = 0; i < sizeof(ecc_curves) / sizeof(ecc_curves[0]); i++) { + if (ecc_curves[i].param == param) { + *out_curve_id = ecc_curves[i].curve_id; + *out_key_size = ecc_curves[i].key_size; return WOLFCERT_OK; - case 521: - *out_curve_id = ECC_SECP521R1; - *out_key_size = 66; + } + } + return WOLFCERT_ERR_UNSUPPORTED; +} + +int wolfcert_ecc_param_from_curve(int curve_id, int* out_param) +{ + size_t i; + + for (i = 0; i < sizeof(ecc_curves) / sizeof(ecc_curves[0]); i++) { + if (ecc_curves[i].curve_id == curve_id) { + *out_param = ecc_curves[i].param; return WOLFCERT_OK; - default: - return WOLFCERT_ERR_UNSUPPORTED; + } } + return WOLFCERT_ERR_UNSUPPORTED; } #endif /* WOLFCERT_HAVE_ECC */ diff --git a/src/internal.h b/src/internal.h index 65d9f74e..1021a854 100644 --- a/src/internal.h +++ b/src/internal.h @@ -82,12 +82,24 @@ #error "WOLFCERT_SCEP_MAX_GET_URL exceeds WOLFCERT_HTTP_QUERY_SZ; raise WOLFCERT_HTTP_QUERY_SZ so the SCEP server can receive the largest GET the client will build." #endif +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_PRIVATE_KEY_ID) +#define WOLFCERT_USE_KEY_ID +#endif + +/* Restores the start devId; wolfCrypt_Cleanup unregisters the devices. */ +void wolfcert_default_dev_id_reset(void); + +/* BAD_ARG or UNSUPPORTED, with a message, unless dev_id is INVALID_DEVID or + * names a registered CryptoCb device. */ +int wolfcert_dev_id_check(int dev_id, const char* module); + struct WolfCertKey { WolfCertKeyType type; int dev_id; int curve_id; /* ECC only */ int rsa_bits; /* RSA only */ - char* label; + uint8_t id[WOLFCERT_KEY_ID_MAX_LEN]; + size_t id_len; void* heap; void* impl; /* RsaKey* / ecc_key* / ... */ }; @@ -100,15 +112,18 @@ typedef struct { uint8_t* key_der; size_t key_der_len; void* heap; + int skid_copies; /* SKID is KEYID_SIZE, so issued AKIDs copy it */ } WolfCertCa; int wolfcert_ca_generate(WolfCertCa* ca, WolfCertKeyType type, int param, void* heap); -WOLFCERT_TEST_VIS int wolfcert_ca_load(WolfCertCa* ca, WolfCertStoreOps* store, +WOLFCERT_TEST_VIS int wolfcert_ca_load(WolfCertCa* ca, + const uint8_t* cert, size_t cert_len, + const uint8_t* key, size_t key_len, void* heap); -int wolfcert_ca_save(const WolfCertCa* ca, WolfCertStoreOps* store); +int wolfcert_ca_export(const WolfCertCa* ca, WolfCertEncoding enc, + WolfCertBuffer* out_cert, WolfCertBuffer* out_key); +int wolfcert_ca_skid_copies(const WolfCertCa* ca); WOLFCERT_TEST_VIS void wolfcert_ca_free(WolfCertCa* ca); -/* wolfcert_buffer_free() after wiping: for a buffer that held key material. */ -void wolfcert_buffer_free_secure(WolfCertBuffer* buf); /* Rebuild an issued certificate's subject from a decoded CSR. */ WOLFCERT_TEST_VIS int wolfcert_copy_csr_subject(const DecodedCert* dc, Cert* nc); @@ -138,6 +153,9 @@ struct WolfCertServer { void* priv; /* protocol-specific state */ WOLFSSL_CTX* tls_ctx; WOLFSSL* tls_current; /* owned by the accept loop */ + /* Only ca.cert_der; set when tls_client_trust_issued meets a client CA. */ + WOLFSSL_CERT_MANAGER* issued_cm; + int renew_only; /* tls_client_trust_issued alone */ int keep_alive; /* handlers clear it to close */ /* Set when the accept loop armed SO_RCVTIMEO/SO_SNDTIMEO; would-block * retries in wolfcert_io_{recv,send} are allowed only then. */ @@ -256,6 +274,7 @@ void wolfcert_logv(WolfCertLogLevel lvl, const char* module, const char* fmt, .. int wolfcert_rng_new(WC_RNG* rng); #ifdef WOLFCERT_HAVE_ECC int wolfcert_ecc_curve_from_param(int param, int* out_curve_id, int* out_key_size); +int wolfcert_ecc_param_from_curve(int curve_id, int* out_param); #endif /* Returns WOLFCERT_ERR_BAD_ARG unless srv->protocol is want. */ @@ -274,6 +293,7 @@ typedef struct { WOLFCERT_TEST_VIS int wolfcert_http_url_parse(const char* url, WolfCertUrl* out, void* heap); WOLFCERT_TEST_VIS void wolfcert_http_url_free (WolfCertUrl* u); + /* Resume point for wolfcert_http_chunked_complete(); zero it before the first * call, setting max to cap the decoded body (0 for no cap). */ typedef struct { @@ -341,6 +361,11 @@ WOLFCERT_TEST_VIS int wolfcert_find_san(const DecodedCert* dc, WOLFCERT_TEST_VIS int wolfcert_buffer_is_der(const uint8_t* buf, size_t len); +/* Private key DER of a software key; fails for a key with a key_id. The + * caller zeroizes and frees *out_der. */ +int wolfcert_key_export_der(const WolfCertKey* key, uint8_t** out_der, + int* out_len, void* heap); + /* Degenerate (certs-only) PKCS#7 helpers. */ WOLFCERT_TEST_VIS int wolfcert_pkcs7_certs_to_pem(const uint8_t* p7_der, size_t p7_der_len, WolfCertBuffer* out_pem, void* heap); @@ -422,7 +447,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_issuer_name_matches( WOLFCERT_TEST_VIS int wolfcert_scep_envelop(const uint8_t* ra_cert_der, size_t ra_cert_len, const uint8_t* payload, size_t payload_len, int enc_oid, - WolfCertBuffer* out_der, void* heap); + WolfCertBuffer* out_der, int dev_id, void* heap); /* RFC 8894 section 4.1 GET PKIOperation URL; WOLFCERT_ERR_UNSUPPORTED past * WOLFCERT_SCEP_MAX_GET_URL. */ @@ -442,21 +467,23 @@ WOLFCERT_TEST_VIS int wolfcert_scep_pick_hash_oid(const WolfCertScepCaps* caps, int wolfcert_scep_deenvelop(const uint8_t* recipient_cert_der, size_t recipient_cert_len, const uint8_t* recipient_key_der, size_t recipient_key_len, const uint8_t* env_der, size_t env_len, - WolfCertBuffer* out_plain, void* heap); + WolfCertBuffer* out_plain, int dev_id, void* heap); #ifdef WOLFCERT_HAVE_RSA WOLFCERT_TEST_VIS int wolfcert_scep_self_signed_rsa(RsaKey* key, - const uint8_t* csr_der, size_t csr_len, uint8_t** out_der, size_t* out_len, void* heap); + const uint8_t* csr_der, size_t csr_len, uint8_t** out_der, size_t* out_len, + int dev_id, void* heap); #endif WOLFCERT_TEST_VIS int wolfcert_scep_build_pki_message(const uint8_t* envelope_der, size_t envelope_len, const uint8_t* signer_cert_der, size_t signer_cert_len, const uint8_t* signer_key_der, size_t signer_key_len, int hash_oid, - const WolfCertScepAttrs* attrs, WolfCertBuffer* out_der, void* heap); + const WolfCertScepAttrs* attrs, WolfCertBuffer* out_der, int dev_id, + void* heap); WOLFCERT_TEST_VIS int wolfcert_scep_parse_pki_message(const uint8_t* pki_der, size_t pki_len, WolfCertBuffer* out_envelope, uint8_t** out_transaction_id, size_t* out_tid_len, uint8_t** out_sender_nonce, size_t* out_snonce_len, uint8_t** out_recipient_nonce,size_t* out_rnonce_len, char** out_message_type, char** out_pki_status, uint8_t** out_signer_cert, size_t* out_signer_cert_len, - char** out_fail_info, void* heap); + char** out_fail_info, int dev_id, void* heap); /* GetNextCACert response (RFC 8894 section 4.7.1), signed by the current CA. */ WOLFCERT_TEST_VIS int wolfcert_scep_build_next_ca_response( diff --git a/src/key_algs.c b/src/key_algs.c index 5f3c160d..91f030a8 100644 --- a/src/key_algs.c +++ b/src/key_algs.c @@ -44,16 +44,27 @@ #include #ifdef WOLFCERT_HAVE_RSA +int wolfcert_rsa_bits_ok(int bits) +{ + return bits == 2048 || bits == 3072 || bits == 4096; +} + static int rsa_alloc_init(struct WolfCertKey* k) { RsaKey* rk = (RsaKey*)WOLFCERT_XMALLOC(sizeof(*rk), k->heap); if (rk == NULL) return WOLFCERT_ERR_MEMORY; - int rc = wc_InitRsaKey_ex(rk, k->heap, k->dev_id); + int rc; +#ifdef WOLFCERT_USE_KEY_ID + if (k->id_len > 0) + rc = wc_InitRsaKey_Id(rk, k->id, (int)k->id_len, k->heap, k->dev_id); + else +#endif + rc = wc_InitRsaKey_ex(rk, k->heap, k->dev_id); if (rc != 0) { WOLFCERT_XFREE(rk, k->heap); - return WOLFCERT_ERR_WC(rc, "keygen", "InitRsaKey_ex"); + return WOLFCERT_ERR_WC(rc, "keygen", "InitRsaKey"); } k->impl = rk; @@ -63,7 +74,7 @@ static int rsa_alloc_init(struct WolfCertKey* k) static int rsa_make(struct WolfCertKey* k, const WolfCertKeyCfg* cfg, WC_RNG* rng) { int bits = cfg->param; - if (bits != 2048 && bits != 3072 && bits != 4096) + if (!wolfcert_rsa_bits_ok(bits)) return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", "bad RSA size %d", bits); k->rsa_bits = bits; @@ -85,6 +96,53 @@ static int rsa_priv_to_der(const struct WolfCertKey* k, uint8_t* buf, word32 cap return wc_RsaKeyToDer((RsaKey*)k->impl, buf, cap); } +/* Modulus size in bits; wc_RsaEncryptSize rounds up to whole bytes. */ +static int rsa_der_modulus_bits(const uint8_t* der, word32 len) +{ + const byte* n = NULL; + word32 n_len = 0; + word32 idx = 0; + int bits; + byte top; + + if (wc_RsaPublicKeyDecode_ex(der, &idx, len, &n, &n_len, NULL, NULL) != 0) + return 0; + while (n_len > 0 && n[0] == 0) { + n++; + n_len--; + } + if (n_len == 0) + return 0; + bits = (int)n_len * 8; + for (top = n[0]; (top & 0x80) == 0; top <<= 1) + bits--; + return bits; +} + +static int rsa_pub_decode(struct WolfCertKey* k, const uint8_t* der, + word32 len) +{ + word32 idx = 0; + if (wc_RsaPublicKeyDecode(der, &idx, (RsaKey*)k->impl, len) != 0) + return WOLFCERT_ERR_PARSE; + + k->rsa_bits = rsa_der_modulus_bits(der, len); + return WOLFCERT_OK; +} + +static int rsa_host_priv(const struct WolfCertKey* k) +{ + return !mp_iszero(&((RsaKey*)k->impl)->d); +} + +#ifdef WOLFCERT_USE_KEY_ID +static const uint8_t* rsa_impl_id(const struct WolfCertKey* k, int* len) +{ + *len = ((RsaKey*)k->impl)->idLen; + return ((RsaKey*)k->impl)->id; +} +#endif + static int rsa_pub_check(struct WolfCertKey* k, const uint8_t* pub, word32 pub_len) { @@ -163,10 +221,16 @@ static int ecc_alloc_init(struct WolfCertKey* k) if (ek == NULL) return WOLFCERT_ERR_MEMORY; - int rc = wc_ecc_init_ex(ek, k->heap, k->dev_id); + int rc; +#ifdef WOLFCERT_USE_KEY_ID + if (k->id_len > 0) + rc = wc_ecc_init_id(ek, k->id, (int)k->id_len, k->heap, k->dev_id); + else +#endif + rc = wc_ecc_init_ex(ek, k->heap, k->dev_id); if (rc != 0) { WOLFCERT_XFREE(ek, k->heap); - return WOLFCERT_ERR_WC(rc, "keygen", "ecc_init_ex"); + return WOLFCERT_ERR_WC(rc, "keygen", "ecc_init"); } k->impl = ek; @@ -203,6 +267,30 @@ static int ecc_priv_to_der(const struct WolfCertKey* k, uint8_t* buf, word32 cap return wc_EccKeyToDer((ecc_key*)k->impl, buf, cap); } +static int ecc_pub_decode(struct WolfCertKey* k, const uint8_t* der, + word32 len) +{ + word32 idx = 0; + if (wc_EccPublicKeyDecode(der, &idx, (ecc_key*)k->impl, len) != 0) + return WOLFCERT_ERR_PARSE; + + k->curve_id = wc_ecc_get_curve_id(((ecc_key*)k->impl)->idx); + return WOLFCERT_OK; +} + +static int ecc_host_priv(const struct WolfCertKey* k) +{ + return !mp_iszero(wc_ecc_key_get_priv((ecc_key*)k->impl)); +} + +#ifdef WOLFCERT_USE_KEY_ID +static const uint8_t* ecc_impl_id(const struct WolfCertKey* k, int* len) +{ + *len = ((ecc_key*)k->impl)->idLen; + return ((ecc_key*)k->impl)->id; +} +#endif + /* Uncompressed X9.63 point: the 0x04 marker plus two coordinates. */ #define ECC_X963_CAP (1 + 2 * MAX_ECC_BYTES) @@ -279,16 +367,33 @@ static void ecc_free(struct WolfCertKey* k) #endif /* WOLFCERT_HAVE_ECC */ #ifdef WOLFCERT_HAVE_ED25519 +/* wolfSSL after 5.9.4 has wc_ed25519_init_id and the TLS support for it. */ +#if defined(WOLFCERT_USE_KEY_ID) && defined(ED25519_MAX_ID_LEN) +#define WOLFCERT_ED25519_KEY_ID +#endif + static int ed25519_alloc_init(struct WolfCertKey* k) { +#ifndef WOLFCERT_ED25519_KEY_ID + if (k->id_len > 0) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "this wolfSSL has no key_id init for Ed25519"); +#endif + ed25519_key* ek = (ed25519_key*)WOLFCERT_XMALLOC(sizeof(*ek), k->heap); if (ek == NULL) return WOLFCERT_ERR_MEMORY; - int rc = wc_ed25519_init_ex(ek, k->heap, k->dev_id); + int rc; +#ifdef WOLFCERT_ED25519_KEY_ID + if (k->id_len > 0) + rc = wc_ed25519_init_id(ek, k->id, (int)k->id_len, k->heap, k->dev_id); + else +#endif + rc = wc_ed25519_init_ex(ek, k->heap, k->dev_id); if (rc != 0) { WOLFCERT_XFREE(ek, k->heap); - return WOLFCERT_ERR_WC(rc, "keygen", "ed25519_init_ex"); + return WOLFCERT_ERR_WC(rc, "keygen", "ed25519_init"); } k->impl = ek; @@ -316,6 +421,27 @@ static int ed25519_priv_to_der(const struct WolfCertKey* k, uint8_t* buf, word32 return wc_Ed25519PrivateKeyToDer((ed25519_key*)k->impl, buf, cap); } +#ifdef WOLFCERT_ED25519_KEY_ID +static int ed25519_pub_decode(struct WolfCertKey* k, const uint8_t* der, + word32 len) +{ + word32 idx = 0; + return wc_Ed25519PublicKeyDecode(der, &idx, (ed25519_key*)k->impl, len) == 0 + ? WOLFCERT_OK : WOLFCERT_ERR_PARSE; +} + +static int ed25519_host_priv(const struct WolfCertKey* k) +{ + return ((ed25519_key*)k->impl)->privKeySet; +} + +static const uint8_t* ed25519_impl_id(const struct WolfCertKey* k, int* len) +{ + *len = ((ed25519_key*)k->impl)->idLen; + return ((ed25519_key*)k->impl)->id; +} +#endif + static int ed25519_pub_check(struct WolfCertKey* k, const uint8_t* pub, word32 pub_len) { @@ -347,16 +473,32 @@ static void ed25519_free(struct WolfCertKey* k) #endif #ifdef WOLFCERT_HAVE_ED448 +#if defined(WOLFCERT_USE_KEY_ID) && defined(ED448_MAX_ID_LEN) +#define WOLFCERT_ED448_KEY_ID +#endif + static int ed448_alloc_init(struct WolfCertKey* k) { +#ifndef WOLFCERT_ED448_KEY_ID + if (k->id_len > 0) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "this wolfSSL has no key_id init for Ed448"); +#endif + ed448_key* ek = (ed448_key*)WOLFCERT_XMALLOC(sizeof(*ek), k->heap); if (ek == NULL) return WOLFCERT_ERR_MEMORY; - int rc = wc_ed448_init_ex(ek, k->heap, k->dev_id); + int rc; +#ifdef WOLFCERT_ED448_KEY_ID + if (k->id_len > 0) + rc = wc_ed448_init_id(ek, k->id, (int)k->id_len, k->heap, k->dev_id); + else +#endif + rc = wc_ed448_init_ex(ek, k->heap, k->dev_id); if (rc != 0) { WOLFCERT_XFREE(ek, k->heap); - return WOLFCERT_ERR_WC(rc, "keygen", "ed448_init_ex"); + return WOLFCERT_ERR_WC(rc, "keygen", "ed448_init"); } k->impl = ek; @@ -383,6 +525,27 @@ static int ed448_priv_to_der(const struct WolfCertKey* k, uint8_t* buf, word32 c return wc_Ed448PrivateKeyToDer((ed448_key*)k->impl, buf, cap); } +#ifdef WOLFCERT_ED448_KEY_ID +static int ed448_pub_decode(struct WolfCertKey* k, const uint8_t* der, + word32 len) +{ + word32 idx = 0; + return wc_Ed448PublicKeyDecode(der, &idx, (ed448_key*)k->impl, len) == 0 + ? WOLFCERT_OK : WOLFCERT_ERR_PARSE; +} + +static int ed448_host_priv(const struct WolfCertKey* k) +{ + return ((ed448_key*)k->impl)->privKeySet; +} + +static const uint8_t* ed448_impl_id(const struct WolfCertKey* k, int* len) +{ + *len = ((ed448_key*)k->impl)->idLen; + return ((ed448_key*)k->impl)->id; +} +#endif + static int ed448_pub_check(struct WolfCertKey* k, const uint8_t* pub, word32 pub_len) { @@ -440,10 +603,16 @@ static int mldsa_alloc_init(struct WolfCertKey* k) if (dk == NULL) return WOLFCERT_ERR_MEMORY; - int rc = wc_MlDsaKey_Init(dk, k->heap, k->dev_id); + int rc; +#ifdef WOLFCERT_USE_KEY_ID + if (k->id_len > 0) + rc = wc_MlDsaKey_InitId(dk, k->id, (int)k->id_len, k->heap, k->dev_id); + else +#endif + rc = wc_MlDsaKey_Init(dk, k->heap, k->dev_id); if (rc != 0) { WOLFCERT_XFREE(dk, k->heap); - return WOLFCERT_ERR_WC(rc, "keygen", "MlDsaKey_Init"); + return WOLFCERT_ERR_WC(rc, "keygen", "mldsa_init"); } int lvl = mldsa_level_for(k->type); @@ -478,6 +647,27 @@ static int mldsa_priv_to_der(const struct WolfCertKey* k, uint8_t* buf, word32 c return wc_MlDsaKey_PrivateKeyToDer((MlDsaKey*)k->impl, buf, cap); } +static int mldsa_pub_decode(struct WolfCertKey* k, const uint8_t* der, + word32 len) +{ + word32 idx = 0; + int rc = wc_MlDsaKey_PublicKeyDecode((MlDsaKey*)k->impl, der, len, &idx); + return rc == 0 ? WOLFCERT_OK : WOLFCERT_ERR_PARSE; +} + +static int mldsa_host_priv(const struct WolfCertKey* k) +{ + return ((MlDsaKey*)k->impl)->prvKeySet; +} + +#ifdef WOLFCERT_USE_KEY_ID +static const uint8_t* mldsa_impl_id(const struct WolfCertKey* k, int* len) +{ + *len = ((MlDsaKey*)k->impl)->idLen; + return ((MlDsaKey*)k->impl)->id; +} +#endif + /* Adopts the certificate's public half, which a PKCS#8 v1 key lacks. */ static int mldsa_pub_check(struct WolfCertKey* k, const uint8_t* pub, word32 pub_len) @@ -513,6 +703,11 @@ static const WolfCertKeyAlg ALG_RSA = { .priv_decode = rsa_priv_decode, .priv_to_der = rsa_priv_to_der, .pub_check = rsa_pub_check, + .pub_decode = rsa_pub_decode, + .host_priv = rsa_host_priv, +#ifdef WOLFCERT_USE_KEY_ID + .impl_id = rsa_impl_id, +#endif .free_ = rsa_free, }; #endif @@ -530,6 +725,11 @@ static const WolfCertKeyAlg ALG_ECC = { .priv_decode = ecc_priv_decode, .priv_to_der = ecc_priv_to_der, .pub_check = ecc_pub_check, + .pub_decode = ecc_pub_decode, + .host_priv = ecc_host_priv, +#ifdef WOLFCERT_USE_KEY_ID + .impl_id = ecc_impl_id, +#endif .free_ = ecc_free, }; #endif @@ -547,6 +747,11 @@ static const WolfCertKeyAlg ALG_ED25519 = { .priv_decode = ed25519_priv_decode, .priv_to_der = ed25519_priv_to_der, .pub_check = ed25519_pub_check, +#ifdef WOLFCERT_ED25519_KEY_ID + .pub_decode = ed25519_pub_decode, + .host_priv = ed25519_host_priv, + .impl_id = ed25519_impl_id, +#endif .free_ = ed25519_free, }; #endif @@ -564,6 +769,11 @@ static const WolfCertKeyAlg ALG_ED448 = { .priv_decode = ed448_priv_decode, .priv_to_der = ed448_priv_to_der, .pub_check = ed448_pub_check, +#ifdef WOLFCERT_ED448_KEY_ID + .pub_decode = ed448_pub_decode, + .host_priv = ed448_host_priv, + .impl_id = ed448_impl_id, +#endif .free_ = ed448_free, }; #endif @@ -582,6 +792,11 @@ static const WolfCertKeyAlg ALG_MLDSA44 = { .priv_decode = mldsa_priv_decode, .priv_to_der = mldsa_priv_to_der, .pub_check = mldsa_pub_check, + .pub_decode = mldsa_pub_decode, + .host_priv = mldsa_host_priv, +#ifdef WOLFCERT_USE_KEY_ID + .impl_id = mldsa_impl_id, +#endif .free_ = mldsa_free, }; #endif @@ -599,6 +814,11 @@ static const WolfCertKeyAlg ALG_MLDSA65 = { .priv_decode = mldsa_priv_decode, .priv_to_der = mldsa_priv_to_der, .pub_check = mldsa_pub_check, + .pub_decode = mldsa_pub_decode, + .host_priv = mldsa_host_priv, +#ifdef WOLFCERT_USE_KEY_ID + .impl_id = mldsa_impl_id, +#endif .free_ = mldsa_free, }; #endif @@ -616,6 +836,11 @@ static const WolfCertKeyAlg ALG_MLDSA87 = { .priv_decode = mldsa_priv_decode, .priv_to_der = mldsa_priv_to_der, .pub_check = mldsa_pub_check, + .pub_decode = mldsa_pub_decode, + .host_priv = mldsa_host_priv, +#ifdef WOLFCERT_USE_KEY_ID + .impl_id = mldsa_impl_id, +#endif .free_ = mldsa_free, }; #endif diff --git a/src/key_algs.h b/src/key_algs.h index 4ecea75b..4ca849b9 100644 --- a/src/key_algs.h +++ b/src/key_algs.h @@ -50,6 +50,16 @@ typedef struct WolfCertKeyAlg { * usable after a failure. */ int (*pub_check) (struct WolfCertKey* key, const uint8_t* pub, word32 pub_len); + /* Decode a SubjectPublicKeyInfo, for a key behind a key_id. NULL if the + * type cannot take one. */ + int (*pub_decode)(struct WolfCertKey* key, + const uint8_t* der, word32 len); + /* Non-zero if the private half sits in host memory. NULL if the type + * cannot take a key_id. */ + int (*host_priv) (const struct WolfCertKey* key); + /* The key id in key->impl, which make may have changed. NULL if the type + * cannot take a key_id. */ + const uint8_t* (*impl_id)(const struct WolfCertKey* key, int* len); void (*free_) (struct WolfCertKey* key); } WolfCertKeyAlg; @@ -59,4 +69,7 @@ const WolfCertKeyAlg* wolfcert_key_alg(WolfCertKeyType t); /* NULL-terminated list of compiled-in algorithms. */ const WolfCertKeyAlg* const* wolfcert_key_algs_all(void); +/* Non-zero for an RSA modulus size wolfCert generates and accepts. */ +int wolfcert_rsa_bits_ok(int bits); + #endif /* WOLFCERT_KEY_ALGS_H */ diff --git a/src/keygen.c b/src/keygen.c index e1a95b49..f938d91e 100644 --- a/src/keygen.c +++ b/src/keygen.c @@ -30,7 +30,7 @@ #include static WolfCertKey* alloc_shell(WolfCertKeyType type, int dev_id, - const char* label, void* heap) + const uint8_t* id, size_t id_len, void* heap) { WolfCertKey* k = (WolfCertKey*)WOLFCERT_XMALLOC(sizeof(*k), heap); if (k == NULL) @@ -41,17 +41,39 @@ static WolfCertKey* alloc_shell(WolfCertKeyType type, int dev_id, k->dev_id = dev_id; k->heap = heap; - if (label != NULL) { - k->label = wolfcert_strdup(label, heap); - if (k->label == NULL) { - WOLFCERT_XFREE(k, heap); - return NULL; - } + if (id_len > 0) { + memcpy(k->id, id, id_len); + k->id_len = id_len; } return k; } +static int check_key_id(const WolfCertKeyCfg* cfg, int dev_id) +{ + int rc = wolfcert_dev_id_check(dev_id, "keygen"); + + if (rc != WOLFCERT_OK) + return rc; + if (cfg->key_id_len == 0) + return cfg->key_id == NULL ? WOLFCERT_OK + : WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "keygen", + "key_id is set but key_id_len is 0"); + if (cfg->key_id == NULL || cfg->key_id_len > WOLFCERT_KEY_ID_MAX_LEN) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "keygen", + "key id must be 1..%d bytes", + WOLFCERT_KEY_ID_MAX_LEN); + if (dev_id == INVALID_DEVID) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "keygen", + "key id needs a CryptoCb device id"); +#ifndef WOLFCERT_USE_KEY_ID + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "wolfSSL lacks WOLF_CRYPTO_CB or WOLF_PRIVATE_KEY_ID"); +#else + return WOLFCERT_OK; +#endif +} + static void free_shell(WolfCertKey* k) { if (k == NULL) @@ -61,29 +83,38 @@ static void free_shell(WolfCertKey* k) if (a && a->free_) a->free_(k); - WOLFCERT_XFREE(k->label, k->heap); WOLFCERT_XFREE(k, k->heap); } int wolfcert_key_generate(const WolfCertKeyCfg* cfg, WolfCertKey** out_key) { - if (cfg == NULL || out_key == NULL) + if (out_key == NULL) + return WOLFCERT_ERR_BAD_ARG; + *out_key = NULL; + if (cfg == NULL) return WOLFCERT_ERR_BAD_ARG; + int dev_id = cfg->dev_id; + const WolfCertKeyAlg* alg = wolfcert_key_alg(cfg->type); if (alg == NULL) return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", "unknown or disabled key type %d", (int)cfg->type); + int rc = check_key_id(cfg, dev_id); + if (rc != WOLFCERT_OK) + return rc; + void* heap = cfg->heap ? cfg->heap : wolfcert_default_heap(); - WolfCertKey* k = alloc_shell(cfg->type, cfg->dev_id, cfg->key_label, heap); + WolfCertKey* k = alloc_shell(cfg->type, dev_id, cfg->key_id, + cfg->key_id_len, heap); if (k == NULL) return WOLFCERT_ERR_MEMORY; /* The RNG is set up first; a DRBG alloc between the large ML-DSA * allocations tripped a glibc sysmalloc assertion. */ WC_RNG rng; - int rc = wc_InitRng_ex(&rng, heap, cfg->dev_id); + rc = wc_InitRng_ex(&rng, heap, dev_id); if (rc != 0) { free_shell(k); return WOLFCERT_ERR_WC(rc, "keygen", "InitRng"); @@ -103,6 +134,30 @@ int wolfcert_key_generate(const WolfCertKeyCfg* cfg, WolfCertKey** out_key) return rc; } + /* wolfSSL 5.9.4 falls back to software keygen when the device declines. */ + if (k->id_len > 0 && alg->host_priv != NULL && alg->host_priv(k)) { + free_shell(k); + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "CryptoCb device %d did not generate the key", + dev_id); + } + + /* The device may rename the key, as a TPM does for a transient one. */ + if (k->id_len > 0 && alg->impl_id != NULL) { + int id_len = 0; + const uint8_t* id = alg->impl_id(k, &id_len); + + /* The device holds the key, so hand it out under the requested id. */ + if (id_len <= 0 || id_len > WOLFCERT_KEY_ID_MAX_LEN) { + *out_key = k; + return WOLFCERT_ERR(WOLFCERT_ERR_CRYPTO, "keygen", + "CryptoCb device %d left a bad key id", + dev_id); + } + memcpy(k->id, id, (size_t)id_len); + k->id_len = (size_t)id_len; + } + *out_key = k; return WOLFCERT_OK; } @@ -173,7 +228,7 @@ int wolfcert_key_from_pem(const uint8_t* data, size_t data_len, const WolfCertKeyAlg* const* list = wolfcert_key_algs_all(); for (; *list != NULL; ++list) { const WolfCertKeyAlg* a = *list; - WolfCertKey* k = alloc_shell(a->type, WOLFCERT_DEVID_SOFTWARE, NULL, heap); + WolfCertKey* k = alloc_shell(a->type, INVALID_DEVID, NULL, 0, heap); if (k == NULL) { if (der != NULL) wc_FreeDer(&der); @@ -200,13 +255,143 @@ int wolfcert_key_from_pem(const uint8_t* data, size_t data_len, return WOLFCERT_ERR_PARSE; } +/* SubjectPublicKeyInfo of a PEM or DER certificate, in a fresh buffer. */ +static int cert_spki(const uint8_t* cert, size_t cert_len, void* heap, + uint8_t** out, word32* out_len) +{ + WolfCertBuffer pem_der = { 0 }; + const uint8_t* der = cert; + size_t der_len = cert_len; + uint8_t* spki = NULL; + word32 spki_len = 0; + int rc = WOLFCERT_OK; + + if (!wolfcert_buffer_is_der(cert, cert_len)) { + rc = wolfcert_pem_cert_to_der(cert, cert_len, &pem_der, heap); + der = pem_der.data; + der_len = pem_der.len; + } + if (rc == WOLFCERT_OK && + (wc_GetSubjectPubKeyInfoDerFromCert(der, (word32)der_len, NULL, + &spki_len) < 0 || spki_len == 0)) + rc = WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "keygen", + "public key source is not a certificate"); + if (rc == WOLFCERT_OK) { + spki = (uint8_t*)WOLFCERT_XMALLOC(spki_len, heap); + if (spki == NULL) + rc = WOLFCERT_ERR_MEMORY; + } + if (rc == WOLFCERT_OK && + wc_GetSubjectPubKeyInfoDerFromCert(der, (word32)der_len, spki, + &spki_len) < 0) + rc = WOLFCERT_ERR_PARSE; + + wolfcert_buffer_free(&pem_der); + if (rc != WOLFCERT_OK) { + WOLFCERT_XFREE(spki, heap); + return rc; + } + + *out = spki; + *out_len = spki_len; + return WOLFCERT_OK; +} + +/* The key must have a curve or RSA size keygen makes, and a non-zero param + * must name that one. */ +static int check_param(const WolfCertKey* k, int param) +{ + int have = 0; + +#if !defined(WOLFCERT_HAVE_RSA) && !defined(WOLFCERT_HAVE_ECC) + (void)k; +#endif +#ifdef WOLFCERT_HAVE_RSA + if (k->type == WOLFCERT_KEY_RSA) { + if (!wolfcert_rsa_bits_ok(k->rsa_bits)) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "RSA-%d is not 2048, 3072 or 4096", + k->rsa_bits); + have = k->rsa_bits; + } +#endif +#ifdef WOLFCERT_HAVE_ECC + if (k->type == WOLFCERT_KEY_ECC && + wolfcert_ecc_param_from_curve(k->curve_id, &have) != WOLFCERT_OK) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "public key is not on P-256, P-384 or P-521"); +#endif + if (param != 0 && have != 0 && param != have) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "keygen", + "public key is %d bits, param is %d", have, param); + return WOLFCERT_OK; +} + +int wolfcert_key_from_id(const WolfCertKeyCfg* cfg, + const uint8_t* cert, size_t cert_len, + WolfCertKey** out_key) +{ + if (out_key == NULL) + return WOLFCERT_ERR_BAD_ARG; + *out_key = NULL; + if (cfg == NULL || cfg->key_id_len == 0 || cert == NULL || cert_len == 0) + return WOLFCERT_ERR_BAD_ARG; + + int dev_id = cfg->dev_id; + int rc = check_key_id(cfg, dev_id); + if (rc != WOLFCERT_OK) + return rc; + + const WolfCertKeyAlg* alg = wolfcert_key_alg(cfg->type); + if (alg == NULL || alg->pub_decode == NULL) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "key type %d cannot take a key_id", (int)cfg->type); + + void* heap = cfg->heap ? cfg->heap : wolfcert_default_heap(); + uint8_t* spki = NULL; + word32 spki_len = 0; + rc = cert_spki(cert, cert_len, heap, &spki, &spki_len); + if (rc != WOLFCERT_OK) + return rc; + + WolfCertKey* k = alloc_shell(cfg->type, dev_id, cfg->key_id, + cfg->key_id_len, heap); + if (k == NULL) { + WOLFCERT_XFREE(spki, heap); + return WOLFCERT_ERR_MEMORY; + } + + rc = alg->alloc_init(k); + if (rc == WOLFCERT_OK) { + rc = alg->pub_decode(k, spki, spki_len); + if (rc == WOLFCERT_ERR_PARSE) + rc = WOLFCERT_ERR(WOLFCERT_ERR_PARSE, "keygen", + "certificate key is not a type %d key", + (int)cfg->type); + } + WOLFCERT_XFREE(spki, heap); + if (rc == WOLFCERT_OK) + rc = check_param(k, cfg->param); + if (rc != WOLFCERT_OK) { + free_shell(k); + return rc; + } + + *out_key = k; + return WOLFCERT_OK; +} + /* Serialize a software key's private DER into a freshly allocated buffer. */ -static int key_export_der(const WolfCertKey* key, uint8_t** out_der, - int* out_len, void* heap) +int wolfcert_key_export_der(const WolfCertKey* key, uint8_t** out_der, + int* out_len, void* heap) { const WolfCertKeyAlg* alg = wolfcert_key_alg(key->type); if (alg == NULL) return WOLFCERT_ERR_UNSUPPORTED; + if (key->id_len > 0 || (alg->host_priv != NULL && !alg->host_priv(key))) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "keygen", + "the private key stays in CryptoCb device %d", + key->dev_id); size_t der_cap = alg->der_cap_hint; if (key->type == WOLFCERT_KEY_RSA) { @@ -238,7 +423,7 @@ int wolfcert_key_to_der(const WolfCertKey* key, WolfCertBuffer* out_der) uint8_t* der = NULL; int der_len = 0; - int rc = key_export_der(key, &der, &der_len, key->heap); + int rc = wolfcert_key_export_der(key, &der, &der_len, key->heap); if (rc != WOLFCERT_OK) return rc; @@ -261,7 +446,7 @@ int wolfcert_key_to_pem(const WolfCertKey* key, WolfCertBuffer* out_pem) void* heap = key->heap; uint8_t* der = NULL; int der_len = 0; - int rc = key_export_der(key, &der, &der_len, heap); + int rc = wolfcert_key_export_der(key, &der, &der_len, heap); if (rc != WOLFCERT_OK) return rc; @@ -304,5 +489,15 @@ WolfCertKeyType wolfcert_key_type(const WolfCertKey* k) int wolfcert_key_dev_id(const WolfCertKey* k) { - return k ? k->dev_id : 0; + return k ? k->dev_id : INVALID_DEVID; +} + +int wolfcert_key_id(const WolfCertKey* k, const uint8_t** id, size_t* id_len) +{ + if (k == NULL || id == NULL || id_len == NULL) + return WOLFCERT_ERR_BAD_ARG; + + *id = k->id_len > 0 ? k->id : NULL; + *id_len = k->id_len; + return WOLFCERT_OK; } diff --git a/src/pkcs7_util.c b/src/pkcs7_util.c index 40c1fbea..0235aec7 100644 --- a/src/pkcs7_util.c +++ b/src/pkcs7_util.c @@ -83,7 +83,7 @@ static int pkcs7_certs_extract(const uint8_t* p7_der, size_t p7_der_len, if (p7_der == NULL || p7_der_len == 0 || out == NULL) return WOLFCERT_ERR_BAD_ARG; - PKCS7* p7 = wc_PKCS7_New(heap, WOLFCERT_DEVID_SOFTWARE); + PKCS7* p7 = wc_PKCS7_New(heap, INVALID_DEVID); if (p7 == NULL) return WOLFCERT_ERR_MEMORY; @@ -155,7 +155,7 @@ WOLFCERT_TEST_VIS int wolfcert_pkcs7_build_certs_only(const uint8_t* const* cert /* wc_PKCS7_InitWithCert() would set publicKeyOID, which makes the encoder * demand a content hash for ECDSA and RSA-PSS certs. */ - PKCS7* p7 = wc_PKCS7_New(heap, WOLFCERT_DEVID_SOFTWARE); + PKCS7* p7 = wc_PKCS7_New(heap, INVALID_DEVID); if (p7 == NULL) return WOLFCERT_ERR_MEMORY; diff --git a/src/scep/scep_client.c b/src/scep/scep_client.c index 62e42b6e..26a279b0 100644 --- a/src/scep/scep_client.c +++ b/src/scep/scep_client.c @@ -413,35 +413,6 @@ static int scep_build_txid(const ScepTxidSel* sel, return WOLFCERT_OK; } -/* The caller has already checked that key->type is WOLFCERT_KEY_RSA. */ -static int rsa_key_to_der(const WolfCertKey* key, void* heap, - uint8_t** out_der, size_t* out_len) -{ - uint8_t* der; - int sz; - int n; - - sz = wc_RsaKeyToDer((RsaKey*)key->impl, NULL, 0); - if (sz <= 0) - return WOLFCERT_ERR_WC(sz, "scep", "RsaKeyToDer"); - - der = (uint8_t*)WOLFCERT_XMALLOC((size_t)sz, heap); - if (der == NULL) - return WOLFCERT_ERR_MEMORY; - - n = wc_RsaKeyToDer((RsaKey*)key->impl, der, (word32)sz); - if (n <= 0) { - wc_ForceZero(der, (word32)sz); - WOLFCERT_XFREE(der, heap); - return WOLFCERT_ERR_WC(n, "scep", "RsaKeyToDer"); - } - - *out_der = der; - *out_len = (size_t)n; - - return WOLFCERT_OK; -} - WOLFCERT_TEST_VIS int wolfcert_scep_pem_has_cert(const uint8_t* pem, size_t pem_len, const uint8_t* issuer, size_t issuer_len, const uint8_t* serial, size_t serial_len, @@ -690,37 +661,46 @@ static int scep_call_check(const ScepCall* c) "SCEP (RFC 8894) requires an RSA signer for pkiMessage; " "Ed25519/Ed448/ML-DSA are not permitted"); + /* PKCS#7 takes the private key as DER, which a key_id key cannot give. */ + if (pki && c->key->id_len > 0) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "scep", + "SCEP cannot sign or decrypt with a key_id key"); + return WOLFCERT_OK; } struct WolfCertScepSession { - WolfCertHttpSession* http; - char* server_url; /* full SCEP endpoint URL, owned */ - void* heap; + WolfCertHttpSession* http; + char* server_url; /* full SCEP endpoint URL, owned */ + void* heap; WolfCertScepTxidMode txid_mode; WolfCertScepContentCipher content_cipher; WolfCertScepRenewalMsgType renewal_msg_type; WolfCertScepSigningHash signing_hash; - char* ca_id; /* owned copy, or NULL */ + char* ca_id; /* owned copy, or NULL */ /* In-flight state of the single active round trip. */ int in_active; - enum scep_session_op in_op; /* valid when in_active */ + enum scep_session_op in_op; /* valid when in_active */ WolfCertEncoding in_enc; - char* in_url; /* owned request URL */ - WolfCertBuffer in_pki; /* built pkiMessage, owned (POST body) */ + char* in_url; /* owned request URL */ + WolfCertBuffer in_pki; /* pkiMessage POST body, owned */ WolfCertHttpRequest in_req; WolfCertHttpResponse in_resp; - const uint8_t* in_ca_bundle; size_t in_ca_bundle_len; /* in use */ - uint8_t* in_ca_bundle_copy; /* owned, for an _nb request */ - const uint8_t* in_signer; size_t in_signer_len; /* in use */ - uint8_t* in_signer_copy; /* owned: _nb copy or self-signed */ - uint8_t* in_signer_key; size_t in_signer_key_len; /* key DER, zeroized */ - uint8_t* in_txid; size_t in_txid_len; /* owned, from scep_prepare */ - uint8_t in_nonce[SCEP_NONCE_SZ]; - WolfCertBuffer in_ias; /* IssuerAndSubject or IssuerAndSerial sent, owned */ - const void* in_out; /* caller's output, checked on resume */ + const uint8_t* in_ca_bundle; /* in use */ + size_t in_ca_bundle_len; + uint8_t* in_ca_bundle_copy; /* owned, for an _nb request */ + const uint8_t* in_signer; /* in use */ + size_t in_signer_len; + uint8_t* in_signer_copy; /* owned: _nb copy or self-signed */ + uint8_t* in_signer_key; /* key DER, zeroized */ + size_t in_signer_key_len; + uint8_t* in_txid; /* owned, from scep_prepare */ + size_t in_txid_len; + uint8_t in_nonce[SCEP_NONCE_SZ]; + WolfCertBuffer in_ias; /* IssuerAndSubject/Serial, owned */ + const void* in_out; /* caller's output, resume check */ }; static uint8_t* dup_buf(const uint8_t* src, size_t len, void* heap) @@ -796,6 +776,7 @@ static int scep_session_connect(WolfCertScepSession* s, .client_cert_len = srv->client_cert_len, .client_key = srv->client_key, .client_key_len = srv->client_key_len, + .client_key_obj = srv->client_key_obj, .transport = srv->transport, .heap = s->heap, }; @@ -992,12 +973,13 @@ static int scep_prepare(WolfCertScepSession* s, const ScepCall* c, WolfCertBuffer env = { 0 }; int rc = wolfcert_scep_envelop(c->ra_cert, c->ra_cert_len, envelope_content, envelope_content_len, - enc_oid, &env, heap); + enc_oid, &env, wolfcert_default_dev_id(), + heap); if (rc != WOLFCERT_OK) return rc; WC_RNG rng; - int rng_rc = wc_InitRng_ex(&rng, heap, WOLFCERT_DEVID_SOFTWARE); + int rng_rc = wc_InitRng_ex(&rng, heap, wolfcert_default_dev_id()); if (rng_rc != 0) { wolfcert_buffer_free(&env); return WOLFCERT_ERR_WC(rng_rc, "scep", "RNG init failed"); @@ -1026,7 +1008,8 @@ static int scep_prepare(WolfCertScepSession* s, const ScepCall* c, rc = wolfcert_scep_build_pki_message(env.data, env.len, s->in_signer, s->in_signer_len, s->in_signer_key, s->in_signer_key_len, - hash_oid, &attrs, out_pki, heap); + hash_oid, &attrs, out_pki, + wolfcert_default_dev_id(), heap); wolfcert_buffer_free(&env); return rc; @@ -1053,7 +1036,8 @@ static int scep_finish(const WolfCertScepSession* s, WolfCertScepResult* out) int rc = wolfcert_scep_parse_pki_message(s->in_resp.body, s->in_resp.body_len, &resp_env, &rx_tid, &rx_tid_len, &rx_sn, &rx_sn_len, &rx_rn, &rx_rn_len, - &resp_mt, &status, &rx_signer, &rx_signer_len, &fail_info, heap); + &resp_mt, &status, &rx_signer, &rx_signer_len, &fail_info, + wolfcert_default_dev_id(), heap); WOLFCERT_XFREE(rx_sn, heap); @@ -1126,7 +1110,7 @@ static int scep_finish(const WolfCertScepSession* s, WolfCertScepResult* out) rc = wolfcert_scep_deenvelop(s->in_signer, s->in_signer_len, s->in_signer_key, s->in_signer_key_len, resp_env.data, resp_env.len, &inner, - heap); + wolfcert_default_dev_id(), heap); if (rc == WOLFCERT_OK) rc = wolfcert_pkcs7_certs_to_pem(inner.data, inner.len, &out->cert_pem, heap); @@ -1155,6 +1139,7 @@ static int scep_session_begin_pki_op(WolfCertScepSession* s, const ScepCall* c, WolfCertBuffer pki = { 0 }; char* url = NULL; int use_post = 0; + int key_len = 0; int rc = WOLFCERT_OK; c->res_out->heap = heap; @@ -1163,7 +1148,8 @@ static int scep_session_begin_pki_op(WolfCertScepSession* s, const ScepCall* c, rc = wolfcert_scep_self_signed_rsa((RsaKey*)c->key->impl, c->csr, c->csr_len, &s->in_signer_copy, - &s->in_signer_len, heap); + &s->in_signer_len, + wolfcert_default_dev_id(), heap); s->in_signer = s->in_signer_copy; } else { @@ -1213,8 +1199,9 @@ static int scep_session_begin_pki_op(WolfCertScepSession* s, const ScepCall* c, } if (rc == WOLFCERT_OK) - rc = rsa_key_to_der(c->key, heap, &s->in_signer_key, - &s->in_signer_key_len); + rc = wolfcert_key_export_der(c->key, &s->in_signer_key, &key_len, + heap); + s->in_signer_key_len = (size_t)key_len; if (rc == WOLFCERT_OK) rc = scep_prepare(s, c, msg_type, content, content_len, &pki); if (rc == WOLFCERT_OK) diff --git a/src/scep/scep_msg.c b/src/scep/scep_msg.c index f164294d..ba742fcb 100644 --- a/src/scep/scep_msg.c +++ b/src/scep/scep_msg.c @@ -325,9 +325,9 @@ static int build_signed_attribs(const WolfCertScepAttrs* a, WOLFCERT_TEST_VIS int wolfcert_scep_envelop(const uint8_t* ra_cert_der, size_t ra_cert_len, const uint8_t* payload, size_t payload_len, int enc_oid, - WolfCertBuffer* out_der, void* heap) + WolfCertBuffer* out_der, int dev_id, void* heap) { - PKCS7* p7 = wc_PKCS7_New(heap, WOLFCERT_DEVID_SOFTWARE); + PKCS7* p7 = wc_PKCS7_New(heap, dev_id); if (p7 == NULL) return WOLFCERT_ERR_MEMORY; @@ -347,7 +347,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_envelop(const uint8_t* ra_cert_der, } WC_RNG rng; - if (wc_InitRng_ex(&rng, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRng_ex(&rng, heap, dev_id) != 0) { wc_PKCS7_Free(p7); return WOLFCERT_ERR_CRYPTO; } @@ -385,13 +385,13 @@ WOLFCERT_TEST_VIS int wolfcert_scep_envelop(const uint8_t* ra_cert_der, int wolfcert_scep_deenvelop(const uint8_t* recipient_cert_der, size_t recipient_cert_len, const uint8_t* recipient_key_der, size_t recipient_key_len, const uint8_t* env_der, size_t env_len, - WolfCertBuffer* out_plain, void* heap) + WolfCertBuffer* out_plain, int dev_id, void* heap) { /* env_len is server-controlled and sizes the env_len + 4096 allocation. */ if (env_len == 0 || env_len > WOLFCERT_SCEP_MAX_MSG_SZ) return WOLFCERT_ERR_BAD_ARG; - PKCS7* p7 = wc_PKCS7_New(heap, WOLFCERT_DEVID_SOFTWARE); + PKCS7* p7 = wc_PKCS7_New(heap, dev_id); if (p7 == NULL) return WOLFCERT_ERR_MEMORY; @@ -429,7 +429,7 @@ int wolfcert_scep_deenvelop(const uint8_t* recipient_cert_der, size_t recipient_ WOLFCERT_TEST_VIS int wolfcert_scep_self_signed_rsa(RsaKey* key, const uint8_t* csr_der, size_t csr_len, uint8_t** out_der, size_t* out_len, - void* heap) + int dev_id, void* heap) { DecodedCert* dc; Cert* cert; @@ -450,7 +450,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_self_signed_rsa(RsaKey* key, if (cert == NULL) return WOLFCERT_ERR_MEMORY; - wc_InitCert_ex(cert, heap, WOLFCERT_DEVID_SOFTWARE); + wc_InitCert_ex(cert, heap, dev_id); dc = (DecodedCert*)WOLFCERT_XMALLOC(sizeof(*dc), heap); if (dc == NULL) { @@ -503,7 +503,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_self_signed_rsa(RsaKey* key, return WOLFCERT_ERR_WC(rc, "scep", "SetKeyUsage"); } - if (wc_InitRng_ex(&rng, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRng_ex(&rng, heap, dev_id) != 0) { wc_CertFree(cert); return WOLFCERT_ERR_CRYPTO; } @@ -532,9 +532,10 @@ WOLFCERT_TEST_VIS int wolfcert_scep_self_signed_rsa(RsaKey* key, WOLFCERT_TEST_VIS int wolfcert_scep_build_pki_message(const uint8_t* envelope_der, size_t envelope_len, const uint8_t* signer_cert_der, size_t signer_cert_len, const uint8_t* signer_key_der, size_t signer_key_len, int hash_oid, - const WolfCertScepAttrs* attrs, WolfCertBuffer* out_der, void* heap) + const WolfCertScepAttrs* attrs, WolfCertBuffer* out_der, int dev_id, + void* heap) { - PKCS7* p7 = wc_PKCS7_New(heap, WOLFCERT_DEVID_SOFTWARE); + PKCS7* p7 = wc_PKCS7_New(heap, dev_id); if (p7 == NULL) return WOLFCERT_ERR_MEMORY; @@ -545,7 +546,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_build_pki_message(const uint8_t* envelope_de } WC_RNG rng; - if (wc_InitRng_ex(&rng, heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRng_ex(&rng, heap, dev_id) != 0) { wc_PKCS7_Free(p7); return WOLFCERT_ERR_CRYPTO; } @@ -639,7 +640,8 @@ WOLFCERT_TEST_VIS int wolfcert_scep_build_next_ca_response(const uint8_t* next_c rc = wolfcert_scep_build_pki_message(inner.data, inner.len, ca_cert, ca_cert_len, ca_key, ca_key_len, - SHA256h, &attrs, out_der, heap); + SHA256h, &attrs, out_der, + INVALID_DEVID, heap); wolfcert_buffer_free(&inner); return rc; @@ -662,7 +664,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_verify_next_ca_response(const uint8_t* resp_ rc = wolfcert_scep_parse_pki_message(resp_der, resp_len, &content, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - &signer, &signer_len, NULL, heap); + &signer, &signer_len, NULL, wolfcert_default_dev_id(), heap); /* The rollover signer must share the trusted current CA's public key. */ if (rc == WOLFCERT_OK) { @@ -722,7 +724,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_parse_pki_message(const uint8_t* pki_der, size_t* out_tid_len, uint8_t** out_sender_nonce, size_t* out_snonce_len, uint8_t** out_recipient_nonce,size_t* out_rnonce_len, char** out_message_type, char** out_pki_status, uint8_t** out_signer_cert, size_t* out_signer_cert_len, - char** out_fail_info, void* heap) + char** out_fail_info, int dev_id, void* heap) { PKCS7* p7; PKCS7DecodedAttrib* a; @@ -739,7 +741,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_parse_pki_message(const uint8_t* pki_der, int bit; int rc; - p7 = wc_PKCS7_New(heap, WOLFCERT_DEVID_SOFTWARE); + p7 = wc_PKCS7_New(heap, dev_id); if (p7 == NULL) return WOLFCERT_ERR_MEMORY; diff --git a/src/scep/scep_server.c b/src/scep/scep_server.c index 5bc58130..45e9fe44 100644 --- a/src/scep/scep_server.c +++ b/src/scep/scep_server.c @@ -590,6 +590,7 @@ static int send_cert_rep(WolfCertServer* s, int fd, rc = wolfcert_scep_envelop(env_target, env_target_len, p7.data, p7.len, SCEP_SRV_ENC_OID, &resp_env, + INVALID_DEVID, s->heap); wolfcert_buffer_free(&p7); @@ -600,7 +601,7 @@ static int send_cert_rep(WolfCertServer* s, int fd, } WC_RNG rng; - if (wc_InitRng_ex(&rng, s->heap, WOLFCERT_DEVID_SOFTWARE) != 0) { + if (wc_InitRng_ex(&rng, s->heap, INVALID_DEVID) != 0) { wolfcert_buffer_free(&resp_env); send_text(s, fd, 500, "Server Error", "text/plain", ""); return WOLFCERT_ERR_CRYPTO; @@ -679,7 +680,8 @@ static int send_cert_rep(WolfCertServer* s, int fd, rc = wolfcert_scep_build_pki_message(resp_env.data, resp_env.len, sign_cert, sign_cert_len, sign_key, sign_key_len, - SHA256h, &attrs, &pki_out, s->heap); + SHA256h, &attrs, &pki_out, + INVALID_DEVID, s->heap); wolfcert_buffer_free(&resp_env); if (rc != WOLFCERT_OK) { @@ -1099,7 +1101,8 @@ static int handle_pki_op(WolfCertServer* s, int fd, const ScepRequest* req) int rc = wolfcert_scep_parse_pki_message(req->body, req->body_len, &env, &tid, &tid_len, &snonce, &snonce_len, &rnonce, &rnonce_len, - &mt, &ps, &signer_cert, &signer_cert_len, NULL, s->heap); + &mt, &ps, &signer_cert, &signer_cert_len, NULL, INVALID_DEVID, + s->heap); if (rc == WOLFCERT_ERR_MEMORY) { send_text(s, fd, 500, "Server Error", "text/plain", ""); goto out; @@ -1129,6 +1132,7 @@ static int handle_pki_op(WolfCertServer* s, int fd, const ScepRequest* req) rep_identity(s, &rcpt_cert, &rcpt_cert_len, &rcpt_key, &rcpt_key_len); rc = wolfcert_scep_deenvelop(rcpt_cert, rcpt_cert_len, rcpt_key, rcpt_key_len, env.data, env.len, &csr, + INVALID_DEVID, s->heap); if (rc != WOLFCERT_OK) { const char* fail_info = rc == WOLFCERT_ERR_UNSUPPORTED @@ -1318,7 +1322,7 @@ static int handle_request(WolfCertServer* s, int fd) static int make_split_ra(WolfCertServer* s, ScepPriv* p) { WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE, + .dev_id = INVALID_DEVID, .heap = s->heap }; WolfCertCertMeta meta = { .subject_dn = "CN=wolfCert Test RA,O=wolfCert" }; WolfCertKey* key = NULL; @@ -1397,7 +1401,7 @@ static int bundle_cert(WolfCertServer* s, int key_type, void* pub, issuer = s->ca.cert_der; issuer_len = s->ca.cert_der_len; } - if (wc_InitCert_ex(c, s->heap, WOLFCERT_DEVID_SOFTWARE) != 0) + if (wc_InitCert_ex(c, s->heap, INVALID_DEVID) != 0) rc = WOLFCERT_ERR_CRYPTO; if (rc == WOLFCERT_OK) { c->sigType = CTC_SHA256wRSA; @@ -1427,7 +1431,7 @@ static int bundle_cert(WolfCertServer* s, int key_type, void* pub, rc = WOLFCERT_ERR_MEMORY; } if (rc == WOLFCERT_OK) { - if (wc_InitRng_ex(&rng, s->heap, WOLFCERT_DEVID_SOFTWARE) != 0) + if (wc_InitRng_ex(&rng, s->heap, INVALID_DEVID) != 0) rc = WOLFCERT_ERR_CRYPTO; else rng_ok = 1; @@ -1458,7 +1462,7 @@ static int bundle_cert(WolfCertServer* s, int key_type, void* pub, static int bundle_root(WolfCertServer* s, uint8_t** root, size_t* root_len) { WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE, + .dev_id = INVALID_DEVID, .heap = s->heap }; WolfCertKey* key = NULL; uint8_t* ca = NULL; @@ -1479,6 +1483,7 @@ static int bundle_root(WolfCertServer* s, uint8_t** root, size_t* root_len) WOLFCERT_XFREE(s->ca.cert_der, s->ca.heap); s->ca.cert_der = ca; s->ca.cert_der_len = ca_len; + s->ca.skid_copies = wolfcert_ca_skid_copies(&s->ca); } wolfcert_key_free(key); @@ -1491,7 +1496,7 @@ WOLFCERT_TEST_VIS int wolfcert_scep_server_set_bundle_fault(WolfCertServer* s, ScepPriv* p = (ScepPriv*)s->priv; RsaKey* ca_key = (RsaKey*)s->ca.impl; WolfCertKeyCfg ecc = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE, + .dev_id = INVALID_DEVID, .heap = s->heap }; WolfCertKey* ecc_key = NULL; uint8_t* der[4] = { NULL, NULL, NULL, NULL }; diff --git a/src/server.c b/src/server.c index 1c4563ff..fd7694c0 100644 --- a/src/server.c +++ b/src/server.c @@ -327,7 +327,6 @@ static int tls_setup(WolfCertServer* s, const WolfCertServerCfgSrv* cfg) if (cfg->tls_cert_pem_len == 0 || cfg->tls_key_pem_len == 0) { return WOLFCERT_ERR_BAD_ARG; } - WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfTLS_server_method()); if (ctx == NULL) return WOLFCERT_ERR_CRYPTO; @@ -372,6 +371,18 @@ static int tls_setup(WolfCertServer* s, const WolfCertServerCfgSrv* cfg) wolfSSL_CTX_set_verify(ctx, verify, NULL); } + if (cfg->tls_client_trust_issued) { + rc = wolfSSL_CTX_load_verify_buffer(ctx, s->ca.cert_der, + (long)s->ca.cert_der_len, + WOLFSSL_FILETYPE_ASN1); + if (rc != WOLFSSL_SUCCESS) { + wolfSSL_CTX_free(ctx); + return WOLFCERT_ERR(WOLFCERT_ERR_CRYPTO, "server", + "TLS: load_verify_buffer (issuing CA) failed"); + } + if (cfg->tls_client_ca_pem == NULL || cfg->tls_client_ca_pem_len == 0) + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + } /* Grouped messages would hold back the PHA CertificateRequest. */ if (cfg->tls_post_handshake_auth) (void)wolfSSL_CTX_clear_group_messages(ctx); @@ -392,6 +403,23 @@ static int tls_setup(WolfCertServer* s, const WolfCertServerCfgSrv* cfg) } #endif + if (cfg->tls_client_trust_issued && cfg->tls_client_ca_pem != NULL && + cfg->tls_client_ca_pem_len > 0) { + s->issued_cm = wolfSSL_CertManagerNew_ex(s->heap); + rc = WOLFSSL_FAILURE; + if (s->issued_cm != NULL) + rc = wolfSSL_CertManagerLoadCABuffer(s->issued_cm, s->ca.cert_der, + (long)s->ca.cert_der_len, + WOLFSSL_FILETYPE_ASN1); + if (rc != WOLFSSL_SUCCESS) { + wolfSSL_CertManagerFree(s->issued_cm); + s->issued_cm = NULL; + wolfSSL_CTX_free(ctx); + return WOLFCERT_ERR(WOLFCERT_ERR_CRYPTO, "server", + "TLS: cannot load the issuing CA"); + } + } + s->tls_ctx = ctx; return WOLFCERT_OK; } @@ -412,11 +440,28 @@ static const WolfCertServerOps* lookup_ops(WolfCertProtocol p) } } +/* Basic, a client CA or the anonymous opt-in admits a /simpleenroll. */ +static int cfg_enroll_auth(const WolfCertServerCfgSrv* cfg) +{ + return cfg->http_basic_user != NULL || + (cfg->tls_client_ca_pem != NULL && cfg->tls_client_ca_pem_len > 0) || + cfg->est_allow_anonymous_enroll; +} + int wolfcert_server_start(const WolfCertServerCfgSrv* cfg, WolfCertServer** out) { if (cfg == NULL || out == NULL) return WOLFCERT_ERR_BAD_ARG; + if (cfg->protocol != WOLFCERT_PROTO_EST && cfg->tls_client_trust_issued) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", + "tls_client_trust_issued is supported only for EST"); +#ifndef KEEP_PEER_CERT + if (cfg->tls_client_trust_issued) + return WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "server", + "tls_client_trust_issued needs wolfSSL built with KEEP_PEER_CERT"); +#endif + const WolfCertServerOps* ops = lookup_ops(cfg->protocol); if (ops == NULL) return WOLFCERT_ERR_UNSUPPORTED; @@ -432,19 +477,32 @@ int wolfcert_server_start(const WolfCertServerCfgSrv* cfg, WolfCertServer** out) return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", "http_basic_user and http_basic_pass must both be non-empty"); - if (cfg->protocol == WOLFCERT_PROTO_EST && cfg->http_basic_user == NULL && - (cfg->tls_client_ca_pem == NULL || - cfg->tls_client_ca_pem_len == 0) && - !cfg->est_allow_anonymous_enroll) + int renew_only = cfg->protocol == WOLFCERT_PROTO_EST && + !cfg_enroll_auth(cfg) && cfg->tls_client_trust_issued; + + if (cfg->protocol == WOLFCERT_PROTO_EST && !cfg_enroll_auth(cfg) && + !cfg->tls_client_trust_issued) return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", "EST enrollment needs http_basic_user or tls_client_ca_pem, " - "or est_allow_anonymous_enroll"); + "or est_allow_anonymous_enroll, or tls_client_trust_issued to " + "only renew"); + + if (renew_only && cfg->ca_cert == NULL) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", + "a renewal-only server needs ca_cert and ca_key; a new CA has " + "issued nothing to renew"); /* Only EST requests the certificate that PHA defers past the handshake. */ if (cfg->protocol != WOLFCERT_PROTO_EST && cfg->tls_post_handshake_auth) return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", "post-handshake auth is supported only for EST"); + if ((cfg->ca_cert == NULL) != (cfg->ca_key == NULL) || + (cfg->ca_cert == NULL) != (cfg->ca_cert_len == 0) || + (cfg->ca_key == NULL) != (cfg->ca_key_len == 0)) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", + "ca_cert and ca_key must both be set, or both NULL"); + struct in_addr bind_addr = { .s_addr = htonl(INADDR_ANY) }; if (cfg->bind_host != NULL && inet_pton(AF_INET, cfg->bind_host, &bind_addr) != 1) @@ -461,6 +519,7 @@ int wolfcert_server_start(const WolfCertServerCfgSrv* cfg, WolfCertServer** out) s->listen_fd = -1; s->ops = ops; s->heap = heap; + s->renew_only = renew_only; if (cfg->challenge_password) s->cfg_challenge = wolfcert_strdup(cfg->challenge_password, heap); @@ -490,19 +549,14 @@ int wolfcert_server_start(const WolfCertServerCfgSrv* cfg, WolfCertServer** out) } int rc; - int have_ca = 0; - - if (cfg->ca_store != NULL) { - rc = wolfcert_ca_load(&s->ca, cfg->ca_store, heap); - if (rc == WOLFCERT_OK) - have_ca = 1; - /* Only an empty store means no CA yet; any other failure must not - * replace the stored CA. */ - else if (rc != WOLFCERT_ERR_NOT_FOUND) + + if (cfg->ca_cert != NULL) { + rc = wolfcert_ca_load(&s->ca, cfg->ca_cert, cfg->ca_cert_len, + cfg->ca_key, cfg->ca_key_len, heap); + if (rc != WOLFCERT_OK) goto fail; } - - if (!have_ca) { + else { WolfCertKeyType kt = cfg->ca_key_type ? cfg->ca_key_type : WOLFCERT_DEFAULT_KEY_TYPE; int kp = cfg->ca_key_param; @@ -510,13 +564,6 @@ int wolfcert_server_start(const WolfCertServerCfgSrv* cfg, WolfCertServer** out) rc = wolfcert_ca_generate(&s->ca, kt, kp, heap); if (rc != WOLFCERT_OK) goto fail; - - if (cfg->ca_store != NULL) { - /* Not re-wrapped: it would lose ca_save's rollback diagnostic. */ - rc = wolfcert_ca_save(&s->ca, cfg->ca_store); - if (rc != WOLFCERT_OK) - goto fail; - } } rc = ops->start(cfg, s); @@ -701,6 +748,8 @@ void wolfcert_server_free(WolfCertServer* srv) wolfSSL_CTX_free(srv->tls_ctx); srv->tls_ctx = NULL; } + wolfSSL_CertManagerFree(srv->issued_cm); + srv->issued_cm = NULL; if (srv->listen_fd >= 0) close(srv->listen_fd); @@ -722,6 +771,18 @@ uint16_t wolfcert_server_port(const WolfCertServer* srv) return srv ? srv->cfg.bind_port : 0; } +int wolfcert_server_get_ca(const WolfCertServer* srv, WolfCertEncoding enc, + WolfCertBuffer* out_cert, WolfCertBuffer* out_key) +{ + if (srv == NULL || out_cert == NULL) + return WOLFCERT_ERR_BAD_ARG; + if (enc != WOLFCERT_ENCODING_PEM && enc != WOLFCERT_ENCODING_DER) + return WOLFCERT_ERR(WOLFCERT_ERR_BAD_ARG, "server", "bad encoding %d", + (int)enc); + + return wolfcert_ca_export(&srv->ca, enc, out_cert, out_key); +} + #if defined(WOLFCERT_BUILD_TESTING) WOLFCERT_TEST_VIS void wolfcert_server_set_request_timeout(WolfCertServer* srv, int ms) diff --git a/src/store.c b/src/store.c deleted file mode 100644 index 25cc2cea..00000000 --- a/src/store.c +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright (C) 2026 wolfSSL Inc. - * - * This file is part of wolfCert. - * - * wolfCert 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. - * - * wolfCert 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 wolfCert. If not, see . - */ - -/* Precedes every system header, so not gated on WOLFCERT_HAVE_POSIX_STORE. */ -#define _POSIX_C_SOURCE 200809L -#define _DEFAULT_SOURCE - -#include -#include -#include "internal.h" - -#include - -#include - -#ifdef WOLFCERT_HAVE_POSIX_STORE -#include -#include -#include -#include -#endif - -#ifdef WOLFCERT_HAVE_POSIX_STORE - -typedef struct { - char* root; -} PosixCtx; - -static int posix_join(const char* root, const char* key, char** out, void* heap) -{ - size_t rl = strlen(root); - size_t kl = strlen(key); - - char* p = (char*)WOLFCERT_XMALLOC(rl + 1 + kl + 1, heap); - if (p == NULL) - return WOLFCERT_ERR_MEMORY; - - memcpy(p, root, rl); - p[rl] = '/'; - memcpy(p + rl + 1, key, kl + 1); - *out = p; - - return WOLFCERT_OK; -} - -static int posix_read(void* ctx_, const char* key, WolfCertBuffer* out) -{ - PosixCtx* ctx = (PosixCtx*)ctx_; - char* path = NULL; - FILE* f = NULL; - uint8_t* buf = NULL; - long len = 0; - size_t n = 0; - int rc = posix_join(ctx->root, key, &path, out->heap); - if (rc != WOLFCERT_OK) - return rc; - - f = fopen(path, "rb"); - if (f == NULL) - rc = (errno == ENOENT) ? WOLFCERT_ERR_NOT_FOUND : WOLFCERT_ERR_IO; - - if (rc == WOLFCERT_OK && fseek(f, 0, SEEK_END) != 0) - rc = WOLFCERT_ERR_IO; - - if (rc == WOLFCERT_OK) { - len = ftell(f); - rewind(f); - if (len < 0) - rc = WOLFCERT_ERR_IO; - } - - if (rc == WOLFCERT_OK) { - buf = (uint8_t*)WOLFCERT_XMALLOC((size_t)len, out->heap); - if (buf == NULL) - rc = WOLFCERT_ERR_MEMORY; - } - - if (rc == WOLFCERT_OK) { - n = fread(buf, 1, (size_t)len, f); - if (n != (size_t)len) - rc = WOLFCERT_ERR_IO; - } - - if (rc == WOLFCERT_OK) { - out->data = buf; - out->len = (size_t)len; - buf = NULL; /* ownership moves to out */ - } - - if (f != NULL) - fclose(f); - WOLFCERT_XFREE(path, out->heap); - WOLFCERT_XFREE(buf, out->heap); - return rc; -} - -static int posix_write(void* ctx_, const char* key, - const uint8_t* data, size_t len, int sensitive) -{ - PosixCtx* ctx = (PosixCtx*)ctx_; - char* path = NULL; - int rc = posix_join(ctx->root, key, &path, NULL); - if (rc != WOLFCERT_OK) - return rc; - - size_t plen = strlen(path); - char* tmp = (char*)WOLFCERT_XMALLOC(plen + 8, NULL); - if (tmp == NULL) { - WOLFCERT_XFREE(path, NULL); - return WOLFCERT_ERR_MEMORY; - } - - memcpy(tmp, path, plen); - memcpy(tmp + plen, ".XXXXXX", 8); - - int fd = mkstemp(tmp); - if (fd < 0) { - WOLFCERT_XFREE(tmp, NULL); - WOLFCERT_XFREE(path, NULL); - return WOLFCERT_ERR_IO; - } - - if (fchmod(fd, sensitive ? 0600 : 0644) != 0) - goto fail; - - size_t off = 0; - while (off < len) { - ssize_t w = write(fd, data + off, len - off); - if (w < 0) { - if (errno == EINTR) - continue; - goto fail; - } - off += (size_t)w; - } - - if (fsync(fd) != 0) - goto fail; - - if (close(fd) != 0) { - unlink(tmp); - goto fail_free; - } - - if (rename(tmp, path) != 0) { - unlink(tmp); - goto fail_free; - } - - WOLFCERT_XFREE(tmp, NULL); - WOLFCERT_XFREE(path, NULL); - - return WOLFCERT_OK; - -fail: - close(fd); - unlink(tmp); - -fail_free: - WOLFCERT_XFREE(tmp, NULL); - WOLFCERT_XFREE(path, NULL); - - return WOLFCERT_ERR_IO; -} - -static int posix_remove(void* ctx_, const char* key) -{ - PosixCtx* ctx = (PosixCtx*)ctx_; - char* path = NULL; - - int rc = posix_join(ctx->root, key, &path, NULL); - if (rc != WOLFCERT_OK) - return rc; - - if (unlink(path) != 0 && errno != ENOENT) - rc = WOLFCERT_ERR_IO; - - WOLFCERT_XFREE(path, NULL); - return rc; -} - -WolfCertStoreOps* wolfcert_store_posix_open(const char* root_dir, void* heap) -{ - if (root_dir == NULL) - return NULL; - - if (heap == NULL) - heap = wolfcert_default_heap(); - - WolfCertStoreOps* ops = (WolfCertStoreOps*)WOLFCERT_XMALLOC(sizeof(*ops), heap); - if (ops == NULL) - return NULL; - - PosixCtx* ctx = (PosixCtx*)WOLFCERT_XMALLOC(sizeof(*ctx), heap); - if (ctx == NULL) { - WOLFCERT_XFREE(ops, heap); - return NULL; - } - - ctx->root = wolfcert_strdup(root_dir, heap); - if (ctx->root == NULL) { - WOLFCERT_XFREE(ctx, heap); - WOLFCERT_XFREE(ops, heap); - return NULL; - } - - ops->read = posix_read; - ops->write = posix_write; - ops->remove = posix_remove; - ops->heap = heap; - ops->ctx = ctx; - - return ops; -} - -void wolfcert_store_posix_close(WolfCertStoreOps* ops) -{ - if (ops == NULL) - return; - - PosixCtx* ctx = (PosixCtx*)ops->ctx; - if (ctx) { - WOLFCERT_XFREE(ctx->root, ops->heap); - WOLFCERT_XFREE(ctx, ops->heap); - } - - WOLFCERT_XFREE(ops, ops->heap); -} - -#else /* !WOLFCERT_HAVE_POSIX_STORE */ - -WolfCertStoreOps* wolfcert_store_posix_open(const char* root_dir, void* heap) -{ - (void)root_dir; - (void)heap; - - WOLFCERT_ERR(WOLFCERT_ERR_UNSUPPORTED, "store", - "wolfCert was built without the POSIX file backend"); - return NULL; -} - -void wolfcert_store_posix_close(WolfCertStoreOps* ops) -{ - (void)ops; -} - -#endif /* WOLFCERT_HAVE_POSIX_STORE */ - -typedef struct MemEntry { - char* key; - uint8_t* data; - size_t len; - struct MemEntry* next; -} MemEntry; - -typedef struct { - MemEntry* head; -} MemCtx; - -static MemEntry** find_slot(MemCtx* ctx, const char* key) -{ - MemEntry** p = &ctx->head; - while (*p) { - if (strcmp((*p)->key, key) == 0) - return p; - p = &(*p)->next; - } - return p; -} - -static int mem_read(void* ctx_, const char* key, WolfCertBuffer* out) -{ - MemCtx* ctx = (MemCtx*)ctx_; - MemEntry** slot = find_slot(ctx, key); - if (*slot == NULL) - return WOLFCERT_ERR_NOT_FOUND; - - uint8_t* buf = (uint8_t*)WOLFCERT_XMALLOC((*slot)->len, out->heap); - if (buf == NULL) - return WOLFCERT_ERR_MEMORY; - - memcpy(buf, (*slot)->data, (*slot)->len); - out->data = buf; - out->len = (*slot)->len; - - return WOLFCERT_OK; -} - -static int mem_write(void* ctx_, const char* key, - const uint8_t* data, size_t len, int sensitive) -{ - (void)sensitive; - MemCtx* ctx = (MemCtx*)ctx_; - MemEntry** slot = find_slot(ctx, key); - void* heap = NULL; /* memory backend uses default heap */ - - if (*slot != NULL) { - WOLFCERT_XFREE((*slot)->data, heap); - (*slot)->data = (uint8_t*)WOLFCERT_XMALLOC(len, heap); - if ((*slot)->data == NULL) { - (*slot)->len = 0; - return WOLFCERT_ERR_MEMORY; - } - - memcpy((*slot)->data, data, len); - (*slot)->len = len; - - return WOLFCERT_OK; - } - - MemEntry* e = (MemEntry*)WOLFCERT_XMALLOC(sizeof(*e), heap); - if (e == NULL) - return WOLFCERT_ERR_MEMORY; - - memset(e, 0, sizeof(*e)); - e->key = wolfcert_strdup(key, heap); - e->data = (uint8_t*)WOLFCERT_XMALLOC(len, heap); - if (e->key == NULL || e->data == NULL) { - WOLFCERT_XFREE(e->key, heap); - WOLFCERT_XFREE(e->data, heap); - WOLFCERT_XFREE(e, heap); - return WOLFCERT_ERR_MEMORY; - } - - memcpy(e->data, data, len); - e->len = len; - e->next = ctx->head; - ctx->head = e; - - return WOLFCERT_OK; -} - -static int mem_remove(void* ctx_, const char* key) -{ - MemCtx* ctx = (MemCtx*)ctx_; - MemEntry** slot = find_slot(ctx, key); - if (*slot == NULL) - return WOLFCERT_OK; - - MemEntry* e = *slot; - *slot = e->next; - WOLFCERT_XFREE(e->key, NULL); - WOLFCERT_XFREE(e->data, NULL); - WOLFCERT_XFREE(e, NULL); - - return WOLFCERT_OK; -} - -WolfCertStoreOps* wolfcert_store_memory_open(void* heap) -{ - if (heap == NULL) - heap = wolfcert_default_heap(); - - WolfCertStoreOps* ops = (WolfCertStoreOps*)WOLFCERT_XMALLOC(sizeof(*ops), heap); - if (ops == NULL) - return NULL; - - MemCtx* ctx = (MemCtx*)WOLFCERT_XMALLOC(sizeof(*ctx), heap); - if (ctx == NULL) { - WOLFCERT_XFREE(ops, heap); - return NULL; - } - - memset(ctx, 0, sizeof(*ctx)); - ops->read = mem_read; - ops->write = mem_write; - ops->remove = mem_remove; - ops->heap = heap; - ops->ctx = ctx; - - return ops; -} - -void wolfcert_store_memory_close(WolfCertStoreOps* ops) -{ - if (ops == NULL) - return; - - MemCtx* ctx = (MemCtx*)ops->ctx; - while (ctx->head) { - MemEntry* e = ctx->head; - ctx->head = e->next; - WOLFCERT_XFREE(e->key, NULL); - WOLFCERT_XFREE(e->data, NULL); - WOLFCERT_XFREE(e, NULL); - } - - WOLFCERT_XFREE(ctx, ops->heap); - WOLFCERT_XFREE(ops, ops->heap); -} - -int wolfcert_store_write_cert(WolfCertStoreOps* store, const char* key, - const uint8_t* cert, size_t len) -{ - if (store == NULL || key == NULL) - return WOLFCERT_ERR_BAD_ARG; - - return store->write(store->ctx, key, cert, len, 0); -} - -int wolfcert_store_read_cert(WolfCertStoreOps* store, const char* key, - WolfCertBuffer* out) -{ - if (store == NULL || key == NULL || out == NULL) - return WOLFCERT_ERR_BAD_ARG; - - memset(out, 0, sizeof(*out)); - out->heap = store->heap; - - return store->read(store->ctx, key, out); -} - -int wolfcert_store_write_key(WolfCertStoreOps* store, const char* key_name, - const WolfCertKey* key) -{ - if (store == NULL || key_name == NULL || key == NULL) - return WOLFCERT_ERR_BAD_ARG; - - WolfCertBuffer pem = { 0 }; - int rc = wolfcert_key_to_pem(key, &pem); - if (rc != WOLFCERT_OK) - return rc; - - rc = store->write(store->ctx, key_name, pem.data, pem.len, 1); - wolfcert_buffer_free_secure(&pem); - - return rc; -} - -int wolfcert_store_read_key(WolfCertStoreOps* store, const char* key_name, - WolfCertKey** out_key) -{ - if (store == NULL || key_name == NULL || out_key == NULL) - return WOLFCERT_ERR_BAD_ARG; - - WolfCertBuffer pem = { 0 }; - pem.heap = store->heap; - - int rc = store->read(store->ctx, key_name, &pem); - if (rc != WOLFCERT_OK) - return rc; - - rc = wolfcert_key_from_pem(pem.data, pem.len, store->heap, out_key); - wolfcert_buffer_free_secure(&pem); - - return rc; -} diff --git a/src/wolfcert.c b/src/wolfcert.c index 41e7ae23..137ef277 100644 --- a/src/wolfcert.c +++ b/src/wolfcert.c @@ -40,6 +40,7 @@ int wolfcert_init(void* heap) void wolfcert_cleanup(void) { wolfSSL_Cleanup(); + wolfcert_default_dev_id_reset(); } void wolfcert_buffer_free(WolfCertBuffer* buf) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 3c8da4b1..9a2e809d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -6,6 +6,7 @@ target_link_libraries(test_smoke PRIVATE wolfcert Threads::Threads) add_test(NAME smoke COMMAND test_smoke) add_executable(test_keygen unit/test_keygen.c) +target_include_directories(test_keygen PRIVATE ${CMAKE_SOURCE_DIR}/src) target_link_libraries(test_keygen PRIVATE wolfcert) add_test(NAME keygen COMMAND test_keygen) @@ -14,10 +15,6 @@ target_include_directories(test_csr PRIVATE ${CMAKE_SOURCE_DIR}/src) target_link_libraries(test_csr PRIVATE wolfcert) add_test(NAME csr COMMAND test_csr) -add_executable(test_store unit/test_store.c) -target_link_libraries(test_store PRIVATE wolfcert) -add_test(NAME store COMMAND test_store) - if(WOLFCERT_ENABLE_BUILTIN_TRANSPORT) add_executable(test_net unit/test_net.c) target_include_directories(test_net PRIVATE ${CMAKE_SOURCE_DIR}/src) @@ -73,6 +70,11 @@ if(WOLFCERT_ENABLE_EST) target_link_libraries(test_est_mtls_roundtrip PRIVATE wolfcert Threads::Threads) add_test(NAME est_mtls_roundtrip COMMAND test_est_mtls_roundtrip) + add_executable(test_est_devid_roundtrip integration/test_est_devid_roundtrip.c) + target_link_libraries(test_est_devid_roundtrip PRIVATE wolfcert Threads::Threads) + add_test(NAME est_devid_roundtrip COMMAND test_est_devid_roundtrip) + set_tests_properties(est_devid_roundtrip PROPERTIES SKIP_RETURN_CODE 77) + add_executable(test_est_pha_roundtrip integration/test_est_pha_roundtrip.c) target_link_libraries(test_est_pha_roundtrip PRIVATE wolfcert Threads::Threads) add_test(NAME est_pha_roundtrip COMMAND test_est_pha_roundtrip) @@ -119,10 +121,10 @@ if(WOLFCERT_ENABLE_SERVER) # A stop that cannot interrupt an idle peer hangs the serving thread. set_tests_properties(server_stop_idle PROPERTIES TIMEOUT 90) - add_executable(test_server_ca_store unit/test_server_ca_store.c) - target_include_directories(test_server_ca_store PRIVATE ${CMAKE_SOURCE_DIR}/src) - target_link_libraries(test_server_ca_store PRIVATE wolfcert Threads::Threads) - add_test(NAME server_ca_store COMMAND test_server_ca_store) + add_executable(test_server_ca unit/test_server_ca.c) + target_include_directories(test_server_ca PRIVATE ${CMAKE_SOURCE_DIR}/src) + target_link_libraries(test_server_ca PRIVATE wolfcert Threads::Threads) + add_test(NAME server_ca COMMAND test_server_ca) endif() if(WOLFCERT_ENABLE_SCEP) diff --git a/tests/integration/cli_proto_scoping.sh b/tests/integration/cli_proto_scoping.sh index 02008097..e9ca5e5f 100755 --- a/tests/integration/cli_proto_scoping.sh +++ b/tests/integration/cli_proto_scoping.sh @@ -277,8 +277,41 @@ if [ -x "$SERVER" ]; then expect_server_reject "--basic $b" "non-empty USER:PASS" \ --proto est --tls-cert "$0" --tls-key "$0" --basic "$b" done + expect_server_reject "--tls-trust-issued under scep" "only for EST" \ + --proto scep --tls-trust-issued + # A wolfSSL without KEEP_PEER_CERT refuses --tls-trust-issued first. + trust_issued_ok=1 + want_alone="needs ca_cert and ca_key" + want_empty="needs ca_cert and ca_key" + case "$("$SERVER" --proto est --listen 127.0.0.1:0 --tls-cert "$0" \ + --tls-key "$0" --tls-trust-issued --est-allow-anonymous 2>&1)" in + *KEEP_PEER_CERT*) + trust_issued_ok=0 + want_alone="KEEP_PEER_CERT" + want_empty="KEEP_PEER_CERT" + ;; + *"out of memory"*) + trust_issued_ok=0 + want_empty="" + ;; + esac + expect_server_reject "--tls-trust-issued alone without --ca-dir" \ + "$want_alone" --proto est --tls-cert "$0" --tls-key "$0" \ + --tls-trust-issued + expect_server_reject "missing --ca-dir" "No such file or directory" \ + --proto est --tls-cert "$0" --tls-key "$0" --est-allow-anonymous \ + --ca-dir "$0.missing" + expect_server_reject "--ca-dir naming a file" "is not a directory" \ + --proto est --tls-cert "$0" --tls-key "$0" --est-allow-anonymous \ + --ca-dir "$0" + opendir="$(mktemp -d -t wolfcert-cadir.XXXXXX)" + chmod 0777 "$opendir" + expect_server_reject "--ca-dir writable by others" "not writable by others" \ + --proto est --tls-cert "$0" --tls-key "$0" --est-allow-anonymous \ + --ca-dir "$opendir" + rmdir "$opendir" # $0 is no PEM, so start fails in TLS setup, before anything binds. - out="$("$SERVER" --proto est --listen 127.0.0.1:18099 --tls-cert "$0" \ + out="$("$SERVER" --proto est --listen 127.0.0.1:0 --tls-cert "$0" \ --tls-key "$0" --est-allow-anonymous 2>&1)" case "$out" in *"start failed"*) @@ -289,6 +322,24 @@ if [ -x "$SERVER" ]; then fails=$((fails + 1)) ;; esac + cadir="$(mktemp -d -t wolfcert-cadir.XXXXXX)" + if [ -n "$want_empty" ]; then + expect_server_reject "--tls-trust-issued alone with an empty --ca-dir" \ + "$want_empty" --proto est --listen 127.0.0.1:0 \ + --tls-cert "$0" --tls-key "$0" --tls-trust-issued --ca-dir "$cadir" + else + echo "skip --tls-trust-issued with an empty --ca-dir (no allocator)" + fi + printf 'x' > "$cadir/ca.cert.der" + expect_server_reject "--ca-dir holding the certificate alone" \ + "ca.key.der is missing" --proto est --listen 127.0.0.1:0 \ + --tls-cert "$0" --tls-key "$0" --est-allow-anonymous --ca-dir "$cadir" + printf 'x' > "$cadir/ca.key.der" + chmod 0644 "$cadir/ca.key.der" + expect_server_reject "--ca-dir with a CA key others can read" \ + "not accessible by others" --proto est --listen 127.0.0.1:0 \ + --tls-cert "$0" --tls-key "$0" --est-allow-anonymous --ca-dir "$cadir" + rm -rf "$cadir" fi if [ ! -x "$SERVER" ]; then skip_group "--ca-fingerprint pinning (wolfcert-server not built)" @@ -318,33 +369,43 @@ else poll_tries=10 fi - # start_scep_server : a busy port is an - # environment problem, so try four and poll GetCACert into $tmp/-*. + # start_server : start wolfcert-server on a free port + # and set started_pid, and port from its "listening on" line. + start_server() { + local log="$1" i=0 + shift + port="" + # The child's own truncation can land after the first read below. + : >"$log" + "$SERVER" --listen 127.0.0.1:0 "$@" >"$log" 2>&1 & + started_pid=$! + while [ "$i" -lt "$poll_tries" ] && + kill -0 "$started_pid" 2>/dev/null; do + port="$(sed -n 's/.* listening on [0-9.]*:\([0-9]*\)$/\1/p' "$log")" + [ -n "$port" ] && return 0 + sleep "$poll_delay" + i=$((i + 1)) + done + return 1 + } + + # start_scep_server : GetCACert into $tmp/-*. start_scep_server() { - local name="$1" port="$2" n i - shift 2 + local name="$1" + shift ready=0 - for n in 0 1 2 3; do - "$SERVER" --proto scep --listen "127.0.0.1:$port" "$@" \ - >"$tmp/$name-server.log" 2>&1 & - started_pid=$! + url="" + if start_server "$tmp/$name-server.log" --proto scep "$@"; then url="http://127.0.0.1:$port/scep" - i=0 - while [ "$i" -lt "$poll_tries" ] && - kill -0 "$started_pid" 2>/dev/null; do - if "$CLI" getcacerts --proto scep --url "$url" \ - --out-cert "$tmp/$name-ca.pem" \ - >"$tmp/$name-getca.log" 2>&1; then - ready=1 - return - fi - sleep "$poll_delay" - i=$((i + 1)) - done - kill "$started_pid" 2>/dev/null - wait "$started_pid" 2>/dev/null - port=$((port + 100)) - done + if "$CLI" getcacerts --proto scep --url "$url" \ + --out-cert "$tmp/$name-ca.pem" \ + >"$tmp/$name-getca.log" 2>&1; then + ready=1 + return + fi + fi + kill "$started_pid" 2>/dev/null + wait "$started_pid" 2>/dev/null } # cert_fp : the pin getcacerts printed for that certificate. @@ -352,7 +413,7 @@ else sed -n "s/.*certificate $2 is \(sha256:[0-9A-Fa-f:]*\).*/\1/p" "$1" } - start_scep_server pin 18088 --scep-enable-next-ca + start_scep_server pin --scep-enable-next-ca srv_pid=$started_pid PIN_URL="$url" @@ -451,33 +512,20 @@ else --subject "CN=localhost" --san-ip 127.0.0.1 \ --ca-fingerprint "$fp" --out-key "$tmp/tls.key" \ --out-cert "$tmp/tls.crt" >"$tmp/tls-enroll.log" 2>&1; then - port=18092 - for n in 0 1 2 3; do - "$SERVER" --proto est --listen "127.0.0.1:$port" \ - --tls-cert "$tmp/tls.crt" --tls-key "$tmp/tls.key" \ - --tls-client-ca "$tmp/pin-ca.pem" \ - >"$tmp/est-server.log" 2>&1 & - est_pid=$! - est_url="https://127.0.0.1:$port/.well-known/est" - i=0 - while [ "$i" -lt "$poll_tries" ] && - kill -0 "$est_pid" 2>/dev/null; do - if "$CLI" getcacerts --proto est --url "$est_url" \ - --trust "$tmp/pin-ca.pem" \ - --client-cert "$tmp/ok.crt" \ - --client-key "$tmp/ok.key" \ - --out-cert "$tmp/est-ca.pem" \ - >"$tmp/est-getca.log" 2>&1; then - est_ready=1 - break 2 - fi - sleep "$poll_delay" - i=$((i + 1)) - done - kill "$est_pid" 2>/dev/null - wait "$est_pid" 2>/dev/null - port=$((port + 100)) - done + start_server "$tmp/est-server.log" --proto est \ + --tls-cert "$tmp/tls.crt" --tls-key "$tmp/tls.key" \ + --tls-client-ca "$tmp/pin-ca.pem" + est_pid=$started_pid + est_url="https://127.0.0.1:$port/.well-known/est" + if [ -n "$port" ] && + "$CLI" getcacerts --proto est --url "$est_url" \ + --trust "$tmp/pin-ca.pem" \ + --client-cert "$tmp/ok.crt" \ + --client-key "$tmp/ok.key" \ + --out-cert "$tmp/est-ca.pem" \ + >"$tmp/est-getca.log" 2>&1; then + est_ready=1 + fi fi if [ "$est_ready" -ne 1 ]; then skip_group "EST reenroll --cert forms (no mTLS server would start)" @@ -500,6 +548,78 @@ else kill "$est_pid" 2>/dev/null est_pid="" + # --ca-dir keeps the CA across a restart; only --tls-trust-issued + # lets the certificates it issued renew. + cadir="$tmp/est-ca-dir" + mkdir -m 0700 "$cadir" + cadir_ok=0 + started_pid="" + if [ -f "$tmp/tls.crt" ] && + start_server "$tmp/cadir-1.log" --proto est \ + --tls-cert "$tmp/tls.crt" --tls-key "$tmp/tls.key" \ + --est-allow-anonymous --ca-dir "$cadir"; then + cadir_url="https://127.0.0.1:$port/.well-known/est" + if "$CLI" getcacerts --proto est --url "$cadir_url" \ + --trust "$tmp/pin-ca.pem" --out-cert "$tmp/cadir-ca1.pem" \ + >"$tmp/cadir.log" 2>&1 && + "$CLI" enroll --proto est --url "$cadir_url" \ + --trust "$tmp/pin-ca.pem" --key-type rsa:2048 \ + --subject "CN=ca-dir" \ + --out-key "$tmp/cadir.key" --out-cert "$tmp/cadir.crt" \ + >>"$tmp/cadir.log" 2>&1; then + cadir_ok=1 + case "$(ls -l "$cadir/ca.key.der")" in + -rw-------*) echo "ok --ca-dir keeps the CA key 0600" ;; + *) + echo "FAIL: --ca-dir CA key mode" + fails=$((fails + 1)) + ;; + esac + if "$CLI" reenroll --proto est --url "$cadir_url" \ + --trust "$tmp/pin-ca.pem" --cert "$tmp/cadir.crt" \ + --key "$tmp/cadir.key" \ + --out-cert "$tmp/cadir-untrusted.crt" \ + >>"$tmp/cadir.log" 2>&1; then + echo "FAIL: reenroll without --tls-trust-issued succeeded" + fails=$((fails + 1)) + else + echo "ok reenroll needs --tls-trust-issued" + fi + fi + fi + kill "$started_pid" 2>/dev/null + wait "$started_pid" 2>/dev/null + started_pid="" + if [ "$trust_issued_ok" -eq 0 ]; then + echo "skip --ca-dir renewal (wolfSSL lacks KEEP_PEER_CERT)" + elif [ "$cadir_ok" -eq 1 ] && + start_server "$tmp/cadir-2.log" --proto est \ + --tls-cert "$tmp/tls.crt" --tls-key "$tmp/tls.key" \ + --est-allow-anonymous --ca-dir "$cadir" \ + --tls-trust-issued; then + cadir_url="https://127.0.0.1:$port/.well-known/est" + if "$CLI" getcacerts --proto est --url "$cadir_url" \ + --trust "$tmp/pin-ca.pem" --out-cert "$tmp/cadir-ca2.pem" \ + >>"$tmp/cadir.log" 2>&1 && + cmp -s "$tmp/cadir-ca1.pem" "$tmp/cadir-ca2.pem" && + "$CLI" reenroll --proto est --url "$cadir_url" \ + --trust "$tmp/pin-ca.pem" --cert "$tmp/cadir.crt" \ + --key "$tmp/cadir.key" --out-cert "$tmp/cadir-renewed.crt" \ + >>"$tmp/cadir.log" 2>&1 && + grep -q "BEGIN CERTIFICATE" "$tmp/cadir-renewed.crt"; then + echo "ok --ca-dir keeps the CA and renews its certificates" + else + echo "FAIL: --ca-dir after a restart" + cat "$tmp/cadir.log" "$tmp/cadir-2.log" + fails=$((fails + 1)) + fi + kill "$started_pid" 2>/dev/null + started_pid="" + else + skip_group "--ca-dir (no EST server with --ca-dir would start)" + cat "$tmp/cadir.log" "$tmp/cadir-1.log" 2>/dev/null + fi + # getnextca resolves the current CA through the same pin. expect_reject "getnextca with a mismatched --ca-fingerprint" \ "does not match --ca-fingerprint" \ @@ -521,7 +641,7 @@ else # Against a split CA/RA server that defers issuance, the RA counts only once # --ra-fingerprint names it; pinning the RA alone ignores the CA. poll="--poll-attempts 5 --poll-interval-ms 100" - start_scep_server ra 18087 --scep-split-ra --scep-require-approval \ + start_scep_server ra --scep-split-ra --scep-require-approval \ --scep-enable-next-ca --scep-enable-get-cert ra_pid=$started_pid RA_URL="$url" @@ -666,7 +786,7 @@ else case "$layout" in ras|tie|expired) split="--scep-split-ra" ;; esac - start_scep_server bundle 18091 $split --scep-ca-bundle "$layout" + start_scep_server bundle $split --scep-ca-bundle "$layout" bundle_pid=$started_pid BUNDLE_URL="$url" @@ -799,7 +919,7 @@ else # A non-200 GetCACaps warns and carries on; a dropped one stops enroll and # getcert with exit 2. AES is forced; NO_DES3 builds lack the 3DES default. for caps in 404 close; do - start_scep_server caps 18086 --scep-enable-get-cert \ + start_scep_server caps --scep-enable-get-cert \ --scep-caps-status "$caps" caps_pid=$started_pid CAPS_URL="$url" @@ -920,7 +1040,7 @@ else done # A hostname --listen is refused, and the reason reaches stderr. - "$SERVER" --proto scep --listen localhost:18090 >"$tmp/listen.log" 2>&1 & + "$SERVER" --proto scep --listen localhost:0 >"$tmp/listen.log" 2>&1 & listen_pid=$! i=0 while [ "$i" -lt "$poll_tries" ] && kill -0 "$listen_pid" 2>/dev/null; do @@ -941,25 +1061,12 @@ else # Secrets passed on the server command line must not stay visible to ps. listening=0 - for port in 18089 18189 18289 18389; do - "$SERVER" --proto scep --listen "127.0.0.1:$port" \ + if start_server "$tmp/argv.log" --proto scep \ --basic argvuser:argv-basic-secret \ - --challenge argv-challenge-secret >"$tmp/argv.log" 2>&1 & - argv_pid=$! - i=0 - while [ "$i" -lt "$poll_tries" ] && kill -0 "$argv_pid" 2>/dev/null; do - if grep -q "listening" "$tmp/argv.log"; then - listening=1 - break - fi - sleep "$poll_delay" - i=$((i + 1)) - done - if [ "$listening" -eq 1 ]; then - break - fi - kill "$argv_pid" 2>/dev/null - done + --challenge argv-challenge-secret; then + listening=1 + fi + argv_pid=$started_pid if [ "$listening" -ne 1 ]; then skip_group "server argv scrubbing (no test server would start)" diff --git a/tests/integration/est_client_cases.h b/tests/integration/est_client_cases.h index ed155c28..1904e6a9 100644 --- a/tests/integration/est_client_cases.h +++ b/tests/integration/est_client_cases.h @@ -51,7 +51,7 @@ static inline int enroll_one(const WolfCertServerCfg* client_cfg, const WolfCertBuffer* ca_pem) { WolfCertKeyCfg kcfg = { .type = kt, .param = param, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; const char* dns[] = { "device-7.local" }; WolfCertCertMeta meta = { .subject_dn = "CN=device-7,O=Acme", .san_dns = dns, .san_dns_len = 1 }; @@ -114,7 +114,7 @@ static inline int has_alt(const DNS_entry* list, int type, const char* val, static inline int enroll_check_san(const WolfCertServerCfg* client_cfg) { WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; const char* dns[] = { "device-san.local" }; const char* ips[] = { "10.20.30.40" }; const char* emails[] = { "dev-san@example.com" }; @@ -174,7 +174,7 @@ static inline int enroll_check_san(const WolfCertServerCfg* client_cfg) static inline int session_basic_auth(const WolfCertServerCfg* client_cfg) { WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=session-basic-auth" }; WolfCertServerCfg bad_cfg = *client_cfg; WolfCertKey* dk = NULL; diff --git a/tests/integration/test_est_async_roundtrip.c b/tests/integration/test_est_async_roundtrip.c index bff4f228..691c31b4 100644 --- a/tests/integration/test_est_async_roundtrip.c +++ b/tests/integration/test_est_async_roundtrip.c @@ -112,7 +112,7 @@ int main(void) &cli_cert, &cli_cert_len, &cli_key, &cli_key_len) == 0); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=async-enrollee" }; @@ -123,7 +123,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .tls_client_ca_pem = cli_cert, .tls_client_ca_pem_len = cli_cert_len, @@ -185,7 +185,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .http_basic_user = "alice", .http_basic_pass = "hunter2", .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, @@ -255,7 +255,7 @@ int main(void) free(tls_key); free(cli_cert); free(cli_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); if (pha_skipped) return 77; diff --git a/tests/integration/test_est_chunked_robustness.c b/tests/integration/test_est_chunked_robustness.c index 2688e510..99259711 100644 --- a/tests/integration/test_est_chunked_robustness.c +++ b/tests/integration/test_est_chunked_robustness.c @@ -422,7 +422,7 @@ static int build_split_enroll(char** head, size_t* head_len, char** tail) { WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=keepalive-test" }; WolfCertKey* key = NULL; WolfCertBuffer csr = { 0 }; @@ -551,7 +551,7 @@ static int no_sigpipe_on_response(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .est_allow_anonymous_enroll = 1, }; WolfCertServer* srv = NULL; @@ -613,7 +613,7 @@ int main(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = g_tls_cert, .tls_cert_pem_len = g_tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .est_allow_anonymous_enroll = 1, @@ -659,7 +659,7 @@ int main(void) if (rc != 0) return rc; - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_est_csr_attrs_apply_roundtrip.c b/tests/integration/test_est_csr_attrs_apply_roundtrip.c index 7fee0fca..b49a12a8 100644 --- a/tests/integration/test_est_csr_attrs_apply_roundtrip.c +++ b/tests/integration/test_est_csr_attrs_apply_roundtrip.c @@ -142,7 +142,7 @@ static int auto_apply_pins_everything(WolfCertServer* s) WolfCertClient* cli = NULL; REQUIRE(wolfcert_client_new(&cli) == WOLFCERT_OK); - WolfCertKeyCfg key_cfg = { .dev_id = WOLFCERT_DEVID_SOFTWARE }; + WolfCertKeyCfg key_cfg = { .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=csrattrs-auto-1", .challenge_password = "hunter2", @@ -193,7 +193,7 @@ static int explicit_caller_wins(WolfCertServer* s) WolfCertKeyCfg key_cfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE, + .dev_id = INVALID_DEVID, }; WolfCertCertMeta meta = { .subject_dn = "CN=csrattrs-auto-2", @@ -260,7 +260,7 @@ int main(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .csr_attributes_der = policy.data, .csr_attributes_len = policy.len, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, @@ -293,7 +293,7 @@ int main(void) if (rc != 0) return rc; - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_est_csr_attrs_enforce.c b/tests/integration/test_est_csr_attrs_enforce.c index 28376ff7..0689641a 100644 --- a/tests/integration/test_est_csr_attrs_enforce.c +++ b/tests/integration/test_est_csr_attrs_enforce.c @@ -116,7 +116,7 @@ static int enroll_with_challenge(WolfCertServer* s) REQUIRE(wolfcert_client_new(&cli) == WOLFCERT_OK); WolfCertKeyCfg key_cfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=enforce-ok", .challenge_password = "hunter2", @@ -150,7 +150,7 @@ static int enroll_without_challenge(WolfCertServer* s) REQUIRE(wolfcert_client_new(&cli) == WOLFCERT_OK); WolfCertKeyCfg key_cfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=enforce-reject", }; @@ -204,7 +204,7 @@ static int reject_body_names_missing_oid(uint16_t port) /* OID_CHALLENGE_PASSWORD in dotted form. */ static const char EXPECT_OID[] = "1.2.840.113549.1.9.7"; WolfCertKeyCfg key_cfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=raw-enforce" }; WolfCertKey* key = NULL; WolfCertBuffer csr_der = { 0 }; @@ -334,7 +334,7 @@ static int values_only_policy_does_not_block(WolfCertServer* s) REQUIRE(wolfcert_client_new(&cli) == WOLFCERT_OK); WolfCertKeyCfg key_cfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=enforce-values-advisory" }; WolfCertKey* key = NULL; @@ -367,7 +367,7 @@ int main(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .csr_attributes_der = policy.data, .csr_attributes_len = policy.len, .est_require_csr_attributes = 1, @@ -396,7 +396,7 @@ int main(void) WolfCertServerCfgSrv cfg2 = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .csr_attributes_der = policy2.data, .csr_attributes_len = policy2.len, .est_require_csr_attributes = 1, @@ -424,7 +424,7 @@ int main(void) WolfCertServerCfgSrv cfg_raw = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .csr_attributes_der = policy_raw.data, .csr_attributes_len = policy_raw.len, .est_require_csr_attributes = 1, @@ -452,7 +452,7 @@ int main(void) WolfCertServerCfgSrv cfg_bare = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .http_basic_user = "alice", .http_basic_pass = "secret", .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, @@ -472,7 +472,7 @@ int main(void) if (rc != 0) return rc; - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_est_csr_attrs_roundtrip.c b/tests/integration/test_est_csr_attrs_roundtrip.c index 596604fc..a2daf99d 100644 --- a/tests/integration/test_est_csr_attrs_roundtrip.c +++ b/tests/integration/test_est_csr_attrs_roundtrip.c @@ -102,7 +102,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .csr_attributes_der = blob.data, .csr_attributes_len = blob.len, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, @@ -178,7 +178,7 @@ int main(void) WolfCertServerCfgSrv cfg2 = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .est_allow_anonymous_enroll = 1, @@ -232,7 +232,7 @@ int main(void) wolfcert_buffer_free(&blob); free(tls_cert); free(tls_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_est_devid_roundtrip.c b/tests/integration/test_est_devid_roundtrip.c new file mode 100644 index 00000000..3d4e64ff --- /dev/null +++ b/tests/integration/test_est_devid_roundtrip.c @@ -0,0 +1,1160 @@ +/* + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfCert. + * + * wolfCert 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. + * + * wolfCert 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 wolfCert. If not, see . + */ + +/* EST with keys that never leave a mock CryptoCb key store, which keeps them + * by key_id and counts the private-key operations it performs. */ + +#define _POSIX_C_SOURCE 200809L +#define _DEFAULT_SOURCE +#define _DARWIN_C_SOURCE +#define _GNU_SOURCE + +#include +#include +#ifdef WOLFCERT_HAVE_SCEP +#include +#endif +#include + +#include +#include +#include + +#include "tls_test_util.h" + +#include +#include +#include +#include + +#if !defined(WOLF_CRYPTO_CB) || !defined(WOLF_PRIVATE_KEY_ID) +int main(void) +{ + printf("SKIP (wolfSSL built without WOLF_CRYPTO_CB or " + "WOLF_PRIVATE_KEY_ID)\n"); + return 77; +} +#else + +#define REQUIRE(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \ + return 1; \ + } \ + } while (0) + +#define MOCK_DEVID 0x6d6b +#define ACCEL_DEVID 0x6163 +#define UNREGISTERED_DEVID 0x7a7a +#define MOCK_SLOTS 4 + +enum { MOCK_ECC = 1, MOCK_RSA, MOCK_MLDSA, MOCK_ED25519, MOCK_ED448 }; + +/* wolfSSL after 5.9.4 can name Ed25519 and Ed448 keys by id. */ +#if defined(WOLFCERT_HAVE_ED25519) && defined(ED25519_MAX_ID_LEN) +#define MOCK_HAVE_ED25519 +#endif +#if defined(WOLFCERT_HAVE_ED448) && defined(ED448_MAX_ID_LEN) +#define MOCK_HAVE_ED448 +#endif + +typedef struct { + byte id[WOLFCERT_KEY_ID_MAX_LEN]; + int id_len; + int type; +#ifdef WOLFCERT_HAVE_ECC + ecc_key ecc; +#endif +#ifdef WOLFCERT_HAVE_RSA + RsaKey rsa; +#endif +#ifdef WOLFCERT_HAVE_MLDSA + MlDsaKey mldsa; +#endif +#ifdef MOCK_HAVE_ED25519 + ed25519_key ed25519; +#endif +#ifdef MOCK_HAVE_ED448 + ed448_key ed448; +#endif +} MockSlot; + +static MockSlot mock_slots[MOCK_SLOTS]; +static int mock_sign_requests; +static int mock_keygens; +static int mock_private_ops; + +static MockSlot* mock_find(const byte* id, int id_len) +{ + for (int i = 0; i < MOCK_SLOTS; i++) { + if (mock_slots[i].id_len == id_len && id_len > 0 && + memcmp(mock_slots[i].id, id, (size_t)id_len) == 0) + return &mock_slots[i]; + } + return NULL; +} + +static MockSlot* mock_new(const byte* id, int id_len, int type) +{ + if (mock_find(id, id_len) != NULL) + return NULL; + for (int i = 0; i < MOCK_SLOTS; i++) { + if (mock_slots[i].id_len == 0) { + memcpy(mock_slots[i].id, id, (size_t)id_len); + mock_slots[i].id_len = id_len; + mock_slots[i].type = type; + return &mock_slots[i]; + } + } + return NULL; +} + +static int mock_cb(int devId, wc_CryptoInfo* info, void* ctx) +{ + (void)devId; + (void)ctx; + + if (info->algo_type != WC_ALGO_TYPE_PK) + return CRYPTOCB_UNAVAILABLE; + + switch (info->pk.type) { +#ifdef WOLFCERT_HAVE_ECC + case WC_PK_TYPE_EC_KEYGEN: { + ecc_key* key = info->pk.eckg.key; + byte pub[1 + 2 * MAX_ECC_BYTES]; + word32 pub_len = sizeof(pub); + MockSlot* s; + int rc; + + if (key->idLen == 0) + return CRYPTOCB_UNAVAILABLE; + s = mock_new(key->id, key->idLen, MOCK_ECC); + if (s == NULL) + return BAD_STATE_E; + rc = wc_ecc_init_ex(&s->ecc, NULL, INVALID_DEVID); + if (rc == 0) + rc = wc_ecc_make_key_ex(info->pk.eckg.rng, info->pk.eckg.size, + &s->ecc, info->pk.eckg.curveId); + if (rc == 0) + rc = wc_ecc_export_x963(&s->ecc, pub, &pub_len); + if (rc == 0) + rc = wc_ecc_import_x963_ex(pub, pub_len, key, + info->pk.eckg.curveId); + if (rc == 0) + mock_keygens++; + return rc; + } + case WC_PK_TYPE_ECDSA_SIGN: { + ecc_key* key = info->pk.eccsign.key; + MockSlot* s = mock_find(key->id, key->idLen); + int rc; + + mock_sign_requests++; + if (s == NULL || s->type != MOCK_ECC) + return CRYPTOCB_UNAVAILABLE; + rc = wc_ecc_sign_hash(info->pk.eccsign.in, info->pk.eccsign.inlen, + info->pk.eccsign.out, info->pk.eccsign.outlen, + info->pk.eccsign.rng, &s->ecc); + if (rc == 0) + mock_private_ops++; + return rc; + } +#endif +#ifdef WOLFCERT_HAVE_RSA + case WC_PK_TYPE_RSA_KEYGEN: { + RsaKey* key = info->pk.rsakg.key; + byte n[512], e[8]; + word32 n_len = sizeof(n), e_len = sizeof(e); + MockSlot* s; + int rc; + + if (key->idLen == 0) + return CRYPTOCB_UNAVAILABLE; + s = mock_new(key->id, key->idLen, MOCK_RSA); + if (s == NULL) + return BAD_STATE_E; + rc = wc_InitRsaKey_ex(&s->rsa, NULL, INVALID_DEVID); + if (rc == 0) + rc = wc_MakeRsaKey(&s->rsa, info->pk.rsakg.size, + info->pk.rsakg.e, info->pk.rsakg.rng); + if (rc == 0) + rc = wc_RsaFlattenPublicKey(&s->rsa, e, &e_len, n, &n_len); + if (rc == 0) + rc = wc_RsaPublicKeyDecodeRaw(n, n_len, e, e_len, key); + if (rc == 0) + mock_keygens++; + return rc; + } + case WC_PK_TYPE_RSA: { + RsaKey* key = info->pk.rsa.key; + MockSlot* s = mock_find(key->id, key->idLen); + int rc; + + if (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT) + mock_sign_requests++; + if (s == NULL || s->type != MOCK_RSA) + return CRYPTOCB_UNAVAILABLE; + rc = wc_RsaFunction(info->pk.rsa.in, info->pk.rsa.inLen, + info->pk.rsa.out, info->pk.rsa.outLen, + info->pk.rsa.type, &s->rsa, info->pk.rsa.rng); + if (rc == 0 && (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT || + info->pk.rsa.type == RSA_PRIVATE_DECRYPT)) + mock_private_ops++; + return rc; + } +#endif +#ifdef WOLFCERT_HAVE_MLDSA + case WC_PK_TYPE_PQC_SIG_KEYGEN: { + MlDsaKey* key = (MlDsaKey*)info->pk.pqc_sig_kg.key; + byte pub[WC_MLDSA_87_PUB_KEY_SIZE]; + word32 pub_len = sizeof(pub); + MockSlot* s; + int rc; + + if (info->pk.pqc_sig_kg.type != WC_PQC_SIG_TYPE_MLDSA || + key->idLen == 0) + return CRYPTOCB_UNAVAILABLE; + s = mock_new(key->id, key->idLen, MOCK_MLDSA); + if (s == NULL) + return BAD_STATE_E; + rc = wc_MlDsaKey_Init(&s->mldsa, NULL, INVALID_DEVID); + if (rc == 0) + rc = wc_MlDsaKey_SetParams(&s->mldsa, + (byte)info->pk.pqc_sig_kg.size); + if (rc == 0) + rc = wc_MlDsaKey_MakeKey(&s->mldsa, info->pk.pqc_sig_kg.rng); + if (rc == 0) + rc = wc_MlDsaKey_ExportPubRaw(&s->mldsa, pub, &pub_len); + if (rc == 0) + rc = wc_MlDsaKey_ImportPubRaw(key, pub, pub_len); + if (rc == 0) + mock_keygens++; + return rc; + } + case WC_PK_TYPE_PQC_SIG_SIGN: { + MlDsaKey* key = (MlDsaKey*)info->pk.pqc_sign.key; + MockSlot* s; + int rc; + + mock_sign_requests++; + if (info->pk.pqc_sign.type != WC_PQC_SIG_TYPE_MLDSA || + info->pk.pqc_sign.preHashType != WC_HASH_TYPE_NONE || + info->pk.pqc_sign.addRnd != NULL) + return CRYPTOCB_UNAVAILABLE; + s = mock_find(key->id, key->idLen); + if (s == NULL || s->type != MOCK_MLDSA) + return CRYPTOCB_UNAVAILABLE; + rc = wc_MlDsaKey_SignCtx(&s->mldsa, info->pk.pqc_sign.context, + info->pk.pqc_sign.contextLen, + info->pk.pqc_sign.out, + info->pk.pqc_sign.outlen, + info->pk.pqc_sign.in, info->pk.pqc_sign.inlen, + info->pk.pqc_sign.rng); + if (rc == 0) + mock_private_ops++; + return rc; + } +#endif +#ifdef MOCK_HAVE_ED25519 + case WC_PK_TYPE_ED25519_KEYGEN: { + ed25519_key* key = info->pk.ed25519kg.key; + byte pub[ED25519_PUB_KEY_SIZE]; + word32 pub_len = sizeof(pub); + MockSlot* s; + int rc; + + if (key->idLen == 0) + return CRYPTOCB_UNAVAILABLE; + s = mock_new(key->id, key->idLen, MOCK_ED25519); + if (s == NULL) + return BAD_STATE_E; + rc = wc_ed25519_init_ex(&s->ed25519, NULL, INVALID_DEVID); + if (rc == 0) + rc = wc_ed25519_make_key(info->pk.ed25519kg.rng, + info->pk.ed25519kg.size, &s->ed25519); + if (rc == 0) + rc = wc_ed25519_export_public(&s->ed25519, pub, &pub_len); + if (rc == 0) + rc = wc_ed25519_import_public(pub, pub_len, key); + if (rc == 0) + mock_keygens++; + return rc; + } + case WC_PK_TYPE_ED25519_SIGN: { + ed25519_key* key = info->pk.ed25519sign.key; + MockSlot* s = mock_find(key->id, key->idLen); + int rc; + + mock_sign_requests++; + if (s == NULL || s->type != MOCK_ED25519) + return CRYPTOCB_UNAVAILABLE; + rc = wc_ed25519_sign_msg_ex(info->pk.ed25519sign.in, + info->pk.ed25519sign.inLen, + info->pk.ed25519sign.out, + info->pk.ed25519sign.outLen, &s->ed25519, + info->pk.ed25519sign.type, + info->pk.ed25519sign.context, + info->pk.ed25519sign.contextLen); + if (rc == 0) + mock_private_ops++; + return rc; + } +#endif +#ifdef MOCK_HAVE_ED448 + case WC_PK_TYPE_ED448: { + ed448_key* key = info->pk.ed448sign.key; + MockSlot* s = mock_find(key->id, key->idLen); + int rc; + + mock_sign_requests++; + if (s == NULL || s->type != MOCK_ED448) + return CRYPTOCB_UNAVAILABLE; + rc = wc_ed448_sign_msg_ex(info->pk.ed448sign.in, + info->pk.ed448sign.inLen, + info->pk.ed448sign.out, + info->pk.ed448sign.outLen, &s->ed448, + info->pk.ed448sign.type, + info->pk.ed448sign.context, + info->pk.ed448sign.contextLen); + if (rc == 0) + mock_private_ops++; + return rc; + } +#endif + default: + return CRYPTOCB_UNAVAILABLE; + } +} + +/* An accelerator that counts what it is offered and leaves it to software. */ +static int accel_calls; +static int accel_signs; + +static int accel_cb(int devId, wc_CryptoInfo* info, void* ctx) +{ + (void)devId; + (void)ctx; + + accel_calls++; + if (info->algo_type == WC_ALGO_TYPE_PK && + info->pk.type == WC_PK_TYPE_ECDSA_SIGN) + accel_signs++; +#ifndef NO_RSA + if (info->algo_type == WC_ALGO_TYPE_PK && + info->pk.type == WC_PK_TYPE_RSA && + (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT || + info->pk.rsa.type == RSA_PRIVATE_DECRYPT)) + accel_signs++; +#endif + return CRYPTOCB_UNAVAILABLE; +} + +#ifdef MOCK_HAVE_ED448 +/* Provisions the store's key out of band, since not every wolfSSL with Ed448 + * key ids passes Ed448 keygen to a CryptoCb. */ +static int mock_provision_ed448(const byte* id, int id_len, byte* cert, + int* cert_len) +{ + MockSlot* s = mock_new(id, id_len, MOCK_ED448); + Cert c; + WC_RNG rng; + int n; + + if (s == NULL || wc_InitRng(&rng) != 0) + return -1; + n = wc_ed448_init_ex(&s->ed448, NULL, INVALID_DEVID); + if (n == 0) + n = wc_ed448_make_key(&rng, ED448_KEY_SIZE, &s->ed448); + if (n == 0) + n = wc_InitCert(&c); + if (n == 0) { + strncpy(c.subject.commonName, "ed448-provisioned", CTC_NAME_SIZE - 1); + c.sigType = CTC_ED448; + n = wc_MakeCert_ex(&c, cert, (word32)*cert_len, ED448_TYPE, &s->ed448, + &rng); + } + if (n > 0) + n = wc_SignCert_ex(c.bodySz, c.sigType, cert, (word32)*cert_len, + ED448_TYPE, &s->ed448, &rng); + wc_FreeRng(&rng); + if (n <= 0) + return -1; + *cert_len = n; + return 0; +} +#endif + +static void mock_reset(void) +{ + for (int i = 0; i < MOCK_SLOTS; i++) { +#ifdef WOLFCERT_HAVE_ECC + if (mock_slots[i].id_len > 0 && mock_slots[i].type == MOCK_ECC) + wc_ecc_free(&mock_slots[i].ecc); +#endif +#ifdef WOLFCERT_HAVE_RSA + if (mock_slots[i].id_len > 0 && mock_slots[i].type == MOCK_RSA) + wc_FreeRsaKey(&mock_slots[i].rsa); +#endif +#ifdef WOLFCERT_HAVE_MLDSA + if (mock_slots[i].id_len > 0 && mock_slots[i].type == MOCK_MLDSA) + wc_MlDsaKey_Free(&mock_slots[i].mldsa); +#endif +#ifdef MOCK_HAVE_ED25519 + if (mock_slots[i].id_len > 0 && mock_slots[i].type == MOCK_ED25519) + wc_ed25519_free(&mock_slots[i].ed25519); +#endif +#ifdef MOCK_HAVE_ED448 + if (mock_slots[i].id_len > 0 && mock_slots[i].type == MOCK_ED448) + wc_ed448_free(&mock_slots[i].ed448); +#endif + } + memset(mock_slots, 0, sizeof(mock_slots)); +} + +static void* server_thread(void* arg) +{ + wolfcert_server_run((WolfCertServer*)arg); + return NULL; +} + +static int test_cfg_errors(void) +{ + static const uint8_t id[] = "dev-key"; + uint8_t long_id[WOLFCERT_KEY_ID_MAX_LEN + 1] = { 0 }; + WolfCertKeyCfg cfg = { .type = TEST_ENROLL_KEY_TYPE, + .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID, + .key_id = id, .key_id_len = sizeof(id) - 1 }; + WolfCertKey* k = NULL; + + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_BAD_ARG); + + cfg.dev_id = MOCK_DEVID; + cfg.key_id = long_id; + cfg.key_id_len = sizeof(long_id); + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_BAD_ARG); + + cfg.key_id = NULL; + cfg.key_id_len = 4; + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_BAD_ARG); + +#if defined(WOLFCERT_HAVE_ED25519) && !defined(MOCK_HAVE_ED25519) + cfg.type = WOLFCERT_KEY_ED25519; + cfg.key_id = id; + cfg.key_id_len = sizeof(id) - 1; + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_UNSUPPORTED); +#endif + + REQUIRE(k == NULL); + return 0; +} + +/* Enroll a store-resident key over a bootstrap mTLS identity, reload it by id + * from the issued certificate, then use it as the mTLS identity itself. */ +static int run_key_type(const char* url, WolfCertKeyType type, int param, + const uint8_t* tls_cert, size_t tls_cert_len, + const uint8_t* boot_cert, size_t boot_cert_len, + const uint8_t* boot_key, size_t boot_key_len) +{ + static const uint8_t id[] = "wolfcert/device-key"; + const WolfCertCertMeta meta = { .subject_dn = "CN=devid-device,O=wolfSSL" }; + WolfCertKeyCfg kcfg = { .type = type, .param = param, + .dev_id = MOCK_DEVID, + .key_id = id, .key_id_len = sizeof(id) - 1 }; + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + .client_cert = boot_cert, + .client_cert_len = boot_cert_len, + .client_key = boot_key, + .client_key_len = boot_key_len, + }; + WolfCertKey* key = NULL; + WolfCertKey* reloaded = NULL; + WolfCertBuffer out = { 0 }; + WolfCertBuffer csr = { 0 }; + WolfCertEstResult issued = { 0 }; + WolfCertBuffer renewed = { 0 }; + WolfCertEstResult second = { 0 }; + const uint8_t* got_id = NULL; + size_t got_len = 0; + int ops; + int rc; + + mock_reset(); + mock_keygens = 0; + mock_private_ops = 0; + +#ifdef MOCK_HAVE_ED448 + if (type == WOLFCERT_KEY_ED448) { + static byte prov[1024]; + int prov_len = sizeof(prov); + + REQUIRE(wolfcert_key_generate(&kcfg, &key) == + WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(mock_provision_ed448(id, sizeof(id) - 1, prov, &prov_len) == 0); + REQUIRE(wolfcert_key_from_id(&kcfg, prov, (size_t)prov_len, &key) == + WOLFCERT_OK); + mock_keygens++; + } + else +#endif + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(mock_keygens == 1); + REQUIRE(wolfcert_key_id(key, &got_id, &got_len) == WOLFCERT_OK); + REQUIRE(got_len == sizeof(id) - 1 && memcmp(got_id, id, got_len) == 0); + REQUIRE(wolfcert_key_to_pem(key, &out) == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(wolfcert_key_to_der(key, &out) == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(out.data == NULL); + + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(mock_private_ops == 1); +#ifdef WOLFCERT_HAVE_SCEP + if (type == WOLFCERT_KEY_RSA) { + static const uint8_t dummy[] = { 0x30, 0x00 }; + static const uint8_t txid[] = { '1' }; + const WolfCertServerCfg scep = { + .protocol = WOLFCERT_PROTO_SCEP, + .server_url = "http://127.0.0.1:9/scep", + }; + WolfCertScepResult res; + int before = mock_private_ops; + int src; + + for (int call = 0; call < 4; call++) { + if (call == 0) + src = wolfcert_scep_pkcs_req(&scep, NULL, dummy, + sizeof(dummy), dummy, sizeof(dummy), key, csr.data, + csr.len, &res); + else if (call == 1) + src = wolfcert_scep_renewal_req(&scep, NULL, dummy, + sizeof(dummy), dummy, sizeof(dummy), dummy, + sizeof(dummy), key, csr.data, csr.len, &res); + else if (call == 2) + src = wolfcert_scep_get_cert_initial(&scep, NULL, dummy, + sizeof(dummy), dummy, sizeof(dummy), dummy, + sizeof(dummy), key, csr.data, csr.len, txid, + sizeof(txid), &res); + else + src = wolfcert_scep_get_cert(&scep, NULL, dummy, + sizeof(dummy), dummy, sizeof(dummy), dummy, + sizeof(dummy), key, dummy, sizeof(dummy), &res); + if (src != WOLFCERT_ERR_UNSUPPORTED) + fprintf(stderr, "SCEP call %d rc=%d\n", call, src); + REQUIRE(src == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(strstr(wolfcert_last_error_message(), "key_id") != NULL); + REQUIRE(mock_private_ops == before); + wolfcert_scep_result_free(&res); + } + + /* The session calls too, over a listener that never answers. */ + const WolfCertScepCaps caps = { 0 }; + WolfCertScepSession* ss = NULL; + uint16_t hole_port = 0; + int hole = black_hole_listener(&hole_port); + char hole_url[64]; + + REQUIRE(hole >= 0); + snprintf(hole_url, sizeof(hole_url), "http://127.0.0.1:%u/scep", + hole_port); + WolfCertServerCfg scep_sess = scep; + scep_sess.server_url = hole_url; + REQUIRE(wolfcert_scep_session_open(&scep_sess, &ss) == WOLFCERT_OK); + for (int call = 0; call < 3; call++) { + if (call == 0) + src = wolfcert_scep_session_pkcs_req(ss, &caps, dummy, + sizeof(dummy), dummy, sizeof(dummy), key, csr.data, + csr.len, &res); + else if (call == 1) + src = wolfcert_scep_session_renewal_req(ss, &caps, dummy, + sizeof(dummy), dummy, sizeof(dummy), dummy, + sizeof(dummy), key, csr.data, csr.len, &res); + else + src = wolfcert_scep_session_get_cert_initial(ss, &caps, + dummy, sizeof(dummy), dummy, sizeof(dummy), dummy, + sizeof(dummy), key, csr.data, csr.len, txid, + sizeof(txid), &res); + if (src != WOLFCERT_ERR_UNSUPPORTED) + fprintf(stderr, "SCEP session call %d rc=%d\n", call, src); + REQUIRE(src == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(strstr(wolfcert_last_error_message(), "key_id") != NULL); + REQUIRE(mock_private_ops == before); + wolfcert_scep_result_free(&res); + } + wolfcert_scep_session_close(ss); + close(hole); + } +#endif + rc = wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &issued); + wolfcert_buffer_free(&csr); + if (rc != WOLFCERT_OK) + fprintf(stderr, "enroll rc=%d (%s)\n", rc, + wolfcert_last_error_message()); + REQUIRE(rc == WOLFCERT_OK); + + /* Reload by id from the issued certificate as PEM, ahead of another + * certificate, and as DER padded like a fixed-size flash slot. */ + REQUIRE(wolfcert_key_from_id(&kcfg, issued.cert_pem.data, + issued.cert_pem.len, &reloaded) == + WOLFCERT_OK); + REQUIRE(wolfcert_key_type(reloaded) == type); + REQUIRE(wolfcert_key_to_pem(reloaded, &out) == WOLFCERT_ERR_UNSUPPORTED); + { + static uint8_t buf[16384]; + int der_len = wc_CertPemToDer(issued.cert_pem.data, + (int)issued.cert_pem.len, buf, + sizeof(buf), CERT_TYPE); + WolfCertKey* other = NULL; + + REQUIRE(der_len > 0); + memset(buf + der_len, 0xff, sizeof(buf) - (size_t)der_len); + REQUIRE(wolfcert_key_from_id(&kcfg, buf, sizeof(buf), &other) == + WOLFCERT_OK); + REQUIRE(wolfcert_key_type(other) == type); + wolfcert_key_free(other); + other = NULL; + + REQUIRE(issued.cert_pem.len + tls_cert_len <= sizeof(buf)); + memcpy(buf, issued.cert_pem.data, issued.cert_pem.len); + memcpy(buf + issued.cert_pem.len, tls_cert, tls_cert_len); + REQUIRE(wolfcert_key_from_id(&kcfg, buf, + issued.cert_pem.len + tls_cert_len, + &other) == WOLFCERT_OK); + REQUIRE(wolfcert_key_type(other) == type); + wolfcert_key_free(other); + other = NULL; + + WolfCertKeyCfg wrong = kcfg; + if (type == WOLFCERT_KEY_ECC || type == WOLFCERT_KEY_RSA) { + wrong.param = type == WOLFCERT_KEY_RSA ? 3072 : 384; + REQUIRE(wolfcert_key_from_id(&wrong, issued.cert_pem.data, + issued.cert_pem.len, &other) == + WOLFCERT_ERR_BAD_ARG); + } +#if defined(WOLFCERT_HAVE_MLDSA) && !defined(WOLFSSL_NO_ML_DSA_65) + if (type == WOLFCERT_KEY_MLDSA44) { + wrong.type = WOLFCERT_KEY_MLDSA65; + REQUIRE(wolfcert_key_from_id(&wrong, issued.cert_pem.data, + issued.cert_pem.len, &other) != + WOLFCERT_OK); + } +#endif + REQUIRE(other == NULL); + } + +#ifdef KEEP_PEER_CERT + /* /simplereenroll authenticates with the store key: one signature for the + * CSR, at least one more for the TLS handshake. */ + WolfCertClient* client = NULL; + WolfCertKey* unused = NULL; + const WolfCertCertMeta renew_meta = { 0 }; + + REQUIRE(wolfcert_client_new(&client) == WOLFCERT_OK); + ops = mock_private_ops; + rc = wolfcert_client_reenroll(client, &cli, issued.cert_pem.data, + issued.cert_pem.len, reloaded, NULL, + &renew_meta, &unused, &renewed); + wolfcert_client_free(client); + REQUIRE(unused == NULL); + if (rc != WOLFCERT_OK) + fprintf(stderr, "reenroll rc=%d (%s)\n", rc, + wolfcert_last_error_message()); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(mock_private_ops >= ops + 2); +#endif + + /* The store key as the mTLS identity, one-shot and in a session. */ + cli.client_cert = issued.cert_pem.data; + cli.client_cert_len = issued.cert_pem.len; + cli.client_key = NULL; + cli.client_key_len = 0; + cli.client_key_obj = reloaded; + REQUIRE(wolfcert_csr_build(reloaded, &meta, &csr) == WOLFCERT_OK); + ops = mock_private_ops; + rc = wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &second); + wolfcert_buffer_free(&csr); + if (rc != WOLFCERT_OK) + fprintf(stderr, "id enroll rc=%d (%s)\n", rc, + wolfcert_last_error_message()); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(mock_private_ops > ops); + + WolfCertEstSession* sess = NULL; + WolfCertEstResult third = { 0 }; + REQUIRE(wolfcert_csr_build(reloaded, &meta, &csr) == WOLFCERT_OK); + ops = mock_private_ops; + REQUIRE(wolfcert_est_session_open(&cli, &sess) == WOLFCERT_OK); + rc = wolfcert_est_session_simple_enroll(sess, csr.data, csr.len, &third); + wolfcert_est_session_close(sess); + wolfcert_buffer_free(&csr); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(mock_private_ops > ops); + wolfcert_est_result_free(&third); + + wolfcert_est_result_free(&second); + wolfcert_buffer_free(&renewed); + wolfcert_est_result_free(&issued); + wolfcert_key_free(reloaded); + wolfcert_key_free(key); + mock_reset(); + return 0; +} + +/* A software key handle is an mTLS identity as PEM bytes are; it cannot come + * with client_key. */ +static int test_client_key_obj(const char* url, + const uint8_t* tls_cert, size_t tls_cert_len, + const uint8_t* boot_cert, size_t boot_cert_len, + const uint8_t* boot_key, size_t boot_key_len) +{ + const WolfCertCertMeta meta = { .subject_dn = "CN=devid-accel,O=wolfSSL" }; + WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, + .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID }; + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + .client_cert = boot_cert, + .client_cert_len = boot_cert_len, + .client_key = boot_key, + .client_key_len = boot_key_len, + }; + WolfCertKey* key = NULL; + WolfCertBuffer csr = { 0 }; + WolfCertEstResult cert = { 0 }; + WolfCertEstResult again = { 0 }; + int requests; + + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + + cli.client_key_obj = key; + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &again) == + WOLFCERT_ERR_BAD_ARG); + cli.client_cert = cert.cert_pem.data; + cli.client_cert_len = cert.cert_pem.len; + cli.client_key = NULL; + cli.client_key_len = 0; + requests = mock_sign_requests; + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &again) == + WOLFCERT_OK); + REQUIRE(mock_sign_requests == requests); + wolfcert_est_result_free(&again); + wolfcert_est_result_free(&cert); + wolfcert_buffer_free(&csr); + wolfcert_key_free(key); + key = NULL; + cli.client_cert = boot_cert; + cli.client_cert_len = boot_cert_len; + cli.client_key = boot_key; + cli.client_key_len = boot_key_len; + cli.client_key_obj = NULL; + +#ifdef KEEP_PEER_CERT + /* A dev_id key without a key_id signs its CSR on the device and the + * handshake on the default devId. */ + const WolfCertCertMeta renew_meta = { 0 }; + WolfCertClient* client = NULL; + WolfCertKey* unused = NULL; + WolfCertBuffer renewed = { 0 }; + + kcfg.dev_id = MOCK_DEVID; + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + REQUIRE(wolfcert_client_new(&client) == WOLFCERT_OK); + requests = mock_sign_requests; + int rc = wolfcert_client_reenroll(client, &cli, cert.cert_pem.data, + cert.cert_pem.len, key, NULL, + &renew_meta, &unused, &renewed); + wolfcert_client_free(client); + if (rc != WOLFCERT_OK) + fprintf(stderr, "dev reenroll rc=%d (%s)\n", rc, + wolfcert_last_error_message()); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(mock_sign_requests == requests + 1); + wolfcert_buffer_free(&renewed); + wolfcert_est_result_free(&cert); + wolfcert_buffer_free(&csr); + wolfcert_key_free(key); +#endif + return 0; +} + +/* The default devId gets the client's TLS crypto, including the signature of a + * PEM key or a software key handle, while a key_id key signs in its device. */ +static int test_default_dev_id(const char* url, + const uint8_t* tls_cert, size_t tls_cert_len, + const uint8_t* boot_cert, size_t boot_cert_len, + const uint8_t* boot_key, size_t boot_key_len) +{ + static const uint8_t id[] = "wolfcert/accel-key"; + static const uint8_t dflt_id[] = "wolfcert/default-key"; + const WolfCertCertMeta meta = { + .subject_dn = "CN=devid-default,O=wolfSSL" + }; + WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, + .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID }; + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + .client_cert = boot_cert, + .client_cert_len = boot_cert_len, + .client_key = boot_key, + .client_key_len = boot_key_len, + }; + WolfCertKey* key = NULL; + WolfCertBuffer csr = { 0 }; + WolfCertEstResult cert = { 0 }; + WolfCertEstResult issued = { 0 }; + WolfCertEstResult soft = { 0 }; + WolfCertKey* soft_key = NULL; + int ops; + +#ifndef WC_USE_DEVID + REQUIRE(wolfcert_default_dev_id() == INVALID_DEVID); +#endif + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); + accel_calls = 0; + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + wolfcert_est_result_free(&cert); + REQUIRE(accel_calls == 0); + + REQUIRE(wolfcert_set_default_dev_id(ACCEL_DEVID) == WOLFCERT_OK); + REQUIRE(wolfcert_default_dev_id() == ACCEL_DEVID); + accel_signs = 0; + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + wolfcert_est_result_free(&cert); + REQUIRE(accel_calls > 0); + REQUIRE(accel_signs > 0); + wolfcert_buffer_free(&csr); + wolfcert_key_free(key); + key = NULL; + + /* A key made with INVALID_DEVID stays in software; the caller names the + * default device to use it. */ + accel_signs = 0; + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_key_dev_id(key) == INVALID_DEVID); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(accel_signs == 0); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &soft) == + WOLFCERT_OK); + wolfcert_buffer_free(&csr); + soft_key = key; + accel_signs = 0; + kcfg.dev_id = wolfcert_default_dev_id(); + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_key_dev_id(key) == ACCEL_DEVID); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(accel_signs == 1); + wolfcert_buffer_free(&csr); + wolfcert_key_free(key); + key = NULL; + + /* A key_id needs a device, and a dev_id a registered one. */ + kcfg.dev_id = INVALID_DEVID; + kcfg.key_id = dflt_id; + kcfg.key_id_len = sizeof(dflt_id) - 1; + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(key == NULL); +#ifndef WOLF_CRYPTO_CB_FIND + kcfg.dev_id = UNREGISTERED_DEVID; + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(key == NULL); + kcfg.key_id = NULL; + kcfg.key_id_len = 0; + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(key == NULL); +#endif + + kcfg.dev_id = MOCK_DEVID; + kcfg.key_id = id; + kcfg.key_id_len = sizeof(id) - 1; + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &issued) == + WOLFCERT_OK); + + cli.client_cert = issued.cert_pem.data; + cli.client_cert_len = issued.cert_pem.len; + cli.client_key = NULL; + cli.client_key_len = 0; + cli.client_key_obj = key; + accel_calls = 0; + accel_signs = 0; + ops = mock_private_ops; + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + REQUIRE(accel_calls > 0); + REQUIRE(accel_signs == 0); + REQUIRE(mock_private_ops > ops); + wolfcert_est_result_free(&cert); + + /* A software key handle signs its handshake on the default device. */ + cli.client_cert = soft.cert_pem.data; + cli.client_cert_len = soft.cert_pem.len; + cli.client_key_obj = soft_key; + accel_signs = 0; + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + REQUIRE(accel_signs > 0); + + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); + wolfcert_est_result_free(&cert); + wolfcert_est_result_free(&soft); + wolfcert_est_result_free(&issued); + wolfcert_buffer_free(&csr); + wolfcert_key_free(soft_key); + wolfcert_key_free(key); + mock_reset(); + return 0; +} + +/* A failed enroll or rekey still hands back a key made under a key_id. */ +static int test_failure_keeps_key(const char* url, const uint8_t* tls_cert, + size_t tls_cert_len) +{ + static const uint8_t id[] = "wolfcert/orphan-key"; + static const uint8_t junk[] = { 0x30, 0x03, 0x02, 0x01, 0x00 }; + const WolfCertCertMeta meta = { .subject_dn = "CN=devid-orphan" }; + const WolfCertCertMeta renew = { 0 }; + WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, + .param = TEST_ENROLL_KEY_PARAM, + .dev_id = MOCK_DEVID, + .key_id = id, .key_id_len = sizeof(id) - 1 }; + WolfCertKeyCfg scfg = { .type = TEST_ENROLL_KEY_TYPE, + .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID }; + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + }; + WolfCertKey* key = NULL; + WolfCertKey* cur = NULL; + WolfCertBuffer cert = { 0 }; + const uint8_t* got_id = NULL; + size_t got_len = 0; + + mock_reset(); + REQUIRE(wolfcert_client_enroll(NULL, &cli, &kcfg, &meta, &key, &cert) != + WOLFCERT_OK); + REQUIRE(key != NULL); + REQUIRE(wolfcert_key_id(key, &got_id, &got_len) == WOLFCERT_OK); + REQUIRE(got_len == sizeof(id) - 1 && memcmp(got_id, id, got_len) == 0); + wolfcert_key_free(key); + key = NULL; + + mock_reset(); + REQUIRE(wolfcert_key_generate(&scfg, &cur) == WOLFCERT_OK); + REQUIRE(wolfcert_client_reenroll(NULL, &cli, junk, sizeof(junk), cur, + &kcfg, &renew, &key, &cert) == + WOLFCERT_ERR_PARSE); + REQUIRE(key != NULL); + wolfcert_key_free(key); + key = NULL; + + REQUIRE(wolfcert_client_enroll(NULL, &cli, &scfg, &meta, &key, &cert) != + WOLFCERT_OK); + REQUIRE(key == NULL); + + /* An early failure also leaves out_key defined. */ + key = cur; + scfg.param = 123; + REQUIRE(wolfcert_client_enroll(NULL, &cli, &scfg, &meta, &key, &cert) != + WOLFCERT_OK); + REQUIRE(key == NULL); + key = cur; + REQUIRE(wolfcert_client_reenroll(NULL, &cli, junk, sizeof(junk), cur, + NULL, &meta, &key, &cert) == + WOLFCERT_ERR_BAD_ARG); + REQUIRE(key == NULL); + scfg.param = TEST_ENROLL_KEY_PARAM; + REQUIRE(wolfcert_client_reenroll(NULL, &cli, junk, sizeof(junk), cur, + &scfg, &renew, &key, &cert) == + WOLFCERT_ERR_PARSE); + REQUIRE(key == NULL); + REQUIRE(cert.data == NULL); + + /* A protocol the client calls cannot enroll creates no key. */ + cli.protocol = WOLFCERT_PROTO_SCEP; + int gens = mock_keygens; + REQUIRE(wolfcert_client_enroll(NULL, &cli, &kcfg, &meta, &key, &cert) == + WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(wolfcert_client_reenroll(NULL, &cli, junk, sizeof(junk), cur, + &kcfg, &renew, &key, &cert) == + WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(key == NULL); + REQUIRE(mock_keygens == gens); + wolfcert_key_free(cur); + mock_reset(); + return 0; +} + +int main(void) +{ + uint8_t* tls_cert = NULL; size_t tls_cert_len = 0; + uint8_t* tls_key = NULL; size_t tls_key_len = 0; + uint8_t* boot_cert = NULL; size_t boot_cert_len = 0; + uint8_t* boot_key = NULL; size_t boot_key_len = 0; + WolfCertServer* srv = NULL; + WolfCertBuffer ca_der = { 0 }; + WolfCertBuffer ca_key = { 0 }; + uint8_t* bundle = NULL; + size_t bundle_cap; + pthread_t tid; + char url[128]; + int pem_len; + + REQUIRE(wolfcert_init(NULL) == WOLFCERT_OK); + REQUIRE(wc_CryptoCb_RegisterDevice(MOCK_DEVID, mock_cb, NULL) == 0); + REQUIRE(wc_CryptoCb_RegisterDevice(ACCEL_DEVID, accel_cb, NULL) == 0); + /* A WC_USE_DEVID build starts on a device; these checks expect none. */ + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); + REQUIRE(test_cfg_errors() == 0); + + REQUIRE(mint_self_id("127.0.0.1", 0, &tls_cert, &tls_cert_len, + &tls_key, &tls_key_len) == 0); + REQUIRE(mint_self_id("factory-bootstrap", 1, &boot_cert, &boot_cert_len, + &boot_key, &boot_key_len) == 0); + + WolfCertServerCfgSrv cfg = { + .protocol = WOLFCERT_PROTO_EST, + .bind_host = "127.0.0.1", + .bind_port = 0, + .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, + .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, + .tls_client_ca_pem = boot_cert, .tls_client_ca_pem_len = boot_cert_len, + }; + + /* Mint the CA first so the server can also trust the certs it issues. */ + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &ca_der, + &ca_key) == WOLFCERT_OK); + wolfcert_server_free(srv); + srv = NULL; + cfg.ca_cert = ca_der.data; + cfg.ca_cert_len = ca_der.len; + cfg.ca_key = ca_key.data; + cfg.ca_key_len = ca_key.len; + + bundle_cap = boot_cert_len + ca_der.len * 2 + 256; + bundle = (uint8_t*)malloc(bundle_cap); + REQUIRE(bundle != NULL); + memcpy(bundle, boot_cert, boot_cert_len); + pem_len = wc_DerToPem(ca_der.data, (word32)ca_der.len, + bundle + boot_cert_len, + (word32)(bundle_cap - boot_cert_len), CERT_TYPE); + REQUIRE(pem_len > 0); + cfg.tls_client_ca_pem = bundle; + cfg.tls_client_ca_pem_len = boot_cert_len + (size_t)pem_len; + + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + +#ifdef WOLFCERT_HAVE_ECC + REQUIRE(run_key_type(url, WOLFCERT_KEY_ECC, 256, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif +#ifdef WOLFCERT_HAVE_RSA + REQUIRE(run_key_type(url, WOLFCERT_KEY_RSA, 2048, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif +#ifdef WOLFCERT_HAVE_MLDSA +#ifndef WOLFSSL_NO_ML_DSA_44 + REQUIRE(run_key_type(url, WOLFCERT_KEY_MLDSA44, 0, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + REQUIRE(run_key_type(url, WOLFCERT_KEY_MLDSA65, 0, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + REQUIRE(run_key_type(url, WOLFCERT_KEY_MLDSA87, 0, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif +#endif +#ifdef MOCK_HAVE_ED25519 + REQUIRE(run_key_type(url, WOLFCERT_KEY_ED25519, 0, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif +#ifdef MOCK_HAVE_ED448 + REQUIRE(run_key_type(url, WOLFCERT_KEY_ED448, 0, tls_cert, tls_cert_len, + boot_cert, boot_cert_len, boot_key, + boot_key_len) == 0); +#endif + REQUIRE(test_client_key_obj(url, tls_cert, tls_cert_len, boot_cert, + boot_cert_len, boot_key, boot_key_len) == 0); + REQUIRE(test_default_dev_id(url, tls_cert, tls_cert_len, boot_cert, + boot_cert_len, boot_key, boot_key_len) == 0); + REQUIRE(test_failure_keeps_key(url, tls_cert, tls_cert_len) == 0); + + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + wolfcert_buffer_free(&ca_der); + wolfcert_buffer_free_secure(&ca_key); + free(bundle); + free(tls_cert); + free(tls_key); + free(boot_cert); + free(boot_key); + REQUIRE(wolfcert_set_default_dev_id(ACCEL_DEVID) == WOLFCERT_OK); + wc_CryptoCb_UnRegisterDevice(ACCEL_DEVID); + wc_CryptoCb_UnRegisterDevice(MOCK_DEVID); + wolfcert_cleanup(); +#ifdef WC_USE_DEVID + REQUIRE(wolfcert_default_dev_id() == WC_USE_DEVID); +#else + REQUIRE(wolfcert_default_dev_id() == INVALID_DEVID); +#endif + printf("est_devid_roundtrip: OK\n"); + return 0; +} +#endif diff --git a/tests/integration/test_est_mldsa_roundtrip.c b/tests/integration/test_est_mldsa_roundtrip.c index 6ded64b6..87df39bf 100644 --- a/tests/integration/test_est_mldsa_roundtrip.c +++ b/tests/integration/test_est_mldsa_roundtrip.c @@ -63,7 +63,7 @@ static void* server_thread(void* arg) static int enroll_mldsa(const WolfCertServerCfg* client_cfg, WolfCertKeyType kt, const char* label, const WolfCertBuffer* ca_pem) { - WolfCertKeyCfg kcfg = { .type = kt, .dev_id = WOLFCERT_DEVID_SOFTWARE }; + WolfCertKeyCfg kcfg = { .type = kt, .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); @@ -114,7 +114,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .http_basic_user = "alice", .http_basic_pass = "hunter2", .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, @@ -158,7 +158,7 @@ int main(void) wolfcert_buffer_free(&ca_pem); free(tls_cert); free(tls_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); if (rc == 0) diff --git a/tests/integration/test_est_mtls_roundtrip.c b/tests/integration/test_est_mtls_roundtrip.c index 9d12b026..d8fa4d1d 100644 --- a/tests/integration/test_est_mtls_roundtrip.c +++ b/tests/integration/test_est_mtls_roundtrip.c @@ -80,7 +80,7 @@ static int test_reenroll_ignores_cfg_identity(const char* url, WolfCertEstSession* sess = NULL; WolfCertEstResult res = { 0 }; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=factory-bootstrap" }; WolfCertServerCfg cli = { .protocol = WOLFCERT_PROTO_EST, @@ -153,7 +153,7 @@ static int test_reenroll_rejects_identity_change(const char* url, { .subject_dn = "CN=factory-bootstrap", .san_dns = dns, .san_dns_len = 1 }, }; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertServerCfg cli = { .protocol = WOLFCERT_PROTO_EST, .server_url = url, @@ -287,6 +287,40 @@ static int csr_with_critical_san(const WolfCertBuffer* cert_pem, } #endif +/* A software key of each type re-enrolls; its DER reaches TLS untyped. */ +static int reenroll_key_type(const WolfCertServerCfg* cli, WolfCertKeyType type, + int param) +{ + const WolfCertCertMeta meta = { .subject_dn = "CN=reenroll-type,O=wolfSSL" }; + WolfCertKeyCfg kcfg = { .type = type, .param = param, + .dev_id = INVALID_DEVID }; + WolfCertKey* key = NULL; + WolfCertBuffer csr = { 0 }; + WolfCertEstResult cert = { 0 }; + WolfCertEstResult renewed = { 0 }; + int rc; + + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(cli, csr.data, csr.len, &cert) == + WOLFCERT_OK); + REQUIRE(cert.status == WOLFCERT_EST_STATUS_SUCCESS); + rc = wolfcert_est_simple_reenroll(cli, cert.cert_pem.data, + cert.cert_pem.len, key, csr.data, + csr.len, &renewed); + if (rc != WOLFCERT_OK) + fprintf(stderr, "key type %d reenroll rc=%d (%s)\n", (int)type, rc, + wolfcert_last_error_message()); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(renewed.status == WOLFCERT_EST_STATUS_SUCCESS); + + wolfcert_est_result_free(&renewed); + wolfcert_est_result_free(&cert); + wolfcert_buffer_free(&csr); + wolfcert_key_free(key); + return 0; +} + /* Reenroll of a multi-RDN, multi-SAN cert the server CA issued succeeds; a * changed dNSName or a critical SAN (ECC builds) gets 400. */ static int test_reenroll_server_issued(const uint8_t* tls_cert, size_t tls_cert_len, @@ -311,7 +345,7 @@ static int test_reenroll_server_issued(const uint8_t* tls_cert, size_t tls_cert_ .san_email = email, .san_email_len = 1, }; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", @@ -319,10 +353,10 @@ static int test_reenroll_server_issued(const uint8_t* tls_cert, size_t tls_cert_ .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .tls_client_ca_pem = cli_cert, .tls_client_ca_pem_len = cli_cert_len, + TEST_CA_CFG, }; - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); WolfCertServer* srv = NULL; - WolfCertBuffer ca_der = { 0 }; + const TestCa* ca = test_ca(); WolfCertBuffer csr = { 0 }; WolfCertEstResult issued = { 0 }; WolfCertEstResult renewed = { 0 }; @@ -330,10 +364,9 @@ static int test_reenroll_server_issued(const uint8_t* tls_cert, size_t tls_cert_ WolfCertKey* k1 = NULL; WolfCertKey* k2 = NULL; uint8_t* bundle = NULL; - size_t bundle_cap; + size_t bundle_len; pthread_t tid; char url[128]; - int pem_len; int rc; #ifdef HAVE_ECC uint8_t crit_csr[4096]; @@ -341,23 +374,13 @@ static int test_reenroll_server_issued(const uint8_t* tls_cert, size_t tls_cert_ int crit_len; #endif - /* The first start mints the CA into the store; the second adopts it. */ - REQUIRE(store != NULL); - cfg.ca_store = store; - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - srv = NULL; - REQUIRE(store->read(store->ctx, "ca.cert.der", &ca_der) == WOLFCERT_OK); - - bundle_cap = cli_cert_len + ca_der.len * 2 + 256; - bundle = (uint8_t*)malloc(bundle_cap); + bundle_len = cli_cert_len + ca->cert_len; + bundle = (uint8_t*)malloc(bundle_len); REQUIRE(bundle != NULL); memcpy(bundle, cli_cert, cli_cert_len); - pem_len = wc_DerToPem(ca_der.data, (word32)ca_der.len, bundle + cli_cert_len, - (word32)(bundle_cap - cli_cert_len), CERT_TYPE); - REQUIRE(pem_len > 0); + memcpy(bundle + cli_cert_len, ca->cert, ca->cert_len); cfg.tls_client_ca_pem = bundle; - cfg.tls_client_ca_pem_len = cli_cert_len + (size_t)pem_len; + cfg.tls_client_ca_pem_len = bundle_len; REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); @@ -412,14 +435,40 @@ static int test_reenroll_server_issued(const uint8_t* tls_cert, size_t tls_cert_ REQUIRE(refused.cert_pem.data == NULL); #endif + static const struct { WolfCertKeyType type; int param; } types[] = { +#ifdef WOLFCERT_HAVE_RSA + { WOLFCERT_KEY_RSA, 2048 }, +#endif +#ifdef WOLFCERT_HAVE_ECC + { WOLFCERT_KEY_ECC, 384 }, +#endif +#ifdef WOLFCERT_HAVE_ED25519 + { WOLFCERT_KEY_ED25519, 0 }, +#endif +#ifdef WOLFCERT_HAVE_ED448 + { WOLFCERT_KEY_ED448, 0 }, +#endif +#ifdef WOLFCERT_HAVE_MLDSA +#ifndef WOLFSSL_NO_ML_DSA_44 + { WOLFCERT_KEY_MLDSA44, 0 }, +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + { WOLFCERT_KEY_MLDSA65, 0 }, +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + { WOLFCERT_KEY_MLDSA87, 0 }, +#endif +#endif + }; + for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) + REQUIRE(reenroll_key_type(&cli, types[i].type, types[i].param) == 0); + wolfcert_server_stop(srv); pthread_join(tid, NULL); wolfcert_server_free(srv); - wolfcert_store_memory_close(store); wolfcert_est_result_free(&renewed); wolfcert_est_result_free(&issued); wolfcert_buffer_free(&csr); - wolfcert_buffer_free(&ca_der); wolfcert_key_free(k2); wolfcert_key_free(k1); free(bundle); @@ -438,12 +487,12 @@ static int test_reenroll_under_approval(const uint8_t* tls_cert, size_t tls_cert const WolfCertCertMeta same = { .subject_dn = "CN=factory-bootstrap" }; const WolfCertCertMeta none = { 0 }; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .tls_client_ca_pem = cli_cert, .tls_client_ca_pem_len = cli_cert_len, @@ -517,6 +566,416 @@ static int test_reenroll_under_approval(const uint8_t* tls_cert, size_t tls_cert return 0; } +/* tls_client_trust_issued: anonymous enroll still works, the issued cert + * renews over mTLS, and a cert from another CA is refused. */ +static int test_reenroll_trust_issued(const uint8_t* tls_cert, size_t tls_cert_len, + const uint8_t* tls_key, size_t tls_key_len, + const uint8_t* cli_cert, size_t cli_cert_len, + const uint8_t* cli_key, size_t cli_key_len) +{ + WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID }; + WolfCertCertMeta meta = { .subject_dn = "CN=trust-issued" }; + WolfCertServerCfgSrv cfg = { + .protocol = WOLFCERT_PROTO_EST, + .bind_host = "127.0.0.1", + .bind_port = 0, + TEST_CA_CFG, + .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, + .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, + .est_allow_anonymous_enroll = 1, + .tls_client_trust_issued = 1, + }; + WolfCertServer* srv = NULL; + WolfCertKey* k1 = NULL; + WolfCertKey* k2 = NULL; + WolfCertKey* foreign = NULL; + WolfCertBuffer ca_pem = { 0 }; + WolfCertBuffer csr = { 0 }; + WolfCertEstResult issued = { 0 }; + WolfCertEstResult renewed = { 0 }; + WolfCertEstResult refused = { 0 }; + static const char anon_req[] = + "POST /.well-known/est/simplereenroll HTTP/1.1\r\n" + "Host: 127.0.0.1\r\nContent-Type: application/pkcs10\r\n" + "Content-Length: 4\r\nConnection: close\r\n\r\nAAAA"; + TestTlsConn conn; + char resp[1024]; + size_t resp_len = 0; + pthread_t tid; + char url[128]; + int rc; + + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + }; + REQUIRE(wolfcert_est_get_cacerts(&cli, WOLFCERT_ENCODING_PEM, &ca_pem) == WOLFCERT_OK); + + REQUIRE(wolfcert_key_generate(&kcfg, &k1) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(k1, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &issued) == + WOLFCERT_OK); + wolfcert_buffer_free(&csr); + + REQUIRE(wolfcert_key_generate(&kcfg, &k2) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(k2, &meta, &csr) == WOLFCERT_OK); + rc = wolfcert_est_simple_reenroll(&cli, issued.cert_pem.data, issued.cert_pem.len, k1, + csr.data, csr.len, &renewed); + wolfcert_buffer_free(&csr); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(memmem(renewed.cert_pem.data, renewed.cert_pem.len, "BEGIN CERTIFICATE", 17) != NULL); + + REQUIRE(wolfcert_key_from_pem(cli_key, cli_key_len, NULL, &foreign) == + WOLFCERT_OK); + meta.subject_dn = "CN=factory-bootstrap"; + REQUIRE(wolfcert_csr_build(foreign, &meta, &csr) == WOLFCERT_OK); + rc = wolfcert_est_simple_reenroll(&cli, cli_cert, cli_cert_len, foreign, + csr.data, csr.len, &refused); + /* The handshake refuses it, so no HTTP answer comes. */ + REQUIRE(rc != WOLFCERT_OK && rc != WOLFCERT_ERR_HTTP && + rc != WOLFCERT_ERR_AUTH); + REQUIRE(refused.cert_pem.data == NULL); + + /* Without a client certificate there is nothing to renew. */ + REQUIRE(test_tls_connect(&conn, wolfcert_server_port(srv), tls_cert, + tls_cert_len) == 0); + REQUIRE(test_tls_write(&conn, anon_req, sizeof(anon_req) - 1) == 0); + while (resp_len < sizeof(resp) - 1) { + int n = test_tls_read(&conn, resp + resp_len, + sizeof(resp) - 1 - resp_len); + if (n <= 0) + break; + resp_len += (size_t)n; + } + test_tls_close(&conn); + resp[resp_len] = '\0'; + REQUIRE(strncmp(resp, "HTTP/1.1 403", 12) == 0); + + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + srv = NULL; + wolfcert_buffer_free(&csr); + +#ifdef WOLFCERT_HAVE_SCEP + cfg.protocol = WOLFCERT_PROTO_SCEP; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(srv == NULL); + cfg.protocol = WOLFCERT_PROTO_EST; +#endif + + /* With no other authenticator the server only renews, from a kept CA. */ + cfg.est_allow_anonymous_enroll = 0; + cfg.ca_cert = NULL; + cfg.ca_cert_len = 0; + cfg.ca_key = NULL; + cfg.ca_key_len = 0; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(srv == NULL); + cfg.ca_cert = test_ca()->cert; + cfg.ca_cert_len = test_ca()->cert_len; + cfg.ca_key = test_ca()->key; + cfg.ca_key_len = test_ca()->key_len; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + meta.subject_dn = "CN=trust-issued"; + REQUIRE(wolfcert_csr_build(k2, &meta, &csr) == WOLFCERT_OK); + wolfcert_clear_error(); + rc = wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &refused); + REQUIRE(rc == WOLFCERT_ERR_AUTH); + REQUIRE(strstr(wolfcert_last_error_message(), "HTTP 403") != NULL); + REQUIRE(refused.cert_pem.data == NULL); + wolfcert_est_result_free(&issued); + rc = wolfcert_est_simple_reenroll(&cli, renewed.cert_pem.data, renewed.cert_pem.len, k2, + csr.data, csr.len, &issued); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(memmem(issued.cert_pem.data, issued.cert_pem.len, "BEGIN CERTIFICATE", 17) != NULL); + + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + wolfcert_buffer_free(&csr); + wolfcert_est_result_free(&renewed); + wolfcert_est_result_free(&issued); + wolfcert_buffer_free(&ca_pem); + wolfcert_key_free(foreign); + wolfcert_key_free(k2); + wolfcert_key_free(k1); + return 0; +} +/* Without ECC the test server offers no TLS 1.2 suite: it loads no DH. */ +#if !defined(WOLFSSL_NO_TLS12) && defined(HAVE_ECC) +/* A TLS 1.2 session resumed from one authenticated by cert/key carries no + * peer certificate; write req on it and return the response's status line. */ +static int resumed_status(uint16_t port, const uint8_t* ca, size_t ca_len, + const WolfCertBuffer* cert, const WolfCertBuffer* key, + const char* req, char* status, size_t status_sz) +{ + TestTlsConn c; + WOLFSSL_SESSION* sess = NULL; + char resp[512]; + int n; + + REQUIRE(test_tls_setup(&c, port, ca, ca_len) == 0); + REQUIRE(wolfSSL_SetVersion(c.ssl, WOLFSSL_TLSV1_2) == WOLFSSL_SUCCESS); + REQUIRE(wolfSSL_use_certificate_buffer(c.ssl, cert->data, (long)cert->len, + WOLFSSL_FILETYPE_PEM) == + WOLFSSL_SUCCESS); + REQUIRE(wolfSSL_use_PrivateKey_buffer(c.ssl, key->data, (long)key->len, + WOLFSSL_FILETYPE_PEM) == + WOLFSSL_SUCCESS); + REQUIRE(wolfSSL_connect(c.ssl) == WOLFSSL_SUCCESS); + sess = wolfSSL_get1_session(c.ssl); + test_tls_close(&c); + REQUIRE(sess != NULL); + + REQUIRE(test_tls_setup(&c, port, ca, ca_len) == 0); + REQUIRE(wolfSSL_SetVersion(c.ssl, WOLFSSL_TLSV1_2) == WOLFSSL_SUCCESS); + REQUIRE(wolfSSL_set_session(c.ssl, sess) == WOLFSSL_SUCCESS); + REQUIRE(wolfSSL_connect(c.ssl) == WOLFSSL_SUCCESS); + wolfSSL_SESSION_free(sess); + REQUIRE(wolfSSL_session_reused(c.ssl) == 1); + REQUIRE(test_tls_write(&c, req, strlen(req)) == 0); + n = test_tls_read(&c, resp, sizeof(resp) - 1); + test_tls_close(&c); + REQUIRE(n > 0); + resp[n] = '\0'; + snprintf(status, status_sz, "%.*s", (int)strcspn(resp, "\r"), resp); + return 0; +} +#endif + +/* tls_client_trust_issued next to a client CA that is another wolfCert CA, + * with the same subject: a certificate from either CA verifies, and one this + * server issued renews but does not enroll. */ +static int test_trust_issued_with_client_ca(const uint8_t* tls_cert, + size_t tls_cert_len, + const uint8_t* tls_key, + size_t tls_key_len) +{ + WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID }; + WolfCertCertMeta meta = { .subject_dn = "CN=bootstrap" }; + WolfCertServerCfgSrv cfg = { + .protocol = WOLFCERT_PROTO_EST, + .bind_host = "127.0.0.1", + .bind_port = 0, + .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, + .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, + .est_allow_anonymous_enroll = 1, + }; + WolfCertServer* srv = NULL; + WolfCertKey* kb = NULL; + WolfCertKey* k1 = NULL; + WolfCertKey* k2 = NULL; + WolfCertBuffer other_ca = { 0 }; + WolfCertBuffer none = { 0 }; + WolfCertEstResult boot = { 0 }; + WolfCertEstResult issued = { 0 }; + WolfCertEstResult renewed = { 0 }; + WolfCertEstResult refused = { 0 }; + WolfCertBuffer csr = { 0 }; + WolfCertBuffer boot_key = { 0 }; + WolfCertBuffer k1_pem = { 0 }; + char status[64]; + pthread_t tid; + char url[128]; + int rc; + + /* A second CA, as another wolfcert-server would generate it. */ + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + }; + REQUIRE(wolfcert_est_get_cacerts(&cli, WOLFCERT_ENCODING_PEM, + &other_ca) == WOLFCERT_OK); + REQUIRE(wolfcert_key_generate(&kcfg, &kb) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(kb, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &boot) == + WOLFCERT_OK); + wolfcert_buffer_free(&csr); + REQUIRE(wolfcert_key_to_pem(kb, &boot_key) == WOLFCERT_OK); + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + srv = NULL; + + cfg.ca_cert = test_ca()->cert; + cfg.ca_cert_len = test_ca()->cert_len; + cfg.ca_key = test_ca()->key; + cfg.ca_key_len = test_ca()->key_len; + cfg.est_allow_anonymous_enroll = 0; + cfg.tls_client_ca_pem = other_ca.data; + cfg.tls_client_ca_pem_len = other_ca.len; + cfg.tls_client_trust_issued = 1; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + + /* The client CA still demands a certificate, so no HTTP answer comes. */ + rc = wolfcert_est_get_cacerts(&cli, WOLFCERT_ENCODING_PEM, &none); + REQUIRE(rc != WOLFCERT_OK && rc != WOLFCERT_ERR_HTTP && + rc != WOLFCERT_ERR_AUTH); + + cli.client_cert = boot.cert_pem.data; + cli.client_cert_len = boot.cert_pem.len; + cli.client_key = boot_key.data; + cli.client_key_len = boot_key.len; + meta.subject_dn = "CN=issued-here"; + REQUIRE(wolfcert_key_generate(&kcfg, &k1) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(k1, &meta, &csr) == WOLFCERT_OK); + REQUIRE(wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &issued) == + WOLFCERT_OK); + + /* A certificate this server issued does not authenticate an enroll. */ + REQUIRE(wolfcert_key_to_pem(k1, &k1_pem) == WOLFCERT_OK); + cli.client_cert = issued.cert_pem.data; + cli.client_cert_len = issued.cert_pem.len; + cli.client_key = k1_pem.data; + cli.client_key_len = k1_pem.len; + wolfcert_clear_error(); + rc = wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &refused); + wolfcert_buffer_free(&csr); + REQUIRE(rc == WOLFCERT_ERR_AUTH); + REQUIRE(strstr(wolfcert_last_error_message(), "HTTP 403") != NULL); + REQUIRE(refused.cert_pem.data == NULL); + + REQUIRE(wolfcert_key_generate(&kcfg, &k2) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(k2, &meta, &csr) == WOLFCERT_OK); + rc = wolfcert_est_simple_reenroll(&cli, issued.cert_pem.data, issued.cert_pem.len, k1, + csr.data, csr.len, &renewed); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(memmem(renewed.cert_pem.data, renewed.cert_pem.len, "BEGIN CERTIFICATE", 17) != NULL); + +#if !defined(WOLFSSL_NO_TLS12) && defined(HAVE_ECC) + /* A resumed session cannot enroll: 403 when SESSION_CERTS keeps its + * certificate, 500 when there is none to check. */ + REQUIRE(resumed_status(wolfcert_server_port(srv), tls_cert, tls_cert_len, + &issued.cert_pem, &k1_pem, + "POST /.well-known/est/simpleenroll HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Content-Type: application/pkcs10\r\n" + "Content-Length: 4\r\nConnection: close\r\n" + "\r\nAAAA", status, sizeof(status)) == 0); + REQUIRE(strcmp(status, "HTTP/1.1 500 Server Error") == 0 || + strncmp(status, "HTTP/1.1 403", 12) == 0); +#endif + + /* With Basic, a certificate issued here no longer blocks an enroll. */ + WolfCertEstResult with_basic = { 0 }; + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + srv = NULL; + cfg.http_basic_user = "alice"; + cfg.http_basic_pass = "secret"; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + cli.proto_opts.est.username = "alice"; + cli.proto_opts.est.password = "secret"; + rc = wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &with_basic); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(with_basic.status == WOLFCERT_EST_STATUS_SUCCESS); + wolfcert_est_result_free(&with_basic); + + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + wolfcert_buffer_free(&csr); + wolfcert_est_result_free(&renewed); + wolfcert_est_result_free(&issued); + wolfcert_est_result_free(&boot); + wolfcert_buffer_free(&other_ca); + wolfcert_buffer_free(&k1_pem); + wolfcert_buffer_free(&boot_key); + wolfcert_key_free(k2); + wolfcert_key_free(k1); + wolfcert_key_free(kb); + return 0; +} + +/* A pinned self-signed client certificate still enrolls next to + * tls_client_trust_issued. */ +static int test_trust_issued_pinned_self_signed(const uint8_t* tls_cert, + size_t tls_cert_len, + const uint8_t* tls_key, + size_t tls_key_len, + const uint8_t* cli_cert, + size_t cli_cert_len, + const uint8_t* cli_key, + size_t cli_key_len) +{ + WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, + .dev_id = INVALID_DEVID }; + WolfCertCertMeta meta = { .subject_dn = "CN=pinned" }; + WolfCertServerCfgSrv cfg = { + .protocol = WOLFCERT_PROTO_EST, + .bind_host = "127.0.0.1", + .bind_port = 0, + TEST_CA_CFG, + .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, + .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, + .tls_client_ca_pem = cli_cert, + .tls_client_ca_pem_len = cli_cert_len, + .tls_client_trust_issued = 1, + }; + WolfCertServer* srv = NULL; + WolfCertKey* k = NULL; + WolfCertBuffer csr = { 0 }; + WolfCertEstResult issued = { 0 }; + pthread_t tid; + char url[128]; + int rc; + + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(pthread_create(&tid, NULL, server_thread, srv) == 0); + snprintf(url, sizeof(url), "https://127.0.0.1:%u/.well-known/est", + wolfcert_server_port(srv)); + WolfCertServerCfg cli = { + .protocol = WOLFCERT_PROTO_EST, + .server_url = url, + .trust_anchors = tls_cert, + .trust_anchors_len = tls_cert_len, + .verify_server = 1, + .client_cert = cli_cert, + .client_cert_len = cli_cert_len, + .client_key = cli_key, + .client_key_len = cli_key_len, + }; + REQUIRE(wolfcert_key_generate(&kcfg, &k) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(k, &meta, &csr) == WOLFCERT_OK); + rc = wolfcert_est_simple_enroll(&cli, csr.data, csr.len, &issued); + + wolfcert_server_stop(srv); + pthread_join(tid, NULL); + wolfcert_server_free(srv); + REQUIRE(rc == WOLFCERT_OK); + wolfcert_est_result_free(&issued); + wolfcert_buffer_free(&csr); + wolfcert_key_free(k); + return 0; +} #endif /* KEEP_PEER_CERT */ #ifndef KEEP_PEER_CERT @@ -527,7 +986,7 @@ static int test_reenroll_needs_peer_cert(const char* url, const uint8_t* cli_key, size_t cli_key_len) { WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=factory-bootstrap" }; WolfCertServerCfg cli = { .protocol = WOLFCERT_PROTO_EST, @@ -555,6 +1014,26 @@ static int test_reenroll_needs_peer_cert(const char* url, REQUIRE(issued.cert_pem.data == NULL); return 0; } + +/* tls_client_trust_issued cannot work without the peer certificate. */ +static int test_trust_issued_needs_peer_cert(const uint8_t* tls_cert, + size_t tls_cert_len, + const uint8_t* tls_key, + size_t tls_key_len) +{ + WolfCertServerCfgSrv cfg = { + .protocol = WOLFCERT_PROTO_EST, + .bind_host = "127.0.0.1", + .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, + .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, + .tls_client_trust_issued = 1, + }; + WolfCertServer* srv = NULL; + + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(srv == NULL); + return 0; +} #endif int main(void) @@ -581,7 +1060,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .tls_client_ca_pem = cli_cert, .tls_client_ca_pem_len = cli_cert_len, @@ -639,7 +1118,7 @@ int main(void) wolfcert_buffer_free(&ca_pem); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=mtls-est-client" }; @@ -673,6 +1152,8 @@ int main(void) REQUIRE(test_reenroll_needs_peer_cert(url, tls_cert, tls_cert_len, cli_cert, cli_cert_len, cli_key, cli_key_len) == 0); + REQUIRE(test_trust_issued_needs_peer_cert(tls_cert, tls_cert_len, + tls_key, tls_key_len) == 0); printf("skip reenroll cases: wolfSSL built without KEEP_PEER_CERT\n"); #endif @@ -689,13 +1170,23 @@ int main(void) tls_key, tls_key_len, cli_cert, cli_cert_len, cli_key, cli_key_len) == 0); + REQUIRE(test_reenroll_trust_issued(tls_cert, tls_cert_len, + tls_key, tls_key_len, + cli_cert, cli_cert_len, + cli_key, cli_key_len) == 0); + REQUIRE(test_trust_issued_with_client_ca(tls_cert, tls_cert_len, + tls_key, tls_key_len) == 0); + REQUIRE(test_trust_issued_pinned_self_signed(tls_cert, tls_cert_len, + tls_key, tls_key_len, + cli_cert, cli_cert_len, + cli_key, cli_key_len) == 0); #endif free(tls_cert); free(tls_key); free(cli_cert); free(cli_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_est_pending_roundtrip.c b/tests/integration/test_est_pending_roundtrip.c index 7ac1a73b..4f375bda 100644 --- a/tests/integration/test_est_pending_roundtrip.c +++ b/tests/integration/test_est_pending_roundtrip.c @@ -96,7 +96,7 @@ static int make_csr(const char* subject, WolfCertKey** out_key, WolfCertBuffer* out_csr) { WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; if (wolfcert_key_generate(&kcfg, out_key) != WOLFCERT_OK) return 1; WolfCertCertMeta meta = { .subject_dn = subject }; @@ -222,7 +222,7 @@ static int pending_path(WolfCertServer* s) WolfCertClient* client = NULL; REQUIRE(wolfcert_client_new(&client) == WOLFCERT_OK); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=device-est-pending-client" }; WolfCertKey* key = NULL; WolfCertBuffer cert = { 0 }; @@ -461,7 +461,7 @@ int main(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .est_require_approval = 1, .est_retry_after_sec = 1, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, @@ -479,7 +479,7 @@ int main(void) free(tls_cert); free(tls_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); if (rc != 0) return rc; diff --git a/tests/integration/test_est_pha_roundtrip.c b/tests/integration/test_est_pha_roundtrip.c index e55f4f65..07a6ecd0 100644 --- a/tests/integration/test_est_pha_roundtrip.c +++ b/tests/integration/test_est_pha_roundtrip.c @@ -74,7 +74,7 @@ static int expect_enroll_refused(const WolfCertServerCfg* cli, const char* cn) wolfcert_buffer_free(&ca_pem); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = cn }; @@ -114,7 +114,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, @@ -145,7 +145,7 @@ int main(void) free(tls_key); free(cli_cert); free(cli_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); return 77; } @@ -182,7 +182,7 @@ int main(void) /* /simpleenroll triggers the server's CertificateRequest. */ WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=pha-enrollee" }; @@ -258,7 +258,7 @@ int main(void) .proto_opts.est = { .allow_post_handshake_auth = 1 }, }; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=factory-bootstrap" }; WolfCertKey* dk = NULL; WolfCertBuffer csr = { 0 }; @@ -342,7 +342,7 @@ int main(void) free(tls_key); free(cli_cert); free(cli_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_est_roundtrip.c b/tests/integration/test_est_roundtrip.c index 9cef8008..dc74a3f6 100644 --- a/tests/integration/test_est_roundtrip.c +++ b/tests/integration/test_est_roundtrip.c @@ -172,7 +172,7 @@ static int rdn_is(const char* p, int len, const char* want) static int enroll_check_subject_rdns(const WolfCertServerCfg* client_cfg) { WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); @@ -238,7 +238,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .http_basic_user = "alice", .http_basic_pass = "hunter2", .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, @@ -324,7 +324,7 @@ int main(void) /* A flipped signature bit keeps the CSR parseable and the credentials are * valid, so only the proof-of-possession check can reject it. */ WolfCertKeyCfg pop_kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* pop_dk = NULL; REQUIRE(wolfcert_key_generate(&pop_kcfg, &pop_dk) == WOLFCERT_OK); WolfCertCertMeta pop_meta = { .subject_dn = "CN=pop-tamper" }; @@ -342,7 +342,7 @@ int main(void) wolfcert_key_free(pop_dk); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=auth-fail" }; @@ -363,7 +363,7 @@ int main(void) WolfCertServerCfgSrv acfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .http_basic_user = "alice", .http_basic_pass = "hunter", .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, @@ -384,7 +384,7 @@ int main(void) .password = "hunter" } }; WolfCertKeyCfg akcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* adk = NULL; REQUIRE(wolfcert_key_generate(&akcfg, &adk) == WOLFCERT_OK); WolfCertCertMeta ameta = { .subject_dn = "CN=auth-exact" }; @@ -416,7 +416,7 @@ int main(void) wolfcert_buffer_free(&ca_pem); free(tls_cert); free(tls_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK (%d transport connects)\n", g_connect_calls); return 0; diff --git a/tests/integration/test_est_tls_roundtrip.c b/tests/integration/test_est_tls_roundtrip.c index 9809257a..ce856877 100644 --- a/tests/integration/test_est_tls_roundtrip.c +++ b/tests/integration/test_est_tls_roundtrip.c @@ -162,7 +162,7 @@ static int test_client_reenroll_keeps_identity(const uint8_t* tls_cert, .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, }; @@ -180,7 +180,7 @@ static int test_client_reenroll_keeps_identity(const uint8_t* tls_cert, #ifdef KEEP_PEER_CERT WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; int called = 0; #endif @@ -297,33 +297,26 @@ int main(void) size_t tls_key_len = 0; REQUIRE(gen_server_identity(&tls_cert, &tls_cert_len, &tls_key, &tls_key_len) == 0); - /* An EST listener without a TLS identity is refused at start. */ - WolfCertStoreOps* plain_store = wolfcert_store_memory_open(NULL); - REQUIRE(plain_store != NULL); + /* An EST listener without a TLS identity is refused at start, before the + * CA is loaded: this one does not parse. */ + static const uint8_t junk_ca[] = "not a CA"; WolfCertServerCfgSrv plain = { - .protocol = WOLFCERT_PROTO_EST, - .bind_host = "127.0.0.1", - .bind_port = 0, - .ca_store = plain_store, + .protocol = WOLFCERT_PROTO_EST, + .bind_host = "127.0.0.1", + .bind_port = 0, + .ca_cert = junk_ca, .ca_cert_len = sizeof(junk_ca) - 1, + .ca_key = junk_ca, .ca_key_len = sizeof(junk_ca) - 1, }; WolfCertServer* plain_srv = NULL; REQUIRE(wolfcert_server_start(&plain, &plain_srv) == WOLFCERT_ERR_TLS); REQUIRE(plain_srv == NULL); - /* The refusal comes before a CA is minted into the store. */ - WolfCertBuffer leftover = { 0 }; - REQUIRE(plain_store->read(plain_store->ctx, "ca.cert.der", &leftover) - == WOLFCERT_ERR_NOT_FOUND); - REQUIRE(plain_store->read(plain_store->ctx, "ca.key.der", &leftover) - == WOLFCERT_ERR_NOT_FOUND); - wolfcert_store_memory_close(plain_store); - /* An EST listener with no way to authenticate a client is refused too. */ WolfCertServerCfgSrv open_cfg = { .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, }; @@ -361,7 +354,7 @@ int main(void) .protocol = WOLFCERT_PROTO_EST, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .tls_cert_pem = tls_cert, .tls_cert_pem_len = tls_cert_len, .tls_key_pem = tls_key, .tls_key_pem_len = tls_key_len, .est_allow_anonymous_enroll = 1, @@ -389,7 +382,7 @@ int main(void) REQUIRE(ca_pem.len > 0); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=tls-est-client" }; @@ -457,7 +450,7 @@ int main(void) wolfcert_key_free(dk); free(tls_cert); free(tls_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_scep_async_roundtrip.c b/tests/integration/test_scep_async_roundtrip.c index a8da75db..739bf864 100644 --- a/tests/integration/test_scep_async_roundtrip.c +++ b/tests/integration/test_scep_async_roundtrip.c @@ -198,7 +198,7 @@ static int bootstrap(const WolfCertServerCfg* cli, const char* cn, } WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; if (wolfcert_key_generate(&kcfg, key) != WOLFCERT_OK) { wc_FreeDer(ca_der); wolfcert_buffer_free(ca_pem); @@ -255,7 +255,7 @@ static int async_enroll_path(WolfCertServer* s) WolfCertScepResult r = { 0 }; WolfCertScepSession* bsess = NULL; WolfCertKeyCfg kcfg2 = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk2 = NULL; WolfCertCertMeta meta2 = { .subject_dn = "CN=sync-scep-1" }; WolfCertBuffer csr2 = { 0 }; @@ -733,7 +733,7 @@ static int non_rsa_reject_path(WolfCertServer* s) WolfCertKey* dk = NULL; WolfCertBuffer csr = { 0 }; WolfCertKeyCfg ecfg = { .type = WOLFCERT_KEY_ED25519, .param = 0, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* ek = NULL; WolfCertScepSession* sess = NULL; WolfCertScepResult r = { 0 }; @@ -791,7 +791,7 @@ static int blocking_renewal_poll_path(WolfCertServer* s) WolfCertScepResult r3 = { 0 }; WolfCertScepResult r4 = { 0 }; WolfCertKeyCfg nkcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta nmeta = { .subject_dn = "CN=sync-renew-poll" }; WolfCertKey* nk = NULL; WolfCertBuffer ncsr = { 0 }; @@ -1223,7 +1223,7 @@ int main(void) /* Scenario A: auto-approve server. */ WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s1 = NULL; REQUIRE(wolfcert_server_start(&cfg, &s1) == WOLFCERT_OK); pthread_t t1; @@ -1238,7 +1238,7 @@ int main(void) /* Scenario B: approval-required server (PENDING -> poll). */ WolfCertServerCfgSrv cfg_pending = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_require_approval = 1 }; WolfCertServer* s2 = NULL; REQUIRE(wolfcert_server_start(&cfg_pending, &s2) == WOLFCERT_OK); @@ -1254,7 +1254,7 @@ int main(void) /* Scenario C: auto-approve server, async enroll -> async RenewalReq. */ WolfCertServerCfgSrv cfg_renew = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s3 = NULL; REQUIRE(wolfcert_server_start(&cfg_renew, &s3) == WOLFCERT_OK); pthread_t t3; @@ -1269,7 +1269,7 @@ int main(void) /* Scenario D: auto-approve server, session misuse guards. */ WolfCertServerCfgSrv cfg_guard = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s4 = NULL; REQUIRE(wolfcert_server_start(&cfg_guard, &s4) == WOLFCERT_OK); pthread_t t4; @@ -1284,7 +1284,7 @@ int main(void) /* Scenario E: approval-required server, blocking PENDING -> poll. */ WolfCertServerCfgSrv cfg_bpoll = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_require_approval = 1 }; WolfCertServer* s5 = NULL; REQUIRE(wolfcert_server_start(&cfg_bpoll, &s5) == WOLFCERT_OK); @@ -1300,7 +1300,7 @@ int main(void) /* Scenario F: auto-approve server, session over base64 GET. */ WolfCertServerCfgSrv cfg_get = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s6 = NULL; REQUIRE(wolfcert_server_start(&cfg_get, &s6) == WOLFCERT_OK); pthread_t t6; @@ -1320,7 +1320,7 @@ int main(void) /* Scenario H: auto-approve server, non-RSA signer rejection. */ WolfCertServerCfgSrv cfg_nonrsa = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s7 = NULL; REQUIRE(wolfcert_server_start(&cfg_nonrsa, &s7) == WOLFCERT_OK); pthread_t t7; @@ -1336,7 +1336,7 @@ int main(void) /* Scenario I: approval-required server, renewal poll with signer_cert. */ WolfCertServerCfgSrv cfg_rpoll = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_require_approval = 1 }; WolfCertServer* s8 = NULL; REQUIRE(wolfcert_server_start(&cfg_rpoll, &s8) == WOLFCERT_OK); @@ -1352,7 +1352,7 @@ int main(void) /* Scenario J: auto-approve server for bootstrap, then the 500 stub. */ WolfCertServerCfgSrv cfg_500 = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s9 = NULL; REQUIRE(wolfcert_server_start(&cfg_500, &s9) == WOLFCERT_OK); pthread_t t9; @@ -1367,7 +1367,7 @@ int main(void) /* Scenario K: auto-approve server, argument-validation guards. */ WolfCertServerCfgSrv cfg_neg = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s10 = NULL; REQUIRE(wolfcert_server_start(&cfg_neg, &s10) == WOLFCERT_OK); pthread_t t10; @@ -1383,7 +1383,7 @@ int main(void) * GetCert over a session. */ WolfCertServerCfgSrv cfg_get_ops = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_enable_next_ca = 1, .scep_enable_get_cert = 1 }; WolfCertServer* s11 = NULL; @@ -1397,7 +1397,7 @@ int main(void) if (rc != 0) return rc; - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_scep_get_cert.c b/tests/integration/test_scep_get_cert.c index 88308fa8..c12afec4 100644 --- a/tests/integration/test_scep_get_cert.c +++ b/tests/integration/test_scep_get_cert.c @@ -70,7 +70,7 @@ static int get_cert_path(WolfCertServer* s) &ca_der, NULL, NULL, NULL) == 0); WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=device-getcert-1" }; @@ -325,7 +325,7 @@ static int disabled_path(WolfCertServer* s) &ca_der, NULL, NULL, NULL) == 0); WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=device-getcert-off" }; @@ -374,7 +374,7 @@ int main(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_enable_get_cert = 1, }; WolfCertServer* s = NULL; @@ -394,7 +394,7 @@ int main(void) WolfCertServerCfgSrv cfg_off = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, }; WolfCertServer* s_off = NULL; REQUIRE(wolfcert_server_start(&cfg_off, &s_off) == WOLFCERT_OK); @@ -409,7 +409,7 @@ int main(void) if (rc != 0) return rc; - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_scep_poll_roundtrip.c b/tests/integration/test_scep_poll_roundtrip.c index 467afdef..a77de5bf 100644 --- a/tests/integration/test_scep_poll_roundtrip.c +++ b/tests/integration/test_scep_poll_roundtrip.c @@ -77,6 +77,7 @@ static int post_signed(const char* url, WolfCertKey* dk, REQUIRE(wolfcert_scep_self_signed_rsa((RsaKey*)dk->impl, csr->data, csr->len, &signer, &signer_len, + INVALID_DEVID, NULL) == WOLFCERT_OK); key_len = wc_RsaKeyToDer((RsaKey*)dk->impl, key_der, sizeof(key_der)); REQUIRE(key_len > 0); @@ -91,7 +92,7 @@ static int post_signed(const char* url, WolfCertKey* dk, REQUIRE(wolfcert_scep_build_pki_message(content, content_len, signer, signer_len, key_der, (size_t)key_len, 0, - &attrs, &pki, NULL) == WOLFCERT_OK); + &attrs, &pki, INVALID_DEVID, NULL) == WOLFCERT_OK); snprintf(pki_url, sizeof(pki_url), "%s?operation=PKIOperation", url); WolfCertHttpRequest req = { .method = "POST", .url = pki_url, @@ -101,7 +102,7 @@ static int post_signed(const char* url, WolfCertKey* dk, REQUIRE(resp.status_code == 200); REQUIRE(wolfcert_scep_parse_pki_message(resp.body, resp.body_len, &env, NULL, NULL, NULL, NULL, NULL, NULL, NULL, out_status, - NULL, NULL, out_fail_info, NULL) == WOLFCERT_OK); + NULL, NULL, out_fail_info, INVALID_DEVID, NULL) == WOLFCERT_OK); wolfcert_buffer_free(&env); wolfcert_http_response_free(&resp); @@ -124,6 +125,7 @@ static int poll_ias_refused(const char* url, WolfCertKey* dk, int refused = 0; if (wolfcert_scep_envelop(ca_der, ca_len, ias, ias_len, AES128CBCb, &env, + INVALID_DEVID, NULL) == WOLFCERT_OK && post_signed(url, dk, csr, "20", tid, tid_len, env.data, env.len, &status, &fail_info) == 0) { @@ -184,7 +186,7 @@ static int poll_path(WolfCertServer* s) &ca_der, NULL, NULL, NULL) == 0); WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=device-poll-1" }; @@ -251,6 +253,7 @@ static int poll_path(WolfCertServer* s) junk_ias, sizeof(junk_ias)) == 0); REQUIRE(wolfcert_scep_self_signed_rsa((RsaKey*)dk->impl, csr.data, csr.len, &self, &self_len, + INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(wolfcert_scep_issuer_and_subject(self, self_len, csr.data, csr.len, &ias, NULL) @@ -276,7 +279,7 @@ static int poll_path(WolfCertServer* s) char* tk_fail_info = NULL; REQUIRE(wolfcert_scep_envelop(ca_der->buffer, ca_der->length, other_csr.data, other_csr.len, AES128CBCb, - &other_env, NULL) == WOLFCERT_OK); + &other_env, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(post_signed(url, other, &other_csr, "19", r1.transaction_id, r1.transaction_id_len, other_env.data, other_env.len, &tk_status, &tk_fail_info) == 0); @@ -521,7 +524,7 @@ static int empty_subject_path(WolfCertServer* s) &ca_der, NULL, NULL, NULL) == 0); WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); static const char* const dns[] = { "empty-subject.example" }; @@ -630,7 +633,7 @@ static int next_ca_disabled_path(void) /* GetNextCACert is not advertised and answers WOLFCERT_ERR_NOT_FOUND. */ WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s = NULL; REQUIRE(wolfcert_server_start(&cfg, &s) == WOLFCERT_OK); pthread_t tid; @@ -672,7 +675,7 @@ int main(void) WolfCertServerCfgSrv cfg_pending = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_require_approval = 1, }; WolfCertServer* s1 = NULL; @@ -691,7 +694,7 @@ int main(void) WolfCertServerCfgSrv cfg_next = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_enable_next_ca = 1, }; WolfCertServer* s2 = NULL; @@ -709,7 +712,7 @@ int main(void) if (rc != 0) return rc; - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_scep_roundtrip.c b/tests/integration/test_scep_roundtrip.c index 9cc13865..aab0a738 100644 --- a/tests/integration/test_scep_roundtrip.c +++ b/tests/integration/test_scep_roundtrip.c @@ -29,6 +29,9 @@ #include #include /* SHA256h */ #include +#ifdef WOLF_CRYPTO_CB +#include +#endif #include #include #include @@ -321,7 +324,7 @@ static int check_rsa4096(const WolfCertServerCfg* cli, const uint8_t* ca_der_buf, size_t ca_der_len) { WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 4096, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=device-scep-4096" }; WolfCertKey* key = NULL; WolfCertBuffer csr = { 0 }; @@ -369,6 +372,81 @@ static int check_rsa4096(const WolfCertServerCfg* cli, return rc; } +#ifdef WOLF_CRYPTO_CB +#define ACCEL_DEVID 0x6163 + +static int accel_priv; +static int accel_pub; + +/* Counts RSA operations and leaves them to software. */ +static int accel_cb(int devId, wc_CryptoInfo* info, void* ctx) +{ + (void)devId; + (void)ctx; + + if (info->algo_type == WC_ALGO_TYPE_PK && info->pk.type == WC_PK_TYPE_RSA) { + if (info->pk.rsa.type == RSA_PRIVATE_ENCRYPT || + info->pk.rsa.type == RSA_PRIVATE_DECRYPT) + accel_priv++; + else + accel_pub++; + } + return CRYPTOCB_UNAVAILABLE; +} + +/* A PKCSReq with a default devId runs its PKCS#7 signing, decryption, + * encryption and verification there; a software key and the built-in server + * stay in software. */ +static int check_default_dev_id(const WolfCertServerCfg* cli, + const WolfCertScepCaps* caps, + const uint8_t* ca_der_buf, size_t ca_der_len) +{ + WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, + .dev_id = INVALID_DEVID }; + WolfCertCertMeta meta = { .subject_dn = "CN=device-scep-accel" }; + WolfCertKey* key = NULL; + WolfCertKey* imported = NULL; + WolfCertBuffer pem = { 0 }; + WolfCertBuffer csr = { 0 }; + WolfCertScepResult issued = { 0 }; + +#ifndef WOLF_CRYPTO_CB_FIND + REQUIRE(wolfcert_set_default_dev_id(ACCEL_DEVID + 1) == + WOLFCERT_ERR_BAD_ARG); +#endif + REQUIRE(wc_CryptoCb_RegisterDevice(ACCEL_DEVID, accel_cb, NULL) == 0); + REQUIRE(wolfcert_set_default_dev_id(ACCEL_DEVID) == WOLFCERT_OK); + + REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); + REQUIRE(wolfcert_key_dev_id(key) == INVALID_DEVID); + REQUIRE(wolfcert_key_to_pem(key, &pem) == WOLFCERT_OK); + REQUIRE(wolfcert_key_from_pem(pem.data, pem.len, NULL, &imported) == + WOLFCERT_OK); + REQUIRE(wolfcert_key_dev_id(imported) == INVALID_DEVID); + REQUIRE(wolfcert_csr_build(key, &meta, &csr) == WOLFCERT_OK); + + accel_priv = 0; + accel_pub = 0; + REQUIRE(wolfcert_scep_pkcs_req(cli, caps, ca_der_buf, ca_der_len, + ca_der_buf, ca_der_len, + key, csr.data, csr.len, &issued) == + WOLFCERT_OK); + REQUIRE(issued.status == WOLFCERT_SCEP_STATUS_SUCCESS); + /* pkiMessage signature and CertRep decryption. */ + REQUIRE(accel_priv >= 2); + REQUIRE(accel_pub >= 2); + + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); + wc_CryptoCb_UnRegisterDevice(ACCEL_DEVID); + wolfcert_scep_result_free(&issued); + wolfcert_buffer_free(&csr); + wolfcert_buffer_free(&pem); + wolfcert_key_free(imported); + wolfcert_key_free(key); + return WOLFCERT_OK; +} +#endif /* WOLF_CRYPTO_CB */ + /* Two PKCSReqs of one key under txid_mode PUBKEY_HASH carry the same * transactionID, the upper-case hex SHA-256 of the CSR's SPKI. */ static int check_pubkey_txid(const WolfCertServerCfg* cli, @@ -489,7 +567,7 @@ static int check_renewal_foreign_signer(const WolfCertServerCfg* cli, int rc; rc = wolfcert_scep_self_signed_rsa((RsaKey*)key->impl, csr, csr_len, - &signer, &signer_len, NULL); + &signer, &signer_len, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) { rc = wolfcert_scep_renewal_req(cli, caps, ca_der_buf, ca_der_len, ca_der_buf, ca_der_len, @@ -874,7 +952,7 @@ static void msgtype_send_cert_rep(const struct msgtype_ctx* mc, int cs, WolfCertBuffer rep = { 0 }; if (wolfcert_scep_build_pki_message(NULL, 0, mc->rep_cert, mc->rep_cert_len, mc->rep_key, mc->rep_key_len, SHA256h, - &attrs, &rep, NULL) != WOLFCERT_OK) + &attrs, &rep, INVALID_DEVID, NULL) != WOLFCERT_OK) return; char hdr[160]; @@ -952,7 +1030,7 @@ static void* msgtype_srv_thread(void* arg) &mt, /* messageType */ NULL, /* pkiStatus */ NULL, NULL, /* signer cert */ - NULL, /* failInfo */ + NULL, INVALID_DEVID, /* failInfo */ NULL) == WOLFCERT_OK) { if (mt != NULL) snprintf(mc->seen, sizeof(mc->seen), "%s", mt); @@ -1250,10 +1328,10 @@ static int check_required_attrs(WolfCertServer* s, const WolfCertKeyCfg* kcfg, rc = wolfcert_key_to_der(key, &kder); if (rc == WOLFCERT_OK) rc = wolfcert_scep_self_signed_rsa((RsaKey*)key->impl, csr.data, - csr.len, &signer, &signer_len, NULL); + csr.len, &signer, &signer_len, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) rc = wolfcert_scep_envelop(ca_der_buf, ca_der_len, csr.data, csr.len, - AES128CBCb, &env, NULL); + AES128CBCb, &env, INVALID_DEVID, NULL); memset(tid, 'A', sizeof(tid)); memset(snonce, 0x22, sizeof(snonce)); @@ -1308,7 +1386,7 @@ static int check_required_attrs(WolfCertServer* s, const WolfCertKeyCfg* kcfg, rc = wolfcert_scep_build_pki_message(env.data, env.len, signer, signer_len, kder.data, kder.len, - SHA256h, &a, &msg, NULL); + SHA256h, &a, &msg, INVALID_DEVID, NULL); if (rc != WOLFCERT_OK) break; @@ -1326,7 +1404,7 @@ static int check_required_attrs(WolfCertServer* s, const WolfCertKeyCfg* kcfg, ok = (st == 200 && rsp != NULL && wolfcert_scep_parse_pki_message(rsp, rsp_len, &renv, &r_tid, &r_tidl, &r_sn, &r_snl, &r_rn, &r_rnl, - &r_mt, &r_st, &r_sc, &r_scl, &r_fi, NULL) == WOLFCERT_OK); + &r_mt, &r_st, &r_sc, &r_scl, &r_fi, INVALID_DEVID, NULL) == WOLFCERT_OK); ok = ok && r_tid != NULL && r_tidl == sizeof(tid) && memcmp(r_tid, tid, sizeof(tid)) == 0 && @@ -1359,7 +1437,7 @@ static int check_required_attrs(WolfCertServer* s, const WolfCertKeyCfg* kcfg, rc = wolfcert_scep_build_pki_message(env.data, env.len, signer, signer_len, kder.data, kder.len, - SHA256h, &a, &msg, NULL); + SHA256h, &a, &msg, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) { if (raw_http_req(wolfcert_server_port(s), "POST", "/scep?operation=PKIOperation", @@ -1611,7 +1689,7 @@ static int check_unprintable_tid(uint16_t port, const WolfCertKeyCfg* kcfg) rc = wolfcert_key_to_der(key, &kder); if (rc == WOLFCERT_OK) rc = wolfcert_scep_self_signed_rsa((RsaKey*)key->impl, csr.data, - csr.len, &signer, &signer_len, NULL); + csr.len, &signer, &signer_len, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) { st = post_raw_tid(port, signer, signer_len, &kder, "tid@1", 0); @@ -1687,10 +1765,10 @@ static int check_malformed_dispatch(uint16_t port, const WolfCertKeyCfg* kcfg, rc = wolfcert_key_to_der(key, &kder); if (rc == WOLFCERT_OK) rc = wolfcert_scep_self_signed_rsa((RsaKey*)key->impl, csr.data, - csr.len, &signer, &signer_len, NULL); + csr.len, &signer, &signer_len, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) rc = wolfcert_scep_envelop(ca_der_buf, ca_der_len, csr.data, csr.len, - AES128CBCb, &env, NULL); + AES128CBCb, &env, INVALID_DEVID, NULL); /* The last round needs a cipher the CA cannot run: copy the envelope and * point its algorithm at an unassigned OID under the same arc. */ @@ -1733,7 +1811,7 @@ static int check_malformed_dispatch(uint16_t port, const WolfCertKeyCfg* kcfg, rc = wolfcert_scep_build_pki_message(content, content_len, signer, signer_len, kder.data, kder.len, - SHA256h, &a, &msg, NULL); + SHA256h, &a, &msg, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) { WolfCertHttpRequest req = { .method = "POST", @@ -1748,7 +1826,7 @@ static int check_malformed_dispatch(uint16_t port, const WolfCertKeyCfg* kcfg, ok = ok && wolfcert_scep_parse_pki_message(resp.body, resp.body_len, &renv, &r_tid, &r_tidl, &r_sn, &r_snl, &r_rn, &r_rnl, &r_mt, &r_st, &r_sc, - &r_scl, &r_fi, NULL) == WOLFCERT_OK; + &r_scl, &r_fi, INVALID_DEVID, NULL) == WOLFCERT_OK; ok = ok && r_mt != NULL && strcmp(r_mt, "3") == 0 && r_st != NULL && strcmp(r_st, "2") == 0 && @@ -1792,7 +1870,7 @@ static int check_malformed_dispatch(uint16_t port, const WolfCertKeyCfg* kcfg, WolfCertBuffer msg = { 0 }; rc = wolfcert_scep_build_pki_message(env.data, env.len, signer, - signer_len, kder.data, kder.len, SHA256h, &a, &msg, NULL); + signer_len, kder.data, kder.len, SHA256h, &a, &msg, INVALID_DEVID, NULL); if (rc == WOLFCERT_OK) { if (raw_http_req(port, "POST", "/scep?operation=PKIOperation", "application/x-pki-message", @@ -1821,10 +1899,10 @@ static int test_split_ra(void) { WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .scep_split_ra = 1 }; WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = "CN=device-split-ra" }; WolfCertServer* s = NULL; WolfCertScepCaps caps = { 0 }; @@ -1971,7 +2049,7 @@ int main(void) WolfCertServerCfgSrv cfg = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s = NULL; REQUIRE(wolfcert_server_start(&cfg, &s) == WOLFCERT_OK); REQUIRE(wolfcert_scep_server_set_bundle_fault(s, 2) @@ -2007,7 +2085,7 @@ int main(void) REQUIRE(check_getca_media_type(ca_der->buffer, ca_der->length) == 0); WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=device-scep-1" }; @@ -2054,6 +2132,10 @@ int main(void) if (rc != WOLFCERT_OK) fprintf(stderr, "SCEP rsa:4096 rc=%d (%s)\n", rc, wolfcert_strerror(rc)); REQUIRE(rc == WOLFCERT_OK); +#ifdef WOLF_CRYPTO_CB + REQUIRE(check_default_dev_id(&cli, &caps, ca_der->buffer, ca_der->length) + == WOLFCERT_OK); +#endif /* A CA advertising SHA-512 or SHA-384 still enrolls within the digests * wolfSSL was built with, and so does a forced SHA-256. */ @@ -2234,7 +2316,7 @@ int main(void) #ifdef WOLFCERT_HAVE_ED25519 /* Ed25519 signer must be rejected cleanly (RFC 8894 requires RSA). */ WolfCertKeyCfg edcfg = { .type = WOLFCERT_KEY_ED25519, .param = 0, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* edk = NULL; REQUIRE(wolfcert_key_generate(&edcfg, &edk) == WOLFCERT_OK); WolfCertCertMeta edmeta = { .subject_dn = "CN=ed-scep" }; @@ -2257,7 +2339,7 @@ int main(void) /* Challenge password (RFC 8894 section 2.9). */ WolfCertServerCfgSrv cfg2 = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store(), + TEST_CA_CFG, .challenge_password = "correct-horse" }; WolfCertServer* s2 = NULL; REQUIRE(wolfcert_server_start(&cfg2, &s2) == WOLFCERT_OK); @@ -2366,7 +2448,7 @@ int main(void) WolfCertBuffer wmsg = { 0 }; REQUIRE(wolfcert_scep_build_pki_message(content, sizeof(content), signer_cert, (size_t)cl, signer_key, (size_t)kl, - SHA256h, &wattrs, &wmsg, NULL) == WOLFCERT_OK); + SHA256h, &wattrs, &wmsg, INVALID_DEVID, NULL) == WOLFCERT_OK); WolfCertBuffer wenv = { 0 }; uint8_t *w_tid = NULL, *w_sn = NULL, *w_rn = NULL, *w_sc = NULL; @@ -2374,7 +2456,7 @@ int main(void) char *w_mt = NULL, *w_st = NULL; REQUIRE(wolfcert_scep_parse_pki_message(wmsg.data, wmsg.len, &wenv, &w_tid, &w_tidl, &w_sn, &w_snl, &w_rn, &w_rnl, - &w_mt, &w_st, &w_sc, &w_scl, NULL, NULL) == WOLFCERT_OK); + &w_mt, &w_st, &w_sc, &w_scl, NULL, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(w_rn != NULL); /* present */ REQUIRE(w_rnl == sizeof(rnonce)); REQUIRE(memcmp(w_rn, rnonce, sizeof(rnonce)) == 0); /* unchanged */ @@ -2391,7 +2473,7 @@ int main(void) /* A CertRep with no recipientNonce is rejected (RFC 8894 3.2.1.2). */ WolfCertServerCfgSrv cfg3 = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s3 = NULL; REQUIRE(wolfcert_server_start(&cfg3, &s3) == WOLFCERT_OK); wolfcert_scep_server_set_faults(s3, 1 /* omit recipientNonce */, 0, 0); @@ -2434,7 +2516,7 @@ int main(void) /* A CertRep signed by a key other than the CA's is rejected. */ WolfCertServerCfgSrv cfg4 = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s4 = NULL; REQUIRE(wolfcert_server_start(&cfg4, &s4) == WOLFCERT_OK); wolfcert_scep_server_set_faults(s4, 0, 1 /* sign with wrong key */, 0); @@ -2477,7 +2559,7 @@ int main(void) /* A failed senderNonce RNG draw on the server answers HTTP 500. */ WolfCertServerCfgSrv cfg5 = { .protocol = WOLFCERT_PROTO_SCEP, .bind_host = "127.0.0.1", .bind_port = 0, - .ca_store = test_ca_store() }; + TEST_CA_CFG }; WolfCertServer* s5 = NULL; REQUIRE(wolfcert_server_start(&cfg5, &s5) == WOLFCERT_OK); wolfcert_scep_server_set_faults(s5, 0, 0, 1 /* RNG draw fails */); @@ -2523,7 +2605,7 @@ int main(void) wolfcert_buffer_free(&csr); wolfcert_scep_result_free(&issued); wolfcert_key_free(dk); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/integration/test_server_stop_idle.c b/tests/integration/test_server_stop_idle.c index b5353c94..1bb24668 100644 --- a/tests/integration/test_server_stop_idle.c +++ b/tests/integration/test_server_stop_idle.c @@ -250,16 +250,17 @@ int main(void) REQUIRE(gen_server_identity(&tls_cert, &tls_cert_len, &tls_key, &tls_key_len) == 0); - memset(&cfg, 0, sizeof(cfg)); - cfg.protocol = TLS_LISTENER_PROTO; - cfg.bind_host = "127.0.0.1"; - cfg.bind_port = 0; - cfg.ca_store = test_ca_store(); - cfg.tls_cert_pem = tls_cert; - cfg.tls_cert_pem_len = tls_cert_len; - cfg.tls_key_pem = tls_key; - cfg.tls_key_pem_len = tls_key_len; - cfg.est_allow_anonymous_enroll = 1; + cfg = (WolfCertServerCfgSrv){ + .protocol = TLS_LISTENER_PROTO, + .bind_host = "127.0.0.1", + .bind_port = 0, + TEST_CA_CFG, + .tls_cert_pem = tls_cert, + .tls_cert_pem_len = tls_cert_len, + .tls_key_pem = tls_key, + .tls_key_pem_len = tls_key_len, + .est_allow_anonymous_enroll = 1, + }; /* 1. Parked in wolfSSL_accept() after answering the ClientHello. */ memset(&ctx, 0, sizeof(ctx)); @@ -298,11 +299,12 @@ int main(void) #ifdef WOLFCERT_HAVE_SCEP /* 3. Parked in recv() on a plaintext listener. */ - memset(&cfg, 0, sizeof(cfg)); - cfg.protocol = WOLFCERT_PROTO_SCEP; - cfg.bind_host = "127.0.0.1"; - cfg.bind_port = 0; - cfg.ca_store = test_ca_store(); + cfg = (WolfCertServerCfgSrv){ + .protocol = WOLFCERT_PROTO_SCEP, + .bind_host = "127.0.0.1", + .bind_port = 0, + TEST_CA_CFG, + }; memset(&ctx, 0, sizeof(ctx)); REQUIRE(wolfcert_server_start(&cfg, &ctx.srv) == WOLFCERT_OK); @@ -427,11 +429,12 @@ int main(void) #ifdef WOLFCERT_HAVE_SCEP /* 8. The next client is served behind a silent plaintext peer. */ - memset(&cfg, 0, sizeof(cfg)); - cfg.protocol = WOLFCERT_PROTO_SCEP; - cfg.bind_host = "127.0.0.1"; - cfg.bind_port = 0; - cfg.ca_store = test_ca_store(); + cfg = (WolfCertServerCfgSrv){ + .protocol = WOLFCERT_PROTO_SCEP, + .bind_host = "127.0.0.1", + .bind_port = 0, + TEST_CA_CFG, + }; memset(&ctx, 0, sizeof(ctx)); REQUIRE(wolfcert_server_start(&cfg, &ctx.srv) == WOLFCERT_OK); @@ -456,7 +459,7 @@ int main(void) free(tls_cert); free(tls_key); - test_ca_store_close(); + test_ca_close(); wolfcert_cleanup(); printf("server stop idle: OK\n"); diff --git a/tests/integration/tls_test_util.h b/tests/integration/tls_test_util.h index 098d803f..d4cd810c 100644 --- a/tests/integration/tls_test_util.h +++ b/tests/integration/tls_test_util.h @@ -23,6 +23,9 @@ #define WOLFCERT_TLS_TEST_UTIL_H #include +#ifdef WOLFCERT_HAVE_SERVER +#include +#endif #include /* pid_t, referenced by wolfssl/wolfcrypt/random.h */ @@ -101,10 +104,13 @@ static inline int black_hole_listener(uint16_t* out_port) typedef RsaKey test_signkey; #define TEST_CERT_SIGTYPE CTC_SHA256wRSA #define TEST_KEY_PEM_TYPE PRIVATEKEY_TYPE + #define TEST_CA_KEY_USAGE \ + "keyCertSign,cRLSign,digitalSignature,keyEncipherment" #elif defined(HAVE_ECC) typedef ecc_key test_signkey; #define TEST_CERT_SIGTYPE CTC_SHA256wECDSA #define TEST_KEY_PEM_TYPE ECC_PRIVATEKEY_TYPE + #define TEST_CA_KEY_USAGE "keyCertSign,cRLSign,digitalSignature" #else #error "tls_test_util: tests need RSA or ECC for a signing identity" #endif @@ -187,7 +193,7 @@ static inline int test_signkey_to_der(test_signkey* key, uint8_t* der, } /* Self-signed cert + key (PEM) for `cn`. A leaf gets an iPAddress SAN for - * 127.0.0.1, a CA none. The caller frees both with free(). */ + * 127.0.0.1, a CA keyUsage instead. The caller frees both with free(). */ static inline int mint_self_id(const char* cn, int is_ca, uint8_t** cert_pem, size_t* cert_pem_len, uint8_t** key_pem, size_t* key_pem_len) @@ -215,7 +221,11 @@ static inline int mint_self_id(const char* cn, int is_ca, cert.sigType = TEST_CERT_SIGTYPE; cert.daysValid = 1; cert.isCA = is_ca ? 1 : 0; - if (!is_ca) { + if (is_ca) { + if (wc_SetKeyUsage(&cert, TEST_CA_KEY_USAGE) != 0) + goto fail; + } + else { memcpy(cert.altNames, san_seq, sizeof(san_seq)); cert.altNamesSz = (int)sizeof(san_seq); } @@ -249,44 +259,57 @@ static inline int mint_self_id(const char* cn, int is_ca, return -1; } -static inline WolfCertStoreOps** test_ca_store_slot(void) +/* Self-signed TLS server identity (cert + key, PEM) for 127.0.0.1. */ +static inline int gen_server_identity(uint8_t** cert_pem, size_t* cert_pem_len, + uint8_t** key_pem, size_t* key_pem_len) { - static WolfCertStoreOps* store = NULL; - - return &store; + return mint_self_id("127.0.0.1", 0, cert_pem, cert_pem_len, + key_pem, key_pem_len); } -/* One CA store for every test server in the process, so only the first - * server start generates a CA. */ -static inline WolfCertStoreOps* test_ca_store(void) +#ifdef WOLFCERT_HAVE_SERVER +typedef struct { + uint8_t* cert; + size_t cert_len; + uint8_t* key; + size_t key_len; +} TestCa; + +static inline TestCa* test_ca_slot(void) { - WolfCertStoreOps** store = test_ca_store_slot(); - - if (*store == NULL) { - *store = wolfcert_store_memory_open(NULL); - if (*store == NULL) { - fprintf(stderr, "test_ca_store: cannot open the memory store\n"); - exit(1); - } - } - return *store; + static TestCa ca; + + return &ca; } -static inline void test_ca_store_close(void) +/* One CA per process, handed to every server the test starts. */ +static inline const TestCa* test_ca(void) { - WolfCertStoreOps** store = test_ca_store_slot(); + TestCa* ca = test_ca_slot(); - wolfcert_store_memory_close(*store); - *store = NULL; + if (ca->cert == NULL && + mint_self_id("wolfCert Test CA", 1, &ca->cert, &ca->cert_len, + &ca->key, &ca->key_len) != 0) { + fprintf(stderr, "test_ca: cannot generate the shared CA\n"); + exit(1); + } + return ca; } -/* Self-signed TLS server identity (cert + key, PEM) for 127.0.0.1. */ -static inline int gen_server_identity(uint8_t** cert_pem, size_t* cert_pem_len, - uint8_t** key_pem, size_t* key_pem_len) +/* Designated initializers that give a server config the shared CA. */ +#define TEST_CA_CFG \ + .ca_cert = test_ca()->cert, .ca_cert_len = test_ca()->cert_len, \ + .ca_key = test_ca()->key, .ca_key_len = test_ca()->key_len + +static inline void test_ca_close(void) { - return mint_self_id("127.0.0.1", 0, cert_pem, cert_pem_len, - key_pem, key_pem_len); + TestCa* ca = test_ca_slot(); + + free(ca->cert); + free(ca->key); + memset(ca, 0, sizeof(*ca)); } +#endif /* WOLFCERT_HAVE_SERVER */ /* Raw TLS client; each test_tls_write() is one TLS record, so one * wolfSSL_read() on the server, which the split-request tests need. */ diff --git a/tests/interop/tpm_wolftpm.sh b/tests/interop/tpm_wolftpm.sh new file mode 100755 index 00000000..64958915 --- /dev/null +++ b/tests/interop/tpm_wolftpm.sh @@ -0,0 +1,217 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: GPL-3.0-or-later +# +# EST enrollment with keys in a TPM: examples/enroll_tpm against wolfTPM's +# fwTPM and wolfcert-server. Needs fwtpm_server in PATH (or FWTPM_SERVER) and +# a wolfCert build with examples on, found through WOLFCERT_BUILD. +# +# TPM_KEY_TYPES picks the key types (default: all the example knows). + +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO="$(cd "$HERE/../.." && pwd)" +. "$HERE/lib/common.sh" + +FWTPM="${FWTPM_SERVER:-}" +if [ -z "$FWTPM" ]; then + need fwtpm_server "Build wolfTPM with -DWOLFTPM_FWTPM=yes (scripts/ci/build-wolftpm.sh)" + FWTPM="$(command -v fwtpm_server)" +fi +WC_SERVER="$(wolfcert_bin wolfcert-server)" +EXAMPLE="$WOLFCERT_BUILD/examples/example_enroll_tpm" +if [ ! -x "$EXAMPLE" ]; then + echo "ERROR: $EXAMPLE not built; configure wolfCert with" \ + "-DWOLFCERT_ENABLE_EXAMPLES=ON and a wolfTPM with its CryptoCb" >&2 + exit 1 +fi +KEY_TYPES="${TPM_KEY_TYPES:-ecc:256 ecc:384 rsa:2048 mldsa:44 mldsa:65 mldsa:87}" + +cd "$WOLFCERT_INTEROP_WORK" +fw_pid="" +srv_pid="" +trap 'kill_if "$srv_pid"; kill_if "$fw_pid"; echo "--- work dir: $WOLFCERT_INTEROP_WORK"' EXIT + +fails=0 +checks=0 +pass() { checks=$((checks + 1)); echo "ok $1"; } +fail() { + checks=$((checks + 1)); fails=$((fails + 1)) + echo "FAIL $1" + [ -n "${2:-}" ] && [ -f "$2" ] && sed 's/^/ /' "$2" + return 0 +} + +# The fwTPM also binds TPM_PORT + 1 for its platform port. +free_port_pair() { + python3 -c ' +import socket +while True: + a = socket.socket(); a.bind(("127.0.0.1", 0)); p = a.getsockname()[1] + b = socket.socket() + try: + b.bind(("127.0.0.1", p + 1)) + except OSError: + a.close(); b.close(); continue + a.close(); b.close(); print(p); break +' +} + +TPM_PORT="$(free_port_pair)" +export TPM2_SWTPM_PORT="$TPM_PORT" + +# start_fwtpm [--clear]: without --clear a restart keeps the keys. +start_fwtpm() { + local dir="$1"; shift + mkdir -p "$dir" + (cd "$dir" && exec "$FWTPM" "$@" --port "$TPM_PORT" \ + --platform-port $((TPM_PORT + 1))) >>fwtpm.log 2>&1 & + fw_pid=$! + wait_port 127.0.0.1 "$TPM_PORT" +} + +stop_fwtpm() { + kill_if "$fw_pid" + fw_pid="" +} + +TRUST="$REPO/examples/certs/ecc/ca-cert.pem" +mkdir -m 0700 ca + +start_est() { + "$WC_SERVER" --proto est --listen "127.0.0.1:$EST_PORT" \ + --tls-cert "$REPO/examples/certs/ecc/server-cert.pem" \ + --tls-key "$REPO/examples/certs/ecc/server-key.pem" \ + --est-allow-anonymous --ca-dir ca --tls-trust-issued \ + >>est.log 2>&1 & + srv_pid=$! + wait_port 127.0.0.1 "$EST_PORT" + kill -0 "$srv_pid" 2>/dev/null || { cat est.log >&2; exit 1; } +} + +# ex : run the example, output to ; returns its status. +ex() { + local log="$1"; shift + "$EXAMPLE" "$@" >"$log" 2>&1 +} + +# The fwTPM keeps 8 persistent objects, so each key type gets its own NV. +run_type() { + local kt="$1" t="${1/:/-}" + local h0=0x81000100 h1=0x81000101 h2=0x81000102 + + start_fwtpm "tpm-$t" --clear + if ex "$t-enroll.log" enroll "$URL" "$TRUST" "CN=tpm-$t" "$kt" "$h0" "$t-0.crt" && + grep -q "BEGIN CERTIFICATE" "$t-0.crt"; then + pass "$kt: enroll at $h0" + else + fail "$kt: enroll at $h0" "$t-enroll.log" + stop_fwtpm + return 0 + fi + + if ! ex "$t-busy.log" enroll "$URL" "$TRUST" "CN=tpm-$t" "$kt" "$h0" "$t-x.crt" && + grep -q "needs a free persistent handle" "$t-busy.log"; then + pass "$kt: occupied handle refused" + else + fail "$kt: occupied handle refused" "$t-busy.log" + fi + + if ! ex "$t-dead.log" enroll "https://127.0.0.1:1/.well-known/est" "$TRUST" \ + "CN=tpm-$t" "$kt" "$h2" "$t-x.crt" && + ex "$t-after-dead.log" enroll "$URL" "$TRUST" "CN=tpm-$t" "$kt" "$h2" \ + "$t-2.crt"; then + pass "$kt: a failed enroll leaves the handle free" + else + fail "$kt: a failed enroll leaves the handle free" "$t-after-dead.log" + fi + + # Keys and CA survive a restart of both the fwTPM and the EST server. + stop_fwtpm + kill_if "$srv_pid"; srv_pid="" + start_fwtpm "tpm-$t" + start_est + + cp "$t-0.crt" "$t-before.crt" + if ex "$t-renew.log" reenroll "$URL" "$TRUST" "$kt" "$h0" "$t-0.crt" "$t-0.crt" && + ! cmp -s "$t-0.crt" "$t-before.crt" && + grep -q "BEGIN CERTIFICATE" "$t-0.crt" && [ ! -e "$t-0.crt.tmp" ]; then + pass "$kt: renew in place after a restart" + else + fail "$kt: renew in place after a restart" "$t-renew.log" + fi + + if ! ex "$t-ro.log" reenroll "$URL" "$TRUST" "$kt" "$h0" "$t-0.crt" notadir/x.crt "$h1" && + grep -q "revoke this certificate, its key is evicted" "$t-ro.log"; then + pass "$kt: unwritable rekey shows the certificate, evicts the new key" + else + fail "$kt: unwritable rekey shows the certificate, evicts the new key" "$t-ro.log" + fi + + if ex "$t-rekey.log" reenroll "$URL" "$TRUST" "$kt" "$h0" "$t-0.crt" "$t-1.crt" "$h1" && + grep -q "old key at TPM handle $h0 evicted" "$t-rekey.log"; then + pass "$kt: rekey to $h1 evicts $h0" + else + fail "$kt: rekey to $h1 evicts $h0" "$t-rekey.log" + fi + + if ! ex "$t-gone.log" reenroll "$URL" "$TRUST" "$kt" "$h0" "$t-0.crt" "$t-x.crt"; then + pass "$kt: the evicted key cannot renew" + else + fail "$kt: the evicted key cannot renew" "$t-gone.log" + fi + + if ex "$t-renew1.log" reenroll "$URL" "$TRUST" "$kt" "$h1" "$t-1.crt" "$t-1b.crt"; then + pass "$kt: the rotated key renews" + else + fail "$kt: the rotated key renews" "$t-renew1.log" + fi + + if ! ex "$t-down.log" reenroll "$URL" "$TRUST" "$kt" "$h1" "$t-1.crt" "$t-x.crt" \ + 0x80000000 && grep -q "NEW_HANDLE must be persistent" "$t-down.log"; then + pass "$kt: a persistent key does not rotate to a transient one" + else + fail "$kt: a persistent key does not rotate to a transient one" "$t-down.log" + fi + stop_fwtpm +} + +# A transient key lives until the fwTPM restarts; it has no resource manager. +run_transient() { + local kt="$1" t="${1/:/-}-tr" th + + start_fwtpm "tpm-$t" --clear + if ex "$t.log" enroll "$URL" "$TRUST" "CN=tpm-$t" "$kt" 0x80000000 "$t.crt"; then + th="$(sed -n 's/^enrolled: key in TPM handle \(0x[0-9a-f]*\),.*/\1/p' "$t.log")" + pass "$kt: enroll under 0x80000000 (got $th)" + if ex "$t-renew.log" reenroll "$URL" "$TRUST" "$kt" "$th" "$t.crt" "$t-2.crt"; then + pass "$kt: another process renews the transient key" + else + fail "$kt: another process renews the transient key" "$t-renew.log" + fi + else + fail "$kt: enroll under 0x80000000" "$t.log" + fi + if ! ex "$t-other.log" enroll "$URL" "$TRUST" "CN=tpm-$t" "$kt" 0x80000001 "$t-x.crt"; then + pass "$kt: a transient handle other than 0x80000000 is refused" + else + fail "$kt: a transient handle other than 0x80000000 is refused" "$t-other.log" + fi + stop_fwtpm +} + +# A write under a regular file fails even for root. +: >notadir +start_fwtpm tpm-probe --clear +# Picked while the fwTPM holds both of its ports. +EST_PORT="$(free_port)" +URL="https://127.0.0.1:$EST_PORT/.well-known/est" +stop_fwtpm +start_est + +for kt in $KEY_TYPES; do + run_type "$kt" +done +run_transient "${KEY_TYPES%% *}" + +echo "$checks checks, $fails failures" +[ "$fails" -eq 0 ] diff --git a/tests/unit/test_csr.c b/tests/unit/test_csr.c index ea088f72..454e4411 100644 --- a/tests/unit/test_csr.c +++ b/tests/unit/test_csr.c @@ -44,7 +44,7 @@ static int build_and_reparse(WolfCertKeyType kt, int param) { WolfCertKeyCfg cfg = { .type = kt, .param = param, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; REQUIRE(wolfcert_key_generate(&cfg, &key) == WOLFCERT_OK); @@ -112,7 +112,7 @@ static int ecc_sig_follows_curve(void) for (size_t i = 0; i < sizeof(want) / sizeof(want[0]); i++) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = want[i].param, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertBuffer der = { 0 }; DecodedCert dc; @@ -152,7 +152,7 @@ static int ecc_sig_follows_preferred_hash(void) #endif }; WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; int ret = 0; @@ -189,7 +189,7 @@ static int ecc_sig_follows_preferred_hash(void) static int build_with_extras(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; REQUIRE(wolfcert_key_generate(&cfg, &key) == WOLFCERT_OK); @@ -273,7 +273,7 @@ static int subject_copy_rejects_oversized_rdn(void) static int csr_build_rejects_oversized_rdn(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer der = { 0 }; @@ -314,7 +314,7 @@ static int csr_build_rejects_unprintable_rdn(void) "CN=dev,emailAddress=j\xc3\xbcrgen@example.de" }; WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer der = { 0 }; @@ -377,7 +377,7 @@ static int renewal_keeps_empty_subject(int san_crit) static const byte san[] = { 0x30, 0x0d, 0x82, 0x0b, 'd', 'e', 'v', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e' }; WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer csr = { 0 }; @@ -464,7 +464,7 @@ static const byte crit_ext_cert[] = { static int renewal_reads_past_unknown_critical_ext(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer csr = { 0 }; @@ -533,7 +533,7 @@ static const byte bmp_subject_cert[] = { static int renewal_refuses_bmpstring_subject(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer csr = { 0 }; @@ -552,7 +552,7 @@ static int renewal_refuses_bmpstring_subject(void) static int renewal_drops_callback_san(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer csr = { 0 }; @@ -590,7 +590,7 @@ static int renewal_drops_callback_san(void) static int renewal_walks_extensions_without_san(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer csr = { 0 }; @@ -626,7 +626,7 @@ static int renewal_walks_extensions_without_san(void) static int renewal_rejects_non_certificate(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer key_pem = { 0 }; @@ -649,7 +649,7 @@ static int renewal_rejects_meta_identity(void) { static const char* const one[] = { "x" }; WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta; WolfCertBuffer csr = { 0 }; @@ -710,7 +710,7 @@ static int count_csr_sans(const WolfCertBuffer* csr) static int csr_carries_large_san(void) { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; char names[LARGE_SAN_COUNT][40]; const char* dns[LARGE_SAN_COUNT]; WolfCertKey* key = NULL; @@ -919,7 +919,7 @@ static int renewal_size_limits(void) const word32 name_max = (word32)sizeof(((Cert*)NULL)->sbjRaw) - 1; const word32 san_max = (word32)sizeof(((Cert*)NULL)->altNames); WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* key = NULL; WolfCertCertMeta meta = { 0 }; WolfCertBuffer csr = { 0 }; diff --git a/tests/unit/test_est.c b/tests/unit/test_est.c index d5b11a80..7c460f2b 100644 --- a/tests/unit/test_est.c +++ b/tests/unit/test_est.c @@ -291,7 +291,7 @@ static int test_est_require_server_auth(void) WolfCertEstResult res = { 0 }; WolfCertEstSession* sess = NULL; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* rk = NULL; /* Each call gets ERR_TLS, even simple_enroll with a placeholder CSR. */ @@ -372,7 +372,7 @@ static int test_est_rejects_scep_cfg(void) WolfCertEstResult res = { 0 }; WolfCertEstSession* sess = NULL; WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* rk = NULL; REQUIRE(wolfcert_est_get_cacerts(&srv, WOLFCERT_ENCODING_PEM, @@ -449,10 +449,10 @@ static int test_est_result_defined_on_early_return(void) WolfCertKey* key = NULL; #ifdef WOLFCERT_HAVE_RSA WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_RSA, .param = 2048, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; #else WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; #endif REQUIRE(wolfcert_key_generate(&kcfg, &key) == WOLFCERT_OK); @@ -709,7 +709,7 @@ int main(void) wolfcert_buffer_free(&ca_pem); WolfCertKeyCfg kcfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* dk = NULL; REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); WolfCertCertMeta meta = { .subject_dn = "CN=device-99" }; diff --git a/tests/unit/test_http.c b/tests/unit/test_http.c index 34f9d3f8..1b078fd3 100644 --- a/tests/unit/test_http.c +++ b/tests/unit/test_http.c @@ -1205,12 +1205,57 @@ static int test_chunked_complete_resume(void) return 0; } +/* A client_key_obj is checked before any connection. */ +static int test_client_key_checks(void) +{ + static const uint8_t cert[] = "-----BEGIN CERTIFICATE-----"; + static const uint8_t pem[] = "-----BEGIN PRIVATE KEY-----"; + WolfCertKey key; + WolfCertHttpRequest req = { + .method = "GET", + .url = "https://127.0.0.1:1/x", + .client_key_obj = &key, + }; + WolfCertHttpSessionCfg scfg = { + .base_url = "https://127.0.0.1:1", + .client_key_obj = &key, + }; + WolfCertHttpResponse resp; + WolfCertHttpSession* s = NULL; + + memset(&key, 0, sizeof(key)); + REQUIRE(wolfcert_http_request(&req, &resp) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(strstr(wolfcert_last_error_message(), "client_cert") != NULL); + REQUIRE(wolfcert_http_session_open(&scfg, &s) == WOLFCERT_ERR_BAD_ARG); + scfg.client_cert = cert; + scfg.client_cert_len = sizeof(cert); + scfg.client_key = pem; + scfg.client_key_len = sizeof(pem); + REQUIRE(wolfcert_http_session_open(&scfg, &s) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(strstr(wolfcert_last_error_message(), "not both") != NULL); + scfg.client_key = NULL; + scfg.client_key_len = 0; + scfg.base_url = "http://127.0.0.1:1"; + REQUIRE(wolfcert_http_session_open(&scfg, &s) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(strstr(wolfcert_last_error_message(), "https://") != NULL); + REQUIRE(s == NULL); + + req.client_cert = cert; + req.client_cert_len = sizeof(cert); + req.client_key = pem; + req.client_key_len = sizeof(pem); + REQUIRE(wolfcert_http_request(&req, &resp) == WOLFCERT_ERR_BAD_ARG); + return 0; +} + int main(void) { /* make check has no per-test timeout, and a framing bug shows as a hang. */ alarm(25); REQUIRE(wolfcert_init(NULL) == WOLFCERT_OK); + /* A WC_USE_DEVID build starts on a device; these checks expect none. */ + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); if (test_url_parser()) return 1; #ifdef WOLFCERT_HAVE_SERVER @@ -1293,6 +1338,8 @@ int main(void) return 1; if (test_chunked_uppercase_hex_size()) return 1; + if (test_client_key_checks()) + return 1; wolfcert_cleanup(); printf("OK\n"); return 0; diff --git a/tests/unit/test_keygen.c b/tests/unit/test_keygen.c index 91bd68a8..f10d6115 100644 --- a/tests/unit/test_keygen.c +++ b/tests/unit/test_keygen.c @@ -18,11 +18,26 @@ */ #include +#include "internal.h" #include "../test_static_mem.h" +#include +#include + #include #include +#if defined(WOLFCERT_HAVE_ECC) + #define TEST_KEY_TYPE WOLFCERT_KEY_ECC + #define TEST_KEY_PARAM 256 +#elif defined(WOLFCERT_HAVE_RSA) + #define TEST_KEY_TYPE WOLFCERT_KEY_RSA + #define TEST_KEY_PARAM 2048 +#elif defined(WOLFCERT_HAVE_MLDSA) && !defined(WOLFSSL_NO_ML_DSA_65) + #define TEST_KEY_TYPE WOLFCERT_KEY_MLDSA65 + #define TEST_KEY_PARAM 0 +#endif + #define REQUIRE(cond) \ do { \ if (!(cond)) { \ @@ -34,7 +49,7 @@ static int roundtrip(WolfCertKeyType type, int param) { WolfCertKeyCfg cfg = { .type = type, .param = param, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* k = NULL; REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_OK); REQUIRE(k != NULL); @@ -58,6 +73,11 @@ static int roundtrip(WolfCertKeyType type, int param) REQUIRE(wolfcert_key_from_pem(der.data, der.len, NULL, &k3) == WOLFCERT_OK); REQUIRE(k3 != NULL); + const uint8_t* id = (const uint8_t*)"x"; + size_t id_len = 1; + REQUIRE(wolfcert_key_id(k, &id, &id_len) == WOLFCERT_OK); + REQUIRE(id == NULL && id_len == 0); + wolfcert_buffer_free(&pem); wolfcert_buffer_free(&der); wolfcert_key_free(k); @@ -66,10 +86,325 @@ static int roundtrip(WolfCertKeyType type, int param) return 0; } +#ifdef TEST_KEY_TYPE +#define DECLINE_DEVID 0x6b69 + +#ifdef WOLF_CRYPTO_CB +static int decline_cb(int devId, wc_CryptoInfo* info, void* ctx) +{ + (void)devId; + (void)info; + (void)ctx; + return CRYPTOCB_UNAVAILABLE; +} +#endif + +#if defined(WOLF_CRYPTO_CB) && defined(WOLF_PRIVATE_KEY_ID) + +/* A device that declines keygen leaves wolfCrypt to generate in software, + * which a key_id must refuse. */ +static int key_id_declined(WolfCertKeyType type, int param) +{ + static const uint8_t id[] = { 0x01, 0x02 }; + WolfCertKeyCfg cfg = { .type = type, .param = param, + .dev_id = DECLINE_DEVID, + .key_id = id, .key_id_len = sizeof(id) }; + WolfCertKey* k = NULL; + + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(k == NULL); + return 0; +} + +#ifdef WOLFCERT_HAVE_ECC +#define RENAME_DEVID 0x726e +static const uint8_t renamed_id[] = { 0x52, 0x45, 0x4e }; + +/* Keeps only the public point of a software key and renames the key, or + * clears its id when ctx is set. */ +static int rename_cb(int devId, wc_CryptoInfo* info, void* ctx) +{ + ecc_key tmp; + byte pub[1 + 2 * MAX_ECC_BYTES]; + word32 pub_len = sizeof(pub); + int rc; + + (void)devId; + if (info->algo_type != WC_ALGO_TYPE_PK || + info->pk.type != WC_PK_TYPE_EC_KEYGEN) + return CRYPTOCB_UNAVAILABLE; + + rc = wc_ecc_init_ex(&tmp, NULL, INVALID_DEVID); + if (rc != 0) + return rc; + rc = wc_ecc_make_key_ex(info->pk.eckg.rng, info->pk.eckg.size, &tmp, + info->pk.eckg.curveId); + if (rc == 0) + rc = wc_ecc_export_x963(&tmp, pub, &pub_len); + if (rc == 0) + rc = wc_ecc_import_x963_ex(pub, pub_len, info->pk.eckg.key, + info->pk.eckg.curveId); + wc_ecc_free(&tmp); + if (rc == 0 && ctx != NULL) + info->pk.eckg.key->idLen = 0; + else if (rc == 0) { + memcpy(info->pk.eckg.key->id, renamed_id, sizeof(renamed_id)); + info->pk.eckg.key->idLen = (int)sizeof(renamed_id); + } + return rc; +} + +/* The id a device gives the key it generates replaces the requested one. */ +static int key_id_renamed(void) +{ + static const uint8_t id[] = { 0x01, 0x02 }; + WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, + .dev_id = RENAME_DEVID, + .key_id = id, .key_id_len = sizeof(id) }; + WolfCertKey* k = NULL; + const uint8_t* got = NULL; + size_t got_len = 0; + + REQUIRE(wc_CryptoCb_RegisterDevice(RENAME_DEVID, rename_cb, NULL) == 0); + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_OK); + REQUIRE(wolfcert_key_id(k, &got, &got_len) == WOLFCERT_OK); + REQUIRE(got_len == sizeof(renamed_id)); + REQUIRE(memcmp(got, renamed_id, sizeof(renamed_id)) == 0); + wolfcert_key_free(k); + wc_CryptoCb_UnRegisterDevice(RENAME_DEVID); + + /* A device that leaves no id still hands out the key, under the + * requested id. */ + k = NULL; + REQUIRE(wc_CryptoCb_RegisterDevice(RENAME_DEVID, rename_cb, + (void*)id) == 0); + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_CRYPTO); + REQUIRE(k != NULL); + REQUIRE(wolfcert_key_id(k, &got, &got_len) == WOLFCERT_OK); + REQUIRE(got_len == sizeof(id) && memcmp(got, id, sizeof(id)) == 0); + wolfcert_key_free(k); + wc_CryptoCb_UnRegisterDevice(RENAME_DEVID); + return 0; +} +#endif + +static int key_id_cases(void) +{ + static const uint8_t id[] = { 0x01, 0x02 }; + static const uint8_t junk[] = { 0x30, 0x03, 0x02, 0x01, 0x00 }; + WolfCertKey* k = NULL; + +#ifdef WOLFCERT_HAVE_ECC + if (key_id_renamed()) + return 1; +#endif + REQUIRE(wc_CryptoCb_RegisterDevice(DECLINE_DEVID, decline_cb, NULL) == 0); + WolfCertKeyCfg cfg = { .type = TEST_KEY_TYPE, .param = TEST_KEY_PARAM, + .dev_id = INVALID_DEVID, + .key_id = id, .key_id_len = sizeof(id) }; + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_BAD_ARG); + cfg.dev_id = DECLINE_DEVID; + cfg.key_id_len = 0; + k = (WolfCertKey*)&cfg; + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(strstr(wolfcert_last_error_message(), "key_id_len") != NULL); + REQUIRE(k == NULL); + cfg.dev_id = INVALID_DEVID; + cfg.key_id_len = sizeof(id); + + if (key_id_declined(TEST_KEY_TYPE, TEST_KEY_PARAM)) + return 1; +#ifdef WOLFCERT_HAVE_RSA + if (key_id_declined(WOLFCERT_KEY_RSA, 2048)) + return 1; +#endif +#ifdef WOLFCERT_HAVE_MLDSA +#ifndef WOLFSSL_NO_ML_DSA_44 + if (key_id_declined(WOLFCERT_KEY_MLDSA44, 0)) + return 1; +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + if (key_id_declined(WOLFCERT_KEY_MLDSA65, 0)) + return 1; +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + if (key_id_declined(WOLFCERT_KEY_MLDSA87, 0)) + return 1; +#endif +#endif +#if defined(WOLFCERT_HAVE_ED25519) && defined(ED25519_MAX_ID_LEN) + if (key_id_declined(WOLFCERT_KEY_ED25519, 0)) + return 1; +#endif + + cfg.dev_id = DECLINE_DEVID; + cfg.key_id_len = 0; + REQUIRE(wolfcert_key_from_id(&cfg, junk, sizeof(junk), &k) == + WOLFCERT_ERR_BAD_ARG); + k = (WolfCertKey*)&cfg; + REQUIRE(wolfcert_key_from_id(&cfg, NULL, 0, &k) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(k == NULL); + cfg.key_id_len = sizeof(id); + REQUIRE(wolfcert_key_from_id(&cfg, junk, sizeof(junk), &k) == + WOLFCERT_ERR_PARSE); +#ifdef WOLFCERT_HAVE_RSA + /* Even with param 0, a reload refuses an RSA size keygen would not make. */ + { + static const uint8_t weak[] = { + 0x30, 0x82, 0x01, 0xf7, 0x30, 0x82, 0x01, 0x60, 0xa0, 0x03, 0x02, + 0x01, 0x02, 0x02, 0x14, 0x59, 0x46, 0x07, 0x05, 0xaa, 0x88, 0x4f, + 0xba, 0x81, 0x5e, 0xee, 0x36, 0x6e, 0xf3, 0x66, 0xd2, 0x9f, 0x0d, + 0x68, 0x8f, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, + 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, 0x0f, 0x31, 0x0d, 0x30, + 0x0b, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x04, 0x77, 0x65, 0x61, + 0x6b, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x36, 0x31, 0x30, 0x31, 0x37, + 0x31, 0x32, 0x31, 0x36, 0x31, 0x39, 0x5a, 0x17, 0x0d, 0x33, 0x36, + 0x31, 0x30, 0x31, 0x34, 0x31, 0x32, 0x31, 0x36, 0x31, 0x39, 0x5a, + 0x30, 0x0f, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x03, + 0x0c, 0x04, 0x77, 0x65, 0x61, 0x6b, 0x30, 0x81, 0x9f, 0x30, 0x0d, + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, + 0x05, 0x00, 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, + 0x81, 0x00, 0xd6, 0x71, 0xd3, 0xa4, 0x94, 0x12, 0x9e, 0x33, 0x9c, + 0x3e, 0x4c, 0x0f, 0xd0, 0xe1, 0x90, 0xd0, 0x25, 0x95, 0x19, 0x34, + 0x96, 0x6e, 0x97, 0x0b, 0x48, 0x21, 0x0f, 0x26, 0xb4, 0x03, 0x92, + 0xb6, 0x99, 0xe7, 0xe7, 0x7a, 0xe5, 0x73, 0x8d, 0x37, 0x54, 0xf9, + 0x8c, 0xe0, 0x1d, 0x0e, 0xae, 0x63, 0x80, 0x72, 0x4a, 0xb9, 0x94, + 0xef, 0x82, 0x30, 0x70, 0xda, 0xce, 0x85, 0x52, 0x0b, 0x75, 0x18, + 0xb9, 0x4d, 0xcb, 0xc0, 0x30, 0x69, 0x06, 0xcb, 0x9d, 0x03, 0x5c, + 0xe0, 0x6c, 0xf9, 0xe8, 0x6d, 0x08, 0xe8, 0xb2, 0xb7, 0x60, 0x31, + 0xc3, 0xfc, 0x2c, 0x01, 0xb7, 0xaf, 0x10, 0xaa, 0xe2, 0x89, 0xcb, + 0xad, 0xa9, 0xa0, 0xcf, 0x68, 0x8e, 0xa6, 0x36, 0xcd, 0xdc, 0x16, + 0xc8, 0x59, 0xad, 0x38, 0x5e, 0xc1, 0x9f, 0xdb, 0xa4, 0x6a, 0xa6, + 0x43, 0x2d, 0x94, 0xe1, 0xcf, 0xd2, 0x71, 0x59, 0x93, 0x02, 0x03, + 0x01, 0x00, 0x01, 0xa3, 0x50, 0x30, 0x4e, 0x30, 0x1d, 0x06, 0x03, + 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0xa8, 0xc9, 0xf0, 0x7b, + 0x4e, 0x72, 0x2d, 0x7a, 0xb7, 0x51, 0x48, 0x2d, 0x6e, 0x34, 0x92, + 0xc9, 0x10, 0x74, 0x3c, 0x9b, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, + 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xa8, 0xc9, 0xf0, 0x7b, + 0x4e, 0x72, 0x2d, 0x7a, 0xb7, 0x51, 0x48, 0x2d, 0x6e, 0x34, 0x92, + 0xc9, 0x10, 0x74, 0x3c, 0x9b, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, + 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00, 0x30, 0x0d, 0x06, + 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, + 0x00, 0x03, 0x81, 0x81, 0x00, 0x34, 0xaa, 0x11, 0x9e, 0x41, 0x4a, + 0x5e, 0x86, 0x2e, 0xae, 0x14, 0x37, 0xf8, 0xfa, 0x0b, 0x05, 0x5b, + 0x46, 0x31, 0x08, 0xef, 0xae, 0x6d, 0xd2, 0x23, 0xc0, 0xb6, 0xb8, + 0xb7, 0x63, 0x68, 0x26, 0x33, 0x04, 0x72, 0xab, 0x98, 0x4a, 0xb8, + 0xad, 0x86, 0xef, 0xc3, 0xdf, 0x5a, 0x7b, 0x00, 0x87, 0x8e, 0xf2, + 0x8f, 0x97, 0x19, 0x62, 0x4b, 0xda, 0x36, 0xdc, 0x31, 0x79, 0xf9, + 0x45, 0x1d, 0x7d, 0xbe, 0xc7, 0x51, 0xff, 0xd2, 0xd6, 0x73, 0xd3, + 0x88, 0x0b, 0x54, 0x6c, 0x2f, 0xb9, 0xe1, 0x08, 0xe9, 0x0e, 0x4e, + 0xe8, 0xba, 0x9c, 0x04, 0x74, 0x37, 0x6f, 0x49, 0x73, 0x1d, 0x21, + 0x02, 0xa7, 0x67, 0x11, 0x1a, 0x85, 0x01, 0x88, 0x2a, 0x40, 0x32, + 0x6f, 0x12, 0x3c, 0x68, 0xa9, 0xe6, 0x40, 0x4e, 0xa2, 0x4a, 0x8a, + 0x2f, 0xed, 0x8d, 0x8e, 0xac, 0xbc, 0xee, 0xf3, 0x1f, 0xe8, 0x54, + 0x97, + }; + WolfCertKeyCfg rcfg = { .type = WOLFCERT_KEY_RSA, + .dev_id = DECLINE_DEVID, + .key_id = id, .key_id_len = sizeof(id) }; + + REQUIRE(wolfcert_key_from_id(&rcfg, weak, sizeof(weak), &k) == + WOLFCERT_ERR_UNSUPPORTED); +#ifdef WOLFCERT_HAVE_ECC + rcfg.type = WOLFCERT_KEY_ECC; + REQUIRE(wolfcert_key_from_id(&rcfg, weak, sizeof(weak), &k) == + WOLFCERT_ERR_PARSE); + REQUIRE(strstr(wolfcert_last_error_message(), "not a type") != NULL); +#endif + } +#endif +#ifdef WOLFCERT_HAVE_ECC + /* Likewise a curve keygen does not make: a P-224 certificate. */ + { + static const uint8_t p224[] = { + 0x30, 0x82, 0x01, 0x5f, 0x30, 0x82, 0x01, 0x0e, 0xa0, 0x03, 0x02, + 0x01, 0x02, 0x02, 0x14, 0x3d, 0xf5, 0x24, 0x44, 0x39, 0x0d, 0xf6, + 0x77, 0xeb, 0xd4, 0x87, 0x95, 0x79, 0x98, 0xc5, 0xd2, 0x06, 0xb7, + 0xdb, 0x94, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, + 0x04, 0x03, 0x02, 0x30, 0x0f, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, + 0x55, 0x04, 0x03, 0x0c, 0x04, 0x70, 0x32, 0x32, 0x34, 0x30, 0x1e, + 0x17, 0x0d, 0x32, 0x36, 0x31, 0x30, 0x31, 0x37, 0x31, 0x34, 0x30, + 0x36, 0x33, 0x32, 0x5a, 0x17, 0x0d, 0x33, 0x36, 0x31, 0x30, 0x31, + 0x34, 0x31, 0x34, 0x30, 0x36, 0x33, 0x32, 0x5a, 0x30, 0x0f, 0x31, + 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x04, 0x70, + 0x32, 0x32, 0x34, 0x30, 0x4e, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, + 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, + 0x21, 0x03, 0x3a, 0x00, 0x04, 0xe8, 0x66, 0x0e, 0x19, 0x35, 0xc9, + 0x09, 0x98, 0xb2, 0x14, 0x18, 0x2a, 0xb8, 0x7b, 0x4e, 0x2b, 0x89, + 0xea, 0x78, 0x54, 0x01, 0xc4, 0x25, 0xb2, 0x10, 0x52, 0xed, 0x26, + 0x22, 0x4a, 0x23, 0x42, 0x6e, 0x2d, 0x9f, 0x50, 0x37, 0xfc, 0xf4, + 0x2a, 0x94, 0x43, 0xf1, 0x28, 0xee, 0x44, 0xff, 0x6f, 0x92, 0xa7, + 0xab, 0xb5, 0xdb, 0x52, 0x36, 0x26, 0xa3, 0x53, 0x30, 0x51, 0x30, + 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x03, + 0x45, 0x74, 0x20, 0xc9, 0xc6, 0xc6, 0xdd, 0x0f, 0xe5, 0x17, 0xbf, + 0x61, 0xe3, 0xbc, 0x21, 0xce, 0x0a, 0x31, 0xc8, 0x30, 0x1f, 0x06, + 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x03, + 0x45, 0x74, 0x20, 0xc9, 0xc6, 0xc6, 0xdd, 0x0f, 0xe5, 0x17, 0xbf, + 0x61, 0xe3, 0xbc, 0x21, 0xce, 0x0a, 0x31, 0xc8, 0x30, 0x0f, 0x06, + 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, + 0x01, 0x01, 0xff, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, + 0x3d, 0x04, 0x03, 0x02, 0x03, 0x3f, 0x00, 0x30, 0x3c, 0x02, 0x1c, + 0x51, 0xad, 0x29, 0x59, 0x0b, 0x12, 0x22, 0x51, 0x76, 0x60, 0x02, + 0x26, 0x53, 0xb6, 0xd8, 0x46, 0xa8, 0xda, 0x06, 0x60, 0x6e, 0x67, + 0x4e, 0x71, 0xbe, 0x1c, 0xb0, 0x36, 0x02, 0x1c, 0x0c, 0x7b, 0x06, + 0x77, 0xf6, 0x9a, 0xed, 0xc0, 0x31, 0x92, 0x8c, 0x5e, 0x84, 0xb3, + 0x6f, 0xb1, 0x65, 0x2a, 0xe4, 0x4a, 0x89, 0x65, 0x3e, 0x16, 0x3f, + 0xb8, 0x05, 0x99, + }; + WolfCertKeyCfg ecfg = { .type = WOLFCERT_KEY_ECC, + .dev_id = DECLINE_DEVID, + .key_id = id, .key_id_len = sizeof(id) }; + int erc = wolfcert_key_from_id(&ecfg, p224, sizeof(p224), &k); + +#if (defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES)) && ECC_MIN_KEY_SZ <= 224 + REQUIRE(erc == WOLFCERT_ERR_UNSUPPORTED); +#else + REQUIRE(erc == WOLFCERT_ERR_PARSE); +#endif + } +#endif +#if defined(WOLFCERT_HAVE_ED25519) && !defined(ED25519_MAX_ID_LEN) + cfg.type = WOLFCERT_KEY_ED25519; + cfg.param = 0; + REQUIRE(wolfcert_key_from_id(&cfg, junk, sizeof(junk), &k) == + WOLFCERT_ERR_UNSUPPORTED); +#endif + REQUIRE(k == NULL); + + wc_CryptoCb_UnRegisterDevice(DECLINE_DEVID); + return 0; +} +#else +static int key_id_cases(void) +{ + static const uint8_t id[] = { 0x01, 0x02 }; + static const uint8_t junk[] = { 0x30, 0x03, 0x02, 0x01, 0x00 }; + WolfCertKeyCfg cfg = { .type = TEST_KEY_TYPE, .param = TEST_KEY_PARAM, + .dev_id = DECLINE_DEVID, + .key_id = id, .key_id_len = sizeof(id) }; + WolfCertKey* k = NULL; + +#ifdef WOLF_CRYPTO_CB + REQUIRE(wc_CryptoCb_RegisterDevice(DECLINE_DEVID, decline_cb, NULL) == 0); +#endif + REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(wolfcert_key_from_id(&cfg, junk, sizeof(junk), &k) == + WOLFCERT_ERR_UNSUPPORTED); + REQUIRE(k == NULL); +#ifdef WOLF_CRYPTO_CB + wc_CryptoCb_UnRegisterDevice(DECLINE_DEVID); +#endif + return 0; +} +#endif +#endif /* TEST_KEY_TYPE */ + int main(void) { REQUIRE(test_static_mem_init() == 0); REQUIRE(wolfcert_init(test_heap_hint()) == WOLFCERT_OK); + /* A WC_USE_DEVID build starts on a device; these checks expect none. */ + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); #ifdef WOLFCERT_HAVE_ECC if (roundtrip(WOLFCERT_KEY_ECC, 256)) return 1; @@ -105,16 +440,29 @@ int main(void) /* Runtime rejection when the wolfSSL build lacks Dilithium. */ { WolfCertKeyCfg cfg = { .type = WOLFCERT_KEY_MLDSA44, .param = 0, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* k = NULL; REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_ERR_UNSUPPORTED); } #endif +#ifdef TEST_KEY_TYPE + if (key_id_cases()) + return 1; +#endif + WolfCertKeyCfg bad = { .type = WOLFCERT_KEY_ECC, .param = 123, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertKey* k = NULL; REQUIRE(wolfcert_key_generate(&bad, &k) != WOLFCERT_OK); + REQUIRE(wolfcert_key_dev_id(NULL) == INVALID_DEVID); + k = (WolfCertKey*)&bad; + REQUIRE(wolfcert_key_generate(NULL, &k) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(k == NULL); +#ifndef WOLF_CRYPTO_CB + REQUIRE(wolfcert_set_default_dev_id(7) == WOLFCERT_ERR_UNSUPPORTED); +#endif + REQUIRE(wolfcert_set_default_dev_id(INVALID_DEVID) == WOLFCERT_OK); wolfcert_cleanup(); printf("OK\n"); diff --git a/tests/unit/test_parse_negative.c b/tests/unit/test_parse_negative.c index e4c4352f..be80bfc2 100644 --- a/tests/unit/test_parse_negative.c +++ b/tests/unit/test_parse_negative.c @@ -163,10 +163,10 @@ static int test_scep_envelop_alg(void) REQUIRE(csr_len > 0); REQUIRE(wolfcert_scep_self_signed_rsa(&key, csr_der, (size_t)csr_len, - &ra_der, &ra_len, NULL) == WOLFCERT_OK); + &ra_der, &ra_len, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(wolfcert_scep_envelop(ra_der, ra_len, payload, sizeof(payload), - AES128CBCb, &env, NULL) == WOLFCERT_OK); + AES128CBCb, &env, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(oid_present(env.data, env.len, OID_AES128_CBC, sizeof(OID_AES128_CBC))); @@ -177,7 +177,7 @@ static int test_scep_envelop_alg(void) #ifndef NO_DES3 REQUIRE(wolfcert_scep_envelop(ra_der, ra_len, payload, sizeof(payload), - DES3b, &env, NULL) == WOLFCERT_OK); + DES3b, &env, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(oid_present(env.data, env.len, OID_DES3_CBC, sizeof(OID_DES3_CBC))); diff --git a/tests/unit/test_scep_msg.c b/tests/unit/test_scep_msg.c index 28f65102..51c33b39 100644 --- a/tests/unit/test_scep_msg.c +++ b/tests/unit/test_scep_msg.c @@ -351,12 +351,14 @@ static int test_envelop_rejects_ecc_ra(void) if (made_ecc == 0) { ecc_rc = wolfcert_scep_envelop(ecc_ca, ecc_ca_len, payload, sizeof(payload), AES128CBCb, &ecc_env, + INVALID_DEVID, NULL); ecc_env_empty = (ecc_env.data == NULL); } if (made_rsa == 0) { rsa_rc = wolfcert_scep_envelop(rsa_ca, rsa_ca_len, payload, sizeof(payload), AES128CBCb, &rsa_env, + INVALID_DEVID, NULL); rsa_env_ok = (rsa_env.data != NULL && rsa_env.len > 0); } @@ -422,14 +424,14 @@ static int check_no_envelope(const uint8_t* ca_der, size_t ca_len, REQUIRE(wolfcert_scep_build_pki_message(NULL, 0, ca_der, ca_len, key_der, key_len, hash_oid, - &attrs, &pki, NULL) == WOLFCERT_OK); + &attrs, &pki, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(memmem(pki.data, pki.len, ENVELOPED_OID, sizeof(ENVELOPED_OID)) == NULL); prc = wolfcert_scep_parse_pki_message(pki.data, pki.len, &env, &rx_tid, &rx_tid_len, &rx_sn, &rx_sn_len, &rx_rn, &rx_rn_len, - &mt, &status, NULL, NULL, &rx_fi, NULL); + &mt, &status, NULL, NULL, &rx_fi, INVALID_DEVID, NULL); /* Free the parsed outputs before the REQUIREs so a failure cannot leak. */ env_ok = (env.len == 0 && env.data == NULL); status_ok = (status != NULL && strcmp(status, "2") == 0); @@ -512,11 +514,11 @@ static int test_long_transaction_id(void) brc = wolfcert_scep_build_pki_message(NULL, 0, ca_der, ca_len, key_der, key_len, SHA256h, - &attrs, &pki, NULL); + &attrs, &pki, INVALID_DEVID, NULL); if (brc == WOLFCERT_OK) prc = wolfcert_scep_parse_pki_message(pki.data, pki.len, &env, &rx_tid, &rx_tid_len, &rx_sn, &rx_sn_len, NULL, NULL, - &mt, &status, NULL, NULL, NULL, NULL); + &mt, &status, NULL, NULL, NULL, INVALID_DEVID, NULL); else prc = brc; @@ -608,7 +610,7 @@ static int test_signer_subject_matches_csr(void) &csr_der, &csr_len) == 0); REQUIRE(wolfcert_scep_self_signed_rsa(&key, csr_der, csr_len, - &signer_der, &signer_len, NULL) + &signer_der, &signer_len, INVALID_DEVID, NULL) == WOLFCERT_OK); wc_InitDecodedCert(&csr_dc, csr_der, (word32)csr_len, NULL); @@ -656,7 +658,7 @@ static int test_signer_key_usage(void) &csr_der, &csr_len) == 0); REQUIRE(wolfcert_scep_self_signed_rsa(&key, csr_der, csr_len, - &signer_der, &signer_len, NULL) + &signer_der, &signer_len, INVALID_DEVID, NULL) == WOLFCERT_OK); wc_InitDecodedCert(&dc, signer_der, (word32)signer_len, NULL); @@ -1520,7 +1522,7 @@ static int test_next_ca_response_is_signed(void) /* OK proves a signature; the parser refuses degenerate SignedData. */ rc = wolfcert_scep_parse_pki_message(resp.data, resp.len, &content, - NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, INVALID_DEVID, NULL); REQUIRE(rc == WOLFCERT_OK); REQUIRE(content.data != NULL && content.len > 0); @@ -1692,7 +1694,7 @@ static int test_signer_is_verified_cert(void) REQUIRE(wolfcert_scep_parse_pki_message(msg, msg_len, &env, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, - &signer, &signer_len, NULL, NULL) == WOLFCERT_OK); + &signer, &signer_len, NULL, INVALID_DEVID, NULL) == WOLFCERT_OK); /* The parser reports the cert that signed. */ REQUIRE(signer != NULL); @@ -1786,7 +1788,7 @@ static int test_signer_subject_fallback(void) REQUIRE(make_csr(&key, &rng, "", "", &csr, &csr_len) == 0); REQUIRE(wolfcert_scep_self_signed_rsa(&key, csr, csr_len, - &signer, &signer_len, NULL) + &signer, &signer_len, INVALID_DEVID, NULL) == WOLFCERT_OK); wc_InitDecodedCert(&dc, signer, (word32)signer_len, NULL); @@ -2124,7 +2126,7 @@ static int test_envelop_cipher_oid(void) #if defined(WOLFSSL_AES_256) WolfCertBuffer env256 = { 0 }; REQUIRE(wolfcert_scep_envelop(ca_der, ca_len, payload, sizeof(payload), - AES256CBCb, &env256, NULL) == WOLFCERT_OK); + AES256CBCb, &env256, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(memmem(env256.data, env256.len, OID_AES256, sizeof(OID_AES256)) != NULL); REQUIRE(memmem(env256.data, env256.len, OID_AES128, sizeof(OID_AES128)) == NULL); wolfcert_buffer_free(&env256); @@ -2132,7 +2134,7 @@ static int test_envelop_cipher_oid(void) WolfCertBuffer env128 = { 0 }; REQUIRE(wolfcert_scep_envelop(ca_der, ca_len, payload, sizeof(payload), - AES128CBCb, &env128, NULL) == WOLFCERT_OK); + AES128CBCb, &env128, INVALID_DEVID, NULL) == WOLFCERT_OK); REQUIRE(memmem(env128.data, env128.len, OID_AES128, sizeof(OID_AES128)) != NULL); wolfcert_buffer_free(&env128); @@ -2300,7 +2302,7 @@ static int test_duplicate_signed_attrib(void) /* Every output is requested so each can be checked after the reject. */ rc = wolfcert_scep_parse_pki_message(msg, msg_len, &env, &tid, &tid_len, &snonce, &snonce_len, &rnonce, &rnonce_len, - &mt, &ps, &signer, &signer_len, &fi, NULL); + &mt, &ps, &signer, &signer_len, &fi, INVALID_DEVID, NULL); if (rc != WOLFCERT_ERR_PROTOCOL) { fprintf(stderr, "duplicate transactionID accepted: rc=%d tid=%.*s\n", rc, (int)tid_len, tid == NULL ? "" : (const char*)tid); @@ -2366,7 +2368,7 @@ static int test_multi_value_signed_attrib(void) rc = wolfcert_scep_parse_pki_message(msg, msg_len, &env, &tid, &tid_len, &snonce, &snonce_len, &rnonce, &rnonce_len, - &mt, &ps, &signer, &signer_len, &fi, NULL); + &mt, &ps, &signer, &signer_len, &fi, INVALID_DEVID, NULL); if (rc != WOLFCERT_ERR_PROTOCOL) { fprintf(stderr, "multi-valued transactionID accepted: rc=%d tid=%.*s\n", rc, (int)tid_len, tid == NULL ? "" : (const char*)tid); @@ -2430,7 +2432,7 @@ static int check_text_attrib(const uint8_t* ca_der, size_t ca_len, wolfcert_clear_error(); rc = wolfcert_scep_parse_pki_message(msg, msg_len, &env, NULL, NULL, NULL, NULL, NULL, NULL, - &mt, &ps, NULL, NULL, &fi, NULL); + &mt, &ps, NULL, NULL, &fi, INVALID_DEVID, NULL); got = mt != NULL ? mt : (ps != NULL ? ps : fi); if (expect_rc == WOLFCERT_OK) @@ -2885,7 +2887,7 @@ static int test_parse_reports_oom(void) REQUIRE(oom_arm(fails) == 0); rc = wolfcert_scep_parse_pki_message(msg, msg_len, &env, &t, &t_len, NULL, NULL, NULL, NULL, &mt, NULL, &signer, &signer_len, - NULL, NULL); + NULL, INVALID_DEVID, NULL); REQUIRE((failed = oom_disarm()) >= 0); /* wolfSSL's PKCS#7 verify can report a failed allocation as a parse * error, so only wolfCert's own allocations must give ERR_MEMORY. */ diff --git a/tests/unit/test_server_ca.c b/tests/unit/test_server_ca.c new file mode 100644 index 00000000..1c404a04 --- /dev/null +++ b/tests/unit/test_server_ca.c @@ -0,0 +1,1012 @@ +/* + * Copyright (C) 2026 wolfSSL Inc. + * + * This file is part of wolfCert. + * + * wolfCert 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. + * + * wolfCert 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 wolfCert. If not, see . + */ + +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include "internal.h" +#include "../test_static_mem.h" +#include "../integration/tls_test_util.h" + +#include + +#include +#include +#include + +#define REQUIRE(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \ + return 1; \ + } \ + } while (0) + +#ifdef WOLFCERT_HAVE_ECC + #define CA_KEY_TYPE WOLFCERT_KEY_ECC + #define CA_KEY_PARAM 256 +#else + #define CA_KEY_TYPE 0 + #define CA_KEY_PARAM 0 +#endif + +/* SCEP is absent from NO_RSA builds, and EST needs a server identity. */ +#if defined(WOLFCERT_HAVE_EST) + #define CA_TEST_PROTO WOLFCERT_PROTO_EST + #define CA_TEST_NEEDS_TLS 1 +#else + #define CA_TEST_PROTO WOLFCERT_PROTO_SCEP + #define CA_TEST_NEEDS_TLS 0 +#endif + +#if CA_TEST_NEEDS_TLS +static uint8_t* srv_cert_pem; +static size_t srv_cert_pem_len; +static uint8_t* srv_key_pem; +static size_t srv_key_pem_len; +#endif + +/* A server config issuing from cert and key; both NULL generates a CA. */ +static void ca_cfg(WolfCertServerCfgSrv* cfg, const WolfCertBuffer* cert, + const WolfCertBuffer* key) +{ + memset(cfg, 0, sizeof(*cfg)); + cfg->protocol = CA_TEST_PROTO; +#if CA_TEST_NEEDS_TLS + cfg->tls_cert_pem = srv_cert_pem; + cfg->tls_cert_pem_len = srv_cert_pem_len; + cfg->tls_key_pem = srv_key_pem; + cfg->tls_key_pem_len = srv_key_pem_len; + cfg->est_allow_anonymous_enroll = 1; +#endif + cfg->bind_host = "127.0.0.1"; + cfg->ca_key_type = CA_KEY_TYPE; + cfg->ca_key_param = CA_KEY_PARAM; + if (cert != NULL) { + cfg->ca_cert = cert->data; + cfg->ca_cert_len = cert->len; + } + if (key != NULL) { + cfg->ca_key = key->data; + cfg->ca_key_len = key->len; + } +} + +static int ca_key_param(WolfCertKeyType t) +{ + if (t == WOLFCERT_KEY_RSA) + return 2048; + if (t == WOLFCERT_KEY_ECC) + return 256; + return 0; +} + +/* A server start generates a CA of type; the pair is copied out as enc. */ +static int generate_ca(WolfCertKeyType type, WolfCertEncoding enc, + WolfCertBuffer* cert, WolfCertBuffer* key) +{ + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + int rc; + + ca_cfg(&cfg, NULL, NULL); + cfg.ca_key_type = type; + cfg.ca_key_param = ca_key_param(type); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, enc, cert, key); + wolfcert_server_free(srv); + REQUIRE(rc == WOLFCERT_OK); + return 0; +} + +/* A server start with cert and key gets want and, on failure, no server. */ +static int start_gets(const WolfCertBuffer* cert, const WolfCertBuffer* key, + int want) +{ + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + + ca_cfg(&cfg, cert, key); + REQUIRE(wolfcert_server_start(&cfg, &srv) == want); + if (want != WOLFCERT_OK) + REQUIRE(srv == NULL); + wolfcert_server_free(srv); + return 0; +} + +static int test_corrupt_ca_rejected(void) +{ + uint8_t junk[] = { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; + WolfCertBuffer bad = { junk, sizeof(junk), NULL }; + + return start_gets(&bad, &bad, WOLFCERT_ERR_PARSE); +} + +/* One half of the pair, or an empty half, is refused before any work. */ +static int test_half_ca_rejected(void) +{ + uint8_t der[] = { 0x30, 0x03, 0x02, 0x01, 0x01 }; + WolfCertBuffer half = { der, sizeof(der), NULL }; + WolfCertBuffer empty = { der, 0, NULL }; + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + + if (start_gets(&half, NULL, WOLFCERT_ERR_BAD_ARG)) + return 1; + if (start_gets(NULL, &half, WOLFCERT_ERR_BAD_ARG)) + return 1; + if (start_gets(&half, &empty, WOLFCERT_ERR_BAD_ARG)) + return 1; + if (start_gets(&empty, &half, WOLFCERT_ERR_BAD_ARG)) + return 1; + + /* A length without its pointer is not a request to generate a CA. */ + ca_cfg(&cfg, NULL, NULL); + cfg.ca_cert_len = sizeof(der); + cfg.ca_key_len = sizeof(der); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(srv == NULL); + return 0; +} + +/* A generated CA handed back in, as DER or PEM, is the one the server uses. */ +static int test_ca_round_trip(void) +{ + WolfCertBuffer der_cert = { 0 }; + WolfCertBuffer der_key = { 0 }; + WolfCertBuffer pem_cert = { 0 }; + WolfCertBuffer pem_key = { 0 }; + WolfCertBuffer again = { 0 }; + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + int rc; + + ca_cfg(&cfg, NULL, NULL); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &der_cert, + &der_key) == WOLFCERT_OK); + REQUIRE(wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_PEM, &pem_cert, + &pem_key) == WOLFCERT_OK); + wolfcert_server_free(srv); + srv = NULL; + REQUIRE(der_cert.data[0] == 0x30 && der_key.data[0] == 0x30); + REQUIRE(memcmp(pem_cert.data, "-----BEGIN CERTIFICATE-----", 27) == 0); + REQUIRE(memcmp(pem_key.data, "-----BEGIN ", 11) == 0); + + ca_cfg(&cfg, &pem_cert, &pem_key); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &again, NULL); + wolfcert_server_free(srv); + srv = NULL; + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(again.len == der_cert.len); + REQUIRE(memcmp(again.data, der_cert.data, der_cert.len) == 0); + wolfcert_buffer_free(&again); + + ca_cfg(&cfg, &der_cert, &der_key); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &again, NULL); + wolfcert_server_free(srv); + srv = NULL; + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(again.len == der_cert.len); + REQUIRE(memcmp(again.data, der_cert.data, der_cert.len) == 0); + wolfcert_buffer_free(&again); + + /* Each half may use its own encoding. */ + ca_cfg(&cfg, &pem_cert, &der_key); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &again, NULL); + wolfcert_server_free(srv); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(again.len == der_cert.len); + REQUIRE(memcmp(again.data, der_cert.data, der_cert.len) == 0); + + wolfcert_buffer_free(&again); + wolfcert_buffer_free(&der_cert); + wolfcert_buffer_free_secure(&der_key); + wolfcert_buffer_free(&pem_cert); + wolfcert_buffer_free_secure(&pem_key); + return 0; +} + +static int test_get_ca_args(void) +{ + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + + ca_cfg(&cfg, NULL, NULL); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + + REQUIRE(wolfcert_server_get_ca(NULL, WOLFCERT_ENCODING_DER, &cert, &key) + == WOLFCERT_ERR_BAD_ARG); + REQUIRE(wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, NULL, &key) + == WOLFCERT_ERR_BAD_ARG); + REQUIRE(wolfcert_server_get_ca(srv, (WolfCertEncoding)7, &cert, &key) + == WOLFCERT_ERR_BAD_ARG); + REQUIRE(strstr(wolfcert_last_error_message(), "encoding") != NULL); + REQUIRE(cert.data == NULL && key.data == NULL); + + REQUIRE(wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_PEM, &cert, NULL) + == WOLFCERT_OK); + REQUIRE(cert.data != NULL && cert.len > 0); + + wolfcert_buffer_free(&cert); + wolfcert_server_free(srv); + return 0; +} + +#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) && \ + !defined(WOLFSSL_DEBUG_MEMORY) +/* Index of the one allocation fail_one_malloc() refuses; -1 refuses none. */ +static int g_fail_at = -1; +static int g_allocs; + +static void* fail_one_malloc(size_t sz) +{ + return g_allocs++ == g_fail_at ? NULL : malloc(sz); +} + +static void fail_one_free(void* ptr) +{ + free(ptr); +} + +static void* fail_one_realloc(void* ptr, size_t sz) +{ + return g_allocs++ == g_fail_at ? NULL : realloc(ptr, sz); +} + +/* A start that survives any single failed allocation keeps every credential. */ +static int test_start_oom_keeps_credentials(void) +{ + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + wolfSSL_Malloc_cb mf; + wolfSSL_Free_cb ff; + wolfSSL_Realloc_cb rf; + int fail_at; + int rc; + + if (generate_ca(CA_KEY_TYPE, WOLFCERT_ENCODING_PEM, &cert, &key)) + return 1; + ca_cfg(&cfg, &cert, &key); + cfg.http_basic_user = "alice"; + cfg.http_basic_pass = "secret"; + cfg.challenge_password = "otp"; + + REQUIRE(wolfSSL_GetAllocators(&mf, &ff, &rf) == 0); + for (fail_at = 0; ; fail_at++) { + srv = NULL; + g_fail_at = fail_at; + g_allocs = 0; + wolfcert_clear_error(); + REQUIRE(wolfSSL_SetAllocators(fail_one_malloc, fail_one_free, + fail_one_realloc) == 0); + rc = wolfcert_server_start(&cfg, &srv); + REQUIRE(wolfSSL_SetAllocators(mf, ff, rf) == 0); + if (rc != WOLFCERT_OK) { + REQUIRE(srv == NULL); + REQUIRE(strstr(wolfcert_last_error_message(), "does not match") + == NULL); + continue; + } + REQUIRE(srv->cfg_basic_user != NULL && + strcmp(srv->cfg_basic_user, "alice") == 0); + REQUIRE(srv->cfg_basic_pass != NULL && + strcmp(srv->cfg_basic_pass, "secret") == 0); + REQUIRE(srv->cfg_challenge != NULL && + strcmp(srv->cfg_challenge, "otp") == 0); + wolfcert_server_free(srv); + if (g_allocs <= fail_at) + break; + } + g_fail_at = -1; + REQUIRE(fail_at > 4); + + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + return 0; +} +#endif + +static const WolfCertKeyType CA_KEY_TYPES[] = { +#ifdef WOLFCERT_HAVE_RSA + WOLFCERT_KEY_RSA, +#endif +#ifdef WOLFCERT_HAVE_ECC + WOLFCERT_KEY_ECC, +#endif +#ifdef WOLFCERT_HAVE_ED25519 + WOLFCERT_KEY_ED25519, +#endif +#ifdef WOLFCERT_HAVE_ED448 + WOLFCERT_KEY_ED448, +#endif +#ifdef WOLFCERT_HAVE_MLDSA +#ifndef WOLFSSL_NO_ML_DSA_44 + WOLFCERT_KEY_MLDSA44, +#endif +#ifndef WOLFSSL_NO_ML_DSA_65 + WOLFCERT_KEY_MLDSA65, +#endif +#ifndef WOLFSSL_NO_ML_DSA_87 + WOLFCERT_KEY_MLDSA87, +#endif +#endif +}; + +/* The loaded CA issues a leaf that verifies against it. */ +static int loaded_ca_signs(const WolfCertBuffer* cert, const WolfCertBuffer* key) +{ + /* Any compiled algorithm serves as the leaf; the first entry always is. */ + WolfCertKeyCfg kcfg = { .type = CA_KEY_TYPES[0], + .param = ca_key_param(CA_KEY_TYPES[0]), + .dev_id = INVALID_DEVID }; + WolfCertCertMeta meta = { .subject_dn = "CN=leaf" }; + WolfCertKey* leaf_key = NULL; + WolfCertBuffer csr = { 0 }; + WolfCertCa ca; + uint8_t* issued = NULL; + size_t issued_len = 0; + WOLFSSL_CERT_MANAGER* cm = NULL; + int rc; + + REQUIRE(wolfcert_key_generate(&kcfg, &leaf_key) == WOLFCERT_OK); + REQUIRE(wolfcert_csr_build(leaf_key, &meta, &csr) == WOLFCERT_OK); + wolfcert_key_free(leaf_key); + + REQUIRE(wolfcert_ca_load(&ca, cert->data, cert->len, key->data, key->len, + NULL) == WOLFCERT_OK); + rc = wolfcert_ca_issue(&ca, csr.data, csr.len, &issued, &issued_len); + wolfcert_buffer_free(&csr); + REQUIRE(rc == WOLFCERT_OK); + + cm = wolfSSL_CertManagerNew(); + REQUIRE(cm != NULL); + REQUIRE(wolfSSL_CertManagerLoadCABuffer(cm, ca.cert_der, + (long)ca.cert_der_len, WOLFSSL_FILETYPE_ASN1) == WOLFSSL_SUCCESS); + rc = wolfSSL_CertManagerVerifyBuffer(cm, issued, (long)issued_len, + WOLFSSL_FILETYPE_ASN1); + wolfSSL_CertManagerFree(cm); + + WOLFCERT_XFREE(issued, ca.heap); + wolfcert_ca_free(&ca); + + REQUIRE(rc == WOLFSSL_SUCCESS); + return 0; +} + +/* Every algorithm's CA loads back from both encodings and still signs. */ +static int test_every_alg_reloads(void) +{ + size_t i; + int e; + + for (i = 0; i < sizeof(CA_KEY_TYPES) / sizeof(CA_KEY_TYPES[0]); ++i) { + WolfCertBuffer cert[2] = { { 0 }, { 0 } }; + WolfCertBuffer key[2] = { { 0 }, { 0 } }; + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + int rc; + + ca_cfg(&cfg, NULL, NULL); + cfg.ca_key_type = CA_KEY_TYPES[i]; + cfg.ca_key_param = ca_key_param(CA_KEY_TYPES[i]); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &cert[0], + &key[0]); + if (rc == WOLFCERT_OK) + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_PEM, &cert[1], + &key[1]); + wolfcert_server_free(srv); + REQUIRE(rc == WOLFCERT_OK); + + for (e = 0; e < 2; ++e) { + if (start_gets(&cert[e], &key[e], WOLFCERT_OK)) + return 1; + if (loaded_ca_signs(&cert[e], &key[e])) + return 1; + wolfcert_buffer_free(&cert[e]); + wolfcert_buffer_free_secure(&key[e]); + } + } + return 0; +} + +#ifdef WOLFCERT_HAVE_ECC +/* A SEC1 CA key without its optional public point still loads. */ +static int test_ecc_key_without_public_point(void) +{ + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + WolfCertBuffer bare = { 0 }; + ecc_key ek; + word32 idx = 0; + uint8_t der[256]; + int n; + + if (generate_ca(WOLFCERT_KEY_ECC, WOLFCERT_ENCODING_DER, &cert, &key)) + return 1; + REQUIRE(wc_ecc_init(&ek) == 0); + REQUIRE(wc_EccPrivateKeyDecode(key.data, &idx, &ek, (word32)key.len) == 0); + n = wc_EccPrivateKeyToDer(&ek, der, sizeof(der)); + wc_ecc_free(&ek); + REQUIRE(n > 0 && (size_t)n < key.len); + + bare.data = der; + bare.len = (size_t)n; + if (start_gets(&cert, &bare, WOLFCERT_OK)) + return 1; + + wc_ForceZero(der, sizeof(der)); + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + return 0; +} +#endif + +#ifdef WOLFCERT_HAVE_SCEP +/* With a split RA, get_ca returns the CA, not the RA certificate. */ +static int test_split_ra_get_ca_is_ca(void) +{ + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + WolfCertBuffer cert = { 0 }; + DecodedCert dc; + int rc; + + ca_cfg(&cfg, NULL, NULL); + cfg.protocol = WOLFCERT_PROTO_SCEP; + cfg.ca_key_type = WOLFCERT_KEY_RSA; + cfg.ca_key_param = 2048; + cfg.scep_split_ra = 1; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &cert, NULL); + wolfcert_server_free(srv); + REQUIRE(rc == WOLFCERT_OK); + + wc_InitDecodedCert(&dc, cert.data, (word32)cert.len, NULL); + rc = wc_ParseCert(&dc, CERT_TYPE, NO_VERIFY, NULL); + if (rc == 0 && !dc.isCA) + rc = -1; + wc_FreeDecodedCert(&dc); + wolfcert_buffer_free(&cert); + REQUIRE(rc == 0); + return 0; +} +#endif + +/* Have the CA in cert/key issue a CSR carrying san; *rc_out is the result. */ +static int issue_with_san(const WolfCertBuffer* cert, const WolfCertBuffer* key, + const uint8_t* san, size_t san_len, int* rc_out, + uint8_t** issued, size_t* issued_len) +{ + WolfCertCa ca; + WC_RNG rng; + test_signkey skey; + Cert req; + uint8_t csr[CTC_MAX_ALT_SIZE + 4096]; + int csr_len; + + REQUIRE(wc_InitRng(&rng) == 0); + REQUIRE(test_signkey_make(&skey, &rng) == 0); + REQUIRE(wc_InitCert(&req) == 0); + strncpy(req.subject.commonName, "san-leaf", CTC_NAME_SIZE - 1); + memcpy(req.altNames, san, san_len); + req.altNamesSz = (int)san_len; + req.sigType = TEST_CERT_SIGTYPE; + csr_len = test_sign_certreq(&req, csr, (int)sizeof(csr), &skey, &rng); + test_signkey_free(&skey); + wc_FreeRng(&rng); + REQUIRE(csr_len > 0); + + REQUIRE(wolfcert_ca_load(&ca, cert->data, cert->len, key->data, key->len, + NULL) == WOLFCERT_OK); + *rc_out = wolfcert_ca_issue(&ca, csr, (size_t)csr_len, issued, issued_len); + wolfcert_ca_free(&ca); + return 0; +} + +/* Issued SANs match the CSR in order; unsupported GeneralName forms fail. */ +static int test_issued_san_verbatim(void) +{ + static const uint8_t san[] = { + 0x30, 0x20, + 0x82, 0x09, 'b', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', + 0x81, 0x0d, 'a', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', + 'm', + 0x87, 0x04, 127, 0, 0, 1 + }; + static const uint8_t dir_san[] = { + 0x30, 0x12, + 0xa4, 0x10, 0x30, 0x0e, 0x31, 0x0c, 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, + 0x03, 0x0c, 0x03, 'd', 'i', 'r' + }; + WolfCertBuffer ca_cert = { 0 }; + WolfCertBuffer ca_key = { 0 }; + uint8_t* issued = NULL; + size_t issued_len = 0; + DecodedCert dc; + const byte* got = NULL; + word32 got_len = 0; + uint8_t big_san[10 * 1024]; + size_t big_len = 4; + int rc = -1; + + if (generate_ca(CA_KEY_TYPES[0], WOLFCERT_ENCODING_DER, &ca_cert, &ca_key)) + return 1; + + REQUIRE(issue_with_san(&ca_cert, &ca_key, dir_san, sizeof(dir_san), &rc, + &issued, &issued_len) == 0); + REQUIRE(rc == WOLFCERT_ERR_UNSUPPORTED); + + /* Over 8 KB of SAN in few entries, so a static-memory pool can parse it. */ + while (big_len + 3 + 240 <= sizeof(big_san)) { + big_san[big_len] = 0x82; + big_san[big_len + 1] = 0x81; + big_san[big_len + 2] = 240; + memset(big_san + big_len + 3, 'a', 240); + big_san[big_len + 3 + 60] = '.'; + big_san[big_len + 3 + 120] = '.'; + big_san[big_len + 3 + 180] = '.'; + big_len += 3 + 240; + } + big_san[0] = 0x30; + big_san[1] = 0x82; + big_san[2] = (uint8_t)((big_len - 4) >> 8); + big_san[3] = (uint8_t)(big_len - 4); + REQUIRE(issue_with_san(&ca_cert, &ca_key, big_san, big_len, &rc, &issued, + &issued_len) == 0); + REQUIRE(rc == WOLFCERT_OK); + WOLFCERT_XFREE(issued, wolfcert_default_heap()); + issued = NULL; + REQUIRE(issue_with_san(&ca_cert, &ca_key, san, sizeof(san), &rc, &issued, + &issued_len) == 0); + wolfcert_buffer_free(&ca_cert); + wolfcert_buffer_free_secure(&ca_key); + REQUIRE(rc == WOLFCERT_OK); + + wc_InitDecodedCert(&dc, issued, (word32)issued_len, NULL); + rc = wc_ParseCert(&dc, CERT_TYPE, NO_VERIFY, NULL); + if (rc == 0) + rc = wolfcert_find_san(&dc, &got, &got_len); + if (rc == 0 && (got_len != sizeof(san) || + memcmp(got, san, sizeof(san)) != 0)) + rc = -1; + wc_FreeDecodedCert(&dc); + WOLFCERT_XFREE(issued, wolfcert_default_heap()); + REQUIRE(rc == 0); + return 0; +} + +static int mismatched_ca_rejected(WolfCertKeyType type) +{ + WolfCertBuffer cert_a = { 0 }; + WolfCertBuffer key_a = { 0 }; + WolfCertBuffer cert_b = { 0 }; + WolfCertBuffer key_b = { 0 }; + + if (generate_ca(type, WOLFCERT_ENCODING_DER, &cert_a, &key_a)) + return 1; + if (generate_ca(type, WOLFCERT_ENCODING_DER, &cert_b, &key_b)) + return 1; + REQUIRE(key_a.len != key_b.len || memcmp(key_a.data, key_b.data, key_a.len) != 0); + + if (start_gets(&cert_a, &key_b, WOLFCERT_ERR_PARSE)) + return 1; + + wolfcert_buffer_free(&cert_a); + wolfcert_buffer_free_secure(&key_a); + wolfcert_buffer_free(&cert_b); + wolfcert_buffer_free_secure(&key_b); + return 0; +} + +static int test_mismatched_ca_rejected(void) +{ + size_t i; + + for (i = 0; i < sizeof(CA_KEY_TYPES) / sizeof(CA_KEY_TYPES[0]); ++i) { + if (mismatched_ca_rejected(CA_KEY_TYPES[i])) + return 1; + } + return 0; +} + +/* The generated CA's key usages and critical basicConstraints. */ +static int ca_key_usage_set(WolfCertKeyType type) +{ + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + DecodedCert dc; + int rc = 0; + + if (generate_ca(type, WOLFCERT_ENCODING_DER, &cert, &key)) + return 1; + + wc_InitDecodedCert(&dc, cert.data, (word32)cert.len, NULL); + REQUIRE(wc_ParseCert(&dc, CERT_TYPE, NO_VERIFY, NULL) == 0); + + if (dc.extBasicConstSet == 0 || dc.extBasicConstCrit == 0 || dc.isCA == 0) { + rc = 1; + } + else if (dc.extKeyUsageSet == 0 || + (dc.extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0 || + (dc.extKeyUsage & KEYUSE_CRL_SIGN) == 0 || + (dc.extKeyUsage & KEYUSE_DIGITAL_SIG) == 0) { + rc = 1; + } + /* Only the RSA CA has keyEncipherment, for the SCEP pkcsPKIEnvelope. */ + else if (((dc.extKeyUsage & KEYUSE_KEY_ENCIPHER) != 0) != + (type == WOLFCERT_KEY_RSA)) { + rc = 1; + } + + wc_FreeDecodedCert(&dc); + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + + REQUIRE(rc == 0); + return 0; +} + +static int test_ca_key_usage(void) +{ + size_t i; + + for (i = 0; i < sizeof(CA_KEY_TYPES) / sizeof(CA_KEY_TYPES[0]); ++i) { + if (ca_key_usage_set(CA_KEY_TYPES[i])) + return 1; + } + return 0; +} + +static int test_corrupt_ca_cert_rejected(void) +{ + uint8_t junk[] = { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; + WolfCertBuffer bad = { junk, sizeof(junk), NULL }; + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + WolfCertBuffer padded = { 0 }; + + if (generate_ca(CA_KEY_TYPE, WOLFCERT_ENCODING_DER, &cert, &key)) + return 1; + if (start_gets(&bad, &key, WOLFCERT_ERR_PARSE)) + return 1; + REQUIRE(strstr(wolfcert_last_error_message(), "ca_cert") != NULL); + if (start_gets(&cert, &bad, WOLFCERT_ERR_PARSE)) + return 1; + REQUIRE(strstr(wolfcert_last_error_message(), "ca_key") != NULL); + + /* DER that is not a certificate fails the same way. */ + if (start_gets(&key, &key, WOLFCERT_ERR_PARSE)) + return 1; + + /* So does a certificate with bytes after it. */ + padded.data = (uint8_t*)malloc(cert.len + 1); + REQUIRE(padded.data != NULL); + memcpy(padded.data, cert.data, cert.len); + padded.data[cert.len] = 0; + padded.len = cert.len + 1; + if (start_gets(&padded, &key, WOLFCERT_ERR_PARSE)) + return 1; + free(padded.data); + + /* And a DER key with bytes after it. */ + padded.data = (uint8_t*)malloc(key.len + 1); + REQUIRE(padded.data != NULL); + memcpy(padded.data, key.data, key.len); + padded.data[key.len] = 0; + padded.len = key.len + 1; + if (start_gets(&cert, &padded, WOLFCERT_ERR_PARSE)) + return 1; + REQUIRE(strstr(wolfcert_last_error_message(), "ca_key") != NULL); + wc_ForceZero(padded.data, (word32)padded.len); + free(padded.data); + + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + return 0; +} + +#if !defined(NO_PKCS8) && \ + (defined(WOLFCERT_HAVE_RSA) || defined(WOLFCERT_HAVE_ECC)) +/* A PKCS#8 CA key comes back in the form its PEM label names. */ +static int test_pkcs8_ca_key_normalized(void) +{ +#ifdef WOLFCERT_HAVE_RSA + const WolfCertKeyType type = WOLFCERT_KEY_RSA; + const int algo = RSAk; + const byte* curve = NULL; + word32 curve_sz = 0; + const char* label = "-----BEGIN RSA PRIVATE KEY-----"; +#else + const WolfCertKeyType type = WOLFCERT_KEY_ECC; + const int algo = ECDSAk; + const byte* curve = NULL; + word32 curve_sz = 0; + const char* label = "-----BEGIN EC PRIVATE KEY-----"; +#endif + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + WolfCertBuffer p8 = { 0 }; + WolfCertBuffer out_cert = { 0 }; + WolfCertBuffer out_key = { 0 }; + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + word32 p8_len = 0; + int rc; + + if (generate_ca(type, WOLFCERT_ENCODING_DER, &cert, &key)) + return 1; +#ifndef WOLFCERT_HAVE_RSA + REQUIRE(wc_ecc_get_oid(ECC_SECP256R1_OID, &curve, &curve_sz) > 0); +#endif + REQUIRE(wc_CreatePKCS8Key(NULL, &p8_len, key.data, (word32)key.len, algo, + curve, curve_sz) == LENGTH_ONLY_E); + p8.data = (uint8_t*)malloc(p8_len); + REQUIRE(p8.data != NULL); + rc = wc_CreatePKCS8Key(p8.data, &p8_len, key.data, (word32)key.len, algo, + curve, curve_sz); + REQUIRE(rc > 0); + p8.len = (size_t)rc; + REQUIRE(p8.len != key.len || memcmp(p8.data, key.data, key.len) != 0); + + ca_cfg(&cfg, &cert, &p8); + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_DER, &out_cert, + &out_key); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(out_key.len == key.len && + memcmp(out_key.data, key.data, key.len) == 0); + wolfcert_buffer_free(&out_cert); + wolfcert_buffer_free_secure(&out_key); + + rc = wolfcert_server_get_ca(srv, WOLFCERT_ENCODING_PEM, &out_cert, + &out_key); + wolfcert_server_free(srv); + REQUIRE(rc == WOLFCERT_OK); + REQUIRE(out_key.len > strlen(label) && + memcmp(out_key.data, label, strlen(label)) == 0); + + wolfcert_buffer_free(&out_cert); + wolfcert_buffer_free_secure(&out_key); + free(p8.data); + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + return 0; +} +#endif + +#ifdef WOLFCERT_HAVE_ECC +/* A self-signed certificate with a skid_len-byte subject key id, or none, and + * its key. */ +static int make_self_pair(int is_ca, int skid_len, WolfCertBuffer* cert_out, + WolfCertBuffer* key_out) +{ + WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, + .dev_id = INVALID_DEVID }; + WolfCertKey* dk = NULL; + ecc_key wck; + word32 idx = 0; + Cert cert; + WC_RNG rng; + uint8_t der[4096]; + int body, sz; + + REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); + REQUIRE(wolfcert_key_to_der(dk, key_out) == WOLFCERT_OK); + wolfcert_key_free(dk); + + REQUIRE(wc_ecc_init(&wck) == 0); + REQUIRE(wc_EccPrivateKeyDecode(key_out->data, &idx, &wck, + (word32)key_out->len) == 0); + + wc_InitCert(&cert); + snprintf(cert.subject.commonName, sizeof(cert.subject.commonName), + "%s", "wolfCert Leaf"); + cert.isCA = is_ca; + cert.selfSigned = 1; + memset(cert.skid, 0x5a, (size_t)skid_len); + cert.skidSz = skid_len; + cert.daysValid = 30; + cert.sigType = CTC_SHA256wECDSA; + + REQUIRE(wc_InitRng(&rng) == 0); + body = wc_MakeCert(&cert, der, sizeof(der), NULL, &wck, &rng); + REQUIRE(body > 0); + sz = wc_SignCert(body, cert.sigType, der, sizeof(der), NULL, &wck, &rng); + REQUIRE(sz > 0); + wc_FreeRng(&rng); + wc_ecc_free(&wck); + + cert_out->data = (uint8_t*)WOLFCERT_XMALLOC((size_t)sz, NULL); + REQUIRE(cert_out->data != NULL); + memcpy(cert_out->data, der, (size_t)sz); + cert_out->len = (size_t)sz; + cert_out->heap = NULL; + return 0; +} + +static int test_leaf_ca_rejected(void) +{ + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + + if (make_self_pair(0, 0, &cert, &key)) + return 1; + if (start_gets(&cert, &key, WOLFCERT_ERR_PARSE)) + return 1; + + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + return 0; +} + +/* A loaded CA without a subject key id, or with one wolfSSL would hash, + * issues without an authority key id; a generated CA's leaves carry it. */ +static int test_issued_key_ids(void) +{ + static const uint8_t san[] = { + 0x30, 0x0b, 0x82, 0x09, 'k', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e' + }; + WolfCertBuffer cert = { 0 }; + WolfCertBuffer key = { 0 }; + uint8_t* issued = NULL; + size_t issued_len = 0; + DecodedCert ca_dc; + DecodedCert leaf_dc; + int skid_len; + int rc = -1; + int ok; + + for (skid_len = 0; skid_len <= 8; skid_len += 8) { + if (make_self_pair(1, skid_len, &cert, &key)) + return 1; + REQUIRE(issue_with_san(&cert, &key, san, sizeof(san), &rc, &issued, + &issued_len) == 0); + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + REQUIRE(rc == WOLFCERT_OK); + wc_InitDecodedCert(&leaf_dc, issued, (word32)issued_len, NULL); + ok = wc_ParseCert(&leaf_dc, CERT_TYPE, NO_VERIFY, NULL) == 0 && + !leaf_dc.extAuthKeyIdSet; + wc_FreeDecodedCert(&leaf_dc); + WOLFCERT_XFREE(issued, wolfcert_default_heap()); + issued = NULL; + REQUIRE(ok); + } + + if (generate_ca(WOLFCERT_KEY_ECC, WOLFCERT_ENCODING_DER, &cert, &key)) + return 1; + REQUIRE(issue_with_san(&cert, &key, san, sizeof(san), &rc, &issued, + &issued_len) == 0); + REQUIRE(rc == WOLFCERT_OK); + wc_InitDecodedCert(&ca_dc, cert.data, (word32)cert.len, NULL); + wc_InitDecodedCert(&leaf_dc, issued, (word32)issued_len, NULL); + ok = wc_ParseCert(&ca_dc, CERT_TYPE, NO_VERIFY, NULL) == 0 && + wc_ParseCert(&leaf_dc, CERT_TYPE, NO_VERIFY, NULL) == 0 && + ca_dc.extSubjKeyIdSet && leaf_dc.extAuthKeyIdSet && + memcmp(ca_dc.extSubjKeyId, leaf_dc.extAuthKeyId, + sizeof(ca_dc.extSubjKeyId)) == 0; + wc_FreeDecodedCert(&leaf_dc); + wc_FreeDecodedCert(&ca_dc); + WOLFCERT_XFREE(issued, wolfcert_default_heap()); + wolfcert_buffer_free(&cert); + wolfcert_buffer_free_secure(&key); + REQUIRE(ok); + return 0; +} +#endif /* WOLFCERT_HAVE_ECC */ + +static int test_bad_bind_host_rejected(void) +{ + static const char* const hosts[] = { + "localhost", "::1", "", "127.0.0.300", "127.0.0.1 " + }; + WolfCertServerCfgSrv cfg; + WolfCertServer* srv = NULL; + size_t i; + + for (i = 0; i < sizeof(hosts) / sizeof(hosts[0]); i++) { + ca_cfg(&cfg, NULL, NULL); + cfg.bind_host = hosts[i]; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_BAD_ARG); + REQUIRE(srv == NULL); + } + + /* NULL binds every interface and must still start. */ + ca_cfg(&cfg, NULL, NULL); + cfg.bind_host = NULL; + REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); + REQUIRE(wolfcert_server_port(srv) != 0); + wolfcert_server_free(srv); + + return 0; +} + +int main(void) +{ + REQUIRE(test_static_mem_init() == 0); + REQUIRE(wolfcert_init(test_heap_hint()) == WOLFCERT_OK); + +#if CA_TEST_NEEDS_TLS + REQUIRE(gen_server_identity(&srv_cert_pem, &srv_cert_pem_len, + &srv_key_pem, &srv_key_pem_len) == 0); +#endif + + if (test_corrupt_ca_rejected()) + return 1; + if (test_half_ca_rejected()) + return 1; + if (test_ca_round_trip()) + return 1; + if (test_get_ca_args()) + return 1; +#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) && \ + !defined(WOLFSSL_DEBUG_MEMORY) + if (test_start_oom_keeps_credentials()) + return 1; +#endif + if (test_every_alg_reloads()) + return 1; +#ifdef WOLFCERT_HAVE_ECC + if (test_ecc_key_without_public_point()) + return 1; +#endif +#ifdef WOLFCERT_HAVE_SCEP + if (test_split_ra_get_ca_is_ca()) + return 1; +#endif + if (test_mismatched_ca_rejected()) + return 1; + if (test_corrupt_ca_cert_rejected()) + return 1; +#if !defined(NO_PKCS8) && \ + (defined(WOLFCERT_HAVE_RSA) || defined(WOLFCERT_HAVE_ECC)) + if (test_pkcs8_ca_key_normalized()) + return 1; +#endif + if (test_issued_san_verbatim()) + return 1; +#ifdef WOLFCERT_HAVE_ECC + if (test_issued_key_ids()) + return 1; + if (test_leaf_ca_rejected()) + return 1; +#endif + if (test_ca_key_usage()) + return 1; + if (test_bad_bind_host_rejected()) + return 1; + +#if CA_TEST_NEEDS_TLS + free(srv_cert_pem); + free(srv_key_pem); +#endif + wolfcert_cleanup(); + printf("OK\n"); + return 0; +} diff --git a/tests/unit/test_server_ca_store.c b/tests/unit/test_server_ca_store.c deleted file mode 100644 index 3a6bd8bf..00000000 --- a/tests/unit/test_server_ca_store.c +++ /dev/null @@ -1,1012 +0,0 @@ -/* - * Copyright (C) 2026 wolfSSL Inc. - * - * This file is part of wolfCert. - * - * wolfCert 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. - * - * wolfCert 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 wolfCert. If not, see . - */ - -#define _POSIX_C_SOURCE 200809L - -#include -#include -#include "internal.h" -#include "../test_static_mem.h" -#include "../integration/tls_test_util.h" - -#include - -#include -#include -#include - -#define REQUIRE(cond) \ - do { \ - if (!(cond)) { \ - fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \ - return 1; \ - } \ - } while (0) - -#ifdef WOLFCERT_HAVE_ECC - #define CA_KEY_TYPE WOLFCERT_KEY_ECC - #define CA_KEY_PARAM 256 -#else - #define CA_KEY_TYPE 0 - #define CA_KEY_PARAM 0 -#endif - -/* SCEP is absent from NO_RSA builds, and EST needs a server identity. */ -#if defined(WOLFCERT_HAVE_EST) - #define CA_STORE_PROTO WOLFCERT_PROTO_EST - #define CA_STORE_NEEDS_TLS 1 -#else - #define CA_STORE_PROTO WOLFCERT_PROTO_SCEP - #define CA_STORE_NEEDS_TLS 0 -#endif - -#if CA_STORE_NEEDS_TLS -static uint8_t* srv_cert_pem; -static size_t srv_cert_pem_len; -static uint8_t* srv_key_pem; -static size_t srv_key_pem_len; -#endif - -static void ca_store_cfg(WolfCertServerCfgSrv* cfg, WolfCertStoreOps* store) -{ - memset(cfg, 0, sizeof(*cfg)); - cfg->protocol = CA_STORE_PROTO; -#if CA_STORE_NEEDS_TLS - cfg->tls_cert_pem = srv_cert_pem; - cfg->tls_cert_pem_len = srv_cert_pem_len; - cfg->tls_key_pem = srv_key_pem; - cfg->tls_key_pem_len = srv_key_pem_len; - cfg->est_allow_anonymous_enroll = 1; -#endif - cfg->bind_host = "127.0.0.1"; - cfg->ca_store = store; - cfg->ca_key_type = CA_KEY_TYPE; - cfg->ca_key_param = CA_KEY_PARAM; -} - -/* Stub backend whose reads and writes all return the configured error. */ -typedef struct { - int read_rc; - int write_rc; -} StubCtx; - -static int stub_read(void* ctx_, const char* key, WolfCertBuffer* out) -{ - (void)key; - (void)out; - return ((StubCtx*)ctx_)->read_rc; -} - -static int stub_write(void* ctx_, const char* key, const uint8_t* data, - size_t len, int sensitive) -{ - (void)key; - (void)data; - (void)len; - (void)sensitive; - return ((StubCtx*)ctx_)->write_rc; -} - -static int stub_remove(void* ctx_, const char* key) -{ - (void)ctx_; - (void)key; - return WOLFCERT_OK; -} - -static void stub_store(WolfCertStoreOps* ops, StubCtx* ctx) -{ - memset(ops, 0, sizeof(*ops)); - ops->read = stub_read; - ops->write = stub_write; - ops->remove = stub_remove; - ops->ctx = ctx; -} - -static int test_corrupt_ca_rejected(void) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - REQUIRE(store != NULL); - - const uint8_t junk[] = { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - REQUIRE(store->write(store->ctx, "ca.cert.der", junk, sizeof(junk), 0) == WOLFCERT_OK); - REQUIRE(store->write(store->ctx, "ca.key.der", junk, sizeof(junk), 1) == WOLFCERT_OK); - - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - ca_store_cfg(&cfg, store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_PARSE); - REQUIRE(srv == NULL); - - wolfcert_store_memory_close(store); - return 0; -} - -static int test_load_io_error_rejected(void) -{ - StubCtx ctx = { WOLFCERT_ERR_IO, WOLFCERT_OK }; - WolfCertStoreOps store; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - stub_store(&store, &ctx); - ca_store_cfg(&cfg, &store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_IO); - REQUIRE(srv == NULL); - return 0; -} - -static int test_save_failure_rejected(void) -{ - StubCtx ctx = { WOLFCERT_ERR_NOT_FOUND, WOLFCERT_ERR_IO }; - WolfCertStoreOps store; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - stub_store(&store, &ctx); - ca_store_cfg(&cfg, &store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_IO); - REQUIRE(srv == NULL); - return 0; -} - -/* Stub backend whose certificate and key reads fail differently. */ -typedef struct { - int cert_rc; - int key_rc; -} SplitCtx; - -static int split_read(void* ctx_, const char* key, WolfCertBuffer* out) -{ - SplitCtx* ctx = (SplitCtx*)ctx_; - - (void)out; - return strcmp(key, "ca.cert.der") == 0 ? ctx->cert_rc : ctx->key_rc; -} - -/* wolfcert_server_start with cert and key reads returning cert_rc and key_rc - * gets want and no server. */ -static int mixed_read_failure(int cert_rc, int key_rc, int want) -{ - SplitCtx ctx = { cert_rc, key_rc }; - WolfCertStoreOps store; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - memset(&store, 0, sizeof(store)); - store.read = split_read; - store.write = stub_write; - store.remove = stub_remove; - store.ctx = &ctx; - - ca_store_cfg(&cfg, &store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == want); - REQUIRE(srv == NULL); - return 0; -} - -static int test_mixed_read_failure(void) -{ - if (mixed_read_failure(WOLFCERT_ERR_NOT_FOUND, WOLFCERT_ERR_IO, - WOLFCERT_ERR_IO)) - return 1; - if (mixed_read_failure(WOLFCERT_ERR_IO, WOLFCERT_ERR_NOT_FOUND, - WOLFCERT_ERR_IO)) - return 1; - if (mixed_read_failure(WOLFCERT_ERR_NOT_FOUND, WOLFCERT_ERR_MEMORY, - WOLFCERT_ERR_MEMORY)) - return 1; - - /* Cert NOT_FOUND beside a good key read: start gets PARSE. */ - return mixed_read_failure(WOLFCERT_ERR_NOT_FOUND, WOLFCERT_OK, - WOLFCERT_ERR_PARSE); -} - -/* Backend that forwards to a real store but fails the nth write. */ -typedef struct { - WolfCertStoreOps* inner; - int writes; - int fail_at; -} FlakyCtx; - -static int flaky_read(void* ctx_, const char* key, WolfCertBuffer* out) -{ - WolfCertStoreOps* in = ((FlakyCtx*)ctx_)->inner; - - return in->read(in->ctx, key, out); -} - -static int flaky_write(void* ctx_, const char* key, const uint8_t* data, - size_t len, int sensitive) -{ - FlakyCtx* ctx = (FlakyCtx*)ctx_; - - if (++ctx->writes == ctx->fail_at) - return WOLFCERT_ERR_IO; - - return ctx->inner->write(ctx->inner->ctx, key, data, len, sensitive); -} - -static int flaky_remove(void* ctx_, const char* key) -{ - WolfCertStoreOps* in = ((FlakyCtx*)ctx_)->inner; - - return in->remove(in->ctx, key); -} - -static int failing_remove(void* ctx_, const char* key) -{ - (void)ctx_; - (void)key; - return WOLFCERT_ERR_IO; -} - -/* A failed key write removes the certificate already written. */ -static int test_save_rollback(void) -{ - WolfCertStoreOps* mem = wolfcert_store_memory_open(NULL); - FlakyCtx fctx; - WolfCertStoreOps store; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - WolfCertBuffer left = { 0 }; - - REQUIRE(mem != NULL); - - memset(&fctx, 0, sizeof(fctx)); - fctx.inner = mem; - fctx.fail_at = 2; - - memset(&store, 0, sizeof(store)); - store.read = flaky_read; - store.write = flaky_write; - store.remove = flaky_remove; - store.ctx = &fctx; - - ca_store_cfg(&cfg, &store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_IO); - REQUIRE(srv == NULL); - REQUIRE(mem->read(mem->ctx, "ca.cert.der", &left) == WOLFCERT_ERR_NOT_FOUND); - - /* The store is still empty, so the next start bootstraps normally. */ - fctx.fail_at = 0; - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - REQUIRE(mem->read(mem->ctx, "ca.cert.der", &left) == WOLFCERT_OK); - - wolfcert_buffer_free(&left); - wolfcert_store_memory_close(mem); - return 0; -} - -/* Key write fails with remove absent or failing: IO, a "rolled back" - * message, and the next start gets PARSE. */ -static int rollback_unavailable(int have_remove) -{ - WolfCertStoreOps* mem = wolfcert_store_memory_open(NULL); - FlakyCtx fctx; - WolfCertStoreOps store; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - WolfCertBuffer left = { 0 }; - - REQUIRE(mem != NULL); - - memset(&fctx, 0, sizeof(fctx)); - fctx.inner = mem; - fctx.fail_at = 2; - - memset(&store, 0, sizeof(store)); - store.read = flaky_read; - store.write = flaky_write; - store.remove = have_remove ? failing_remove : NULL; - store.ctx = &fctx; - - ca_store_cfg(&cfg, &store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_IO); - REQUIRE(srv == NULL); - REQUIRE(strstr(wolfcert_last_error_message(), "rolled back") != NULL); - - /* The certificate really is still there, and the next start refuses it. */ - REQUIRE(mem->read(mem->ctx, "ca.cert.der", &left) == WOLFCERT_OK); - wolfcert_buffer_free(&left); - - fctx.fail_at = 0; - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_PARSE); - REQUIRE(srv == NULL); - - wolfcert_store_memory_close(mem); - return 0; -} - -static int test_rollback_unavailable(void) -{ - if (rollback_unavailable(0)) - return 1; - - return rollback_unavailable(1); -} - -/* A store holding one half of the pair fails to start. */ -static int partial_store_rejected(const char* present) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - const uint8_t stored[] = { 0x30, 0x03, 0x02, 0x01, 0x01 }; - WolfCertBuffer left = { 0 }; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - REQUIRE(store != NULL); - REQUIRE(store->write(store->ctx, present, stored, sizeof(stored), 0) - == WOLFCERT_OK); - - ca_store_cfg(&cfg, store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_PARSE); - REQUIRE(srv == NULL); - - /* The survivor is still exactly what was stored. */ - REQUIRE(store->read(store->ctx, present, &left) == WOLFCERT_OK); - REQUIRE(left.len == sizeof(stored)); - REQUIRE(memcmp(left.data, stored, left.len) == 0); - - wolfcert_buffer_free(&left); - wolfcert_store_memory_close(store); - return 0; -} - -static int test_partial_store_rejected(void) -{ - if (partial_store_rejected("ca.cert.der")) - return 1; - - return partial_store_rejected("ca.key.der"); -} - -static int test_ca_persists_across_starts(void) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - REQUIRE(store != NULL); - - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - WolfCertBuffer first = { 0 }; - WolfCertBuffer second = { 0 }; - - ca_store_cfg(&cfg, store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - srv = NULL; - REQUIRE(store->read(store->ctx, "ca.cert.der", &first) == WOLFCERT_OK); - - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - REQUIRE(store->read(store->ctx, "ca.cert.der", &second) == WOLFCERT_OK); - - REQUIRE(first.len == second.len); - REQUIRE(memcmp(first.data, second.data, first.len) == 0); - - wolfcert_buffer_free(&first); - wolfcert_buffer_free(&second); - wolfcert_store_memory_close(store); - return 0; -} - -#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) && \ - !defined(WOLFSSL_DEBUG_MEMORY) -/* Index of the one allocation fail_one_malloc() refuses; -1 refuses none. */ -static int g_fail_at = -1; -static int g_allocs; - -static void* fail_one_malloc(size_t sz) -{ - return g_allocs++ == g_fail_at ? NULL : malloc(sz); -} - -static void fail_one_free(void* ptr) -{ - free(ptr); -} - -static void* fail_one_realloc(void* ptr, size_t sz) -{ - return g_allocs++ == g_fail_at ? NULL : realloc(ptr, sz); -} - -/* A start that survives any single failed allocation keeps every credential. */ -static int test_start_oom_keeps_credentials(void) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - wolfSSL_Malloc_cb mf; - wolfSSL_Free_cb ff; - wolfSSL_Realloc_cb rf; - int fail_at; - int rc; - - REQUIRE(store != NULL); - ca_store_cfg(&cfg, store); - cfg.http_basic_user = "alice"; - cfg.http_basic_pass = "secret"; - cfg.challenge_password = "otp"; - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - - REQUIRE(wolfSSL_GetAllocators(&mf, &ff, &rf) == 0); - for (fail_at = 0; ; fail_at++) { - srv = NULL; - g_fail_at = fail_at; - g_allocs = 0; - REQUIRE(wolfSSL_SetAllocators(fail_one_malloc, fail_one_free, - fail_one_realloc) == 0); - rc = wolfcert_server_start(&cfg, &srv); - REQUIRE(wolfSSL_SetAllocators(mf, ff, rf) == 0); - if (rc != WOLFCERT_OK) { - REQUIRE(srv == NULL); - continue; - } - REQUIRE(srv->cfg_basic_user != NULL && - strcmp(srv->cfg_basic_user, "alice") == 0); - REQUIRE(srv->cfg_basic_pass != NULL && - strcmp(srv->cfg_basic_pass, "secret") == 0); - REQUIRE(srv->cfg_challenge != NULL && - strcmp(srv->cfg_challenge, "otp") == 0); - wolfcert_server_free(srv); - if (g_allocs <= fail_at) - break; - } - g_fail_at = -1; - REQUIRE(fail_at > 4); - - wolfcert_store_memory_close(store); - return 0; -} -#endif - -static const WolfCertKeyType CA_KEY_TYPES[] = { -#ifdef WOLFCERT_HAVE_RSA - WOLFCERT_KEY_RSA, -#endif -#ifdef WOLFCERT_HAVE_ECC - WOLFCERT_KEY_ECC, -#endif -#ifdef WOLFCERT_HAVE_ED25519 - WOLFCERT_KEY_ED25519, -#endif -#ifdef WOLFCERT_HAVE_ED448 - WOLFCERT_KEY_ED448, -#endif -#ifdef WOLFCERT_HAVE_MLDSA -#ifndef WOLFSSL_NO_ML_DSA_44 - WOLFCERT_KEY_MLDSA44, -#endif -#ifndef WOLFSSL_NO_ML_DSA_65 - WOLFCERT_KEY_MLDSA65, -#endif -#ifndef WOLFSSL_NO_ML_DSA_87 - WOLFCERT_KEY_MLDSA87, -#endif -#endif -}; - -static int ca_key_param(WolfCertKeyType t) -{ - if (t == WOLFCERT_KEY_RSA) - return 2048; - if (t == WOLFCERT_KEY_ECC) - return 256; - return 0; -} - -/* The CA reloaded from store issues a leaf that verifies against it; the - * cert/key match on load alone passes a key with no public half. */ -static int reloaded_ca_signs(WolfCertStoreOps* store) -{ - /* Any compiled algorithm serves as the leaf; the first entry always is. */ - WolfCertKeyCfg kcfg = { .type = CA_KEY_TYPES[0], - .param = ca_key_param(CA_KEY_TYPES[0]), - .dev_id = WOLFCERT_DEVID_SOFTWARE }; - WolfCertCertMeta meta = { .subject_dn = "CN=leaf" }; - WolfCertKey* leaf_key = NULL; - WolfCertBuffer csr = { 0 }; - WolfCertCa ca; - uint8_t* issued = NULL; - size_t issued_len = 0; - WOLFSSL_CERT_MANAGER* cm = NULL; - int rc; - - REQUIRE(wolfcert_key_generate(&kcfg, &leaf_key) == WOLFCERT_OK); - REQUIRE(wolfcert_csr_build(leaf_key, &meta, &csr) == WOLFCERT_OK); - wolfcert_key_free(leaf_key); - - REQUIRE(wolfcert_ca_load(&ca, store, NULL) == WOLFCERT_OK); - rc = wolfcert_ca_issue(&ca, csr.data, csr.len, &issued, &issued_len); - wolfcert_buffer_free(&csr); - REQUIRE(rc == WOLFCERT_OK); - - cm = wolfSSL_CertManagerNew(); - REQUIRE(cm != NULL); - REQUIRE(wolfSSL_CertManagerLoadCABuffer(cm, ca.cert_der, - (long)ca.cert_der_len, WOLFSSL_FILETYPE_ASN1) == WOLFSSL_SUCCESS); - rc = wolfSSL_CertManagerVerifyBuffer(cm, issued, (long)issued_len, - WOLFSSL_FILETYPE_ASN1); - wolfSSL_CertManagerFree(cm); - - WOLFCERT_XFREE(issued, ca.heap); - wolfcert_ca_free(&ca); - - REQUIRE(rc == WOLFSSL_SUCCESS); - return 0; -} - -static int test_every_alg_reloads(void) -{ - size_t i; - - for (i = 0; i < sizeof(CA_KEY_TYPES) / sizeof(CA_KEY_TYPES[0]); ++i) { - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - REQUIRE(store != NULL); - ca_store_cfg(&cfg, store); - cfg.ca_key_type = CA_KEY_TYPES[i]; - cfg.ca_key_param = ca_key_param(CA_KEY_TYPES[i]); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - srv = NULL; - - /* Second start reloads the saved pair and checks the cert/key match. */ - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - - if (reloaded_ca_signs(store)) - return 1; - - wolfcert_store_memory_close(store); - } - return 0; -} - -/* A server start generates a CA into `store`; the pair is copied out. */ -static int generate_ca_into(WolfCertStoreOps* store, WolfCertKeyType type, - WolfCertBuffer* cert, WolfCertBuffer* key) -{ - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - ca_store_cfg(&cfg, store); - cfg.ca_key_type = type; - cfg.ca_key_param = ca_key_param(type); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - wolfcert_server_free(srv); - - REQUIRE(store->read(store->ctx, "ca.cert.der", cert) == WOLFCERT_OK); - REQUIRE(store->read(store->ctx, "ca.key.der", key) == WOLFCERT_OK); - return 0; -} - -/* Have the CA in store issue a CSR carrying san; *rc_out is the issue result. */ -static int issue_with_san(WolfCertStoreOps* store, const uint8_t* san, - size_t san_len, int* rc_out, uint8_t** issued, - size_t* issued_len) -{ - WolfCertCa ca; - WC_RNG rng; - test_signkey key; - Cert req; - uint8_t csr[CTC_MAX_ALT_SIZE + 4096]; - int csr_len; - - REQUIRE(wc_InitRng(&rng) == 0); - REQUIRE(test_signkey_make(&key, &rng) == 0); - REQUIRE(wc_InitCert(&req) == 0); - strncpy(req.subject.commonName, "san-leaf", CTC_NAME_SIZE - 1); - memcpy(req.altNames, san, san_len); - req.altNamesSz = (int)san_len; - req.sigType = TEST_CERT_SIGTYPE; - csr_len = test_sign_certreq(&req, csr, (int)sizeof(csr), &key, &rng); - test_signkey_free(&key); - wc_FreeRng(&rng); - REQUIRE(csr_len > 0); - - REQUIRE(wolfcert_ca_load(&ca, store, NULL) == WOLFCERT_OK); - *rc_out = wolfcert_ca_issue(&ca, csr, (size_t)csr_len, issued, issued_len); - wolfcert_ca_free(&ca); - return 0; -} - -/* Issued SANs match the CSR in order; unsupported GeneralName forms fail. */ -static int test_issued_san_verbatim(void) -{ - static const uint8_t san[] = { - 0x30, 0x20, - 0x82, 0x09, 'b', '.', 'e', 'x', 'a', 'm', 'p', 'l', 'e', - 0x81, 0x0d, 'a', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', - 'm', - 0x87, 0x04, 127, 0, 0, 1 - }; - static const uint8_t dir_san[] = { - 0x30, 0x12, - 0xa4, 0x10, 0x30, 0x0e, 0x31, 0x0c, 0x30, 0x0a, 0x06, 0x03, 0x55, 0x04, - 0x03, 0x0c, 0x03, 'd', 'i', 'r' - }; - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - WolfCertBuffer ca_cert = { 0 }; - WolfCertBuffer ca_key = { 0 }; - uint8_t* issued = NULL; - size_t issued_len = 0; - DecodedCert dc; - const byte* got = NULL; - word32 got_len = 0; - uint8_t big_san[10 * 1024]; - size_t big_len = 4; - int rc = -1; - - REQUIRE(store != NULL); - REQUIRE(generate_ca_into(store, CA_KEY_TYPES[0], &ca_cert, &ca_key) == 0); - wolfcert_buffer_free(&ca_cert); - wolfcert_buffer_free(&ca_key); - - REQUIRE(issue_with_san(store, dir_san, sizeof(dir_san), &rc, &issued, - &issued_len) == 0); - REQUIRE(rc == WOLFCERT_ERR_UNSUPPORTED); - - /* Over 8 KB of SAN in few entries, so a static-memory pool can parse it. */ - while (big_len + 3 + 240 <= sizeof(big_san)) { - big_san[big_len] = 0x82; - big_san[big_len + 1] = 0x81; - big_san[big_len + 2] = 240; - memset(big_san + big_len + 3, 'a', 240); - big_san[big_len + 3 + 60] = '.'; - big_san[big_len + 3 + 120] = '.'; - big_san[big_len + 3 + 180] = '.'; - big_len += 3 + 240; - } - big_san[0] = 0x30; - big_san[1] = 0x82; - big_san[2] = (uint8_t)((big_len - 4) >> 8); - big_san[3] = (uint8_t)(big_len - 4); - REQUIRE(issue_with_san(store, big_san, big_len, &rc, &issued, - &issued_len) == 0); - REQUIRE(rc == WOLFCERT_OK); - WOLFCERT_XFREE(issued, NULL); - issued = NULL; - REQUIRE(issue_with_san(store, san, sizeof(san), &rc, &issued, - &issued_len) == 0); - wolfcert_store_memory_close(store); - REQUIRE(rc == WOLFCERT_OK); - - wc_InitDecodedCert(&dc, issued, (word32)issued_len, NULL); - rc = wc_ParseCert(&dc, CERT_TYPE, NO_VERIFY, NULL); - if (rc == 0) - rc = wolfcert_find_san(&dc, &got, &got_len); - if (rc == 0 && (got_len != sizeof(san) || - memcmp(got, san, sizeof(san)) != 0)) - rc = -1; - wc_FreeDecodedCert(&dc); - WOLFCERT_XFREE(issued, NULL); - REQUIRE(rc == 0); - return 0; -} - -static int mismatched_ca_rejected(WolfCertKeyType type) -{ - WolfCertStoreOps* src_a = wolfcert_store_memory_open(NULL); - WolfCertStoreOps* src_b = wolfcert_store_memory_open(NULL); - WolfCertStoreOps* mixed = wolfcert_store_memory_open(NULL); - WolfCertBuffer cert_a = { 0 }; - WolfCertBuffer key_a = { 0 }; - WolfCertBuffer cert_b = { 0 }; - WolfCertBuffer key_b = { 0 }; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - REQUIRE(src_a != NULL); - REQUIRE(src_b != NULL); - REQUIRE(mixed != NULL); - - if (generate_ca_into(src_a, type, &cert_a, &key_a)) - return 1; - if (generate_ca_into(src_b, type, &cert_b, &key_b)) - return 1; - REQUIRE(key_a.len != key_b.len || memcmp(key_a.data, key_b.data, key_a.len) != 0); - - REQUIRE(mixed->write(mixed->ctx, "ca.cert.der", cert_a.data, cert_a.len, 0) - == WOLFCERT_OK); - REQUIRE(mixed->write(mixed->ctx, "ca.key.der", key_b.data, key_b.len, 1) - == WOLFCERT_OK); - - ca_store_cfg(&cfg, mixed); - cfg.ca_key_type = type; - cfg.ca_key_param = ca_key_param(type); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_PARSE); - REQUIRE(srv == NULL); - - wolfcert_buffer_free(&cert_a); - wolfcert_buffer_free(&key_a); - wolfcert_buffer_free(&cert_b); - wolfcert_buffer_free(&key_b); - wolfcert_store_memory_close(src_a); - wolfcert_store_memory_close(src_b); - wolfcert_store_memory_close(mixed); - return 0; -} - -static int test_mismatched_ca_rejected(void) -{ - size_t i; - - for (i = 0; i < sizeof(CA_KEY_TYPES) / sizeof(CA_KEY_TYPES[0]); ++i) { - if (mismatched_ca_rejected(CA_KEY_TYPES[i])) - return 1; - } - return 0; -} - -/* The generated CA's key usages and critical basicConstraints. */ -static int ca_key_usage_set(WolfCertKeyType type) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - WolfCertBuffer cert = { 0 }; - WolfCertBuffer key = { 0 }; - DecodedCert dc; - int rc = 0; - - REQUIRE(store != NULL); - - if (generate_ca_into(store, type, &cert, &key)) - return 1; - - wc_InitDecodedCert(&dc, cert.data, (word32)cert.len, NULL); - REQUIRE(wc_ParseCert(&dc, CERT_TYPE, NO_VERIFY, NULL) == 0); - - if (dc.extBasicConstSet == 0 || dc.extBasicConstCrit == 0 || dc.isCA == 0) { - rc = 1; - } - else if (dc.extKeyUsageSet == 0 || - (dc.extKeyUsage & KEYUSE_KEY_CERT_SIGN) == 0 || - (dc.extKeyUsage & KEYUSE_CRL_SIGN) == 0 || - (dc.extKeyUsage & KEYUSE_DIGITAL_SIG) == 0) { - rc = 1; - } - /* Only the RSA CA has keyEncipherment, for the SCEP pkcsPKIEnvelope. */ - else if (((dc.extKeyUsage & KEYUSE_KEY_ENCIPHER) != 0) != - (type == WOLFCERT_KEY_RSA)) { - rc = 1; - } - - wc_FreeDecodedCert(&dc); - wolfcert_buffer_free(&cert); - wolfcert_buffer_free(&key); - wolfcert_store_memory_close(store); - - REQUIRE(rc == 0); - return 0; -} - -static int test_ca_key_usage(void) -{ - size_t i; - - for (i = 0; i < sizeof(CA_KEY_TYPES) / sizeof(CA_KEY_TYPES[0]); ++i) { - if (ca_key_usage_set(CA_KEY_TYPES[i])) - return 1; - } - return 0; -} - -static int test_corrupt_ca_cert_rejected(void) -{ - WolfCertStoreOps* src = wolfcert_store_memory_open(NULL); - WolfCertStoreOps* mixed = wolfcert_store_memory_open(NULL); - WolfCertBuffer cert = { 0 }; - WolfCertBuffer key = { 0 }; - const uint8_t junk[] = { 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - REQUIRE(src != NULL); - REQUIRE(mixed != NULL); - - if (generate_ca_into(src, CA_KEY_TYPE, &cert, &key)) - return 1; - - REQUIRE(mixed->write(mixed->ctx, "ca.cert.der", junk, sizeof(junk), 0) - == WOLFCERT_OK); - REQUIRE(mixed->write(mixed->ctx, "ca.key.der", key.data, key.len, 1) - == WOLFCERT_OK); - - ca_store_cfg(&cfg, mixed); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_PARSE); - REQUIRE(srv == NULL); - - wolfcert_buffer_free(&cert); - wolfcert_buffer_free(&key); - wolfcert_store_memory_close(src); - wolfcert_store_memory_close(mixed); - return 0; -} - -#ifdef WOLFCERT_HAVE_ECC -/* A self-signed non-CA certificate and its key. */ -static int make_leaf_pair(WolfCertBuffer* cert_out, WolfCertBuffer* key_out) -{ - WolfCertKeyCfg kcfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; - WolfCertKey* dk = NULL; - ecc_key wck; - word32 idx = 0; - Cert cert; - WC_RNG rng; - uint8_t der[4096]; - int body, sz; - - REQUIRE(wolfcert_key_generate(&kcfg, &dk) == WOLFCERT_OK); - REQUIRE(wolfcert_key_to_der(dk, key_out) == WOLFCERT_OK); - wolfcert_key_free(dk); - - REQUIRE(wc_ecc_init(&wck) == 0); - REQUIRE(wc_EccPrivateKeyDecode(key_out->data, &idx, &wck, - (word32)key_out->len) == 0); - - wc_InitCert(&cert); - snprintf(cert.subject.commonName, sizeof(cert.subject.commonName), - "%s", "wolfCert Leaf"); - cert.isCA = 0; - cert.selfSigned = 1; - cert.daysValid = 30; - cert.sigType = CTC_SHA256wECDSA; - - REQUIRE(wc_InitRng(&rng) == 0); - body = wc_MakeCert(&cert, der, sizeof(der), NULL, &wck, &rng); - REQUIRE(body > 0); - sz = wc_SignCert(body, cert.sigType, der, sizeof(der), NULL, &wck, &rng); - REQUIRE(sz > 0); - wc_FreeRng(&rng); - wc_ecc_free(&wck); - - cert_out->data = (uint8_t*)WOLFCERT_XMALLOC((size_t)sz, NULL); - REQUIRE(cert_out->data != NULL); - memcpy(cert_out->data, der, (size_t)sz); - cert_out->len = (size_t)sz; - cert_out->heap = NULL; - return 0; -} - -static int test_leaf_ca_rejected(void) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - WolfCertBuffer cert = { 0 }; - WolfCertBuffer key = { 0 }; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - - REQUIRE(store != NULL); - if (make_leaf_pair(&cert, &key)) - return 1; - - REQUIRE(store->write(store->ctx, "ca.cert.der", cert.data, cert.len, 0) - == WOLFCERT_OK); - REQUIRE(store->write(store->ctx, "ca.key.der", key.data, key.len, 1) - == WOLFCERT_OK); - - ca_store_cfg(&cfg, store); - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_PARSE); - REQUIRE(srv == NULL); - - wolfcert_buffer_free(&cert); - wolfcert_buffer_free(&key); - wolfcert_store_memory_close(store); - return 0; -} -#endif /* WOLFCERT_HAVE_ECC */ - -static int test_bad_bind_host_rejected(void) -{ - static const char* const hosts[] = { - "localhost", "::1", "", "127.0.0.300", "127.0.0.1 " - }; - WolfCertServerCfgSrv cfg; - WolfCertServer* srv = NULL; - WolfCertBuffer left = { 0 }; - size_t i; - - for (i = 0; i < sizeof(hosts) / sizeof(hosts[0]); i++) { - WolfCertStoreOps* mem = wolfcert_store_memory_open(NULL); - REQUIRE(mem != NULL); - - ca_store_cfg(&cfg, mem); - cfg.bind_host = hosts[i]; - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_ERR_BAD_ARG); - REQUIRE(srv == NULL); - REQUIRE(mem->read(mem->ctx, "ca.cert.der", &left) == - WOLFCERT_ERR_NOT_FOUND); - REQUIRE(mem->read(mem->ctx, "ca.key.der", &left) == - WOLFCERT_ERR_NOT_FOUND); - wolfcert_store_memory_close(mem); - } - - /* NULL binds every interface and must still start. */ - ca_store_cfg(&cfg, NULL); - cfg.bind_host = NULL; - REQUIRE(wolfcert_server_start(&cfg, &srv) == WOLFCERT_OK); - REQUIRE(wolfcert_server_port(srv) != 0); - wolfcert_server_free(srv); - - return 0; -} - -int main(void) -{ - REQUIRE(test_static_mem_init() == 0); - REQUIRE(wolfcert_init(test_heap_hint()) == WOLFCERT_OK); - -#if CA_STORE_NEEDS_TLS - REQUIRE(gen_server_identity(&srv_cert_pem, &srv_cert_pem_len, - &srv_key_pem, &srv_key_pem_len) == 0); -#endif - - if (test_corrupt_ca_rejected()) - return 1; - if (test_load_io_error_rejected()) - return 1; - if (test_save_failure_rejected()) - return 1; - if (test_save_rollback()) - return 1; - if (test_rollback_unavailable()) - return 1; - if (test_mixed_read_failure()) - return 1; - if (test_partial_store_rejected()) - return 1; - if (test_ca_persists_across_starts()) - return 1; -#if defined(USE_WOLFSSL_MEMORY) && !defined(WOLFSSL_STATIC_MEMORY) && \ - !defined(WOLFSSL_DEBUG_MEMORY) - if (test_start_oom_keeps_credentials()) - return 1; -#endif - if (test_every_alg_reloads()) - return 1; - if (test_mismatched_ca_rejected()) - return 1; - if (test_corrupt_ca_cert_rejected()) - return 1; - if (test_issued_san_verbatim()) - return 1; -#ifdef WOLFCERT_HAVE_ECC - if (test_leaf_ca_rejected()) - return 1; -#endif - if (test_ca_key_usage()) - return 1; - if (test_bad_bind_host_rejected()) - return 1; - -#if CA_STORE_NEEDS_TLS - free(srv_cert_pem); - free(srv_key_pem); -#endif - wolfcert_cleanup(); - printf("OK\n"); - return 0; -} diff --git a/tests/unit/test_store.c b/tests/unit/test_store.c deleted file mode 100644 index 2b513a71..00000000 --- a/tests/unit/test_store.c +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2026 wolfSSL Inc. - * - * This file is part of wolfCert. - * - * wolfCert 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. - * - * wolfCert 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 wolfCert. If not, see . - */ - -#define _POSIX_C_SOURCE 200809L -#define _DEFAULT_SOURCE -#define _DARWIN_C_SOURCE /* expose memmem/strcasestr/INADDR_LOOPBACK on macOS */ - -#include -#include "../test_static_mem.h" - -#include "../integration/tls_test_util.h" - -#include -#include -#include -#include -#include - -#define REQUIRE(cond) \ - do { \ - if (!(cond)) { \ - fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #cond); \ - return 1; \ - } \ - } while (0) - -#ifdef WOLFCERT_HAVE_POSIX_STORE -static int test_posix(void) -{ - char dir[] = "/tmp/wolfcert_store_XXXXXX"; - REQUIRE(mkdtemp(dir) != NULL); - - WolfCertStoreOps* store = wolfcert_store_posix_open(dir, NULL); - REQUIRE(store != NULL); - - WolfCertKeyCfg cfg = { .type = TEST_ENROLL_KEY_TYPE, .param = TEST_ENROLL_KEY_PARAM, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; - WolfCertKey* k = NULL; - REQUIRE(wolfcert_key_generate(&cfg, &k) == WOLFCERT_OK); - REQUIRE(wolfcert_store_write_key(store, "device.key.pem", k) == WOLFCERT_OK); - - struct stat st; - char p[512]; - snprintf(p, sizeof(p), "%s/device.key.pem", dir); - REQUIRE(stat(p, &st) == 0); - REQUIRE((st.st_mode & 0777) == 0600); - - WolfCertKey* k2 = NULL; - REQUIRE(wolfcert_store_read_key(store, "device.key.pem", &k2) == WOLFCERT_OK); - REQUIRE(k2 != NULL); - - const uint8_t fake_cert[] = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; - REQUIRE(wolfcert_store_write_cert(store, "device.crt", fake_cert, sizeof(fake_cert)-1) == WOLFCERT_OK); - WolfCertBuffer rb = { 0 }; - REQUIRE(wolfcert_store_read_cert(store, "device.crt", &rb) == WOLFCERT_OK); - REQUIRE(rb.len == sizeof(fake_cert)-1); - REQUIRE(memcmp(rb.data, fake_cert, rb.len) == 0); - - wolfcert_buffer_free(&rb); - wolfcert_key_free(k); - wolfcert_key_free(k2); - wolfcert_store_posix_close(store); - - char p2[512]; - snprintf(p2, sizeof(p2), "%s/device.crt", dir); - unlink(p); - unlink(p2); - rmdir(dir); - return 0; -} - -#endif /* WOLFCERT_HAVE_POSIX_STORE */ - -static int test_memory(void) -{ - WolfCertStoreOps* store = wolfcert_store_memory_open(NULL); - REQUIRE(store != NULL); - - const uint8_t d[] = "hello"; - REQUIRE(wolfcert_store_write_cert(store, "x", d, sizeof(d)-1) == WOLFCERT_OK); - WolfCertBuffer r = { 0 }; - REQUIRE(wolfcert_store_read_cert(store, "x", &r) == WOLFCERT_OK); - REQUIRE(r.len == sizeof(d)-1 && memcmp(r.data, d, r.len) == 0); - wolfcert_buffer_free(&r); - - REQUIRE(store->remove(store->ctx, "x") == WOLFCERT_OK); - REQUIRE(wolfcert_store_read_cert(store, "x", &r) == WOLFCERT_ERR_NOT_FOUND); - - wolfcert_store_memory_close(store); - return 0; -} - -int main(void) -{ - REQUIRE(test_static_mem_init() == 0); - REQUIRE(wolfcert_init(test_heap_hint()) == WOLFCERT_OK); -#ifdef WOLFCERT_HAVE_POSIX_STORE - if (test_posix()) - return 1; -#endif - if (test_memory()) - return 1; - wolfcert_cleanup(); - printf("OK\n"); - return 0; -} diff --git a/wolfcert/check_config.h b/wolfcert/check_config.h index b4699b73..91c97241 100644 --- a/wolfcert/check_config.h +++ b/wolfcert/check_config.h @@ -56,9 +56,6 @@ !defined(WOLFCERT_NO_BUILTIN_TRANSPORT) #error "Define WOLFCERT_HAVE_BUILTIN_TRANSPORT for the built-in POSIX socket transport, or WOLFCERT_NO_BUILTIN_TRANSPORT to confirm every config supplies its own WolfCertTransport." #endif -#if !defined(WOLFCERT_HAVE_POSIX_STORE) && !defined(WOLFCERT_NO_POSIX_STORE) -#error "Define WOLFCERT_HAVE_POSIX_STORE for the POSIX file store, or WOLFCERT_NO_POSIX_STORE to confirm you supply your own WolfCertStoreOps." -#endif /* Required wolfSSL feature set */ @@ -84,9 +81,6 @@ #ifndef WOLFSSL_KEY_GEN #error "wolfSSL is missing WOLFSSL_KEY_GEN; rebuild wolfSSL with --enable-keygen." #endif -#ifndef WOLF_CRYPTO_CB -#error "wolfSSL is missing WOLF_CRYPTO_CB; rebuild wolfSSL with --enable-cryptocb." -#endif #ifndef WOLFSSL_BASE64_ENCODE #error "wolfSSL is missing WOLFSSL_BASE64_ENCODE; rebuild wolfSSL with --enable-base64encode." #endif diff --git a/wolfcert/client.h b/wolfcert/client.h index 6134a9c4..b01f58d8 100644 --- a/wolfcert/client.h +++ b/wolfcert/client.h @@ -52,7 +52,11 @@ WOLFCERT_API int wolfcert_client_fetch_meta(WolfCertClient* client, /* Generate a new key (honoring cfg->dev_id for CryptoCb offloading), build * a CSR from meta, and enroll. On success out_key owns the key and * out_cert_pem owns the issued certificate. A pending enrollment returns - * WOLFCERT_ERR_PENDING and hands out neither. */ + * WOLFCERT_ERR_PENDING. On any failure neither is handed out, except that a + * key generated under a key_id stays in the backend and out_key still owns + * it, so the caller can delete it there under wolfcert_key_id. Every call + * generates a new key, so polling a pending request with that key takes + * wolfcert_csr_build and wolfcert_est_simple_enroll. */ WOLFCERT_API int wolfcert_client_enroll(WolfCertClient* client, const WolfCertServerCfg* srv, const WolfCertKeyCfg* key_cfg, @@ -63,8 +67,8 @@ WOLFCERT_API int wolfcert_client_enroll(WolfCertClient* client, /* Re-enroll using an existing cert/key; a NULL new_key_cfg reuses the key. * The CSR copies current_cert's Subject and SAN: WOLFCERT_ERR_BAD_ARG if meta * sets them, _PARSE for a bad cert, _UNSUPPORTED if one cannot be carried. - * A pending renewal returns WOLFCERT_ERR_PENDING and hands out neither - * out_key nor out_cert_pem. */ + * A pending renewal returns WOLFCERT_ERR_PENDING. On failure a new key with a + * key_id stays in the backend and in out_key, as for enroll. */ WOLFCERT_API int wolfcert_client_reenroll(WolfCertClient* client, const WolfCertServerCfg* srv, const uint8_t* current_cert, size_t current_cert_len, diff --git a/wolfcert/http.h b/wolfcert/http.h index 619068a3..2be4d3eb 100644 --- a/wolfcert/http.h +++ b/wolfcert/http.h @@ -65,6 +65,9 @@ typedef struct { void* heap; /* NULL -> default */ WolfCertTransport transport; + + /* As in WolfCertServerCfg. */ + const WolfCertKey* client_key_obj; } WolfCertHttpRequest; typedef struct { @@ -108,6 +111,9 @@ typedef struct { void* heap; WolfCertTransport transport; + + /* As in WolfCertServerCfg. */ + const WolfCertKey* client_key_obj; } WolfCertHttpSessionCfg; /* Connects without verifying the server; the first request runs the TLS diff --git a/wolfcert/keygen.h b/wolfcert/keygen.h index 497cd517..861e60f4 100644 --- a/wolfcert/keygen.h +++ b/wolfcert/keygen.h @@ -26,30 +26,47 @@ extern "C" { #endif -typedef struct WolfCertKey WolfCertKey; - -/* Generate a key per cfg. With cfg->dev_id != -1 the key lives in the - * CryptoCb backend registered under that id and the handle only references - * it. The handle is allocated from cfg->heap, or the default heap if NULL. */ +/* Generate a key per cfg on CryptoCb device cfg->dev_id, or in software for + * INVALID_DEVID. An unregistered dev_id, or a key_id without one, is _BAD_ARG; + * either without wolfSSL's WOLF_CRYPTO_CB / WOLF_PRIVATE_KEY_ID is + * _UNSUPPORTED. With cfg->key_id the key stays in the device, under the id + * wolfcert_key_id returns, which the device may have changed. *out_key is NULL + * after a failure, except WOLFCERT_ERR_CRYPTO when the device left an unusable + * id: *out_key then holds the key under the requested id to delete it there. */ WOLFCERT_API int wolfcert_key_generate(const WolfCertKeyCfg* cfg, WolfCertKey** out_key); -/* Load a software key from PEM or DER; the encoding is auto-detected. */ +/* Reference a key a CryptoCb device holds under cfg->key_id, its public half + * from `cert`, PEM or DER: a curve or RSA size keygen makes, matching a + * non-zero cfg->param. Nothing checks that `cert` belongs to that key. + * *out_key is NULL after a failure. */ +WOLFCERT_API int wolfcert_key_from_id(const WolfCertKeyCfg* cfg, + const uint8_t* cert, size_t cert_len, + WolfCertKey** out_key); + +/* Load a software key from PEM or DER, auto-detected, into host memory. */ WOLFCERT_API int wolfcert_key_from_pem(const uint8_t* data, size_t data_len, void* heap, WolfCertKey** out_key); -/* Export a software key as PEM. Fails for keys that live behind a CryptoCb - * that does not permit export. */ +/* Export a software key as PEM. Fails with WOLFCERT_ERR_UNSUPPORTED for a + * key with a key_id or whose private half its device keeps. */ WOLFCERT_API int wolfcert_key_to_pem(const WolfCertKey* key, WolfCertBuffer* out_pem); /* Export a software key as raw DER (same export constraints as * wolfcert_key_to_pem). */ WOLFCERT_API int wolfcert_key_to_der(const WolfCertKey* key, WolfCertBuffer* out_der); +/* Frees the handle; for a key_id key, the device's free callback decides what + * happens to the key it holds. */ WOLFCERT_API void wolfcert_key_free(WolfCertKey* key); -/* Accessors. wolfcert_key_type returns 0 on NULL. */ +/* Accessors. wolfcert_key_type returns 0 on NULL, wolfcert_key_dev_id + * INVALID_DEVID. */ WOLFCERT_API WolfCertKeyType wolfcert_key_type(const WolfCertKey* key); WOLFCERT_API int wolfcert_key_dev_id(const WolfCertKey* key); +/* Points *id at the key's backend id, or NULL with *id_len 0 if it has + * none. The bytes stay owned by the key. */ +WOLFCERT_API int wolfcert_key_id(const WolfCertKey* key, const uint8_t** id, + size_t* id_len); #ifdef __cplusplus } diff --git a/wolfcert/options.h.in b/wolfcert/options.h.in index fc3c51a2..145990f5 100644 --- a/wolfcert/options.h.in +++ b/wolfcert/options.h.in @@ -28,7 +28,6 @@ @WOLFCERT_OPT_SERVER@ /* Platform */ -@WOLFCERT_OPT_POSIX_STORE@ @WOLFCERT_OPT_BUILTIN_TRANSPORT@ /* Key algorithms */ diff --git a/wolfcert/server.h b/wolfcert/server.h index 9df2d6be..d3bff074 100644 --- a/wolfcert/server.h +++ b/wolfcert/server.h @@ -21,7 +21,6 @@ #define WOLFCERT_SERVER_H #include -#include #ifdef __cplusplus extern "C" { @@ -37,22 +36,21 @@ typedef struct { const char* bind_host; /* numeric IPv4, NULL = all * interfaces */ uint16_t bind_port; - WolfCertStoreOps* ca_store; /* optional CA persistence; NULL = - new CA on each start. A store - error fails the start. */ const char* challenge_password; /* SCEP challengePassword to accept; NULL disables */ const char* http_basic_user; /* EST HTTP Basic credentials to accept; NULL disables */ const char* http_basic_pass; /* must be non-empty when http_basic_user is set */ - /* CA configuration. NULL/zero values fall back to library defaults. */ + /* Key for each CA the server generates, including for GetNextCACert. + * NULL/zero values fall back to library defaults. */ WolfCertKeyType ca_key_type; /* WOLFCERT_KEY_RSA default */ int ca_key_param; /* 2048 default for RSA, 256 for ECC */ /* TLS identity, required for EST (wolfcert_server_start() returns * WOLFCERT_ERR_TLS without it) and optional for SCEP. tls_client_ca_pem - * enables mutual TLS; EST /simplereenroll needs it (else 403) and a - * wolfSSL built with KEEP_PEER_CERT (else 500). All three PEM buffers - * are copied by wolfcert_server_start(). */ + * enables mutual TLS; EST /simplereenroll needs it or + * tls_client_trust_issued (else 403) and a wolfSSL built with + * KEEP_PEER_CERT (else 500). All three PEM buffers are copied by + * wolfcert_server_start(). */ const uint8_t* tls_cert_pem; size_t tls_cert_pem_len; const uint8_t* tls_key_pem; @@ -104,9 +102,21 @@ typedef struct { /* Lets EST start with neither Basic nor tls_client_ca_pem. */ int est_allow_anonymous_enroll; - /* SCEP split CA/RA: the CA issues a new RA certificate at every start and - * ca_store does not keep it; the RA decrypts and signs SCEP messages. */ + /* SCEP split CA/RA: the CA issues a new RA certificate at every start to + * decrypt and sign SCEP messages. */ int scep_split_ra; + + /* CA to issue from: one certificate and its key, PEM or DER, copied at + * start. Both NULL generates a CA; one alone is WOLFCERT_ERR_BAD_ARG. */ + const uint8_t* ca_cert; + size_t ca_cert_len; + const uint8_t* ca_key; + size_t ca_key_len; + + /* EST: accept client certificates this CA issued, for /simplereenroll + * only, so with tls_client_ca_pem naming this CA /simpleenroll needs + * Basic. Needs KEEP_PEER_CERT, else start returns UNSUPPORTED. */ + int tls_client_trust_issued; } WolfCertServerCfgSrv; WOLFCERT_API int wolfcert_server_start(const WolfCertServerCfgSrv* cfg, WolfCertServer** out); @@ -119,6 +129,13 @@ WOLFCERT_API void wolfcert_server_free(WolfCertServer* srv); /* Returns the port the server is bound to. Useful after binding on port 0. */ WOLFCERT_API uint16_t wolfcert_server_port(const WolfCertServer* srv); +/* Copies out the CA the server issues from, e.g. to keep a generated one. + * out_key may be NULL; free the key with wolfcert_buffer_free_secure(). */ +WOLFCERT_API int wolfcert_server_get_ca(const WolfCertServer* srv, + WolfCertEncoding enc, + WolfCertBuffer* out_cert, + WolfCertBuffer* out_key); + /* Service exactly one request on an already-accepted connection; the caller * closes fd. WOLFCERT_SERVER_REQUEST_TIMEOUT_MS does not apply. The fd carries * no TLS, so EST enrollment on it needs http_basic_user or diff --git a/wolfcert/store.h b/wolfcert/store.h deleted file mode 100644 index d4e3184d..00000000 --- a/wolfcert/store.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2026 wolfSSL Inc. - * - * This file is part of wolfCert. - * - * wolfCert 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. - * - * wolfCert 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 wolfCert. If not, see . - */ - -#ifndef WOLFCERT_STORE_H -#define WOLFCERT_STORE_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Pluggable storage backend: a vtable plus an opaque context, with slots - * addressed by caller-defined string keys (e.g. "device.crt", "slot/3"). */ - -typedef struct { - /* Read key into a newly allocated buffer; WOLFCERT_ERR_NOT_FOUND if - * absent. */ - int (*read) (void* ctx, const char* key, WolfCertBuffer* out); - /* Write or replace key atomically; sensitive marks a secret value that - * needs tight access modes. */ - int (*write)(void* ctx, const char* key, - const uint8_t* data, size_t len, int sensitive); - /* Remove `key` if present; not-an-error if already absent. */ - int (*remove)(void* ctx, const char* key); - /* Heap hint forwarded into wolfcert allocations done by the backend. */ - void* heap; - /* Backend-private state. */ - void* ctx; -} WolfCertStoreOps; - -/* POSIX-file backend under an existing root_dir; a '/' in a key names a - * subdirectory, which must already exist. Returns NULL on failure or in a - * build without WOLFCERT_HAVE_POSIX_STORE. */ -WOLFCERT_API WolfCertStoreOps* wolfcert_store_posix_open(const char* root_dir, - void* heap); -WOLFCERT_API void wolfcert_store_posix_close(WolfCertStoreOps* ops); - -/* In-memory backend, for tests or an application that persists the output - * itself. */ -WOLFCERT_API WolfCertStoreOps* wolfcert_store_memory_open(void* heap); -WOLFCERT_API void wolfcert_store_memory_close(WolfCertStoreOps* ops); - -/* Cert and key helpers over a store. */ - -WOLFCERT_API int wolfcert_store_write_cert(WolfCertStoreOps* store, - const char* key, - const uint8_t* cert, size_t len); -WOLFCERT_API int wolfcert_store_read_cert(WolfCertStoreOps* store, - const char* key, - WolfCertBuffer* out); - -WOLFCERT_API int wolfcert_store_write_key(WolfCertStoreOps* store, - const char* key_name, - const WolfCertKey* key); -WOLFCERT_API int wolfcert_store_read_key(WolfCertStoreOps* store, - const char* key_name, - WolfCertKey** out_key); - -#ifdef __cplusplus -} -#endif - -#endif /* WOLFCERT_STORE_H */ diff --git a/wolfcert/types.h b/wolfcert/types.h index 9cad4e48..a187e3cd 100644 --- a/wolfcert/types.h +++ b/wolfcert/types.h @@ -31,6 +31,7 @@ #include #include +#include #include @@ -38,6 +39,8 @@ extern "C" { #endif +typedef struct WolfCertKey WolfCertKey; + typedef enum { WOLFCERT_PROTO_EST = 1, WOLFCERT_PROTO_SCEP = 2 @@ -77,18 +80,41 @@ typedef enum { WOLFCERT_KEY_MLDSA87 = 7 } WolfCertKeyType; -/* Keys are offloaded through a wolfSSL CryptoCb devId that the application - * registers; WOLFCERT_DEVID_SOFTWARE selects software. */ -#define WOLFCERT_DEVID_SOFTWARE (-1) +/* Defaults to wolfSSL's default ECC_MAX_ID_LEN / RSA_MAX_ID_LEN. */ +#ifndef WOLFCERT_KEY_ID_MAX_LEN +#define WOLFCERT_KEY_ID_MAX_LEN 32 +#endif typedef struct { WolfCertKeyType type; int param; /* RSA 2048/3072/4096 or ECC 256/384/521 bits */ - int dev_id; /* wolfSSL CryptoCb devId; -1 for software */ - const char* key_label; /* optional backend identifier for persistent keys */ + int dev_id; /* devId as given; INVALID_DEVID = software */ void* heap; /* optional heap hint; NULL = default */ + /* Backend key id, opaque to wolfCert; needs a devId. Up to + * WOLFCERT_KEY_ID_MAX_LEN bytes. */ + const uint8_t* key_id; + size_t key_id_len; } WolfCertKeyCfg; +/* Start value of the default devId; user_settings.h may override it. */ +#ifndef WOLFCERT_DEFAULT_DEVID + #if defined(WC_USE_DEVID) && defined(WOLF_CRYPTO_CB) + #define WOLFCERT_DEFAULT_DEVID WC_USE_DEVID + #else + #define WOLFCERT_DEFAULT_DEVID INVALID_DEVID + #endif +#endif +#if !defined(WOLF_CRYPTO_CB) && WOLFCERT_DEFAULT_DEVID != INVALID_DEVID + #error "WOLFCERT_DEFAULT_DEVID needs wolfSSL built with WOLF_CRYPTO_CB" +#endif + +/* Registered devId for the TLS contexts and SCEP PKCS#7 objects wolfCert + * creates; keys, their keygen and CSRs use their own. BAD_ARG for an + * unregistered devId, UNSUPPORTED without WOLF_CRYPTO_CB. Set it before + * threads use wolfCert. */ +WOLFCERT_API int wolfcert_set_default_dev_id(int dev_id); +WOLFCERT_API int wolfcert_default_dev_id(void); + /* Called by wolfcert_csr_build() once the standard fields are set, with the * wolfSSL Cert* to add what wolfCert does not expose; any error aborts. * A renewal then overwrites Cert's subject and altNames from current_cert. */ @@ -233,6 +259,10 @@ typedef struct { void* heap; WolfCertTransport transport; + + /* Instead of client_key: the TLS client key as a key handle, borrowed + * while an https:// connection opens; a key_id key signs in its device. */ + const WolfCertKey* client_key_obj; } WolfCertServerCfg; /* Caller-owned byte buffer filled by the library. wolfcert_buffer_free() @@ -244,6 +274,8 @@ typedef struct { } WolfCertBuffer; WOLFCERT_API void wolfcert_buffer_free(WolfCertBuffer* buf); +/* wolfcert_buffer_free() after wiping data, for a buffer holding a key. */ +WOLFCERT_API void wolfcert_buffer_free_secure(WolfCertBuffer* buf); #ifdef __cplusplus } diff --git a/wolfcert/wolfcert.h b/wolfcert/wolfcert.h index 42be2006..b8e15c7a 100644 --- a/wolfcert/wolfcert.h +++ b/wolfcert/wolfcert.h @@ -34,7 +34,6 @@ #include #include #include -#include #include #ifdef WOLFCERT_HAVE_EST # include diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index e8d914e4..c9c6148f 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -26,8 +26,6 @@ if(CONFIG_WOLFCERT) _wc_opt(WOLFCERT_OPT_SCEP "${CONFIG_WOLFCERT_SCEP}" WOLFCERT_HAVE_SCEP) # Host-only; zephyr/README.md says why. _wc_opt(WOLFCERT_OPT_SERVER "OFF" WOLFCERT_HAVE_SERVER) - _wc_plat(WOLFCERT_OPT_POSIX_STORE "OFF" - WOLFCERT_HAVE_POSIX_STORE WOLFCERT_NO_POSIX_STORE) _wc_plat(WOLFCERT_OPT_BUILTIN_TRANSPORT "${CONFIG_WOLFCERT_BUILTIN_TRANSPORT}" WOLFCERT_HAVE_BUILTIN_TRANSPORT WOLFCERT_NO_BUILTIN_TRANSPORT) _wc_opt(WOLFCERT_OPT_RSA "${CONFIG_WOLFCERT_RSA}" WOLFCERT_HAVE_RSA) @@ -55,7 +53,6 @@ if(CONFIG_WOLFCERT) ${WOLFCERT_DIR}/src/key_algs.c ${WOLFCERT_DIR}/src/keygen.c ${WOLFCERT_DIR}/src/csr.c - ${WOLFCERT_DIR}/src/store.c ${WOLFCERT_DIR}/src/http.c ${WOLFCERT_DIR}/src/client.c) diff --git a/zephyr/README.md b/zephyr/README.md index 1b58ad12..894fe558 100644 --- a/zephyr/README.md +++ b/zephyr/README.md @@ -227,8 +227,7 @@ needs changing. `prj.conf` leaves these to the board: clock — [`docs/EMBEDDED.md` section 8](../docs/EMBEDDED.md#8-zephyr) explains why. - **Keeping the key and certificate.** They are freed here. A real device - writes them through a `WolfCertStoreOps` — on Zephyr, one over NVS or the - settings subsystem. + writes them to NVS or the settings subsystem. ## Running the tests diff --git a/zephyr/include.am b/zephyr/include.am index bce8f8eb..34d4a390 100644 --- a/zephyr/include.am +++ b/zephyr/include.am @@ -42,7 +42,4 @@ EXTRA_DIST += zephyr/tests/wolfcert_unit_scep_msg/testcase.yaml EXTRA_DIST += zephyr/tests/wolfcert_unit_smoke/CMakeLists.txt EXTRA_DIST += zephyr/tests/wolfcert_unit_smoke/prj.conf EXTRA_DIST += zephyr/tests/wolfcert_unit_smoke/testcase.yaml -EXTRA_DIST += zephyr/tests/wolfcert_unit_store/CMakeLists.txt -EXTRA_DIST += zephyr/tests/wolfcert_unit_store/prj.conf -EXTRA_DIST += zephyr/tests/wolfcert_unit_store/testcase.yaml EXTRA_DIST += zephyr/wolfssl_user_settings.h diff --git a/zephyr/samples/wolfcert_est_client/src/main.c b/zephyr/samples/wolfcert_est_client/src/main.c index 0f6febc1..5e6f07a4 100644 --- a/zephyr/samples/wolfcert_est_client/src/main.c +++ b/zephyr/samples/wolfcert_est_client/src/main.c @@ -72,7 +72,7 @@ static int enroll(void) .verify_server = 1, }; WolfCertKeyCfg key_cfg = { .type = WOLFCERT_KEY_ECC, .param = 256, - .dev_id = WOLFCERT_DEVID_SOFTWARE }; + .dev_id = INVALID_DEVID }; WolfCertCertMeta meta = { .subject_dn = CONFIG_WOLFCERT_SAMPLE_SUBJECT }; WolfCertClient* client = NULL; WolfCertKey* key = NULL; diff --git a/zephyr/tests/wolfcert_unit_store/CMakeLists.txt b/zephyr/tests/wolfcert_unit_store/CMakeLists.txt deleted file mode 100644 index c08f0e1c..00000000 --- a/zephyr/tests/wolfcert_unit_store/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -# SPDX-License-Identifier: GPL-3.0-or-later -cmake_minimum_required(VERSION 3.20.0) - -set(CONF_FILE - ${CMAKE_CURRENT_LIST_DIR}/../common/wolfcert.conf - ${CMAKE_CURRENT_LIST_DIR}/prj.conf) - -find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) -project(wolfcert_unit_store) - -include(${ZEPHYR_WOLFCERT_MODULE_DIR}/zephyr/tests/common/unit_test.cmake) -wolfcert_zephyr_unit_test(test_store) diff --git a/zephyr/tests/wolfcert_unit_store/prj.conf b/zephyr/tests/wolfcert_unit_store/prj.conf deleted file mode 100644 index b7e9b380..00000000 --- a/zephyr/tests/wolfcert_unit_store/prj.conf +++ /dev/null @@ -1,4 +0,0 @@ -CONFIG_WOLFCERT_EST=y -CONFIG_WOLFCERT_RSA=y -CONFIG_WOLFCERT_ECC=y -CONFIG_WOLFCERT_ED25519=y diff --git a/zephyr/tests/wolfcert_unit_store/testcase.yaml b/zephyr/tests/wolfcert_unit_store/testcase.yaml deleted file mode 100644 index 5be1f102..00000000 --- a/zephyr/tests/wolfcert_unit_store/testcase.yaml +++ /dev/null @@ -1,14 +0,0 @@ -common: - tags: - - wolfcert - harness: console - harness_config: - type: one_line - regex: - - "WOLFCERT TEST RESULT: 0" -tests: - wolfcert.unit.store: - timeout: 180 - platform_allow: qemu_x86 - integration_platforms: - - qemu_x86