$ uname -a A_BLOG_ABOUT_UNIX_TOOLS_AND_THE_BEAUTY_OF_SIMPLE_SYSTEMS
SYS.YEAR  2026
← Back to articles
2026-09-09ARTICLE

Esp32 C3 Zfs

A tiny ZFS key server on an ESP32-C3, built from FreeBSD

An ESP32-C3 can do something useful with a very small HTTP API: return one ZFS encryption key to an authenticated client. This project turns a USB-connected board into a Wi-Fi HTTPS server with exactly one application endpoint, GET /zfs.key. The response is 32 raw bytes, and the client must present a certificate signed by a private CA before it can make the request.

The firmware was built, flashed, and tested from a FreeBSD machine. The build ran in a persistent development jail using the host's existing Linux compatibility support; flashing and network verification used native FreeBSD tools. Both curl and fetch retrieved the exact key, while connections without a valid client certificate failed.

No existing encrypted ZFS datasets were changed during the work.

What the board does

The board joins a 2.4 GHz Wi-Fi network in station mode, requests an address through DHCP, and sets its hostname to zfs-keybox. Once it has an address and has synchronized its clock, it starts the ESP-IDF HTTPS server on port 443.

An authenticated request to /zfs.key returns:

HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Length: 32
Cache-Control: no-store

The body is the key itself: no hex encoding, base64, JSON, or trailing newline. Other application paths return 404. There is no plain HTTP listener, administration page, OTA endpoint, shell, directory listing, or Bluetooth service.

The resulting system is deliberately small. Configuration changes require rebuilding and reflashing the firmware.

Start by identifying the FreeBSD devices

The first step was to inspect the actual host rather than assume a Linux development environment:

uname -a
freebsd-version
pkg -vv
usbconfig
dmesg | tail -100
ls -l /dev/cua* /dev/tty* 2>/dev/null

The machine had FreeBSD 15.1-RELEASE-p3 userland and two USB serial devices. That distinction mattered: /dev/cuaU0 belonged to a separate CH340 adapter. The Espressif USB Serial/JTAG device was attached through umodem0, with tty name U1:

doas usbconfig
sysctl dev.umodem

This mapped the board to /dev/cuaU1. USB enumeration showed Espressif vendor/product IDs 303a:1001, but enumeration alone was not enough to decide what to flash. The next step was to ask the chip directly.

FreeBSD supplied the flashing tool as a package:

pkg search esptool
doas pkg install py312-esptool
command -v esptool

The installed command was /usr/local/bin/esptool, version 5.3.1. Communication worked with:

doas esptool --chip esp32c3 -p /dev/cuaU1 chip-id
doas esptool --chip esp32c3 -p /dev/cuaU1 flash-id

Esptool identified an ESP32-C3 QFN32 revision v0.4, with a 40 MHz crystal and 4 MB of embedded XMC flash. It also reported the MAC address, which can be used to create a DHCP reservation in the router.

Device names can change after USB resets. The important procedure is to map the device and confirm the chip again, rather than carry /dev/cuaU1 into another setup as an assumption.

A development jail for the build

There was no usable ESP-IDF installation on the host. FreeBSD offered a generic RISC-V compiler package, but that was not a substitute for the matching Espressif toolchain.

The host already had Podman, ocijail, and Linuxulator configured. A Linux container smoke test worked, so the build used the official ESP-IDF v6.0.3 image in a persistent jail named esp32-zfs-dev. This is a Linux userspace running through FreeBSD's compatibility layer, not a Linux VM or a replacement operating system.

The source lives at /home/wongk/esp32-zfs-keyserver on the host and appears at /project inside the jail:

doas podman pull --platform linux/amd64 docker.io/espressif/idf:v6.0.3

doas podman run -d --name esp32-zfs-dev --platform linux/amd64 \
  --network none \
  -v /home/wongk/esp32-zfs-keyserver:/project \
  -w /project \
  docker.io/espressif/idf:v6.0.3 sleep infinity

The existing container is named esp32-zfs-dev. It is a Podman container backed by FreeBSD's ocijail/Linuxulator support, rather than a Bastille jail. Its current configuration is:

container: esp32-zfs-dev
image:     docker.io/espressif/idf:v6.0.3
mount:     /home/wongk/esp32-zfs-keyserver:/project
network:   none

Start it after a host reboot or if it has been stopped:

doas podman start esp32-zfs-dev

Open an interactive development shell:

doas podman exec -it esp32-zfs-dev bash
cd /project

Check its state from the host:

doas podman ps -a --filter name=esp32-zfs-dev

The image includes the SDK and compiler, so the development jail can build without network access. USB access stays on the FreeBSD host. Flashing is therefore performed from the host with FreeBSD's esptool; the container does not need /dev/cuaU1 access. These commands assume the working Podman/Linuxulator setup found on this machine; they are not a complete installation guide for those facilities on a fresh FreeBSD host.

For repeatability, the deployment record also saves the image digest:

docker.io/espressif/idf@sha256:01ab23e20744721378d1dd9d0fff4fe15e2edd8bd5cdaf02d24597f4ade05a1e

The Python subprocess problem

The first attempt to activate ESP-IDF failed during a Python subprocess call with:

subprocess.SubprocessError: Bad exception data from child

A project-local scripts/linuxulator/sitecustomize.py resolved the observed failure by disabling Python's vfork and posix_spawn paths:

import subprocess

subprocess._USE_VFORK = False
subprocess._USE_POSIX_SPAWN = False

The build script adds that directory to PYTHONPATH before sourcing ESP-IDF's environment. These are private Python implementation flags, so this workaround is specific to the tested environment and should be revisited when upgrading Python or FreeBSD. It does not patch the host installation or the SDK.

The build then runs:

idf.py set-target esp32c3   # initial configuration
idf.py build

From the host, the repeatable entry point is:

doas podman exec esp32-zfs-dev bash /project/scripts/build-in-jail.sh

Keeping secrets out of the source tree's history

The project separates source from private configuration:

esp32-zfs-keyserver/
├── CMakeLists.txt
├── main/
│   ├── CMakeLists.txt
│   └── main.c
├── scripts/
├── sdkconfig.defaults
├── secrets/
├── .gitignore
├── README.md
└── VERIFICATION.md

secrets/ is ignored by Git, as are build artifacts, generated configuration, and logs. The private files include Wi-Fi configuration, the raw ZFS key, the CA key and certificate, and separate server and client key/certificate pairs. The project and secrets directories have mode 700; private files have mode 600.

No existing ZFS key had been supplied in the checked project locations, so the initialization script generated a new 32-byte random key. It preserves an existing key and rejects a key of the wrong length. Verification uses the file size and SHA-256, never a dump of the key:

stat -f %z secrets/zfs.key
sha256 secrets/zfs.key

A new random key will not unlock a dataset encrypted with a different key. To serve an existing dataset, install its existing raw key deliberately, then rebuild and reflash.

Wi-Fi credentials go in one private JSON file:

{"WIFI_SSID":"your 2.4 GHz SSID", "WIFI_PASSWORD":"your password"}

On this machine, one existing host Wi-Fi profile was available and its credentials were imported without displaying them. The firmware requires WPA2 or stronger authentication.

An early build failed because the json component was no longer available under that name in the selected SDK. Instead of adding a runtime JSON dependency, a small build script validates the JSON and packs the SSID and password into a fixed-size binary resource. The firmware embeds that resource along with the raw key and server TLS material.

This also avoids a writable filesystem on the board. Credentials are held in Wi-Fi RAM at runtime rather than saved through Wi-Fi NVS, although they are still present in application flash.

Mandatory client certificates

The private CA and leaf certificates were generated with OpenSSL using P-256 keys. The server certificate has a DNS:zfs-keybox subject alternative name and serverAuth usage. The client certificate has clientAuth usage.

Only the server private key, server certificate, and CA certificate are embedded in firmware. The CA private key and client private key remain on the host.

The significant HTTPS configuration is:

httpd_ssl_config_t cfg = HTTPD_SSL_CONFIG_DEFAULT();
cfg.transport_mode = HTTPD_SSL_TRANSPORT_SECURE;
cfg.port_secure = 443;
cfg.servercert = cert_start;
cfg.servercert_len = cert_end - cert_start;
cfg.prvtkey_pem = priv_start;
cfg.prvtkey_len = priv_end - priv_start;
cfg.cacert_pem = ca_start;
cfg.cacert_len = ca_end - ca_start;

In the inspected ESP-IDF version, supplying the client CA selects required certificate verification in ESP-TLS. The optional client-authentication configuration remains disabled. Authentication happens in the TLS handshake, before an HTTP handler can return the key.

The handler also compares the complete request URI with /zfs.key. ESP-IDF's normal URI matching can ignore a query string; the explicit comparison ensures /zfs.key?x=1 does not accidentally become another accepted endpoint. A method-not-allowed handler maps unsupported methods on the route to 404.

The SDK's internal HTTP control socket was checked too: it binds to loopback, not the Wi-Fi interface.

Certificate dates need a clock

ESP-IDF's certificate expiry checks were disabled by default in this configuration. The firmware explicitly enables:

CONFIG_MBEDTLS_HAVE_TIME_DATE=y

It waits for time synchronization with pool.ntp.org before starting HTTPS. DNS and outbound UDP port 123 therefore need to work. If initial time synchronization fails, the key server stays unavailable.

This uses ordinary, unauthenticated SNTP. An attacker who controls time could affect certificate date checks, although that does not let them forge a CA signature. This is a limitation of the current implementation, not a trusted-time solution.

Flash the generated images, using generated offsets

The successful build produced:

Image under build/ Offset Size
bootloader/bootloader.bin 0x0 21,344 bytes
partition_table/partition-table.bin 0x8000 3,072 bytes
zfs_keyserver.bin 0x10000 874,624 bytes

Those offsets came from build/flasher_args.json and build/flash_args. They were not copied from a generic ESP32 example.

Flashing used native FreeBSD esptool at a requested baud rate of 460800:

cd /home/wongk/esp32-zfs-keyserver/build

doas esptool --chip esp32c3 -p /dev/cuaU1 -b 460800 \
  --before default-reset --after hard-reset write-flash @flash_args

doas esptool --chip esp32c3 -p /dev/cuaU1 -b 460800 \
  --before default-reset --after hard-reset verify-flash @flash_args

All three regions passed write-time hash verification and a separate flash verification pass.

The first serial monitor reset sequence left the chip in ROM download mode. Using esptool's USB-aware HardReset sequence corrected that. The resulting boot log showed ESP-IDF v6.0.3, the ESP32-C3 application starting, Wi-Fi initialization, DHCP, clock synchronization, and HTTPS startup.

If automatic reset fails on another board, hold BOOT/GPIO9 low while resetting, then release BOOT to enter the ROM downloader. After flashing, reset normally and rediscover the USB serial device if needed.

Verify the bytes and the authentication failures

The board received 192.168.3.225 through DHCP. The certificate identifies zfs-keybox, so curl's --resolve option supplies the address while preserving hostname verification:

cd /home/wongk/esp32-zfs-keyserver
umask 077
ESP32_IP=192.168.3.225
KEY_TMP=$(mktemp -d /tmp/zfs-keycheck.XXXXXX) || exit 1

curl --fail --silent --show-error --noproxy '*' \
  --connect-timeout 5 --max-time 20 \
  --cacert secrets/ca.crt \
  --cert secrets/client.crt \
  --key secrets/client.key \
  --resolve "zfs-keybox:443:$ESP32_IP" \
  https://zfs-keybox/zfs.key -o "$KEY_TMP/zfs-test.key"

stat -f %z "$KEY_TMP/zfs-test.key"
cmp secrets/zfs.key "$KEY_TMP/zfs-test.key"
sha256 secrets/zfs.key "$KEY_TMP/zfs-test.key"

rm -P "$KEY_TMP/zfs-test.key" 2>/dev/null || rm -f "$KEY_TMP/zfs-test.key"
rmdir "$KEY_TMP"

The retrieved file was exactly 32 bytes. cmp succeeded, and the source and retrieved SHA-256 hashes matched. The automated test also checked status 200, the content type, content length, and Cache-Control: no-store.

The negative tests were just as important:

Test Observed result
No client certificate TLS connection rejected
Untrusted client certificate TLS connection rejected
Expired client certificate signed by our CA TLS connection rejected
Authenticated GET / or GET /other 404
Authenticated GET /zfs.key?x=1 404
Authenticated POST /zfs.key 404
Authenticated GET /zfs.key/ 404
Plain HTTP request Unavailable

Native FreeBSD fetch also passed using --ca-cert, --cert, and --key. Because the hostname was not in DNS, its test used a temporary loopback CONNECT tunnel to reach the board. Fetch still performed the TLS handshake, verified the server hostname, and used the client key locally. The tunnel only forwarded encrypted traffic. No hostname-verification bypass was used.

All temporary downloaded keys and negative-test credentials were removed afterward.

Loading a ZFS key through stdin

The portable integration is to retrieve the raw bytes with curl and feed them to zfs load-key. This avoids depending on whether the installed OpenZFS build supports an HTTPS keylocation backend with the necessary authentication options.

For a dataset using keyformat=raw, whose existing key exactly matches the served key:

cd /home/wongk/esp32-zfs-keyserver
ESP32_IP=192.168.3.225
set -o pipefail

curl --fail --silent --show-error --noproxy '*' \
  --connect-timeout 5 --max-time 20 \
  --cacert secrets/ca.crt \
  --cert secrets/client.crt \
  --key secrets/client.key \
  --resolve "zfs-keybox:443:$ESP32_IP" \
  https://zfs-keybox/zfs.key |
  doas zfs load-key -L prompt pool/encrypted-dataset

Replace the dataset name before using this command. It is an integration example, not a command executed during verification. Loading the key does not mount the dataset.

What this version protects—and what it leaves to the operator

The verified result is a working, small mTLS key server. It authenticates clients, encrypts transport, and serves the exact binary key expected by ZFS. Its network dependencies are Wi-Fi, DHCP, DNS, and time synchronization; the key-loading client needs access to the board before it can unlock its dataset.

This version does not enable flash encryption or burn secure-boot eFuses. Someone who can read the board's flash or obtain the build artifacts can recover the embedded ZFS key and server private key. Build output must therefore be treated as secret material even though it sits outside secrets/. Keep an offline recovery copy of the dataset key, and protect the CA and client private keys separately.

Certificate revocation is also deliberately simple: there is no CRL service or administration API. Replacing the trusted CA and reflashing changes which clients are accepted. Replacing Wi-Fi credentials, the served key, or the server certificate likewise requires a rebuild and flash.

The project README records those maintenance procedures. VERIFICATION.md records the exact image paths, build image digest, flash commands, and observed results, with supporting logs retained locally. The development jail remains available for the next firmware change.

Complete project source

The following listings reproduce the firmware, build configuration, and supporting scripts from the verified project as of 2026-09-09. Save each listing at the indicated path relative to the project root. Both articles include the same listings, so either contains the complete application source and its build and test scripts. ESP-IDF and compiler sources are obtained separately as described above.

The contents of secrets/ and generated build artifacts are deliberately excluded. scripts/init-secrets.sh creates private configuration and certificate files when absent; fill in secrets/wifi.json privately before building. For an existing encrypted dataset, supply its existing 32-byte raw key before running the initialization script. Never substitute a newly generated key for that dataset's key.

scripts/build-in-freebsd-jail.sh is the source of the native jail's /opt/build-keyserver.sh entry point and can also be run there with sh /project/scripts/build-in-freebsd-jail.sh. scripts/build-in-jail.sh and scripts/linuxulator/sitecustomize.py are for the Linuxulator container. The serial and network test scripts run on the FreeBSD host; the certificate rejection test additionally uses the native cryptography Python package. Run the initialization script from a writable host checkout, since /project is read-only in the native jail.

CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(zfs_keyserver)

main/CMakeLists.txt

set(secret_dir "${CMAKE_CURRENT_LIST_DIR}/../secrets")
foreach(name wifi.json zfs.key server.key server.crt ca.crt)
    if(NOT EXISTS "${secret_dir}/${name}")
        message(FATAL_ERROR "Missing secrets/${name}; see README.md")
    endif()
endforeach()
file(SIZE "${secret_dir}/zfs.key" key_size)
if(NOT key_size EQUAL 32)
    message(FATAL_ERROR "secrets/zfs.key must be exactly 32 bytes")
endif()
# Copy to the private build directory for stable linker symbol names.
configure_file("${secret_dir}/zfs.key" "${CMAKE_CURRENT_BINARY_DIR}/zfs.key" COPYONLY)
foreach(name server.key server.crt ca.crt)
    configure_file("${secret_dir}/${name}" "${CMAKE_CURRENT_BINARY_DIR}/${name}" COPYONLY)
endforeach()
idf_component_register(SRCS "main.c" REQUIRES esp_wifi esp_event esp_netif nvs_flash esp_https_server)
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_CURRENT_BINARY_DIR}/zfs.key" BINARY)
foreach(name server.key server.crt ca.crt)
    target_add_binary_data(${COMPONENT_LIB} "${CMAKE_CURRENT_BINARY_DIR}/${name}" TEXT)
endforeach()

execute_process(COMMAND "${PYTHON}" "${CMAKE_CURRENT_LIST_DIR}/../scripts/pack-wifi.py"
    "${secret_dir}/wifi.json" "${CMAKE_CURRENT_BINARY_DIR}/wifi.bin"
    RESULT_VARIABLE wifi_result)
if(NOT wifi_result EQUAL 0)
    message(FATAL_ERROR "Fill valid WIFI_SSID and WIFI_PASSWORD in secrets/wifi.json")
endif()
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${secret_dir}/wifi.json")
target_add_binary_data(${COMPONENT_LIB} "${CMAKE_CURRENT_BINARY_DIR}/wifi.bin" BINARY)

main/main.c

#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <assert.h>
#include <stdatomic.h>
#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_netif_sntp.h"
#include "esp_wifi.h"
#include "esp_https_server.h"
#include "nvs_flash.h"

#define RESOURCE(name, symbol) \
    extern const unsigned char name##_start[] asm("_binary_" symbol "_start"); \
    extern const unsigned char name##_end[] asm("_binary_" symbol "_end")
RESOURCE(zfs, "zfs_key");
RESOURCE(cert, "server_crt");
RESOURCE(priv, "server_key");
RESOURCE(ca, "ca_crt");
RESOURCE(wifi_blob, "wifi_bin");
static const char *TAG = "keybox";
static httpd_handle_t server;
static TaskHandle_t network_task;
static atomic_bool connected;

static esp_err_t not_found(httpd_req_t *req)
{
    httpd_resp_set_status(req, "404 Not Found");
    httpd_resp_set_hdr(req, "Cache-Control", "no-store");
    return httpd_resp_send(req, NULL, 0);
}
static esp_err_t http_error(httpd_req_t *req, httpd_err_code_t error)
{
    (void)error;
    return not_found(req);
}
static esp_err_t get_key(httpd_req_t *req)
{
    // IDF URI matching ignores query strings; require the entire raw URI.
    if (req->method != HTTP_GET || strcmp(req->uri, "/zfs.key") != 0)
        return not_found(req);
    httpd_resp_set_type(req, "application/octet-stream");
    httpd_resp_set_hdr(req, "Cache-Control", "no-store");
    return httpd_resp_send(req, (const char *)zfs_start, 32);
}
static void start_server(void)
{
    httpd_ssl_config_t cfg = HTTPD_SSL_CONFIG_DEFAULT();
    cfg.transport_mode = HTTPD_SSL_TRANSPORT_SECURE;
    cfg.port_secure = 443;
    cfg.servercert = cert_start;
    cfg.servercert_len = cert_end - cert_start;
    cfg.prvtkey_pem = priv_start;
    cfg.prvtkey_len = priv_end - priv_start;
    // Supplying the client CA makes certificate verification mandatory in ESP-TLS.
    cfg.cacert_pem = ca_start;
    cfg.cacert_len = ca_end - ca_start;
    cfg.httpd.max_open_sockets = 3;
    cfg.httpd.lru_purge_enable = true;
    cfg.httpd.recv_wait_timeout = 5;
    cfg.httpd.send_wait_timeout = 5;
    esp_err_t err = httpd_ssl_start(&server, &cfg);
    if (err != ESP_OK) {
        server = NULL;
        ESP_LOGE(TAG, "HTTPS startup failed: %s", esp_err_to_name(err));
        return;
    }
    httpd_uri_t endpoint = {.uri = "/zfs.key", .method = HTTP_GET, .handler = get_key};
    ESP_ERROR_CHECK(httpd_register_uri_handler(server, &endpoint));
    ESP_ERROR_CHECK(httpd_register_err_handler(server, HTTPD_404_NOT_FOUND, http_error));
    ESP_ERROR_CHECK(httpd_register_err_handler(server, HTTPD_405_METHOD_NOT_ALLOWED, http_error));
    ESP_LOGW(TAG, "HTTPS started on port 443; client certificate required");
}
static void events(void *arg, esp_event_base_t base, int32_t id, void *data)
{
    (void)arg;
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
        connected = false;
        ESP_LOGW(TAG, "Wi-Fi disconnected; reconnecting");
        xTaskNotifyGive(network_task);
    } else if (base == IP_EVENT && id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t *event = data;
        connected = true;
        ESP_LOGW(TAG, "DHCP IPv4: " IPSTR, IP2STR(&event->ip_info.ip));
        xTaskNotifyGive(network_task);
    }
}
void app_main(void)
{
    ESP_LOGW(TAG, "ZFS key server starting; target ESP32-C3");
    ESP_ERROR_CHECK((zfs_end - zfs_start == 32) ? ESP_OK : ESP_ERR_INVALID_SIZE);
    esp_err_t err = nvs_flash_init();
    // No automatic NVS erase: preserve any existing board state.
    ESP_ERROR_CHECK(err);
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_t *netif = esp_netif_create_default_wifi_sta();
    assert(netif);
    ESP_ERROR_CHECK(esp_netif_set_hostname(netif, "zfs-keybox"));
    network_task = xTaskGetCurrentTaskHandle();
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, events, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, events, NULL));
    wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&init));
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
    ESP_ERROR_CHECK((wifi_blob_end - wifi_blob_start == 96) ? ESP_OK : ESP_ERR_INVALID_SIZE);
    wifi_config_t wifi = {0};
    memcpy(wifi.sta.ssid, wifi_blob_start, 32);
    memcpy(wifi.sta.password, wifi_blob_start + 32, 64);
    wifi.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
    wifi.sta.pmf_cfg.capable = true;
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi));
    memset(&wifi, 0, sizeof(wifi));
    ESP_ERROR_CHECK(esp_wifi_start());
    ESP_LOGW(TAG, "Wi-Fi station initialized; hostname zfs-keybox");
    bool time_started = false;
    bool time_ready = false;
    for (;;) {
        if (!connected) {
            if (server) { httpd_ssl_stop(server); server = NULL; }
            esp_wifi_connect();
        } else if (!server) {
            if (!time_started) {
                esp_sntp_config_t time_cfg = ESP_NETIF_SNTP_DEFAULT_CONFIG("pool.ntp.org");
                ESP_ERROR_CHECK(esp_netif_sntp_init(&time_cfg));
                time_started = true;
                ESP_LOGW(TAG, "Waiting for network time before enabling HTTPS");
            }
            if (!time_ready && esp_netif_sntp_sync_wait(pdMS_TO_TICKS(1000)) == ESP_OK) {
                time_ready = true;
                ESP_LOGW(TAG, "Network time synchronized; certificate date checks enabled");
            }
            if (time_ready) start_server();
        }
        ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(5000));
    }
}

sdkconfig.defaults

CONFIG_IDF_TARGET="esp32c3"
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_PARTITION_TABLE_SINGLE_APP=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
CONFIG_ESP_HTTPS_SERVER_ENABLE=y
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=n
CONFIG_BT_ENABLED=n
CONFIG_ESP_WIFI_NVS_ENABLED=n
CONFIG_ESP_WIFI_SOFTAP_SUPPORT=n
CONFIG_ESP_TLS_SERVER=y
CONFIG_ESP_TLS_SERVER_SESSION_TICKETS=n
CONFIG_MBEDTLS_SSL_PROTO_TLS1_3=n
CONFIG_LOG_DEFAULT_LEVEL_WARN=y
CONFIG_MBEDTLS_HAVE_TIME_DATE=y
CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL=n

.gitignore

/secrets/
/build/
/sdkconfig
/sdkconfig.old
/managed_components/
/dependencies.lock
/build-*/
/logs/

scripts/pack-wifi.py

import json, os, sys
from pathlib import Path
try:
    data = json.loads(Path(sys.argv[1]).read_text())
    ssid = data["WIFI_SSID"].encode("utf-8")
    password = data["WIFI_PASSWORD"].encode("utf-8")
    assert 1 <= len(ssid) <= 32 and b"\0" not in ssid
    assert 8 <= len(password) <= 63 or (len(password) == 64 and all(c in b"0123456789abcdefABCDEF" for c in password))
    assert b"\0" not in password
    Path(sys.argv[2]).write_bytes(ssid.ljust(32, b"\0") + password.ljust(64, b"\0"))
    os.chmod(sys.argv[2], 0o600)
except Exception:
    sys.exit("Invalid Wi-Fi configuration; edit secrets/wifi.json (values suppressed)")

scripts/init-secrets.sh

#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets
chmod 700 secrets
if [ ! -e secrets/zfs.key ]; then
    (set -C; dd if=/dev/random of=secrets/zfs.key bs=32 count=1 2>/dev/null)
fi
[ "$(wc -c < secrets/zfs.key | tr -d ' ')" = 32 ] || { echo 'Key must be exactly 32 bytes' >&2; exit 1; }
chmod 600 secrets/zfs.key
if [ ! -e secrets/wifi.json ]; then
    printf '%s\n' '{"WIFI_SSID":"", "WIFI_PASSWORD":""}' > secrets/wifi.json
fi
# Refuse partial existing PKI rather than replacing any key or certificate.
count=0
for f in ca.key ca.crt server.key server.crt client.key client.crt; do
    if [ -e "secrets/$f" ]; then count=$((count + 1)); fi
done
if [ "$count" = 6 ]; then echo 'Existing PKI retained'; exit 0; fi
if [ "$count" != 0 ]; then echo 'Partial PKI exists; resolve manually without overwriting keys' >&2; exit 1; fi
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out secrets/ca.key
openssl req -new -x509 -sha256 -days 3650 -key secrets/ca.key -out secrets/ca.crt -subj '/CN=ZFS Keybox Private CA' -addext 'basicConstraints=critical,CA:TRUE,pathlen:0' -addext 'keyUsage=critical,keyCertSign,cRLSign'
for role in server client; do
    openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "secrets/$role.key"
    openssl req -new -key "secrets/$role.key" -out "secrets/$role.csr" -subj "/CN=zfs-keybox-$role"
    {
        echo 'basicConstraints=critical,CA:FALSE'
        echo 'keyUsage=critical,digitalSignature'
        if [ "$role" = server ]; then
            echo 'extendedKeyUsage=serverAuth'
            echo 'subjectAltName=DNS:zfs-keybox'
        else
            echo 'extendedKeyUsage=clientAuth'
        fi
    } > "secrets/$role.ext"
    openssl x509 -req -in "secrets/$role.csr" -CA secrets/ca.crt -CAkey secrets/ca.key -set_serial "0x$(openssl rand -hex 16)" -days 825 -sha256 -extfile "secrets/$role.ext" -out "secrets/$role.crt"
    rm "secrets/$role.csr" "secrets/$role.ext"
done
chmod 600 secrets/*

scripts/build-in-freebsd-jail.sh

#!/bin/sh
set -eu
umask 077
export IDF_PATH=/opt/esp-idf
export ESP_IDF_VERSION=6.0.3

export IDF_TOOLS_PATH=/opt/idf-tools
export IDF_PYTHON_ENV_PATH=/opt/idf-venv
export PATH=/opt/idf-venv/bin:/usr/local/riscv32-esp-elf-idf60/bin:/opt/esp-idf/tools:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin
unset PYTHONPATH
cd /project
if [ ! -f /build/sdkconfig ]; then
    idf.py -B /build -D SDKCONFIG=/build/sdkconfig set-target esp32c3
fi
idf.py -B /build -D SDKCONFIG=/build/sdkconfig build

scripts/build-in-jail.sh

#!/bin/bash
set -e
umask 077
export PYTHONPATH=/project/scripts/linuxulator${PYTHONPATH:+:$PYTHONPATH}
. /opt/esp/idf/export.sh >/dev/null
cd /project
if [ ! -f sdkconfig ]; then idf.py set-target esp32c3; fi
idf.py build

scripts/linuxulator/sitecustomize.py

"""Use fork for Python child processes on FreeBSD Linuxulator."""
import subprocess
subprocess._USE_VFORK = False
subprocess._USE_POSIX_SPAWN = False

scripts/serial-monitor.py

#!/usr/local/bin/python3.12
import sys, time, serial
port = sys.argv[1]
seconds = int(sys.argv[2]) if len(sys.argv) > 2 else 60
from esptool.reset import HardReset
s = serial.Serial(None, 115200, timeout=0.5)
s.dtr = False
s.rts = False
s.port = port
s.open()
with s:
    HardReset(s, uses_usb=True).reset()
    end = time.monotonic() + seconds
    while time.monotonic() < end:
        data = s.read(4096)
        if data:
            sys.stdout.write(data.decode('utf-8', errors='replace'))
            sys.stdout.flush()

scripts/test-keyserver.py

#!/usr/local/bin/python3.12
"""Verify TLS, mandatory mTLS, exact bytes, response headers and routing."""
import hashlib, ipaddress, pathlib, subprocess, sys, tempfile
root = pathlib.Path(__file__).resolve().parents[1]
ip = str(ipaddress.IPv4Address(sys.argv[1]))
secret = root / 'secrets'
base = ['curl', '--silent', '--show-error', '--noproxy', '*', '--connect-timeout', '5', '--max-time', '20',
        '--cacert', str(secret/'ca.crt'), '--resolve', f'zfs-keybox:443:{ip}']
auth = ['--cert', str(secret/'client.crt'), '--key', str(secret/'client.key')]
with tempfile.TemporaryDirectory(prefix='zfs-test-') as td:
    body, headers = pathlib.Path(td)/'zfs-test.key', pathlib.Path(td)/'headers'
    def request(path, cert=True, method=None):
        args = base + (auth if cert else [])
        if method: args += ['-X', method]
        return subprocess.run(args + ['-D',str(headers),'-o',str(body),'-w','%{http_code}',
                                      'https://zfs-keybox'+path], capture_output=True, text=True)
    try:
        r = request('/zfs.key')
        assert r.returncode == 0 and r.stdout == '200', 'Authenticated HTTPS GET failed: '+r.stderr
        data = body.read_bytes()
        assert len(data) == 32, 'Response is not 32 bytes'
        assert data == (secret/'zfs.key').read_bytes(), 'Key mismatch'
        h = headers.read_text().lower()
        for expected in ['content-type: application/octet-stream', 'content-length: 32', 'cache-control: no-store']:
            assert expected in h, 'Missing header: '+expected
        print('PASS HTTPS/mTLS: HTTP 200, raw 32-byte key, correct headers and exact byte match')
        print('Source SHA256:', hashlib.sha256((secret/'zfs.key').read_bytes()).hexdigest())
        print('Retrieved SHA256:', hashlib.sha256(data).hexdigest())
        r = request('/zfs.key', cert=False)
        assert r.returncode != 0 and r.stdout == '000', 'Unauthenticated connection was not rejected by TLS'
        print('PASS no client certificate: TLS rejected connection')
        for path,method in [('/',None),('/other',None),('/zfs.key?x=1',None),('/zfs.key','POST'),('/zfs.key/','GET')]:
            r = request(path,method=method)
            assert r.returncode == 0 and r.stdout == '404', f'{method or "GET"} {path}: expected 404, got {r.stdout} {r.stderr}'
            assert body.stat().st_size == 0, 'Unexpected error response body'
            print('PASS',method or 'GET',path,'404')
        r = subprocess.run(['curl','--silent','--noproxy','*','--connect-timeout','3','--max-time','5',
                            '-o',str(body),f'http://{ip}/zfs.key'],capture_output=True)
        assert r.returncode != 0, 'Plain HTTP unexpectedly available'
        print('PASS plain HTTP unavailable')
    finally:
        if body.exists():
            subprocess.run(['rm','-P',str(body)],capture_output=True)
            body.unlink(missing_ok=True)

scripts/test-client-rejection.py

#!/usr/local/bin/python3.12
"""Ensure the firmware rejects untrusted and expired client certificates."""
import datetime, ipaddress, os, pathlib, subprocess, sys, tempfile
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
root=pathlib.Path(__file__).resolve().parents[1]
ip=str(ipaddress.IPv4Address(sys.argv[1]))
now=datetime.datetime.now(datetime.timezone.utc)
ca=x509.load_pem_x509_certificate((root/'secrets/ca.crt').read_bytes())
ca_key=serialization.load_pem_private_key((root/'secrets/ca.key').read_bytes(),password=None)
key=ec.generate_private_key(ec.SECP256R1())
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'negative-test-only')])
with tempfile.TemporaryDirectory(prefix='zfs-negative-') as td:
    p=pathlib.Path(td)
    (p/'client.key').write_bytes(key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
    os.chmod(p/'client.key',0o600)
    for kind in ['untrusted','expired']:
        cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name if kind=='untrusted' else ca.subject)
              .public_key(key.public_key()).serial_number(x509.random_serial_number())
              .not_valid_before(now-datetime.timedelta(days=2))
              .not_valid_after(now+datetime.timedelta(days=1) if kind=='untrusted' else now-datetime.timedelta(days=1))
              .add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
              .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False)
              .sign(key if kind=='untrusted' else ca_key,hashes.SHA256()))
        (p/'client.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))
        r=subprocess.run(['curl','--silent','--show-error','--noproxy','*','--max-time','15',
                          '--cacert',str(root/'secrets/ca.crt'),'--cert',str(p/'client.crt'),'--key',str(p/'client.key'),
                          '--resolve',f'zfs-keybox:443:{ip}','-o',str(p/'response'),'-w','%{http_code}',
                          'https://zfs-keybox/zfs.key'],capture_output=True,text=True)
        assert r.returncode != 0 and r.stdout=='000', f'{kind} certificate was not rejected at TLS'
        print('PASS',kind,'client certificate rejected at TLS')
    for f in p.iterdir():
        subprocess.run(['rm','-P',str(f)],capture_output=True)
        f.unlink(missing_ok=True)

scripts/test-fetch.py

#!/usr/local/bin/python3.12
"""Native FreeBSD fetch test using a one-shot loopback CONNECT tunnel for DNS."""
import hashlib, ipaddress, os, pathlib, select, socket, subprocess, sys, tempfile, threading
root = pathlib.Path(__file__).resolve().parents[1]
ip = str(ipaddress.IPv4Address(sys.argv[1]))
listener = socket.socket()
listener.bind(('127.0.0.1', 0))
listener.listen(1)
listener.settimeout(25)
port = listener.getsockname()[1]
def tunnel():
    try:
        with listener.accept()[0] as local:
            local.settimeout(20)
            header = b''
            while b'\r\n\r\n' not in header:
                data = local.recv(1)
                if not data: return
                header += data
                if len(header) > 8192: return
            if header.split(b'\r\n',1)[0] != b'CONNECT zfs-keybox:443 HTTP/1.1':
                local.sendall(b'HTTP/1.1 403 Forbidden\r\n\r\n'); return
            with socket.create_connection((ip,443),timeout=10) as remote:
                local.sendall(b'HTTP/1.1 200 Connection established\r\n\r\n')
                while True:
                    readable,_,_ = select.select([local,remote],[],[],25)
                    if not readable: return
                    for src in readable:
                        data=src.recv(16384)
                        if not data: return
                        (remote if src is local else local).sendall(data)
    finally: listener.close()
thread = threading.Thread(target=tunnel,daemon=True)
thread.start()
with tempfile.TemporaryDirectory(prefix='zfs-fetch-') as td:
    out = pathlib.Path(td)/'zfs-test.key'
    env = os.environ.copy()
    for name in list(env):
        if name.lower().endswith('_proxy'): env.pop(name)
    env['HTTP_PROXY'] = f'http://127.0.0.1:{port}'
    try:
        subprocess.run(['fetch','--ca-cert='+str(root/'secrets/ca.crt'),
                        '--cert='+str(root/'secrets/client.crt'),'--key='+str(root/'secrets/client.key'),
                        '-T','20','-o',str(out),'https://zfs-keybox/zfs.key'],env=env,check=True)
        assert out.stat().st_size == 32
        subprocess.run(['cmp',str(root/'secrets/zfs.key'),str(out)],check=True)
        print('PASS native FreeBSD fetch: 32 bytes, exact match, server hostname verified, mTLS')
        print('Retrieved SHA256:',hashlib.sha256(out.read_bytes()).hexdigest())
    finally:
        if out.exists():
            subprocess.run(['rm','-P',str(out)],capture_output=True)
            out.unlink(missing_ok=True)
thread.join(timeout=2)