# Native ESP32-C3 development in a FreeBSD jail

This documents the native FreeBSD build path for the ZFS key server, alongside the existing Linux development container. Work resumed on 2026-09-09. No secrets are included here.

## Verified result

Completed on 2026-09-09: the same firmware source built successfully using native FreeBSD executables in the ordinary Bastille jail. The resulting images were flashed to the physical ESP32-C3 and all three flash regions verified. Boot, Wi-Fi/DHCP, time synchronization, HTTPS, mandatory mTLS and exact 32-byte key retrieval passed. No application source changes were required.

The ESP32-C3 is now running the native-built firmware. Its verified DHCP address was `192.168.3.225`, with hostname `zfs-keybox`. Authenticated curl and FreeBSD fetch requests returned exactly the source key; missing, untrusted and expired client certificates were rejected. Invalid routes returned 404 and plain HTTP was unavailable.

The existing `esp32-zfs-dev` Podman/Linuxulator container and its original firmware images are preserved. Native development uses the separate Bastille jail `esp32freebsd`. The matching native compiler is also saved as a reusable FreeBSD package; its location and installation instructions are below.

## Layout and access

| Item | Location |
| --- | --- |
| Native jail | `esp32freebsd` |
| Jail root on host | `/usr/local/bastille/jails/esp32freebsd/root` |
| Firmware source on host | `/home/wongk/esp32-zfs-keyserver` |
| Source inside native jail | `/project`, read-only nullfs mount |
| Native build output | `/build` inside jail |
| Exported native images on host | `/home/wongk/esp32-zfs-keyserver/build-freebsd/` |
| Deployment evidence on host | `/home/wongk/esp32-zfs-keyserver/logs/native-freebsd/` |
| ESP-IDF | `/opt/esp-idf` inside jail |
| Native Python environment | `/opt/idf-venv` inside jail |
| Native compiler | `/usr/local/riscv32-esp-elf-idf60/bin` inside jail |
| Build entry point | `/opt/build-keyserver.sh` inside jail |

Start the jail if stopped, then enter a shell:

```sh
doas bastille start esp32freebsd
doas bastille console esp32freebsd
```

Run a build from the host:

```sh
doas bastille cmd esp32freebsd /opt/build-keyserver.sh
```

The jail was created as a FreeBSD 15.1-RELEASE thin jail with DHCP on the existing `vm-public` bridge:

```sh
doas bastille create -B --no-boot esp32freebsd 15.1-RELEASE DHCP vm-public
doas bastille mount esp32freebsd /home/wongk/esp32-zfs-keyserver /project nullfs ro 0 0
```

The observed jail IP was `192.168.3.237`. `--no-boot` disables automatic startup; start it explicitly when needed. VNET jail names in this Bastille version cannot contain hyphens or underscores. The bridge and base release already existed on this machine.

## Native compiler

The official package catalogue on this host provides `py312-esptool`, build utilities and an Xtensa compiler, but not the matching Espressif RISC-V compiler needed for this C3/ESP-IDF combination. The generic `riscv32-unknown-elf-gcc` package is not the matching SDK toolchain.

The compiler was built from the [community FreeBSD port](https://github.com/trombik/xtensa-esp32-elf):

```sh
make -C /usr/ports/devel/riscv32-esp-elf \
  FLAVOR=idf60 BATCH=yes MAKE_JOBS_NUMBER=4 install
```

Installed package: `riscv32-esp-elf-idf60-15.2.0.20251204_1`.

`riscv32-esp-elf-gcc --version` reports GCC 15.2.0, crosstool-NG `esp-15.2.0_20251204`. `file` identifies the compiler as an x86-64 FreeBSD executable using `/libexec/ld-elf.so.1`. Python, CMake, Ninja and the bootstrap compilers were also confirmed as FreeBSD binaries. The generated firmware itself targets RISC-V on the ESP32-C3.

The jail's build dependencies were installed with FreeBSD packages: `git`, `cmake-core`, `ninja`, `python312`, `py312-pip`, `bash`, `gawk`, `patch`, `gnugrep`, `gperf`, `gsed`, `help2man`, `texinfo`, `rust`, `gcc14`, `gcc15`, `autoconf`, `automake`, `bison`, `gmake`, `libtool`, `gettext-runtime`, `libiconv`, `ncurses`, `meson`, and `pkgconf`. Native `py312-esptool`, `py312-cryptography`, `py312-cffi` and `py312-pyyaml` were installed too. The port selected GCC 14 as its bootstrap compiler.

Source revisions used:

| Source | Revision |
| --- | --- |
| ESP-IDF v6.0.3 | `76f5dedd9950a3012fee8fb7d5586df21fc67802` |
| Community toolchain ports | `dac739dfc6c26c37cfcbcdb5c6dd17261914c6d6` |
| FreeBSD ports framework | `fe653567b1c82389013eb31280fea4031edb30ce` |
| Espressif GCC | `esp-15.2.0_20251204` |
| Espressif binutils | `esp-2.45.0_20251204` |
| Espressif newlib | `esp-4.5.0_20251204` |
| Espressif picolibc | `esp-1.8.10_20251204` |

The official ports framework was populated with its `Mk`, `Templates`, `Tools`, `Keywords`, and required language metadata; the community `devel/riscv32-esp-elf` and `devel/xtensa-esp-elf` directories supplied the native toolchain port. Its distfile checksums passed. Toolchain compilation is a one-time setup cost.

## ESP-IDF and Python

ESP-IDF was cloned separately inside the FreeBSD jail:

```sh
git clone --depth 1 --branch v6.0.3 --recursive --shallow-submodules \
  https://github.com/espressif/esp-idf.git /opt/esp-idf
python3.12 -m venv --system-site-packages /opt/idf-venv
```

Do not run the ordinary tool downloader for this path: the inspected SDK maps FreeBSD to Linux binary downloads. The native build script explicitly selects the locally compiled toolchain.

Python requirements use Espressif's `espidf.constraints.v6.0.txt`. One packaging change was necessary: remove `--only-binary cryptography` while retaining the version bounds. There is no matching prebuilt FreeBSD wheel in that installation path. Cryptography 46.0.7 was built into the virtual environment; the system package remains untouched. Other required native extensions, including Pydantic Core, psutil and Tree-sitter, also built successfully.

The adapted constraints are saved at `/opt/espidf.constraints.v6.0.freebsd.txt` and `/opt/idf-tools/espidf.constraints.v6.0.txt`. The installed package list is `/opt/native-python-freeze.txt`.

The build script sets these variables:

```sh
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
```

Setting `ESP_IDF_VERSION` explicitly is necessary for the installed component manager when bypassing `export.sh`. The Linuxulator-specific `sitecustomize.py` workaround is not used in the native jail.

The successful build used these commands:

```sh
cd /project
idf.py -B /build -D SDKCONFIG=/build/sdkconfig set-target esp32c3
idf.py -B /build -D SDKCONFIG=/build/sdkconfig build
```

Both generated configuration and compiled output stay under `/build`, leaving the original Linux build intact. The source mount is read-only; secret resources are embedded from the existing project without displaying or replacing them.

## Exporting and flashing the native build

The native output was copied to `/home/wongk/esp32-zfs-keyserver/build-freebsd/`. The original Linux output remains in `build/`. The native build includes its own `sdkconfig` and generated metadata; its application is 874,624 bytes with 17% of the factory application partition free.

| Native image under `build-freebsd/` | Offset from generated metadata | Bytes |
| --- | --- | --- |
| `bootloader/bootloader.bin` | `0x0` | 21,344 |
| `partition_table/partition-table.bin` | `0x8000` | 3,072 |
| `zfs_keyserver.bin` | `0x10000` | 874,624 |

After future builds, refresh that export from the host:

```sh
doas mkdir -p /home/wongk/esp32-zfs-keyserver/build-freebsd
doas cp -Rp /usr/local/bastille/jails/esp32freebsd/root/build/. \
  /home/wongk/esp32-zfs-keyserver/build-freebsd/
doas chown -R wongk:wongk /home/wongk/esp32-zfs-keyserver/build-freebsd
```

Esptool positively identified the board again before writing: ESP32-C3 QFN32 revision v0.4, embedded 4 MB XMC flash, MAC `90:70:69:ad:77:f4`, native USB Serial/JTAG on `/dev/cuaU1`. Rediscover the device on future runs rather than assuming the name persists:

```sh
doas usbconfig
sysctl dev.umodem
doas esptool --chip esp32c3 -p /dev/cuaU1 chip-id
```

These are the exact flashing and verification commands used on the FreeBSD host:

```sh
cd /home/wongk/esp32-zfs-keyserver/build-freebsd
doas -n esptool --chip esp32c3 -p /dev/cuaU1 -b 460800 \
  --before default-reset --after hard-reset write-flash @flash_args
doas -n esptool --chip esp32c3 -p /dev/cuaU1 -b 460800 \
  --before default-reset --after hard-reset verify-flash @flash_args
```

All three regions passed both write-time hash checking and separate verification against flash. The metadata specifies DIO, 80 MHz and 4 MB flash. USB is accessed from the host; the native jail does not require serial-device access.

Capture a fresh boot using the project's USB-aware reset/monitor script:

```sh
doas python3.12 /home/wongk/esp32-zfs-keyserver/scripts/serial-monitor.py /dev/cuaU1 45
```

The native-built firmware reported ESP-IDF v6.0.3, initialized Wi-Fi, received `192.168.3.225` through DHCP, synchronized network time, and started HTTPS on port 443 with client certificates required.

## Network verification

The tests run from the FreeBSD host, with the existing CA and client certificates and full server hostname verification:

```sh
cd /home/wongk/esp32-zfs-keyserver
python3.12 scripts/test-keyserver.py 192.168.3.225
python3.12 scripts/test-client-rejection.py 192.168.3.225
python3.12 scripts/test-fetch.py 192.168.3.225
```

| Check | Result |
| --- | --- |
| HTTPS GET with trusted client certificate | HTTP 200 |
| Body | Exactly 32 raw bytes, equal to source key |
| Headers | `application/octet-stream`, content length 32, `Cache-Control: no-store` |
| No client certificate | Rejected at TLS |
| Untrusted client certificate | Rejected at TLS |
| Expired client certificate signed by our CA | Rejected at TLS |
| GET `/`, `/other`, `/zfs.key?x=1`, `/zfs.key/` | 404 |
| POST `/zfs.key` | 404 |
| Plain HTTP | Unavailable |
| Native FreeBSD fetch | 32 bytes, exact match, hostname verification and mTLS enabled |

Source and retrieved key SHA-256 both equal:

```text
afb955552a78c9d4f02bff47212b4712f4ebde335c2a28baae444caf2cb2010f
```

The fetch test uses a temporary loopback CONNECT tunnel solely to map `zfs-keybox` to the board IP; TLS and private-key operations remain in native fetch. Temporary downloads and negative-test credentials were removed by the test scripts.

The original Linux-built bootloader, partition table and application hashes still match the pre-experiment record. `esp32-zfs-dev` remains running. The board is now running the native-built images.

## Evidence and repeatability

Evidence is saved under `/home/wongk/esp32-zfs-keyserver/logs/native-freebsd/`: build, chip identification, flash, read-back verification, boot, network tests, certificate rejection tests, fetch tests, native executable identification and original-image preservation records.

Native image SHA-256 values:

```text
bootloader.bin       5ea18ed3e514ddf8c3dcc5c791ed4f5ce62c02a563c3b4a66d717aa782ef89dd
partition-table.bin  7f00b6c042a89b15b0cac534f82ed988caf29278ff5700b0c511eb1b5bb7c820
zfs_keyserver.bin    627808dd89967d20aca7f9ab5c2164e3bac096b12395e4f51b92eeb443176ad8
```

The native and original Linux application images have equal sizes but different hashes; this does not establish byte-for-byte reproducibility across builds. Each deployed image was independently verified against flash and tested on the board. Build timestamps also differ.

A copy of the native build entry point is retained in the firmware project's `scripts/build-in-freebsd-jail.sh`. The installed toolchain and Python environment are reused for subsequent builds. Firmware source remains editable on the host and read-only inside the jail.

No ZFS dataset operations are part of this build/deployment exercise. Build output contains embedded secrets and must remain private.

## Reusing the compiled toolchain package

The installed native compiler was exported as a FreeBSD binary package, and the completed archive was checked by reading its metadata and traversing the entire compressed tar archive:

```text
Inside jail:
/opt/packages/riscv32-esp-elf-idf60-15.2.0.20251204_1.pkg

On host:
/usr/local/bastille/jails/esp32freebsd/root/opt/packages/riscv32-esp-elf-idf60-15.2.0.20251204_1.pkg

Architecture: FreeBSD:15:amd64
SHA256: 68d7a60188c62b1ceac9d43a449949d14f593780351b09ac266df5b829934004
```

This is a locally built package, not an official FreeBSD repository package. It was created with:

```sh
pkg -o COMPRESSION_LEVEL=1 create -o /opt/packages riscv32-esp-elf-idf60
```

On a compatible FreeBSD 15 amd64 jail, install its runtime dependencies from the official repository, transfer the package, and install it:

```sh
pkg install python312 ncurses libiconv gettext-runtime gcc14
pkg add /path/to/riscv32-esp-elf-idf60-15.2.0.20251204_1.pkg
```

ESP-IDF source and the constrained Python environment described above are still required. This package removes the need to rebuild the compiler for another compatible development jail. The compiler package contains toolchain files, not this project's Wi-Fi credentials, TLS private keys or ZFS key.

<!-- BEGIN PROJECT SOURCE LISTINGS -->

## 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
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(zfs_keyserver)
```


### `main/CMakeLists.txt`

```cmake
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`

```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`

```ini
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`

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


### `scripts/pack-wifi.py`

```python
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`

```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`

```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`

```bash
#!/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`

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


### `scripts/serial-monitor.py`

```python
#!/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`

```python
#!/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`

```python
#!/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`

```python
#!/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)
```


<!-- END PROJECT SOURCE LISTINGS -->
