Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/esp8266-images.yml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ certs/private/
vendor/
zephyr-workspace/
results.json
.deps/
firmware/esp8266/sdkconfig
firmware/esp8266/components/wolfssl/upstream
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,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:
Expand Down
12 changes: 12 additions & 0 deletions ci/esp8266.Dockerfile
Original file line number Diff line number Diff line change
@@ -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
154 changes: 154 additions & 0 deletions ci/esp8266_images.py
Original file line number Diff line number Diff line change
@@ -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)()
132 changes: 132 additions & 0 deletions docs/esp8266-d1mini.md
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions firmware/esp8266/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# SPDX-License-Identifier: MIT
PROJECT_NAME := d1mini_hybrid_https
include $(IDF_PATH)/make/project.mk
10 changes: 10 additions & 0 deletions firmware/esp8266/components/wolfssl/component.mk
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# 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
# 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
Loading