From 1d86c3347e82f7675027ae01c814fe1c8664215d Mon Sep 17 00:00:00 2001 From: Alex J Lennon Date: Fri, 4 Dec 2026 09:37:59 +0000 Subject: [PATCH 1/3] Add D1 mini hybrid HTTPS feasibility prototype Target ESP8266 RTOS SDK with a pinned wolfSSL ML-KEM-768 profile, strict public-CA TLS verification, bounded HTTP parsing, memory instrumentation and runner-only cross-build support. No hardware execution or ML-DSA claim. Assisted-by: Briar --- .github/workflows/esp8266-images.yml | 38 +++ .gitignore | 3 + README.md | 7 + ci/esp8266.Dockerfile | 12 + ci/esp8266_images.py | 154 ++++++++++ docs/esp8266-d1mini.md | 132 +++++++++ firmware/esp8266/Makefile | 3 + .../esp8266/components/wolfssl/component.mk | 6 + .../wolfssl/include/user_settings.h | 54 ++++ firmware/esp8266/main/component.mk | 3 + firmware/esp8266/main/main.c | 262 ++++++++++++++++++ firmware/esp8266/main/response.c | 48 ++++ firmware/esp8266/main/response.h | 8 + firmware/esp8266/main/trust-anchor.pem | 14 + firmware/esp8266/sdkconfig.defaults | 3 + tests/test_esp8266.py | 108 ++++++++ 16 files changed, 855 insertions(+) create mode 100644 .github/workflows/esp8266-images.yml create mode 100644 ci/esp8266.Dockerfile create mode 100644 ci/esp8266_images.py create mode 100644 docs/esp8266-d1mini.md create mode 100644 firmware/esp8266/Makefile create mode 100644 firmware/esp8266/components/wolfssl/component.mk create mode 100644 firmware/esp8266/components/wolfssl/include/user_settings.h create mode 100644 firmware/esp8266/main/component.mk create mode 100644 firmware/esp8266/main/main.c create mode 100644 firmware/esp8266/main/response.c create mode 100644 firmware/esp8266/main/response.h create mode 100644 firmware/esp8266/main/trust-anchor.pem create mode 100644 firmware/esp8266/sdkconfig.defaults create mode 100644 tests/test_esp8266.py diff --git a/.github/workflows/esp8266-images.yml b/.github/workflows/esp8266-images.yml new file mode 100644 index 0000000..5ef0526 --- /dev/null +++ b/.github/workflows/esp8266-images.yml @@ -0,0 +1,38 @@ +name: ESP8266 D1 mini prototype +on: + pull_request: + paths: ['firmware/esp8266/**', 'ci/esp8266*', '.github/workflows/esp8266-images.yml'] + workflow_dispatch: +permissions: + contents: read + actions: read +concurrency: + # Serialise jobs sharing this mutable SDK/toolchain cache; don't cancel a build. + group: pqc-esp8266-images + cancel-in-progress: false +jobs: + d1mini-build: + if: >- + github.repository == 'DynamicDevices/pqc-testing' && github.actor == 'ajlennon' && + (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) + runs-on: [self-hosted, Linux, X64, dd-esl-proxmox] + # Includes cold image package setup, SDK/submodules and the 89MB toolchain. + # Reuses runner-local Docker layers/downloads on subsequent corrected builds. + timeout-minutes: 45 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6, Node24 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Build only on the registered DD organisation runner + env: + GH_TOKEN: ${{ github.token }} + run: python3 ci/esp8266_images.py build + - name: Retain static-memory evidence (not firmware distribution) + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6, Node24 + with: + name: d1mini-build-evidence + if-no-files-found: error + path: | + firmware/esp8266/build/d1mini_hybrid_https.map + firmware/esp8266/build/build-evidence.json diff --git a/.gitignore b/.gitignore index 82080ff..290afc7 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,6 @@ certs/private/ vendor/ zephyr-workspace/ results.json +.deps/ +firmware/esp8266/sdkconfig +firmware/esp8266/components/wolfssl/upstream diff --git a/README.md b/README.md index 0549c8b..5d72d20 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,13 @@ browser trust, while the Python runner independently observes TLS/group evidence See [browser setup and limitations](docs/browser-tests.md) and [dated results](docs/testing-results.md). +## ESP8266 D1 mini experiment + +The [D1 mini hybrid-HTTPS prototype](docs/esp8266-d1mini.md) targets the ESP8266 +with ESP8266_RTOS_SDK and wolfSSL, separately from the ESP32/Zephyr work. +It is build-only until physical-device TLS, RAM/stack and watchdog evidence is +collected. ML-DSA certificate authentication is not implemented or proved. + ## Test the running HTTPS and MQTT servers Run the explained 25-test table against an authorised lab: diff --git a/ci/esp8266.Dockerfile b/ci/esp8266.Dockerfile new file mode 100644 index 0000000..31d3c84 --- /dev/null +++ b/ci/esp8266.Dockerfile @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: MIT +# Legacy SDK tooling, isolated from the runner OS and never shipped on-device. +FROM ubuntu:20.04@sha256:c664f8f86ed5a386b0a340d981b8f81714e21a8b9c73f658c4bea56aa179d54a +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates git make gcc g++ libncurses5 flex bison gperf \ + python3 python3-pip python-is-python3 cmake ninja-build xz-utils \ + && rm -rf /var/lib/apt/lists/* +RUN python3 -m pip install --no-cache-dir \ + setuptools==57.5.0 click==7.1.2 pyserial==3.5 future==0.18.3 \ + cryptography==3.4.8 pyparsing==2.3.1 pyelftools==0.29 +WORKDIR /work diff --git a/ci/esp8266_images.py b/ci/esp8266_images.py new file mode 100644 index 0000000..e7dd405 --- /dev/null +++ b/ci/esp8266_images.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""D1 mini build-only experiment, restricted to the existing DD runner. + +No flashing, credentials in images, local compilation fallback or success claim +from an ELF alone. Native host parser tests are separate from firmware builds. +Assisted-by: Briar +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tarfile +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +import ci_runner + +SDK = "89a3f254b63819035f65d9c5dcdae8864f1a6a8a" +WOLFSSL = "3c5eead44904df64e6a5a1f4ebdce377d35a849a" +TOOLCHAIN_URL = "https://dl.espressif.com/dl/xtensa-lx106-elf-gcc8_4_0-esp-2020r3-linux-amd64.tar.gz" +TOOLCHAIN_SHA256 = "0a1804b5e2231c6db8b72af6bc2a0f9a5b6994cfba29956d412651109f13fe7e" +PROJECT = ROOT / "firmware/esp8266" + + +def command(args, **kwargs): + return subprocess.run([str(x) for x in args], check=True, **kwargs) + + +def digest(path): + with Path(path).open("rb") as source: + return hashlib.file_digest(source, "sha256").hexdigest() if hasattr(hashlib, "file_digest") else _old_digest(source) + + +def _old_digest(source): + result = hashlib.sha256() + for block in iter(lambda: source.read(1024 * 1024), b""): + result.update(block) + return result.hexdigest() + + +def checkout(cache, name, url, commit): + dest = cache / name + if not dest.exists(): + dest.mkdir() + command(["git", "init", "-q", dest]) + command(["git", "-C", dest, "remote", "add", "origin", url]) + command(["git", "-C", dest, "fetch", "--depth", "1", "origin", commit]) + command(["git", "-C", dest, "checkout", "--detach", "FETCH_HEAD"]) + head = subprocess.check_output(["git", "-C", str(dest), "rev-parse", "HEAD"], text=True).strip() + dirty = subprocess.check_output(["git", "-C", str(dest), "status", "--porcelain", "--untracked-files=no"], text=True) + if head != commit or dirty or dest.is_symlink(): + raise RuntimeError("Dependency cache drift: " + name) + return dest + + +def unpack_toolchain(archive, cache): + """Reject traversal/link payloads even after verifying the upstream digest.""" + if digest(archive) != TOOLCHAIN_SHA256: + raise RuntimeError("Toolchain checksum mismatch") + with tarfile.open(archive, "r:gz") as source: + members = source.getmembers() + for item in members: + path = Path(item.name) + if path.is_absolute() or ".." in path.parts or not path.parts or path.parts[0] != "xtensa-lx106-elf": + raise RuntimeError("Unsafe toolchain archive path") + if not (item.isfile() or item.isdir() or item.issym() or item.islnk()): + raise RuntimeError("Unsupported toolchain archive member") + if item.issym() or item.islnk(): + link = Path(item.linkname) + target = path.parent / link if item.issym() else link + resolved = (cache / target).resolve() + if link.is_absolute() or not str(resolved).startswith(str((cache / "xtensa-lx106-elf").resolve()) + os.sep): + raise RuntimeError("Unsafe toolchain archive link") + source.extractall(cache, members=members) + + +def container_build(): + # Independent authenticated binding inside the container too; do not make + # a command-line switch or environment marker a local-build bypass. + ci_runner.main("d1mini-build") + os.environ.pop("GH_TOKEN", None) + cache = Path("/cache") + sdk = checkout(cache, "sdk-" + SDK, "https://github.com/espressif/ESP8266_RTOS_SDK.git", SDK) + command(["git", "-C", sdk, "submodule", "update", "--init", "--recursive", + "components/json/cJSON", "components/lwip/lwip", "components/mbedtls/mbedtls"]) + wolf = checkout(cache, "wolfssl-" + WOLFSSL, "https://github.com/wolfSSL/wolfssl.git", WOLFSSL) + archive = cache / (TOOLCHAIN_SHA256 + ".tar.gz") + if not archive.exists(): + urllib.request.urlretrieve(TOOLCHAIN_URL, archive) + # Extract the verified archive afresh rather than trusting mutable cached + # compiler executables. Docker's package layer remains reusable. + tools = PROJECT / "build-tools" + if tools.exists(): + raise RuntimeError("Expected a fresh isolated build-tools directory") + tools.mkdir() + unpack_toolchain(archive, tools) + upstream = PROJECT / "components/wolfssl/upstream" + if upstream.exists() or upstream.is_symlink(): + raise RuntimeError("Refuse an existing wolfSSL component link") + upstream.symlink_to(wolf, target_is_directory=True) + os.environ["IDF_PATH"] = str(sdk) + os.environ["PYTHON"] = sys.executable + os.environ["PATH"] = str(tools / "xtensa-lx106-elf/bin") + os.pathsep + os.environ["PATH"] + command(["make", "defconfig"], cwd=PROJECT) + command(["make", "-j2", "all"], cwd=PROJECT) + elf = PROJECT / "build/d1mini_hybrid_https.elf" + command(["xtensa-lx106-elf-size", elf]) + config = (PROJECT / "sdkconfig").read_text() + if "CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y" not in config: + raise RuntimeError("Wrong flash layout for the selected D1 mini") + result = { + "target": "LOLIN D1 mini ESP8266EX 4MB", "sdk": SDK, "wolfssl": WOLFSSL, + "toolchain_sha256": TOOLCHAIN_SHA256, + "source_commit": os.environ["PQC_SOURCE_COMMIT"], "elf_sha256": digest(elf), + "build_only": True, "physical_execution": False, + "peak_ram_stack_watchdog_and_tls_interop": "UNTESTED", + } + (PROJECT / "build/build-evidence.json").write_text(json.dumps(result, indent=2) + "\n") + + +def build(): + ci_runner.main("d1mini-build") + source = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip() + if not shutil.which("docker"): + raise RuntimeError("Existing runner Docker unavailable; no host install or fallback") + dockerfile = ROOT / "ci/esp8266.Dockerfile" + image = "pqc-d1mini-builder:" + digest(dockerfile)[:20] + # Persistent runner-local Docker layers and download cache, not remote + # cache archives. Only repository-owned trusted jobs may use this cache. + cache = Path(os.environ["RUNNER_WORKSPACE"]).parent / ".pqc-esp8266-cache" + cache.mkdir(mode=0o700, exist_ok=True) + if cache.is_symlink() or cache.stat().st_uid != os.getuid() or cache.stat().st_mode & 0o022: + raise RuntimeError("Untrusted runner-local cache owner/path") + command(["docker", "build", "--file", dockerfile, "--tag", image, ROOT / "ci"]) + args = ["docker", "run", "--rm", "--cap-drop=ALL", "--security-opt=no-new-privileges", + "--user", f"{os.getuid()}:{os.getgid()}", "--env", "HOME=/tmp", + "--env", "PQC_SOURCE_COMMIT=" + source, + "--volume", str(ROOT) + ":/work", "--volume", str(cache) + ":/cache"] + for name in ("GH_TOKEN", "GITHUB_ACTIONS", "GITHUB_REPOSITORY", "GITHUB_RUN_ID", "RUNNER_NAME"): + args += ["--env", name] + command(args + [image, "python3", "/work/ci/esp8266_images.py", "container"]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("build", "container")) + args = parser.parse_args() + (build if args.action == "build" else container_build)() diff --git a/docs/esp8266-d1mini.md b/docs/esp8266-d1mini.md new file mode 100644 index 0000000..cf9f410 --- /dev/null +++ b/docs/esp8266-d1mini.md @@ -0,0 +1,132 @@ +# ESP8266 D1 mini: experimental hybrid HTTPS client + +Target: LOLIN D1 mini, ESP8266EX, **4 MB flash**. This is separate from the +ESP32/Zephyr work: no Zephyr target, ESP-IDF firmware or ESP32 binary is reused. +The chip's approximately 50 KB station-mode heap/data budget is not 4 MB RAM. + +## First milestone and present limits + +The first experiment is a **direct device-to-server** connection to +`https://mqtt.dynamicdevices.co.uk:8091/`: TLS 1.3, the final X25519MLKEM768 +group (4588), and ordinary public-CA ECDSA server authentication. It requests +the real page, checks HTTP 200, bounded Content-Length framing and a `PQC` body +marker, and reports the negotiated group, version, cipher and memory watermarks. +The body marker is an application-delivery check, not an attestation mechanism. + +Source preparation, host parser tests and a cross-build are **not device +interoperability, peak-memory or watchdog acceptance**. No board has been +flashed or run by this work. MQTTS/WSS and strict ML-DSA-65 authentication on +8090/8890/8891 are not implemented here. A signature-only test, desktop TLS +connection or proxy does not establish direct ESP8266 PQC TLS support. + +## Dependencies and deliberate configuration + +The builder pins: + +* [ESP8266_RTOS_SDK v3.4](https://github.com/espressif/ESP8266_RTOS_SDK/tree/89a3f254b63819035f65d9c5dcdae8864f1a6a8a), + commit `89a3f254b63819035f65d9c5dcdae8864f1a6a8a`. +* [wolfSSL v5.9.4-stable](https://github.com/wolfSSL/wolfssl/tree/3c5eead44904df64e6a5a1f4ebdce377d35a849a), + commit `3c5eead44904df64e6a5a1f4ebdce377d35a849a`. +* Espressif GCC 8.4.0, esp-2020r3, x86-64 Linux toolchain, SHA-256 + `0a1804b5e2231c6db8b72af6bc2a0f9a5b6994cfba29956d412651109f13fe7e`, + matching that SDK's `tools/tools.json`. + +The SDK's bundled Mbed TLS 2.16.5 and Arduino's TLS1.2 BearSSL are not used for +the application TLS connection. The project uses wolfSSL's generic software +path with application I/O and an SDK RNG seed callback, rather than inheriting +Espressif defaults which disable Curve25519/ML-KEM-768 in some configurations. +Only ML-KEM-768 is enabled; key generation uses the small-memory path. The TLS +client needs key generation and decapsulation, not encapsulation. No legacy +Kyber group IDs, standalone KEM fallback or permissive certificate callbacks. + +`main/trust-anchor.pem` is the public +[ISRG Root X2](https://letsencrypt.org/certs/isrg-root-x2.pem), SHA-256 of the +PEM file `a13d881e11fe6df181b53841f9fa738a2d7ca9ae7be3d53c866f722b4242b013`. +The observed 8091 chain can terminate at this ECDSA root even though the server +also sends an RSA-cross-signed X2 certificate. Actual wolfSSL path construction +on the target remains a test, not an assumption of compatibility. A changed +public CA chain may need an independently reviewed trust-anchor update. + +The old SDK/toolchain and isolated Ubuntu20.04/Python3.8 build environment are +maintenance liabilities. Container/toolchain pins do not establish security, +fully reproducible builds or a supported production platform; installed distro +packages are not individually pinned. No host packages, runner service changes, +local firmware builds or hosted runners are permitted. SDK portability failures +must be diagnosed; never disable verification or watchdogs to obtain a pass. + +Original adapter sources remain MIT. wolfSSL is separately GPLv3-or-later or +commercially licensed; a linked experimental image is **not MIT-only**. +Retain wolfSSL's licence/source obligations when distributing it. The SDK and +toolchain retain their own upstream licences, including component-specific +terms for binary-only libraries. Public firmware distribution is withheld until +the combined-image licence compatibility and corresponding-source package are +reviewed; CI uploads only memory/evidence files. This is not a product licensing +or compliance approval. + +## Build and evidence + +The `ESP8266 D1 mini prototype` workflow runs on own-repository PRs touching +these files. Both the outer builder and container independently check the +authenticated GitHub job assignment through `ci_runner.py`. Only the existing +registered DD organisation executor is admitted; absence/mismatch is fatal. +This is a procedural location guard, not a claim that job code is contained +against a compromised runner. Never emulate its environment to build locally. + +Docker package layers and verified upstream downloads use persistent +runner-local caches. A job re-extracts the checksum-verified compiler into its +isolated workspace and checks cached source commit/cleanliness. Jobs sharing +that mutable cache are serialized. The 45-minute enforced deadline includes +cold container/dependency setup and compilation; it is not a measured build ETA. + +CI builds ELF/BIN/map and retains the map plus `build-evidence.json`: exact source and dependency +identities, image digest and explicit `build_only=true`, `physical_execution=false`. +The compiler's size/map report describes **static** RAM/flash, not peak use. +Artifacts have no Wi-Fi credentials. There is deliberately no flashing command. + +Host-only regression: + +```sh +python3 -m unittest discover -s tests -p test_esp8266.py -v +``` + +This compiles only the portable HTTP parser with the workstation's native C +compiler; it does not compile ESP8266 firmware. Tests cover fragmented headers, +wrong status, missing/duplicate/invalid Content-Length, unsupported transfer +encoding, header limits, archive traversal and refusal of local build paths. + +## Future physical test: separate authorisation and provisioning + +The image stops with `NOT_CONFIGURED` unless its device-local `pqc_test` NVS +namespace contains `ssid`, `password` and `utc_epoch`. Provisioning tooling is +not included and credentials must never be embedded in CI artifacts. NVS must +not be erased to overcome an error. Empty/unconfigured NVS is expected for a +public image, not a successful TLS test. + +Before each cold-boot experiment, a trusted, separately authorised local +procedure must refresh `utc_epoch` to current UTC. Stored time is **not an +authenticated production clock or replay defence**. Certificate date checking +remains enabled. Wi-Fi must be active before SDK hardware RNG use; disconnection +prevents fresh seeding. Provisioning, entropy quality, side channels and a +production time/update strategy still need their own assessment. + +On a designated development board, record: + +1. Source/image identity, SDK/library versions and reset cause. +2. Before/after handshake free heap, lifetime minimum free heap and task stack + high-water bytes (the selected SDK's StackType_t is one byte). Include Wi-Fi + allocations, largest free block/fragmentation if supported, elapsed time, + repeated-run leaks and watchdog resets. Current logs do not measure energy, + largest free block or a full per-subsystem heap trace. +3. TLS1.3/X25519MLKEM768 with verified trust/name/date and actual HTTP delivery. +4. Only after a positive baseline, the classical-group, TLS1.2, wrong-name and + no-trust probes. Each logs its exact error as `REQUIRES_REVIEW`: an OOM, + network failure or unsupported local configuration is **inconclusive**, not + a valid server-policy negative. Unexpected TLS success is a failure. + +Expired-certificate and malformed-chain fixtures still need controlled +on-target coverage. MQTT authentication/ACL and native WSS delivery negatives +belong to later clients; they cannot be inferred from HTTPS handshake rejection. +An eventual successful 8091 run proves hybrid confidentiality with classical +authentication, **not post-quantum authentication or compliance**. + +Assisted-by: Briar diff --git a/firmware/esp8266/Makefile b/firmware/esp8266/Makefile new file mode 100644 index 0000000..740a692 --- /dev/null +++ b/firmware/esp8266/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +PROJECT_NAME := d1mini_hybrid_https +include $(IDF_PATH)/make/project.mk diff --git a/firmware/esp8266/components/wolfssl/component.mk b/firmware/esp8266/components/wolfssl/component.mk new file mode 100644 index 0000000..77be692 --- /dev/null +++ b/firmware/esp8266/components/wolfssl/component.mk @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: MIT +# The CI adapter links upstream to the independently pinned wolfSSL checkout. +COMPONENT_ADD_INCLUDEDIRS := include upstream +COMPONENT_SRCDIRS := upstream/src upstream/wolfcrypt/src +COMPONENT_OBJEXCLUDE := upstream/wolfcrypt/src/misc.o upstream/wolfcrypt/src/evp.o upstream/src/bio.o +CFLAGS += -DWOLFSSL_USER_SETTINGS diff --git a/firmware/esp8266/components/wolfssl/include/user_settings.h b/firmware/esp8266/components/wolfssl/include/user_settings.h new file mode 100644 index 0000000..20d5aaa --- /dev/null +++ b/firmware/esp8266/components/wolfssl/include/user_settings.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: MIT + * Experimental software-only FreeRTOS port; NOT the ESP32 default profile. + * Assisted-by: Briar + */ +#ifndef D1MINI_USER_SETTINGS_H +#define D1MINI_USER_SETTINGS_H + +#define SINGLE_THREADED /* Only the HTTPS task may call wolfSSL. */ +#define WOLFSSL_USER_IO +#define NO_FILESYSTEM +#define NO_WRITEV +#define NO_DEV_RANDOM +#define WOLFSSL_SMALL_STACK +#define NO_SESSION_CACHE +#define NO_WOLFSSL_SERVER +#define NO_OLD_TLS +#define NO_RSA +#define NO_DH +#define NO_DSA +#define NO_RC4 +#define NO_DES3 +#define NO_MD4 +#define WOLFSSL_SP_MATH_ALL +#define WOLFSSL_SP_SMALL +#define WOLFSSL_SP_NO_ASM +#define WOLFSSL_TLS13 +#define HAVE_TLS_EXTENSIONS +#define HAVE_SUPPORTED_CURVES +#define HAVE_SNI +#define HAVE_HKDF +#define HAVE_AESGCM +#define HAVE_ECC +#define ECC_USER_CURVES +#define HAVE_ECC256 +#define HAVE_ECC384 /* Public ISRG Root X2 trust anchor. */ +#define ECC_TIMING_RESISTANT +#define HAVE_CURVE25519 +#define CURVE25519_SMALL +#define WOLFSSL_SHA384 +#define WOLFSSL_SHA512 +#define WOLFSSL_SHA3 +#define WOLFSSL_HAVE_MLKEM +#define WOLFSSL_PQC_HYBRIDS +#define WOLFSSL_NO_ML_KEM_512 +#define WOLFSSL_NO_ML_KEM_1024 +#define WOLFSSL_MLKEM_MAKEKEY_SMALL_MEM +#define WOLFSSL_MLKEM_DYNAMIC_KEYS +#define WOLFSSL_MLKEM_NO_ENCAPSULATE /* TLS client makes keys and decapsulates. */ +#define WOLFSSL_TLS_NO_MLKEM_STANDALONE + +/* Seed the library DRBG from the SDK hardware RNG only with Wi-Fi active. */ +int pqc_random_seed(unsigned char *out, unsigned int size); +#define CUSTOM_RAND_GENERATE_SEED pqc_random_seed +#endif diff --git a/firmware/esp8266/main/component.mk b/firmware/esp8266/main/component.mk new file mode 100644 index 0000000..5806284 --- /dev/null +++ b/firmware/esp8266/main/component.mk @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT +COMPONENT_EMBED_TXTFILES := trust-anchor.pem +CFLAGS += -DWOLFSSL_USER_SETTINGS diff --git a/firmware/esp8266/main/main.c b/firmware/esp8266/main/main.c new file mode 100644 index 0000000..6fc8ad9 --- /dev/null +++ b/firmware/esp8266/main/main.c @@ -0,0 +1,262 @@ +/* SPDX-License-Identifier: MIT + * D1 mini feasibility probe: no firmware success claim without device evidence. + * Assisted-by: Briar + */ +#include +#include +#include +#include +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_event.h" +#include "esp_netif.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "nvs.h" +#include "nvs_flash.h" +#include "lwip/netdb.h" +#include "lwip/sockets.h" +#include +#include +#include "response.h" + +#define HOST "mqtt.dynamicdevices.co.uk" +#define PORT "8091" +#define UP BIT0 +#define DOWN BIT1 +static EventGroupHandle_t wifi_events; +static volatile int wifi_ready; +extern const unsigned char root_start[] asm("_binary_trust_anchor_pem_start"); +extern const unsigned char root_end[] asm("_binary_trust_anchor_pem_end"); +static char headers[4096]; /* Static data is included in the linker RAM report. */ + +int pqc_random_seed(unsigned char *out, unsigned int size) +{ + if (!wifi_ready) return -1; + esp_fill_random(out, size); + return 0; +} + +static void memory(const char *phase) +{ + printf("MEM phase=%s free_heap=%u minimum_free_heap=%u stack_free_bytes=%u\n", + phase, (unsigned)esp_get_free_heap_size(), + (unsigned)esp_get_minimum_free_heap_size(), + (unsigned)(uxTaskGetStackHighWaterMark(NULL) * sizeof(StackType_t))); +} + +static void event(void *arg, esp_event_base_t base, int32_t id, void *data) +{ + (void)arg; (void)data; + if (base == WIFI_EVENT && id == WIFI_EVENT_STA_START) esp_wifi_connect(); + if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) { + wifi_ready = 1; + xEventGroupSetBits(wifi_events, UP); + } + if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) { + wifi_ready = 0; + xEventGroupSetBits(wifi_events, DOWN); + } +} + +static int send_cb(WOLFSSL *ssl, char *buf, int size, void *ctx) +{ + int n = send(*(int *)ctx, buf, size, 0); + (void)ssl; + return n > 0 ? n : WOLFSSL_CBIO_ERR_GENERAL; +} + +static int recv_cb(WOLFSSL *ssl, char *buf, int size, void *ctx) +{ + int n = recv(*(int *)ctx, buf, size, 0); + (void)ssl; + return n > 0 ? n : (n == 0 ? WOLFSSL_CBIO_ERR_CONN_CLOSE : WOLFSSL_CBIO_ERR_GENERAL); +} + +static int tcp_connect(void) +{ + struct addrinfo hint = {0}, *addr = NULL; + struct timeval deadline = {15, 0}; + int fd = -1, flags, error = 0; + socklen_t error_size = sizeof(error); + fd_set writable; + hint.ai_family = AF_INET; + hint.ai_socktype = SOCK_STREAM; + if (getaddrinfo(HOST, PORT, &hint, &addr) != 0) return -1; + fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); + if (fd < 0) goto done; + flags = fcntl(fd, F_GETFL, 0); + if (flags < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) goto fail; + if (connect(fd, addr->ai_addr, addr->ai_addrlen) != 0) { + if (errno != EINPROGRESS) goto fail; + FD_ZERO(&writable); FD_SET(fd, &writable); + if (select(fd + 1, NULL, &writable, NULL, &deadline) <= 0 || + getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &error_size) != 0 || error) goto fail; + } + deadline.tv_sec = 15; deadline.tv_usec = 0; + if (fcntl(fd, F_SETFL, flags) < 0 || + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &deadline, sizeof(deadline)) != 0 || + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &deadline, sizeof(deadline)) != 0) goto fail; + goto done; +fail: + close(fd); fd = -1; +done: + if (addr) freeaddrinfo(addr); + return fd; +} + +static int get_page(WOLFSSL *ssl) +{ + const char request[] = "GET / HTTP/1.0\r\nHost: " HOST ":8091\r\nConnection: close\r\n\r\n"; + char buf[256], tail[4] = {0}; + size_t used = 0, expected = 0, body = 0, written = 0; + int head = 0, marker = 0, n; + while (written < sizeof(request) - 1) { + n = wolfSSL_write(ssl, request + written, (int)(sizeof(request) - 1 - written)); + if (n <= 0) return 0; + written += (size_t)n; + } + while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) { + int i; + for (i = 0; i < n; ++i) { + if (!head) { + if (used == sizeof(headers)) return 0; + headers[used++] = buf[i]; + head = pqc_http_headers(headers, used, &expected); + if (head < 0) return 0; + } else { + if (++body > expected) return 0; + memmove(tail, tail + 1, 2); tail[2] = buf[i]; + if (memcmp(tail, "PQC", 3) == 0) marker = 1; + } + } + if (head && body == expected) { + printf("HTTP status=200 body_bytes=%u marker=%d\n", (unsigned)body, marker); + return marker; + } + } + return 0; +} + +enum mode { POSITIVE, CLASSICAL, TLS12, WRONG_NAME, NO_TRUST }; + +static int probe(enum mode mode) +{ + WOLFSSL_CTX *ctx = NULL; + WOLFSSL *ssl = NULL; + int fd = -1, ok = 0, result, group = mode == CLASSICAL ? WOLFSSL_ECC_X25519 : WOLFSSL_X25519MLKEM768; + const char *names[] = {"positive", "classical-only", "tls12", "wrong-name", "no-trust"}; + memory(names[mode]); + ctx = wolfSSL_CTX_new(mode == TLS12 ? wolfTLSv1_2_client_method() : wolfTLSv1_3_client_method()); + if (!ctx) goto done; + wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_PEER, NULL); + wolfSSL_SetIORecv(ctx, recv_cb); + wolfSSL_SetIOSend(ctx, send_cb); + if (mode != NO_TRUST && wolfSSL_CTX_load_verify_buffer(ctx, root_start, + (long)(root_end - root_start), WOLFSSL_FILETYPE_PEM) != WOLFSSL_SUCCESS) goto done; + ssl = wolfSSL_new(ctx); + if (!ssl || wolfSSL_check_domain_name(ssl, mode == WRONG_NAME ? "wrong.invalid" : HOST) != WOLFSSL_SUCCESS || + wolfSSL_UseSNI(ssl, WOLFSSL_SNI_HOST_NAME, HOST, sizeof(HOST) - 1) != WOLFSSL_SUCCESS) goto done; + if (mode != TLS12 && (wolfSSL_set_groups(ssl, &group, 1) != WOLFSSL_SUCCESS || + wolfSSL_UseKeyShare(ssl, (word16)group) != WOLFSSL_SUCCESS)) goto done; + fd = tcp_connect(); + if (fd < 0) goto done; + wolfSSL_SetIOReadCtx(ssl, &fd); wolfSSL_SetIOWriteCtx(ssl, &fd); + result = wolfSSL_connect(ssl); + memory("after-handshake"); + if (mode != POSITIVE) { + /* Print the exact failure for later classification. A failed handshake + * alone is NOT an accepted negative: OOM/network errors are inconclusive. */ + printf("NEGATIVE mode=%s handshake=%d error=%d classification=REQUIRES_REVIEW\n", + names[mode], result, result == WOLFSSL_SUCCESS ? 0 : wolfSSL_get_error(ssl, result)); + ok = result != WOLFSSL_SUCCESS; + } else if (result == WOLFSSL_SUCCESS) { + const char *curve = wolfSSL_get_curve_name(ssl); + /* Success with VERIFY_PEER and no permissive callback is the certificate + * check; don't enable bulky OpenSSL compatibility just for its getter. */ + printf("TLS version=%s group=%s cipher=%s verify=peer\n", wolfSSL_get_version(ssl), + curve ? curve : "unknown", wolfSSL_get_cipher(ssl)); + ok = curve && strcmp(curve, "X25519MLKEM768") == 0 && + strcmp(wolfSSL_get_version(ssl), "TLSv1.3") == 0 && + get_page(ssl); + printf("APPLICATION positive=%s\n", ok ? "PASS" : "FAIL"); + } else { + printf("TLS positive=FAIL error=%d\n", wolfSSL_get_error(ssl, result)); + } +done: + if (ssl) wolfSSL_free(ssl); + if (ctx) wolfSSL_CTX_free(ctx); + if (fd >= 0) close(fd); + memory("after-cleanup"); + return ok; +} + +static void https_task(void *arg) +{ + nvs_handle storage; + wifi_config_t wifi = {0}; + size_t ssid_size = sizeof(wifi.sta.ssid), password_size = sizeof(wifi.sta.password); + uint64_t epoch = 0; + struct timeval now; + (void)arg; + memory("boot"); + /* No Wi-Fi credentials in source, CI configuration, binaries or logs. + * Secure provisioning and hardware execution are separate work. */ + if (nvs_open("pqc_test", NVS_READONLY, &storage) != ESP_OK) goto unconfigured; + if (nvs_get_str(storage, "ssid", (char *)wifi.sta.ssid, &ssid_size) != ESP_OK || + nvs_get_str(storage, "password", (char *)wifi.sta.password, &password_size) != ESP_OK || + nvs_get_u64(storage, "utc_epoch", &epoch) != ESP_OK || epoch < 1796342400ULL || epoch > 2145916799ULL) { + nvs_close(storage); goto unconfigured; + } + nvs_close(storage); + now.tv_sec = (time_t)epoch; now.tv_usec = 0; + if (settimeofday(&now, NULL) != 0) goto unconfigured; + wifi_events = xEventGroupCreate(); + if (!wifi_events) goto unconfigured; + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + /* SDK3.4's esp_netif is a tcpip_adapter shim; it does not have the + * ESP32-IDF esp_netif_create_default_wifi_sta() API. */ + wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&init)); + ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, event, NULL)); + ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, event, NULL)); + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); + ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi)); + memset(&wifi, 0, sizeof(wifi)); + ESP_ERROR_CHECK(esp_wifi_start()); + if ((xEventGroupWaitBits(wifi_events, UP | DOWN, pdFALSE, pdFALSE, + pdMS_TO_TICKS(30000)) & (UP | DOWN)) != UP) goto finish; + if (wolfSSL_Init() != WOLFSSL_SUCCESS) goto finish; + if (probe(POSITIVE)) { + enum mode m; + for (m = CLASSICAL; m <= NO_TRUST; ++m) { + if (!wifi_ready) break; + probe(m); + vTaskDelay(pdMS_TO_TICKS(100)); + } + } else puts("NEGATIVES not_run: positive baseline failed"); + wolfSSL_Cleanup(); +finish: + esp_wifi_stop(); + wifi_ready = 0; + puts("RUN_FINISHED: device results require log review; no automatic feasibility acceptance"); + vTaskDelete(NULL); + return; +unconfigured: + puts("NOT_CONFIGURED: needs separately authorised private device provisioning and fresh trusted UTC"); + vTaskDelete(NULL); +} + +void app_main(void) +{ + /* Never erase NVS or reset an existing device to make a demonstration work. */ + if (nvs_flash_init() != ESP_OK) { puts("NVS unavailable; no erase attempted"); return; } + if (xTaskCreate(https_task, "pqc_https", 8192, NULL, 4, NULL) != pdPASS) + puts("FAIL: cannot allocate HTTPS task stack"); +} diff --git a/firmware/esp8266/main/response.c b/firmware/esp8266/main/response.c new file mode 100644 index 0000000..001786c --- /dev/null +++ b/firmware/esp8266/main/response.c @@ -0,0 +1,48 @@ +/* SPDX-License-Identifier: MIT + * Deliberately small HTTP/1.x profile, not a general HTTP client. + * Assisted-by: Briar + */ +#include "response.h" +#include +#include +#include +#include + +int pqc_http_headers(const char *data, size_t size, size_t *body_size) +{ + size_t i, end = 0, pos, count = 0, length = 0; + if (size > 4096) return -1; + for (i = 3; i < size; ++i) + if (memcmp(data + i - 3, "\r\n\r\n", 4) == 0) { end = i + 1; break; } + if (!end) return size == 4096 ? -1 : 0; + if (end < 19 || (memcmp(data, "HTTP/1.0 200 ", 13) != 0 && + memcmp(data, "HTTP/1.1 200 ", 13) != 0)) return -1; + pos = 0; + while (pos + 1 < end && !(data[pos] == '\r' && data[pos + 1] == '\n')) ++pos; + pos += 2; + while (pos + 2 < end) { + size_t start = pos, stop; + while (pos + 1 < end && !(data[pos] == '\r' && data[pos + 1] == '\n')) ++pos; + stop = pos; + pos += 2; + if (stop == start) break; + if (data[start] == ' ' || data[start] == '\t') return -1; + if (stop - start >= 18 && strncasecmp(data + start, "Transfer-Encoding:", 18) == 0) + return -1; /* No chunked or ambiguous framing. */ + if (stop - start >= 15 && strncasecmp(data + start, "Content-Length:", 15) == 0) { + size_t p = start + 15; + if (++count != 1) return -1; + while (p < stop && (data[p] == ' ' || data[p] == '\t')) ++p; + if (p == stop || !isdigit((unsigned char)data[p])) return -1; + while (p < stop && isdigit((unsigned char)data[p])) { + length = length * 10 + (size_t)(data[p++] - '0'); + if (length > 65536) return -1; + } + while (p < stop && (data[p] == ' ' || data[p] == '\t')) ++p; + if (p != stop) return -1; + } + } + if (count != 1 || length == 0) return -1; + *body_size = length; + return (int)end; +} diff --git a/firmware/esp8266/main/response.h b/firmware/esp8266/main/response.h new file mode 100644 index 0000000..b4b8131 --- /dev/null +++ b/firmware/esp8266/main/response.h @@ -0,0 +1,8 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef PQC_RESPONSE_H +#define PQC_RESPONSE_H +#include +/* Return header length for a bounded, unambiguous HTTP 200 Content-Length + * response; return 0 for incomplete headers and -1 for invalid/unsupported. */ +int pqc_http_headers(const char *data, size_t size, size_t *body_size); +#endif diff --git a/firmware/esp8266/main/trust-anchor.pem b/firmware/esp8266/main/trust-anchor.pem new file mode 100644 index 0000000..7d903ed --- /dev/null +++ b/firmware/esp8266/main/trust-anchor.pem @@ -0,0 +1,14 @@ +-----BEGIN CERTIFICATE----- +MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw +CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg +R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00 +MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT +ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw +EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW ++1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9 +ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T +AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI +zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW +tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1 +/q4AaOeMSQ+2b1tbFfLn +-----END CERTIFICATE----- diff --git a/firmware/esp8266/sdkconfig.defaults b/firmware/esp8266/sdkconfig.defaults new file mode 100644 index 0000000..c3ff7bf --- /dev/null +++ b/firmware/esp8266/sdkconfig.defaults @@ -0,0 +1,3 @@ +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_ESP8266_DEFAULT_CPU_FREQ_160=y +CONFIG_FREERTOS_HZ=100 diff --git a/tests/test_esp8266.py b/tests/test_esp8266.py new file mode 100644 index 0000000..86bd4e6 --- /dev/null +++ b/tests/test_esp8266.py @@ -0,0 +1,108 @@ +# SPDX-License-Identifier: MIT +"""Host-side parser/guard tests, NOT an ESP8266 firmware build or device run.""" +import ctypes +import importlib.util +import io +import os +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile +import unittest +from unittest import mock + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("esp8266_images", ROOT / "ci/esp8266_images.py") +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +class HTTPParserTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + if not shutil.which("cc"): + raise RuntimeError("Host C compiler required for native parser tests; not a firmware build") + cls.temp = tempfile.TemporaryDirectory() + lib = Path(cls.temp.name) / "response.so" + subprocess.run(["cc", "-std=c99", "-Wall", "-Wextra", "-Werror", "-shared", "-fPIC", + str(ROOT / "firmware/esp8266/main/response.c"), "-o", str(lib)], check=True) + cls.library = ctypes.CDLL(str(lib)) + cls.parse = cls.library.pqc_http_headers + cls.parse.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_size_t)] + cls.parse.restype = ctypes.c_int + + @classmethod + def tearDownClass(cls): + cls.temp.cleanup() + + def check(self, data): + length = ctypes.c_size_t() + return self.parse(data, len(data), ctypes.byref(length)), length.value + + def test_fragmented_headers(self): + header = b"HTTP/1.1 200 OK\r\nContent-Length: 2665\r\n\r\n" + for end in range(len(header)): + self.assertEqual(self.check(header[:end])[0], 0) + self.assertEqual(self.check(header), (len(header), 2665)) + + def test_http10_and_case_insensitive_length(self): + header = b"HTTP/1.0 200 OK\r\ncontent-length:\t3 \r\n\r\n" + self.assertEqual(self.check(header), (len(header), 3)) + + def test_reject_bad_status_framing_and_lengths(self): + for line in (b"", b"Content-Length: 0\r\n", b"Content-Length: -1\r\n", + b"Content-Length: 65537\r\n", b"Content-Length: 1junk\r\n", + b"Content-Length: 1\r\nContent-Length: 1\r\n", + b"Content-Length: 1\r\nTransfer-Encoding: chunked\r\n", + b" Content-Length: 1\r\n"): + with self.subTest(line=line): + self.assertEqual(self.check(b"HTTP/1.1 200 OK\r\n" + line + b"\r\n")[0], -1) + self.assertEqual(self.check(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 1\r\n\r\n")[0], -1) + + def test_header_limit(self): + self.assertEqual(self.check(b"a" * 4096)[0], -1) + + +class BuildGuardTests(unittest.TestCase): + def test_workstation_cannot_enter_either_build_path(self): + with mock.patch.dict(os.environ, {}, clear=True), mock.patch.object(builder, "command") as command: + for entry in (builder.build, builder.container_build): + with self.assertRaises(RuntimeError): + entry() + command.assert_not_called() + + def test_archive_rejects_traversal(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = root / "bad.tgz" + with tarfile.open(archive, "w:gz") as dest: + item = tarfile.TarInfo("xtensa-lx106-elf/../../outside") + item.size = 1 + dest.addfile(item, io.BytesIO(b"x")) + with mock.patch.object(builder, "TOOLCHAIN_SHA256", builder.digest(archive)): + with self.assertRaisesRegex(RuntimeError, "Unsafe"): + builder.unpack_toolchain(archive, root) + self.assertFalse((root.parent / "outside").exists()) + + def test_pins_are_exact(self): + for revision in (builder.SDK, builder.WOLFSSL): + self.assertRegex(revision, r"^[0-9a-f]{40}$") + self.assertRegex(builder.TOOLCHAIN_SHA256, r"^[0-9a-f]{64}$") + + def test_archive_rejects_external_symlink(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = root / "bad.tgz" + with tarfile.open(archive, "w:gz") as dest: + item = tarfile.TarInfo("xtensa-lx106-elf/lib/outside") + item.type = tarfile.SYMTYPE + item.linkname = "/tmp" + dest.addfile(item) + with mock.patch.object(builder, "TOOLCHAIN_SHA256", builder.digest(archive)): + with self.assertRaisesRegex(RuntimeError, "Unsafe"): + builder.unpack_toolchain(archive, root) + + +if __name__ == "__main__": + unittest.main() From 74fc7b1f0556405c74122b7a148b831edf5aaf26 Mon Sep 17 00:00:00 2001 From: Alex J Lennon Date: Fri, 4 Dec 2026 10:24:24 +0000 Subject: [PATCH 2/3] Enable SHAKE primitives required by ESP8266 ML-KEM Fix wc_Shake compile failure against pinned wolfSSL. Add host-preprocessed profile regression coverage; preserve hybrid TLS and certificate verification. Assisted-by: Briar --- .../components/wolfssl/include/user_settings.h | 4 ++++ tests/test_esp8266.py | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/firmware/esp8266/components/wolfssl/include/user_settings.h b/firmware/esp8266/components/wolfssl/include/user_settings.h index 20d5aaa..195b3cb 100644 --- a/firmware/esp8266/components/wolfssl/include/user_settings.h +++ b/firmware/esp8266/components/wolfssl/include/user_settings.h @@ -39,6 +39,10 @@ #define WOLFSSL_SHA384 #define WOLFSSL_SHA512 #define WOLFSSL_SHA3 +/* ML-KEM uses SHAKE-128 for matrix expansion and SHAKE-256 for its KDF/PRF. + * WOLFSSL_SHA3 alone does not declare wc_Shake or enable those functions. */ +#define WOLFSSL_SHAKE128 +#define WOLFSSL_SHAKE256 #define WOLFSSL_HAVE_MLKEM #define WOLFSSL_PQC_HYBRIDS #define WOLFSSL_NO_ML_KEM_512 diff --git a/tests/test_esp8266.py b/tests/test_esp8266.py index 86bd4e6..37e2275 100644 --- a/tests/test_esp8266.py +++ b/tests/test_esp8266.py @@ -65,6 +65,20 @@ def test_header_limit(self): class BuildGuardTests(unittest.TestCase): + def test_mlkem_profile_enables_both_shake_primitives(self): + # Inspect the real preprocessed configuration, not a copied macro list. + # Host preprocessing only; this does not build ESP8266 firmware. + result = subprocess.run( + ["cc", "-E", "-dM", "-include", + str(ROOT / "firmware/esp8266/components/wolfssl/include/user_settings.h"), "-"], + input="", text=True, capture_output=True, check=True) + defines = {line.split()[1] for line in result.stdout.splitlines() + if line.startswith("#define ")} + for required in ("WOLFSSL_SHA3", "WOLFSSL_SHAKE128", "WOLFSSL_SHAKE256", + "WOLFSSL_HAVE_MLKEM", "WOLFSSL_PQC_HYBRIDS", "WOLFSSL_TLS13"): + self.assertIn(required, defines) + self.assertNotIn("WOLFSSL_MLKEM_NO_DECAPSULATE", defines) + def test_workstation_cannot_enter_either_build_path(self): with mock.patch.dict(os.environ, {}, clear=True), mock.patch.object(builder, "command") as command: for entry in (builder.build, builder.container_build): From 891c74a646df368a1e8efda255fad4d739016538 Mon Sep 17 00:00:00 2001 From: Alex J Lennon Date: Fri, 4 Dec 2026 10:48:04 +0000 Subject: [PATCH 3/3] Exclude foreign assembly from ESP8266 wolfSSL component Explicitly select portable C objects instead of SDK default discovery of every .S source. Exercise the real Make adapter against synthetic C and foreign-assembly filenames. Assisted-by: Briar --- .../esp8266/components/wolfssl/component.mk | 4 +++ tests/test_esp8266.py | 25 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/firmware/esp8266/components/wolfssl/component.mk b/firmware/esp8266/components/wolfssl/component.mk index 77be692..8ef0273 100644 --- a/firmware/esp8266/components/wolfssl/component.mk +++ b/firmware/esp8266/components/wolfssl/component.mk @@ -2,5 +2,9 @@ # The CI adapter links upstream to the independently pinned wolfSSL checkout. COMPONENT_ADD_INCLUDEDIRS := include upstream COMPONENT_SRCDIRS := upstream/src upstream/wolfcrypt/src +# The SDK's default discovery also selects every .S file, including x86/ARM +# implementations. This software-only Xtensa profile must use portable C only. +# Set objects explicitly so the SDK does not perform its default source scan. +COMPONENT_OBJS := $(patsubst $(COMPONENT_PATH)/%.c,%.o,$(foreach srcdir,$(COMPONENT_SRCDIRS),$(wildcard $(COMPONENT_PATH)/$(srcdir)/*.c))) COMPONENT_OBJEXCLUDE := upstream/wolfcrypt/src/misc.o upstream/wolfcrypt/src/evp.o upstream/src/bio.o CFLAGS += -DWOLFSSL_USER_SETTINGS diff --git a/tests/test_esp8266.py b/tests/test_esp8266.py index 37e2275..4484dc4 100644 --- a/tests/test_esp8266.py +++ b/tests/test_esp8266.py @@ -65,6 +65,31 @@ def test_header_limit(self): class BuildGuardTests(unittest.TestCase): + def test_component_selects_portable_c_without_architecture_assembly(self): + # Evaluate the real adapter with synthetic filenames; no compilation. + with tempfile.TemporaryDirectory() as directory: + component = Path(directory) + files = ('upstream/src/ssl.c', 'upstream/src/bio.c', + 'upstream/wolfcrypt/src/sha512.c', 'upstream/wolfcrypt/src/sha3.c', + 'upstream/wolfcrypt/src/wc_mlkem.c', 'upstream/wolfcrypt/src/misc.c', + 'upstream/wolfcrypt/src/evp.c', 'upstream/wolfcrypt/src/sha512_asm.S', + 'upstream/wolfcrypt/src/armv8-sha512-asm.S', + 'upstream/wolfcrypt/src/assembly_only.S') + for name in files: + path = component / name + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + adapter = ROOT / 'firmware/esp8266/components/wolfssl/component.mk' + makefile = (f'COMPONENT_PATH := {component}\ninclude {adapter}\n' + 'ifndef COMPONENT_OBJS\n$(error Explicit portable objects required)\nendif\n' + # The pinned SDK applies COMPONENT_OBJEXCLUDE afterwards. + "show:\n\t@printf '%s\\n' $(filter-out $(COMPONENT_OBJEXCLUDE),$(COMPONENT_OBJS))\n") + result = subprocess.run(['make', '--no-print-directory', '-f', '-', 'show'], + input=makefile, text=True, capture_output=True, check=True) + self.assertEqual(set(result.stdout.split()), { + 'upstream/src/ssl.o', 'upstream/wolfcrypt/src/sha512.o', + 'upstream/wolfcrypt/src/sha3.o', 'upstream/wolfcrypt/src/wc_mlkem.o'}) + def test_mlkem_profile_enables_both_shake_primitives(self): # Inspect the real preprocessed configuration, not a copied macro list. # Host preprocessing only; this does not build ESP8266 firmware.