diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8675d11ca..6bfa670b4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,6 +10,9 @@ jobs: # commit twice, without restricting which branches build on push. if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository runs-on: self-hosted + env: + # The ESP32 modules (raw_u64, raw_c3, u64ctrl) need ESP-IDF 6, so they build here, not in my_docker_image + IDF6_IMAGE: espressif/idf:v6.1.1@sha256:2b4f966c37eaedc19542b0637a5f850b2eff9478d8e858192aa0073d92c2dc91 steps: - name: Checkout repository uses: actions/checkout@v7 @@ -186,6 +189,22 @@ jobs: -v /opt/build-tools:/mnt/build-tools:ro \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make host_tests" + # In the ESP-IDF 6 image, because the control module's signature check is + # built against the crypto library that image ships. + - name: Test Recovery Manifest Signature Check + run: | + docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp \ + -v $GITHUB_WORKSPACE:/mnt/project:rw --workdir /mnt/project $IDF6_IMAGE make host_tests_idf6 + + # The UCI TLS commands against stand-ins for FreeRTOS, the UART, lwIP and the + # WiFi module: the module calls, the dedicated channel and the network target + # (network_target.cc, network_target_tls.cc) itself. Needs no device and no network beyond loopback. + - name: Test UCI TLS Sockets + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C target/pc/linux/wifitls test" + - name: Cache U2 FPGA id: cache-u2 uses: actions/cache@v6 @@ -234,16 +253,15 @@ jobs: software/wifi/raw_u64/build/bridge.bin software/wifi/raw_u64/build/bootloader/bootloader.bin software/wifi/raw_u64/build/partition_table/partition-table.bin - key: ${{ runner.os }}-esp32-${{ hashFiles('software/esp_depends.txt') }} + key: ${{ runner.os }}-esp32-${{ env.IDF6_IMAGE }}-${{ hashFiles('software/esp_depends.txt') }} restore-keys: | - ${{ runner.os }}-esp32-${{ hashFiles('software/esp_depends.txt') }} + ${{ runner.os }}-esp32-${{ env.IDF6_IMAGE }}-${{ hashFiles('software/esp_depends.txt') }} - if: steps.cache-esp32.outputs.cache-hit != 'true' name: Build ESP32 Software (skipped if available in cache) run: | - docker run --rm --net=custom_network --mac-address=4c:cc:6a:06:b3:79 \ - -v /opt/build-tools:/mnt/build-tools:ro \ - -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make esp32" + docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp \ + -v $GITHUB_WORKSPACE:/mnt/project:rw --workdir /mnt/project $IDF6_IMAGE make esp32 - if: steps.cache-u2.outputs.cache-hit != 'true' name: Build U2 including FPGAs diff --git a/Makefile b/Makefile index 8a0781f5d..166847b21 100755 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ OPENAPI = python3 tools/openapi/generate.py # make openapi_validate PYTHON=/path/to/venv/bin/python PYTHON ?= python3 -.PHONY: all app_space app_space_test d81_tracks_test observability_test lint_test host_tests openapi openapi_check openapi_test openapi_validate +.PHONY: all app_space app_space_test d81_tracks_test observability_test lint_test host_tests host_tests_idf6 openapi openapi_check openapi_test openapi_validate all: esp32 u2_rv u2plus u2pl u64 u64ii @$(APP_SPACE) report @@ -67,6 +67,11 @@ openapi_validate: exit 2; } @$(PYTHON) -m openapi_spec_validator --validation-errors all `$(OPENAPI) paths` +# The recovery manifest check is built against the crypto library of ESP-IDF 6, +# so it runs in that image (IDF_PATH of an ESP-IDF 6), apart from the rest. +host_tests_idf6: + @$(MAKE) -C target/pc/linux/recoverymanifest test + # Unit tests that run on the build host rather than on the device. Kept out of # the firmware targets deliberately: those build with a cross compiler, and # these need a host g++. @@ -80,7 +85,6 @@ host_tests: @$(MAKE) -C software/io/wifi/tests @$(MAKE) -C software/wifi/tests @$(MAKE) -C software/wifi/uart_tests - @$(MAKE) -C target/pc/linux/recoverymanifest test @$(MAKE) -C target/pc/linux/recoveryimage test @$(MAKE) -C target/pc/linux/recoveryurl test @$(MAKE) -C target/pc/linux/c64mem test @@ -89,6 +93,11 @@ host_tests: @$(MAKE) -C target/pc/linux/socketdma test @$(MAKE) -C target/pc/linux/syslog test @$(MAKE) -C target/pc/linux/ucitargets test + @$(MAKE) -C target/pc/linux/radioentropy test + @$(MAKE) -C target/pc/linux/wifirandom test + @$(MAKE) -C target/pc/linux/wifidedicated test + @$(MAKE) -C target/pc/linux/getrandompaths test + @$(MAKE) -C target/pc/linux/wifitls test @$(MAKE) -C software/userinterface/tests esp32: esp32_raw_u64 esp32_raw_c3 esp32_u64ctrl diff --git a/README.txt b/README.txt index 9b092b117..47a388c05 100644 --- a/README.txt +++ b/README.txt @@ -18,15 +18,15 @@ U2+: U2+L: - Lattice Diamond 3.13 with a (free) generated license - RiscV GNU C/C++ Compiler (for RV32I), same as for U2/RiscV. -- Espressif IDF 5.x +- Espressif IDF 6.x U64: - Altera Quartus (tested with 18.1 Lite Edition) - for the Nios-II compiler only. -- Espressif IDF 5.x +- Espressif IDF 6.x U64E-II: - RiscV GNU C/C++ Compiler (for RV32I), same as for U2/RiscV. -- Espressif IDF 5.x +- Espressif IDF 6.x Environment variables @@ -40,7 +40,7 @@ In this file, you need to set the location of your Xilinx ISE toolchain. Building targets ================ -ALL targets can be built by just typing 'make' in the root of the repository. +ALL targets can be built by just typing 'make' in the root of the repository (see the ESP32 note below). In order to build for U2 only, use the 'u2_rv' target in the top level makefile. This will build the FPGAs as well as the RiscV based software, including all updaters. @@ -53,8 +53,13 @@ target 'niosapps'. This target will only succeed if you have already successfull For the U2+L, you can build the 'u2pl' target. The U64 firmware can be built by typing 'make u64'. - The U64E-II firmware can be built by typing 'make u64ii' +The ESP32 module firmware (software/wifi/raw_u64 for the U64, software/wifi/raw_c3 for the U2+L and +software/u64ctrl for the U64E-II) needs ESP-IDF 6, so IDF_PATH has to be an ESP-IDF 6 for 'make', 'make esp32', +'make u64', 'make u64ii', 'make u2pl' and 'make clean'. The Dockerfile in docker/ still installs ESP-IDF 5.3.1; CI +builds the modules in the espressif/idf:v6.1.1 image (see .github/workflows/build.yml) and then packs them with +'make u64_no_esp', 'make u64ii_no_esp' and 'make u2pl_no_esp'. The README.md in each module directory shows the +command. ==> When using the top level makefile, the results are copied into the root of the project. diff --git a/doc/uci_tls.md b/doc/uci_tls.md new file mode 100644 index 000000000..8b1dde6fa --- /dev/null +++ b/doc/uci_tls.md @@ -0,0 +1,297 @@ +# TLS sockets on the UCI network target + +Commands `$21`-`$25` of network target 3 open TLS client connections. The WiFi module (ESP32) runs the TLS +sessions. The Ultimate keeps the TCP socket and carries the ciphertext between it and the module, so the C64 only ever +sees plaintext. Implementation: `software/io/network/network_target_tls.cc` (Ultimate side), +`software/wifi/tls/tls_engine.c` and `tls_rpc.c` (module side; the directory is shared by module firmware). + +## Conventions + +- Byte 0 of a command is the target (`$03`), byte 1 the command. A command is at most 895 bytes. +- Multi-byte integers in commands and replies are little endian, the IANA values too: TLS 1.3 (`0x0304`) travels as + `04 03`. +- Hash bytes (the pin, the SPKI hash) are in digest order, as `openssl dgst` prints them. +- A reply is data (possibly empty) plus one status string `NN,TEXT`. Hex in status texts is upper case and zero + padded: mbedTLS codes `-0x%04X`, flag words `0x%08X`, versions `0x%04X`. +- A TLS handle is an lwIP descriptor number, in the same space as TCP and UDP handles. +- `$21` and `$24` with the no-reply bit (`$80` in byte 0) are refused with 81 and open nothing. (A build without TLS + answers them from their layout alone, 81 or 90.) +- TLS is built for the Ultimate 64 (Nios II) only. Every other build has the commands without TLS, see + [Builds without TLS](#builds-without-tls). + +## Commands + +### `$21` OPEN_TLS + +``` +[2..3] port (LE) +[4] trust: 0 BUNDLE, 1 CUSTOM, 2 PIN +[5] flags: bit 0 REQUIRE_TLS13; bits 1-7 reserved (a set bit answers 82) +[6..37] pin, 32 bytes, only when trust = 2 (all zero answers 82) +tail host [ $00 [ name [ $00 ] ] ] +``` + +`host` is 1..253 bytes without `$00` (a DNS name or an IPv4 literal). `name` is 1..253 bytes without `$00`: the server +name for SNI and certificate checking. `host`, or `host $00`, gives no explicit name. Anything else in the tail +(empty host, `host $00 $00`, `$00` inside a name, bytes after the name's `$00`, a host or name over 253 bytes) +answers 81. + +The effective server name is the explicit name; else the host unless it is an IPv4 literal (anything lwIP's +`ip4addr_aton` accepts); else none. + +| Trust | Effective name | Server name sent and checked | +|---|---|---| +| BUNDLE, CUSTOM | must exist and must not be an IPv4 literal, else 81 | SNI sent, certificate must carry the name | +| PIN | any; an IPv4 literal counts as none | SNI sent for a DNS name, name not checked; none: no SNI | + +Success reply, 8 bytes, then `00,OK`: + +| Byte | Content | +|---|---| +| 0 | handle | +| 1..2 | negotiated version (`04 03` TLS 1.3, `03 03` TLS 1.2) | +| 3..4 | cipher suite (`01 13` TLS_AES_128_GCM_SHA256) | +| 5..6 | key exchange group (`1D 00` x25519, `17 00` secp256r1); never 0 | +| 7 | bit 0 extended master secret used (1 on TLS 1.2, 0 on 1.3); other bits 0 | + +A failure replies with no data and one status, and leaves nothing open. Refusals are applied in this order, and +nothing touches the network before step 5: + +1. Layout, lengths and tail grammar: 81. Then the name rule for BUNDLE/CUSTOM: 81. Then trust > 2, reserved flag bits, + all-zero pin: 82. +2. Module not available (no module, WiFi off, module image without TLS): 90. +3. No free table entry: 91. +4. CUSTOM and no CA loaded: 97 `NO CUSTOM CA`. +5. The module's open: 17, 87, 90, 92 or 97 (see the status table). +6. DNS: 84, or 17 if a C64 reset cut the wait short. +7. Socket and connect: 85, 11; 17 if a C64 reset cut the wait short; 86 if lwIP hands out a descriptor above 255. +8. Handshake: 13-19, 93-96. + +### `$22` TLS_TRUST_CA + +``` +[2..3] offset (LE) [4..5] total (LE) [6..] DER bytes of this chunk (0..889) +``` + +Uploads the one custom CA that trust mode CUSTOM uses. At most one is held, not stored in flash, and cleared by a +C64 reset or a module restart. + +| Command | Result | +|---|---| +| offset 0, total 1..1472 | starts an upload; any installed CA is dropped at once | +| offset 0, total 0, no data | clears the CA, `00,OK` | +| offset 0, total 0, with data | 81 | +| offset 0, total > 1472 | 82, no CA | +| offset > 0 | must continue the pending upload (offset = bytes so far, same total, not past total), else 81 and the upload is dropped. With no upload pending: 81, an installed CA untouched | +| intermediate chunk | empty reply, `00,OK` | +| final chunk | the module parses it: `00,OK` and the CA is LOADED, or one of the 97 texts below, or 90 / 17; the CA is then EMPTY | + +Any other network target command while an upload is pending cancels it. An ABORT does not. + +### `$23` TLS_INFO + +`[2]` handle. The command must be exactly 3 bytes, else 81. + +Handle `$FF`, the capability record, 16 bytes, `00,OK`. It makes one module STATS call, waited for at most 1 s: + +| Byte | Content | +|---|---| +| 0 | interface version, 1 | +| 1 | maximum sessions, 2 | +| 2 | table entries in use, including failed ones not yet closed | +| 3 | trust modes: bit 0 BUNDLE, bit 1 CUSTOM, bit 2 PIN (always `07`) | +| 4 | ready: bit 0 the module answered a STATS (kept while the module is merely busy, cleared when it stops, has no TLS or restarts); bit 1 entropy (the module has an entropy source on, the radio or the ADC source; never set without bit 0); bit 2 trusted time (SNTP time not before 2025-01-01, or the module's clock while bit 0); bit 3 custom CA LOADED | +| 5 | versions: bit 0 TLS 1.2, bit 1 TLS 1.3 (always `03`) | +| 6 | module major version (0 with no module) | +| 7..8 | module minor version (LE). 0 while no module application is detected, and on builds without TLS | +| 9..11 | `FF FF FF` while bit 0 of byte 4 is set (a bundle is present, the date is unknown; not a date), else 0 | +| 12..13 | the longest the module's dispatcher was blocked since boot, ms (LE); 0 while bit 0 is clear | +| 14 | entries not yet claimed (0 or 1; what `$25` would close) | +| 15 | 0 | + +Bytes 3 and 5 do not say whether a device has TLS: test bit 0 of byte 4. A device where it never sets has none. + +A TLS handle, 48 bytes, `00,OK`. A handle that failed after its handshake still reports the handshake's values: + +| Byte | Content | +|---|---| +| 0..1 | TLS version (LE) | +| 2..3 | cipher suite (LE) | +| 4..5 | group (LE) | +| 6 | trust mode used | +| 7 | the same bits as byte 7 of the open reply | +| 8..39 | SHA-256 of the leaf certificate's SubjectPublicKeyInfo | +| 40..43 | handshake time, ms (LE) | +| 44..47 | 0 | + +Any other handle: no data, 81. + +### `$24` START_TLS + +Starts TLS on a TCP socket this target already owns and has connected. + +``` +[2] handle +[3] trust [4] flags (as $21 [4] and [5]) +[5..36] pin, only when trust = 2 +tail [ name ] [ $00 ] name 1..253 bytes without $00; a lone $00 means no name +``` + +BUNDLE and CUSTOM need a name that is not an IPv4 literal (else 81). PIN with no name sends no SNI. The handle must +be an owned, not yet TLS, stream socket: the check comes first and a UDP handle, a TLS handle or an unowned number +answers 81 with the socket untouched. The TLS layer starts at the socket's current read position. Success replies like +`$21`, with the same handle. + +On failure the code decides what the handle is: + +| Codes | Handle afterwards | +|---|---| +| 81, 82, 87, 90, 91, 92, 97 | unchanged: still an open TCP handle, nothing was sent | +| every other code (11-19, 93-96, 17, 86) | gone: closed and untracked; do not close it | + +### `$25` TLS_RELEASE + +Exactly 2 bytes, else 81. Closes every TLS entry that is still unclaimed (see below) and replies one byte, the number +closed (0 or 1), `00,OK`. The no-reply bit is allowed. It is for one use only: as the next network target command +after an `$21` whose reply the program did not read, so that a session the abandoned open may have created is closed. + +## Sessions after an ABORT + +An ABORT cancels an `$21` or `$24` that is still in flight: the wait ends within about 100 ms and the session the +command had begun on the module is closed, so nothing is left behind and `$25` afterwards is harmless and answers 0. +An ABORT that arrives after the session was made does not close or free it. Every network target command except `$25` and `$23 $FF` (exactly 3 bytes) +marks all open entries as claimed, so only the entry the most recent `$21`/`$24` created can be unclaimed, and only +until the next command. + +- After an ABORTed `$21`: treat any handle from it as gone and send `$25` next (it answers 0 if the abort cancelled the + open, 1 if the session had been made already). `$23 $FF` is allowed in between. +- After an ABORTed `$24`: send CLOSE on the handle. It answers `12,ERROR ON CLOSE: 9` if the handle was already gone, + which is harmless if nothing was opened in between. +- After an ABORT during a READ, or before all of a READ reply was read, plaintext is lost from the stream without an + error: CLOSE the handle. +- After an ABORTed WRITE: it was carried out in full, or the handle is failed. Do not resend it. +- A program that exits without a C64 reset leaves its sessions behind, claimed. The next program finds them with + `$23 $FF` (byte 2 is the count) and `$23 h` for each handle, and CLOSEs those that answer `00,OK`. A C64 reset + closes everything. + +## Existing commands on a TLS handle + +| Command | Behaviour | +|---|---| +| `$10` READ_SOCKET `[2]h [3..4]maxlen` | maxlen 1..1472 (else 82). Reply: 2-byte count, then that much plaintext, in blocks as for TCP. Plaintext already received is returned first; otherwise the target steps the session until plaintext arrives, the stream ends, or the read budget is spent. See the result table. | +| `$11` WRITE_SOCKET `[2]h [3..]data` | 0..892 bytes of plaintext. All or nothing: header `n` = bytes taken, then `00,OK`. 0 bytes: header 0, `00,OK`, nothing sent. A failure answers header `$FFFF`. Sent as TLS records; the plaintext never reaches the TCP socket. | +| `$16` WRITE_SOCKET_CHUNK `[2]h [3..4]offset [5..6]total [7..]data` | Where the firmware has it. The chunks are collected as for a plain socket (total at most 1472); the intermediate chunks answer an empty reply and `00,OK`, and the final chunk is written as one TLS write exactly as `$11` would, with header = total. | +| `$09` CLOSE_SOCKET `[2]h` | Sends close_notify (best effort, 100 ms) if the session is live, then closes the TCP socket. Always `00,OK`, failed or not. No module call if the session is already gone. | + +A pending chunk of `$16` is dropped by any other command, as for plain sockets. + +### READ and WRITE results + +| Situation | READ header | WRITE header | Status | Handle afterwards | +|---|---|---|---|---| +| Data | n | n | `00,OK` | open | +| Nothing yet | `$FFFF` | | `02,NO DATA: 11` | open | +| close_notify from the peer, all delivered | `$0000` | | `01,CONNECTION CLOSED BY HOST` | gone | +| TCP end without close_notify, all delivered | `$0000` | | `05,TLS CLOSED WITHOUT NOTIFY` | gone | +| Fatal alert from the peer | `$0000` | `$FFFF` | `14,TLS ALERT RECEIVED: ` | failed, owned until CLOSE | +| Record or decode failure | `$0000` | `$FFFF` | `16,TLS SESSION FAILED: -0xNNNN` | failed | +| Module timeout, restart, bad reply, WRITE stall | `$0000` | `$FFFF` | `17,TLS MODULE NOT RESPONDING` | failed | +| TCP send failed | `$0000` (later READs) | `$FFFF` | `12,SEND ERROR: ` | failed | +| TCP receive error (peer RST) | `$0000` | `$FFFF` | `12,RECEIVE ERROR: ` | failed (see below) | + +- A receive error fails the handle only when a READ ends in it, after all received plaintext was delivered. A WRITE + that meets it answers `$FFFF` and the same 12 but sends nothing; the READs go on and end in that 12. +- `$0000` on READ means the stream is over. After 01 and 05 the handle is gone: do not CLOSE it, because the number + may already belong to a newer socket. After 12, 14, 16 and 17 the handle is still owned: CLOSE it. +- `$FFFF` with `02,NO DATA: 9` means the number is not the program's handle any more; stop polling. +- 01, 05 and `12,RECEIVE ERROR` come only after every authenticated plaintext byte has been delivered. When a failure + (12 SEND ERROR, 14, 16, 17) is recorded, plaintext received but not yet read is discarded. +- A WRITE ends only when the module has taken all the plaintext and has no more ciphertext to send. If it cannot + within 4 module steps or 10 s, the handle fails with 17. +- Before a WRITE, READ until `$FFFF` with `02,NO DATA: 11` or `$0000`. If a WRITE still answers `$FFFF` with a `12` + other than `RECEIVE ERROR`, CLOSE the handle at once. + +## Status codes + +| Code | Text | From | Meaning | +|---|---|---|---| +| 01 | CONNECTION CLOSED BY HOST | READ | clean close; handle gone | +| 05 | TLS CLOSED WITHOUT NOTIFY | READ | TCP end without close_notify, possible truncation; handle gone | +| 11 | ERROR ON CONNECT: errno | OPEN | as OPEN_TCP, including the connect timeout | +| 12 | SEND ERROR: errno, RECEIVE ERROR: errno | READ, WRITE | failed handle; never from `$21` or `$24` | +| 13 | TLS HANDSHAKE FAILED: -0xNNNN, or `: NO EMS`, `: NO ENTROPY`, `: PEER CLOSED`, `: PEER RESET: errno`, `: SEND ERROR: errno` | OPEN | a handshake failure that is none of 14, 15, 18, 19, 93-96 | +| 14 | TLS ALERT RECEIVED: n | OPEN, READ, WRITE | fatal alert n from the server; 70 is protocol_version | +| 15 | TLS HANDSHAKE TIMEOUT | OPEN | no established session in 15 s, or the 40 s open budget ran out in the handshake | +| 16 | TLS SESSION FAILED: -0xNNNN | READ, WRITE | bad record MAC, decode error, too many empty records, KeyUpdate | +| 17 | TLS MODULE NOT RESPONDING | any | module timeout, full queue, malformed reply, restart or WRITE stall | +| 18 | TLS VERSION REFUSED: 0xNNNN | OPEN | the ServerHello chose a version not offered (TLS 1.2 under REQUIRE_TLS13, or below 1.2), or a TLS 1.2 ServerHello carried version 0x0304 (TLS 1.3 claimed through the 1.2 path) | +| 19 | TLS DOWNGRADE DETECTED | OPEN | a TLS 1.2 ServerHello carrying the RFC 8446 4.1.3 downgrade sentinel | +| 81 | INVALID PARAMS | all | layout, lengths, tail grammar, name rule, not a TLS handle for `$23`, bad handle for `$24`, `$22` sequence error, no-reply bit on `$21`/`$24` | +| 82 | PARAMETER(S) OUT OF RANGE | all | trust > 2, reserved flag bit, all-zero pin, READ maxlen 0 or > 1472, CA total > 1472 | +| 84 | UNRESOLVED HOST | OPEN | as OPEN_TCP, also a 10 s DNS timeout | +| 85 | ERROR OPENING SOCKET | OPEN | as OPEN_TCP | +| 86 | INTERNAL ERROR | any | | +| 87 | NO ENTROPY SOURCE | OPEN, START_TLS | no entropy source is on, so there is no random seed. Answered only at the module's OPEN (step 5), before anything is sent: the radio is off and the ADC source did not read back. The handle is always unchanged, so 87 never ends a handle. A source that is lost after the OPEN is answered as `13,TLS HANDSHAKE FAILED: NO ENTROPY` and the handle is gone, as for every 13: only a random draw that lands inside a radio change, or after a failed readback, finds no source (a finished radio stop leaves the ADC source on; a voltage read, on a product that has one, only delays a draw while its hold of the entropy gate stays under the 60 ms a draw waits, and a longer hold fails the draw; `raw_u64` has no voltage read). A draw that finds the entropy gate busy for that whole wait, which on `raw_u64` means a radio change in progress, is answered the same way, `13,TLS HANDSHAKE FAILED: NO ENTROPY`, even with the source on. A radio change is also started implicitly, by a `CMD_WIFI_IS_CONNECTED` on an Ultimate without the radio switch and by the WiFi connector when it enables a disabled radio. A radio change or a voltage read never waits for the handshake's computing: each draw holds the source only for itself | +| 90 | TLS NOT AVAILABLE | OPEN, START_TLS, TRUST | no module, WiFi disabled, a module image without TLS, or a build without TLS | +| 91 | TLS SESSIONS IN USE | OPEN, START_TLS | both table entries are used, failed ones included; none is ever evicted | +| 92 | NO TRUSTED TIME | OPEN, START_TLS | BUNDLE and CUSTOM need a trusted clock; PIN does not | +| 93 | CERTIFICATE NOT TRUSTED: 0xNNNNNNNN | OPEN | chain not trusted, bad signature, weak key or hash, bad key usage; `0xFFFFFFFF` when verification did not complete | +| 94 | CERTIFICATE NAME MISMATCH: 0xNNNNNNNN | OPEN | the certificate is not for the server name | +| 95 | CERTIFICATE EXPIRED: 0xNNNNNNNN | OPEN | expired or not yet valid by the trusted clock | +| 96 | PINNED KEY MISMATCH | OPEN | PIN only: the leaf key is not the pinned key | +| 97 | CUSTOM CA INVALID: -0xNNNN, CUSTOM CA REJECTED: RSA KEY < 2048, CURVE or NOT A CA, NO CUSTOM CA | TRUST, OPEN | the upload did not parse or was refused when uploaded, or CUSTOM without a loaded CA the module holds | + +Where a chain is both untrusted and has the wrong name, the answer is 94. Only the first two digits are the code: a +client matches on those. + +## Trust modes and flags + +| Trust | Verifies against | +|---|---| +| 0 BUNDLE | the Mozilla root store built into the module (`software/u64ctrl/ca/cacert.pem`, the list the control module trusts too) | +| 1 CUSTOM | the one CA uploaded with `$22`, and nothing else | +| 2 PIN | the SHA-256 of the server leaf's SubjectPublicKeyInfo. The certificate chain and name are not checked; key usage and extended key usage still are | + +There is no mode without verification. BUNDLE and CUSTOM need a trusted time, so 92 until the SNTP clock is set. + +| Flag | Meaning | +|---|---| +| bit 0 REQUIRE_TLS13 | offer TLS 1.3 only. Clear: offer TLS 1.3 and hardened TLS 1.2 | +| bits 1-7 | reserved, answer 82 | + +Policy of the module's client, for both versions: + +- TLS 1.2 suites: ECDHE-ECDSA and ECDHE-RSA with AES-128-GCM, AES-256-GCM or ChaCha20-Poly1305 (`C02B C02C C02F C030 + CCA9 CCA8`). TLS 1.3 suites `1301 1302 1303`. No CBC, static key exchange, finite-field DH, PSK or SHA-1/MD5 + signatures. +- Key exchange groups, in order: x25519, secp256r1, secp384r1, secp521r1. +- TLS 1.2 requires the extended master secret (else `13,...: NO EMS`). No renegotiation, no session tickets or + resumption. +- A TLS 1.3 KeyUpdate from the server is not supported (mbedTLS 4.1.1 treats it as an unexpected message): the READ or + WRITE that meets it fails with `16,TLS SESSION FAILED: -0x7700` and the handle is closed. Servers send a KeyUpdate + only near the record limit of the cipher, about 2^24 records, so a C64 transfer does not reach it. +- A ServerHello without `supported_versions` is 18 under REQUIRE_TLS13; in default mode it is 19 only when its random + ends in the downgrade sentinel, else 13. A protocol_version alert is always 14 with 70. + +## Timing + +| Stage | Limit | +|---|---| +| module open | 5 s | +| DNS (inside `$21` only) | 10 s | +| TCP connect | 10 s | +| handshake | 15 s | +| `$21` or `$24` in total | 40 s; the command can take about 41 s before it answers | +| every other TLS command | 12 s at most | + +A program waits at least 45 s for `$21` and `$24` and 12 s for the others before it treats the interface as wedged. Only +a C64 reset ends a command early. + +## Builds without TLS + +Builds other than the Ultimate 64 (the U2 family, the Ultimate 64-II) have the commands but no TLS: + +- `$23 $FF` answers the 16-byte record with byte 4 = 0, byte 3 = `07` and byte 5 = `03`; byte 6..8 are 0. +- `$21` checks its layout (81) and otherwise answers 90, including trust > 2. `$24` answers 81 for a handle it does + not own, else 90. `$22` answers 81 below 6 bytes, else 90 for every chunk, the clear included. `$25` answers one + byte, 0, `00,OK`. diff --git a/run-tests b/run-tests index ab2b5bad8..2da9e5a53 100755 --- a/run-tests +++ b/run-tests @@ -419,6 +419,11 @@ SUITES: Sequence[Suite] = ( # it skips when the device has no second address on this host's subnet. Suite("e2e", "uci-net-route", "tests/e2e/io/command_interface/net_route_test.py", "-H @HOST@ -p @PASS@ -t @TIMEOUT@", profile=profiles.DEEP), + # The UCI TLS suite against a simulated device; needs no device. The device + # suite itself, net_tls_test.py, is opt-in by name only and deliberately NOT + # registered: see tests/lib/registry_test.py NOT_SUITES. + Suite("e2e", "uci-net-tls-selftest", "tests/e2e/io/command_interface/net_tls_selftest.py", + "", profile=profiles.DEEP), # Two checks that are genuinely about the Telnet transport itself (a # concurrent poll-mode connection, per-keystroke output volume) only run # under --mode telnet. diff --git a/software/esp_depends.py b/software/esp_depends.py index 7d3fcd73c..689d9e3b0 100644 --- a/software/esp_depends.py +++ b/software/esp_depends.py @@ -11,7 +11,7 @@ def get_hash(path="", hash_type='md5'): return func.hexdigest() # Find dependencies -dirs = [ 'wifi/raw_c3/main', 'wifi/raw_c3', 'wifi/raw_u64/main', 'wifi/raw_u64', 'u64ctrl', 'u64ctrl/main', 'u64ctrl/ca', 'wifi/common' ] +dirs = [ 'wifi/raw_c3/main', 'wifi/raw_c3', 'wifi/raw_u64/main', 'wifi/raw_u64', 'wifi/tls', 'u64ctrl', 'u64ctrl/main', 'u64ctrl/ca', 'wifi/common' ] ptrns = [ '*.c', '*.h', '*.mk', '*.txt', '*.pem', 'sdkconfig'] fns = [ ] for d in dirs: diff --git a/software/io/command_interface/command_intf.cc b/software/io/command_interface/command_intf.cc index 5b0dde4f8..c803bdfb2 100644 --- a/software/io/command_interface/command_intf.cc +++ b/software/io/command_interface/command_intf.cc @@ -333,6 +333,11 @@ void CommandInterface :: copy_result(Message *data, Message *status) } } +bool CommandInterface :: reset_pending(void) +{ + return c64_reset_pending; +} + bool CommandInterface :: is_dma_active(void) { return ((CMD_IF_HANDSHAKE_OUT & CMD_HS_DMA_ACTIVE) != 0); diff --git a/software/io/command_interface/command_intf.h b/software/io/command_interface/command_intf.h index ef4c0643d..0cc417795 100644 --- a/software/io/command_interface/command_intf.h +++ b/software/io/command_interface/command_intf.h @@ -108,6 +108,10 @@ class CommandInterface : public SubSystem void deferred_done(uint32_t done); const char *identify(void) { return "Command Interface"; } bool is_dma_active(void); + // Whether a C64 reset has come in that run_task has not yet handed to the + // targets. Only looks: a long command polls it to end early, and the reset + // is still delivered after the command returns. + bool reset_pending(void); void set_kernal_device_id(uint8_t id); }; diff --git a/software/io/network/network_target.cc b/software/io/network/network_target.cc index 99f55c8bd..c91759f42 100644 --- a/software/io/network/network_target.cc +++ b/software/io/network/network_target.cc @@ -13,6 +13,11 @@ #include "socket_slices.h" #include #include +#if U64 >= 1 +#include "wifi_random.h" +#endif +#include +#include NetworkTarget net(3); @@ -25,6 +30,8 @@ Message c_status_no_socket = { 23, true, (uint8_t *)"85,ERROR OPENING Message c_status_socket_closed = { 28, true, (uint8_t *)"01,CONNECTION CLOSED BY HOST" }; Message c_status_net_no_data = { 26, true, (uint8_t *)"03,MORE DATA NOT SUPPORTED" }; Message c_status_internal_error = { 17, true, (uint8_t *)"86,INTERNAL ERROR" }; +Message c_status_no_entropy = { 20, true, (uint8_t *)"87,NO ENTROPY SOURCE" }; +Message c_status_entropy_busy = { 22, true, (uint8_t *)"88,ENTROPY SOURCE BUSY" }; // lwIP also uses SO_SNDTIMEO as the time a close may wait for a buffer for the FIN (20 s without // it); with the send slice it would reset the connection after 100 ms and drop unsent data. @@ -52,6 +59,9 @@ NetworkTarget::NetworkTarget(int id) quick_message.message = quick_bytes; socket_count = 0; discard_read_reply(); +#if NET_TLS + tls_init(); +#endif memset(jobs, 0, sizeof(jobs)); job = NULL; queue = NULL; @@ -90,6 +100,12 @@ void NetworkTarget :: answer_quick(Message *command, Message **reply, Message ** { NetworkInterface *interface; +#if NET_TLS + // Every command counts as one for the TLS rules, and the TLS state belongs to the worker: + // this one leaves word for it (tls_before_command). + tls_quick_seen = true; +#endif + switch(command->message[1]) { case NET_CMD_IDENTIFY: *reply = &c_net_message_identification; @@ -286,6 +302,10 @@ void NetworkTarget :: worker_task(void *a) t->execute(&j->command, &j->reply, &j->status); j->opened = t->opened_socket; t->cancel = NULL; + } else { +#if NET_TLS + t->tls_quick_seen = true; // it was a command all the same +#endif } t->close_sockets_after_reset(); portENTER_CRITICAL(); @@ -326,6 +346,9 @@ void NetworkTarget :: close_sockets_after_reset(void) uint32_t seen = resets; if (seen != resets_closed) { close_all_sockets(); +#if NET_TLS + tls_reset(); +#endif resets_closed = seen; } } @@ -341,6 +364,10 @@ void NetworkTarget :: execute(Message *command, Message **reply, Message **statu // client bytes left over from an earlier read. discard_read_reply(); +#if NET_TLS + tls_before_command(command); +#endif + switch(command->message[1]) { case NET_CMD_SET_IPADDR: *reply = &c_message_empty; @@ -397,6 +424,29 @@ void NetworkTarget :: execute(Message *command, Message **reply, Message **statu case NET_CMD_WRITE_SOCKET: write_socket(command, reply, status); break; + case NET_CMD_GET_RANDOM: + if (command->length != 4) { // 2 + 2 + *reply = &c_message_empty; + *status = &c_status_invalid_params; + break; + } + get_random(command, reply, status); + break; + case NET_CMD_OPEN_TLS: + open_tls(command, reply, status); + break; + case NET_CMD_TLS_TRUST_CA: + trust_ca(command, reply, status); + break; + case NET_CMD_TLS_INFO: + tls_info(command, reply, status); + break; + case NET_CMD_START_TLS: + start_tls(command, reply, status); + break; + case NET_CMD_TLS_RELEASE: + tls_release(command, reply, status); + break; default: *reply = &c_message_empty; *status = &c_status_unknown_command; @@ -482,6 +532,14 @@ void NetworkTarget :: read_socket(Message *command, Message **reply, Message **s uint8_t socketnr = command->message[2]; uint32_t length = ((uint32_t)command->message[3]) | (((uint32_t)command->message[4]) << 8); +#if NET_TLS + TlsSocket *session = tls_find(socketnr); + if (session) { + tls_read(session, length, reply, status); + return; + } +#endif + // A complete unfragmented IPv4 UDP datagram is the most this command can // ever return, so that is what it accepts. Anything larger cannot arrive. if (length > NET_MAX_SOCKET_READ) { @@ -593,6 +651,13 @@ void NetworkTarget :: write_socket(Message *command, Message **reply, Message ** int length = command->length - 3; int ret; +#if NET_TLS + TlsSocket *session = (command->length >= 3) ? tls_find(socketnr) : NULL; + if (session) { + tls_write(session, src, length, reply, status); + return; + } +#endif if (owns_socket(socketnr)) { SliceWait wait(cancel, 0); // no limit, as before, unless the command is aborted int sent = 0, waited_ms = 0; @@ -648,6 +713,16 @@ void NetworkTarget :: close_socket(Message *command, Message **reply, Message ** { uint8_t socketnr = command->message[2]; int result = -1; +#if NET_TLS + // Always OK: the session goes, whatever state it is in. + TlsSocket *session = tls_find(socketnr); + if (session) { + tls_close_entry(session, true); + *reply = &c_message_empty; + *status = &c_status_ok; + return; + } +#endif if (owns_socket(socketnr)) { untrack_socket(socketnr); result = close_after_slices(socketnr); @@ -664,6 +739,36 @@ void NetworkTarget :: close_socket(Message *command, Message **reply, Message ** } } +void NetworkTarget :: get_random(Message *command, Message **reply, Message **status) +{ + uint16_t length = uint16_t(command->message[2]) | (uint16_t(command->message[3]) << 8); + + *reply = &c_message_empty; + if ((length == 0) || (length > NET_MAX_RANDOM)) { + *status = &c_status_param_out_of_range; + return; + } + // The bytes come from the WiFi module's hardware generator and from + // nowhere else, so without that module there are none. + *status = &c_status_no_entropy; +#if U64 >= 1 + static_assert(NET_MAX_RANDOM == WIFI_RANDOM_MAX_BYTES, "the module's limit and the UCI's differ"); + // The reply stays empty unless the result may carry data, and 87 stays + // for any status not handled here. + int result = wifi_get_random(data_message.message, length); + if (wifi_random_status(result) == 0) { + data_message.length = length; + data_message.last_part = true; + *reply = &data_message; + *status = &c_status_ok; + } else if (wifi_random_status(result) == 88) { + *status = &c_status_entropy_busy; + } else if (wifi_random_status(result) == 86) { + *status = &c_status_internal_error; + } +#endif +} + // A socket handed to the client without a table entry would survive a C64 // reset, which is the defect in #808, so the table must cover every descriptor // lwip can return. lwip's NUM_SOCKETS is MEMP_NUM_NETCONN, tested here rather diff --git a/software/io/network/network_target.h b/software/io/network/network_target.h index 6b2048eb1..c8d4ff899 100644 --- a/software/io/network/network_target.h +++ b/software/io/network/network_target.h @@ -24,6 +24,12 @@ #define NET_CMD_CLOSE_SOCKET 0x09 #define NET_CMD_READ_SOCKET 0x10 #define NET_CMD_WRITE_SOCKET 0x11 +#define NET_CMD_GET_RANDOM 0x20 +#define NET_CMD_OPEN_TLS 0x21 +#define NET_CMD_TLS_TRUST_CA 0x22 +#define NET_CMD_TLS_INFO 0x23 +#define NET_CMD_START_TLS 0x24 +#define NET_CMD_TLS_RELEASE 0x25 #define NET_CMD_BUFSIZE 2048 @@ -46,10 +52,61 @@ // Payload bytes in the first block, which also carries the two byte header. #define NET_FIRST_BLOCK_PAYLOAD (NET_MAX_REPLY_BLOCK - 2) +// The most random bytes GET_RANDOM returns at once, which is what the WiFi +// module hands out per request (RANDOM_MAX_BYTES in software/wifi/common/rpc_shared.h; +// network_target.cc and wifi_random.cc assert the three agree). +#define NET_MAX_RANDOM 512 +// TLS sockets: the WiFi module runs the session, this target +// keeps the TCP socket and carries the ciphertext. U64 only; elsewhere the +// commands exist and answer that TLS is not available. The target with the WiFi +// module is the Nios II one (wifi_tls.cc is not built for the others). +#if (U64 == 1) && defined(NIOS) +#define NET_TLS 1 +#else +#define NET_TLS 0 +#endif + +#define NET_MAX_TLS 2 // the module's cap (TLS_MAX_SESSIONS), asserted in network_target_tls.cc +#define NET_TLS_CT_MAX 1536 // ciphertext into one step +#define NET_TLS_PT_MAX 1024 // one step's output +#define NET_TLS_CA_MAX 1472 // one DER certificate +#define NET_TLS_STICKY_MAX 48 // the longest status a failed session keeps + #if NET_MAX_SOCKET_READ > NET_CMD_BUFSIZE #error "the socket read buffer cannot hold the largest accepted read" #endif +#if NET_MAX_RANDOM > NET_MAX_REPLY_BLOCK +#error "random bytes must fit a single reply block" +#endif +// One TLS socket: the TCP socket, which is also in sockets[], and the session +// on the module that runs over it. +struct TlsSocket { + bool used; + int socketnr; + uint8_t slot; // on the module; the index of this entry + uint16_t tag; // with slot, names the session on the module + bool failed; // sticky: every READ and WRITE answers `sticky` until CLOSE + char sticky[NET_TLS_STICKY_MAX]; + bool claimed; // any network command but $23 $FF and $25 claims every entry + bool module_live; // false once the module freed the session: CLOSE sends no RPC + int rx_err; // the first receive error, latched; 0 = none, no receive after it + bool write_saw_rx_err; // a WRITE reported rx_err: the stream ends in that 12 + bool rx_fin; // TCP said end of stream; no receive after it + bool module_more; // the last step handed something out: the next READ steps at once + uint8_t end; // how the stream ends once rx is empty (TLS_END_*) + uint8_t quiet; // ct_in_len-0 drain steps in a row that changed nothing, across READs + uint16_t rx_off, rx_len; // plaintext received, not yet read by the C64 + uint16_t held_len; // ciphertext received, not yet taken by the module + // What OPEN answered with, for TLS_INFO. + uint16_t version, suite, group; + uint8_t trust, bits; + uint8_t spki[32]; + uint32_t handshake_ms; + uint8_t rx[NET_TLS_PT_MAX]; + uint8_t held[NET_TLS_CT_MAX]; +}; + // Commands the worker may hold: the one the C64 waits for, and ones that were aborted // while they still run or wait. With none free, a command fails at once. #define NET_JOBS 4 @@ -100,6 +157,65 @@ class NetworkTarget : public CommandTarget { int sockets[NET_MAX_SOCKETS]; int socket_count; +#if NET_TLS + TlsSocket tls[NET_MAX_TLS]; + uint16_t tls_last_tag; + bool tls_generation_known; + volatile bool tls_quick_seen; // a command ran or was skipped apart from the worker; see tls_before_command + uint32_t tls_generation; + uint8_t ca_state; // CA_EMPTY, CA_UPLOADING or CA_LOADED + uint16_t ca_tag; // never 0; a new one whenever the CA changes + uint16_t ca_len; + uint16_t ca_total; + uint8_t ca_buf[NET_TLS_CA_MAX]; + // The last global STATS that answered, for TLS_INFO $FF: kept through a + // STATS that fails for a busy module, so that one slow RPC does not flip + // the ready bits; dropped when the module is gone, has no TLS, or restarts. + bool info_valid; + uint32_t info_generation; + uint8_t info_ready; // ready bits 0-2 as that STATS gave them + uint16_t info_block_max_ms; + uint8_t tls_ct_out[NET_TLS_CT_MAX]; + uint8_t tls_pt[NET_TLS_PT_MAX]; + + void tls_init(void); + void tls_before_command(Message *command); + void tls_reset(void); + TlsSocket *tls_find(int socketnr); + TlsSocket *tls_reserve(void); + int tls_in_use(bool unclaimed_only); + uint16_t tls_new_tag(void); + void tls_new_ca_tag(void); + void tls_check_generation(void); + void tls_fail(TlsSocket *e, const char *text); + void tls_fail_module(TlsSocket *e, bool cleanup); + void tls_fail_step(TlsSocket *e, int esp_err, uint8_t alert_in); + void tls_close_entry(TlsSocket *e, bool send_notify); + void tls_cleanup_close(TlsSocket *e); + void tls_abandon(TlsSocket *e); + int tls_run_step(TlsSocket *e, void *step, uint32_t deadline, bool use_deadline); + int tls_send_all(int sock, const uint8_t *data, int length, uint32_t deadline); + bool tls_wait(int sock, bool for_write, uint32_t until); + int tls_resolve(const char *host, uint32_t deadline, uint32_t *address); + int tls_connect(int sock, uint32_t address, uint16_t port, uint32_t deadline); + Message *tls_prepare(TlsSocket *e, uint8_t trust, uint8_t flags, const uint8_t *pin, const char *name, + int name_len, uint32_t total, bool *keep); + Message *tls_handshake(TlsSocket *e, uint32_t total); + Message *tls_classify(TlsSocket *e, void *step); + void tls_reply_open(TlsSocket *e, Message **reply); + void tls_read(TlsSocket *e, uint32_t length, Message **reply, Message **status); + void tls_write(TlsSocket *e, const uint8_t *data, int length, Message **reply, Message **status); + void tls_end(TlsSocket *e, Message **reply, Message **status); +#endif + Message *set_status(const char *text); + Message *tls_parse_open(Message *command, int fixed, bool start, uint8_t *trust, uint8_t *flags, + const uint8_t **pin, const char **host, int *host_len, const char **name, int *name_len); + void open_tls(Message *command, Message **reply, Message **status); + void start_tls(Message *command, Message **reply, Message **status); + void trust_ca(Message *command, Message **reply, Message **status); + void tls_info(Message *command, Message **reply, Message **status); + void tls_release(Message *command, Message **reply, Message **status); + bool track_socket(int socketnr); void untrack_socket(int socketnr); bool is_datagram_socket(int socketnr); @@ -110,6 +226,7 @@ class NetworkTarget : public CommandTarget { void read_socket(Message *command, Message **reply, Message **status); void write_socket(Message *command, Message **reply, Message **status); void close_socket(Message *command, Message **reply, Message **status); + void get_random(Message *command, Message **reply, Message **status); void start_read_reply(int payload_length, Message *result, Message **reply, Message **status); void discard_read_reply(void); @@ -143,6 +260,11 @@ class NetworkTarget : public CommandTarget { void get_more_data(Message **reply, Message **status); void abort(int a); void c64_reset(void); + + // For the TLS waits, which run on the worker: a C64 reset the UCI Server task has noted but the worker has not + // yet acted on, and an abort of the command that runs. + bool reset_noted(void) { return resets != resets_closed; } + bool job_aborted(void) { return cancel && *cancel; } }; #endif /* IO_NETWORK_NETWORK_TARGET_H_ */ diff --git a/software/io/network/network_target_tls.cc b/software/io/network/network_target_tls.cc new file mode 100644 index 000000000..fd3fad299 --- /dev/null +++ b/software/io/network/network_target_tls.cc @@ -0,0 +1,1684 @@ +/* + * network_target_tls.cc + * + * The TLS commands of the network target ($21-$25) and the TLS side of its socket commands. + * The protocol is described in doc/uci_tls.md. + */ + +#include "network_target.h" +#include "network_interface.h" +#include "socket.h" +#include "lwip/opt.h" +#include "netdb.h" +#include +#include +#include +#include +#if NET_TLS +#include "lwip/dns.h" +#include "lwip/tcpip.h" +#include "FreeRTOS.h" +#include "task.h" +#include "sntp_time.h" +#include "wifi_tls.h" +#endif + +extern Message c_status_invalid_params; +extern Message c_status_param_out_of_range; +extern Message c_status_host_not_resolvable; +extern Message c_status_no_socket; +extern Message c_status_internal_error; +extern Message c_status_socket_closed; + +// The status texts are part of the protocol (doc/uci_tls.md). +#define TLS_MESSAGE(text) { sizeof(text) - 1, true, (uint8_t *)text } +Message c_status_tls_not_available = TLS_MESSAGE("90,TLS NOT AVAILABLE"); +Message c_status_tls_in_use = TLS_MESSAGE("91,TLS SESSIONS IN USE"); +Message c_status_tls_no_time = TLS_MESSAGE("92,NO TRUSTED TIME"); +Message c_status_tls_no_custom_ca = TLS_MESSAGE("97,NO CUSTOM CA"); +Message c_status_tls_module = TLS_MESSAGE("17,TLS MODULE NOT RESPONDING"); +Message c_status_tls_hs_timeout = TLS_MESSAGE("15,TLS HANDSHAKE TIMEOUT"); +Message c_status_tls_downgrade = TLS_MESSAGE("19,TLS DOWNGRADE DETECTED"); +Message c_status_tls_pin_mismatch = TLS_MESSAGE("96,PINNED KEY MISMATCH"); +Message c_status_tls_no_notify = TLS_MESSAGE("05,TLS CLOSED WITHOUT NOTIFY"); +extern Message c_status_no_entropy; // network_target.cc: GET_RANDOM answers the same + +#if NET_TLS +// Deadlines and caps. +#define TLS_DNS_MS 10000 +#define TLS_CONNECT_MS 10000 +#define TLS_OPEN_TOTAL_MS 40000 +#define TLS_HANDSHAKE_MS 15000 +#define TLS_STEP_RPC_MS 5000 +#define TLS_OPEN_RPC_MS 5000 +#define TLS_CLOSE_RPC_MS 1000 +#define TLS_STATS_RPC_MS 1000 +#define TLS_CLOSE_ALL_RPC_MS 500 +#define TLS_READ_WAIT_MS 40 +#define TLS_READ_BUDGET_STEPS 8 +#define TLS_READ_BUDGET_MS 250 +#define TLS_READ_TOTAL_MS 10000 +#define TLS_WRITE_BUDGET 4 +#define TLS_WRITE_TOTAL_MS 10000 +#define TLS_SEND_MS 5000 +#define TLS_NOTIFY_SEND_MS 100 +#define TLS_UNSENT_RETRIES 10 +#define TLS_UNSENT_DELAY_MS 50 +#define TLS_SLICE_MS 100 // the longest any wait goes without looking at a reset +#define TLS_SNDTIMEO_MS 500 // caps lwIP's close when it cannot get memory for the FIN + // (api_msg.c:1034-1037, else 20 s); our sends are MSG_DONTWAIT +#define TLS_EARLIEST_TIME 1735689600u // 2025-01-01: an SNTP time before this is not one + +#define CA_EMPTY 0 +#define CA_UPLOADING 1 +#define CA_LOADED 2 + +// How a stream ends once the C64 has read everything before the end. +#define TLS_END_NONE 0 +#define TLS_END_CLOSED 1 // close_notify: 01, the handle is gone +#define TLS_END_NO_NOTIFY 2 // TCP end without close_notify: 05, the handle is gone +#define TLS_END_RX_ERR 3 // the latched receive error: sticky 12 + +static_assert(NET_MAX_TLS == WIFI_TLS_MAX_SESSIONS, "the TLS table must match the module's cap"); +static_assert(NET_TLS_CT_MAX == WIFI_TLS_STEP_MAX_IN, "a step takes at most this much ciphertext"); +static_assert(NET_TLS_PT_MAX == WIFI_TLS_STEP_MAX_OUT, "a step hands out at most this much"); +static_assert(NET_TLS_CA_MAX == WIFI_TLS_CA_MAX, "CA sizes differ"); +static_assert(NET_MAX_SOCKET_READ <= NET_CMD_BUFSIZE, "a TLS read goes through buffer"); +#endif + + +Message *NetworkTarget :: set_status(const char *text) +{ + // The status length register is 8 bits, so 255 is the longest status a reply can carry + int n = strlen(text); + if (n > CMD_MAX_STATUS_LEN - 1) { + n = CMD_MAX_STATUS_LEN - 1; + } + memcpy(status_message.message, text, n); + status_message.length = n; + status_message.last_part = true; + return &status_message; +} + +// Byte-exact parsing of OPEN_TLS ($21, fixed = 6) and START_TLS ($24, fixed = 5): the refusals that need only the +// command, 81 before 82. OPEN's tail is host [ $00 [ name [ $00 ] ] ], START's is [ name ] [ $00 ]; host and name +// point into the command, unterminated. NULL when the command is well formed. +Message *NetworkTarget :: tls_parse_open(Message *command, int fixed, bool start, uint8_t *trust, uint8_t *flags, + const uint8_t **pin, const char **host, int *host_len, const char **name, + int *name_len) +{ + const uint8_t *m = command->message; + int length = command->length; + if (length < fixed) { + return &c_status_invalid_params; + } + *trust = m[fixed - 2]; + *flags = m[fixed - 1]; + int pos = fixed; + *pin = NULL; + if (*trust == 2) { // PIN + if (length < fixed + 32) { + return &c_status_invalid_params; + } + *pin = &m[fixed]; + pos += 32; + } + *host = NULL; + *host_len = 0; + *name = NULL; + *name_len = 0; + + int end = pos; + if (!start) { + while ((end < length) && (m[end] != 0)) { + end++; + } + *host = (const char *)&m[pos]; + *host_len = end - pos; + if ((*host_len < 1) || (*host_len > 253)) { + return &c_status_invalid_params; + } + if (end == length) { + return NULL; // host + } + pos = end + 1; // past the $00 + if (pos == length) { + return NULL; // host $00 + } + } else if ((length - pos == 1) && (m[pos] == 0)) { + return NULL; // a lone $00: no name + } + if (pos == length) { + return NULL; // START_TLS without a name + } + end = pos; + while ((end < length) && (m[end] != 0)) { + end++; + } + *name = (const char *)&m[pos]; + *name_len = end - pos; + if ((*name_len < 1) || (*name_len > 253)) { + return &c_status_invalid_params; + } + // After the name, at most its $00, as the very last byte. + if ((end < length) && (end != length - 1)) { + return &c_status_invalid_params; + } + return NULL; +} + +#if NET_TLS + +// Status texts carry numbers; the firmware's printf is not relied on for hex. +static char *put_text(char *p, const char *text) +{ + while (*text) { + *p++ = *text++; + } + *p = 0; + return p; +} + +static char *put_dec(char *p, int value) +{ + char digits[12]; + int n = 0; + uint32_t v = (value < 0) ? (uint32_t)(-(int64_t)value) : (uint32_t)value; + if (value < 0) { + *p++ = '-'; + } + do { + digits[n++] = '0' + (v % 10); + v /= 10; + } while (v); + while (n) { + *p++ = digits[--n]; + } + *p = 0; + return p; +} + +static char *put_hex(char *p, uint32_t value, int digits) +{ + static const char hex[] = "0123456789ABCDEF"; + p = put_text(p, "0x"); + for (int i = digits - 1; i >= 0; i--) { + *p++ = hex[(value >> (4 * i)) & 0xF]; + } + *p = 0; + return p; +} + +// An mbedTLS code, as -0x%04X in a status text. +static char *put_error(char *p, int error) +{ + if (error < 0) { + *p++ = '-'; + return put_hex(p, (uint32_t)(-(int64_t)error), 4); + } + return put_hex(p, (uint32_t)error, 4); +} + +// lwIP's own predicate for an IPv4 literal, which also takes 127.1 and +// 0x7f.0.0.1. +static bool is_ipv4_literal(const char *text, int length) +{ + char name[254]; + memcpy(name, text, length); + name[length] = 0; + ip4_addr_t address; + return ip4addr_aton(name, &address) != 0; +} + +static bool reached(uint32_t deadline) +{ + return (int32_t)(xTaskGetTickCount() - deadline) >= 0; +} + +static uint32_t tick_after(uint32_t ms) +{ + return xTaskGetTickCount() + pdMS_TO_TICKS(ms); +} + +static uint32_t earlier(uint32_t a, uint32_t b) +{ + return ((int32_t)(a - b) <= 0) ? a : b; +} + +// The waits stop for a C64 reset and for an abort of the command that runs. Both are noted by the UCI Server +// task for the worker: the command interface's own reset flag is cleared there at once, long before the worker +// looks, so it cannot be used. Cleanup (the CLOSE of a session that the command opened) stops for a reset only, +// so that an aborted OPEN still tells the module to free its session. +static NetworkTarget *tls_owner; + +// The cancel predicate of the module calls: the above, and a deadline for the waits that have one. +typedef struct { + bool use_deadline; + uint32_t deadline; + bool cleanup; +} tls_cancel_context_t; + +static bool reset_only(void) +{ + return tls_owner->reset_noted(); +} + +static bool reset_now(void) +{ + return tls_owner->reset_noted() || tls_owner->job_aborted(); +} + +static bool tls_cancelled(void *context) +{ + tls_cancel_context_t *c = (tls_cancel_context_t *)context; + if (c->cleanup ? reset_only() : reset_now()) { + return true; + } + return c->use_deadline && reached(c->deadline); +} + +TlsSocket *NetworkTarget :: tls_find(int socketnr) +{ + for (int i = 0; i < NET_MAX_TLS; i++) { + if (tls[i].used && (tls[i].socketnr == socketnr)) { + return &tls[i]; + } + } + return NULL; +} + +// A free entry, not yet in use; the slot on the module is its index. +TlsSocket *NetworkTarget :: tls_reserve(void) +{ + for (int i = 0; i < NET_MAX_TLS; i++) { + if (!tls[i].used) { + return &tls[i]; + } + } + return NULL; +} + +int NetworkTarget :: tls_in_use(bool unclaimed_only) +{ + int n = 0; + for (int i = 0; i < NET_MAX_TLS; i++) { + if (tls[i].used && (!unclaimed_only || !tls[i].claimed)) { + n++; + } + } + return n; +} + +uint16_t NetworkTarget :: tls_new_tag(void) +{ + if (++tls_last_tag == 0) { + tls_last_tag = 1; + } + return tls_last_tag; +} + +void NetworkTarget :: tls_new_ca_tag(void) +{ + if (++ca_tag == 0) { + ca_tag = 1; + } +} + +// A module restart ends every session it held, and its CA. +void NetworkTarget :: tls_check_generation(void) +{ + if (!wifi_tls_module_available()) { + return; + } + uint32_t now = wifi_tls_generation(); + if (!tls_generation_known) { + tls_generation_known = true; + tls_generation = now; + return; + } + if (now == tls_generation) { + return; + } + tls_generation = now; + for (int i = 0; i < NET_MAX_TLS; i++) { + TlsSocket *e = &tls[i]; + if (e->used) { + if (!e->failed) { + tls_fail(e, "17,TLS MODULE NOT RESPONDING"); + } + e->module_live = false; + } + } + ca_state = CA_EMPTY; + tls_new_ca_tag(); +} + +// Sticky: the entry answers text on every READ and WRITE until CLOSE, and +// plaintext not yet read is dropped. +void NetworkTarget :: tls_fail(TlsSocket *e, const char *text) +{ + e->failed = true; + strncpy(e->sticky, text, NET_TLS_STICKY_MAX - 1); + e->sticky[NET_TLS_STICKY_MAX - 1] = 0; + e->rx_len = 0; + e->rx_off = 0; + e->end = TLS_END_NONE; +} + +// 17. With cleanup, the session is closed on the module at once, since +// nothing says what it did with the last request. +void NetworkTarget :: tls_fail_module(TlsSocket *e, bool cleanup) +{ + tls_fail(e, "17,TLS MODULE NOT RESPONDING"); + if (!cleanup) { + e->module_live = false; + } else { + tls_cleanup_close(e); + } +} + +// A session that FAILED after its handshake: 14 for a fatal alert from the +// peer, 16 otherwise. The module has freed it. +void NetworkTarget :: tls_fail_step(TlsSocket *e, int esp_err, uint8_t alert_in) +{ + char text[NET_TLS_STICKY_MAX]; + if (alert_in != WIFI_TLS_ALERT_NONE) { + put_dec(put_text(text, "14,TLS ALERT RECEIVED: "), alert_in); + } else { + put_error(put_text(text, "16,TLS SESSION FAILED: "), esp_err); + } + e->module_live = false; + tls_fail(e, text); +} + +// CLOSE with the reset as its only cancel, bounded by CLOSE_RPC_MS; what the +// module answers is not sent. A module that no longer knows the session has +// freed it all the same. +void NetworkTarget :: tls_cleanup_close(TlsSocket *e) +{ + if (!e->module_live || reset_only()) { + return; + } + tls_cancel_context_t context = { false, 0, true }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + uint16_t notify_len; + int esp_err; + int result = wifi_tls_close(e->slot, e->tag, tls_ct_out, sizeof(tls_ct_out), ¬ify_len, &esp_err, + TLS_CLOSE_RPC_MS, &cancel); + if ((result == 0) || ((result == WIFI_TLS_REFUSED) && (esp_err == WIFI_TLS_ESP_NOT_FOUND))) { + e->module_live = false; + } +} + +// CLOSE_SOCKET, $25, and the end of a stream: the session on the module, its +// close_notify best effort, the socket, the entry. +void NetworkTarget :: tls_close_entry(TlsSocket *e, bool send_notify) +{ + if (e->module_live && !reset_only()) { + tls_cancel_context_t context = { false, 0, true }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + uint16_t notify_len = 0; + int esp_err; + int result = wifi_tls_close(e->slot, e->tag, tls_ct_out, sizeof(tls_ct_out), ¬ify_len, &esp_err, + TLS_CLOSE_RPC_MS, &cancel); + if ((result == 0) && send_notify && notify_len) { + tls_send_all(e->socketnr, tls_ct_out, notify_len, tick_after(TLS_NOTIFY_SEND_MS)); + } + } + untrack_socket(e->socketnr); + lwip_close(e->socketnr); + e->used = false; +} + +// One STEP, sent again while it could not be sent at all. +int NetworkTarget :: tls_run_step(TlsSocket *e, void *step, uint32_t deadline, bool use_deadline) +{ + tls_cancel_context_t context = { use_deadline, deadline }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + int result; + for (int i = 0; ; i++) { + result = wifi_tls_step(e->slot, e->tag, (wifi_tls_step_t *)step, TLS_STEP_RPC_MS, &cancel); + if ((result != WIFI_TLS_UNSENT) || (i == TLS_UNSENT_RETRIES) || tls_cancelled(&context)) { + break; + } + vTaskDelay(pdMS_TO_TICKS(TLS_UNSENT_DELAY_MS)); + } + return result; +} + +// Waits at most one slice, and never past until, for the socket to become +// readable (or writable). True when it did. +bool NetworkTarget :: tls_wait(int sock, bool for_write, uint32_t until) +{ + int32_t left = (int32_t)(until - xTaskGetTickCount()); + if (left <= 0) { + return false; + } + if (left > (int32_t)pdMS_TO_TICKS(TLS_SLICE_MS)) { + left = pdMS_TO_TICKS(TLS_SLICE_MS); + } + fd_set fds, errs; + FD_ZERO(&fds); + FD_ZERO(&errs); + FD_SET(sock, &fds); + FD_SET(sock, &errs); + struct timeval tv; + uint32_t us = (uint32_t)left * portTICK_PERIOD_MS * 1000; + tv.tv_sec = us / 1000000; + tv.tv_usec = us % 1000000; + int n = lwip_select(sock + 1, for_write ? NULL : &fds, for_write ? &fds : NULL, &errs, &tv); + return n > 0; +} + +// Sends all of it, polling a non-blocking socket, before SEND_MS and deadline. +// Returns 0, an errno (ETIMEDOUT at the deadline), or -1 on a reset. +int NetworkTarget :: tls_send_all(int sock, const uint8_t *data, int length, uint32_t deadline) +{ + uint32_t until = earlier(tick_after(TLS_SEND_MS), deadline); + while (length > 0) { + int sent = lwip_send(sock, data, length, MSG_DONTWAIT); + if (sent > 0) { + data += sent; + length -= sent; + continue; + } + if ((sent < 0) && (errno != EWOULDBLOCK) && (errno != EAGAIN)) { + return errno; + } + if (reset_now()) { + return -1; + } + if (reached(until)) { + return ETIMEDOUT; + } + tls_wait(sock, true, until); + } + return 0; +} + +// DNS inside OPEN_TLS: lwIP's callback resolver, polled. One slot, and a +// lookup is known by its sequence number, carried by value; a late answer to +// an abandoned lookup finds another number and writes nothing. +#define DNS_PENDING 0 +#define DNS_OK 1 +#define DNS_FAILED 2 +static struct { + uint32_t cur_seq; + ip_addr_t addr; + uint8_t state; +} tls_dns; + +static void tls_dns_found(const char *name, const ip_addr_t *ipaddr, void *arg) +{ + // On the tcpip thread, which holds the core lock. + if ((uint32_t)(uintptr_t)arg != tls_dns.cur_seq) { + return; + } + if (ipaddr) { + tls_dns.addr = *ipaddr; + tls_dns.state = DNS_OK; + } else { + tls_dns.state = DNS_FAILED; + } +} + +// 0 with the address, 84, or -1 on a reset. +int NetworkTarget :: tls_resolve(const char *host, uint32_t deadline, uint32_t *address) +{ + ip_addr_t found; + LOCK_TCPIP_CORE(); + uint32_t seq = ++tls_dns.cur_seq; + tls_dns.state = DNS_PENDING; + err_t err = dns_gethostbyname(host, &found, tls_dns_found, (void *)(uintptr_t)seq); + UNLOCK_TCPIP_CORE(); + if (err == ERR_OK) { + *address = ip4_addr_get_u32(ip_2_ip4(&found)); + return 0; + } + if (err != ERR_INPROGRESS) { + return 84; + } + while (true) { + LOCK_TCPIP_CORE(); + uint8_t state = tls_dns.state; + found = tls_dns.addr; + UNLOCK_TCPIP_CORE(); + if (state == DNS_OK) { + *address = ip4_addr_get_u32(ip_2_ip4(&found)); + return 0; + } + if (state == DNS_FAILED) { + return 84; + } + if (reset_now()) { + return -1; + } + int32_t left = (int32_t)(deadline - xTaskGetTickCount()); + if (left <= 0) { + return 84; + } + vTaskDelay((left > (int32_t)pdMS_TO_TICKS(TLS_SLICE_MS)) ? pdMS_TO_TICKS(TLS_SLICE_MS) : left); + } +} + +// A non-blocking connect, polled: lwIP answers EALREADY while it is under way +// and EISCONN once it is done. 0, an errno (ETIMEDOUT at the deadline), or -1 +// on a reset. +int NetworkTarget :: tls_connect(int sock, uint32_t address, uint16_t port, uint32_t deadline) +{ + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_len = sizeof(addr); + addr.sin_family = AF_INET; + addr.sin_port = PP_HTONS(port); + addr.sin_addr.s_addr = address; + while (lwip_connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + int error = errno; + if (error == EISCONN) { + return 0; + } + if ((error != EINPROGRESS) && (error != EALREADY)) { + return error; + } + if (reset_now()) { + return -1; + } + int32_t left = (int32_t)(deadline - xTaskGetTickCount()); + if (left <= 0) { + return ETIMEDOUT; + } + tls_wait(sock, true, deadline); + } + return 0; +} + +// What every TLS socket gets: non-blocking, TCP_NODELAY, and a send timeout, which also bounds lwIP's close when it +// has no memory for the FIN. OPEN_TLS sets them on its new socket; START_TLS only once steps 1-5 have passed, so +// that a kept code leaves the socket as it was. +static void tls_socket_options(int sock) +{ + int on = 1; + lwip_ioctl(sock, FIONBIO, &on); + lwip_setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)); + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = TLS_SNDTIMEO_MS * 1000; + lwip_setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); +} + +// Steps 2 to 5 of the refusal order: the module, the table, the CA, and the OPEN RPC, which starts a session on the +// module under (slot, tag). keep says whether START_TLS leaves the TCP socket as it was. NULL once the module holds +// the session. +Message *NetworkTarget :: tls_prepare(TlsSocket *e, uint8_t trust, uint8_t flags, const uint8_t *pin, + const char *name, int name_len, uint32_t total, bool *keep) +{ + *keep = true; + if (!wifi_tls_module_available()) { + return &c_status_tls_not_available; + } + if (!e) { + return &c_status_tls_in_use; + } + if ((trust == WIFI_TLS_TRUST_CUSTOM) && (ca_state != CA_LOADED)) { + return &c_status_tls_no_custom_ca; + } + memset(e, 0, offsetof(TlsSocket, rx)); // all but the buffers + e->slot = (uint8_t)(e - tls); + e->tag = tls_new_tag(); + e->trust = trust; + e->module_live = false; + + wifi_tls_open_t open; + open.trust = trust; + open.slot = e->slot; + open.tag = e->tag; + open.opts = flags & WIFI_TLS_OPT_REQUIRE_TLS13; + uint32_t now = sntp_utc_now(); + open.time_source = (now >= TLS_EARLIEST_TIME) ? WIFI_TLS_TIME_NIOS : WIFI_TLS_TIME_NONE; + open.unix_time = (now >= TLS_EARLIEST_TIME) ? now : 0; + open.ca_tag = (trust == WIFI_TLS_TRUST_CUSTOM) ? ca_tag : 0; + open.pin = (trust == WIFI_TLS_TRUST_PIN) ? pin : NULL; + open.sni = name; + open.sni_len = (uint8_t)name_len; + + tls_cancel_context_t context = { true, earlier(tick_after(TLS_OPEN_RPC_MS), total) }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + int esp_err; + uint8_t reason; + int result; + for (int i = 0; ; i++) { + result = wifi_tls_open(&open, TLS_OPEN_RPC_MS, &cancel, &esp_err, &reason); + if ((result != WIFI_TLS_UNSENT) || (i == TLS_UNSENT_RETRIES) || tls_cancelled(&context)) { + break; + } + vTaskDelay(pdMS_TO_TICKS(TLS_UNSENT_DELAY_MS)); + } + if (result == 0) { + e->module_live = true; + return NULL; + } + if (result == WIFI_TLS_NO_MODULE) { + return &c_status_tls_not_available; + } + if (result == WIFI_TLS_REFUSED) { + switch (reason) { + case WIFI_TLS_REASON_NO_ENTROPY: return &c_status_no_entropy; + case WIFI_TLS_REASON_NO_TIME: return &c_status_tls_no_time; + case WIFI_TLS_REASON_NO_CUSTOM_CA: return &c_status_tls_no_custom_ca; + default: break; + } + if (esp_err == WIFI_TLS_ESP_NOT_SUPPORTED) { + return &c_status_tls_not_available; // a module image without TLS + } + *keep = false; + return &c_status_tls_module; + } + // No answer, or not a well formed one: the module may hold the session + // all the same. The (slot, tag) takeover covers a CLOSE that is lost too. + *keep = false; + e->module_live = true; + tls_cleanup_close(e); + return &c_status_tls_module; +} + +// A handshake that FAILED, to its status code. +Message *NetworkTarget :: tls_classify(TlsSocket *e, void *step) +{ + wifi_tls_step_t *st = (wifi_tls_step_t *)step; + char text[64]; + uint32_t w = st->verify_flags; + bool pin = (e->trust == WIFI_TLS_TRUST_PIN); + switch (st->fail_reason) { + case WIFI_TLS_FAIL_NONE: + if (st->alert_in != WIFI_TLS_ALERT_NONE) { + put_dec(put_text(text, "14,TLS ALERT RECEIVED: "), st->alert_in); + } else { + put_error(put_text(text, "13,TLS HANDSHAKE FAILED: "), st->esp_err); + } + return set_status(text); + case WIFI_TLS_FAIL_VERSION_REFUSED: + put_hex(put_text(text, "18,TLS VERSION REFUSED: "), w & 0xFFFF, 4); + return set_status(text); + case WIFI_TLS_FAIL_DOWNGRADE: + return &c_status_tls_downgrade; + case WIFI_TLS_FAIL_NO_EMS: + return set_status("13,TLS HANDSHAKE FAILED: NO EMS"); + case WIFI_TLS_FAIL_CERT_VERIFY: + if ((w == 0xFFFFFFFF) || pin) { + put_hex(put_text(text, "93,CERTIFICATE NOT TRUSTED: "), w, 8); + } else if (w & 0x04) { // MBEDTLS_X509_BADCERT_CN_MISMATCH + put_hex(put_text(text, "94,CERTIFICATE NAME MISMATCH: "), w, 8); + } else if (w & (0x01 | 0x200)) { // BADCERT_EXPIRED, BADCERT_FUTURE + put_hex(put_text(text, "95,CERTIFICATE EXPIRED: "), w, 8); + } else { + put_hex(put_text(text, "93,CERTIFICATE NOT TRUSTED: "), w, 8); + } + return set_status(text); + case WIFI_TLS_FAIL_PIN_MISMATCH: + return pin ? &c_status_tls_pin_mismatch : &c_status_tls_module; + case WIFI_TLS_FAIL_PEER_CLOSED: + return set_status("13,TLS HANDSHAKE FAILED: PEER CLOSED"); + case WIFI_TLS_FAIL_NO_ENTROPY: + // The source went off after the OPEN. 87 is only ever answered with the TCP handle kept, and this ends it, so + // it is a handshake failure with a detail that names the cause. + return set_status("13,TLS HANDSHAKE FAILED: NO ENTROPY"); + default: + return &c_status_tls_module; + } +} + +// Step 8: the handshake, through to the STATS that the OPEN reply is made of. +// NULL when the session is ESTABLISHED; otherwise the code, and e->module_live +// says whether the module still holds the session. +Message *NetworkTarget :: tls_handshake(TlsSocket *e, uint32_t total) +{ + uint32_t started = xTaskGetTickCount(); + uint32_t deadline = earlier(tick_after(TLS_HANDSHAKE_MS), total); + char text[64]; + bool more = true; // the first step, with no input, makes the ClientHello + e->held_len = 0; + while (true) { + if (reset_now()) { + return &c_status_tls_module; + } + if (reached(deadline)) { + return &c_status_tls_hs_timeout; + } + if ((e->held_len == 0) && !more) { + if (!tls_wait(e->socketnr, false, deadline)) { + continue; + } + int n = lwip_recv(e->socketnr, e->held, NET_TLS_CT_MAX, MSG_DONTWAIT); + if (n == 0) { + return set_status("13,TLS HANDSHAKE FAILED: PEER CLOSED"); + } + if (n < 0) { + if ((errno == EWOULDBLOCK) || (errno == EAGAIN)) { + continue; + } + put_dec(put_text(text, "13,TLS HANDSHAKE FAILED: PEER RESET: "), errno); + return set_status(text); + } + e->held_len = n; + } + wifi_tls_step_t st; + memset(&st, 0, sizeof(st)); + st.ct_in = e->held; + st.ct_in_len = e->held_len; + st.ct_out = tls_ct_out; + st.ct_out_room = sizeof(tls_ct_out); + st.pt_out = tls_pt; + st.pt_out_room = sizeof(tls_pt); + int result = tls_run_step(e, &st, deadline, true); + if (reset_now()) { + return &c_status_tls_module; + } + if ((result != 0) && (result != WIFI_TLS_AGAIN)) { + if ((result == WIFI_TLS_REFUSED) && (st.esp_err == WIFI_TLS_ESP_NOT_FOUND)) { + e->module_live = false; + } + if ((result == WIFI_TLS_BUSY) && reached(deadline)) { + return &c_status_tls_hs_timeout; + } + return &c_status_tls_module; + } + if (result == 0) { + e->held_len = 0; + } + if (st.state == WIFI_TLS_FAILED || st.state == WIFI_TLS_CLOSED) { + e->module_live = false; + } + // Every ciphertext goes out before the next step, a failure's alert too. + if (st.ct_out_len) { + int error = tls_send_all(e->socketnr, tls_ct_out, st.ct_out_len, deadline); + if ((error != 0) && (st.state != WIFI_TLS_FAILED)) { + if (error < 0) { + return &c_status_tls_module; + } + if ((error == ETIMEDOUT) && reached(deadline)) { + return &c_status_tls_hs_timeout; + } + // Status 12 is for READ/WRITE only; a send that fails + // mid-handshake, by a reset or by SEND_MS (116), is a + // handshake failure. + put_dec(put_text(text, "13,TLS HANDSHAKE FAILED: SEND ERROR: "), error); + return set_status(text); + } + } + if (st.state == WIFI_TLS_FAILED) { + return tls_classify(e, &st); + } + if (st.state == WIFI_TLS_CLOSED) { + return set_status("13,TLS HANDSHAKE FAILED: PEER CLOSED"); + } + if (st.state == WIFI_TLS_ESTABLISHED) { + if (st.pt_out_len) { + memcpy(e->rx, tls_pt, st.pt_out_len); + e->rx_len = st.pt_out_len; + } + e->module_more = true; + break; + } + more = (st.ct_out_len != 0) || (result == WIFI_TLS_AGAIN); + } + + // What the reply reports is the module's, never guessed here. + tls_cancel_context_t context = { true, deadline }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + wifi_tls_stats_t stats; + int esp_err; + int result = wifi_tls_stats(e->slot, e->tag, &stats, &esp_err, TLS_STATS_RPC_MS, &cancel); + if ((result != 0) || (stats.group == 0)) { + if (!reset_now() && reached(deadline)) { + return &c_status_tls_hs_timeout; + } + return &c_status_tls_module; + } + e->version = stats.tls_version; + e->suite = stats.ciphersuite; + e->group = stats.group; + e->bits = stats.ems ? 0x01 : 0x00; + memcpy(e->spki, stats.spki_sha256, sizeof(e->spki)); + e->handshake_ms = (xTaskGetTickCount() - started) * portTICK_PERIOD_MS; + return NULL; +} + +void NetworkTarget :: tls_reply_open(TlsSocket *e, Message **reply) +{ + uint8_t *m = data_message.message; + m[0] = (uint8_t)e->socketnr; + m[1] = (uint8_t)e->version; + m[2] = (uint8_t)(e->version >> 8); + m[3] = (uint8_t)e->suite; + m[4] = (uint8_t)(e->suite >> 8); + m[5] = (uint8_t)e->group; + m[6] = (uint8_t)(e->group >> 8); + m[7] = e->bits; + data_message.length = 8; + data_message.last_part = true; + *reply = &data_message; +} + +// A failed OPEN or START: the entry stays free, and the session goes on the +// module unless the module ended it itself. +void NetworkTarget :: tls_abandon(TlsSocket *e) +{ + e->used = false; + tls_cleanup_close(e); +} + +void NetworkTarget :: open_tls(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + // No reply means nothing opened: an OPEN whose handle nobody reads + // could never be closed. + if (command->message[0] & CMD_IF_NO_REPLY) { + *status = &c_status_invalid_params; + return; + } + uint8_t trust, flags; + const uint8_t *pin; + const char *host, *name; + int host_len, name_len; + Message *refusal = tls_parse_open(command, 6, false, &trust, &flags, &pin, &host, &host_len, &name, + &name_len); + // The effective server name: the explicit one, else the host unless that + // is an IPv4 literal, else none. + bool host_literal = refusal ? false : is_ipv4_literal(host, host_len); + bool name_literal = (!refusal && name) ? is_ipv4_literal(name, name_len) : false; + if (!refusal && (trust <= WIFI_TLS_TRUST_CUSTOM)) { + if (name ? name_literal : host_literal) { + refusal = &c_status_invalid_params; // BUNDLE and CUSTOM check a name + } + } + if (!refusal) { + if (trust > WIFI_TLS_TRUST_PIN) { + refusal = &c_status_param_out_of_range; + } else if (flags & 0xFE) { + refusal = &c_status_param_out_of_range; + } else if (pin) { + int nonzero = 0; + for (int i = 0; i < 32; i++) { + nonzero |= pin[i]; + } + if (!nonzero) { + refusal = &c_status_param_out_of_range; + } + } + } + if (refusal) { + *status = refusal; + return; + } + const char *sni = name ? name : host; + int sni_len = name ? name_len : host_len; + if ((trust == WIFI_TLS_TRUST_PIN) && (name ? name_literal : host_literal)) { + sni = NULL; // an IPv4 literal never reaches SNI + sni_len = 0; + } + uint16_t port = uint16_t(command->message[2]) | (uint16_t(command->message[3]) << 8); + char hostname[254]; + memcpy(hostname, host, host_len); + hostname[host_len] = 0; + + uint32_t total = tick_after(TLS_OPEN_TOTAL_MS); + TlsSocket *e = tls_reserve(); + bool keep; + Message *failure = tls_prepare(e, trust, flags, pin, sni, sni_len, total, &keep); + if (failure) { + *status = failure; + return; + } + // From here on, every refusal closes the session just opened. + uint32_t address = 0; + int result = tls_resolve(hostname, earlier(tick_after(TLS_DNS_MS), total), &address); + if (result) { + *status = (result < 0) ? &c_status_tls_module : &c_status_host_not_resolvable; + tls_abandon(e); + return; + } + int sock = lwip_socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0) { + *status = &c_status_no_socket; + tls_abandon(e); + return; + } + if (sock > 255) { + lwip_close(sock); + *status = &c_status_internal_error; + tls_abandon(e); + return; + } + tls_socket_options(sock); + result = tls_connect(sock, address, port, earlier(tick_after(TLS_CONNECT_MS), total)); + if (result) { + lwip_close(sock); + if (result < 0) { + *status = &c_status_tls_module; + } else { + char text[40]; + put_dec(put_text(text, "11,ERROR ON CONNECT: "), result); + *status = set_status(text); + } + tls_abandon(e); + return; + } + e->socketnr = sock; + failure = tls_handshake(e, total); + if (failure || !track_socket(sock)) { + *status = failure ? failure : &c_status_no_socket; + lwip_close(sock); + tls_abandon(e); + return; + } + e->used = true; + e->claimed = false; + tls_reply_open(e, reply); + *status = &c_status_ok; +} + +void NetworkTarget :: start_tls(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if (command->message[0] & CMD_IF_NO_REPLY) { + *status = &c_status_invalid_params; + return; + } + // The handle first, before any other check: a TCP socket this target + // owns that is not TLS already. Every 81 here leaves it alone. + if (command->length < 3) { + *status = &c_status_invalid_params; + return; + } + int sock = command->message[2]; + int type = -1; + socklen_t type_len = sizeof(type); + if (!owns_socket(sock) || (lwip_getsockopt(sock, SOL_SOCKET, SO_TYPE, &type, &type_len) < 0) || + (type != SOCK_STREAM) || tls_find(sock)) { + *status = &c_status_invalid_params; + return; + } + uint8_t trust, flags; + const uint8_t *pin; + const char *host, *name; + int host_len, name_len; + Message *refusal = tls_parse_open(command, 5, true, &trust, &flags, &pin, &host, &host_len, &name, + &name_len); + bool name_literal = (!refusal && name) ? is_ipv4_literal(name, name_len) : false; + if (!refusal && (trust <= WIFI_TLS_TRUST_CUSTOM) && (!name || name_literal)) { + refusal = &c_status_invalid_params; + } + if (!refusal) { + if ((trust > WIFI_TLS_TRUST_PIN) || (flags & 0xFE)) { + refusal = &c_status_param_out_of_range; + } else if (pin) { + int nonzero = 0; + for (int i = 0; i < 32; i++) { + nonzero |= pin[i]; + } + if (!nonzero) { + refusal = &c_status_param_out_of_range; + } + } + } + if (refusal) { + *status = refusal; + return; + } + if (name_literal) { + name = NULL; // PIN: an IPv4 literal never reaches SNI + name_len = 0; + } + uint32_t total = tick_after(TLS_OPEN_TOTAL_MS); + TlsSocket *e = tls_reserve(); + bool keep; + Message *failure = tls_prepare(e, trust, flags, pin, name, name_len, total, &keep); + if (failure && keep) { + *status = failure; // nothing was sent: the TCP handle is as it was + return; + } + if (!failure) { + // Only now, so that a kept code leaves the socket truly unchanged. + tls_socket_options(sock); + e->socketnr = sock; + failure = tls_handshake(e, total); + } + if (failure) { + // Every other code ends the handle. + *status = failure; + untrack_socket(sock); + lwip_close(sock); + tls_abandon(e); + return; + } + e->used = true; + e->claimed = false; + tls_reply_open(e, reply); + *status = &c_status_ok; +} + +// $22: the Nios owns the CA state; the module gets the certificate once +// it is complete. +void NetworkTarget :: trust_ca(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if (command->length < 6) { + *status = &c_status_invalid_params; + return; + } + const uint8_t *m = command->message; + uint16_t offset = uint16_t(m[2]) | (uint16_t(m[3]) << 8); + uint16_t total = uint16_t(m[4]) | (uint16_t(m[5]) << 8); + int chunk = command->length - 6; + if (offset == 0) { + if (total == 0) { + if (chunk) { + *status = &c_status_invalid_params; + return; + } + ca_state = CA_EMPTY; // cleared + tls_new_ca_tag(); + *status = &c_status_ok; + return; + } + // Any start drops the installed CA at once, under a new tag. + ca_state = CA_EMPTY; + tls_new_ca_tag(); + if (total > NET_TLS_CA_MAX) { + *status = &c_status_param_out_of_range; + return; + } + ca_state = CA_UPLOADING; + ca_len = 0; + ca_total = total; + } else { + // Only offset 0 touches an installed CA; a sequence error drops an upload. + if (ca_state != CA_UPLOADING) { + *status = &c_status_invalid_params; + return; + } + if ((offset != ca_len) || (total != ca_total)) { + ca_state = CA_EMPTY; + *status = &c_status_invalid_params; + return; + } + } + if (ca_len + chunk > ca_total) { + ca_state = CA_EMPTY; + *status = &c_status_invalid_params; + return; + } + memcpy(&ca_buf[ca_len], &m[6], chunk); + ca_len += chunk; + if (ca_len < ca_total) { + *status = &c_status_ok; + return; + } + + // The final chunk. + ca_state = CA_EMPTY; + if (!wifi_tls_module_available()) { + *status = &c_status_tls_not_available; + return; + } + tls_cancel_context_t context = { false, 0 }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + int esp_err; + uint8_t reject; + int result; + for (int i = 0; ; i++) { + result = wifi_tls_set_ca(ca_buf, ca_len, ca_tag, &esp_err, &reject, TLS_OPEN_RPC_MS, &cancel); + if ((result != WIFI_TLS_UNSENT) || (i == TLS_UNSENT_RETRIES) || reset_now()) { + break; + } + vTaskDelay(pdMS_TO_TICKS(TLS_UNSENT_DELAY_MS)); + } + char text[64]; + if (result == 0) { + ca_state = CA_LOADED; + *status = &c_status_ok; + } else if (result == WIFI_TLS_NO_MODULE) { + *status = &c_status_tls_not_available; + } else if ((result == WIFI_TLS_REFUSED) && (esp_err == WIFI_TLS_ESP_NOT_SUPPORTED) && (reject == 0)) { + *status = &c_status_tls_not_available; + } else if ((result == WIFI_TLS_REFUSED) && (reject == WIFI_TLS_REJECT_NONE) && (esp_err <= -2)) { + put_error(put_text(text, "97,CUSTOM CA INVALID: "), esp_err); + *status = set_status(text); + } else if ((result == WIFI_TLS_REFUSED) && (reject == WIFI_TLS_REJECT_RSA_KEY_SHORT)) { + *status = set_status("97,CUSTOM CA REJECTED: RSA KEY < 2048"); + } else if ((result == WIFI_TLS_REFUSED) && (reject == WIFI_TLS_REJECT_CURVE)) { + *status = set_status("97,CUSTOM CA REJECTED: CURVE"); + } else if ((result == WIFI_TLS_REFUSED) && (reject == WIFI_TLS_REJECT_NOT_CA)) { + *status = set_status("97,CUSTOM CA REJECTED: NOT A CA"); + } else { + *status = &c_status_tls_module; + } + if (ca_state != CA_LOADED) { + tls_new_ca_tag(); // whatever the module holds can no longer match + } +} + +void NetworkTarget :: tls_info(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if (command->length != 3) { + *status = &c_status_invalid_params; + return; + } + uint8_t *m = data_message.message; + uint8_t handle = command->message[2]; + if (handle == 0xFF) { + memset(m, 0, 16); + m[0] = 1; + m[1] = NET_MAX_TLS; + m[2] = (uint8_t)tls_in_use(false); + m[3] = 0x07; // BUNDLE, CUSTOM, PIN + m[5] = 0x03; // TLS 1.2 (hardened), TLS 1.3 + uint32_t now = sntp_utc_now(); + uint8_t ready = (ca_state == CA_LOADED) ? 0x08 : 0x00; + if (now >= TLS_EARLIEST_TIME) { + ready |= 0x04; + } + if (wifi_tls_module_available()) { + uint16_t major, minor; + wifi_tls_module_version(&major, &minor); + m[6] = (uint8_t)major; + m[7] = (uint8_t)minor; + m[8] = (uint8_t)(minor >> 8); + uint32_t generation = wifi_tls_generation(); + if (info_valid && (info_generation != generation)) { + info_valid = false; // the module restarted + } + tls_cancel_context_t context = { false, 0 }; + wifi_tls_cancel_t cancel = { tls_cancelled, &context }; + wifi_tls_stats_t stats; + int esp_err; + int result = wifi_tls_stats(WIFI_TLS_SLOT_GLOBAL, 0, &stats, &esp_err, TLS_STATS_RPC_MS, &cancel); + if (result == 0) { + info_valid = true; + info_generation = generation; + info_ready = 0x01 | (stats.entropy_source ? 0x02 : 0) | (stats.time_source ? 0x04 : 0); + info_block_max_ms = stats.block_max_ms; + } else if ((result == WIFI_TLS_NO_MODULE) || + ((result == WIFI_TLS_REFUSED) && (esp_err == WIFI_TLS_ESP_NOT_SUPPORTED))) { + // No module application, or no TLS in it. Anything else (no + // answer, a full TLS queue's ESP_ERR_TIMEOUT, a bad answer) + // says the module is busy, and the last good STATS stands. + info_valid = false; + } + } else { + info_valid = false; + } + if (info_valid) { + ready |= info_ready; + m[12] = (uint8_t)info_block_max_ms; + m[13] = (uint8_t)(info_block_max_ms >> 8); + // The CA store date: no reply carries it, so "a bundle, date + // unknown". + m[9] = 0xFF; + m[10] = 0xFF; + m[11] = 0xFF; + } + m[4] = ready; + m[14] = (uint8_t)tls_in_use(true); + data_message.length = 16; + data_message.last_part = true; + *reply = &data_message; + *status = &c_status_ok; + return; + } + TlsSocket *e = tls_find(handle); + if (!e) { + *status = &c_status_invalid_params; + return; + } + memset(m, 0, 48); + m[0] = (uint8_t)e->version; + m[1] = (uint8_t)(e->version >> 8); + m[2] = (uint8_t)e->suite; + m[3] = (uint8_t)(e->suite >> 8); + m[4] = (uint8_t)e->group; + m[5] = (uint8_t)(e->group >> 8); + m[6] = e->trust; + m[7] = e->bits; + memcpy(&m[8], e->spki, 32); + m[40] = (uint8_t)e->handshake_ms; + m[41] = (uint8_t)(e->handshake_ms >> 8); + m[42] = (uint8_t)(e->handshake_ms >> 16); + m[43] = (uint8_t)(e->handshake_ms >> 24); + data_message.length = 48; + data_message.last_part = true; + *reply = &data_message; + *status = &c_status_ok; +} + +void NetworkTarget :: tls_release(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if (command->length != 2) { + *status = &c_status_invalid_params; + return; + } + int closed = 0; + for (int i = 0; i < NET_MAX_TLS; i++) { + if (tls[i].used && !tls[i].claimed) { + tls_close_entry(&tls[i], true); + closed++; + } + } + data_message.message[0] = (uint8_t)closed; + data_message.length = 1; + data_message.last_part = true; + *reply = &data_message; + *status = &c_status_ok; +} + +static void read_header(Message *m, uint16_t value) +{ + m->message[0] = (uint8_t)value; + m->message[1] = (uint8_t)(value >> 8); + m->length = 2; + m->last_part = true; +} + +// The end of a stream whose plaintext has all been read: $0000 and the +// status; the handle is gone after 01 and 05, and owned until CLOSE after a +// sticky failure. +void NetworkTarget :: tls_end(TlsSocket *e, Message **reply, Message **status) +{ + read_header(&data_message, 0); + *reply = &data_message; + char text[NET_TLS_STICKY_MAX]; + // A WRITE that reported the latched 12 fixes the end to that 12, also + // when the drain had found close_notify before it: the + // client was told to CLOSE, so the handle must still be its own. + if (e->write_saw_rx_err && (e->end != TLS_END_NONE)) { + e->end = TLS_END_RX_ERR; + } + if (e->end == TLS_END_RX_ERR) { + put_dec(put_text(text, "12,RECEIVE ERROR: "), e->rx_err); + tls_fail(e, text); + } + if (e->failed) { + *status = set_status(e->sticky); + return; + } + if (e->end == TLS_END_CLOSED) { + tls_close_entry(e, false); + *status = &c_status_socket_closed; + } else { + tls_close_entry(e, true); + *status = &c_status_tls_no_notify; + } +} + +// READ on a TLS handle: plaintext already received first; else +// steps, within READ_BUDGET, until one hands out plaintext or the stream +// ends. +void NetworkTarget :: tls_read(TlsSocket *e, uint32_t length, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if ((length == 0) || (length > NET_MAX_SOCKET_READ)) { + *status = &c_status_param_out_of_range; + return; + } + if (!e->failed && (e->rx_len == 0) && (e->end == TLS_END_NONE)) { + uint32_t deadline = tick_after(TLS_READ_TOTAL_MS); + uint32_t budget_end = tick_after(TLS_READ_BUDGET_MS); + int steps = 0; + while (!reset_now()) { + // Eager: top up the ciphertext before each step, unless the + // stream has ended or a receive error is latched. + if (!e->rx_err && !e->rx_fin && (e->held_len < NET_TLS_CT_MAX)) { + int n = lwip_recv(e->socketnr, e->held + e->held_len, NET_TLS_CT_MAX - e->held_len, MSG_DONTWAIT); + if (n > 0) { + e->held_len += n; + } else if (n == 0) { + e->rx_fin = true; + } else if ((errno != EWOULDBLOCK) && (errno != EAGAIN)) { + e->rx_err = errno; // the first one; no receive after it + } + } + bool draining = e->rx_err || e->rx_fin; + if ((e->held_len == 0) && !e->module_more && !draining) { + // Nothing to feed, and the module had nothing more to say. + uint32_t until = earlier(earlier(tick_after(TLS_READ_WAIT_MS), budget_end), deadline); + bool ready = false; + while (!ready && !reached(until) && !reset_now()) { + ready = tls_wait(e->socketnr, false, until); + } + if (!ready) { + break; + } + continue; + } + if ((steps >= TLS_READ_BUDGET_STEPS) || reached(budget_end) || reached(deadline)) { + break; + } + wifi_tls_step_t st; + memset(&st, 0, sizeof(st)); + st.ct_in = e->held; + st.ct_in_len = e->held_len; + st.ct_out = tls_ct_out; + st.ct_out_room = sizeof(tls_ct_out); + st.pt_out = tls_pt; + st.pt_out_room = sizeof(tls_pt); + uint16_t fed = e->held_len; + int result = tls_run_step(e, &st, deadline, true); + steps++; + if (reset_now()) { + break; + } + if ((result != 0) && (result != WIFI_TLS_AGAIN)) { + bool gone = (result == WIFI_TLS_REFUSED) && (st.esp_err == WIFI_TLS_ESP_NOT_FOUND); + tls_fail_module(e, !gone); + break; + } + if (result == 0) { + e->held_len = 0; + } + if (st.ct_out_len) { + int error = tls_send_all(e->socketnr, tls_ct_out, st.ct_out_len, deadline); + if (error < 0) { + break; + } + // After a receive error the peer is gone; its alert need not arrive. Nor need our close_notify + // after the peer's: it may have closed the TCP connection behind it. + if (error && !e->rx_err && (st.state != WIFI_TLS_FAILED) && (st.state != WIFI_TLS_CLOSED)) { + char text[NET_TLS_STICKY_MAX]; + put_dec(put_text(text, "12,SEND ERROR: "), error); + tls_fail(e, text); + break; + } + } + e->module_more = (st.ct_out_len != 0) || (st.pt_out_len != 0) || (result == WIFI_TLS_AGAIN); + if (st.state == WIFI_TLS_FAILED) { + e->module_live = false; + if (e->write_saw_rx_err) { + e->end = TLS_END_RX_ERR; // a WRITE already said 12; plaintext read so far stays + } else { + tls_fail_step(e, st.esp_err, st.alert_in); + } + break; + } + if (st.pt_out_len) { + memcpy(e->rx, tls_pt, st.pt_out_len); + e->rx_off = 0; + e->rx_len = st.pt_out_len; + } + if (st.state == WIFI_TLS_CLOSED) { + // close_notify wins over a latched receive error, unless a + // WRITE has reported that error already. + e->module_live = false; + e->module_more = false; + e->end = e->write_saw_rx_err ? TLS_END_RX_ERR : TLS_END_CLOSED; + break; + } + if (st.state != WIFI_TLS_ESTABLISHED) { + tls_fail_module(e, true); + break; + } + if (e->rx_len) { + e->quiet = 0; // plaintext: not a quiet step + break; + } + if (draining && (fed == 0)) { + // Two quiet input-less steps: the module holds nothing more. + if (++e->quiet >= 2) { + e->end = e->rx_err ? TLS_END_RX_ERR : TLS_END_NO_NOTIFY; + break; + } + } else { + e->quiet = 0; + } + } + } + if (e->rx_len) { + int n = (e->rx_len < length) ? e->rx_len : length; + memcpy(buffer, e->rx + e->rx_off, n); + e->rx_off += n; + e->rx_len -= n; + if (!e->rx_len) { + e->rx_off = 0; + } + read_header(&data_message, n); + start_read_reply(n, &c_status_ok, reply, status); + return; + } + if (e->failed || (e->end != TLS_END_NONE)) { + tls_end(e, reply, status); + return; + } + // Nothing yet: the same answer as an idle TCP read. + read_header(&data_message, 0xFFFF); + *reply = &data_message; + char text[24]; + put_dec(put_text(text, "02,NO DATA: "), EWOULDBLOCK); + *status = set_status(text); +} + +static void write_header(Message *m, Message **reply, uint16_t value) +{ + read_header(m, value); + *reply = m; +} + +// WRITE on a TLS handle: all of it, or a sticky failure. The steps take +// no ciphertext in and hand no plaintext out (NO_READ). +void NetworkTarget :: tls_write(TlsSocket *e, const uint8_t *data, int length, Message **reply, Message **status) +{ + char text[NET_TLS_STICKY_MAX]; + if (e->failed) { + write_header(&data_message, reply, 0xFFFF); + *status = set_status(e->sticky); + return; + } + if (e->rx_err) { + // Nothing is sent; the READs go on draining, and end in this 12. + e->write_saw_rx_err = true; + write_header(&data_message, reply, 0xFFFF); + put_dec(put_text(text, "12,RECEIVE ERROR: "), e->rx_err); + *status = set_status(text); + return; + } + if (!e->module_live) { + // The peer's close_notify ended the session on the module. + put_dec(put_text(text, "12,SEND ERROR: "), EPIPE); + tls_fail(e, text); + write_header(&data_message, reply, 0xFFFF); + *status = set_status(e->sticky); + return; + } + if (length == 0) { + write_header(&data_message, reply, 0); + *status = &c_status_ok; + return; + } + uint32_t deadline = tick_after(TLS_WRITE_TOTAL_MS); + int pending = length; + int steps = 0; + while (true) { + if (reset_now()) { + tls_fail(e, "17,TLS MODULE NOT RESPONDING"); + break; + } + if (steps >= TLS_WRITE_BUDGET) { + tls_fail_module(e, true); + break; + } + wifi_tls_step_t st; + memset(&st, 0, sizeof(st)); + st.flags = WIFI_TLS_STEP_NO_READ; + st.pt_in = data; + st.pt_in_len = pending; + st.ct_out = tls_ct_out; + st.ct_out_room = sizeof(tls_ct_out); + st.pt_out = tls_pt; + st.pt_out_room = sizeof(tls_pt); + int result = tls_run_step(e, &st, deadline, true); + steps++; + if (reset_now()) { + tls_fail(e, "17,TLS MODULE NOT RESPONDING"); + break; + } + if ((result != 0) && (result != WIFI_TLS_AGAIN)) { + bool gone = (result == WIFI_TLS_REFUSED) && (st.esp_err == WIFI_TLS_ESP_NOT_FOUND); + tls_fail_module(e, !gone); + break; + } + if (result == 0) { + pending = 0; + } + if (st.ct_out_len) { + int error = tls_send_all(e->socketnr, tls_ct_out, st.ct_out_len, deadline); + if (error) { + if (error < 0) { + tls_fail(e, "17,TLS MODULE NOT RESPONDING"); + } else { + put_dec(put_text(text, "12,SEND ERROR: "), error); + tls_fail(e, text); // the ciphertext may be torn + } + break; + } + } + if (st.state == WIFI_TLS_FAILED) { + tls_fail_step(e, st.esp_err, st.alert_in); + break; + } + if (st.state != WIFI_TLS_ESTABLISHED) { + tls_fail_module(e, st.state != WIFI_TLS_CLOSED); + break; + } + if ((pending == 0) && (st.ct_out_len == 0)) { + write_header(&data_message, reply, (uint16_t)length); + *status = &c_status_ok; + return; + } + } + write_header(&data_message, reply, 0xFFFF); + *status = set_status(e->sticky); +} + +void NetworkTarget :: tls_init(void) +{ + memset(tls, 0, sizeof(tls)); + tls_last_tag = 0; + tls_owner = this; + tls_generation_known = false; + tls_quick_seen = false; + tls_generation = 0; + ca_state = CA_EMPTY; + ca_tag = 0; + tls_new_ca_tag(); + ca_len = 0; + ca_total = 0; + info_valid = false; + info_generation = 0; + info_ready = 0; + info_block_max_ms = 0; +} + +void NetworkTarget :: tls_before_command(Message *command) +{ + // Every command claims every TLS session, so only the latest OPEN_TLS or START_TLS session can be unclaimed, + // and only until the next command. $25 (which frees an unclaimed session) and $23 $FF (which counts them) + // leave them as they are. + uint8_t code = (command->length >= 2) ? command->message[1] : 0; + bool keeps_claims = (code == NET_CMD_TLS_RELEASE) || + ((code == NET_CMD_TLS_INFO) && (command->length == 3) && (command->message[2] == 0xFF)); + tls_check_generation(); + // A socket-free command, or a queued one that was aborted before it started, set this on the other task. + portENTER_CRITICAL(); + bool other_task = tls_quick_seen; + tls_quick_seen = false; + portEXIT_CRITICAL(); + if (!keeps_claims || other_task) { + for (int i = 0; i < NET_MAX_TLS; i++) { + tls[i].claimed = true; + } + } + // A CA upload takes no other network command in between. + if (((code != NET_CMD_TLS_TRUST_CA) || other_task) && (ca_state == CA_UPLOADING)) { + ca_state = CA_EMPTY; + } +} + +void NetworkTarget :: tls_reset(void) +{ + // The sockets went with close_all_sockets. The sessions on the module go + // with CLOSE_ALL, and if that is lost, with the next OPEN of each slot; + // the CA with the new ca_tag, which the module's copy can never match. + for (int i = 0; i < NET_MAX_TLS; i++) { + tls[i].used = false; + } + ca_state = CA_EMPTY; + tls_new_ca_tag(); + if (wifi_tls_module_available()) { + int esp_err; + wifi_tls_close_all(&esp_err, TLS_CLOSE_ALL_RPC_MS); + } +} + +#else // !NET_TLS + +// Without the WiFi module the commands exist, and TLS is not available. +void NetworkTarget :: open_tls(Message *command, Message **reply, Message **status) +{ + uint8_t trust, flags; + const uint8_t *pin; + const char *host, *name; + int host_len, name_len; + *reply = &c_message_empty; + *status = tls_parse_open(command, 6, false, &trust, &flags, &pin, &host, &host_len, &name, &name_len); + if (!*status) { + *status = &c_status_tls_not_available; + } +} + +void NetworkTarget :: start_tls(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + *status = (command->length < 3) || !owns_socket(command->message[2]) ? &c_status_invalid_params + : &c_status_tls_not_available; +} + +void NetworkTarget :: trust_ca(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + *status = (command->length < 6) ? &c_status_invalid_params : &c_status_tls_not_available; +} + +void NetworkTarget :: tls_info(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if ((command->length != 3) || (command->message[2] != 0xFF)) { + *status = &c_status_invalid_params; + return; + } + uint8_t *m = data_message.message; + memset(m, 0, 16); + m[0] = 1; + m[1] = NET_MAX_TLS; + m[3] = 0x07; + m[5] = 0x03; + data_message.length = 16; + data_message.last_part = true; + *reply = &data_message; + *status = &c_status_ok; +} + +void NetworkTarget :: tls_release(Message *command, Message **reply, Message **status) +{ + *reply = &c_message_empty; + if (command->length != 2) { + *status = &c_status_invalid_params; + return; + } + data_message.message[0] = 0; + data_message.length = 1; + data_message.last_part = true; + *reply = &data_message; + *status = &c_status_ok; +} + +#endif // NET_TLS diff --git a/software/io/network/tests/Makefile b/software/io/network/tests/Makefile index b83afa7d2..4da48ccc3 100644 --- a/software/io/network/tests/Makefile +++ b/software/io/network/tests/Makefile @@ -190,7 +190,7 @@ timeout-pool-red: # Target 3 on its worker task, against loopback peers. network-target: mkdir -p $(OUTPUT_DIR) - $(CXX) $(NETWORK_TARGET_FLAGS) network_target_test.cpp ../network_target.cc -lpthread -o $(NETWORK_TARGET_TEST) \ + $(CXX) $(NETWORK_TARGET_FLAGS) network_target_test.cpp ../network_target.cc ../network_target_tls.cc -lpthread -o $(NETWORK_TARGET_TEST) \ -Wl,--wrap=gethostbyname_r -Wl,--wrap=send -Wl,--wrap=close env -u LD_PRELOAD timeout 60s $(NETWORK_TARGET_TEST) diff --git a/software/io/uart/dma_uart.cc b/software/io/uart/dma_uart.cc index 396ef4583..515a0e51e 100644 --- a/software/io/uart/dma_uart.cc +++ b/software/io/uart/dma_uart.cc @@ -113,11 +113,17 @@ void DmaUART::ModuleCtrl(uint8_t mode) void DmaUART::ClearRxBuffer(void) { + // No other task may run until the pool is refilled and the generation counts the reset, or it could free a + // buffer it held into the half filled pool, which the reset then fills with that buffer a second time. + // Nothing below blocks: queue resets and zero tick sends only. + vTaskSuspendAll(); // uart->ictrl = DMAUART_RxIRQ_DIS | DMAUART_TxIRQ_DIS |DMAUART_BufReq_DIS; // disable interrupts uart->flowctrl = uart->flowctrl | DMAUART_RESET; // reset pulse; will also disable interrupts xQueueGenericReset(rx_bufs, pdFALSE); uart->flowctrl = uart->flowctrl | DMAUART_RESET; // reset pulse; will also disable interrupts cmd_buffer_reset(packets); + generation++; // after the reset, so that any doubt ends in a leak, not a double free + xTaskResumeAll(); } int DmaUART::Read(uint8_t *buffer, int bufsize) diff --git a/software/io/uart/dma_uart.h b/software/io/uart/dma_uart.h index 0e6d180ec..3eb6fd27f 100644 --- a/software/io/uart/dma_uart.h +++ b/software/io/uart/dma_uart.h @@ -61,6 +61,9 @@ class DmaUART public: static uint8_t DmaUartInterrupt(void *context); bool txDebug; + // Counts the resets of the buffer pool. A buffer handed out before the + // last one has been put back in the pool by it, and is not to be freed. + volatile uint32_t generation; DmaUART(void *registers, int irq, void *sem, command_buf_context_t *pkts) { @@ -70,6 +73,7 @@ class DmaUART rxSemaphore = sem; slipMode = false; txDebug = false; + generation = 0; current_tx_buf = NULL; uint16_t rate = (((uint16_t)uart->rate_h) << 8) | uart->rate_l; uart->flowctrl = DMAUART_RESET; diff --git a/software/io/wifi/tests/Makefile b/software/io/wifi/tests/Makefile index 93f8941b0..64e794ba8 100644 --- a/software/io/wifi/tests/Makefile +++ b/software/io/wifi/tests/Makefile @@ -40,7 +40,7 @@ CASES := $(wildcard *_test.cpp) CXXFLAGS := -std=c++14 -g -O0 -Wall -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-switch \ -Wno-format -Wno-unknown-warning-option -Wno-mismatched-tags -Wno-deprecated-declarations \ -fno-access-control -DRISCV=1 $(if $(filter 0,$(U64)),,-DU64=$(U64)) \ - -I$(OUT) -Istubs -I. -I$(WIFI_DIR) -I$(UART) -I$(SW)/wifi/raw_u64/main + -I$(OUT) -Istubs -I. -I$(WIFI_DIR) -I$(UART) -I$(SW)/wifi/raw_u64/main -I$(SW)/wifi/common -I$(SW)/wifi/tls # Prints the function $(1) of file $(2), and stops when it is not there extract = out=$$(awk -v f="$(subst ~, ,$(1))" -f $(EXTRACT) $(2)); \ diff --git a/software/io/wifi/tests/wifi_task_env.h b/software/io/wifi/tests/wifi_task_env.h index 897a226c8..d992d65de 100644 --- a/software/io/wifi/tests/wifi_task_env.h +++ b/software/io/wifi/tests/wifi_task_env.h @@ -105,4 +105,7 @@ class U64Config { extern ultimate_ap_records_t wifi_aps; +// What wifi.cc keeps of the module's version, for the TLS calls +static __attribute__((unused)) uint16_t module_major, module_minor; + #endif /* WIFI_TASK_ENV_H_ */ diff --git a/software/io/wifi/wifi.cc b/software/io/wifi/wifi.cc index c1311cc80..db752a852 100644 --- a/software/io/wifi/wifi.cc +++ b/software/io/wifi/wifi.cc @@ -19,6 +19,8 @@ #include "u64_config.h" #endif #include "init_function.h" +#include "wifi_dedicated.h" +#include "wifi_tls.h" #define DEBUG_INPUT 0 #define EVENT_START 0xF1 @@ -26,6 +28,9 @@ WiFi wifi; ultimate_ap_records_t wifi_aps; +// What the module application said it is, for TLS_INFO; 0 before it answered. +static uint16_t module_major; +static uint16_t module_minor; InitFunction wifi_init("WiFi Application", WiFi::Init, NULL, NULL, 52); // after LWIP WiFi :: WiFi() @@ -302,13 +307,16 @@ void WiFi :: RunModeThread() case eWifi_ModuleDetected: uart->txDebug = false; if (wifi_detect(&major, &minor, moduleName, 32)) { + module_major = major; + module_minor = minor; state = eWifi_AppDetected; #if U64 == 2 memset(&voltages, 0, sizeof(voltages)); result = wifi_get_voltages(&voltages); printf("Result get voltages: %d %d %d %d %d %d %d %d\n", result, voltages.vbus, voltages.vaux, voltages.v50, voltages.v33, voltages.v18, voltages.v10, voltages.vusb); - if (voltages.vbus < 8500) { + // A module that has no reading to give says so; that is not a low voltage + if ((result == 0) && (voltages.vbus < 8500)) { UserInterface :: postMessage("Low input voltage."); } // These settings live in the module's NVS; keep them in sync. @@ -812,6 +820,26 @@ void wifi_free(void *driver, void *buffer) w->freeBuffer((command_buf_t *)buffer); } +#if U64 >= 1 +bool wifi_module_ready(void) +{ + return wifi.getState() >= eWifi_AppDetected; +} + +// The application answers while its radio is off too; the module then refuses +// an OPEN itself, for want of entropy. +bool wifi_tls_module_available(void) +{ + return wifi_module_ready(); +} + +void wifi_tls_module_version(uint16_t *major, uint16_t *minor) +{ + *major = module_major; + *minor = module_minor; +} +#endif + extern "C" { void print_uart_status() { diff --git a/software/io/wifi/wifi_cmd.cc b/software/io/wifi/wifi_cmd.cc index 517a134ab..54dfc19e9 100644 --- a/software/io/wifi/wifi_cmd.cc +++ b/software/io/wifi/wifi_cmd.cc @@ -2,8 +2,12 @@ #include "dump_hex.h" /// C like functions to 'talk' with the WiFi Module -static uint16_t sequence_nr = 0; +uint16_t sequence_nr = 0; static wifi_reply_slot_t replySlots[WIFI_REPLY_SLOTS]; +#if U64 >= 1 +QueueHandle_t dedicated_replies = NULL; +volatile bool dedicated_waiting = false; +#endif void hex(uint8_t h) { @@ -17,6 +21,16 @@ BaseType_t wifi_rx_isr(command_buf_context_t *context, command_buf_t *buf, BaseT rpc_header_t *hdr = (rpc_header_t *)buf->data; BaseType_t res; +#if U64 >= 1 + if (hdr->thread == WIFI_DEDICATED_THREAD) { + // pdFALSE makes the interrupt handler free the buffer. + if (!dedicated_waiting) { + return pdFALSE; + } + dedicated_reply_t reply = { buf, esp32.uart->generation }; + return xQueueSendFromISR(dedicated_replies, &reply, w); + } +#endif TaskHandle_t thread = (TaskHandle_t)wifi_reply_take(replySlots, hdr->thread, hdr->sequence); if (thread) { ioWrite8(UART_DATA, 'N'); @@ -82,6 +96,11 @@ void wifi_command_init(void) esp32.uart->FlowControl(true); esp32.uart->ClearRxBuffer(); esp32.uart->EnableSlip(true); +#if U64 >= 1 + if (!dedicated_replies) { + dedicated_replies = xQueueCreate(4, sizeof(dedicated_reply_t)); + } +#endif esp32.uart->SetReceiveCallback(wifi_rx_isr); esp32.uart->EnableIRQ(true); } diff --git a/software/io/wifi/wifi_cmd.h b/software/io/wifi/wifi_cmd.h index 7c215f294..17d9803a8 100644 --- a/software/io/wifi/wifi_cmd.h +++ b/software/io/wifi/wifi_cmd.h @@ -73,6 +73,22 @@ command_buf_t *wifi_wait_reply(rpc_header_t hdr, int timeout_ms); int wifi_set_recovery_url(const char *url); int wifi_get_recovery_url(char *url, int maxlen); +extern uint16_t sequence_nr; + +// wifi_dedicated_call's thread number, which no transmit buffer has. While +// dedicated_waiting is set, the receive interrupt queues its replies in +// dedicated_replies, tagged with the buffer generation; otherwise it drops them. +// Not a reply slot (0 to WIFI_REPLY_SLOTS - 1), not 0xFF (no reply wanted), and not 0xFD to 0xFF, which +// the HTTPS provider channels of CMD_IDENTIFY use (#936) +#define WIFI_DEDICATED_THREAD 0xFC +#if U64 >= 1 +typedef struct { + command_buf_t *buf; + uint32_t generation; +} dedicated_reply_t; +extern QueueHandle_t dedicated_replies; +extern volatile bool dedicated_waiting; +#endif extern "C" { void print_uart_status(); } extern const char *no_wifi_buf; extern const char *no_wifi_slot; diff --git a/software/io/wifi/wifi_connect.h b/software/io/wifi/wifi_connect.h index 644afb02a..6f8dfd5ad 100644 --- a/software/io/wifi/wifi_connect.h +++ b/software/io/wifi/wifi_connect.h @@ -54,7 +54,7 @@ static inline bool wifi_disconnect_is_radio_start(const void *pkt, int size) // Authentication or the 4-way handshake failed: the access point took the client // for one with the wrong key (WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT, _AUTH_FAIL, -// _HANDSHAKE_TIMEOUT; the same values in ESP-IDF 5.3.1 and 6.0.3) +// _HANDSHAKE_TIMEOUT; the same values in ESP-IDF 5.3.1, 6.0.3 and 6.1.1) static inline bool wifi_disconnect_is_password(uint8_t reason) { return reason == 15 || reason == 202 || reason == 204; diff --git a/software/io/wifi/wifi_dedicated.cc b/software/io/wifi/wifi_dedicated.cc new file mode 100644 index 000000000..2bed2b0e7 --- /dev/null +++ b/software/io/wifi/wifi_dedicated.cc @@ -0,0 +1,175 @@ +// wifi_dedicated.cc: the one waiter for replies on WIFI_DEDICATED_THREAD, and GET_RANDOM, its +// first user. Not in wifi_cmd.cc, which the updater compiles without wifi.cc. + +#include +#include "wifi_cmd.h" +#include "wifi_dedicated.h" +#include "wifi_tls.h" +#include "wifi_random.h" + +static_assert(WIFI_RANDOM_BUSY == DEDICATED_BUSY, "codes differ"); +static_assert(WIFI_RANDOM_NO_MODULE == DEDICATED_NO_MODULE, "codes differ"); +static_assert(WIFI_RANDOM_FOREIGN == DEDICATED_FOREIGN, "codes differ"); +// The log reads esp_err where every reply that has one keeps it. +static_assert(sizeof(rpc_espcmd_resp) == offsetof(rpc_get_random_resp, source), "rpc_espcmd_resp changed"); + +// Checks a queued reply against the request, lets take have it if it is the answer, and frees it. A reply queued +// before the last buffer pool reset is dropped unread: its buffer may since belong to someone else. The scheduler +// stays suspended from the check until the free, so no reset (only tasks do one) gets in between. check false: free. +static int take_dedicated_reply(const dedicated_call_t *call, dedicated_reply_t *reply, bool check, uint16_t sequence) +{ + int retval = DEDICATED_FOREIGN; + int size = 0; + int esp_err = 0; + vTaskSuspendAll(); + if (reply->generation == esp32.uart->generation) { + command_buf_t *packet = reply->buf; + if (check) { + size = packet->size; + if (size >= (int)sizeof(rpc_espcmd_resp)) { + esp_err = ((rpc_espcmd_resp *)packet->data)->esp_err; + } + retval = call->take(packet->data, size, sequence, call->context); + } + esp32.uart->FreeBuffer(packet); // does not block + } + xTaskResumeAll(); + if ((retval != 0) && (retval != DEDICATED_FOREIGN)) { + if (size >= (int)sizeof(rpc_espcmd_resp)) { + printf("%s failed (%d). Size: %d. Error: %d.\n", call->name, retval, size, esp_err); + } else { + printf("%s failed (%d). Size: %d.\n", call->name, retval, size); + } + } + return retval; +} + +// Unlike the calls in wifi_cmd.cc this neither waits for the module forever nor trusts what comes back: take decides +// what the answer is. Between calls dedicated_waiting is clear and dedicated_replies is empty, so no reply is left +// over for the next one. +int wifi_dedicated_call(const dedicated_call_t *call) +{ + // Without the module application nothing can answer, so fail at once + // rather than on a timeout. + if (!wifi_module_ready() || !dedicated_replies) { + return DEDICATED_NO_MODULE; + } + // One request at a time: a second caller fails rather than waits. + bool busy; + ENTER_SAFE_SECTION; + busy = dedicated_waiting; + dedicated_waiting = true; + LEAVE_SAFE_SECTION; + if (busy) { + return DEDICATED_UNSENT; + } + + int retval = DEDICATED_BUSY; + bool sent = false; + bool cancelled = false; + uint16_t sequence = sequence_nr++; + dedicated_reply_t reply; + command_buf_t *packet; + if (esp32.uart->GetBuffer(&packet, 4) == pdFALSE) { // 20 ms + printf(no_wifi_buf); + } else { + rpc_header_t *hdr = (rpc_header_t *)packet->data; + hdr->command = call->command; + hdr->sequence = sequence; + hdr->thread = WIFI_DEDICATED_THREAD; + packet->size = call->fill(packet->data, call->context); + + if (esp32.uart->TransmitPacket(packet) == pdTRUE) { + // A late reply to an earlier request is skipped, within the same + // timeout. + sent = true; + const TickType_t timeout = pdMS_TO_TICKS(call->timeout_ms); + const TickType_t slice = pdMS_TO_TICKS(DEDICATED_SLICE_MS); + TickType_t start = xTaskGetTickCount(); + retval = DEDICATED_FOREIGN; + while (retval == DEDICATED_FOREIGN) { + TickType_t spent = xTaskGetTickCount() - start; + if (spent >= timeout) { + retval = DEDICATED_BUSY; + break; + } + TickType_t wait = timeout - spent; + if (call->cancel && (wait > slice)) { + wait = slice; + } + if (xQueueReceive(dedicated_replies, &reply, wait) == pdFALSE) { + if (call->cancel && call->cancel(call->cancel_context)) { + cancelled = true; + retval = DEDICATED_BUSY; + break; + } + if (!call->cancel) { + retval = DEDICATED_BUSY; + break; + } + continue; + } + retval = take_dedicated_reply(call, &reply, true, sequence); + } + } + } + + // Stop the interrupt from queueing replies, then release what it queued. + // After a timeout that can still be our reply. + dedicated_waiting = false; + while (xQueueReceive(dedicated_replies, &reply, 0) == pdTRUE) { + if ((retval == DEDICATED_BUSY) && !cancelled) { + retval = take_dedicated_reply(call, &reply, true, sequence); + if (retval == DEDICATED_FOREIGN) { + retval = DEDICATED_BUSY; + } + } else { + take_dedicated_reply(call, &reply, false, 0); + } + } + if (cancelled) { + printf("%s: cancelled.\n", call->name); + } else if (retval == DEDICATED_BUSY) { + printf("%s: no reply.\n", call->name); + if (!sent) { + retval = DEDICATED_UNSENT; + } + } + return retval; +} + +uint32_t wifi_tls_generation(void) +{ + return esp32.uart->generation; +} + +typedef struct { + uint8_t *buf; + uint16_t len; +} random_call_t; + +static int fill_random(uint8_t *request, void *context) +{ + rpc_get_random_req *args = (rpc_get_random_req *)request; + args->length = ((random_call_t *)context)->len; + return sizeof(rpc_get_random_req); +} + +static int take_random(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + random_call_t *c = (random_call_t *)context; + return wifi_random_take_reply(reply, size, sequence, c->buf, c->len); +} + +// A C64 program is waiting on the UCI for this one. Bytes are only handed out +// when the reply is the answer to this request and carries all of them. +int wifi_get_random(uint8_t *buf, uint16_t len) +{ + random_call_t args = { buf, len }; + // About 1 ms on the wire; far longer only while the module's dispatcher is + // blocked handing a scan or connect to its connector, which is worth a retry. + const dedicated_call_t call = { "Get Random", CMD_GET_RANDOM, 200, fill_random, take_random, &args }; + int r = wifi_dedicated_call(&call); + // The channel was taken or there was no buffer: nothing was sent, which a caller of GET_RANDOM reads as busy + return (r == DEDICATED_UNSENT) ? WIFI_RANDOM_BUSY : r; +} diff --git a/software/io/wifi/wifi_dedicated.h b/software/io/wifi/wifi_dedicated.h new file mode 100644 index 000000000..581b0766c --- /dev/null +++ b/software/io/wifi/wifi_dedicated.h @@ -0,0 +1,45 @@ +// wifi_dedicated.h: requests to the WiFi module that do not trust it to answer, or to answer only them (the TLS +// calls). Replies come through their own queue, not the reply slots; the caller waits with a deadline, +// and one request is outstanding at a time. Free of rpc_calls.h and FreeRTOS, so it can be tested on the host. + +#ifndef WIFI_DEDICATED_H_ +#define WIFI_DEDICATED_H_ + +#include + +// What wifi_dedicated_call returns itself. Anything else comes from take. +// Callers keep their own numbers for these, and assert that they match. +#define DEDICATED_BUSY 1 // sent, but no answer in time; the module may still act on it +#define DEDICATED_NO_MODULE 4 // the module application is not running; nothing was sent +#define DEDICATED_FOREIGN 5 // from take only: not the answer to this request +#define DEDICATED_UNSENT 6 // another request was outstanding, or no buffer; nothing was sent + +typedef struct { + const char *name; // for the log + uint8_t command; // CMD_* + uint32_t timeout_ms; // for the answer, from the moment the request is queued + // Writes the request's arguments after its header, which is filled in + // already, and returns the size of the whole request. It may not fail, + // so the caller checks the arguments first. + int (*fill)(uint8_t *request, void *context); + // Checks the size bytes at reply as the answer to request sequence and takes what it needs; returns + // DEDICATED_FOREIGN for a reply that is not the answer, which is skipped. Runs with the scheduler suspended, + // so it may neither block nor print. + int (*take)(const uint8_t *reply, int size, uint16_t sequence, void *context); + void *context; + // Optional: the wait is cut into slices of at most DEDICATED_SLICE_MS and cancel is asked after each one that + // brought no answer; true ends the call with DEDICATED_BUSY, and a later answer is dropped by its sequence + // number. NULL waits the whole timeout in one go. + bool (*cancel)(void *cancel_context); + void *cancel_context; +} dedicated_call_t; + +#define DEDICATED_SLICE_MS 100 + +// Sends one request and waits for its answer. U64 == 1 and U64 == 2 (the Ultimate 64 Elite II and the C64 Ultimate) only. +int wifi_dedicated_call(const dedicated_call_t *call); + +// Whether the module application has been detected. In wifi.cc. +bool wifi_module_ready(void); + +#endif /* WIFI_DEDICATED_H_ */ diff --git a/software/io/wifi/wifi_random.cc b/software/io/wifi/wifi_random.cc new file mode 100644 index 000000000..68221acd7 --- /dev/null +++ b/software/io/wifi/wifi_random.cc @@ -0,0 +1,59 @@ +// wifi_random.cc: checks the WiFi module's answer to GET_RANDOM. Free of +// FreeRTOS and of the UART driver, so that the host test tests what ships. + +#include +#include +#include "rpc_calls.h" +#include "wifi_random.h" + +static_assert(WIFI_RANDOM_MAX_BYTES == RANDOM_MAX_BYTES, "the module's limit changed"); + +int wifi_random_take_reply(const uint8_t *reply, int size, uint16_t sequence, + uint8_t *buf, uint16_t len) +{ + const rpc_get_random_resp *result = (const rpc_get_random_resp *)reply; + const int with_error = offsetof(rpc_get_random_resp, source); + const int header = offsetof(rpc_get_random_resp, data); + + if ((size < (int)sizeof(rpc_header_t)) || (result->hdr.command != CMD_GET_RANDOM) || + (result->hdr.sequence != sequence)) { + return WIFI_RANDOM_FOREIGN; + } + if (size < with_error) { + return WIFI_RANDOM_INVALID; + } + // The module holds its entropy source for a moment: nothing was drawn, asking again is safe + if (result->esp_err == RPC_ERR_ENTROPY_BUSY) { + return WIFI_RANDOM_BUSY; + } + if (result->esp_err != 0) { + return WIFI_RANDOM_REFUSED; + } + if (size < header) { + return WIFI_RANDOM_INVALID; + } + // Bytes drawn without an entropy source are refused even when esp_err + // says OK. + if (result->source == ENTROPY_NONE) { + return WIFI_RANDOM_REFUSED; + } + if ((result->length != len) || (size < header + len)) { + return WIFI_RANDOM_INVALID; + } + memcpy(buf, result->data, len); + return 0; +} + +int wifi_random_status(int result) +{ + switch (result) { + case 0: + return 0; + case WIFI_RANDOM_BUSY: + return 88; + case WIFI_RANDOM_INVALID: + return 86; + default: + return 87; + } +} diff --git a/software/io/wifi/wifi_random.h b/software/io/wifi/wifi_random.h new file mode 100644 index 000000000..531217063 --- /dev/null +++ b/software/io/wifi/wifi_random.h @@ -0,0 +1,30 @@ +// wifi_random.h: hardware random bytes from the WiFi module. Apart from +// wifi_cmd.h, whose rpc_calls.h clashes with the command interface (CMD_IDENTIFY). + +#ifndef WIFI_RANDOM_H_ +#define WIFI_RANDOM_H_ + +#include + +// Fills buf with len bytes from the module's hardware random number generator +// and returns 0, or returns one of the codes below and leaves buf untouched. +// U64 == 1 and U64 == 2 (the Ultimate 64 Elite II and the C64 Ultimate) only. +int wifi_get_random(uint8_t *buf, uint16_t len); +#define WIFI_RANDOM_MAX_BYTES 512 // the module's RANDOM_MAX_BYTES, asserted in wifi_random.cc +#define WIFI_RANDOM_BUSY 1 // no answer in time; the module may be busy +#define WIFI_RANDOM_REFUSED 2 // the module refused, or had no entropy source +#define WIFI_RANDOM_INVALID 3 // the answer is not a well formed reply +#define WIFI_RANDOM_NO_MODULE 4 // the module application is not running + +// Checks size bytes at reply as the answer to request sequence for len bytes. +// Only a well formed answer of exactly len bytes from a real source returns 0 +// and copies the bytes to buf; nothing else touches buf. +int wifi_random_take_reply(const uint8_t *reply, int size, uint16_t sequence, + uint8_t *buf, uint16_t len); +#define WIFI_RANDOM_FOREIGN 5 // not the answer to this request + +// The UCI status for a result of wifi_get_random: 0 (the bytes go out) for 0 only, +// 88 (busy) for WIFI_RANDOM_BUSY, 86 (internal error) for WIFI_RANDOM_INVALID, 87 otherwise. +int wifi_random_status(int result); + +#endif /* WIFI_RANDOM_H_ */ diff --git a/software/io/wifi/wifi_tls.cc b/software/io/wifi/wifi_tls.cc new file mode 100644 index 000000000..f2a1344a8 --- /dev/null +++ b/software/io/wifi/wifi_tls.cc @@ -0,0 +1,565 @@ +// wifi_tls.cc: the TLS calls to the WiFi module, what goes into each request and what is taken from each answer. +// The waiting is wifi_dedicated_call's. Free of FreeRTOS calls, so that the checks can be tested on the host. + +#include +#include +#include "rpc_calls.h" // the module's own definitions of the TLS requests and answers +extern "C" { + #include "cmd_buffer.h" +} +#include "wifi_dedicated.h" +#include "wifi_tls.h" + +// The wire layouts of rpc_tls.h, byte for byte. +static_assert(sizeof(rpc_header_t) == 4, "rpc_header_t"); +static_assert(sizeof(rpc_espcmd_resp) == 8, "rpc_espcmd_resp"); +static_assert(offsetof(rpc_tls_open_req, trust) == 4, "open.trust"); +static_assert(offsetof(rpc_tls_open_req, sni_len) == 5, "open.sni_len"); +static_assert(offsetof(rpc_tls_open_req, slot) == 6, "open.slot"); +static_assert(offsetof(rpc_tls_open_req, time_source) == 7, "open.time_source"); +static_assert(offsetof(rpc_tls_open_req, unix_time) == 8, "open.unix_time"); +static_assert(offsetof(rpc_tls_open_req, tag) == 12, "open.tag"); +static_assert(offsetof(rpc_tls_open_req, opts) == 14, "open.opts"); +static_assert(offsetof(rpc_tls_open_req, reserved) == 15, "open.reserved"); +static_assert(offsetof(rpc_tls_open_req, ca_tag) == 16, "open.ca_tag"); +static_assert(offsetof(rpc_tls_open_req, reserved2) == 18, "open.reserved2"); +static_assert(offsetof(rpc_tls_open_req, pin) == 20, "open.pin"); +static_assert(offsetof(rpc_tls_open_req, sni) == 52, "open.sni"); +static_assert(sizeof(rpc_tls_open_req) == 52, "open size"); +static_assert(offsetof(rpc_tls_open_resp, esp_err) == 4, "open resp.esp_err"); +static_assert(offsetof(rpc_tls_open_resp, slot) == 8, "open resp.slot"); +static_assert(offsetof(rpc_tls_open_resp, reason) == 9, "open resp.reason"); +static_assert(offsetof(rpc_tls_open_resp, reserved) == 10, "open resp.reserved"); +static_assert(sizeof(rpc_tls_open_resp) == 12, "open resp size"); +static_assert(offsetof(rpc_tls_step_req, slot) == 4, "step.slot"); +static_assert(offsetof(rpc_tls_step_req, flags) == 5, "step.flags"); +static_assert(offsetof(rpc_tls_step_req, tag) == 6, "step.tag"); +static_assert(offsetof(rpc_tls_step_req, ct_in_len) == 8, "step.ct_in_len"); +static_assert(offsetof(rpc_tls_step_req, pt_in_len) == 10, "step.pt_in_len"); +static_assert(offsetof(rpc_tls_step_req, data) == 12, "step.data"); +static_assert(sizeof(rpc_tls_step_req) == 12, "step size"); +static_assert(offsetof(rpc_tls_step_resp, esp_err) == 4, "step resp.esp_err"); +static_assert(offsetof(rpc_tls_step_resp, state) == 8, "step resp.state"); +static_assert(offsetof(rpc_tls_step_resp, alert_in) == 9, "step resp.alert_in"); +static_assert(offsetof(rpc_tls_step_resp, ct_out_len) == 10, "step resp.ct_out_len"); +static_assert(offsetof(rpc_tls_step_resp, pt_out_len) == 12, "step resp.pt_out_len"); +static_assert(offsetof(rpc_tls_step_resp, alert_out) == 14, "step resp.alert_out"); +static_assert(offsetof(rpc_tls_step_resp, fail_reason) == 15, "step resp.fail_reason"); +static_assert(offsetof(rpc_tls_step_resp, verify_flags) == 16, "step resp.verify_flags"); +static_assert(offsetof(rpc_tls_step_resp, data) == 20, "step resp.data"); +static_assert(sizeof(rpc_tls_step_resp) == 20, "step resp size"); +static_assert(offsetof(rpc_tls_session_req, slot) == 4, "session.slot"); +static_assert(offsetof(rpc_tls_session_req, reserved) == 5, "session.reserved"); +static_assert(offsetof(rpc_tls_session_req, tag) == 6, "session.tag"); +static_assert(sizeof(rpc_tls_session_req) == 8, "session size"); +static_assert(offsetof(rpc_tls_close_resp, esp_err) == 4, "close resp.esp_err"); +static_assert(offsetof(rpc_tls_close_resp, ct_out_len) == 8, "close resp.ct_out_len"); +static_assert(offsetof(rpc_tls_close_resp, reserved) == 10, "close resp.reserved"); +static_assert(offsetof(rpc_tls_close_resp, data) == 12, "close resp.data"); +static_assert(sizeof(rpc_tls_close_resp) == 12, "close resp size"); +static_assert(offsetof(rpc_tls_stats_resp, esp_err) == 4, "stats.esp_err"); +static_assert(offsetof(rpc_tls_stats_resp, handshake_us) == 36, "stats.handshake_us"); +static_assert(offsetof(rpc_tls_stats_resp, tls_version) == 40, "stats.tls_version"); +static_assert(offsetof(rpc_tls_stats_resp, ciphersuite) == 42, "stats.ciphersuite"); +static_assert(offsetof(rpc_tls_stats_resp, group) == 44, "stats.group"); +static_assert(offsetof(rpc_tls_stats_resp, state) == 46, "stats.state"); +static_assert(offsetof(rpc_tls_stats_resp, sessions_open) == 47, "stats.sessions_open"); +static_assert(offsetof(rpc_tls_stats_resp, stack_free) == 48, "stats.stack_free"); +static_assert(offsetof(rpc_tls_stats_resp, esp_time) == 52, "stats.esp_time"); +static_assert(offsetof(rpc_tls_stats_resp, time_source) == 56, "stats.time_source"); +static_assert(offsetof(rpc_tls_stats_resp, entropy_source) == 57, "stats.entropy_source"); +static_assert(offsetof(rpc_tls_stats_resp, ems) == 58, "stats.ems"); +static_assert(offsetof(rpc_tls_stats_resp, reserved) == 59, "stats.reserved"); +static_assert(offsetof(rpc_tls_stats_resp, block_max_ms) == 60, "stats.block_max_ms"); +static_assert(offsetof(rpc_tls_stats_resp, reserved2) == 62, "stats.reserved2"); +static_assert(offsetof(rpc_tls_stats_resp, spki_sha256) == 64, "stats.spki_sha256"); +static_assert(sizeof(rpc_tls_stats_resp) == 96, "stats size"); +static_assert(offsetof(rpc_tls_set_ca_req, der_len) == 4, "set_ca.der_len"); +static_assert(offsetof(rpc_tls_set_ca_req, ca_tag) == 6, "set_ca.ca_tag"); +static_assert(offsetof(rpc_tls_set_ca_req, der) == 8, "set_ca.der"); +static_assert(sizeof(rpc_tls_set_ca_req) == 8, "set_ca size"); +static_assert(offsetof(rpc_tls_set_ca_resp, esp_err) == 4, "set_ca resp.esp_err"); +static_assert(offsetof(rpc_tls_set_ca_resp, reject) == 8, "set_ca resp.reject"); +static_assert(sizeof(rpc_tls_set_ca_resp) == 12, "set_ca resp size"); + +// A full step, either way, fits one buffer, and so do the longest OPEN and SET_CA. +static_assert(sizeof(rpc_tls_open_req) + TLS_SNI_MAX_LEN <= CMD_BUF_SIZE, "largest CMD_TLS_OPEN request"); +static_assert(sizeof(rpc_tls_step_req) + TLS_STEP_IN_MAX <= CMD_BUF_SIZE, "largest CMD_TLS_STEP request"); +static_assert(sizeof(rpc_tls_step_resp) + TLS_STEP_OUT_MAX <= CMD_BUF_SIZE, "largest CMD_TLS_STEP reply"); +static_assert(sizeof(rpc_tls_set_ca_req) + TLS_CA_MAX_LEN <= CMD_BUF_SIZE, "largest CMD_TLS_SET_CA request"); + +// What wifi_tls.h repeats. +static_assert(WIFI_TLS_MAX_SESSIONS == TLS_MAX_SESSIONS, "session caps differ"); +static_assert(WIFI_TLS_MAX_SNI == TLS_SNI_MAX_LEN, "name lengths differ"); +static_assert(WIFI_TLS_STEP_MAX_IN == TLS_STEP_IN_MAX, "step sizes differ"); +static_assert(WIFI_TLS_STEP_MAX_OUT == TLS_STEP_OUT_MAX, "step sizes differ"); +static_assert(WIFI_TLS_CA_MAX == TLS_CA_MAX_LEN, "CA sizes differ"); +static_assert(WIFI_TLS_PIN_LEN == TLS_PIN_LEN, "pin lengths differ"); +static_assert(WIFI_TLS_SLOT_GLOBAL == TLS_SLOT_GLOBAL, "slots differ"); +static_assert(WIFI_TLS_TRUST_BUNDLE == TLS_TRUST_BUNDLE, "trust modes differ"); +static_assert(WIFI_TLS_TRUST_CUSTOM == TLS_TRUST_CUSTOM, "trust modes differ"); +static_assert(WIFI_TLS_TRUST_PIN == TLS_TRUST_PIN, "trust modes differ"); +static_assert(WIFI_TLS_OPT_REQUIRE_TLS13 == TLS_OPT_REQUIRE_TLS13, "options differ"); +static_assert(WIFI_TLS_STEP_NO_READ == TLS_STEP_NO_READ, "step flags differ"); +static_assert(WIFI_TLS_REASON_NO_ENTROPY == TLS_OPEN_REASON_NO_ENTROPY, "reasons differ"); +static_assert(WIFI_TLS_REASON_NO_TIME == TLS_OPEN_REASON_NO_TIME, "reasons differ"); +static_assert(WIFI_TLS_REASON_NO_CUSTOM_CA == TLS_OPEN_REASON_NO_CUSTOM_CA, "reasons differ"); +static_assert(WIFI_TLS_TIME_NONE == TLS_TIME_NONE, "time sources differ"); +static_assert(WIFI_TLS_TIME_NIOS == TLS_TIME_NIOS, "time sources differ"); +static_assert(WIFI_TLS_FAIL_VERSION_REFUSED == TLS_FAIL_VERSION_REFUSED, "fail reasons differ"); +static_assert(WIFI_TLS_FAIL_DOWNGRADE == TLS_FAIL_DOWNGRADE, "fail reasons differ"); +static_assert(WIFI_TLS_FAIL_NO_EMS == TLS_FAIL_NO_EMS, "fail reasons differ"); +static_assert(WIFI_TLS_FAIL_CERT_VERIFY == TLS_FAIL_CERT_VERIFY, "fail reasons differ"); +static_assert(WIFI_TLS_FAIL_PIN_MISMATCH == TLS_FAIL_PIN_MISMATCH, "fail reasons differ"); +static_assert(WIFI_TLS_FAIL_PEER_CLOSED == TLS_FAIL_PEER_CLOSED, "fail reasons differ"); +static_assert(WIFI_TLS_FAIL_NO_ENTROPY == TLS_FAIL_NO_ENTROPY, "fail reasons differ"); +static_assert(WIFI_TLS_ALERT_NONE == TLS_ALERT_NONE, "alerts differ"); +static_assert(WIFI_TLS_REJECT_RSA_KEY_SHORT == TLS_CA_REJECT_RSA_KEY_SHORT, "rejects differ"); +static_assert(WIFI_TLS_REJECT_CURVE == TLS_CA_REJECT_CURVE, "rejects differ"); +static_assert(WIFI_TLS_REJECT_NOT_CA == TLS_CA_REJECT_NOT_CA, "rejects differ"); +static_assert(WIFI_TLS_HANDSHAKING == TLS_STATE_HANDSHAKING, "states differ"); +static_assert(WIFI_TLS_ESTABLISHED == TLS_STATE_ESTABLISHED, "states differ"); +static_assert(WIFI_TLS_CLOSED == TLS_STATE_CLOSED, "states differ"); +static_assert(WIFI_TLS_FAILED == TLS_STATE_FAILED, "states differ"); +static_assert(WIFI_TLS_BUSY == DEDICATED_BUSY, "codes differ"); +static_assert(WIFI_TLS_NO_MODULE == DEDICATED_NO_MODULE, "codes differ"); +static_assert(WIFI_TLS_FOREIGN == DEDICATED_FOREIGN, "codes differ"); +static_assert(WIFI_TLS_UNSENT == DEDICATED_UNSENT, "codes differ"); + +static bool is_answer(const uint8_t *reply, int size, uint8_t command, uint16_t sequence) +{ + const rpc_header_t *hdr = (const rpc_header_t *)reply; + return (size >= (int)sizeof(rpc_header_t)) && (hdr->command == command) && (hdr->sequence == sequence); +} + +// A bare rpc_espcmd_resp with an error: how the module refuses a command it +// does not know (ESP_ERR_NOT_SUPPORTED), or one it cannot start. +static bool bare_refusal(const uint8_t *reply, int size, int *esp_err) +{ + const rpc_espcmd_resp *result = (const rpc_espcmd_resp *)reply; + if ((size == (int)sizeof(rpc_espcmd_resp)) && (result->esp_err != 0)) { + *esp_err = result->esp_err; + return true; + } + return false; +} + +int wifi_tls_take_open(const uint8_t *reply, int size, uint16_t sequence, uint8_t slot, int *esp_err, + uint8_t *reason) +{ + const rpc_tls_open_resp *result = (const rpc_tls_open_resp *)reply; + if (!is_answer(reply, size, CMD_TLS_OPEN, sequence)) { + return WIFI_TLS_FOREIGN; + } + if (bare_refusal(reply, size, esp_err)) { + return WIFI_TLS_REFUSED; + } + if (size != (int)sizeof(rpc_tls_open_resp)) { + return WIFI_TLS_INVALID; + } + if (result->esp_err != 0) { + *esp_err = result->esp_err; + *reason = result->reason; + return WIFI_TLS_REFUSED; + } + // The module answers with the slot it opened (0xFF on a refusal). + if (result->slot != slot) { + return WIFI_TLS_INVALID; + } + return 0; +} + +int wifi_tls_take_step(const uint8_t *reply, int size, uint16_t sequence, wifi_tls_step_t *step) +{ + const rpc_tls_step_resp *result = (const rpc_tls_step_resp *)reply; + const int header = offsetof(rpc_tls_step_resp, data); + if (!is_answer(reply, size, CMD_TLS_STEP, sequence)) { + return WIFI_TLS_FOREIGN; + } + if (bare_refusal(reply, size, &step->esp_err)) { + return WIFI_TLS_REFUSED; + } + // Exactly the header and the bytes it counts, no more and no less. + if ((size < header) || (size != header + result->ct_out_len + result->pt_out_len)) { + return WIFI_TLS_INVALID; + } + bool has_state = result->state <= TLS_STATE_FAILED; + bool failed = has_state && (result->state == TLS_STATE_FAILED); + // Input refused for want of room, output all the same; in a live session the input goes again. Once the peer + // has closed the refusal no longer matters: the output, last plaintext included, is taken and CLOSED reported. + bool no_mem = has_state && (result->esp_err == WIFI_TLS_ESP_NO_MEM); + bool again = no_mem && ((result->state == TLS_STATE_HANDSHAKING) || (result->state == TLS_STATE_ESTABLISHED)); + bool closed = no_mem && (result->state == TLS_STATE_CLOSED); + if ((result->esp_err != 0) && !failed && !again && !closed) { + step->esp_err = result->esp_err; + if (has_state) { + step->state = result->state; + } + return WIFI_TLS_REFUSED; + } + if (!has_state) { + return WIFI_TLS_INVALID; + } + // The reasons come with FAILED only. + if (!failed && (result->fail_reason != TLS_FAIL_NONE)) { + return WIFI_TLS_INVALID; + } + uint16_t ct = result->ct_out_len; + uint16_t pt = result->pt_out_len; + if ((ct > step->ct_out_room) || (pt > step->pt_out_room)) { + return WIFI_TLS_INVALID; + } + // A step that was told not to read cannot have read anything. + if ((step->flags & WIFI_TLS_STEP_NO_READ) && (pt != 0)) { + return WIFI_TLS_INVALID; + } + // Plaintext only from a session that has finished its handshake. Records + // read before a failure were authentic, but they end a session that failed, + // and are withheld. + if (failed) { + pt = 0; + } else if ((pt != 0) && (result->state != TLS_STATE_ESTABLISHED) && (result->state != TLS_STATE_CLOSED)) { + return WIFI_TLS_INVALID; + } + memcpy(step->ct_out, result->data, ct); + memcpy(step->pt_out, result->data + ct, pt); + step->ct_out_len = ct; + step->pt_out_len = pt; + step->state = result->state; + step->esp_err = result->esp_err; + step->alert_in = result->alert_in; + step->alert_out = result->alert_out; + step->fail_reason = result->fail_reason; + step->verify_flags = result->verify_flags; + return again ? WIFI_TLS_AGAIN : 0; +} + +int wifi_tls_take_close(const uint8_t *reply, int size, uint16_t sequence, uint8_t *ct_out, uint16_t room, + uint16_t *ct_out_len, int *esp_err) +{ + const rpc_tls_close_resp *result = (const rpc_tls_close_resp *)reply; + const int header = offsetof(rpc_tls_close_resp, data); + if (!is_answer(reply, size, CMD_TLS_CLOSE, sequence)) { + return WIFI_TLS_FOREIGN; + } + if (bare_refusal(reply, size, esp_err)) { + return WIFI_TLS_REFUSED; + } + if ((size < header) || (size != header + result->ct_out_len)) { + return WIFI_TLS_INVALID; + } + if (result->esp_err != 0) { + *esp_err = result->esp_err; + return WIFI_TLS_REFUSED; + } + if (result->ct_out_len > room) { + return WIFI_TLS_INVALID; + } + memcpy(ct_out, result->data, result->ct_out_len); + *ct_out_len = result->ct_out_len; + return 0; +} + +int wifi_tls_take_stats(const uint8_t *reply, int size, uint16_t sequence, wifi_tls_stats_t *stats, int *esp_err) +{ + const rpc_tls_stats_resp *result = (const rpc_tls_stats_resp *)reply; + if (!is_answer(reply, size, CMD_TLS_STATS, sequence)) { + return WIFI_TLS_FOREIGN; + } + if (bare_refusal(reply, size, esp_err)) { + return WIFI_TLS_REFUSED; + } + if (size != (int)sizeof(rpc_tls_stats_resp)) { + return WIFI_TLS_INVALID; + } + if (result->esp_err != 0) { + *esp_err = result->esp_err; + return WIFI_TLS_REFUSED; + } + stats->heap_free = result->heap_free; + stats->heap_min_ever = result->heap_min; + stats->largest_block = result->largest_block; + stats->ct_in_bytes = result->ct_in_bytes; + stats->ct_out_bytes = result->ct_out_bytes; + stats->pt_in_bytes = result->pt_in_bytes; + stats->pt_out_bytes = result->pt_out_bytes; + stats->handshake_us = result->handshake_us; + stats->tls_version = result->tls_version; + stats->ciphersuite = result->ciphersuite; + stats->group = result->group; + stats->state = result->state; + stats->sessions_open = result->sessions_open; + stats->stack_free = result->stack_free; + stats->esp_time = result->esp_time; + stats->time_source = result->time_source; + stats->entropy_source = result->entropy_source; + stats->ems = result->ems; + stats->block_max_ms = result->block_max_ms; + memcpy(stats->spki_sha256, result->spki_sha256, sizeof(stats->spki_sha256)); + return 0; +} + +int wifi_tls_take_close_all(const uint8_t *reply, int size, uint16_t sequence, int *esp_err) +{ + const rpc_espcmd_resp *result = (const rpc_espcmd_resp *)reply; + if (!is_answer(reply, size, CMD_TLS_CLOSE_ALL, sequence)) { + return WIFI_TLS_FOREIGN; + } + if (size != (int)sizeof(rpc_espcmd_resp)) { + return WIFI_TLS_INVALID; + } + if (result->esp_err != 0) { + *esp_err = result->esp_err; + return WIFI_TLS_REFUSED; + } + return 0; +} + +// Three answers are well formed: loaded (0, no reject), a parse error (an mbedTLS or PSA code, never ESP_FAIL, no +// reject) and a refusal of a certificate that parsed (ESP_ERR_INVALID_ARG with reject 1, 3 or 4). Nothing else is. +int wifi_tls_take_set_ca(const uint8_t *reply, int size, uint16_t sequence, int *esp_err, uint8_t *reject) +{ + const rpc_tls_set_ca_resp *result = (const rpc_tls_set_ca_resp *)reply; + if (!is_answer(reply, size, CMD_TLS_SET_CA, sequence)) { + return WIFI_TLS_FOREIGN; + } + if (bare_refusal(reply, size, esp_err)) { + return WIFI_TLS_REFUSED; + } + if (size != (int)sizeof(rpc_tls_set_ca_resp)) { + return WIFI_TLS_INVALID; + } + int err = result->esp_err; + uint8_t why = result->reject; + if ((err == 0) && (why == TLS_CA_REJECT_NONE)) { + return 0; + } + bool parse_error = (err <= -2) && (why == TLS_CA_REJECT_NONE); + bool refused = (err == WIFI_TLS_ESP_INVALID_ARG) && + ((why == TLS_CA_REJECT_RSA_KEY_SHORT) || (why == TLS_CA_REJECT_CURVE) || + (why == TLS_CA_REJECT_NOT_CA)); + if (!parse_error && !refused) { + return WIFI_TLS_INVALID; + } + *esp_err = err; + *reject = why; + return WIFI_TLS_REFUSED; +} + +typedef struct { + const wifi_tls_open_t *open; + int *esp_err; + uint8_t *reason; +} open_call_t; + +static int fill_open(uint8_t *request, void *context) +{ + const wifi_tls_open_t *o = ((open_call_t *)context)->open; + rpc_tls_open_req *args = (rpc_tls_open_req *)request; + args->trust = o->trust; + args->sni_len = o->sni_len; + args->slot = o->slot; + args->time_source = o->time_source; + args->unix_time = o->unix_time; + args->tag = o->tag; + args->opts = o->opts; + args->reserved = 0; + args->ca_tag = o->ca_tag; + args->reserved2 = 0; + if (o->pin) { + memcpy(args->pin, o->pin, TLS_PIN_LEN); + } else { + memset(args->pin, 0, TLS_PIN_LEN); + } + if (o->sni_len) { + memcpy(args->sni, o->sni, o->sni_len); + } + return offsetof(rpc_tls_open_req, sni) + o->sni_len; +} + +static int take_open(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + open_call_t *c = (open_call_t *)context; + return wifi_tls_take_open(reply, size, sequence, c->open->slot, c->esp_err, c->reason); +} + +static void set_cancel(dedicated_call_t *call, const wifi_tls_cancel_t *cancel) +{ + call->cancel = cancel ? cancel->cancelled : NULL; + call->cancel_context = cancel ? cancel->context : NULL; +} + +int wifi_tls_open(const wifi_tls_open_t *open, uint32_t timeout_ms, const wifi_tls_cancel_t *cancel, int *esp_err, + uint8_t *reason) +{ + *esp_err = 0; + *reason = 0; + if ((open->sni_len > WIFI_TLS_MAX_SNI) || (open->sni_len && !open->sni)) { + return WIFI_TLS_TOO_LONG; + } + open_call_t args = { open, esp_err, reason }; + dedicated_call_t call = { "TLS Open", CMD_TLS_OPEN, timeout_ms, fill_open, take_open, &args, NULL, NULL }; + set_cancel(&call, cancel); + return wifi_dedicated_call(&call); +} + +typedef struct { + uint8_t slot; + uint16_t tag; + wifi_tls_step_t *step; +} step_call_t; + +static int fill_step(uint8_t *request, void *context) +{ + step_call_t *c = (step_call_t *)context; + wifi_tls_step_t *step = c->step; + rpc_tls_step_req *args = (rpc_tls_step_req *)request; + args->slot = c->slot; + args->flags = step->flags; + args->tag = c->tag; + args->ct_in_len = step->ct_in_len; + args->pt_in_len = step->pt_in_len; + // A step with no input of one kind passes a null pointer for it; memcpy takes none, even for 0 bytes. + if (step->ct_in_len) { + memcpy(args->data, step->ct_in, step->ct_in_len); + } + if (step->pt_in_len) { + memcpy(args->data + step->ct_in_len, step->pt_in, step->pt_in_len); + } + return offsetof(rpc_tls_step_req, data) + step->ct_in_len + step->pt_in_len; +} + +static int take_step(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + return wifi_tls_take_step(reply, size, sequence, ((step_call_t *)context)->step); +} + +int wifi_tls_step(uint8_t slot, uint16_t tag, wifi_tls_step_t *step, uint32_t timeout_ms, + const wifi_tls_cancel_t *cancel) +{ + step->ct_out_len = 0; + step->pt_out_len = 0; + step->state = WIFI_TLS_UNKNOWN; + step->esp_err = 0; + step->alert_in = WIFI_TLS_ALERT_NONE; + step->alert_out = WIFI_TLS_ALERT_NONE; + step->fail_reason = WIFI_TLS_FAIL_NONE; + step->verify_flags = 0; + if ((int)step->ct_in_len + step->pt_in_len > WIFI_TLS_STEP_MAX_IN) { + return WIFI_TLS_TOO_LONG; + } + step_call_t args = { slot, tag, step }; + dedicated_call_t call = { "TLS Step", CMD_TLS_STEP, timeout_ms, fill_step, take_step, &args, NULL, NULL }; + set_cancel(&call, cancel); + return wifi_dedicated_call(&call); +} + +typedef struct { + uint8_t slot; + uint16_t tag; + wifi_tls_stats_t *stats; + uint8_t *ct_out; + uint16_t room; + uint16_t *ct_out_len; + int *esp_err; +} session_call_t; + +// CLOSE and STATS carry the same argument. +static int fill_session(uint8_t *request, void *context) +{ + session_call_t *c = (session_call_t *)context; + rpc_tls_session_req *args = (rpc_tls_session_req *)request; + args->slot = c->slot; + args->reserved = 0; + args->tag = c->tag; + return sizeof(rpc_tls_session_req); +} + +static int take_close(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + session_call_t *c = (session_call_t *)context; + return wifi_tls_take_close(reply, size, sequence, c->ct_out, c->room, c->ct_out_len, c->esp_err); +} + +int wifi_tls_close(uint8_t slot, uint16_t tag, uint8_t *ct_out, uint16_t room, uint16_t *ct_out_len, int *esp_err, + uint32_t timeout_ms, const wifi_tls_cancel_t *cancel) +{ + *esp_err = 0; + *ct_out_len = 0; + session_call_t args = { slot, tag, NULL, ct_out, room, ct_out_len, esp_err }; + dedicated_call_t call = { "TLS Close", CMD_TLS_CLOSE, timeout_ms, fill_session, take_close, &args, NULL, NULL }; + set_cancel(&call, cancel); + return wifi_dedicated_call(&call); +} + +static int take_stats(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + session_call_t *c = (session_call_t *)context; + return wifi_tls_take_stats(reply, size, sequence, c->stats, c->esp_err); +} + +int wifi_tls_stats(uint8_t slot, uint16_t tag, wifi_tls_stats_t *stats, int *esp_err, uint32_t timeout_ms, + const wifi_tls_cancel_t *cancel) +{ + *esp_err = 0; + session_call_t args = { slot, tag, stats, NULL, 0, NULL, esp_err }; + dedicated_call_t call = { "TLS Stats", CMD_TLS_STATS, timeout_ms, fill_session, take_stats, &args, NULL, NULL }; + set_cancel(&call, cancel); + return wifi_dedicated_call(&call); +} + +static int fill_close_all(uint8_t *request, void *context) +{ + return sizeof(rpc_header_t); +} + +static int take_close_all(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + return wifi_tls_take_close_all(reply, size, sequence, (int *)context); +} + +int wifi_tls_close_all(int *esp_err, uint32_t timeout_ms) +{ + *esp_err = 0; + const dedicated_call_t call = { "TLS Close All", CMD_TLS_CLOSE_ALL, timeout_ms, fill_close_all, + take_close_all, esp_err, NULL, NULL }; + return wifi_dedicated_call(&call); +} + +typedef struct { + const uint8_t *der; + uint16_t der_len; + uint16_t ca_tag; + int *esp_err; + uint8_t *reject; +} set_ca_call_t; + +static int fill_set_ca(uint8_t *request, void *context) +{ + set_ca_call_t *c = (set_ca_call_t *)context; + rpc_tls_set_ca_req *args = (rpc_tls_set_ca_req *)request; + args->der_len = c->der_len; + args->ca_tag = c->ca_tag; + memcpy(args->der, c->der, c->der_len); + return offsetof(rpc_tls_set_ca_req, der) + c->der_len; +} + +static int take_set_ca(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + set_ca_call_t *c = (set_ca_call_t *)context; + return wifi_tls_take_set_ca(reply, size, sequence, c->esp_err, c->reject); +} + +int wifi_tls_set_ca(const uint8_t *der, uint16_t der_len, uint16_t ca_tag, int *esp_err, uint8_t *reject, + uint32_t timeout_ms, const wifi_tls_cancel_t *cancel) +{ + *esp_err = 0; + *reject = 0; + if (der_len > WIFI_TLS_CA_MAX) { + return WIFI_TLS_TOO_LONG; + } + set_ca_call_t args = { der, der_len, ca_tag, esp_err, reject }; + dedicated_call_t call = { "TLS Set CA", CMD_TLS_SET_CA, timeout_ms, fill_set_ca, take_set_ca, &args, NULL, NULL }; + set_cancel(&call, cancel); + return wifi_dedicated_call(&call); +} diff --git a/software/io/wifi/wifi_tls.h b/software/io/wifi/wifi_tls.h new file mode 100644 index 000000000..2ef524676 --- /dev/null +++ b/software/io/wifi/wifi_tls.h @@ -0,0 +1,180 @@ +// wifi_tls.h: TLS sessions run on the WiFi module (U64 only). It holds the keys and runs the protocol; this side moves +// the ciphertext between a socket and the module, one step at a time, and the module never speaks unasked. Apart +// from wifi_cmd.h; wifi_tls.cc asserts the values repeated here match rpc_tls.h's layout. + +#ifndef WIFI_TLS_H_ +#define WIFI_TLS_H_ + +#include + +#define WIFI_TLS_MAX_SESSIONS 2 // the module's cap +#define WIFI_TLS_MAX_SNI 253 +#define WIFI_TLS_STEP_MAX_IN 1536 // ct_in_len + pt_in_len in one step +#define WIFI_TLS_STEP_MAX_OUT 1024 // ct_out_len + pt_out_len in one step +#define WIFI_TLS_CA_MAX 1472 // one DER certificate for SET_CA +#define WIFI_TLS_PIN_LEN 32 +#define WIFI_TLS_SLOT_GLOBAL 0xFF // for wifi_tls_stats: the module as a whole, with tag 0 + +#define WIFI_TLS_TRUST_BUNDLE 0 +#define WIFI_TLS_TRUST_CUSTOM 1 +#define WIFI_TLS_TRUST_PIN 2 + +#define WIFI_TLS_OPT_REQUIRE_TLS13 0x01 // offer TLS 1.3 only +#define WIFI_TLS_STEP_NO_READ 0x01 // the module takes no plaintext out of the session in this step + +// Why an OPEN was refused. +#define WIFI_TLS_REASON_NO_ENTROPY 1 // no entropy source is on, so there is no seed +#define WIFI_TLS_REASON_NO_TIME 2 // BUNDLE or CUSTOM, and neither side has a trustworthy clock +#define WIFI_TLS_REASON_NO_CUSTOM_CA 3 // CUSTOM, and the module holds no CA under the given ca_tag + +// Where the time in an OPEN came from. +#define WIFI_TLS_TIME_NONE 0 +#define WIFI_TLS_TIME_NIOS 1 // SNTP on this side + +#define WIFI_TLS_HANDSHAKING 0 +#define WIFI_TLS_ESTABLISHED 1 +#define WIFI_TLS_CLOSED 2 +#define WIFI_TLS_FAILED 3 // esp_err holds the mbedTLS error, fail_reason says more +#define WIFI_TLS_UNKNOWN 0xFF // the answer did not say + +// Why a step FAILED, besides esp_err. +#define WIFI_TLS_FAIL_NONE 0 // generic: esp_err has the mbedTLS code, alert_in any alert +#define WIFI_TLS_FAIL_VERSION_REFUSED 1 // the version chosen is in verify_flags' low 16 bits +#define WIFI_TLS_FAIL_DOWNGRADE 2 +#define WIFI_TLS_FAIL_NO_EMS 3 +#define WIFI_TLS_FAIL_CERT_VERIFY 4 // verify_flags is the final verify result +#define WIFI_TLS_FAIL_PIN_MISMATCH 5 +#define WIFI_TLS_FAIL_PEER_CLOSED 6 +#define WIFI_TLS_FAIL_NO_ENTROPY 7 // a draw found no entropy source mid-handshake: status 13, ": NO ENTROPY" + +#define WIFI_TLS_ALERT_NONE 0xFF + +// Why SET_CA refused a certificate that parsed. +#define WIFI_TLS_REJECT_NONE 0 +#define WIFI_TLS_REJECT_RSA_KEY_SHORT 1 +#define WIFI_TLS_REJECT_CURVE 3 +#define WIFI_TLS_REJECT_NOT_CA 4 + +// esp_err values the callers tell apart (esp_err.h). +#define WIFI_TLS_ESP_FAIL (-1) +#define WIFI_TLS_ESP_NO_MEM 0x101 +#define WIFI_TLS_ESP_INVALID_ARG 0x102 +#define WIFI_TLS_ESP_INVALID_STATE 0x103 +#define WIFI_TLS_ESP_NOT_FOUND 0x105 +#define WIFI_TLS_ESP_NOT_SUPPORTED 0x106 + +// What the calls below return besides 0. +#define WIFI_TLS_BUSY 1 // sent, but no answer in time, or cancelled; the module may still act on it +#define WIFI_TLS_REFUSED 2 // the module answered with an error, which is in esp_err +#define WIFI_TLS_INVALID 3 // the answer is not a well formed reply +#define WIFI_TLS_NO_MODULE 4 // the module application is not running; nothing was sent +#define WIFI_TLS_FOREIGN 5 // (from the checks only) not the answer to this request +#define WIFI_TLS_UNSENT 6 // another request was outstanding, or no buffer; nothing was sent +#define WIFI_TLS_TOO_LONG 7 // the request does not fit; nothing was sent +#define WIFI_TLS_AGAIN 8 // STEP only: the module had no room and did not take the input, but its + // output is handed over as for 0; send the same input again + +// Polled between the slices of a wait; true ends the wait with BUSY. NULL +// for no cancelling. +typedef struct { + bool (*cancelled)(void *context); + void *context; +} wifi_tls_cancel_t; + +typedef struct { + uint8_t trust; // WIFI_TLS_TRUST_* + uint8_t slot; // 0 .. WIFI_TLS_MAX_SESSIONS - 1 + uint16_t tag; // never 0; names the session together with slot + uint8_t opts; // WIFI_TLS_OPT_* + uint8_t time_source; // WIFI_TLS_TIME_* + uint32_t unix_time; // UTC seconds, 0 without a time source + uint16_t ca_tag; // CUSTOM: the CA the module must hold; 0 otherwise + const uint8_t *pin; // PIN: WIFI_TLS_PIN_LEN bytes; NULL otherwise (sent as zeros) + const char *sni; // the server name, or NULL for none + uint8_t sni_len; +} wifi_tls_open_t; + +typedef struct { + uint32_t heap_free; + uint32_t heap_min_ever; + uint32_t largest_block; + uint32_t ct_in_bytes; // the session's counters; 0 for the module as a whole + uint32_t ct_out_bytes; + uint32_t pt_in_bytes; + uint32_t pt_out_bytes; + uint32_t handshake_us; + uint16_t tls_version; // as on the wire: 0x0304 is TLS 1.3 + uint16_t ciphersuite; // IANA number + uint16_t group; // IANA NamedGroup + uint8_t state; + uint8_t sessions_open; + uint32_t stack_free; + uint32_t esp_time; + uint8_t time_source; + uint8_t entropy_source; // 0: no live entropy source + uint8_t ems; // 1: extended master secret in use + uint16_t block_max_ms; // the longest the module's dispatcher was blocked since boot + uint8_t spki_sha256[32]; // of the leaf's SubjectPublicKeyInfo, digest order +} wifi_tls_stats_t; + +// One step; the module answers into the second block. Input is taken all or nothing: no room is AGAIN with the output +// handed over and the same input to resend (0 and CLOSED if the peer closed). FAILED is an answer (0, reasons set, +// session freed). Outputs only on 0/AGAIN; plaintext only from ESTABLISHED or just CLOSED; with NO_READ it is invalid. +typedef struct { + uint8_t flags; // WIFI_TLS_STEP_* + const uint8_t *ct_in; + uint16_t ct_in_len; + const uint8_t *pt_in; + uint16_t pt_in_len; + uint8_t *ct_out; + uint16_t ct_out_room; + uint8_t *pt_out; + uint16_t pt_out_room; + + uint16_t ct_out_len; + uint16_t pt_out_len; + uint8_t state; // WIFI_TLS_HANDSHAKING .. WIFI_TLS_FAILED, or WIFI_TLS_UNKNOWN + int esp_err; + uint8_t alert_in; // WIFI_TLS_ALERT_NONE when none + uint8_t alert_out; + uint8_t fail_reason; // WIFI_TLS_FAIL_* + uint32_t verify_flags; +} wifi_tls_step_t; + +// Each returns 0 or a code above after at most timeout_ms, or BUSY earlier when cancel says so. esp_err (where there +// is one), reason and reject are set to 0 first, then to what the module answered when it failed or refused. +int wifi_tls_open(const wifi_tls_open_t *open, uint32_t timeout_ms, const wifi_tls_cancel_t *cancel, int *esp_err, + uint8_t *reason); +int wifi_tls_step(uint8_t slot, uint16_t tag, wifi_tls_step_t *step, uint32_t timeout_ms, + const wifi_tls_cancel_t *cancel); +// ct_out receives the close_notify record, at most room bytes; *ct_out_len is 0 without one. +int wifi_tls_close(uint8_t slot, uint16_t tag, uint8_t *ct_out, uint16_t room, uint16_t *ct_out_len, int *esp_err, + uint32_t timeout_ms, const wifi_tls_cancel_t *cancel); +int wifi_tls_stats(uint8_t slot, uint16_t tag, wifi_tls_stats_t *stats, int *esp_err, uint32_t timeout_ms, + const wifi_tls_cancel_t *cancel); +int wifi_tls_close_all(int *esp_err, uint32_t timeout_ms); +int wifi_tls_set_ca(const uint8_t *der, uint16_t der_len, uint16_t ca_tag, int *esp_err, uint8_t *reject, + uint32_t timeout_ms, const wifi_tls_cancel_t *cancel); + +// The answer checks, apart for host tests. Exact sizes: OPEN 12, CLOSE 12 + record, STATS 96, CLOSE_ALL 8, SET_CA 12, +// STEP 20 + its bytes; a refusal may be a bare 8-byte rpc_espcmd_resp (no TLS: NOT_SUPPORTED). Each returns 0, +// WIFI_TLS_FOREIGN, REFUSED or INVALID (or AGAIN for a step). OPEN's answer must name the slot asked for. +int wifi_tls_take_open(const uint8_t *reply, int size, uint16_t sequence, uint8_t slot, int *esp_err, + uint8_t *reason); +int wifi_tls_take_step(const uint8_t *reply, int size, uint16_t sequence, wifi_tls_step_t *step); +int wifi_tls_take_close(const uint8_t *reply, int size, uint16_t sequence, uint8_t *ct_out, uint16_t room, + uint16_t *ct_out_len, int *esp_err); +int wifi_tls_take_stats(const uint8_t *reply, int size, uint16_t sequence, wifi_tls_stats_t *stats, int *esp_err); +int wifi_tls_take_close_all(const uint8_t *reply, int size, uint16_t sequence, int *esp_err); +int wifi_tls_take_set_ca(const uint8_t *reply, int size, uint16_t sequence, int *esp_err, uint8_t *reject); + +// The UART buffer generation, which changes when the module restarts: every +// session it held is then gone. In wifi_dedicated.cc. +uint32_t wifi_tls_generation(void); + +// Whether TLS calls can be sent at all (the module application runs and WiFi +// is not disabled), and the version the module reported. In wifi.cc. +bool wifi_tls_module_available(void); +void wifi_tls_module_version(uint16_t *major, uint16_t *minor); + +#endif /* WIFI_TLS_H_ */ diff --git a/software/network/sntp_time.cc b/software/network/sntp_time.cc index 51600aaa9..ebc84a1a7 100644 --- a/software/network/sntp_time.cc +++ b/software/network/sntp_time.cc @@ -4,6 +4,14 @@ #include #include "network_config.h" #include "rtc.h" +#include "FreeRTOS.h" +#include "task.h" +#include "itu.h" +#include "sntp_time.h" + +// The last time SNTP gave, UTC, and the tick it came at; 0 before the first. +static uint32_t sntp_seconds; +static TickType_t sntp_tick; extern "C" { #include "lwip/apps/sntp.h" @@ -11,10 +19,28 @@ extern "C" { void sntp_time_received(uint32_t sec) { printf("--> Time Received: %u (current TZ = %s)\n", sec, getenv("TZ")); + ENTER_SAFE_SECTION; + sntp_seconds = sec; + sntp_tick = xTaskGetTickCount(); + LEAVE_SAFE_SECTION; rtc.set_time_utc(sec); } } +uint32_t sntp_utc_now(void) +{ + uint32_t seconds; + TickType_t tick; + ENTER_SAFE_SECTION; + seconds = sntp_seconds; + tick = sntp_tick; + LEAVE_SAFE_SECTION; + if (!seconds) { + return 0; + } + return seconds + (xTaskGetTickCount() - tick) / configTICK_RATE_HZ; +} + void start_sntp(void) { sntp_stop(); diff --git a/software/network/sntp_time.h b/software/network/sntp_time.h index 8d4480dde..b517c2b88 100644 --- a/software/network/sntp_time.h +++ b/software/network/sntp_time.h @@ -1,6 +1,11 @@ #ifndef SNTP_TIME_H #define SNTP_TIME_H +#include + void start_sntp(); +// UTC seconds, counted on from the last time SNTP gave; 0 when it has not. +uint32_t sntp_utc_now(void); + #endif diff --git a/software/test/get_random_paths/isr_env.h b/software/test/get_random_paths/isr_env.h new file mode 100644 index 000000000..bcf28a7f2 --- /dev/null +++ b/software/test/get_random_paths/isr_env.h @@ -0,0 +1,71 @@ +/* + * isr_env.h + * + * What the receive interrupt's dispatch (wifi_rx_isr(), cut out of wifi_cmd.cc as it is) and + * the UART's buffer pool reset (DmaUART::ClearRxBuffer(), cut out of dma_uart.cc) are built + * against on the build host. The real headers need the hardware; these are their parts that + * the two functions use. + */ + +#ifndef ISR_ENV_H_ +#define ISR_ENV_H_ + +#include +#include +#include +#include "rpc_calls.h" +#include "wifi_reply.h" + +typedef int BaseType_t; +typedef void *TaskHandle_t; +typedef void *QueueHandle_t; +#define pdTRUE 1 +#define pdFALSE 0 +typedef enum { eSetValueWithOverwrite } eNotifyAction; + +#define CMD_BUF_SIZE 1600 +#define NUM_TX_BUFFERS 12 +#define WIFI_DEDICATED_THREAD 0xFC // as wifi_cmd.h has it +typedef struct { + uint8_t data[CMD_BUF_SIZE]; + int bufnr; + int size; +} command_buf_t; +typedef struct { int dummy; } command_buf_context_t; +typedef struct { + command_buf_t *buf; + uint32_t generation; +} dedicated_reply_t; + +typedef struct { volatile uint8_t flowctrl; } dma_uart_t; +#define DMAUART_RESET 0x01 + +class DmaUART { +public: + volatile dma_uart_t *uart; + command_buf_context_t *packets; + QueueHandle_t rx_bufs; + volatile uint32_t generation; + void ClearRxBuffer(void); +}; +struct Esp32Stub { DmaUART *uart; }; +extern Esp32Stub esp32; + +extern wifi_reply_slot_t replySlots[WIFI_REPLY_SLOTS]; // static in wifi_cmd.cc +extern QueueHandle_t dedicated_replies; +extern volatile bool dedicated_waiting; + +BaseType_t xQueueSendFromISR(QueueHandle_t q, const void *item, BaseType_t *w); +// The value is the buffer's address in 32 bits on the target; the stub does not need it, +// so it is dropped here rather than cast on a 64-bit host +BaseType_t notify_from_isr(TaskHandle_t t, eNotifyAction a, BaseType_t *w); +#define xTaskNotifyFromISR(t, value, a, w) notify_from_isr((t), (a), (w)) +BaseType_t cmd_buffer_received_isr(command_buf_context_t *context, command_buf_t *b, BaseType_t *w); +void ioWrite8(int reg, uint8_t value); +#define UART_DATA 0 +void vTaskSuspendAll(void); +BaseType_t xTaskResumeAll(void); +BaseType_t xQueueGenericReset(QueueHandle_t q, BaseType_t new_queue); +void cmd_buffer_reset(command_buf_context_t *context); + +#endif /* ISR_ENV_H_ */ diff --git a/software/test/get_random_paths/isr_test.cc b/software/test/get_random_paths/isr_test.cc new file mode 100644 index 000000000..091c8986b --- /dev/null +++ b/software/test/get_random_paths/isr_test.cc @@ -0,0 +1,102 @@ +/* + * isr_test.cc + * + * The receive interrupt's dispatch of a frame (wifi_rx_isr()) and the UART's buffer pool + * reset (DmaUART::ClearRxBuffer()), both cut out of their files as they are, against + * recording stubs. + */ + +#include +#include "isr_env.h" + +static int failures; +#define CHECK(cond, what) do { if (!(cond)) { printf("FAIL %s:%d: %s (log \"%s\")\n", __func__, __LINE__, what, rlog); failures++; } } while (0) + +static char rlog[64]; +static void note(char c) { size_t n = strlen(rlog); if (n + 1 < sizeof(rlog)) { rlog[n] = c; rlog[n + 1] = 0; } } + +BaseType_t wifi_rx_isr(command_buf_context_t *context, command_buf_t *buf, BaseType_t *w); + +static DmaUART uart; +static dma_uart_t regs; +static command_buf_context_t packets; +static int queue_tag, task_tag; +Esp32Stub esp32 = { &uart }; +wifi_reply_slot_t replySlots[WIFI_REPLY_SLOTS]; +QueueHandle_t dedicated_replies = &queue_tag; +volatile bool dedicated_waiting; + +static dedicated_reply_t queued; +BaseType_t xQueueSendFromISR(QueueHandle_t q, const void *item, BaseType_t *w) { note('q'); queued = *(const dedicated_reply_t *)item; return pdTRUE; } +BaseType_t notify_from_isr(TaskHandle_t t, eNotifyAction a, BaseType_t *w) { note('n'); return pdTRUE; } +BaseType_t cmd_buffer_received_isr(command_buf_context_t *context, command_buf_t *b, BaseType_t *w) { note('e'); return pdTRUE; } +void ioWrite8(int reg, uint8_t value) {} +void vTaskSuspendAll(void) { note('{'); } +BaseType_t xTaskResumeAll(void) { note('}'); return pdFALSE; } +BaseType_t xQueueGenericReset(QueueHandle_t q, BaseType_t new_queue) { note('r'); return pdTRUE; } +static uint32_t gen_before; +void cmd_buffer_reset(command_buf_context_t *context) { note('c'); if (uart.generation != gen_before) note('!'); } + +static BaseType_t frame(uint8_t thread, uint16_t sequence = 0) +{ + static command_buf_t buf; + memset(&buf, 0, sizeof(buf)); + ((rpc_header_t *)buf.data)->thread = thread; + ((rpc_header_t *)buf.data)->sequence = sequence; + rlog[0] = 0; + BaseType_t w = pdFALSE; + return wifi_rx_isr(&packets, &buf, &w); +} + +static void dedicated_channel(void) +{ + dedicated_waiting = false; + CHECK(frame(WIFI_DEDICATED_THREAD) == pdFALSE, "nobody waits: the buffer goes back"); + CHECK(rlog[0] == 0, "and is not queued or handed on"); + dedicated_waiting = true; + uart.generation = 7; + CHECK(frame(WIFI_DEDICATED_THREAD) == pdTRUE, "a waiting caller"); + CHECK((strcmp(rlog, "q") == 0) && (queued.generation == 7), "gets it, with the pool's generation"); + dedicated_waiting = false; +} + +static void other_threads(void) +{ + replySlots[3].task = &task_tag; + replySlots[3].sequence = 77; + frame(3, 76); + CHECK(strcmp(rlog, "e") == 0, "a reply with another sequence number is not the slot's"); + frame(3, 77); + CHECK(strcmp(rlog, "n") == 0, "a reply goes to its waiting task"); + CHECK(replySlots[3].task == NULL, "once"); + frame(3, 77); + CHECK(strcmp(rlog, "e") == 0, "without one, to the event queue"); + frame(0xFF); + CHECK(strcmp(rlog, "e") == 0, "events too"); +} + +static void pool_reset(void) +{ + uart.uart = ®s; + uart.packets = &packets; + uart.generation = 41; + gen_before = 41; + rlog[0] = 0; + uart.ClearRxBuffer(); + CHECK(uart.generation == 42, "a reset counts as one generation"); + CHECK((rlog[0] == '{') && (rlog[strlen(rlog) - 1] == '}'), "with the scheduler suspended"); + CHECK((strchr(rlog, 'r') != NULL) && (strchr(rlog, 'c') != NULL) && (strchr(rlog, '!') == NULL), "after both resets"); +} + +int main(void) +{ + dedicated_channel(); + other_threads(); + pool_reset(); + if (failures) { + printf("getrandompaths isr: %d check(s) failed\n", failures); + return 1; + } + printf("getrandompaths isr: all checks passed\n"); + return 0; +} diff --git a/software/test/get_random_paths/net_env.h b/software/test/get_random_paths/net_env.h new file mode 100644 index 000000000..26d3219da --- /dev/null +++ b/software/test/get_random_paths/net_env.h @@ -0,0 +1,23 @@ +/* + * net_env.h + * + * What NetworkTarget::get_random() and the status messages, cut out of network_target.cc + * and command_intf.cc as they are (target/pc/linux/getrandompaths/Makefile), are built + * against on the build host. + */ + +#ifndef NET_ENV_H_ +#define NET_ENV_H_ + +#include +#include +#include "command_intf.h" +#define class struct // get_random() is private +#include "network_target.h" +#undef class +#include "wifi_random.h" + +extern Message c_message_empty; +extern Message c_status_ok; + +#endif /* NET_ENV_H_ */ diff --git a/software/test/get_random_paths/net_target_test.cc b/software/test/get_random_paths/net_target_test.cc new file mode 100644 index 000000000..e63da535e --- /dev/null +++ b/software/test/get_random_paths/net_target_test.cc @@ -0,0 +1,114 @@ +/* + * net_target_test.cc + * + * The UCI network target's GET_RANDOM (NetworkTarget::get_random(), the GET_RANDOM case of + * execute() and the status messages, cut out of network_target.cc as they are) with + * the real wifi_random.cc behind it, and the module's answer stubbed: which UCI status and + * which bytes each answer gives, and which command lengths are taken. + */ + +#include "net_env.h" + +static int failures; +#define CHECK(cond, what) do { if (!(cond)) { printf("FAIL %s:%d: %s\n", __func__, __LINE__, what); failures++; } } while (0) + +// The module's answer, as wifi_get_random() returns it +static int module_result; +static int asked; +int wifi_get_random(uint8_t *buf, uint16_t len) +{ + asked++; + if (module_result == 0) { + memset(buf, 0x5A, len); + } + return module_result; +} + +NetworkTarget :: NetworkTarget(int id) {} +NetworkTarget :: ~NetworkTarget() {} +void NetworkTarget :: get_more_data(Message **reply, Message **status) {} +void NetworkTarget :: abort(int a) {} +void NetworkTarget :: c64_reset(void) {} + +static uint8_t buffer[2048]; + +static void ask(NetworkTarget &t, uint16_t length, Message **reply, Message **status) +{ + uint8_t cmd[4] = { 0x03, 0x20, (uint8_t)(length & 0xFF), (uint8_t)(length >> 8) }; + Message m = { 4, true, cmd }; + t.data_message.message = buffer; + t.data_message.length = 0; + *reply = NULL; + *status = NULL; + t.get_random(&m, reply, status); +} + +static bool status_is(Message *status, const char *text) +{ + return status && (status->length == (int)strlen(text)) && (memcmp(status->message, text, status->length) == 0); +} + +static void answers(void) +{ + NetworkTarget t(0); + Message *reply, *status; + + module_result = 0; + ask(t, 16, &reply, &status); + CHECK(status_is(status, "00,OK"), "bytes: 00,OK"); + CHECK((reply == &t.data_message) && (reply->length == 16) && (buffer[0] == 0x5A), "and the bytes"); + + module_result = WIFI_RANDOM_BUSY; + ask(t, 16, &reply, &status); + CHECK(status_is(status, "88,ENTROPY SOURCE BUSY"), "busy: 88"); + CHECK(reply == &c_message_empty, "busy carries no bytes"); + + module_result = WIFI_RANDOM_REFUSED; + ask(t, 16, &reply, &status); + CHECK(status_is(status, "87,NO ENTROPY SOURCE"), "refused: 87"); + CHECK(reply == &c_message_empty, "refused carries no bytes"); + + // The length is checked before the module is asked + asked = 0; + ask(t, 0, &reply, &status); + CHECK(status_is(status, "82,PARAMETER(S) OUT OF RANGE") && (asked == 0), "0 bytes: 82, module not asked"); + ask(t, NET_MAX_RANDOM + 1, &reply, &status); + CHECK(status_is(status, "82,PARAMETER(S) OUT OF RANGE") && (asked == 0), "513 bytes: 82, module not asked"); + module_result = 0; + ask(t, NET_MAX_RANDOM, &reply, &status); + CHECK(status_is(status, "00,OK") && (asked == 1), "512 bytes: asked"); +} + +// The command is exactly four bytes: target, command, length low, length high +static void command_length(void) +{ + NetworkTarget t(0); + Message *reply, *status; + for (int len = 2; len <= 6; len++) { + uint8_t cmd[6] = { 0x03, 0x20, 16, 0, 0, 0 }; + Message m = { len, true, cmd }; + t.data_message.message = buffer; + asked = 0; + module_result = 0; + reply = status = NULL; + t.execute(&m, &reply, &status); + if (len == 4) { + CHECK(status_is(status, "00,OK") && (asked == 1), "four bytes: asked, 00,OK"); + } else { + CHECK(status_is(status, "81,INVALID PARAMS") && (asked == 0) && (reply == &c_message_empty), + "any other length: 81, no data, the module not asked"); + } + } +} + +int main(void) +{ + answers(); + command_length(); + if (failures) { + printf("getrandompaths net_target: %d check(s) failed\n", failures); + return 1; + } + printf("getrandompaths net_target: all checks passed\n"); + return 0; +} diff --git a/software/test/get_random_paths/stub/command_intf.h b/software/test/get_random_paths/stub/command_intf.h new file mode 100644 index 000000000..2ece4fdac --- /dev/null +++ b/software/test/get_random_paths/stub/command_intf.h @@ -0,0 +1,20 @@ +// Stand-in for command_intf.h: what network_target.h declares against +#ifndef COMMAND_INTF_H_STUB +#define COMMAND_INTF_H_STUB +#include +#define CMD_MAX_REPLY_BLOCK 895 +#define CMD_MAX_COMMAND_LEN 896 +typedef struct _message { + int length; + bool last_part; + uint8_t *message; +} Message; +class CommandTarget { +public: + virtual ~CommandTarget() {} + virtual void parse_command(Message *command, Message **reply, Message **status) = 0; + virtual void get_more_data(Message **reply, Message **status) {} + virtual void abort(int a) {} + virtual void c64_reset(void) {} +}; +#endif diff --git a/software/test/get_random_paths/stub/lwip/netdb.h b/software/test/get_random_paths/stub/lwip/netdb.h new file mode 100644 index 000000000..72207e47d --- /dev/null +++ b/software/test/get_random_paths/stub/lwip/netdb.h @@ -0,0 +1 @@ +// Stand-in for lwIP's netdb.h on the build host. rpc_calls.h needs nothing from it. diff --git a/software/test/get_random_paths/stub/lwip/sockets.h b/software/test/get_random_paths/stub/lwip/sockets.h new file mode 100644 index 000000000..b78473080 --- /dev/null +++ b/software/test/get_random_paths/stub/lwip/sockets.h @@ -0,0 +1,6 @@ +// Stand-in for lwIP's sockets.h on the build host. rpc_calls.h needs only u16_t. +#ifndef LWIP_SOCKETS_H_STUB +#define LWIP_SOCKETS_H_STUB +#include +typedef uint16_t u16_t; +#endif diff --git a/software/test/get_random_paths/voltages_test.c b/software/test/get_random_paths/voltages_test.c new file mode 100644 index 000000000..5db3c956c --- /dev/null +++ b/software/test/get_random_paths/voltages_test.c @@ -0,0 +1,62 @@ +/* + * voltages_test.c + * + * The Elite II / C64 Ultimate module's answer to CMD_GET_VOLTAGES (cmd_get_voltages(), cut + * out of its rpc_dispatch.c as it is): a read that fails says so and carries no stale bytes. + */ + +#include +#include +#include +#include "rpc_calls.h" + +typedef int esp_err_t; +typedef int BaseType_t; +#define UART_NUM_0 0 +#define UART_NUM_1 1 +#define ESP_LOGI(tag, ...) ((void)0) +static const char *TAG = "test"; +typedef struct { uint8_t data[1600]; int bufnr; int size; } command_buf_t; +BaseType_t my_uart_transmit_packet(uint8_t uart_num, command_buf_t *buf); +esp_err_t read_adc_channels(uint16_t *adc_data); + +#include "voltages_extract.c" + +static int failures; +#define CHECK(cond, what) do { if (!(cond)) { printf("FAIL %s:%d: %s\n", __func__, __LINE__, what); failures++; } } while (0) + +static int read_result; +static int sent; +esp_err_t read_adc_channels(uint16_t *adc_data) +{ + if (read_result == 0) { + for (int i = 0; i < 7; i++) adc_data[i] = 1000 + i; + } + return read_result; +} +BaseType_t my_uart_transmit_packet(uint8_t uart_num, command_buf_t *buf) { sent++; return 1; } + +int main(void) +{ + static command_buf_t buf; + rpc_get_voltages_resp *resp = (rpc_get_voltages_resp *)buf.data; + + memset(buf.data, 0xAA, sizeof(buf.data)); + read_result = 0x107; + cmd_get_voltages(&buf); + CHECK(resp->esp_err == 0x107, "the read's error is the answer's"); + CHECK((resp->vbus == 0) && (resp->vusb == 0), "and no stale bytes in the voltages"); + CHECK((sent == 1) && (buf.size == sizeof(rpc_get_voltages_resp)), "sent, whole"); + + memset(buf.data, 0xAA, sizeof(buf.data)); + read_result = 0; + cmd_get_voltages(&buf); + CHECK((resp->esp_err == 0) && (resp->vbus == 1000) && (resp->vusb == 1006), "a good read"); + + if (failures) { + printf("getrandompaths voltages: %d check(s) failed\n", failures); + return 1; + } + printf("getrandompaths voltages: all checks passed\n"); + return 0; +} diff --git a/software/test/radio_entropy/radio_entropy_test.c b/software/test/radio_entropy/radio_entropy_test.c new file mode 100644 index 000000000..3184511be --- /dev/null +++ b/software/test/radio_entropy/radio_entropy_test.c @@ -0,0 +1,1016 @@ +// Host test of radio_entropy.c, against a model of the chip that counts every call the +// hardware would not allow as a violation: +// - bootloader_random_enable while the radio runs or while the source is on already; +// - bootloader_random_disable while it is off; +// - the Wi-Fi start while the source is on or the radio runs, the Wi-Fi stop while it is off; +// - any chip call made without the gate held exclusively, or a log line written with it held; +// - a source other than NONE reported while the radio starts or stops. +// The radio is started and stopped through wifi_radio.c, which is built in too. +// make -C target/pc/linux/radioentropy test +// Each case runs in a process of its own, because the helper keeps its state in statics. +#include +#include +#include +#include +#include +#include +#include +#include "radio_entropy.h" +#include "radio_entropy_port.h" +#include "wifi_radio.h" +#include "wifi_radio_port.h" + +static int failures; + +#define CHECK(cond, what) do { \ + if (!(cond)) { failures++; printf(" FAIL %s (line %d)\n", what, __LINE__); } \ + } while (0) + +//---------------------------------- +// The model + +static pthread_mutex_t lock_mutex = PTHREAD_MUTEX_INITIALIZER; + +static volatile bool wifi_running; +static volatile bool hw_on; // the source is enabled +static volatile bool hw_good = true; // the registers read back correctly while it is on +static volatile int violations; +static volatile int readback_failing; // this many readbacks fail +static volatile int wifi_start_fails; +static volatile int wifi_stop_fails; +static volatile int readbacks; +static char trace[256]; +static pthread_mutex_t trace_mutex = PTHREAD_MUTEX_INITIALIZER; + +static void note(char c) +{ + pthread_mutex_lock(&trace_mutex); + size_t n = strlen(trace); + if (n + 1 < sizeof(trace)) { + trace[n] = c; + trace[n + 1] = 0; + } + pthread_mutex_unlock(&trace_mutex); +} + +static void violate(const char *what) +{ + violations++; + printf(" violation: %s\n", what); +} + +// Every chip call comes with the exclusive hold. +static void need_gate(const char *what) +{ + if (!radio_entropy_held_exclusive()) { + violate(what); + } +} + +void re_port_lock(void) { pthread_mutex_lock(&lock_mutex); } +void re_port_unlock(void) { pthread_mutex_unlock(&lock_mutex); } + +uint32_t re_port_now_ms(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); +} + +void re_port_delay_ms(uint32_t ms) +{ + usleep(ms * 1000); +} + +uintptr_t re_port_task(void) +{ + return (uintptr_t)pthread_self(); +} + +int wr_port_wifi_start(void) +{ + need_gate("wifi start without the gate"); + if (entropy_source() != ENTROPY_NONE) violate("a source reported while the radio starts"); + if (wifi_running) violate("wifi start while running"); + if (hw_on) violate("wifi start with the ADC source on"); + note('S'); + if (wifi_start_fails > 0) { + wifi_start_fails--; + return 0x101; + } + wifi_running = true; + return 0; +} + +int wr_port_wifi_stop(void) +{ + need_gate("wifi stop without the gate"); + if (entropy_source() != ENTROPY_NONE) violate("a source reported while the radio stops"); + if (!wifi_running) violate("wifi stop while not running"); + note('P'); + if (wifi_stop_fails > 0) { + wifi_stop_fails--; + return 0x101; + } + wifi_running = false; + return 0; +} + +static volatile bool bus_clk_off; // as bootloader_random_enable() leaves it on the S3 + +void re_port_random_enable(void) +{ + need_gate("enable without the gate"); + if (wifi_running) violate("enable while the radio runs"); + if (hw_on) violate("enable twice"); + note('E'); + hw_on = true; + bus_clk_off = true; +} + +void re_port_adc_ready(void) +{ + need_gate("ADC readied without the gate"); + bus_clk_off = false; +} + +void re_port_random_disable(void) +{ + need_gate("disable without the gate"); + if (!hw_on) violate("disable while off"); + note('D'); + hw_on = false; +} + +bool re_port_random_readback(void) +{ + need_gate("readback without the gate"); + readbacks++; + if (readback_failing > 0) { + readback_failing--; + return false; + } + return hw_on && hw_good; +} + +static volatile int log_lines; + +void re_port_log(const char *fmt, ...) +{ + if (radio_entropy_held_exclusive()) violate("log line written with the gate held"); + log_lines++; +} + +static void reset_trace(void) +{ + pthread_mutex_lock(&trace_mutex); + trace[0] = 0; + pthread_mutex_unlock(&trace_mutex); +} + +static bool trace_is(const char *expected) +{ + if (strcmp(trace, expected) != 0) { + printf(" trace \"%s\", expected \"%s\"\n", trace, expected); + return false; + } + return true; +} + +//---------------------------------- +// The cases + +static void boot_without_radio(void) +{ + // The bootloader left the source off. A boot that does not start the radio turns it on. + radio_entropy_init(); + CHECK(trace_is("E"), "enable once"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC after a passing readback"); + CHECK(violations == 0, "no violations"); + radio_entropy_init(); + CHECK(trace_is("E"), "a second init does nothing"); +} + +static void boot_with_radio(void) +{ + CHECK(entropy_source() == ENTROPY_NONE, "NONE before anything"); + CHECK(radio_start() == 0, "start"); + CHECK(trace_is("S"), "no disable or enable on a boot that never had the source on"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO"); + radio_entropy_init(); + CHECK(trace_is("S"), "init does nothing with the radio running"); + CHECK(violations == 0, "no violations"); +} + +static void boot_readback_fails_then_retries(void) +{ + // NONE until a readback passes; never ADC without one + readback_failing = 2; + radio_entropy_init(); + CHECK(entropy_source() == ENTROPY_NONE, "NONE after a failed readback"); + radio_entropy_poll(); + CHECK(entropy_source() == ENTROPY_NONE, "still NONE after the first retry fails"); + radio_entropy_poll(); + CHECK(entropy_source() == ENTROPY_ADC, "ADC once a retry reads back"); + CHECK(trace_is("EDEDE"), "each retry disables, then enables"); + radio_entropy_poll(); + CHECK(trace_is("EDEDE"), "no more retries once it passed"); + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.readback_failures == 2, "two failures counted"); + CHECK(st.retries == 2, "two retries counted"); + CHECK(violations == 0, "no violations"); +} + +static void retries_are_bounded(void) +{ + readback_failing = 100; + radio_entropy_init(); + for (int i = 0; i < 10; i++) { + radio_entropy_poll(); + } + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.retries == RE_RETRIES, "RE_RETRIES retries, then no more"); + CHECK(entropy_source() == ENTROPY_NONE, "NONE"); + // A transition gives a new budget + readback_failing = 0; + CHECK(radio_start() == 0, "start"); + CHECK(radio_stop() == 0, "stop"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC after a transition with a good readback"); + CHECK(violations == 0, "no violations"); +} + +static void start_from_adc(void) +{ + radio_entropy_init(); + reset_trace(); + uint32_t epoch = entropy_epoch(); + CHECK(radio_start() == 0, "start"); + CHECK(trace_is("DS"), "disable, then start"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO"); + CHECK(entropy_epoch() == epoch, "the epoch counts stops, not starts"); + CHECK(radio_start() == 0, "start again"); + CHECK(trace_is("DS"), "a second start does nothing"); + CHECK(violations == 0, "no violations"); +} + +static void stop_enables(void) +{ + CHECK(radio_start() == 0, "start"); + reset_trace(); + uint32_t epoch = entropy_epoch(); + CHECK(radio_stop() == 0, "stop"); + CHECK(trace_is("PE"), "stop, then enable"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC"); + CHECK(entropy_epoch() == epoch + 1, "epoch moved"); + CHECK(radio_stop() == 0, "stop again"); + CHECK(trace_is("PE"), "a second stop does nothing"); + CHECK(entropy_epoch() == epoch + 1, "and does not move the epoch"); + CHECK(violations == 0, "no violations"); +} + +static void stop_readback_fails(void) +{ + CHECK(radio_start() == 0, "start"); + readback_failing = 1; + CHECK(radio_stop() == 0, "stop"); + CHECK(entropy_source() == ENTROPY_NONE, "NONE: the readback caught it"); + radio_entropy_poll(); + CHECK(entropy_source() == ENTROPY_ADC, "ADC after the retry"); + // and the source then goes away with the next start + CHECK(radio_start() == 0, "start"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO"); + CHECK(violations == 0, "no violations"); +} + +static void stop_fails(void) +{ + CHECK(radio_start() == 0, "start"); + reset_trace(); + wifi_stop_fails = 1; + CHECK(radio_stop() == 0x101, "stop passes the error on"); + CHECK(trace_is("P"), "no enable after a failed stop"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO: the radio is still on"); + CHECK(wifi_running, "and it is"); + CHECK(radio_stop() == 0, "stop works the next time"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC"); + CHECK(violations == 0, "no violations"); +} + +static void start_fails(void) +{ + radio_entropy_init(); + reset_trace(); + wifi_start_fails = 1; + CHECK(radio_start() == 0x101, "start passes the error on"); + CHECK(trace_is("DSE"), "the source is put back after a failed start"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC"); + CHECK(!wifi_running, "radio off"); + CHECK(radio_start() == 0, "start works the next time"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO"); + CHECK(violations == 0, "no violations"); +} + +static void adc_read_with_source_on(void) +{ + radio_entropy_init(); + reset_trace(); + CHECK(radio_entropy_adc_begin(RE_WAIT_ADC_MS) == 0, "begin"); + CHECK(trace_is("D"), "the source off"); + CHECK(entropy_source() == ENTROPY_NONE, "NONE while the ADC is lent out"); + CHECK(radio_entropy_acquire_shared(0) == RE_ERR_RECURSION, "the lender holds the gate"); + radio_entropy_adc_end(); + CHECK(trace_is("DE"), "the source on again"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC, read back"); + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.adc_hold_max_ms < 10, "held for less than 10 ms"); + CHECK(radio_entropy_acquire_shared(0) == 0, "and the gate is free"); + radio_entropy_release_shared(); + CHECK(violations == 0, "no violations"); +} + +static void adc_read_readback_fails(void) +{ + radio_entropy_init(); + CHECK(radio_entropy_adc_begin(RE_WAIT_ADC_MS) == 0, "begin"); + readback_failing = 1; + radio_entropy_adc_end(); + CHECK(entropy_source() == ENTROPY_NONE, "NONE: the readback caught it"); + radio_entropy_poll(); + CHECK(entropy_source() == ENTROPY_ADC, "ADC after the retry"); + CHECK(violations == 0, "no violations"); +} + +static void adc_read_with_radio_on(void) +{ + CHECK(radio_start() == 0, "start"); + reset_trace(); + CHECK(radio_entropy_adc_begin(RE_WAIT_ADC_MS) == 0, "begin"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO throughout"); + radio_entropy_adc_end(); + CHECK(trace_is(""), "the radio running, nothing is touched"); + CHECK(entropy_source() == ENTROPY_RADIO, "RADIO"); + CHECK(violations == 0, "no violations"); +} + +static void adc_read_with_source_off(void) +{ + // A failed readback left no source; reading the voltages does not make one + readback_failing = 100; + radio_entropy_init(); + reset_trace(); + CHECK(radio_entropy_adc_begin(RE_WAIT_ADC_MS) == 0, "begin"); + radio_entropy_adc_end(); + CHECK(entropy_source() == ENTROPY_NONE, "NONE"); + CHECK(violations == 0, "no violations"); +} + +//---------------------------------- +// The gate + +struct holder { + volatile int state; // 0 not started, 1 holding, 2 done + volatile int release; + int rc; + uint32_t wait_ms; + int kind; // 0 shared hold, 1 radio_stop, 2 adc_begin/end, 3 start +}; + +static void *holder_thread(void *arg) +{ + struct holder *h = arg; + if (h->kind == 0) { + h->rc = radio_entropy_acquire_shared(h->wait_ms); + if (h->rc == 0) { + h->state = 1; + while (!h->release) usleep(500); + radio_entropy_release_shared(); + } + } else if (h->kind == 1) { + h->state = 1; + h->rc = radio_stop(); + } else if (h->kind == 2) { + h->state = 1; + h->rc = radio_entropy_adc_begin(h->wait_ms); + if (h->rc == 0) { + radio_entropy_adc_end(); + } + } else if (h->kind == 5) { + h->rc = radio_entropy_adc_begin(h->wait_ms); + if (h->rc == 0) { + h->state = 1; + while (!h->release) usleep(500); + radio_entropy_adc_end(); + } + } else { + h->state = 1; + h->rc = radio_start(); + } + h->state = 2; + return NULL; +} + +static pthread_t spawn(struct holder *h) +{ + pthread_t t; + h->state = 0; + h->release = 0; + pthread_create(&t, NULL, holder_thread, h); + return t; +} + +static void wait_state(struct holder *h, int state) +{ + for (int i = 0; (i < 4000) && (h->state < state); i++) usleep(500); +} + +static void shared_holders_do_not_block_each_other(void) +{ + CHECK(radio_start() == 0, "start"); + struct holder a = { .wait_ms = 20 }, b = { .wait_ms = 20 }; + pthread_t ta = spawn(&a); + wait_state(&a, 1); + pthread_t tb = spawn(&b); + wait_state(&b, 1); + CHECK((a.state == 1) && (b.state == 1), "two holders at once"); + a.release = b.release = 1; + pthread_join(ta, NULL); + pthread_join(tb, NULL); + CHECK((a.rc == 0) && (b.rc == 0), "both got it"); +} + +static void pending_writer_blocks_new_readers(void) +{ + CHECK(radio_start() == 0, "start"); + struct holder reader = { .wait_ms = 20 }; + pthread_t tr = spawn(&reader); + wait_state(&reader, 1); + + struct holder writer = { .kind = 1 }; + pthread_t tw = spawn(&writer); + usleep(20000); // the stop is waiting for the reader + CHECK(writer.state == 1, "the stop waits for the reader"); + CHECK(wifi_running, "and has not stopped the radio"); + + uint32_t t0 = re_port_now_ms(); + CHECK(radio_entropy_acquire_shared(20) == RE_ERR_BUSY, "a new reader is turned away: busy"); + uint32_t waited = re_port_now_ms() - t0; + CHECK((waited >= 15) && (waited < 200), "after about 20 ms"); + CHECK(radio_entropy_acquire_shared(0) == RE_ERR_BUSY, "at once with a wait of 0"); + + reader.release = 1; + pthread_join(tr, NULL); + pthread_join(tw, NULL); + CHECK(writer.rc == 0, "the stop completes"); + CHECK(!wifi_running, "radio off"); + CHECK(radio_entropy_acquire_shared(20) == 0, "readers are served again"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC"); + radio_entropy_release_shared(); + CHECK(violations == 0, "no violations"); +} + +static void writer_that_gives_up_leaves_nothing_behind(void) +{ + radio_entropy_init(); + struct holder reader = { .wait_ms = 20 }; + pthread_t tr = spawn(&reader); + wait_state(&reader, 1); + uint32_t t0 = re_port_now_ms(); + CHECK(radio_entropy_adc_begin(30) == RE_ERR_BUSY, "the voltage read gives up"); + uint32_t waited = re_port_now_ms() - t0; + CHECK((waited >= 25) && (waited < 200), "after about 30 ms"); + reader.release = 1; + pthread_join(tr, NULL); + CHECK(radio_entropy_acquire_shared(0) == 0, "no pending writer left behind"); + radio_entropy_release_shared(); + CHECK(entropy_source() == ENTROPY_ADC, "the source was not touched"); + CHECK(violations == 0, "no violations"); +} + +static void recursion_is_refused(void) +{ + CHECK(radio_start() == 0, "start"); + CHECK(radio_entropy_acquire_shared(20) == 0, "shared"); + // With a writer pending, a waiting second acquire would never return + struct holder writer = { .kind = 1 }; + pthread_t tw = spawn(&writer); + usleep(20000); + uint32_t t0 = re_port_now_ms(); + CHECK(radio_entropy_acquire_shared(5000) == RE_ERR_RECURSION, "shared again, writer pending: refused"); + CHECK(re_port_now_ms() - t0 < 100, "at once, not after the wait"); + CHECK(radio_stop() == RE_ERR_RECURSION, "a reader cannot become a writer"); + CHECK(radio_start() == RE_ERR_RECURSION, "nor start the radio"); + CHECK(radio_entropy_adc_begin(5000) == RE_ERR_RECURSION, "nor lend out the ADC"); + radio_entropy_release_shared(); + pthread_join(tw, NULL); + CHECK(writer.rc == 0, "the stop completes"); + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.recursion >= 4, "counted"); + CHECK(violations == 0, "no violations"); +} + +// A stub of a busy reader: shared holds of 2 ms, one after another, as fast as it can +static volatile int stop_engine; +static volatile int engine_steps, engine_busy; + +static void *engine(void *arg) +{ + while (!stop_engine) { + if (radio_entropy_acquire_shared(RE_WAIT_RANDOM_MS) == 0) { + usleep(2000); + radio_entropy_release_shared(); + engine_steps++; + } else { + engine_busy++; + } + } + return NULL; +} + +static void back_to_back_readers_do_not_starve_a_transition(void) +{ + CHECK(radio_start() == 0, "start"); + pthread_t te; + pthread_create(&te, NULL, engine, NULL); + while (engine_steps < 5) usleep(1000); + uint32_t t0 = re_port_now_ms(); + CHECK(radio_stop() == 0, "stop"); + uint32_t took = re_port_now_ms() - t0; + CHECK(took < 300, "completes within a few steps, not starved"); + CHECK(!wifi_running, "radio off"); + stop_engine = 1; + pthread_join(te, NULL); + CHECK(violations == 0, "no violations"); +} + +static void gate_is_free_after_a_failed_transition(void) +{ + CHECK(radio_start() == 0, "start"); + wifi_stop_fails = 1; + CHECK(radio_stop() != 0, "stop fails"); + CHECK(radio_entropy_acquire_shared(0) == 0, "the gate is free"); + radio_entropy_release_shared(); + CHECK(radio_entropy_adc_begin(20) == 0, "and for the writer"); + radio_entropy_adc_end(); +} + +//---------------------------------- +// The answer to GET_RANDOM + +static volatile int fills; +static volatile int fill_gate_ok; + +// esp_fill_random(): called with the shared hold, and with nothing else held +static void fake_fill(void *buf, size_t len) +{ + fills++; + if ((radio_entropy_acquire_shared(0) == RE_ERR_RECURSION) && !radio_entropy_held_exclusive()) { + fill_gate_ok++; + } + memset(buf, 0xA5, len); +} + +static union { + uint32_t align; + uint8_t bytes[12 + 512 + 16]; +} msg; + +// Asks for len bytes; returns the size of the answer +static int ask(uint16_t len, int size_in) +{ + memset(msg.bytes, 0xEE, sizeof(msg.bytes)); + rpc_get_random_req *req = (rpc_get_random_req *)msg.bytes; + req->hdr.command = CMD_GET_RANDOM; + req->length = len; + return radio_entropy_serve_get_random(msg.bytes, size_in, fake_fill); +} + +static rpc_get_random_resp *reply(void) +{ + return (rpc_get_random_resp *)msg.bytes; +} + +static bool gate_is_free(void) +{ + if (radio_entropy_acquire_shared(0) != 0) return false; + radio_entropy_release_shared(); + if (radio_entropy_adc_begin(0) != 0) return false; + radio_entropy_adc_end(); + return true; +} + +static void get_random_answers(void) +{ + int n; + // No source yet + n = ask(16, 6); + CHECK((n == 12) && (reply()->esp_err == RE_ESP_ERR_INVALID_STATE) && (reply()->length == 0), "NONE: refused, no bytes"); + CHECK(reply()->source == ENTROPY_NONE, "NONE: source says none"); + CHECK(fills == 0, "nothing drawn"); + CHECK(gate_is_free(), "the gate is free after a refusal (no hold leaks)"); + + radio_entropy_init(); + n = ask(16, 6); + CHECK((n == 12 + 16) && (reply()->esp_err == 0) && (reply()->length == 16), "ADC: 16 bytes"); + CHECK((reply()->source == ENTROPY_ADC) && (reply()->data[0] == 0xA5) && (reply()->data[15] == 0xA5), "ADC: from the draw"); + CHECK(msg.bytes[12 + 16] == 0xEE, "no byte past the length is written"); + CHECK((fills == 1) && (fill_gate_ok == 1), "drawn once, with the shared hold only"); + CHECK(gate_is_free(), "the gate is free when the answer goes out"); + + n = ask(512, 6); + CHECK((n == 12 + 512) && (reply()->esp_err == 0), "512 bytes"); + n = ask(0, 6); + CHECK((n == 12) && (reply()->esp_err == RE_ESP_ERR_INVALID_ARG), "0 bytes: invalid"); + n = ask(513, 6); + CHECK((n == 12) && (reply()->esp_err == RE_ESP_ERR_INVALID_ARG) && (reply()->length == 0), "513 bytes: invalid"); + n = ask(16, 5); + CHECK((n == 12) && (reply()->esp_err == RE_ESP_ERR_INVALID_ARG), "a request too short to hold the length"); + CHECK(fills == 2, "refusals draw nothing"); + CHECK(gate_is_free(), "the gate is free after each"); + CHECK(msg.bytes[12] == 0xEE, "a refusal sends no data"); + + CHECK(radio_start() == 0, "start"); + n = ask(8, 6); + CHECK((n == 12 + 8) && (reply()->source == ENTROPY_RADIO), "RADIO: served"); + CHECK(radio_stop() == 0, "stop"); + n = ask(8, 6); + CHECK((n == 12 + 8) && (reply()->source == ENTROPY_ADC), "ADC again after the stop"); + CHECK(violations == 0, "no violations"); +} + +void serve_from_thread(int *size, uint32_t *ms); + +static void get_random_busy(void) +{ + radio_entropy_init(); + // A voltage read holds the source + CHECK(radio_entropy_adc_begin(20) == 0, "the ADC is lent out"); + // This task holds the gate exclusively, so serve from another + int size = 0; + uint32_t ms = 0; + serve_from_thread(&size, &ms); + CHECK(size == 12, "busy: no data"); + CHECK(reply()->esp_err == RPC_ERR_ENTROPY_BUSY, "busy: the busy error"); + CHECK((reply()->source == ENTROPY_NONE) && (reply()->length == 0), "busy: no source, no bytes"); + CHECK((ms >= 15) && (ms < 200), "after about 20 ms"); + CHECK(fills == 0, "nothing drawn"); + radio_entropy_adc_end(); + CHECK(gate_is_free(), "free again"); + CHECK(ask(4, 6) == 12 + 4, "served once the ADC is back"); + CHECK(violations == 0, "no violations"); +} + +static void *serve_thread(void *arg) +{ + int *r = arg; + uint32_t t0 = re_port_now_ms(); + r[0] = ask(16, 6); + r[1] = (int)(re_port_now_ms() - t0); + return NULL; +} + +void serve_from_thread(int *size, uint32_t *ms) +{ + int r[2]; + pthread_t t; + pthread_create(&t, NULL, serve_thread, r); + pthread_join(t, NULL); + *size = r[0]; + *ms = (uint32_t)r[1]; +} + +//---------------------------------- +// The voltage read + +static volatile int unit_reads; +static volatile int unit_fails; +static volatile uint16_t unit_base; + +static int fake_unit(uint16_t *out) +{ + unit_reads++; + if (!radio_entropy_held_exclusive()) violate("voltages read without the exclusive hold"); + if (bus_clk_off) violate("voltages read with the SAR ADC bus clock off"); + if (hw_on) violate("voltages read with the ADC source on"); + if (unit_fails > 0) { + unit_fails--; + return 0x101; + } + for (int i = 0; i < 7; i++) out[i] = unit_base + i; + return 0; +} + +// Radio off (the source on), then on: the source's enable left the ADC's bus clock off, +// and a voltage read with the radio on must not read with it off +static void adc_read_after_the_radio_came_on(void) +{ + uint16_t out[7], cache[7]; + bool valid = false; + radio_entropy_init(); + CHECK(entropy_source() == ENTROPY_ADC, "radio off: the ADC source"); + CHECK(radio_start() == 0, "start"); + CHECK(radio_entropy_read_adc(out, cache, &valid, 7, fake_unit) == 0, "read with the radio on"); + CHECK(violations == 0, "the clock was on for the read"); +} + +static void adc_read_cache(void) +{ + uint16_t cache[7] = { 0 }; + bool valid = false; + uint16_t out[7]; + radio_entropy_init(); + + unit_base = 1000; + memset(out, 0xEE, sizeof(out)); + CHECK(radio_entropy_read_adc(out, cache, &valid, 7, fake_unit) == 0, "first read"); + CHECK(valid && (out[0] == 1000) && (out[6] == 1006) && (cache[3] == 1003), "values and cache"); + CHECK(entropy_source() == ENTROPY_ADC, "the source is back"); + CHECK(gate_is_free(), "gate free"); + + // The ADC is busy: a reader holds the gate + struct holder reader = { .wait_ms = 20 }; + pthread_t tr = spawn(&reader); + wait_state(&reader, 1); + unit_base = 2000; + int before = unit_reads; + memset(out, 0xEE, sizeof(out)); + uint32_t t0 = re_port_now_ms(); + CHECK(radio_entropy_read_adc(out, cache, &valid, 7, fake_unit) == 0, "busy with a cache: succeeds"); + uint32_t took = re_port_now_ms() - t0; + CHECK((out[0] == 1000) && (out[6] == 1006), "with the last values, not zeros"); + CHECK((took >= 40) && (took < 300), "after about 50 ms"); + CHECK(unit_reads == before, "the unit was not read"); + reader.release = 1; + pthread_join(tr, NULL); + + // A failing read gives the cache and the error + unit_fails = 1; + memset(out, 0xEE, sizeof(out)); + CHECK(radio_entropy_read_adc(out, cache, &valid, 7, fake_unit) == 0x101, "a failed read is reported"); + CHECK((out[0] == 1000) && (cache[0] == 1000), "and does not touch the cache"); + CHECK(entropy_source() == ENTROPY_ADC, "the source is back after a failed read"); + CHECK(gate_is_free(), "gate free"); + CHECK(violations == 0, "no violations"); +} + +static struct holder *release_target; + +static void *release_later(void *arg) +{ + usleep(100000); + release_target->release = 1; + return NULL; +} + +static void adc_read_without_a_cache(void) +{ + uint16_t cache[7] = { 0 }; + bool valid = false; + uint16_t out[7]; + radio_entropy_init(); + + // The boot read fails: no values, so an error, never zeros + unit_fails = 1; + memset(out, 0xEE, sizeof(out)); + CHECK(radio_entropy_read_adc(out, cache, &valid, 7, fake_unit) == 0x101, "the failed first read is an error"); + CHECK(!valid, "and there is no cache"); + CHECK(out[0] == 0xEEEE, "out is left alone"); + + // And the next read, when it cannot get the ADC, is an error too + struct holder reader = { .wait_ms = 20 }; + pthread_t tr = spawn(&reader); + wait_state(&reader, 1); + memset(out, 0xEE, sizeof(out)); + int rc = radio_entropy_read_adc(out, cache, &valid, 7, fake_unit); + CHECK(rc == RE_ERR_BUSY, "no cache and no ADC: an error, after the long wait"); + CHECK(out[0] == 0xEEEE, "out is left alone, not zeros"); + reader.release = 1; + pthread_join(tr, NULL); + + // The long wait lets a short hold through + struct holder blip = { .wait_ms = 20 }; + pthread_t tb = spawn(&blip); + wait_state(&blip, 1); + unit_base = 3000; + pthread_t rel; + release_target = &blip; + pthread_create(&rel, NULL, release_later, NULL); + rc = radio_entropy_read_adc(out, cache, &valid, 7, fake_unit); + CHECK((rc == 0) && valid && (out[0] == 3000), "no cache: waits for the ADC rather than give up at once"); + pthread_join(rel, NULL); + pthread_join(tb, NULL); + CHECK(violations == 0, "no violations"); +} + +static void retry_budget_survives_voltage_reads(void) +{ + uint16_t cache[7] = { 0 }; + bool valid = false; + uint16_t out[7]; + readback_failing = 100; + radio_entropy_init(); + for (int i = 0; i < 6; i++) radio_entropy_poll(); + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.retries == RE_RETRIES, "the budget is spent"); + int lines = log_lines; + for (int i = 0; i < 5; i++) { + radio_entropy_read_adc(out, cache, &valid, 7, fake_unit); + radio_entropy_poll(); + } + radio_entropy_get_stats(&st); + CHECK(st.retries == RE_RETRIES, "voltage reads do not give new retries"); + CHECK(log_lines == lines, "and the failing readbacks are not logged again"); + CHECK(entropy_source() == ENTROPY_NONE, "NONE"); +} + +static void retries_per_transition(void) +{ + // The budget belongs to the transition: poll and voltage reads draw on it, nothing renews it + uint16_t cache[7] = { 0 }; + bool valid = false; + uint16_t out[7]; + unit_base = 500; + radio_entropy_init(); + CHECK(entropy_source() == ENTROPY_ADC, "healthy"); + // A healthy source fails once on a voltage read: that is the first failure, retries follow + readback_failing = 100; + radio_entropy_read_adc(out, cache, &valid, 7, fake_unit); + CHECK(entropy_source() == ENTROPY_NONE, "NONE after the failed re-enable"); + for (int i = 0; i < 10; i++) { + radio_entropy_poll(); + radio_entropy_read_adc(out, cache, &valid, 7, fake_unit); + } + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.retries == RE_RETRIES, "no more than RE_RETRIES retries, polls and reads together"); + reset_trace(); + for (int i = 0; i < 5; i++) { + radio_entropy_read_adc(out, cache, &valid, 7, fake_unit); + } + CHECK(trace_is(""), "once spent, a voltage read does not touch the source at all"); + CHECK(entropy_source() == ENTROPY_NONE, "NONE until the next transition"); + CHECK(valid && (out[0] == 500), "and the voltages still read"); + // The next transition gives a new budget + readback_failing = 0; + CHECK(radio_start() == 0, "start"); + CHECK(radio_stop() == 0, "stop"); + CHECK(entropy_source() == ENTROPY_ADC, "ADC after the next transition"); + CHECK(violations == 0, "no violations"); +} + +static void spent_poll_does_not_wait_for_the_gate(void) +{ + readback_failing = 100; + radio_entropy_init(); + for (int i = 0; i < 4; i++) radio_entropy_poll(); + struct holder reader = { .wait_ms = 20 }; + pthread_t tr = spawn(&reader); + wait_state(&reader, 1); + uint32_t t0 = re_port_now_ms(); + radio_entropy_poll(); + CHECK(re_port_now_ms() - t0 < 5, "a poll with nothing to do returns at once, with the gate busy"); + reader.release = 1; + pthread_join(tr, NULL); + radio_entropy_stats_t st; + radio_entropy_get_stats(&st); + CHECK(st.busy == 0, "and did not queue for the gate"); +} + +static void adc_end_by_a_bystander_changes_nothing(void) +{ + radio_entropy_init(); + struct holder lender = { .kind = 5, .wait_ms = 50 }; + pthread_t tl = spawn(&lender); + wait_state(&lender, 1); + CHECK(entropy_source() == ENTROPY_NONE, "lent out"); + int lines = log_lines; + radio_entropy_adc_end(); + CHECK(log_lines == lines + 1, "an end without a begin is logged"); + CHECK(radio_entropy_acquire_shared(0) == RE_ERR_BUSY, "and the lender still holds the gate"); + CHECK(entropy_source() == ENTROPY_NONE, "and the source is untouched"); + lender.release = 1; + pthread_join(tl, NULL); + CHECK(entropy_source() == ENTROPY_ADC, "the lender's end puts the source back"); + CHECK(violations == 0, "no violations"); +} + +static void logs_are_written_outside_the_gate(void) +{ + readback_failing = 1; + radio_entropy_init(); + CHECK(log_lines == 1, "the mismatch was logged"); + CHECK(violations == 0, "and not with the gate held"); +} + +//---------------------------------- +// A long random walk over everything, with failures, against the model's rules + +static unsigned rng_state = 12345; +static unsigned rnd(unsigned n) +{ + rng_state = rng_state * 1664525u + 1013904223u; + return (rng_state >> 8) % n; +} + +static void random_walk(void) +{ + int adc_without_source = 0; + for (int i = 0; i < 20000; i++) { + switch (rnd(8)) { + case 0: radio_start(); break; + case 1: radio_stop(); break; + case 2: radio_entropy_init(); break; + case 3: radio_entropy_poll(); break; + case 4: + if (radio_entropy_adc_begin(5) == 0) { + radio_entropy_adc_end(); + } + break; + case 5: wifi_start_fails = rnd(3) == 0; break; + case 6: wifi_stop_fails = rnd(3) == 0; break; + case 7: readback_failing = rnd(3) == 0 ? 1 + rnd(3) : 0; break; + } + // The source is only ADC when the hardware really is on and was read back; RADIO only + // while the radio runs + entropy_source_t s = entropy_source(); + if ((s == ENTROPY_ADC) && !(hw_on && !wifi_running)) adc_without_source++; + if ((s == ENTROPY_RADIO) && !wifi_running) adc_without_source++; + if (s == ENTROPY_NONE && wifi_running) { /* a start that failed to report cannot happen */ adc_without_source++; } + } + CHECK(adc_without_source == 0, "the source always matches the chip"); + CHECK(violations == 0, "no violations in 20000 steps"); +} + +//---------------------------------- + +struct testcase { + const char *name; + void (*fn)(void); +}; + +#define CASE(f) { #f, f } + +static const struct testcase cases[] = { + CASE(boot_without_radio), + CASE(boot_with_radio), + CASE(boot_readback_fails_then_retries), + CASE(retries_are_bounded), + CASE(start_from_adc), + CASE(stop_enables), + CASE(stop_readback_fails), + CASE(stop_fails), + CASE(start_fails), + CASE(adc_read_with_source_on), + CASE(adc_read_readback_fails), + CASE(adc_read_with_radio_on), + CASE(adc_read_with_source_off), + CASE(shared_holders_do_not_block_each_other), + CASE(pending_writer_blocks_new_readers), + CASE(writer_that_gives_up_leaves_nothing_behind), + CASE(recursion_is_refused), + CASE(back_to_back_readers_do_not_starve_a_transition), + CASE(gate_is_free_after_a_failed_transition), + CASE(get_random_answers), + CASE(get_random_busy), + CASE(adc_read_after_the_radio_came_on), + CASE(adc_read_cache), + CASE(adc_read_without_a_cache), + CASE(retry_budget_survives_voltage_reads), + CASE(logs_are_written_outside_the_gate), + CASE(retries_per_transition), + CASE(spent_poll_does_not_wait_for_the_gate), + CASE(adc_end_by_a_bystander_changes_nothing), + CASE(random_walk), +}; + +int main(void) +{ + int bad = 0; + int n = sizeof(cases) / sizeof(cases[0]); + setvbuf(stdout, NULL, _IOLBF, 0); + for (int i = 0; i < n; i++) { + printf("%s\n", cases[i].name); + fflush(stdout); + pid_t pid = fork(); + if (pid == 0) { + alarm(30); // a hang is a failure + cases[i].fn(); + fflush(stdout); + _exit(failures ? 1 : 0); + } + int status = 0; + waitpid(pid, &status, 0); + if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { + printf(" FAILED (status 0x%x)\n", status); + bad++; + } else { + printf(" ok\n"); + } + } + printf("\n%d cases, %d failed\n", n, bad); + return bad ? 1 : 0; +} diff --git a/software/test/recovery_manifest/recovery_manifest_test.c b/software/test/recovery_manifest/recovery_manifest_test.c index 89a73c24e..ea847248a 100644 --- a/software/test/recovery_manifest/recovery_manifest_test.c +++ b/software/test/recovery_manifest/recovery_manifest_test.c @@ -8,16 +8,26 @@ * is the code that runs on the board. The signed manifests and the serial * patterns in vectors/ were written by the recovery server's manifest.py and * Python's fnmatch; see make_vectors.py. + * + * The library is linked with --wrap=psa_crypto_init, --wrap=psa_hash_update and + * --wrap=psa_hash_finish, so a test can make the crypto library's start-up or a + * hash fail; see the __wrap_ functions below. */ #include #include #include +#include "mbedtls/pk.h" +#include "psa/crypto.h" #include "recovery_manifest.h" +#include "recovery_verify.h" #ifndef VECTORS_DIR #define VECTORS_DIR "vectors" #endif +/* recovery_trust.c, the keys the board ships with. */ +extern const char *const recovery_trusted_keys[]; + static int failures; static int checks; @@ -171,6 +181,179 @@ static void test_signed_vectors(void) free(other_key); } +/* A failing psa_crypto_init() on demand, for the checks that the verifier says + so rather than calling the manifest badly signed. The Makefile links with + --wrap=psa_crypto_init, so the calls recovery_verify.c makes land here. */ +psa_status_t __real_psa_crypto_init(void); +psa_status_t __real_psa_hash_update(psa_hash_operation_t *operation, const uint8_t *input, size_t input_length); +psa_status_t __real_psa_hash_finish(psa_hash_operation_t *operation, uint8_t *hash, size_t hash_size, + size_t *hash_length); +static psa_status_t crypto_init_forced = PSA_SUCCESS; +static psa_status_t hash_update_forced = PSA_SUCCESS; +static psa_status_t hash_finish_forced = PSA_SUCCESS; +static int crypto_init_calls; + +psa_status_t __wrap_psa_hash_update(psa_hash_operation_t *operation, const uint8_t *input, size_t input_length) +{ + if (hash_update_forced != PSA_SUCCESS) { + return hash_update_forced; + } + return __real_psa_hash_update(operation, input, input_length); +} + +psa_status_t __wrap_psa_hash_finish(psa_hash_operation_t *operation, uint8_t *hash, size_t hash_size, + size_t *hash_length) +{ + if (hash_finish_forced != PSA_SUCCESS) { + return hash_finish_forced; + } + return __real_psa_hash_finish(operation, hash, hash_size, hash_length); +} + +psa_status_t __wrap_psa_crypto_init(void) +{ + crypto_init_calls++; + if (crypto_init_forced != PSA_SUCCESS) { + return crypto_init_forced; + } + return __real_psa_crypto_init(); +} + +/* Each way a manifest or an image is refused, by the name it logs. */ +static void test_refusals_by_name(void) +{ + size_t len, fpga_len, image_len; + char *text = read_file("valid.manifest", &len); + char *test_key = read_file("test_key.pub.pem", NULL); + char *other_key = read_file("other_key.pub.pem", NULL); + char *fpga = read_file("fake.bit", &fpga_len); + char *image = read_file("fake.ue2", &image_len); + const char *trusted[] = { test_key }; + const char *untrusted[] = { other_key }; + recovery_manifest_t m; + recovery_signature_t sig; + recovery_result_t r; + + printf("Refusals, by the error they name\n"); + r = load(text, len, trusted, 1, &m); + check(r == RECOVERY_OK && strcmp(recovery_result_name(r), "ok") == 0, "a valid manifest is accepted"); + r = load(text, len, untrusted, 1, &m); + check(r == RECOVERY_ERR_BAD_SIGNATURE && strcmp(recovery_result_name(r), "bad signature") == 0, + "a wrong key is refused as a bad signature"); + recovery_manifest_split(text, len, &sig); + char *at = strstr(text, "test-1.0"); + check(at != NULL && at < text + sig.signed_len, "the package line is in the signed text"); + *at ^= 0x01; + r = load(text, len, trusted, 1, &m); + check(r == RECOVERY_ERR_BAD_SIGNATURE && strcmp(recovery_result_name(r), "bad signature") == 0, + "a tampered manifest is refused as a bad signature"); + *at ^= 0x01; + + // The hashes the manifest holds were made from these files. + recovery_manifest_t good; + check_result(load(text, len, trusted, 1, &good), RECOVERY_OK, "the manifest verifies again once restored"); + const struct { const recovery_file_t *file; char *data; size_t len; const char *what; } files[] = { + { &good.image, image, image_len, "image" }, + { &good.fpga, fpga, fpga_len, "bitstream" }, + }; + for (int i = 0; i < 2; i++) { + char what[96]; + recovery_hash_t h; + snprintf(what, sizeof(what), "the %s hashes to what its manifest says", files[i].what); + check(files[i].len == files[i].file->size, "the vector is the size its manifest says"); + check(recovery_hash_start(&h) == RECOVERY_OK, "a hash starts"); + // In three pieces, as the download hands it over. + size_t a = files[i].len / 3, b = 2 * files[i].len / 3; + recovery_hash_update(&h, (const uint8_t *)files[i].data, a); + recovery_hash_update(&h, (const uint8_t *)files[i].data + a, b - a); + recovery_hash_update(&h, (const uint8_t *)files[i].data + b, files[i].len - b); + check_result(recovery_hash_finish(&h, files[i].file), RECOVERY_OK, what); + + snprintf(what, sizeof(what), "a changed byte in the %s is refused as a hash mismatch", files[i].what); + files[i].data[files[i].len / 2] ^= 0x01; + recovery_hash_start(&h); + recovery_hash_update(&h, (const uint8_t *)files[i].data, files[i].len); + r = recovery_hash_finish(&h, files[i].file); + check(r == RECOVERY_ERR_HASH_MISMATCH && strcmp(recovery_result_name(r), "hash differs") == 0, what); + files[i].data[files[i].len / 2] ^= 0x01; + + // A compare that stopped early would still see the file change, which + // changes every byte of the hash; the manifest's hash changing in one + // byte, at its start, middle or end, is what shows it. + static const int flips[] = { 0, 16, 31 }; + for (int f = 0; f < 3; f++) { + recovery_file_t wrong = *files[i].file; + wrong.sha256[flips[f]] ^= 0x01; + snprintf(what, sizeof(what), "the %s is refused when byte %d of its manifest hash differs", files[i].what, + flips[f]); + recovery_hash_start(&h); + recovery_hash_update(&h, (const uint8_t *)files[i].data, files[i].len); + check_result(recovery_hash_finish(&h, &wrong), RECOVERY_ERR_HASH_MISMATCH, what); + } + + snprintf(what, sizeof(what), "a %s cut short is refused as a hash mismatch", files[i].what); + recovery_hash_start(&h); + recovery_hash_update(&h, (const uint8_t *)files[i].data, files[i].len - 1); + check_result(recovery_hash_finish(&h, files[i].file), RECOVERY_ERR_HASH_MISMATCH, what); + } + + // A hash that fails part-way is a crypto error, never "matches": the + // image whose hash was not computed must not be accepted. + for (int i = 0; i < 2; i++) { + recovery_hash_t fh; + char what[96]; + recovery_hash_start(&fh); + if (i == 0) { + hash_update_forced = PSA_ERROR_HARDWARE_FAILURE; + r = recovery_hash_update(&fh, (const uint8_t *)image, image_len); + hash_update_forced = PSA_SUCCESS; + snprintf(what, sizeof(what), "a hash update that fails is reported as a crypto library failure"); + check(r == RECOVERY_ERR_CRYPTO && strcmp(recovery_result_name(r), "crypto library failed") == 0, what); + recovery_hash_abort(&fh); + } else { + recovery_hash_update(&fh, (const uint8_t *)image, image_len); + hash_finish_forced = PSA_ERROR_HARDWARE_FAILURE; + r = recovery_hash_finish(&fh, &good.image); + hash_finish_forced = PSA_SUCCESS; + snprintf(what, sizeof(what), "a hash finish that fails is a crypto library failure, not a match"); + check(r == RECOVERY_ERR_CRYPTO && strcmp(recovery_result_name(r), "crypto library failed") == 0, what); + } + } + + // A trusted key that is not an EC key is refused, even with a signature + // that is valid for it: rsa512.manifest holds the signed text of + // valid.manifest with a PKCS#1 v1.5 SHA-256 signature by the RSA-512 key in + // rsa512.pub.pem (openssl genrsa 512; openssl dgst -sha256 -sign). + size_t rsa_len; + char *rsa_text = read_file("rsa512.manifest", &rsa_len); + char *rsa_key = read_file("rsa512.pub.pem", NULL); + const char *rsa_trusted[] = { rsa_key }; + r = load(rsa_text, rsa_len, rsa_trusted, 1, &m); + check(r == RECOVERY_ERR_BAD_SIGNATURE && strcmp(recovery_result_name(r), "bad signature") == 0, + "a manifest correctly signed by an RSA key is refused as a bad signature"); + free(rsa_text); + free(rsa_key); + + // The crypto library failing to start is not a bad signature. + crypto_init_forced = PSA_ERROR_INSUFFICIENT_MEMORY; + crypto_init_calls = 0; + r = load(text, len, trusted, 1, &m); + check(crypto_init_calls > 0, "the verifier initialises the crypto library itself"); + check(r == RECOVERY_ERR_CRYPTO && strcmp(recovery_result_name(r), "crypto library failed") == 0, + "a crypto library that will not start is named, with a valid manifest"); + check(r != RECOVERY_ERR_BAD_SIGNATURE, "and is not called a bad signature"); + recovery_hash_t h; + check_result(recovery_hash_start(&h), RECOVERY_ERR_CRYPTO, "a hash cannot start either"); + crypto_init_forced = PSA_SUCCESS; + check_result(load(text, len, trusted, 1, &m), RECOVERY_OK, "and the manifest verifies once it starts"); + + free(text); + free(test_key); + free(other_key); + free(fpga); + free(image); +} + static void test_split(void) { recovery_signature_t sig; @@ -278,13 +461,59 @@ static void test_serial_patterns(void) free(text); } +/* The keys the board ships with, main and spare: each must load as an EC public + key, no two may be the same (a spare pasted as a copy of the main key rotates + nothing), and a manifest must be verified by a key behind all of them. */ +static void test_shipped_keys(void) +{ + int n = 0; + while (recovery_trusted_keys[n]) { + mbedtls_pk_context pk; + mbedtls_pk_init(&pk); + check(psa_crypto_init() == PSA_SUCCESS, "the crypto library starts"); + check(mbedtls_pk_parse_public_key(&pk, (const unsigned char *)recovery_trusted_keys[n], + strlen(recovery_trusted_keys[n]) + 1) == 0 && + PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(mbedtls_pk_get_key_type(&pk)), + "a shipped key loads as an EC public key"); + mbedtls_pk_free(&pk); + n++; + } + check(n >= 2, "a spare key ships next to the main key"); + int distinct = 1; + for (int i = 0; i < n; i++) { + for (int j = i + 1; j < n; j++) { + distinct &= strcmp(recovery_trusted_keys[i], recovery_trusted_keys[j]) != 0; + } + } + check(distinct, "the shipped keys are all different"); + + size_t len; + char *text = read_file("valid.manifest", &len); + char *test_key = read_file("test_key.pub.pem", NULL); + const char *list[16]; + int count = 0; + for (int i = 0; i < n && i < 15; i++) { + list[count++] = recovery_trusted_keys[i]; + } + recovery_manifest_t m; + check_result(load(text, len, list, count, &m), RECOVERY_ERR_BAD_SIGNATURE, + "a manifest signed by a test key is refused by the shipped keys"); + list[count++] = test_key; + check_result(load(text, len, list, count, &m), RECOVERY_OK, + "a manifest is verified by a key behind every shipped key"); + free(text); + free(test_key); +} + int main(void) { test_signed_vectors(); + test_refusals_by_name(); test_split(); test_parse(); test_board(); test_serial_patterns(); + test_shipped_keys(); // last: it starts the crypto library, which the tests above leave to the code under test printf("\n%d checks, %d failed\n", checks, failures); return failures ? 1 : 0; diff --git a/software/test/recovery_manifest/vectors/rsa512.manifest b/software/test/recovery_manifest/vectors/rsa512.manifest new file mode 100644 index 000000000..d52157a75 --- /dev/null +++ b/software/test/recovery_manifest/vectors/rsa512.manifest @@ -0,0 +1,11 @@ +format=1 +package=test-1.0 +idcode=0362c093 +serial=U64E2-1* +fpga.file=fake.bit +fpga.size=88 +fpga.sha256=53ee5bc784105e3444f8810df9c0b13ea5542d8ce5e112bfafcdf0cd49088408 +image.file=fake.ue2 +image.size=28 +image.sha256=e3989004d19d6ccedafac4b3d6ed7531ed17a26eb4a389a2a5e8050777aa1162 +sig=aebip2VIXnU8CC2yuSAKFNXczOZvuSgd0BIYw58QuryLpRLoeZ/QGxP15u1bR5WhNU4waJHDhXZweC1FyM0WWg== diff --git a/software/test/recovery_manifest/vectors/rsa512.pub.pem b/software/test/recovery_manifest/vectors/rsa512.pub.pem new file mode 100644 index 000000000..d32a3c06e --- /dev/null +++ b/software/test/recovery_manifest/vectors/rsa512.pub.pem @@ -0,0 +1,4 @@ +-----BEGIN PUBLIC KEY----- +MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK/ZCRMQmkgLGfmu2X25Fo2TddpkyeOP +mfBYQhM4ngzNRy1vsWjtdwfJuGn2AqFqVXKoEHTp6gLRL93ZBtVsC40CAwEAAQ== +-----END PUBLIC KEY----- diff --git a/software/test/tls_engine/stub/cmd_buffer.h b/software/test/tls_engine/stub/cmd_buffer.h new file mode 100644 index 000000000..e69de29bb diff --git a/software/test/tls_engine/stub/esp_err.h b/software/test/tls_engine/stub/esp_err.h new file mode 100644 index 000000000..8497af374 --- /dev/null +++ b/software/test/tls_engine/stub/esp_err.h @@ -0,0 +1,11 @@ +#ifndef STUB_ESP_ERR_H +#define STUB_ESP_ERR_H +typedef int esp_err_t; +#define ESP_OK 0 +#define ESP_FAIL (-1) +#define ESP_ERR_NO_MEM 0x101 +#define ESP_ERR_INVALID_ARG 0x102 +#define ESP_ERR_INVALID_STATE 0x103 +#define ESP_ERR_NOT_FOUND 0x105 +#define ESP_ERR_NOT_SUPPORTED 0x106 +#endif diff --git a/software/test/tls_engine/stub/esp_heap_caps.h b/software/test/tls_engine/stub/esp_heap_caps.h new file mode 100644 index 000000000..ebaed95fd --- /dev/null +++ b/software/test/tls_engine/stub/esp_heap_caps.h @@ -0,0 +1,4 @@ +#define MALLOC_CAP_INTERNAL 1 +#define MALLOC_CAP_8BIT 2 +static inline void heap_caps_monitor_local_minimum_free_size_start(void) {} +static inline void heap_caps_monitor_local_minimum_free_size_stop(void) {} diff --git a/software/test/tls_engine/stub/esp_log.h b/software/test/tls_engine/stub/esp_log.h new file mode 100644 index 000000000..76d59540f --- /dev/null +++ b/software/test/tls_engine/stub/esp_log.h @@ -0,0 +1,8 @@ +#ifndef STUB_ESP_LOG_H +#define STUB_ESP_LOG_H +#include +extern int tlsguard_verbose; +extern char tlsguard_last_error[160]; // the last ESP_LOGE text, for tests that assert on which check refused +#define ESP_LOGE(tag, ...) do { snprintf(tlsguard_last_error, sizeof(tlsguard_last_error), __VA_ARGS__); if (tlsguard_verbose) { fprintf(stderr, "E %s: ", tag); fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0) +#define ESP_LOGW(tag, ...) do { if (tlsguard_verbose) { fprintf(stderr, "W %s: ", tag); fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0) +#endif diff --git a/software/test/tls_engine/stub/esp_timer.h b/software/test/tls_engine/stub/esp_timer.h new file mode 100644 index 000000000..a57f4506c --- /dev/null +++ b/software/test/tls_engine/stub/esp_timer.h @@ -0,0 +1,8 @@ +#include +#include +static inline int64_t esp_timer_get_time(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000; +} diff --git a/software/test/tls_engine/stub/freertos/FreeRTOS.h b/software/test/tls_engine/stub/freertos/FreeRTOS.h new file mode 100644 index 000000000..e69de29bb diff --git a/software/test/tls_engine/stub/rpc_calls.h b/software/test/tls_engine/stub/rpc_calls.h new file mode 100644 index 000000000..59571089f --- /dev/null +++ b/software/test/tls_engine/stub/rpc_calls.h @@ -0,0 +1,15 @@ +/* Stand-in for raw_u64/main/rpc_calls.h: only the header type rpc_tls.h builds on. */ +#ifndef STUB_RPC_CALLS_H +#define STUB_RPC_CALLS_H +#include +typedef struct { + uint8_t command; + uint8_t thread; + uint16_t sequence; +} rpc_header_t; +typedef struct { + rpc_header_t hdr; + int esp_err; +} rpc_espcmd_resp; +#include "rpc_tls.h" +#endif diff --git a/software/test/tls_engine/stub/sdkconfig.h b/software/test/tls_engine/stub/sdkconfig.h new file mode 100644 index 000000000..b58cbf3a9 --- /dev/null +++ b/software/test/tls_engine/stub/sdkconfig.h @@ -0,0 +1,6 @@ +/* Host stand-in for the ESP-IDF sdkconfig: what tls_engine.c checks, set as the module's sdkconfig sets it (TLS 1.3 and 1.2, + * time and date, no certificate bundle: the test pins keys). */ +#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 1 +#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1 +#define CONFIG_MBEDTLS_HAVE_TIME_DATE 1 +#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE 0 diff --git a/software/test/tls_engine/stub/sntp.h b/software/test/tls_engine/stub/sntp.h new file mode 100644 index 000000000..385ad3cdb --- /dev/null +++ b/software/test/tls_engine/stub/sntp.h @@ -0,0 +1 @@ +static inline int sntp_has_time(void) { return 0; } diff --git a/software/test/tls_engine/stub/wifi_modem.h b/software/test/tls_engine/stub/wifi_modem.h new file mode 100644 index 000000000..67a0f07d3 --- /dev/null +++ b/software/test/tls_engine/stub/wifi_modem.h @@ -0,0 +1,3 @@ +/* Stand-in: entropy_source() is radio_entropy.h's. The host draws from the OS, so a source is always there. */ +enum { ENTROPY_NONE = 0, ENTROPY_HOST = 1 }; +static inline int entropy_source(void) { return ENTROPY_HOST; } diff --git a/software/test/tls_engine/stub_rng_gate.c b/software/test/tls_engine/stub_rng_gate.c new file mode 100644 index 000000000..1c1839cc7 --- /dev/null +++ b/software/test/tls_engine/stub_rng_gate.c @@ -0,0 +1,4 @@ +/* Host stand-in for tls_rng_gate.c (the radio's entropy gate): the host has no gate, so no draw is ever refused. */ +#include "tls_rng_gate.h" +void tls_rng_gate_bind_task(void) {} +int tls_rng_gate_take_refusal(void) { return 0; } diff --git a/software/test/tls_engine/test_cert.h b/software/test/tls_engine/test_cert.h new file mode 100644 index 000000000..5a7dad79e --- /dev/null +++ b/software/test/tls_engine/test_cert.h @@ -0,0 +1,37 @@ +static const unsigned char test_cert_der[] = { + 0x30, 0x82, 0x01, 0x96, 0x30, 0x82, 0x01, 0x3b, 0xa0, 0x03, 0x02, 0x01, + 0x02, 0x02, 0x14, 0x31, 0xca, 0xde, 0x36, 0x6d, 0x73, 0xb8, 0x76, 0x63, + 0x5d, 0x12, 0x51, 0x02, 0xac, 0x1a, 0xff, 0xae, 0xca, 0x2a, 0x78, 0x30, + 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, + 0x1f, 0x31, 0x1d, 0x30, 0x1b, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x14, + 0x74, 0x6c, 0x73, 0x67, 0x75, 0x61, 0x72, 0x64, 0x20, 0x74, 0x65, 0x73, + 0x74, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x30, 0x20, 0x17, 0x0d, + 0x32, 0x36, 0x31, 0x31, 0x32, 0x34, 0x31, 0x32, 0x30, 0x30, 0x34, 0x35, + 0x5a, 0x18, 0x0f, 0x32, 0x31, 0x32, 0x36, 0x31, 0x30, 0x33, 0x31, 0x31, + 0x32, 0x30, 0x30, 0x34, 0x35, 0x5a, 0x30, 0x1f, 0x31, 0x1d, 0x30, 0x1b, + 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x14, 0x74, 0x6c, 0x73, 0x67, 0x75, + 0x61, 0x72, 0x64, 0x20, 0x74, 0x65, 0x73, 0x74, 0x20, 0x73, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, + 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x65, 0x1d, 0x2e, 0xbe, 0xbf, 0x37, + 0x19, 0x68, 0x2d, 0x94, 0xbb, 0xe6, 0x56, 0x1f, 0xf1, 0xa5, 0x6f, 0xc7, + 0xd4, 0xbb, 0x80, 0x19, 0x80, 0x69, 0x9b, 0x89, 0x85, 0xaa, 0xca, 0x37, + 0x76, 0x2d, 0x4d, 0xe3, 0xb0, 0xcf, 0xb8, 0xd3, 0x53, 0x7c, 0x5a, 0x07, + 0x55, 0x6f, 0x12, 0x91, 0x87, 0xd8, 0x45, 0x6f, 0xfb, 0x6f, 0x89, 0x50, + 0x30, 0x10, 0x78, 0xb0, 0xb9, 0x4a, 0xc4, 0x46, 0x13, 0x06, 0xa3, 0x53, + 0x30, 0x51, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, + 0x14, 0xa1, 0xf0, 0xf4, 0x4d, 0x32, 0x11, 0x0e, 0x13, 0x57, 0x70, 0x01, + 0x3f, 0xa2, 0x86, 0x35, 0xa8, 0x79, 0xb2, 0x33, 0x33, 0x30, 0x1f, 0x06, + 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0xa1, 0xf0, + 0xf4, 0x4d, 0x32, 0x11, 0x0e, 0x13, 0x57, 0x70, 0x01, 0x3f, 0xa2, 0x86, + 0x35, 0xa8, 0x79, 0xb2, 0x33, 0x33, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x1d, + 0x13, 0x01, 0x01, 0xff, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, + 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, + 0x49, 0x00, 0x30, 0x46, 0x02, 0x21, 0x00, 0xba, 0x8c, 0xf8, 0x85, 0xe5, + 0x5c, 0x0c, 0x42, 0x0d, 0xd2, 0x25, 0x13, 0x57, 0x0d, 0xcb, 0x7d, 0x4c, + 0x10, 0x25, 0xcc, 0x2c, 0xdc, 0xac, 0xb8, 0xdd, 0xf7, 0xe2, 0x4a, 0x8a, + 0x20, 0x7c, 0xb0, 0x02, 0x21, 0x00, 0xe6, 0x79, 0xcd, 0xfb, 0x86, 0x28, + 0x68, 0xa9, 0xaf, 0x26, 0xab, 0xd5, 0xfa, 0xd7, 0x37, 0xd6, 0x06, 0xd1, + 0x34, 0xc9, 0x3a, 0x58, 0x00, 0xa7, 0xc0, 0xaa, 0xc3, 0x30, 0xd1, 0x1a, + 0xde, 0x6b, +}; diff --git a/software/test/tls_engine/test_key.h b/software/test/tls_engine/test_key.h new file mode 100644 index 000000000..8ee289121 --- /dev/null +++ b/software/test/tls_engine/test_key.h @@ -0,0 +1,14 @@ +static const unsigned char test_key_der[] = { + 0x30, 0x81, 0x87, 0x02, 0x01, 0x00, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, + 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, + 0x03, 0x01, 0x07, 0x04, 0x6d, 0x30, 0x6b, 0x02, 0x01, 0x01, 0x04, 0x20, + 0xa0, 0xcf, 0x12, 0x7f, 0x32, 0x88, 0x76, 0x53, 0xbc, 0x0d, 0x9c, 0x2e, + 0xcf, 0x53, 0x43, 0xea, 0x3b, 0x0a, 0x34, 0x5a, 0x99, 0x84, 0x97, 0x91, + 0x7c, 0x9e, 0x66, 0x2b, 0xe5, 0x9c, 0xe5, 0x19, 0xa1, 0x44, 0x03, 0x42, + 0x00, 0x04, 0x65, 0x1d, 0x2e, 0xbe, 0xbf, 0x37, 0x19, 0x68, 0x2d, 0x94, + 0xbb, 0xe6, 0x56, 0x1f, 0xf1, 0xa5, 0x6f, 0xc7, 0xd4, 0xbb, 0x80, 0x19, + 0x80, 0x69, 0x9b, 0x89, 0x85, 0xaa, 0xca, 0x37, 0x76, 0x2d, 0x4d, 0xe3, + 0xb0, 0xcf, 0xb8, 0xd3, 0x53, 0x7c, 0x5a, 0x07, 0x55, 0x6f, 0x12, 0x91, + 0x87, 0xd8, 0x45, 0x6f, 0xfb, 0x6f, 0x89, 0x50, 0x30, 0x10, 0x78, 0xb0, + 0xb9, 0x4a, 0xc4, 0x46, 0x13, 0x06, +}; diff --git a/software/test/tls_engine/tls_guard_test.c b/software/test/tls_engine/tls_guard_test.c new file mode 100644 index 000000000..9ecd36fdf --- /dev/null +++ b/software/test/tls_engine/tls_guard_test.c @@ -0,0 +1,448 @@ +/* tls_guard_test.c: host test of the TLS version-confusion guard in tls_engine.c (Mbed TLS advisory 2026-11, + * CVE-2026-115490: a ServerHello without supported_versions, legacy_version 0x0304 and a TLS 1.3 suite, sent to a + * client that offers both TLS 1.2 and 1.3, moves mbedTLS 4.1.1 into its TLS 1.3 machine with no key exchange). + * + * The unit under test is tls_engine.c itself, included below so the test can look at the session it holds. Build and + * run with target/pc/linux/tlsguard (see its Makefile). The peers are in this file: + * - a scripted attacker that answers the ClientHello with the ServerHello above; + * - honest mbedTLS servers (TLS 1.2 only, TLS 1.3 only, TLS 1.3 with a HelloRetryRequest, and one offering both): + * controls, the guard refuses none of them. + * + * What it asserts, on Mbed TLS 4.1.1 and on a 4.1.x that has the upstream fix, alike: the handshake is refused at the + * ServerHello, with a fatal protocol_version alert, the session is freed, and the version reported to the Ultimate is + * the 0x0304 the server sent. Which layer refuses differs: on 4.1.1 the engine's guard (the library accepts the + * ServerHello); on the fixed library the library does, before the guard is reached. The test probes the linked library + * with a bare client and prints which case ran. + * + * The guard is defence in depth and an early, specific refusal, not the only barrier: with the guard compiled out + * (make red) the ServerHello is accepted, but the handshake still cannot end ESTABLISHED, because the engine's + * end-of-handshake check finds no negotiated group. The "barrier" mode of this test shows that, on the guard-disabled + * build, by driving the whole attack (Certificate, CertificateVerify and Finished, computed from the client's own + * key schedule, which has no secret in it). + * + * Usage: tlsguard [-v] the guard checks and the controls; exit status 0 only when every check passes + * tlsguard barrier only on the guard-disabled build: the second barrier; "make test" runs it + * With the guard compiled out the guard checks fail (make red expects that) and the test prints what the client did. */ + +#include TLS_ENGINE_SRC // the engine under test (default: the tree's own tls_engine.c) + +#include +#include +#include "mbedtls/ssl.h" +#include "mbedtls/x509_crt.h" +#include "mbedtls/pk.h" +#include "psa/crypto.h" +#include "test_cert.h" +#include "test_key.h" +#include "ssl_misc.h" +#include "ssl_tls13_keys.h" +#include "mbedtls/md.h" + +int tlsguard_verbose; +char tlsguard_last_error[160]; +static int failures; + +#define CHECK(cond, ...) do { if (!(cond)) { failures++; printf(" FAIL: "); printf(__VA_ARGS__); printf("\n"); } \ + else { printf(" ok: "); printf(__VA_ARGS__); printf("\n"); } } while (0) + +static void hexline(const char *label, const uint8_t *p, size_t n) +{ + printf(" %s (%u bytes):", label, (unsigned)n); + for (size_t i = 0; i < n && i < 48; i++) { + printf(" %02x", p[i]); + } + printf(n > 48 ? " ...\n" : "\n"); +} + +// SHA-256 of the test certificate's SubjectPublicKeyInfo: what the engine's PIN trust compares +static void pin_of_test_cert(uint8_t pin[TLS_PIN_LEN]) +{ + mbedtls_x509_crt crt; + mbedtls_x509_crt_init(&crt); + if (mbedtls_x509_crt_parse_der(&crt, test_cert_der, sizeof(test_cert_der)) != 0) { + printf("test certificate does not parse\n"); + exit(2); + } + size_t n = 0; + if (psa_hash_compute(PSA_ALG_SHA_256, crt.pk_raw.p, crt.pk_raw.len, pin, TLS_PIN_LEN, &n) != PSA_SUCCESS) { + exit(2); + } + mbedtls_x509_crt_free(&crt); +} + +static int open_client(void) +{ + uint8_t pin[TLS_PIN_LEN], reason = 0; + pin_of_test_cert(pin); + tls_open_params_t p = { .trust = TLS_TRUST_PIN, .opts = 0, .time_source = TLS_TIME_NONE, .pin = pin, .sni = NULL, .sni_len = 0 }; + tls_close_all(); + return tls_open(0, 1, &p, &reason); +} + +static int client_step(const uint8_t *in, int in_len, uint8_t *out, uint16_t *out_len, tls_step_result_t *r) +{ + uint16_t pt = 0; + return tls_step(0, 1, TLS_STEP_NO_READ, in, in_len, NULL, 0, out, out_len, &pt, r); +} + +// ---- the attacker ----------------------------------------------------------------------------------------------- + +// ServerHello per the advisory: legacy_version 0x0304, a TLS 1.3 suite the client offered, and no supported_versions +// (RFC 8446 4.1.3 would make it mandatory). The session id is echoed as a TLS 1.3 server does. Two forms: with no +// extensions at all, and with the extended_master_secret extension, which a real attacker adds because the engine +// refuses a TLS 1.2 ServerHello without it (a second barrier that would otherwise hide the guard under test). +static size_t build_attack_server_hello(const uint8_t *client_hello_record, uint8_t *out, int with_ems) +{ + const uint8_t *ch = client_hello_record + 5; // handshake header, then the body + const uint8_t *body = ch + 4; + uint8_t sid_len = body[2 + 32]; + const uint8_t *sid = body + 2 + 32 + 1; + uint8_t *p = out + 5 + 4; + *p++ = 0x03; *p++ = 0x04; // legacy_version 0x0304 + for (int i = 0; i < 32; i++) { + *p++ = (uint8_t)(0xA0 + i); // random: no downgrade sentinel + } + *p++ = sid_len; + memcpy(p, sid, sid_len); p += sid_len; + *p++ = 0x13; *p++ = 0x01; // TLS_AES_128_GCM_SHA256, in the client's list + *p++ = 0x00; // compression null + if (with_ems) { // extensions: extended_master_secret only, which the engine's TLS 1.2 + *p++ = 0x00; *p++ = 0x04; // checks demand (tls_note_handshake); still no supported_versions + *p++ = 0x00; *p++ = 0x17; *p++ = 0x00; *p++ = 0x00; + } // else nothing follows: no extensions at all + size_t hs_len = (size_t)(p - (out + 5 + 4)); + out[5] = 2; out[6] = 0; out[7] = (uint8_t)(hs_len >> 8); out[8] = (uint8_t)hs_len; + size_t rec_len = hs_len + 4; + out[0] = 22; out[1] = 3; out[2] = 3; out[3] = (uint8_t)(rec_len >> 8); out[4] = (uint8_t)rec_len; + return rec_len + 5; +} + +// Without the guard: shows that the TLS 1.3 machine takes a plaintext TLS 1.3 Certificate (the attacker holds the pinned +// key here, as the intended server would) and moves on to CertificateVerify, with no key exchange behind it. The +// handshake is not established by this: see test_second_barrier for how it ends. +static void observe_certificate_path(void) +{ + uint8_t msg[5 + 4 + 1 + 3 + 3 + sizeof(test_cert_der) + 2], out[TLS_STEP_OUT_MAX]; + size_t cl = sizeof(test_cert_der), hl = 1 + 3 + 3 + cl + 2; + uint8_t *p = msg; + *p++ = 22; *p++ = 3; *p++ = 3; *p++ = (uint8_t)((hl + 4) >> 8); *p++ = (uint8_t)(hl + 4); + *p++ = 11; *p++ = 0; *p++ = (uint8_t)(hl >> 8); *p++ = (uint8_t)hl; + *p++ = 0; // certificate_request_context + size_t ll = 3 + cl + 2; + *p++ = 0; *p++ = (uint8_t)(ll >> 8); *p++ = (uint8_t)ll; // certificate_list + *p++ = 0; *p++ = (uint8_t)(cl >> 8); *p++ = (uint8_t)cl; + memcpy(p, test_cert_der, cl); p += cl; + *p++ = 0; *p++ = 0; // no entry extensions + uint16_t out_len = 0; + tls_step_result_t r; + int ret = client_step(msg, (int)(p - msg), out, &out_len, &r); + printf(" OBSERVED without the guard: a plaintext TLS 1.3 Certificate from the attacker: ret=%d state=%d fail_reason=%d, ", ret, r.state, r.fail_reason); + if (sessions[0]) { + printf("ssl.state now %d (%s)\n", sessions[0]->ssl.state, + (sessions[0]->ssl.state == MBEDTLS_SSL_CERTIFICATE_VERIFY && !sessions[0]->pin_mismatch) ? "CERTIFICATE_VERIFY: the certificate was taken, PIN matched" : "?"); + } else { + printf("session freed\n"); + } +} + +static void test_attack(int with_ems) +{ + uint8_t ch[TLS_STEP_OUT_MAX], sh[256], out[TLS_STEP_OUT_MAX]; + uint16_t ch_len = 0, out_len = 0; + tls_step_result_t r; + printf("attack%s: ServerHello, legacy_version 0x0304, suite 0x1301, no supported_versions%s\n", with_ems ? " B" : " A", + with_ems ? ", with extended_master_secret" : ", no extensions"); + CHECK(open_client() == ESP_OK, "client opened (TLS 1.2 + 1.3 offered, PIN trust)"); + int ret = client_step(NULL, 0, ch, &ch_len, &r); + CHECK(ret == 0 && ch_len > 5 && ch[0] == 22 && ch[5] == 1, "ClientHello produced (%u bytes)", ch_len); + size_t sh_len = build_attack_server_hello(ch, sh, with_ems); + hexline("attack ServerHello record", sh, sh_len); + + ret = client_step(sh, (int)sh_len, out, &out_len, &r); + printf(" client result: ret=%d (-0x%04x) state=%d fail_reason=%d verify_flags=0x%x alert_out=%d alert_in=%d\n", ret, + (unsigned)(ret < 0 ? -ret : ret), r.state, r.fail_reason, (unsigned)r.verify_flags, r.alert_out, r.alert_in); + hexline("client output", out, out_len); + if (sessions[0]) { + // Only without the guard (and on an unfixed library). mbedTLS now runs its TLS 1.3 machine on a connection that + // never had a key exchange; the handshake is not over, and does not end ESTABLISHED (see test_second_barrier). + printf(" OBSERVED without the guard: the session is still live, ssl.tls_version=0x%04x, ssl.state=%d%s, handshake_over=%d\n", + (unsigned)sessions[0]->ssl.tls_version, sessions[0]->ssl.state, + sessions[0]->ssl.state == MBEDTLS_SSL_SERVER_CERTIFICATE ? " (SERVER_CERTIFICATE: EncryptedExtensions skipped)" : "", + mbedtls_ssl_is_handshake_over(&sessions[0]->ssl)); + observe_certificate_path(); + } + CHECK(ret == MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION, "step returns BAD_PROTOCOL_VERSION (got %d)", ret); + CHECK(r.state == TLS_STATE_FAILED, "session state FAILED (got %d)", r.state); + CHECK(r.fail_reason == TLS_FAIL_VERSION_REFUSED, "fail_reason TLS_FAIL_VERSION_REFUSED = Ultimate status 18 (got %d)", r.fail_reason); + CHECK((r.verify_flags & 0xFFFF) == 0x0304, "version reported is 0x0304 (got 0x%x)", (unsigned)(r.verify_flags & 0xFFFF)); + static const uint8_t alert[] = { 0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x46 }; // fatal protocol_version + CHECK(r.alert_out == 0x46, "engine reports the unencrypted fatal alert it sent: protocol_version (got %d)", r.alert_out); + CHECK(out_len == sizeof(alert) && !memcmp(out, alert, sizeof(alert)), "the alert record is on the wire to the peer"); + CHECK(sessions[0] == NULL, "session freed"); +} + +// ---- the honest servers (controls) ------------------------------------------------------------------------------ + +typedef struct { uint8_t b[16384]; size_t n; } queue_t; +static queue_t to_client, to_server; + +static int srv_send(void *ctx, const unsigned char *buf, size_t len) +{ + (void)ctx; + memcpy(to_client.b + to_client.n, buf, len); + to_client.n += len; + return (int)len; +} + +static int srv_recv(void *ctx, unsigned char *buf, size_t len) +{ + (void)ctx; + if (to_server.n == 0) { + return MBEDTLS_ERR_SSL_WANT_READ; + } + size_t n = len < to_server.n ? len : to_server.n; + memcpy(buf, to_server.b, n); + memmove(to_server.b, to_server.b + n, to_server.n - n); + to_server.n -= n; + return (int)n; +} + +// min/max: the server's TLS versions; groups: its supported groups (NULL: the default, so no HelloRetryRequest); +// want_version/want_group: what the client must report (group 0: only that one is set) +static void test_honest(const char *name, int min_v, int max_v, const uint16_t *groups, uint16_t want_version, uint16_t want_group) +{ + printf("control: honest %s server\n", name); + mbedtls_ssl_context srv; + mbedtls_ssl_config conf; + mbedtls_x509_crt crt; + mbedtls_pk_context pk; + mbedtls_ssl_init(&srv); mbedtls_ssl_config_init(&conf); mbedtls_x509_crt_init(&crt); mbedtls_pk_init(&pk); + int ok = (mbedtls_x509_crt_parse_der(&crt, test_cert_der, sizeof(test_cert_der)) == 0) && + (mbedtls_pk_parse_key(&pk, test_key_der, sizeof(test_key_der), NULL, 0) == 0) && + (mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_SERVER, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) == 0); + if (ok) { + mbedtls_ssl_conf_min_tls_version(&conf, min_v); + mbedtls_ssl_conf_max_tls_version(&conf, max_v); + if (groups) { + mbedtls_ssl_conf_groups(&conf, groups); + } + ok = (mbedtls_ssl_conf_own_cert(&conf, &crt, &pk) == 0) && (mbedtls_ssl_setup(&srv, &conf) == 0); + } + CHECK(ok, "server set up"); + mbedtls_ssl_set_bio(&srv, NULL, srv_send, srv_recv, NULL); + to_client.n = to_server.n = 0; + CHECK(open_client() == ESP_OK, "client opened"); + + uint8_t out[TLS_STEP_OUT_MAX]; + uint16_t out_len; + tls_step_result_t r = { .state = TLS_STATE_HANDSHAKING }; + int ret = 0; + for (int i = 0; ok && i < 60 && r.state == TLS_STATE_HANDSHAKING && ret == 0; i++) { + int n = to_client.n < TLS_STEP_IN_MAX ? (int)to_client.n : TLS_STEP_IN_MAX; + ret = client_step(to_client.b, n, out, &out_len, &r); + memmove(to_client.b, to_client.b + n, to_client.n - n); + to_client.n -= n; + memcpy(to_server.b + to_server.n, out, out_len); + to_server.n += out_len; + int sret; + do { + sret = mbedtls_ssl_handshake(&srv); + } while (sret == 0 && !mbedtls_ssl_is_handshake_over(&srv) && to_server.n); + } + CHECK(ret == 0 && r.state == TLS_STATE_ESTABLISHED, "client ESTABLISHED (ret=%d state=%d fail_reason=%d)", ret, r.state, r.fail_reason); + tls_session_stats_t st; + memset(&st, 0, sizeof(st)); + if (tls_get_stats(0, 1, &st) == ESP_OK) { + CHECK(st.tls_version == want_version, "negotiated version 0x%04x (want 0x%04x)", st.tls_version, want_version); + CHECK(want_group ? st.group == want_group : st.group != 0, "negotiated group 0x%04x%s", st.group, want_group ? "" : " (not 0)"); + printf(" suite 0x%04x group 0x%04x\n", st.ciphersuite, st.group); + } + tls_close_all(); + mbedtls_ssl_free(&srv); mbedtls_ssl_config_free(&conf); mbedtls_x509_crt_free(&crt); mbedtls_pk_free(&pk); +} + +// ---- which library is linked ------------------------------------------------------------------------------------- + +static uint8_t probe_out[TLS_STEP_OUT_MAX * 2]; +static size_t probe_out_n; +static const uint8_t *probe_in; +static size_t probe_in_n; + +static int probe_send(void *ctx, const unsigned char *buf, size_t len) +{ + (void)ctx; + memcpy(probe_out + probe_out_n, buf, len); + probe_out_n += len; + return (int)len; +} + +static int probe_recv(void *ctx, unsigned char *buf, size_t len) +{ + (void)ctx; + if (probe_in_n == 0) { + return MBEDTLS_ERR_SSL_WANT_READ; + } + size_t n = len < probe_in_n ? len : probe_in_n; + memcpy(buf, probe_in, n); + probe_in += n; + probe_in_n -= n; + return (int)n; +} + +// Sends the attack ServerHello to a bare Mbed TLS client (TLS 1.2 + 1.3, no engine) and returns 1 when the library +// itself refuses it (BAD_PROTOCOL_VERSION: the upstream fix), 0 when it takes it (4.1.1: only the guard stops it) +static int library_refuses_first(void) +{ + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + mbedtls_ssl_init(&ssl); mbedtls_ssl_config_init(&conf); + int ok = (mbedtls_ssl_config_defaults(&conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) == 0); + if (ok) { + mbedtls_ssl_conf_authmode(&conf, MBEDTLS_SSL_VERIFY_NONE); + ok = (mbedtls_ssl_setup(&ssl, &conf) == 0); + } + int ret = -1; + for (int i = 0; ok && i < 10 && ssl.state != MBEDTLS_SSL_SERVER_HELLO; i++) { + mbedtls_ssl_set_bio(&ssl, NULL, probe_send, probe_recv, NULL); + ret = mbedtls_ssl_handshake_step(&ssl); + ok = (ret == 0); + } + uint8_t sh[256]; + if (ok && mbedtls_ssl_flush_output(&ssl) != 0) { // the ClientHello is sent by the next step: flush it + ok = 0; + } + if (ok && probe_out_n > 9 && probe_out[0] == 22 && probe_out[5] == 1) { + probe_in_n = build_attack_server_hello(probe_out, sh, 1); + probe_in = sh; + // the first step may only switch from the TLS 1.3 to the TLS 1.2 parser (no supported_versions): step on + for (int i = 0; i < 4 && ret == 0 && ssl.state == MBEDTLS_SSL_SERVER_HELLO; i++) { + ret = mbedtls_ssl_handshake_step(&ssl); + } + } else { + ok = 0; + } + mbedtls_ssl_free(&ssl); mbedtls_ssl_config_free(&conf); + if (!ok || (ret != 0 && ret != MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION)) { + printf("library probe inconclusive (ret=-0x%04x)\n", (unsigned)(ret < 0 ? -ret : ret)); + exit(2); + } + return ret == MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION; +} + +// ---- the second barrier (guard-disabled build only) ------------------------------------------------------------- + +// Drives the attack as far as it goes, as an attacker that holds the pinned key and computes Finished from the client's +// own key schedule (public: no key exchange went into it). Then the engine's end-of-handshake check must refuse. +static void test_second_barrier(void) +{ + uint8_t ch[TLS_STEP_OUT_MAX], sh[256], out[TLS_STEP_OUT_MAX], msg[2048]; + uint16_t ch_len = 0, out_len = 0; + tls_step_result_t r; + printf("second barrier (guard disabled): the full attack, ServerHello B then Certificate, CertificateVerify, Finished\n"); + CHECK(open_client() == ESP_OK, "client opened"); + int ret = client_step(NULL, 0, ch, &ch_len, &r); + CHECK(ret == 0 && ch_len > 5 && ch[0] == 22 && ch[5] == 1, "ClientHello produced (%u bytes)", ch_len); + size_t sh_len = build_attack_server_hello(ch, sh, 1); + ret = client_step(sh, (int)sh_len, out, &out_len, &r); + CHECK(ret == 0 && sessions[0], "ServerHello accepted (ret=%d): this is the guard-disabled build", ret); + if (ret != 0 || !sessions[0]) { + return; + } + CHECK(sessions[0]->ssl.tls_version == MBEDTLS_SSL_VERSION_TLS1_3, "mbedTLS is in its TLS 1.3 machine (0x%04x)", (unsigned)sessions[0]->ssl.tls_version); + mbedtls_ssl_context *ssl = &sessions[0]->ssl; + + size_t cl = sizeof(test_cert_der), hl = 1 + 3 + 3 + cl + 2, ll = 3 + cl + 2; + uint8_t *p = msg; + *p++ = 22; *p++ = 3; *p++ = 3; *p++ = (uint8_t)((hl + 4) >> 8); *p++ = (uint8_t)(hl + 4); + *p++ = 11; *p++ = 0; *p++ = (uint8_t)(hl >> 8); *p++ = (uint8_t)hl; *p++ = 0; + *p++ = 0; *p++ = (uint8_t)(ll >> 8); *p++ = (uint8_t)ll; + *p++ = 0; *p++ = (uint8_t)(cl >> 8); *p++ = (uint8_t)cl; + memcpy(p, test_cert_der, cl); p += cl; + *p++ = 0; *p++ = 0; + ret = client_step(msg, (int)(p - msg), out, &out_len, &r); + CHECK(ret == 0 && sessions[0], "Certificate accepted (PIN matched), ret=%d", ret); + if (ret != 0 || !sessions[0]) { + return; + } + + // CertificateVerify over the client's own transcript hash + uint8_t th[32], tbs[64 + 33 + 1 + 32], hash[32], sig[128]; + size_t thl = 0, sl = 0, hn = 0; + mbedtls_pk_context pk; + mbedtls_pk_init(&pk); + memset(tbs, 0x20, 64); memcpy(tbs + 64, "TLS 1.3, server CertificateVerify", 33); tbs[97] = 0; + int ok = (mbedtls_ssl_get_handshake_transcript(ssl, MBEDTLS_MD_SHA256, th, sizeof(th), &thl) == 0) && (thl == 32); + memcpy(tbs + 98, th, 32); + ok = ok && (psa_hash_compute(PSA_ALG_SHA_256, tbs, sizeof(tbs), hash, 32, &hn) == PSA_SUCCESS) && + (mbedtls_pk_parse_key(&pk, test_key_der, sizeof(test_key_der), NULL, 0) == 0) && + (mbedtls_pk_sign(&pk, MBEDTLS_MD_SHA256, hash, 32, sig, sizeof(sig), &sl) == 0); + mbedtls_pk_free(&pk); + CHECK(ok, "attacker signed the CertificateVerify"); + if (!ok) { + return; + } + hl = 2 + 2 + sl; + p = msg; + *p++ = 22; *p++ = 3; *p++ = 3; *p++ = (uint8_t)((hl + 4) >> 8); *p++ = (uint8_t)(hl + 4); + *p++ = 15; *p++ = 0; *p++ = (uint8_t)(hl >> 8); *p++ = (uint8_t)hl; *p++ = 4; *p++ = 3; *p++ = (uint8_t)(sl >> 8); *p++ = (uint8_t)sl; + memcpy(p, sig, sl); p += sl; + ret = client_step(msg, (int)(p - msg), out, &out_len, &r); + CHECK(ret == 0 && sessions[0], "CertificateVerify accepted, ret=%d", ret); + if (ret != 0 || !sessions[0]) { + return; + } + + // Finished, from the client's own key schedule + uint8_t vd[64]; + size_t vl = 0; + ok = (mbedtls_ssl_tls13_calculate_verify_data(ssl, vd, sizeof(vd), &vl, MBEDTLS_SSL_IS_SERVER) == 0) && (vl <= 48); + CHECK(ok, "attacker computed the Finished verify data (%u bytes)", (unsigned)vl); + if (!ok) { + return; + } + CHECK(sessions[0]->stats.group == 0, "no negotiated group was ever recorded (group 0x%04x)", sessions[0]->stats.group); + p = msg; + *p++ = 22; *p++ = 3; *p++ = 3; *p++ = (uint8_t)((vl + 4) >> 8); *p++ = (uint8_t)(vl + 4); + *p++ = 20; *p++ = 0; *p++ = 0; *p++ = (uint8_t)vl; + memcpy(p, vd, vl); p += vl; + ret = client_step(msg, (int)(p - msg), out, &out_len, &r); + printf(" client result: ret=%d (-0x%04x) state=%d fail_reason=%d\n", ret, (unsigned)(ret < 0 ? -ret : ret), r.state, r.fail_reason); + CHECK(ret == MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE, "end of the handshake refused: 'Negotiated group not found' (got %d)", ret); + CHECK(strstr(tlsguard_last_error, "Negotiated group not found") != NULL, "the engine logged: %s", tlsguard_last_error); + CHECK(r.state == TLS_STATE_FAILED && r.state != TLS_STATE_ESTABLISHED, "session FAILED, never ESTABLISHED (state %d)", r.state); + CHECK(r.fail_reason == 0, "no specific reason: this is the late, generic refusal, not the guard's (got %d)", r.fail_reason); + CHECK(sessions[0] == NULL, "session freed"); +} + +int main(int argc, char **argv) +{ + int barrier = (argc > 1) && !strcmp(argv[1], "barrier"); + tlsguard_verbose = (argc > 1) && !strcmp(argv[1], "-v"); + printf("Mbed TLS %s\n", MBEDTLS_VERSION_STRING); + if (psa_crypto_init() != PSA_SUCCESS) { + return 2; + } + int lib_first = library_refuses_first(); + if (lib_first) { + printf("case: library refuses first (the linked Mbed TLS refuses the ServerHello itself; the guard is not reached)\n"); + } else { + printf("case: engine guard refuses (the linked Mbed TLS accepts the ServerHello; only the guard stops it)\n"); + } + if (barrier) { + if (lib_first) { + printf("second barrier: not applicable: library refuses first\n"); + return 0; + } + test_second_barrier(); + } else { + static const uint16_t g384[] = { MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1, MBEDTLS_SSL_IANA_TLS_GROUP_NONE }; + test_honest("TLS 1.2", MBEDTLS_SSL_VERSION_TLS1_2, MBEDTLS_SSL_VERSION_TLS1_2, NULL, 0x0303, 0); + test_honest("TLS 1.3", MBEDTLS_SSL_VERSION_TLS1_3, MBEDTLS_SSL_VERSION_TLS1_3, NULL, 0x0304, 0); + test_honest("TLS 1.3 with HelloRetryRequest (secp384r1 only)", MBEDTLS_SSL_VERSION_TLS1_3, MBEDTLS_SSL_VERSION_TLS1_3, g384, 0x0304, 0x0018); + test_honest("dual TLS 1.2 + 1.3", MBEDTLS_SSL_VERSION_TLS1_2, MBEDTLS_SSL_VERSION_TLS1_3, NULL, 0x0304, 0); + test_attack(1); + test_attack(0); + } + printf("%s (%d failed checks)\n", failures ? "FAIL" : "PASS", failures); + return failures ? 1 : 0; +} diff --git a/software/test/tls_engine/tlsguard_mbedtls_config.h b/software/test/tls_engine/tlsguard_mbedtls_config.h new file mode 100644 index 000000000..1d0558867 --- /dev/null +++ b/software/test/tls_engine/tlsguard_mbedtls_config.h @@ -0,0 +1,4 @@ +/* MBEDTLS_USER_CONFIG_FILE for the host build of the engine test: Mbed TLS 4.1.1's default configuration, with the one + * option tls_engine.c refuses ("Renegotiation must stay off") that the default turns on. Library and test must be + * built with the same file. */ +#undef MBEDTLS_SSL_RENEGOTIATION diff --git a/software/test/wifi_app/boot_test.cc b/software/test/wifi_app/boot_test.cc new file mode 100644 index 000000000..85753ea22 --- /dev/null +++ b/software/test/wifi_app/boot_test.cc @@ -0,0 +1,36 @@ +/* + * boot_test.cc + * + * The U64-II / C64 Ultimate's WiFi application when it finds its module (see + * wifi_app_script.h). + * + * CASES_FOR: U64=2 + */ + +#include "wifi_app_script.h" + +#if U64 == 2 +// The U64-II / C64 Ultimate reads the input voltage when it finds its module: a module that +// has no reading to give says so, and that is not a low voltage +static void voltages_at_boot(void) +{ + voltages_result = 0x107; + boot(true, 0, NULL, 0); + CHECK(strchr(rlog, '!') == NULL, "no reading: no Low input voltage"); + voltages_result = 0; + voltages_vbus = 7000; + boot(true, 0, NULL, 0); + CHECK(strchr(rlog, '!') != NULL, "a low reading: the message"); + voltages_vbus = 9000; + boot(true, 0, NULL, 0); + CHECK(strchr(rlog, '!') == NULL, "a good reading: none"); +} +#endif + + +void run_cases(void) +{ +#if U64 == 2 + voltages_at_boot(); +#endif +} diff --git a/software/test/wifi_dedicated/check.cc b/software/test/wifi_dedicated/check.cc new file mode 100644 index 000000000..7a0c51e18 --- /dev/null +++ b/software/test/wifi_dedicated/check.cc @@ -0,0 +1,22 @@ +// check.cc: see check.h. +#include +#include "check.h" + +int failures; +int checks; + +void check(bool condition, const char *what, ...) +{ + char line[300]; + va_list ap; + va_start(ap, what); + vsnprintf(line, sizeof(line), what, ap); + va_end(ap); + checks++; + if (!condition) { + failures++; + printf(" FAIL %s\n", line); + } else { + printf(" ok %s\n", line); + } +} diff --git a/software/test/wifi_dedicated/check.h b/software/test/wifi_dedicated/check.h new file mode 100644 index 000000000..bca1b8d11 --- /dev/null +++ b/software/test/wifi_dedicated/check.h @@ -0,0 +1,8 @@ +#ifndef CHECK_H_ +#define CHECK_H_ +#include +extern int failures; +extern int checks; +// Counts one check and prints it: "ok" or "FAIL". +void check(bool condition, const char *what, ...); +#endif diff --git a/software/test/wifi_dedicated/stub/FreeRTOS.h b/software/test/wifi_dedicated/stub/FreeRTOS.h new file mode 100644 index 000000000..44ddca460 --- /dev/null +++ b/software/test/wifi_dedicated/stub/FreeRTOS.h @@ -0,0 +1,17 @@ +// Host stand-in for FreeRTOS.h: the types and macros the code under test uses. +#ifndef FREERTOS_H_STUB +#define FREERTOS_H_STUB +#include +#include +typedef uint32_t TickType_t; +typedef long BaseType_t; +typedef unsigned long UBaseType_t; +typedef void *QueueHandle_t; +typedef void *TaskHandle_t; +#define pdTRUE 1 +#define pdFALSE 0 +#define configTICK_RATE_HZ 200 +#define portTICK_PERIOD_MS (1000 / configTICK_RATE_HZ) +// As in software/FreeRTOS/Source/include/projdefs.h. +#define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) +#endif diff --git a/software/test/wifi_dedicated/stub/queue.h b/software/test/wifi_dedicated/stub/queue.h new file mode 100644 index 000000000..cb7604eb5 --- /dev/null +++ b/software/test/wifi_dedicated/stub/queue.h @@ -0,0 +1,5 @@ +#ifndef QUEUE_H_STUB +#define QUEUE_H_STUB +#include "FreeRTOS.h" +BaseType_t xQueueReceive(QueueHandle_t queue, void *item, TickType_t ticks); +#endif diff --git a/software/test/wifi_dedicated/stub/task.h b/software/test/wifi_dedicated/stub/task.h new file mode 100644 index 000000000..a6408e654 --- /dev/null +++ b/software/test/wifi_dedicated/stub/task.h @@ -0,0 +1,8 @@ +#ifndef TASK_H_STUB +#define TASK_H_STUB +#include "FreeRTOS.h" +TickType_t xTaskGetTickCount(void); +void vTaskSuspendAll(void); +BaseType_t xTaskResumeAll(void); +void vTaskDelay(TickType_t ticks); +#endif diff --git a/software/test/wifi_dedicated/stub/wifi_cmd.h b/software/test/wifi_dedicated/stub/wifi_cmd.h new file mode 100644 index 000000000..9548c8170 --- /dev/null +++ b/software/test/wifi_dedicated/stub/wifi_cmd.h @@ -0,0 +1,51 @@ +// Host stand-in for software/io/wifi/wifi_cmd.h: only what wifi_dedicated.cc +// uses, backed by world.cc. Keep the declarations in step with the real header. +#ifndef WIFI_CMD_H_ +#define WIFI_CMD_H_ + +#include +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "rpc_calls.h" +extern "C" { + #include "cmd_buffer.h" +} + +class DmaUART +{ +public: + volatile uint32_t generation; + BaseType_t GetBuffer(command_buf_t **buf, TickType_t ticks); + BaseType_t TransmitPacket(command_buf_t *buf, uint16_t *ms = NULL); + BaseType_t FreeBuffer(command_buf_t *buf); +}; + +class Esp32 +{ +public: + DmaUART *uart; +}; +extern Esp32 esp32; + +extern uint16_t sequence_nr; +extern const char *no_wifi_buf; + +#define WIFI_DEDICATED_THREAD 0xFC +typedef struct { + command_buf_t *buf; + uint32_t generation; +} dedicated_reply_t; +extern QueueHandle_t dedicated_replies; +extern volatile bool dedicated_waiting; + +void world_enter_safe(void); +void world_leave_safe(void); +#define ENTER_SAFE_SECTION world_enter_safe() +#define LEAVE_SAFE_SECTION world_leave_safe() + +// Everything the code under test prints goes into the trace. +int world_printf(const char *fmt, ...); +#define printf world_printf + +#endif /* WIFI_CMD_H_ */ diff --git a/software/test/wifi_dedicated/wifi_dedicated_test.cc b/software/test/wifi_dedicated/wifi_dedicated_test.cc new file mode 100644 index 000000000..543177026 --- /dev/null +++ b/software/test/wifi_dedicated/wifi_dedicated_test.cc @@ -0,0 +1,411 @@ +// Host test of wifi_dedicated.cc: GET_RANDOM through the dedicated channel, and +// the channel's own waits, in the scripted world of world.cc. +// make -C target/pc/linux/wifidedicated test +#include +#include +#include +#include "world.h" +#include "wifi_dedicated.h" +#include "wifi_random.h" +#include "check.h" +#undef printf + +// The replies random_maker builds. 0 to 3 are the right answer. +enum { + RIGHT = 0, + LATE = 4, // the answer to the previous request + OTHER_COMMAND = 5, // the answer to another command + REFUSED = 6, // esp_err set, no bytes + NO_SOURCE = 7, // bytes, but no entropy source + TRUNCATED = 8, // cut short at a random size + LONGER = 9, // one byte more than asked for + SHORT = 10, // one byte missing; scripts only +}; + +// The bytes of every right answer made in this world, by sequence number. +struct made_t { + uint16_t sequence; + std::vector data; +}; +static std::vector made; + +static void random_maker(command_buf_t *rx, const uint8_t *req, int req_size, int kind) +{ + const rpc_get_random_req *request = (const rpc_get_random_req *)req; + uint16_t sequence = (req_size >= 0) ? request->hdr.sequence : (uint16_t)world_rand(65536); + uint16_t len = (req_size >= 0) ? request->length : 32; + if (len > RANDOM_MAX_BYTES) { + len = RANDOM_MAX_BYTES; + } + rpc_get_random_resp *r = (rpc_get_random_resp *)rx->data; + memset(rx->data, 0, sizeof(rx->data)); + r->hdr.command = CMD_GET_RANDOM; + r->hdr.thread = WIFI_DEDICATED_THREAD; + r->hdr.sequence = sequence; + r->esp_err = 0; + r->source = ENTROPY_RADIO; + r->length = len; + for (int i = 0; i < len; i++) { + r->data[i] = (uint8_t)world_rand(256); + } + rx->size = sizeof(rpc_get_random_resp) + len; + switch (kind) { + case LATE: r->hdr.sequence = sequence - 1; break; + case OTHER_COMMAND: r->hdr.command = (uint8_t)(CMD_GET_RANDOM + 1 + world_rand(255)); break; + case REFUSED: r->esp_err = 0x103; r->length = 0; rx->size = sizeof(rpc_get_random_resp); break; + case NO_SOURCE: r->source = ENTROPY_NONE; break; + case TRUNCATED: rx->size = world_rand(sizeof(rpc_get_random_resp) + len); break; + case LONGER: r->length = len + 1; break; + case SHORT: rx->size--; break; + default: made.push_back({ sequence, std::vector(r->data, r->data + len) }); break; + } +} + +static int count(const std::string &text, const std::string &what) +{ + int n = 0; + for (size_t at = text.find(what); at != std::string::npos; at = text.find(what, at + 1)) { + n++; + } + return n; +} + +static bool printed(const char *line) +{ + return world_trace.find(std::string("print: ") + line) != std::string::npos; +} + +// The right answer made for sequence, if its bytes are those at buf. +static bool from_right_answer(uint16_t sequence, const uint8_t *buf, uint16_t len) +{ + for (const made_t &m : made) { + if ((m.sequence == sequence) && (m.data.size() == len) && (memcmp(m.data.data(), buf, len) == 0)) { + return true; + } + } + return false; +} + +// A script step: kinds arriving delay ticks into the wait. +static world_step_t at(TickType_t delay, std::initializer_list kinds, bool stale = false, + TickType_t preempt = 0) +{ + world_step_t s; + memset(&s, 0, sizeof(s)); + s.delay = delay; + s.preempt = preempt; + for (int kind : kinds) { + s.stale[s.count] = stale; + s.kind[s.count++] = kind; + } + return s; +} + +#define UNTOUCHED 0xEE +#define WAIT_TICKS 40 // GET_RANDOM's 200 ms + +typedef struct { + int result; + uint16_t sequence; // the request's, if one was sent + uint16_t advanced; // how far sequence_nr moved + uint8_t buf[RANDOM_MAX_BYTES + 8]; +} outcome_t; + +static void get_random(uint16_t len, outcome_t *o) +{ + memset(o->buf, UNTOUCHED, sizeof(o->buf)); + o->sequence = sequence_nr; + o->result = wifi_get_random(o->buf, len); + o->advanced = (uint16_t)(sequence_nr - o->sequence); +} + +static bool untouched(const outcome_t *o) +{ + for (size_t i = 0; i < sizeof(o->buf); i++) { + if (o->buf[i] != UNTOUCHED) { + return false; + } + } + return true; +} + +static bool channel_free(void) +{ + return !dedicated_waiting && (world_queued() == 0) && (world_suspended == 0) && + (world_trace.find("not suspended") == std::string::npos); +} + +// One GET_RANDOM of 32 bytes in a calm world that answers with steps. +static void scripted(uint32_t seed, const world_step_t *steps, int n, outcome_t *o) +{ + made.clear(); + world_reset(seed, random_maker, true); + world_script(steps, n); + get_random(32, o); +} + +static void test_answers(void) +{ + printf("GET_RANDOM: what each reply leads to\n"); + outcome_t o; + const world_step_t right[] = { at(1, { RIGHT }) }; + scripted(1, right, 1, &o); + check((o.result == 0) && from_right_answer(o.sequence, o.buf, 32) && + (o.buf[32] == UNTOUCHED) && (o.advanced == 1) && channel_free(), + "the answer: 0, its 32 bytes and nothing past them, the sequence number moved on by one"); + + struct { + int kind; + int result; + const char *line; + const char *what; + } const single[] = { + { LATE, WIFI_RANDOM_BUSY, "Get Random: no reply.", "an answer to the previous request is skipped: BUSY" }, + { OTHER_COMMAND, WIFI_RANDOM_BUSY, "Get Random: no reply.", "an answer to another command is skipped: BUSY" }, + { REFUSED, WIFI_RANDOM_REFUSED, "Get Random failed (2). Size: 12. Error: 259.", "a refusal: REFUSED" }, + { NO_SOURCE, WIFI_RANDOM_REFUSED, "Get Random failed (2). Size: 44. Error: 0.", "bytes without a source: REFUSED" }, + { LONGER, WIFI_RANDOM_INVALID, "Get Random failed (3). Size: 44. Error: 0.", "one byte too many: INVALID" }, + { SHORT, WIFI_RANDOM_INVALID, "Get Random failed (3). Size: 43. Error: 0.", "one byte missing: INVALID" }, + }; + for (const auto &c : single) { + const world_step_t step[] = { at(1, { c.kind }) }; + scripted(2, step, 1, &o); + check((o.result == c.result) && untouched(&o) && printed(c.line) && (o.advanced == 1) && channel_free(), + "%s, no bytes, logged", c.what); + } + + const world_step_t stale[] = { at(1, { RIGHT }, true) }; + scripted(3, stale, 1, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && (count(world_trace, "free b") == 0) && channel_free(), + "the answer queued before a pool reset is dropped unread and not freed: BUSY"); + const world_step_t foreign_first[] = { at(1, { LATE, RIGHT }) }; + scripted(4, foreign_first, 1, &o); + check((o.result == 0) && from_right_answer(o.sequence, o.buf, 32) && channel_free(), + "a late answer, then the answer, in one wait: the answer is taken"); + const world_step_t two_waits[] = { at(5, { OTHER_COMMAND }), at(10, { RIGHT }) }; + scripted(5, two_waits, 2, &o); + check((o.result == 0) && from_right_answer(o.sequence, o.buf, 32) && (count(world_trace, "receive ") == 3), + "another command's answer, then the answer 10 ticks later: taken in the second wait"); + const world_step_t too_late[] = { at(WAIT_TICKS + 1, { RIGHT }) }; + scripted(6, too_late, 1, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && printed("Get Random: no reply.") && channel_free(), + "an answer after 200 ms: BUSY"); + + const world_step_t overshoot[] = { at(WAIT_TICKS - 1, { OTHER_COMMAND }, false, 5) }; + scripted(11, overshoot, 1, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && (world_wait_span <= WAIT_TICKS) && + (count(world_trace, "receive 0") == 1) && channel_free(), + "a skipped reply just before the deadline, then preempted past it: BUSY, no wait beyond 200 ms " + "(%llu ticks)", (unsigned long long)world_wait_span); + const world_step_t skipped_early[] = { at(10, { OTHER_COMMAND }) }; + scripted(12, skipped_early, 1, &o); + check((o.result == WIFI_RANDOM_BUSY) && (world_wait_span == WAIT_TICKS) && channel_free(), + "a reply skipped 10 ticks in: the wait goes on to the deadline, not 200 ms past the skip (%llu ticks)", + (unsigned long long)world_wait_span); + + // The wait ends on a skipped reply with the timeout spent; what is still + // queued behind it decides the result. + const world_step_t tail_right[] = { at(WAIT_TICKS, { OTHER_COMMAND, RIGHT }) }; + scripted(7, tail_right, 1, &o); + check((o.result == 0) && from_right_answer(o.sequence, o.buf, 32) && channel_free(), + "the answer queued behind a skipped reply as the time runs out is still taken"); + const world_step_t tail_foreign[] = { at(WAIT_TICKS, { OTHER_COMMAND, LATE }) }; + scripted(8, tail_foreign, 1, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && printed("Get Random: no reply.") && channel_free(), + "only foreign replies queued as the time runs out: BUSY, not FOREIGN (%d)", o.result); + const world_step_t tail_refused[] = { at(WAIT_TICKS, { OTHER_COMMAND, REFUSED }) }; + scripted(9, tail_refused, 1, &o); + check((o.result == WIFI_RANDOM_REFUSED) && untouched(&o) && channel_free(), + "a refusal queued behind a skipped reply as the time runs out: REFUSED"); + const world_step_t burst[] = { at(1, { RIGHT, RIGHT, RIGHT, RIGHT }) }; + scripted(10, burst, 1, &o); + check((o.result == 0) && (count(world_trace, "free b") == 4) && channel_free(), + "a burst of four: the first is taken, the other three released, all freed"); +} + +static void test_orderings(void) +{ + printf("GET_RANDOM: the deadline and the claim, around the queue\n"); + outcome_t o; + const world_step_t nothing[] = { at(100000, {}) }; + made.clear(); + world_reset(13, random_maker, true); + world_script(nothing, 1); + world_transmit_ticks = 30; + get_random(32, &o); + check((o.result == WIFI_RANDOM_BUSY) && (world_wait_span == WAIT_TICKS) && channel_free(), + "a request that takes 150 ms to queue still waits 200 ms from then (%llu ticks)", + (unsigned long long)world_wait_span); + made.clear(); + world_reset(14, random_maker, true); + world_script(nothing, 1); + world_late_after_poll = 1; + get_random(32, &o); + check((o.result == WIFI_RANDOM_BUSY) && channel_free(), + "a reply arriving as the queue is drained finds the claim released: nothing is left queued"); +} + +static void test_sequence(void) +{ + printf("GET_RANDOM: the request and its sequence number\n"); + made.clear(); + world_reset(20, random_maker, true); + uint16_t first = sequence_nr; + outcome_t a, b; + get_random(300, &a); + std::string request = world_trace.substr(world_trace.find("transmit")); + char want[64]; + snprintf(want, sizeof(want), "transmit 6: %02x %02x %02x %02x 2c 01\n", CMD_GET_RANDOM, + WIFI_DEDICATED_THREAD, first & 0xFF, first >> 8); + check(request.compare(0, strlen(want), want) == 0, + "the request: CMD_GET_RANDOM, the dedicated thread, the sequence number, the length (%s)", want); + world_trace.clear(); + const world_step_t late[] = { at(1, { LATE, RIGHT }) }; + world_script(late, 1); + get_random(300, &b); + check((a.result == 0) && (b.result == 0) && (b.sequence == (uint16_t)(first + 1)) && + (sequence_nr == (uint16_t)(first + 2)) && from_right_answer(b.sequence, b.buf, 300) && + !from_right_answer(a.sequence, b.buf, 300), + "two calls: two sequence numbers, and the first's late answer is not taken for the second's"); +} + +static void test_unsent(void) +{ + printf("GET_RANDOM: when nothing is sent\n"); + outcome_t o; + world_reset(30, random_maker, true); + world_ready = false; + get_random(32, &o); + check((o.result == WIFI_RANDOM_NO_MODULE) && untouched(&o) && world_trace.empty() && (o.advanced == 0), + "no module application: NO_MODULE, nothing tried"); + world_reset(31, random_maker, true); + dedicated_replies = NULL; + get_random(32, &o); + check((o.result == WIFI_RANDOM_NO_MODULE) && world_trace.empty(), "no reply queue: NO_MODULE, nothing tried"); + world_reset(32, random_maker, true); + dedicated_waiting = true; + get_random(32, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && dedicated_waiting && (world_transmits == 0) && + (o.advanced == 0), + "another request outstanding: BUSY at once, its claim left alone, nothing sent"); + world_reset(33, random_maker, true); + world_no_buffer = true; + get_random(32, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && printed("No buffer for WiFi command.") && + (world_transmits == 0) && channel_free(), + "no buffer: BUSY, logged, the channel free again"); + world_reset(34, random_maker, true); + world_no_transmit = true; + get_random(32, &o); + check((o.result == WIFI_RANDOM_BUSY) && untouched(&o) && printed("Get Random: no reply.") && channel_free(), + "a failed transmit: BUSY, the channel free again"); +} + +// Seeds of a world where anything can go wrong: replies right, late, foreign, +// refused, short, stale, in bursts, after preemption, near the tick wrap. +static void test_random_world(void) +{ + printf("GET_RANDOM in a world where anything goes wrong, seed by seed\n"); + static const uint16_t lengths[] = { 1, 2, 3, 31, 32, 255, 256, 257, 300, 511, 512 }; + const uint32_t seeds = 100000; + int wrong = 0; + int results[5] = { 0 }; + int with[6] = { 0 }; + const char *features[6] = { "a stale reply dropped", "the queue overflowing", "a reply refused or invalid", + "no buffer", "a failed transmit", "a reply released after the wait" }; + static outcome_t o; + for (uint32_t seed = 1; seed <= seeds; seed++) { + made.clear(); + world_reset(seed, random_maker, false); + bool held = dedicated_waiting; + bool gated = held || !world_ready || !dedicated_replies; + uint16_t len = (world_rand(4) == 0) ? (uint16_t)(1 + world_rand(RANDOM_MAX_BYTES)) + : lengths[world_rand(sizeof(lengths) / sizeof(lengths[0]))]; + get_random(len, &o); + bool ok = (o.result >= 0) && (o.result <= WIFI_RANDOM_NO_MODULE) && (o.advanced == (gated ? 0 : 1)) && + (dedicated_waiting == held) && (world_suspended == 0) && + (world_trace.find("not suspended") == std::string::npos) && (gated || (world_queued() == 0)) && + (world_wait_span <= WAIT_TICKS); + if (o.result == 0) { + ok = ok && from_right_answer(o.sequence, o.buf, len) && + (o.buf[len] == UNTOUCHED); + } else { + ok = ok && untouched(&o); + } + if (!ok) { + if (wrong++ < 3) { + printf(" seed %u: result %d, sequence moved %u, waited up to %llu ticks\n", seed, o.result, + o.advanced, (unsigned long long)world_wait_span); + } + continue; + } + results[o.result]++; + const std::string &t = world_trace; + with[0] += t.find("suspend\nresume\n") != std::string::npos; // looked at, not freed + with[1] += t.find("(full)") != std::string::npos; + with[2] += t.find("Get Random failed") != std::string::npos; + with[3] += t.find("getbuffer 4 -> none") != std::string::npos; + with[4] += t.find("-> failed") != std::string::npos; + with[5] += t.find("receive 0 -> b") != std::string::npos; + } + check(wrong == 0, "%u seeds: bytes only from this request's answer, no wait past the 200 ms deadline, the " + "sequence number and the channel as they should be (%d not)", seeds, wrong); + printf(" results: 0 OK %d, 1 BUSY %d, 2 REFUSED %d, 3 INVALID %d, 4 NO_MODULE %d\n", + results[0], results[1], results[2], results[3], results[4]); + for (int i = 0; i < 6; i++) { + check(with[i] > 100, "the seeds include %s (%d)", features[i], with[i]); + } +} + +// A call of the channel's own, with its own timeout. +static int takes; +static uint8_t taken[32]; + +static int fill_test(uint8_t *request, void *context) +{ + ((rpc_get_random_req *)request)->length = sizeof(taken); + return sizeof(rpc_get_random_req); +} + +static int take_test(const uint8_t *reply, int size, uint16_t sequence, void *context) +{ + int retval = wifi_random_take_reply(reply, size, sequence, taken, sizeof(taken)); + takes += (retval != DEDICATED_FOREIGN); + return retval; +} + +static int call(uint32_t timeout_ms) +{ + takes = 0; + const dedicated_call_t c = { "Test", CMD_GET_RANDOM, timeout_ms, fill_test, take_test, NULL }; + return wifi_dedicated_call(&c); +} + +static void test_waits(void) +{ + printf("The channel's wait: the caller's timeout, in one go\n"); + const world_step_t nothing[] = { at(100000, {}) }; + world_reset(40, random_maker, true); + world_script(nothing, 1); + int r = call(5000); + check((r == DEDICATED_BUSY) && (count(world_trace, "receive 1000") == 1) && (takes == 0) && + printed("Test: no reply.") && (world_wait_span == 1000) && channel_free(), + "nothing arrives: one wait of the whole timeout (5 s = 1000 ticks), then BUSY"); + const world_step_t late[] = { at(999, { RIGHT }) }; + world_reset(41, random_maker, true); + world_script(late, 1); + r = call(5000); + check((r == 0) && (takes == 1) && channel_free(), "the answer a tick before the timeout is taken"); +} + +int main(void) +{ + test_answers(); + test_sequence(); + test_orderings(); + test_unsent(); + test_random_world(); + test_waits(); + printf("\n%d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/software/test/wifi_dedicated/world.cc b/software/test/wifi_dedicated/world.cc new file mode 100644 index 000000000..4b774cb6d --- /dev/null +++ b/software/test/wifi_dedicated/world.cc @@ -0,0 +1,326 @@ +// world.cc: see world.h. +#include +#include +#include +#include "world.h" + +Esp32 esp32; +uint16_t sequence_nr; +const char *no_wifi_buf = "No buffer for WiFi command.\n"; +QueueHandle_t dedicated_replies; +volatile bool dedicated_waiting; + +bool world_ready; +bool world_no_buffer; +bool world_no_transmit; +std::string world_trace; +int world_suspended; +int world_transmits; +uint64_t world_wait_span; +TickType_t world_transmit_ticks; +int world_late_after_poll; + +#define QUEUE_DEPTH 4 // as wifi_cmd.cc creates it +#define RX_BUFFERS 16 + +static DmaUART uart; +static std::deque queue; +static uint32_t rng; +static TickType_t now; +static command_buf_t tx_buf; +static command_buf_t rx_bufs[RX_BUFFERS]; +static int rx_next; +static uint8_t last_tx[CMD_BUF_SIZE]; +static int last_tx_size; +static world_maker_t make_reply; +static bool calm; +static bool calm_delivered; +static const world_step_t *script; +static int script_left; +static TickType_t script_waited; // of the current step's delay, in earlier waits +static TickType_t preempt_next; // added at the next tick read +static bool start_pending; // a request went out; the next tick read starts its deadline +static TickType_t start_tick; + +static void trace(const char *fmt, ...) +{ + char line[256]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + world_trace += line; +} + +uint32_t world_rand(uint32_t n) +{ + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + return n ? (rng % n) : 0; +} + +size_t world_queued(void) +{ + return queue.size(); +} + +void world_reset(uint32_t seed, world_maker_t maker, bool quiet) +{ + rng = (seed * 2654435761u) ^ 0x9E3779B9u; + if (!rng) { + rng = 1; + } + make_reply = maker; + calm = quiet; + calm_delivered = false; + script = NULL; + script_left = 0; + script_waited = 0; + preempt_next = 0; + start_pending = false; + start_tick = 0; + world_wait_span = 0; + world_transmit_ticks = 0; + world_late_after_poll = 0; + world_trace.clear(); + queue.clear(); + world_suspended = 0; + world_transmits = 0; + rx_next = 0; + last_tx_size = -1; + // Now and then start just short of the tick counter wrapping. + now = (world_rand(4) == 0) ? (0xFFFFFFFFu - world_rand(400)) : world_rand(100000); + sequence_nr = (uint16_t)world_rand(65536); + uart.generation = world_rand(1000); + esp32.uart = &uart; + world_ready = calm || (world_rand(100) >= 3); + world_no_buffer = false; + world_no_transmit = false; + dedicated_replies = (!calm && (world_rand(100) < 2)) ? NULL : (QueueHandle_t)&queue; + dedicated_waiting = !calm && (world_rand(100) < 5); // another caller holds the channel + memset(tx_buf.data, 0xAB, sizeof(tx_buf.data)); + tx_buf.bufnr = 3; + for (int i = 0; i < RX_BUFFERS; i++) { + rx_bufs[i].bufnr = 0x40 | i; + } +} + +void world_script(const world_step_t *steps, int count) +{ + script = steps; + script_left = count; + script_waited = 0; +} + +// The receive interrupt, as wifi_rx_isr handles a frame on the dedicated thread. +static void isr_deliver(int kind, bool stale) +{ + command_buf_t *rx = &rx_bufs[rx_next++ % RX_BUFFERS]; + make_reply(rx, last_tx, last_tx_size, kind); + uint32_t generation = uart.generation; + if (stale) { + generation--; // tagged before a reset that has since happened + } + if (!dedicated_waiting) { + trace("isr drop b%x (not waiting)\n", rx->bufnr); + } else if (queue.size() >= QUEUE_DEPTH) { + trace("isr drop b%x (full)\n", rx->bufnr); + } else { + dedicated_reply_t reply = { rx, generation }; + queue.push_back(reply); + trace("isr queue b%x g%u k%d\n", rx->bufnr, generation, kind); + } +} + +static void isr_deliver_random(void) +{ + int kind = calm ? 0 : (int)world_rand(10); + isr_deliver(kind, !calm && (world_rand(10) == 0)); +} + +// One wait of a scripted world: the next step, if it falls within the wait. +static void scripted_wait(TickType_t ticks) +{ + if (!script_left || (script->delay - script_waited > ticks)) { + if (script_left) { + script_waited += ticks; + } + now += ticks; + return; + } + TickType_t delay = script->delay - script_waited; + now += delay; + for (int i = 0; i < script->count; i++) { + isr_deliver(script->kind[i], script->stale[i]); + } + preempt_next += script->preempt; + script++; + script_left--; + script_waited = 0; + if (queue.empty()) { + now += ticks - delay; // nothing came through; wait it out + } +} + +TickType_t xTaskGetTickCount(void) +{ + if (!calm && (world_rand(5) == 0)) { + now += world_rand(11); // preempted for a while + } + now += preempt_next; + preempt_next = 0; + if (start_pending) { + start_pending = false; + start_tick = now; + } + trace("tick %u\n", now); + return now; +} + +void vTaskSuspendAll(void) +{ + world_suspended++; + trace("suspend\n"); +} + +BaseType_t xTaskResumeAll(void) +{ + world_suspended--; + trace("resume\n"); + return pdFALSE; +} + +void vTaskDelay(TickType_t ticks) +{ + now += ticks; + trace("delay %u\n", ticks); +} + +BaseType_t xQueueReceive(QueueHandle_t q, void *item, TickType_t ticks) +{ + trace("receive %u", ticks); + uint64_t reach = (uint64_t)(TickType_t)(now - start_tick) + ticks; // no wrap: a huge wait must show + if ((ticks > 0) && (reach > world_wait_span)) { + world_wait_span = reach; + } + if (q != (QueueHandle_t)&queue) { + trace(" wrong queue\n"); + return pdFALSE; + } + if (queue.empty() && (ticks > 0)) { + if (script) { + scripted_wait(ticks); + } else if (calm) { + if (!calm_delivered) { + calm_delivered = true; + now += 1; + isr_deliver_random(); + } else { + now += ticks; + } + } else if (world_rand(10) < 6) { + TickType_t delay = world_rand(ticks); + now += delay; + if (world_rand(10) == 0) { + uart.generation++; + trace(" reset"); + } + int burst = 1 + world_rand((world_rand(4) == 0) ? 6 : 3); // more than the queue holds, now and then + for (int i = 0; i < burst; i++) { + isr_deliver_random(); + } + if (queue.empty()) { + now += ticks - delay; // nothing came through; wait it out + } + } else { + now += ticks; + } + } + if (queue.empty()) { + trace(" -> none\n"); + if ((ticks == 0) && (world_late_after_poll > 0)) { + world_late_after_poll--; + isr_deliver(0, false); + } + return pdFALSE; + } + *(dedicated_reply_t *)item = queue.front(); + queue.pop_front(); + trace(" -> b%x\n", ((dedicated_reply_t *)item)->buf->bufnr); + return pdTRUE; +} + +BaseType_t DmaUART::GetBuffer(command_buf_t **buf, TickType_t ticks) +{ + trace("getbuffer %u", ticks); + if (world_no_buffer || (!calm && (world_rand(100) < 5))) { + now += ticks; + trace(" -> none\n"); + return pdFALSE; + } + tx_buf.size = 0; + tx_buf.dropped = 0; + *buf = &tx_buf; + trace(" -> b%x\n", tx_buf.bufnr); + return pdTRUE; +} + +BaseType_t DmaUART::TransmitPacket(command_buf_t *buf, uint16_t *ms) +{ + trace("transmit %d:", buf->size); + for (int i = 0; (i < buf->size) && (i < CMD_BUF_SIZE); i++) { + trace(" %02x", buf->data[i]); + } + if (world_no_transmit || (!calm && (world_rand(100) < 5))) { + trace(" -> failed\n"); + return pdFALSE; // the real one frees the buffer itself + } + trace("\n"); + world_transmits++; + now += world_transmit_ticks; + start_pending = true; + memcpy(last_tx, buf->data, CMD_BUF_SIZE); + last_tx_size = buf->size; + // Late replies to earlier requests, or even this one, before the wait. + if (!calm && (world_rand(100) < 15)) { + int burst = 1 + world_rand(2); + for (int i = 0; i < burst; i++) { + isr_deliver_random(); + } + } + return pdTRUE; +} + +BaseType_t DmaUART::FreeBuffer(command_buf_t *buf) +{ + trace("free b%x%s\n", buf->bufnr, world_suspended ? "" : " (not suspended)"); + return pdTRUE; +} + +void world_enter_safe(void) +{ + trace("enter\n"); +} + +void world_leave_safe(void) +{ + trace("leave\n"); +} + +int world_printf(const char *fmt, ...) +{ + char line[256]; + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + world_trace += "print: "; + world_trace += line; + return n; +} + +bool wifi_module_ready(void) +{ + return world_ready; +} diff --git a/software/test/wifi_dedicated/world.h b/software/test/wifi_dedicated/world.h new file mode 100644 index 000000000..7f042833e --- /dev/null +++ b/software/test/wifi_dedicated/world.h @@ -0,0 +1,43 @@ +// The scripted world that the host test runs wifi_dedicated.cc in: the module's +// replies, the receive interrupt, the tick, the buffer pool and its resets. +// Every random decision comes from one generator, and every call is traced. +#ifndef WORLD_H_ +#define WORLD_H_ + +#include +#include "wifi_cmd.h" + +// Builds a reply of the given kind into rx, as an answer to the last request +// sent (req, req_size; req_size is -1 when nothing has been sent). +typedef void (*world_maker_t)(command_buf_t *rx, const uint8_t *req, int req_size, int kind); + +// Starts a new world from seed. With calm set nothing fails at random, and the +// first wait delivers exactly one reply of kind 0, unless a script is given. +void world_reset(uint32_t seed, world_maker_t maker, bool calm); +uint32_t world_rand(uint32_t n); + +// A calm world's waits follow a script instead: each step arrives delay ticks +// into the wait, at most MAX_STEP_REPLIES replies, a stale one tagged before a +// pool reset. A step whose delay outlasts the wait is still due in the next one. +#define MAX_STEP_REPLIES 4 +typedef struct { + TickType_t delay; + int count; + int kind[MAX_STEP_REPLIES]; + bool stale[MAX_STEP_REPLIES]; + TickType_t preempt; // added to the clock at the next tick read, as if preempted +} world_step_t; +void world_script(const world_step_t *steps, int count); + +extern bool world_ready; // what wifi_module_ready answers +extern bool world_no_buffer; // GetBuffer fails, even when calm +extern bool world_no_transmit; // TransmitPacket fails, even when calm +extern std::string world_trace; // every call, in order +extern int world_suspended; // vTaskSuspendAll minus xTaskResumeAll +extern int world_transmits; // requests that went out +extern TickType_t world_transmit_ticks; // how long a calm TransmitPacket takes to queue the request +extern int world_late_after_poll; // replies the interrupt hands over just after an empty receive 0 +extern uint64_t world_wait_span; // how far past the first tick read after sending any wait reached +size_t world_queued(void); // replies still in dedicated_replies + +#endif /* WORLD_H_ */ diff --git a/software/test/wifi_random/lwip/netdb.h b/software/test/wifi_random/lwip/netdb.h new file mode 100644 index 000000000..72207e47d --- /dev/null +++ b/software/test/wifi_random/lwip/netdb.h @@ -0,0 +1 @@ +// Stand-in for lwIP's netdb.h on the build host. rpc_calls.h needs nothing from it. diff --git a/software/test/wifi_random/lwip/sockets.h b/software/test/wifi_random/lwip/sockets.h new file mode 100644 index 000000000..b78473080 --- /dev/null +++ b/software/test/wifi_random/lwip/sockets.h @@ -0,0 +1,6 @@ +// Stand-in for lwIP's sockets.h on the build host. rpc_calls.h needs only u16_t. +#ifndef LWIP_SOCKETS_H_STUB +#define LWIP_SOCKETS_H_STUB +#include +typedef uint16_t u16_t; +#endif diff --git a/software/test/wifi_random/wifi_random_test.cc b/software/test/wifi_random/wifi_random_test.cc new file mode 100644 index 000000000..b49d39917 --- /dev/null +++ b/software/test/wifi_random/wifi_random_test.cc @@ -0,0 +1,227 @@ +// Host test of wifi_random.cc, the check on the module's answer to GET_RANDOM: +// answers a broken or confused module could send, none of which may hand out a byte. +// make -C target/pc/linux/wifirandom test +#include +#include +#include +#include +#include "rpc_calls.h" +#include "wifi_random.h" + +// The layout both sides agree on is asserted in rpc_shared.h itself. + +#define SEQUENCE 0x1234 +#define HEADER 12 + +// The length every case below asks for; main runs them for several. +static uint16_t LEN; + +static int failures; +static int checks; + +static void check(int condition, const char *what) +{ + checks++; + if (!condition) { + failures++; + printf(" FAIL %s\n", what); + } else { + printf(" ok %s\n", what); + } +} + +// Word aligned, as the data of a command_buf_t is. +static union { + uint32_t align; + uint8_t bytes[HEADER + 512 + 256]; +} reply; + +// A correct answer to request SEQUENCE for LEN bytes; returns its size. +static int build(void) +{ + memset(reply.bytes, 0, sizeof(reply.bytes)); + rpc_get_random_resp *r = (rpc_get_random_resp *)reply.bytes; + r->hdr.command = CMD_GET_RANDOM; + r->hdr.thread = 12; + r->hdr.sequence = SEQUENCE; + r->esp_err = 0; + r->source = ENTROPY_RADIO; + r->length = LEN; + for (int i = 0; i < LEN; i++) { + r->data[i] = (uint8_t)(0xA0 + (i * 7) + (i >> 8)); // no period of 256 + } + return HEADER + LEN; +} + +static rpc_get_random_resp *answer(void) +{ + return (rpc_get_random_resp *)reply.bytes; +} + +// Runs the check on the first size bytes of the reply; true when it returned +// expected and, unless that is success, left buf alone. +static bool outcome(int size, uint16_t len, int expected) +{ + uint8_t buf[600]; + memset(buf, 0xEE, sizeof(buf)); + int result = wifi_random_take_reply(reply.bytes, size, SEQUENCE, buf, len); + if (result != expected) { + printf(" returned %d, expected %d\n", result, expected); + return false; + } + if (expected == 0) { + return (memcmp(buf, answer()->data, len) == 0) && (buf[len] == 0xEE); + } + for (size_t i = 0; i < sizeof(buf); i++) { + if (buf[i] != 0xEE) { + printf(" byte %d was written\n", (int)i); + return false; + } + } + return true; +} + +static void reply_cases(void) +{ + int size; + + printf("The answer to this request\n"); + size = build(); + check(outcome(size, LEN, 0), "hands out exactly len bytes"); + size = build(); + check(outcome(size + 100, LEN, 0), "ignores bytes the module sent beyond len"); + + printf("An answer to something else\n"); + size = build(); + answer()->hdr.sequence = SEQUENCE - 1; + check(outcome(size, LEN, WIFI_RANDOM_FOREIGN), "wrong sequence is not ours"); + size = build(); + answer()->hdr.sequence = SEQUENCE ^ 0x0100; + check(outcome(size, LEN, WIFI_RANDOM_FOREIGN), "a sequence that differs only in its high byte is not ours"); + size = build(); + answer()->hdr.command = CMD_WIFI_GETMAC; + check(outcome(size, LEN, WIFI_RANDOM_FOREIGN), "wrong command is not ours"); + size = build(); + check(outcome(3, LEN, WIFI_RANDOM_FOREIGN), "fewer bytes than a header is not ours"); + bool only_ours = true; + for (int command = 0; command < 256; command++) { + size = build(); + answer()->hdr.command = (uint8_t)command; + uint8_t buf[512]; + int expected = (command == CMD_GET_RANDOM) ? 0 : WIFI_RANDOM_FOREIGN; + if (wifi_random_take_reply(reply.bytes, size, SEQUENCE, buf, LEN) != expected) { + printf(" command 0x%02x\n", command); + only_ours = false; + } + } + check(only_ours, "of all 256 commands only CMD_GET_RANDOM is ours"); + + printf("The source behind the bytes\n"); + size = build(); + answer()->source = ENTROPY_ADC; + check(outcome(size, LEN, 0), "bytes from the ADC source, with the radio off, are handed out"); + + printf("The module is busy\n"); + size = build(); + answer()->esp_err = RPC_ERR_ENTROPY_BUSY; + answer()->source = ENTROPY_NONE; + answer()->length = 0; + check(outcome(HEADER, LEN, WIFI_RANDOM_BUSY), "busy with no bytes"); + size = build(); + answer()->esp_err = RPC_ERR_ENTROPY_BUSY; + check(outcome(size, LEN, WIFI_RANDOM_BUSY), "busy hands out nothing, even with len bytes behind it"); + size = build(); + answer()->esp_err = RPC_ERR_ENTROPY_BUSY; + check(outcome(8, LEN, WIFI_RANDOM_BUSY), "busy in the 8 byte form"); + size = build(); + answer()->esp_err = RPC_ERR_ENTROPY_BUSY + 1; + check(outcome(HEADER, LEN, WIFI_RANDOM_REFUSED), "the next error is a refusal"); + size = build(); + answer()->esp_err = RPC_ERR_ENTROPY_BUSY - 1; + check(outcome(HEADER, LEN, WIFI_RANDOM_REFUSED), "the error before it is a refusal"); + size = build(); + answer()->esp_err = RPC_ERR_ENTROPY_BUSY; + uint8_t sink[600]; + check(wifi_random_status(wifi_random_take_reply(reply.bytes, size, SEQUENCE, sink, LEN)) == 88, + "a busy answer is UCI status 88"); + + printf("A refusal\n"); + size = build(); + answer()->esp_err = 0x103; // ESP_ERR_INVALID_STATE + answer()->length = 0; + check(outcome(HEADER, LEN, WIFI_RANDOM_REFUSED), "esp_err INVALID_STATE with no bytes"); + size = build(); + answer()->esp_err = 0x103; + check(outcome(size, LEN, WIFI_RANDOM_REFUSED), "esp_err set, even with len bytes behind it"); + const int errors[] = { 0x3000, 0x10000, -1, INT_MIN }; // ESP_ERR_WIFI_BASE, beyond 16 bits, ESP_FAIL + for (int i = 0; i < 4; i++) { + char what[64]; + size = build(); + answer()->esp_err = errors[i]; + snprintf(what, sizeof(what), "esp_err %d, with len bytes behind it", errors[i]); + check(outcome(size, LEN, WIFI_RANDOM_REFUSED), what); + } + size = build(); + answer()->esp_err = 0x106; // ESP_ERR_NOT_SUPPORTED, from firmware without the call + check(outcome(8, LEN, WIFI_RANDOM_REFUSED), "the 8 byte answer of old module firmware"); + size = build(); + answer()->source = ENTROPY_NONE; + check(outcome(size, LEN, WIFI_RANDOM_REFUSED), "OK without an entropy source"); + + printf("A malformed answer\n"); + size = build(); + answer()->esp_err = 0x103; // only partly received, so it must not be read + check(outcome(7, LEN, WIFI_RANDOM_INVALID), "too short to hold esp_err, whatever lies beyond it"); + size = build(); + check(outcome(HEADER - 1, LEN, WIFI_RANDOM_INVALID), "OK but too short to hold the header"); + size = build(); + answer()->source = ENTROPY_NONE; // a byte past the frame must not be read + check(outcome(HEADER - 2, LEN, WIFI_RANDOM_INVALID), "too short to hold the header, whatever lies beyond it"); + size = build(); + answer()->length = LEN - 1; + check(outcome(size, LEN, WIFI_RANDOM_INVALID), "fewer bytes announced than asked"); + size = build(); + answer()->length = LEN + 1; + check(outcome(size + 1, LEN, WIFI_RANDOM_INVALID), "more bytes announced than asked"); + size = build(); + answer()->length = LEN ^ 0x0100; + check(outcome(size + 256, LEN, WIFI_RANDOM_INVALID), "a length that differs only in its high byte"); + size = build(); + check(outcome(size - 1, LEN, WIFI_RANDOM_INVALID), "fewer bytes received than announced"); + size = build(); + answer()->length = 0; + check(outcome(HEADER, LEN, WIFI_RANDOM_INVALID), "OK with no bytes at all"); + +} + +int main(void) +{ + // One byte, a byte count that fills a uint8_t, one past it, a length past + // 256, and the most the UCI asks for. + const uint16_t lengths[] = { 1, 255, 256, 300, 512 }; + for (int i = 0; i < 5; i++) { + LEN = lengths[i]; + printf("\n== len %d\n", LEN); + reply_cases(); + } + + printf("The UCI status of a result\n"); + check(wifi_random_status(0) == 0, "0 is OK"); + check(wifi_random_status(WIFI_RANDOM_BUSY) == 88, "busy is 88"); + check(wifi_random_status(WIFI_RANDOM_INVALID) == 86, "an invalid reply is 86"); + check(wifi_random_status(WIFI_RANDOM_REFUSED) == 87, "a refusal is 87"); + check(wifi_random_status(WIFI_RANDOM_NO_MODULE) == 87, "no module is 87"); + check(wifi_random_status(WIFI_RANDOM_FOREIGN) == 87, "a foreign reply is 87"); + bool only_zero = true; + for (int result = -1000; result <= 1000; result++) { + if ((wifi_random_status(result) == 0) != (result == 0)) { + only_zero = false; + } + } + check(only_zero, "no result but 0 maps to OK, from -1000 to 1000"); + check((wifi_random_status(INT_MIN) == 87) && (wifi_random_status(INT_MAX) == 87), + "INT_MIN and INT_MAX are 87, so carry no data"); + + printf("\n%d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/software/test/wifi_reply/stubs/FreeRTOS.h b/software/test/wifi_reply/stubs/FreeRTOS.h index 4c4f13777..3efaf927b 100644 --- a/software/test/wifi_reply/stubs/FreeRTOS.h +++ b/software/test/wifi_reply/stubs/FreeRTOS.h @@ -13,6 +13,9 @@ typedef long BaseType_t; typedef unsigned long TickType_t; typedef void *TaskHandle_t; typedef void *QueueHandle_t; +// The dedicated reply channel of wifi_cmd.cc (U64 >= 1) is not under test here +static inline QueueHandle_t xQueueCreate(int length, int item_size) { return NULL; } +static inline BaseType_t xQueueSendFromISR(QueueHandle_t q, const void *item, BaseType_t *w) { return 0; } #define pdFALSE 0 #define pdTRUE 1 #define portMAX_DELAY 0xFFFFFFFFUL diff --git a/software/test/wifi_reply/stubs/dma_uart.h b/software/test/wifi_reply/stubs/dma_uart.h index 7d5d325c8..78a0b4183 100644 --- a/software/test/wifi_reply/stubs/dma_uart.h +++ b/software/test/wifi_reply/stubs/dma_uart.h @@ -10,6 +10,7 @@ class DmaUART public: int buffers_free = 0; int transmitted = 0; + volatile uint32_t generation = 0; // U64 >= 1 builds of wifi_cmd.cc tag dedicated replies with it BaseType_t GetBuffer(command_buf_t **b, TickType_t t); void FreeBuffer(command_buf_t *b); void SetBaudRate(int b) {} diff --git a/software/test/wifi_tls/check.h b/software/test/wifi_tls/check.h new file mode 100644 index 000000000..bca1b8d11 --- /dev/null +++ b/software/test/wifi_tls/check.h @@ -0,0 +1,8 @@ +#ifndef CHECK_H_ +#define CHECK_H_ +#include +extern int failures; +extern int checks; +// Counts one check and prints it: "ok" or "FAIL". +void check(bool condition, const char *what, ...); +#endif diff --git a/software/test/wifi_tls/ip4addr_aton.cc b/software/test/wifi_tls/ip4addr_aton.cc new file mode 100644 index 000000000..cd7f61cb3 --- /dev/null +++ b/software/test/wifi_tls/ip4addr_aton.cc @@ -0,0 +1,97 @@ +// lwIP's ip4addr_aton (software/lwip/src/core/ipv4/ip4_addr.c at 26a22151): network_target.cc decides what an IPv4 +// literal is with it, so the host tests need the same predicate (127.1, 0x7f.0.0.1 and "1.2.3.4 x" included). +// Copyright (c) 2001-2004 Swedish Institute of Computer Science. All rights reserved. (BSD; see software/lwip/COPYING.) +#include +#include +#include "lwip/dns.h" + +int ip4addr_aton(const char *cp, ip4_addr_t *addr) +{ + uint32_t val; + uint8_t base; + char c; + uint32_t parts[4]; + uint32_t *pp = parts; + + c = *cp; + for (;;) { + if (!isdigit((unsigned char)c)) { + return 0; + } + val = 0; + base = 10; + if (c == '0') { + c = *++cp; + if (c == 'x' || c == 'X') { + base = 16; + c = *++cp; + } else { + base = 8; + } + } + for (;;) { + if (isdigit((unsigned char)c)) { + if ((base == 8) && ((uint32_t)(c - '0') >= 8)) + break; + val = (val * base) + (uint32_t)(c - '0'); + c = *++cp; + } else if (base == 16 && isxdigit((unsigned char)c)) { + val = (val << 4) | (uint32_t)(c + 10 - (islower((unsigned char)c) ? 'a' : 'A')); + c = *++cp; + } else { + break; + } + } + if (c == '.') { + if (pp >= parts + 3) { + return 0; + } + *pp++ = val; + c = *++cp; + } else { + break; + } + } + if (c != '\0' && !isspace((unsigned char)c)) { + return 0; + } + switch (pp - parts + 1) { + case 0: + return 0; + case 1: + break; + case 2: + if (val > 0xffffffUL) { + return 0; + } + if (parts[0] > 0xff) { + return 0; + } + val |= parts[0] << 24; + break; + case 3: + if (val > 0xffff) { + return 0; + } + if ((parts[0] > 0xff) || (parts[1] > 0xff)) { + return 0; + } + val |= (parts[0] << 24) | (parts[1] << 16); + break; + case 4: + if (val > 0xff) { + return 0; + } + if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff)) { + return 0; + } + val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); + break; + default: + break; + } + if (addr) { + addr->addr = htonl(val); + } + return 1; +} diff --git a/software/test/wifi_tls/net_tls_test.cc b/software/test/wifi_tls/net_tls_test.cc new file mode 100644 index 000000000..2c23e3acc --- /dev/null +++ b/software/test/wifi_tls/net_tls_test.cc @@ -0,0 +1,1871 @@ +/* Host tests for the TLS commands ($21-$25, and READ/WRITE/CLOSE on a TLS handle) of the real + * network_target.cc in the world of net_world.cc. Run: make -C target/pc/linux/wifitls test + * Without the TLS commands every group is RED: the target answers 21,UNKNOWN COMMAND. */ +#include +#include +#include +#include +#include +#include +#include "net_world.h" +#define class struct // execute() and close_sockets_after_reset() are private +#include "network_target.h" +#undef class +#include "check.h" + +int failures; +int checks; + +void check(bool condition, const char *what, ...) +{ + char line[400]; + va_list ap; + va_start(ap, what); + vsnprintf(line, sizeof(line), what, ap); + va_end(ap); + checks++; + if (!condition) { + failures++; + printf(" FAIL %s\n", line); + } else { + printf(" ok %s\n", line); + } +} + +extern NetworkTarget net; + +struct Res { + bytes data; + std::string status; +}; + +// One command as the C64 sends it, and every block of its reply as it reads them. +// The longest status any command of the run answered (the cap is 40 bytes). +static std::string longest_status; + +// A C64 reset: the UCI Server task notes it, and the worker closes the sockets and the TLS sessions. +static void reset_c64(void) +{ + net.c64_reset(); + net.close_sockets_after_reset(); +} + +static Res run(const bytes &command) +{ + static uint8_t buf[1024]; + memcpy(buf, command.data(), command.size()); + Message m = { (int)command.size(), true, buf }; + Message *reply, *status; + // The UCI Server task answers a socket-free command itself; any other runs on the worker, which is + // not started here: execute() is called as the worker calls it, between its own housekeeping. + if (net.is_quick(&m)) { + net.parse_command(&m, &reply, &status); + } else { + static volatile bool not_cancelled; + not_cancelled = false; + net.close_sockets_after_reset(); + net.cancel = ¬_cancelled; + net.opened_socket = -1; + net.execute(&m, &reply, &status); + net.cancel = NULL; + net.close_sockets_after_reset(); + } + Res r; + r.data.assign(reply->message, reply->message + reply->length); + r.status.assign((const char *)status->message, status->length); + if ((size_t)status->length > longest_status.size()) { + longest_status = r.status; + } + int guard = 0; + while (!reply->last_part && (guard++ < 10)) { + net.get_more_data(&reply, &status); + r.data.insert(r.data.end(), reply->message, reply->message + reply->length); + r.status.append((const char *)status->message, status->length); + } + return r; +} + +static bytes B(std::initializer_list v) +{ + bytes b; + for (int x : v) { + b.push_back((uint8_t)x); + } + return b; +} + +static bytes cat(bytes a, const bytes &b) +{ + a.insert(a.end(), b.begin(), b.end()); + return a; +} + +static bytes S(const std::string &s) +{ + return bytes(s.begin(), s.end()); +} + +static bytes PIN(uint8_t fill = 0x5A) +{ + return bytes(32, fill); +} + +static bytes open_cmd(uint8_t trust, uint8_t flags, const std::string &tail, const bytes &pin = bytes(), + uint16_t port = 443, uint8_t first = 0x03) +{ + bytes c = B({ first, 0x21, port & 0xFF, port >> 8, trust, flags }); + c = cat(c, pin); + return cat(c, S(tail)); +} + +static std::string num(int n) +{ + char t[16]; + snprintf(t, sizeof(t), "%d", n); + return t; +} + +// Byte i of a reply, or $EE past its end: a red run must not read beyond it. +static uint8_t at(const Res &r, size_t i) +{ + return (i < r.data.size()) ? r.data[i] : 0xEE; +} + +static uint8_t info_byte(size_t i); + +static uint16_t header(const Res &r) +{ + return (r.data.size() >= 2) ? (uint16_t)(r.data[0] | (r.data[1] << 8)) : 0xEEEE; +} + +static bytes body(const Res &r) +{ + return (r.data.size() >= 2) ? bytes(r.data.begin() + 2, r.data.end()) : bytes(); +} + +// Socket h of the world, or a spare one when h is no socket number: a red run must not crash. +static FakeSock &sock(int h) +{ + static FakeSock spare; + if ((h < 0) || (h >= 16)) { + spare = FakeSock(); + return spare; + } + return world_socks[h]; +} + +static Res read_cmd(int h, int maxlen) +{ + return run(B({ 0x03, 0x10, h, maxlen & 0xFF, maxlen >> 8 })); +} + +static Res write_cmd(int h, const bytes &data) +{ + return run(cat(B({ 0x03, 0x11, h }), data)); +} + +static Res close_cmd(int h) +{ + return run(B({ 0x03, 0x09, h })); +} + +static Res info(int h) +{ + return run(B({ 0x03, 0x23, h })); +} + +static Res release(void) +{ + return run(B({ 0x03, 0x25 })); +} + +static void fresh(void) +{ + world_reset(); + reset_c64(); + world_module.calls.clear(); + world_module.close_alls = 0; + for (int i = 0; i < 16; i++) { + world_socks[i] = FakeSock(); + world_socks[i].srv.saw_alert = -1; + world_socks[i].srv.flight = 2000; + world_socks[i].srv.delay_ms = 20; + world_socks[i].srv.chunk = 1460; + } +} + +// An OPEN that should succeed; the handle, or -1. +static int open_ok(uint8_t trust = 0, const std::string &tail = "example.com", const bytes &pin = bytes()) +{ + Res r = run(open_cmd(trust, 0, tail, pin)); + if ((r.status != "00,OK") || (r.data.size() != 8)) { + printf(" open: %s (%d bytes)\n", r.status.c_str(), (int)r.data.size()); + return -1; + } + return r.data[0]; +} + +// READs until the stream ends or nothing more comes: the data, and the last status. +static bytes read_all(int h, int maxlen, std::string *last, int *reads = NULL, int limit = 400) +{ + bytes all; + int n = 0; + for (; n < limit; n++) { + Res r = read_cmd(h, maxlen); + *last = r.status; + if (header(r) == 0xFFFF) { + if (r.status.compare(0, 3, "02,") != 0) { + break; + } + continue; + } + if (header(r) == 0) { + break; + } + bytes b = body(r); + all.insert(all.end(), b.begin(), b.end()); + } + if (reads) { + *reads = n; + } + return all; +} + +static bytes expected(uint32_t seed, size_t n) +{ + bytes b; + for (size_t i = 0; i < n; i++) { + b.push_back(payload_byte(seed, i)); + } + return b; +} + +// The i-th module call, or an empty one: a red run must not crash. +static RpcCall call_no(size_t i) +{ + return (i < world_module.calls.size()) ? world_module.calls[i] : RpcCall(); +} + +static RpcCall last_call(void) +{ + return world_module.calls.empty() ? RpcCall() : world_module.calls.back(); +} + +static uint8_t info_byte(size_t i) +{ + return at(info(0xFF), i); +} + +static int steps_logged(void) +{ + return world_count(0x31); +} + +// --- TLS_INFO ($23) ------------------------------------------------------------ + +static void test_info(void) +{ + printf("TLS_INFO $FF and on a handle\n"); + fresh(); + Res r = info(0xFF); + check(r.status == "00,OK" && r.data.size() == 16, "info: $FF answers 16 bytes, 00,OK (got %s, %d)", + r.status.c_str(), (int)r.data.size()); + if (r.data.size() == 16) { + const uint8_t want[16] = { 1, 2, 0, 7, 0x07, 3, 1, 0x32, 0x01, 0xFF, 0xFF, 0xFF, 12, 0, 0, 0 }; + check(memcmp(r.data.data(), want, 16) == 0, + "info: v1, 2 sessions, 0 in use, modes 7, ready 07 (image, entropy, time), versions 3, module 1.306, " + "CA date FF FF FF (unknown), block 12 ms, 0 unclaimed"); + } + check(world_count(0x33) == 1 && last_call().slot == 0xFF && last_call().tag == 0, + "info: one global STATS (slot $FF, tag 0)"); + world_module.available = false; + world_module.calls.clear(); + r = info(0xFF); + check(r.data.size() == 16 && !(r.data[4] & 0x01) && world_module.calls.empty(), + "info: no module -> ready bit0 clear, no RPC"); + world_module.available = true; + world_module.entropy = false; + world_module.module_time = false; + world_sntp = 0; + r = info(0xFF); + check(r.data.size() == 16 && r.data[4] == 0x01, "info: no entropy, no time anywhere -> ready 01 (got %02x)", + r.data.size() == 16 ? r.data[4] : 0xEE); + world_sntp = 1790000000u; + r = info(0xFF); + check(r.data.size() == 16 && r.data[4] == 0x05, "info: Nios SNTP alone gives the time bit"); + check(run(B({ 0x03, 0x23 })).status == "81,INVALID PARAMS", "info: 2 bytes -> 81"); + check(run(B({ 0x03, 0x23, 0xFF, 0x00 })).status == "81,INVALID PARAMS", "info: 4 bytes -> 81"); + check(info(5).status == "81,INVALID PARAMS" && info(5).data.empty(), "info: not a TLS handle -> empty, 81"); + + // The last good STATS stands through a STATS that gets no + // answer, within one module generation. + fresh(); + world_module.block_max_ms = 33; + r = info(0xFF); + world_module.block_max_ms = 44; + world_module.stats_result = WIFI_TLS_BUSY; + r = info(0xFF); + check(r.data.size() == 16 && (r.data[4] & 0x03) == 0x03 && r.data[12] == 33 && r.data[9] == 0xFF, + "info (cache): a STATS timeout keeps b0/b1, block_max 33 and the CA date from the last good STATS"); + world_module.stats_result = WIFI_TLS_UNSENT; + check((info_byte(4) & 0x01) == 0x01, "info (cache): an unsent STATS keeps b0 too"); + world_module.stats_result = WIFI_TLS_BUSY; + world_module.generation++; + r = info(0xFF); + check(r.data.size() == 16 && !(r.data[4] & 0x03) && r.data[12] == 0 && r.data[9] == 0, + "info (cache): after a module restart a STATS timeout clears b0/b1, block_max and the CA date"); + world_module.stats_result = -1; + check((info_byte(4) & 0x01) == 0x01 && info_byte(12) == 44, "info (cache): the next good STATS sets them again"); + world_module.stats_result = WIFI_TLS_INVALID; + check((info_byte(4) & 0x01) == 0x01, "info (cache): a malformed STATS answer keeps b0 (only NO_MODULE, " + "NOT_SUPPORTED or a new generation clear it)"); + world_module.stats_result = WIFI_TLS_REFUSED; // a module without TLS + world_module.stats_esp_err = WIFI_TLS_ESP_NOT_SUPPORTED; + check(!(info_byte(4) & 0x01), "info (cache): a STATS refused with NOT_SUPPORTED clears b0"); + world_module.stats_esp_err = 0; + world_module.stats_result = -1; + info(0xFF); + world_module.available = false; + r = info(0xFF); + world_module.available = true; + world_module.stats_result = WIFI_TLS_BUSY; + check(r.data.size() == 16 && !(r.data[4] & 0x01) && r.data[9] == 0 && r.data[10] == 0 && r.data[11] == 0 && + !(info_byte(4) & 0x01), "info (cache): no module clears b0 and the cache; the CA date is 0,0,0"); + world_module.stats_result = -1; +} + +// --- OPEN_TLS: the happy path -------------------------------------------------- + +static void test_open(void) +{ + printf("OPEN_TLS ($21): reply, RPC fields, socket\n"); + fresh(); + Res r = run(open_cmd(0, 0, "example.com")); + check(r.status == "00,OK", "open: BUNDLE example.com -> 00,OK (got %s)", r.status.c_str()); + int h = r.data.empty() ? -1 : r.data[0]; + const uint8_t want[8] = { (uint8_t)h, 0x04, 0x03, 0x01, 0x13, 0x1D, 0x00, 0x00 }; + check(r.data.size() == 8 && memcmp(r.data.data(), want, 8) == 0, + "open: reply is handle, 04 03, 01 13, 1D 00, 00 (8 bytes, LE)"); + RpcCall *o = NULL; + for (size_t i = 0; i < world_module.calls.size(); i++) { + if (world_module.calls[i].cmd == 0x30) { + o = &world_module.calls[i]; + } + } + check(o != NULL, "open: one OPEN RPC"); + if (o) { + check(o->open.trust == 0 && o->sni == "example.com" && o->open.slot == 0 && o->open.tag != 0, + "open: RPC trust 0, sni example.com, slot 0, tag %u != 0", o->open.tag); + check(o->open.time_source == WIFI_TLS_TIME_NIOS && o->open.unix_time == world_sntp, + "open: the Nios SNTP time goes along (time_source 1)"); + check(o->open.opts == 0 && o->open.ca_tag == 0 && o->pin.empty(), "open: opts 0, ca_tag 0, no pin"); + check(o->cancel_given, "open: the RPC wait has a cancel predicate"); + } + check(world_dns_calls == 1 && world_dns_unlocked_calls == 0, "open: dns_gethostbyname under the core lock"); + if (h >= 0 && h < 16) { + check(sock(h).nodelay, "open: TCP_NODELAY on the TLS socket"); + check(sock(h).sndtimeo_ms == 500, "open: SO_SNDTIMEO 500 ms caps lwIP's close (%d)", sock(h).sndtimeo_ms); + check(sock(h).nonblocking, "open: the TLS socket is non-blocking (SEND_MS)"); + check(sock(h).srv.hellos == 1, "open: the server saw one ClientHello"); + } + for (size_t i = 0; i < world_module.calls.size(); i++) { + const RpcCall &c = world_module.calls[i]; + if (c.cmd == 0x31) { + check(o && c.flags == 0 && c.slot == 0 && c.tag == o->open.tag, "open: handshake step %d: flags 0, slot and tag", + (int)i); + } + } + r = info(h); + check(r.status == "00,OK" && r.data.size() == 48, "info: a TLS handle answers 48 bytes"); + if (r.data.size() == 48) { + check(r.data[0] == 0x04 && r.data[1] == 0x03 && r.data[2] == 0x01 && r.data[3] == 0x13 && + r.data[4] == 0x1D && r.data[5] == 0 && r.data[6] == 0 && r.data[7] == 0, + "info: version, suite, group LE, trust 0, bits 0"); + check(memcmp(&r.data[8], world_module.spki, 32) == 0, "info: SPKI hash from the module, digest order"); + uint32_t ms = r.data[40] | (r.data[41] << 8) | (r.data[42] << 16) | (r.data[43] << 24); + check(ms > 0 && ms < 2000 && r.data[44] == 0 && r.data[47] == 0, "info: handshake %u ms, then 4 zero bytes", ms); + } + + fresh(); + world_module.version = 0x0303; + world_module.suite = 0xC02B; + world_module.group = 0x0017; + world_module.ems = 1; + r = run(open_cmd(0, 0x01, "example.com")); + check(r.data.size() == 8 && r.data[1] == 0x03 && r.data[2] == 0x03 && r.data[3] == 0x2B && r.data[4] == 0xC0 && + r.data[5] == 0x17 && r.data[7] == 0x01, "open: TLS 1.2 with EMS -> 03 03, 2B C0, 17 00, bit0 set"); + check(call_no(0).open.opts == WIFI_TLS_OPT_REQUIRE_TLS13, "open: flags bit0 -> opts REQUIRE_TLS13"); + + fresh(); + world_module.group = 0; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "17,TLS MODULE NOT RESPONDING" && r.data.empty() && world_open_sockets() == 0 && + world_count(0x32) == 1, "open: STATS with group 0 -> 17, socket and session closed (an established group is never 0)"); + + fresh(); + world_module.hello_size = 1400; + r = run(open_cmd(0, 0, "example.com")); + int first = -1, second = -1; + for (size_t i = 0; i < world_module.calls.size(); i++) { + if (world_module.calls[i].cmd == 0x31) { + if (first < 0) { + first = i; + } else if (second < 0) { + second = i; + } + } + } + check(r.status == "00,OK" && second > 0 && call_no(second).ct_in_len == 0, + "open: a 1403-B ClientHello goes in two steps, the second input-less (HANDSHAKE_MS)"); + h = r.data.empty() ? 0 : r.data[0]; + check(sock(h).srv.hellos == 1, "open: the server got the whole ClientHello"); + + fresh(); + for (int i = 0; i < 3; i++) { + uint16_t last = 0; + int a = open_ok(); + for (size_t k = 0; k < world_module.calls.size(); k++) { + if (world_module.calls[k].cmd == 0x30) { + last = world_module.calls[k].open.tag; + } + } + check(a >= 0 && last != 0, "open: open %d has a new non-zero tag %u", i, last); + close_cmd(a); + } + uint16_t t1 = 0, t2 = 0; + for (size_t k = 0; k < world_module.calls.size(); k++) { + if (world_module.calls[k].cmd == 0x30) { + t1 = t2; + t2 = world_module.calls[k].open.tag; + } + } + check(t1 != t2, "open: consecutive OPENs of one slot carry different tags"); +} + +// --- OPEN_TLS: the grammar, and 81 before 82 ------------------------------------ + +static void expect_open(const bytes &cmd, const char *want, const char *what) +{ + world_module.calls.clear(); + int dns = world_dns_calls; + Res r = run(cmd); + check(r.status == want && (strcmp(want, "00,OK") == 0 || (r.data.empty() && world_module.calls.empty() && + world_dns_calls == dns && world_open_sockets() == 0)), + "grammar: %s -> %s (got %s)", what, want, r.status.c_str()); + if (r.status == "00,OK" && !r.data.empty()) { + close_cmd(at(r, 0)); + } +} + +static std::string last_sni(void) +{ + for (size_t i = world_module.calls.size(); i-- > 0;) { + if (world_module.calls[i].cmd == 0x30) { + return world_module.calls[i].sni; + } + } + return ""; +} + +static void test_grammar(void) +{ + printf("OPEN_TLS: tail grammar, names and refusals (S19)\n"); + fresh(); + std::string h254(254, 'a'); + std::string h253(253, 'a'); + expect_open(B({ 0x03, 0x21, 0xBB, 0x01, 0 }), "81,INVALID PARAMS", "5 bytes"); + expect_open(open_cmd(0, 0, ""), "81,INVALID PARAMS", "empty host"); + expect_open(open_cmd(0, 0, std::string("\0", 1)), "81,INVALID PARAMS", "host is a lone $00"); + expect_open(open_cmd(0, 0, std::string("example.com\0\0", 13)), "81,INVALID PARAMS", "host $00 $00"); + expect_open(open_cmd(0, 0, std::string("example.com\0a\0b", 15)), "81,INVALID PARAMS", "a $00 inside the name"); + expect_open(open_cmd(0, 0, std::string("example.com\0name\0\0", 18)), "81,INVALID PARAMS", + "bytes after the name's $00"); + expect_open(open_cmd(0, 0, h254), "81,INVALID PARAMS", "a 254-byte host"); + expect_open(open_cmd(0, 0, std::string("x.com\0", 6) + h254), "81,INVALID PARAMS", "a 254-byte name"); + expect_open(open_cmd(2, 0, "example.com", bytes(20, 1)), "81,INVALID PARAMS", "a short pin"); + expect_open(open_cmd(3, 0, "example.com"), "82,PARAMETER(S) OUT OF RANGE", "trust 3"); + expect_open(open_cmd(0, 0x02, "example.com"), "82,PARAMETER(S) OUT OF RANGE", "flags $02 (reserved)"); + expect_open(open_cmd(0, 0x80, "example.com"), "82,PARAMETER(S) OUT OF RANGE", "flags $80"); + expect_open(open_cmd(2, 0, "example.com", PIN(0)), "82,PARAMETER(S) OUT OF RANGE", "an all-zero pin"); + expect_open(open_cmd(0, 0x02, ""), "81,INVALID PARAMS", "a reserved bit AND an empty host: 81 first"); + expect_open(open_cmd(3, 0x02, std::string("a\0\0", 3)), "81,INVALID PARAMS", "trust 3 AND a bad tail: 81 first"); + expect_open(open_cmd(0, 0, "1.2.3.4"), "81,INVALID PARAMS", "BUNDLE, IPv4 host, no name"); + expect_open(open_cmd(1, 0, "1.2.3.4"), "81,INVALID PARAMS", "CUSTOM, IPv4 host, no name"); + expect_open(open_cmd(0, 0, "127.1"), "81,INVALID PARAMS", "BUNDLE, host 127.1 (ip4addr_aton)"); + expect_open(open_cmd(0, 0, "0x7f.0.0.1"), "81,INVALID PARAMS", "BUNDLE, host 0x7f.0.0.1"); + expect_open(open_cmd(0, 0, "1.2.3.4 x"), "81,INVALID PARAMS", "BUNDLE, host '1.2.3.4 x'"); + expect_open(open_cmd(0, 0, std::string("example.com\0" "10.0.0.1", 20)), "81,INVALID PARAMS", + "BUNDLE, an explicit IPv4 name"); + expect_open(open_cmd(0, 0, std::string("1.2.3.4\0", 8)), "81,INVALID PARAMS", "BUNDLE, IPv4 host $00"); + + expect_open(open_cmd(0, 0x01, "example.com"), "00,OK", "flags $01 (REQUIRE_TLS13) is accepted"); + expect_open(open_cmd(0, 0, std::string("example.com\0", 12)), "00,OK", "host $00 (dos-lib habit)"); + check(last_sni() == "example.com", "name: host $00 -> the host is the name"); + expect_open(open_cmd(0, 0, std::string("1.2.3.4\0srv.example", 19)), "00,OK", "BUNDLE, IPv4 host with a name"); + check(last_sni() == "srv.example", "name: the explicit name goes to SNI"); + expect_open(open_cmd(0, 0, std::string("example.com\0srv\0", 16)), "00,OK", "host $00 name $00"); + check(last_sni() == "srv", "name: host $00 name $00 -> name"); + expect_open(open_cmd(0, 0, h253), "00,OK", "a 253-byte host"); + expect_open(open_cmd(2, 0, "10.1.2.3", PIN()), "00,OK", "PIN to an IPv4 host, no name"); + check(last_sni() == "", "name: PIN with an IPv4 host sends no SNI"); + expect_open(open_cmd(2, 0, std::string("host.lan\0" "10.1.2.3", 17), PIN()), "00,OK", "PIN, explicit IPv4 name"); + check(last_sni() == "", "name: PIN with an explicit IPv4 name sends no SNI"); + expect_open(open_cmd(2, 0, "host.lan", PIN()), "00,OK", "PIN to a DNS name"); + check(last_sni() == "host.lan", "name: PIN with a DNS name sends SNI"); + RpcCall o = call_no(0); + check(o.pin == PIN() && o.open.trust == 2, "pin: the 32 pin bytes go to the module unchanged"); + + // No reply, nothing opened. + world_module.calls.clear(); + int dns = world_dns_calls; + Res r = run(open_cmd(0, 0, "example.com", bytes(), 443, 0x83)); + check(r.status == "81,INVALID PARAMS" && world_module.calls.empty() && world_dns_calls == dns && + world_open_sockets() == 0, "no-reply: $83 $21 opens nothing"); +} + +// --- OPEN_TLS: the refusal order ------------------------------------------------ + +static void test_precedence(void) +{ + printf("OPEN_TLS: refusal precedence, nothing on the network before the checks pass\n"); + fresh(); + world_module.available = false; + expect_open(open_cmd(0, 0, "example.com"), "90,TLS NOT AVAILABLE", "no module"); + fresh(); + int a = open_ok(), b = open_ok(); + world_dns.push_back({ "nowhere.invalid", DNS_ASYNC_NO, 0, 10 }); + world_module.calls.clear(); + int dns = world_dns_calls; + int sockets = world_open_sockets(); + Res r = run(open_cmd(0, 0, "nowhere.invalid")); + check(r.status == "91,TLS SESSIONS IN USE" && world_module.calls.empty() && world_dns_calls == dns && + world_open_sockets() == sockets, "precedence: table full + unresolvable host -> 91, no DNS, no socket"); + close_cmd(a); + close_cmd(b); + fresh(); + sock(0).srv.connect_err = ECONNREFUSED; + expect_open(open_cmd(1, 0, "example.com"), "97,NO CUSTOM CA", "CUSTOM with nothing loaded + closed port"); + fresh(); + world_module.entropy = false; + world_module.calls.clear(); + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "87,NO ENTROPY SOURCE" && world_dns_calls == 0 && world_open_sockets() == 0, + "precedence: module reason 1 -> 87, before DNS"); + fresh(); + world_module.module_time = false; + world_sntp = 0; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "92,NO TRUSTED TIME" && world_dns_calls == 0, "precedence: module reason 2 -> 92"); + r = run(open_cmd(2, 0, "10.0.0.5", PIN())); + check(r.status == "00,OK", "precedence: PIN needs no time"); + fresh(); + world_module.open_result = WIFI_TLS_REFUSED; + world_module.open_esp_err = WIFI_TLS_ESP_INVALID_STATE; + world_module.open_reason = WIFI_TLS_REASON_NO_CUSTOM_CA; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "97,NO CUSTOM CA" && world_dns_calls == 0, "precedence: module reason 3 -> 97 NO CUSTOM CA"); + fresh(); + world_module.open_result = WIFI_TLS_REFUSED; + world_module.open_esp_err = WIFI_TLS_ESP_NOT_SUPPORTED; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "90,TLS NOT AVAILABLE" && world_dns_calls == 0, + "precedence: a module without TLS (NOT_SUPPORTED) -> 90"); + fresh(); + world_module.open_result = WIFI_TLS_REFUSED; + world_module.open_esp_err = WIFI_TLS_ESP_NO_MEM; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "17,TLS MODULE NOT RESPONDING" && world_dns_calls == 0, "precedence: another refusal -> 17"); + fresh(); + world_module.open_delay_ms = 6000; + uint32_t t0 = world_ms(); + r = run(open_cmd(0, 0, "example.com")); + uint32_t spent = world_ms() - t0; + check(r.status == "17,TLS MODULE NOT RESPONDING" && world_dns_calls == 0 && world_count(0x32) == 1, + "precedence: OPEN RPC timeout -> 17, best-effort CLOSE(slot, tag), no DNS"); + check(spent >= 5000 && spent <= 6200, "precedence: OPEN_RPC_MS 5 s + CLOSE (%u ms)", spent); + fresh(); + world_module.unsent_next = 3; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "00,OK", "precedence: an unsent OPEN is sent again (UNSENT_RETRIES)"); +} + +// --- the verify classification, and other handshake ends ------------- + +static void expect_fail(uint8_t trust, uint8_t reason, uint32_t flags, uint8_t alert, int err, const char *want, + const char *what) +{ + fresh(); + world_module.hs_fail = true; + world_module.hs_fail_reason = reason; + world_module.hs_verify_flags = flags; + world_module.hs_alert_in = alert; + world_module.hs_fail_err = err; + world_module.hs_alert_out = true; + Res r = (trust == 2) ? run(open_cmd(2, 0, "host.lan", PIN())) : run(open_cmd(trust, 0, "example.com")); + check(r.status == want && r.data.empty() && world_open_sockets() == 0 && world_count(0x32) == 0 && + sock(0).srv.saw_alert == 40, + "classify: %s -> %s (got %s); socket closed, no CLOSE RPC, our alert went out", what, want, r.status.c_str()); +} + +static void test_classify(void) +{ + printf("OPEN_TLS: handshake failures to codes\n"); + const uint8_t N = WIFI_TLS_ALERT_NONE; + expect_fail(0, 0, 0, 70, -0x7780, "14,TLS ALERT RECEIVED: 70", "reason 0 with alert 70"); + expect_fail(0, 0, 0, N, -0x7280, "13,TLS HANDSHAKE FAILED: -0x7280", "reason 0, no alert"); + expect_fail(0, 1, 0x0303, N, -0x7700, "18,TLS VERSION REFUSED: 0x0303", "reason 1 (TLS 1.2 under REQUIRE_TLS13)"); + expect_fail(0, 1, 0x0302, N, -0x7700, "18,TLS VERSION REFUSED: 0x0302", "reason 1 (below 1.2)"); + expect_fail(0, 2, 0, N, -0x7700, "19,TLS DOWNGRADE DETECTED", "reason 2"); + expect_fail(0, 3, 0, N, -0x7700, "13,TLS HANDSHAKE FAILED: NO EMS", "reason 3"); + expect_fail(0, 4, 0x08, N, -0x2700, "93,CERTIFICATE NOT TRUSTED: 0x00000008", "BUNDLE, unknown root (exact)"); + expect_fail(0, 4, 0xFFFFFFFF, N, -0x3000, "93,CERTIFICATE NOT TRUSTED: 0xFFFFFFFF", "w = 0xFFFFFFFF"); + expect_fail(0, 4, 0x0C, N, -0x2700, "94,CERTIFICATE NAME MISMATCH: 0x0000000C", "BUNDLE, w 0x0C (name mismatch first)"); + expect_fail(0, 4, 0x05, N, -0x2700, "94,CERTIFICATE NAME MISMATCH: 0x00000005", "BUNDLE, name and expiry"); + expect_fail(0, 4, 0x01, N, -0x2700, "95,CERTIFICATE EXPIRED: 0x00000001", "BUNDLE, expired"); + expect_fail(0, 4, 0x200, N, -0x2700, "95,CERTIFICATE EXPIRED: 0x00000200", "BUNDLE, not yet valid"); + expect_fail(0, 4, 0x4000, N, -0x7A00, "93,CERTIFICATE NOT TRUSTED: 0x00004000", "BUNDLE, BAD_MD"); + expect_fail(2, 4, 0x04, N, -0x7A00, "93,CERTIFICATE NOT TRUSTED: 0x00000004", "PIN, w 0x04 (no name check)"); + expect_fail(2, 4, 0x01, N, -0x7A00, "93,CERTIFICATE NOT TRUSTED: 0x00000001", "PIN, w 0x01"); + expect_fail(2, 4, 0x200, N, -0x7A00, "93,CERTIFICATE NOT TRUSTED: 0x00000200", "PIN, w 0x200"); + expect_fail(2, 5, 0x08, N, -0x2700, "96,PINNED KEY MISMATCH", "PIN, reason 5"); + expect_fail(0, 5, 0x08, N, -0x2700, "17,TLS MODULE NOT RESPONDING", "BUNDLE, reason 5 (PIN only: malformed)"); + expect_fail(0, 6, 0, N, -0x7280, "13,TLS HANDSHAKE FAILED: PEER CLOSED", "reason 6"); + expect_fail(0, 7, 0, N, -0x0103, "13,TLS HANDSHAKE FAILED: NO ENTROPY", "reason 7 (the source went off after the OPEN)"); + expect_fail(0, 9, 0, N, -0x7280, "17,TLS MODULE NOT RESPONDING", "an unknown reason"); + + fresh(); + sock(0).srv.on_hello = SRV_RST; + Res r = run(open_cmd(0, 0, "example.com")); + check(r.status == "13,TLS HANDSHAKE FAILED: PEER RESET: " + num(ECONNRESET) && world_open_sockets() == 0 && + world_count(0x32) == 1, "handshake: RST after the ClientHello -> 13 PEER RESET: errno, CLOSE RPC (S7c)"); + fresh(); + sock(0).srv.on_hello = SRV_FIN; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "13,TLS HANDSHAKE FAILED: PEER CLOSED" && world_open_sockets() == 0 && world_count(0x32) == 1, + "handshake: FIN mid-handshake -> 13 PEER CLOSED"); + fresh(); + sock(0).srv.on_hello = SRV_STALL; + uint32_t t0 = world_ms(); + r = run(open_cmd(0, 0, "example.com")); + uint32_t spent = world_ms() - t0; + check(r.status == "15,TLS HANDSHAKE TIMEOUT" && world_open_sockets() == 0 && world_count(0x32) == 1, + "handshake: a stalled server -> 15, CLOSE RPC, socket closed (S10)"); + check(spent >= 15000 && spent <= 16300, "handshake: within HANDSHAKE_MS + CLOSE (%u ms)", spent); + fresh(); + world_module.forced.push_back(Forced()); + world_module.forced.back().result = WIFI_TLS_BUSY; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "17,TLS MODULE NOT RESPONDING" && world_count(0x32) == 1 && world_open_sockets() == 0, + "handshake: a STEP timeout -> 17 and CLOSE(slot, tag)"); +} + +// --- DNS and connect ------------------------------------------------------ + +static void test_dns_connect(void) +{ + printf("OPEN_TLS: DNS inside OPEN, connect\n"); + fresh(); + world_dns.push_back({ "slow.example", DNS_NEVER, 0, 0 }); + uint32_t t0 = world_ms(); + Res r = run(open_cmd(0, 0, "slow.example")); + uint32_t spent = world_ms() - t0; + check(r.status == "84,UNRESOLVED HOST" && world_count(0x32) == 1 && world_open_sockets() == 0, + "dns: no answer -> 84 and the module session CLOSEd"); + check(spent >= 10000 && spent <= 11200, "dns: after DNS_MS (%u ms)", spent); + fresh(); + world_dns.push_back({ "bad.example", DNS_ASYNC_NO, 0, 30 }); + r = run(open_cmd(0, 0, "bad.example")); + check(r.status == "84,UNRESOLVED HOST", "dns: a failed lookup -> 84"); + fresh(); + world_dns.push_back({ "val.example", DNS_ERR_VAL, 0, 0 }); + r = run(open_cmd(0, 0, "val.example")); + check(r.status == "84,UNRESOLVED HOST", "dns: ERR_VAL -> 84"); + // A late answer to an abandoned lookup is never taken for the next one. + fresh(); + world_dns.push_back({ "a.example", DNS_ASYNC_OK, 0x01010101, 12000 }); + world_dns.push_back({ "b.example", DNS_ASYNC_OK, 0x02020202, 3000 }); + r = run(open_cmd(0, 0, "a.example")); + check(r.status == "84,UNRESOLVED HOST", "dns: a.example answers after DNS_MS -> 84"); + r = run(open_cmd(0, 0, "b.example")); + int h = r.data.empty() ? 0 : r.data[0]; + check(r.status == "00,OK" && sock(h).connect_addr == 0x02020202, + "dns: the next OPEN connects to b's address, not a's late answer (the slot seq)"); + check(world_lock_bad == 0 && world_dns_unlocked_calls == 0, "dns: lookups start under the lock"); + fresh(); + r = run(open_cmd(2, 0, "10.9.8.7", PIN())); + h = r.data.empty() ? 0 : r.data[0]; + check(r.status == "00,OK" && sock(h).connect_addr == htonl(0x0A090807), + "dns: an IPv4 literal resolves at once"); + + fresh(); + sock(0).srv.connect_err = ECONNREFUSED; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "11,ERROR ON CONNECT: " + num(ECONNREFUSED) && world_count(0x32) == 1 && + world_open_sockets() == 0, "connect: refused -> 11 with errno, session CLOSEd, socket closed"); + fresh(); + sock(0).srv.connect_never = true; + t0 = world_ms(); + r = run(open_cmd(0, 0, "example.com")); + spent = world_ms() - t0; + check(r.status == "11,ERROR ON CONNECT: " + num(ETIMEDOUT) && spent >= 10000 && spent <= 11300, + "connect: no answer -> 11 ETIMEDOUT after CONNECT_MS (%u ms)", spent); + + // The whole OPEN is bounded (OPEN_TOTAL_MS + CLOSE_RPC_MS + a slice). + fresh(); + world_module.open_delay_ms = 4900; + world_dns.push_back({ "slow.example", DNS_ASYNC_OK, 0x03030303, 9900 }); + sock(0).srv.connect_delay_ms = 9900; + sock(0).srv.on_hello = SRV_STALL; + t0 = world_ms(); + r = run(open_cmd(0, 0, "slow.example")); + spent = world_ms() - t0; + check(r.status == "15,TLS HANDSHAKE TIMEOUT" && spent <= 41100, + "budget: slow OPEN RPC, DNS, connect and a stalled server end within 41.1 s (%u ms, %s)", spent, + r.status.c_str()); +} + +// --- a C64 reset during OPEN -------------------------------------------------- + +static void test_reset_during_open(void) +{ + printf("OPEN_TLS: a reset ends it at once\n"); + fresh(); + sock(0).srv.on_hello = SRV_STALL; + world_reset_at = world_tick + 600; // 3 s in + Res r = run(open_cmd(0, 0, "example.com")); + uint32_t late = (world_tick - world_reset_at) * 5; + check(late <= 110, "reset: the OPEN returns within a slice of the reset (%u ms late)", late); + check(world_open_sockets() == 0 && world_count(0x32) == 0, "reset: socket closed, no CLOSE RPC waited for"); + world_reset_at = 0xFFFFFFFF; + check(world_module.close_alls == 1, "reset: c64_reset sends CLOSE_ALL once"); + r = info(0xFF); + check(r.data.size() == 16 && r.data[2] == 0, "reset: no entries afterwards"); + fresh(); + world_dns.push_back({ "never.example", DNS_NEVER, 0, 0 }); + world_reset_at = world_tick + 200; + r = run(open_cmd(0, 0, "never.example")); + late = (world_tick - world_reset_at) * 5; + check(late <= 110 && world_open_sockets() == 0, "reset: during DNS too (%u ms late)", late); + world_reset_at = 0xFFFFFFFF; +} + +// --- START_TLS ($24) -------------------------------------------------------------------- + +static int open_tcp(void) +{ + Res r = run(B({ 0x03, 0x07, 0x19, 0x00, 'm', 'a', 'i', 'l' })); + return (r.status == "00,OK") ? at(r, 0) : -1; +} + +static bytes start_cmd(int h, uint8_t trust, uint8_t flags, const std::string &tail, const bytes &pin = bytes(), + uint8_t first = 0x03) +{ + return cat(cat(B({ first, 0x24, h, trust, flags }), pin), S(tail)); +} + +// An OPEN_TCP socket carries the send slice (SOCKET_SLICE_MS in software/network/socket_slices.h) as its +// SO_SNDTIMEO; what START_TLS must not change is that, and the TLS value is 500 ms. +#define PLAIN_SNDTIMEO_MS 100 + +static void expect_kept(int h, const bytes &cmd, const char *want, const char *what) +{ + Res r = run(cmd); + bool untouched = sock(h).open && !sock(h).nodelay && !sock(h).nonblocking && (sock(h).sndtimeo_ms == PLAIN_SNDTIMEO_MS); + check(r.status == want && r.data.empty() && untouched, "start: %s -> %s, TCP handle unchanged (got %s)", what, + want, r.status.c_str()); +} + +// --- an abort during OPEN, START_TLS and the CA upload --------------------------------------- + +// The job's cancel flag is set by the UCI Server task on an abort. The worker has to be free within a slice, +// and what the aborted command opened on the module is still closed. +static void test_abort_during_open(void) +{ + printf("OPEN_TLS, START_TLS: an abort frees the worker at once, and the module is told to CLOSE\n"); + fresh(); + sock(0).srv.on_hello = SRV_STALL; + world_abort_at = world_tick + 600; // in the handshake + Res r = run(open_cmd(0, 0, "example.com")); + uint32_t late = (world_tick - world_abort_at) * 5; + check(late <= 110, "abort: a stalled handshake returns within a slice of the abort (%u ms late)", late); + check(world_open_sockets() == 0 && world_count(0x32) == 1, "abort: socket closed, the module's session CLOSEd"); + world_abort_at = 0xFFFFFFFF; + check(run(B({ 0x03, 0x23, 0xFF })).status == "00,OK", "abort: the next socket command runs"); + + fresh(); + world_dns.push_back({ "never.example", DNS_NEVER, 0, 0 }); + world_abort_at = world_tick + 200; + r = run(open_cmd(0, 0, "never.example")); + late = (world_tick - world_abort_at) * 5; + check(late <= 110 && world_open_sockets() == 0, "abort: during DNS too (%u ms late)", late); + world_abort_at = 0xFFFFFFFF; + + fresh(); + sock(0).srv.connect_never = true; + world_abort_at = world_tick + 200; + r = run(open_cmd(0, 0, "example.com")); + late = (world_tick - world_abort_at) * 5; + check(late <= 110 && world_open_sockets() == 0, "abort: during connect too (%u ms late)", late); + world_abort_at = 0xFFFFFFFF; + + fresh(); + world_module.open_delay_ms = 4000; + world_abort_at = world_tick + 200; + r = run(open_cmd(0, 0, "example.com")); + late = (world_tick - world_abort_at) * 5; + check(late <= 110, "abort: during the OPEN RPC too (%u ms late)", late); + world_abort_at = 0xFFFFFFFF; + + fresh(); + int t = open_tcp(); + sock(t).srv.on_hello = SRV_STALL; + world_abort_at = world_tick + 600; + r = run(start_cmd(t, 0, 0, "mail.example")); + late = (world_tick - world_abort_at) * 5; + check(late <= 110, "abort: START_TLS's stalled handshake too (%u ms late)", late); + world_abort_at = 0xFFFFFFFF; +} + +// A reset reaches the worker as a count, not as the command interface's flag. +static void test_reset_during_start(void) +{ + printf("START_TLS: a reset ends the handshake at once\n"); + fresh(); + int t = open_tcp(); + sock(t).srv.on_hello = SRV_STALL; + world_reset_at = world_tick + 600; + Res r = run(start_cmd(t, 0, 0, "mail.example")); + uint32_t late = (world_tick - world_reset_at) * 5; + check(late <= 110, "reset: a stalled START_TLS returns within a slice of the reset (%u ms late)", late); + world_reset_at = 0xFFFFFFFF; +} + +static void test_start_tls(void) +{ + printf("START_TLS ($24): handle checks first, kept codes, success\n"); + fresh(); + int t = open_tcp(); + Res u = run(B({ 0x03, 0x08, 0x35, 0x00, 'n', 's' })); + int udp = u.data.empty() ? -1 : u.data[0]; + check(t >= 0 && udp >= 0, "start: a TCP and a UDP handle to work with"); + check((sock(t).sndtimeo_ms == PLAIN_SNDTIMEO_MS) && !sock(t).nodelay, "start: OPEN_TCP's socket gets neither (TLS sockets only)"); + Res r = run(start_cmd(udp, 2, 0, "", PIN())); + check(r.status == "81,INVALID PARAMS" && sock(udp).open, "start: on a UDP handle -> 81, UDP untouched"); + r = run(start_cmd(12, 2, 0, "", PIN())); + check(r.status == "81,INVALID PARAMS", "start: on an unowned number -> 81"); + r = run(start_cmd(udp, 3, 0x80, "")); + check(r.status == "81,INVALID PARAMS", "start: UDP handle AND trust 3: the handle check comes first -> 81"); + r = run(start_cmd(12, 3, 0, "x")); + check(r.status == "81,INVALID PARAMS", "start: unowned number AND trust 3 -> 81, not 82"); + r = run(B({ 0x03, 0x24 })); + check(r.status == "81,INVALID PARAMS", "start: no handle byte -> 81"); + expect_kept(t, start_cmd(t, 3, 0, "mail.example"), "82,PARAMETER(S) OUT OF RANGE", "trust 3"); + expect_kept(t, start_cmd(t, 0, 2, "mail.example"), "82,PARAMETER(S) OUT OF RANGE", "flags $02"); + expect_kept(t, start_cmd(t, 2, 0, "", PIN(0)), "82,PARAMETER(S) OUT OF RANGE", "zero pin"); + expect_kept(t, start_cmd(t, 0, 0, ""), "81,INVALID PARAMS", "BUNDLE without a name"); + expect_kept(t, start_cmd(t, 0, 0, std::string("\0", 1)), "81,INVALID PARAMS", "BUNDLE, a lone $00"); + expect_kept(t, start_cmd(t, 0, 0, "10.0.0.1"), "81,INVALID PARAMS", "BUNDLE, an IPv4 name"); + expect_kept(t, start_cmd(t, 0, 0, std::string("a\0b", 3)), "81,INVALID PARAMS", "bytes after the name's $00"); + expect_kept(t, start_cmd(t, 1, 0, "mail.example"), "97,NO CUSTOM CA", "CUSTOM, nothing loaded"); + world_module.available = false; + expect_kept(t, start_cmd(t, 0, 0, "mail.example"), "90,TLS NOT AVAILABLE", "no module"); + world_module.available = true; + world_module.entropy = false; + expect_kept(t, start_cmd(t, 0, 0, "mail.example"), "87,NO ENTROPY SOURCE", "module reason 1"); + world_module.entropy = true; + world_module.module_time = false; + world_sntp = 0; + expect_kept(t, start_cmd(t, 0, 0, "mail.example"), "92,NO TRUSTED TIME", "module reason 2"); + world_module.module_time = true; + world_sntp = 1790000000u; + // The TCP handle still carries plaintext after all of that. + server_push(t, EV_DATA, S("220 hello\r\n")); + r = read_cmd(t, 100); + check(r.status == "00,OK" && body(r) == S("220 hello\r\n"), "start: the TCP handle still reads plaintext"); + + world_module.calls.clear(); + r = run(start_cmd(t, 2, 0, std::string("\0", 1), PIN())); + check(r.status == "00,OK" && r.data.size() == 8 && r.data[0] == t, "start: PIN, a lone $00 -> OK, the same handle"); + check(last_sni() == "", "start: no name -> no SNI"); + check(sock(t).nodelay && sock(t).nonblocking && (sock(t).sndtimeo_ms == 500), + "start: TCP_NODELAY and SO_SNDTIMEO 500 ms once every refusal check passed"); + r = run(start_cmd(t, 2, 0, "", PIN())); + check(r.status == "81,INVALID PARAMS" && sock(t).open, "start: on a TLS handle -> 81, session untouched"); + check(info(t).data.size() == 48, "start: the handle is a TLS handle now"); + close_cmd(t); + + fresh(); + t = open_tcp(); + world_module.hs_fail = true; + world_module.hs_fail_reason = 4; + world_module.hs_verify_flags = 0x08; + r = run(start_cmd(t, 0, 0, "mail.example")); + check(r.status == "93,CERTIFICATE NOT TRUSTED: 0x00000008" && !sock(t).open, + "start: a 93 closes the handle (every code but the kept ones)"); + r = close_cmd(t); + check(r.status == "12,ERROR ON CLOSE: " + num(EBADF), "start: CLOSE after it -> 12,ERROR ON CLOSE: 9"); + // 87 is answered at the OPEN only, with the handle kept. A source lost in the handshake is a 13 and ends the handle. + fresh(); + t = open_tcp(); + world_module.hs_fail = true; + world_module.hs_fail_reason = 7; + r = run(start_cmd(t, 0, 0, "mail.example")); + check(r.status == "13,TLS HANDSHAKE FAILED: NO ENTROPY" && !sock(t).open, + "start: a source lost in the handshake -> 13 NO ENTROPY, handle closed (87 is only ever kept)"); + r = close_cmd(t); + check(r.status == "12,ERROR ON CLOSE: " + num(EBADF), "start: CLOSE after the 13 NO ENTROPY -> 12"); + fresh(); + t = open_tcp(); + world_module.open_delay_ms = 6000; + r = run(start_cmd(t, 0, 0, "mail.example")); + check(r.status == "17,TLS MODULE NOT RESPONDING" && !sock(t).open, + "start: a 17 from the OPEN RPC closes the handle"); + fresh(); + t = open_tcp(); + int a = open_ok(), b = open_ok(); + expect_kept(t, start_cmd(t, 0, 0, "mail.example"), "91,TLS SESSIONS IN USE", "table full"); + close_cmd(a); + close_cmd(b); + // No reply: nothing happens. + world_module.calls.clear(); + r = run(start_cmd(t, 2, 0, "", PIN(), 0x83)); + check(world_module.calls.empty() && sock(t).open && !sock(t).nodelay, + "start: $83 $24 does nothing"); +} + +// --- READ, WRITE and CLOSE on a TLS handle ----------------------------------------------- + +static void test_read(void) +{ + printf("READ on a TLS handle\n"); + fresh(); + int h = open_ok(); + uint32_t t0 = world_ms(); + Res r = read_cmd(h, 100); + check(header(r) == 0xFFFF && r.status == "02,NO DATA: " + num(EWOULDBLOCK), + "read: nothing yet -> $FFFF + 02,NO DATA: 11 (%s)", r.status.c_str()); + check(world_ms() - t0 <= 300, "read: an idle READ is short (%u ms)", world_ms() - t0); + check(read_cmd(h, 0).status == "82,PARAMETER(S) OUT OF RANGE", "read: maxlen 0 -> 82"); + check(read_cmd(h, 1473).status == "82,PARAMETER(S) OUT OF RANGE", "read: maxlen 1473 -> 82"); + + server_push(h, EV_DATA, record('D', 3000, 5)); + server_push(h, EV_DATA, record('C', 0)); + server_push(h, EV_FIN, bytes()); + std::string last; + bytes got = read_all(h, 1472, &last); + check(got == expected(5, 3000), "read: all 3000 B of one record, in order (%d)", (int)got.size()); + check(last == "01,CONNECTION CLOSED BY HOST" && !sock(h).open, "read: then $0000 + 01, handle GONE (S6)"); + check(sock(h).srv.saw_notify, "read: the peer's close_notify is answered with ours (RFC 8446 6.1)"); + check(close_cmd(h).status == "12,ERROR ON CLOSE: " + num(EBADF), "read: CLOSE afterwards -> 12,…: 9"); + r = read_cmd(h, 10); + check(header(r) == 0xFFFF && r.status == "02,NO DATA: " + num(EBADF), "read: READ afterwards -> 02,NO DATA: 9"); + + // The peer closed TCP behind its close_notify: our answer finds a dead socket, which is not an error. + fresh(); + h = open_ok(); + server_push(h, EV_DATA, cat(record('D', 100, 7), record('C', 0))); + sock(h).srv.send_err_from = sock(h).send_calls + 1; + sock(h).srv.send_err_late = EPIPE; + got = read_all(h, 1472, &last); + check(got == expected(7, 100) && last == "01,CONNECTION CLOSED BY HOST", + "read: our close_notify refused by a closed peer -> all bytes, then 01 (%s)", last.c_str()); + + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 3000, 6)); + server_push(h, EV_FIN, bytes()); + got = read_all(h, 1472, &last); + check(got == expected(6, 3000) && last == "05,TLS CLOSED WITHOUT NOTIFY" && !sock(h).open, + "read: 3000 B, then FIN -> all data, then 05, GONE (S7)"); + check(sock(h).srv.saw_notify, "read: 05 closes the live session with close_notify"); + + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 100, 7)); + uint8_t alert = 80; + server_push(h, EV_DATA, bytes({ 'A', 1, 0, alert })); + got = read_all(h, 1472, &last); + check(got == expected(7, 100) && last == "14,TLS ALERT RECEIVED: 80", "read: data, then an alert -> 14"); + r = read_cmd(h, 10); + check(header(r) == 0 && r.status == "14,TLS ALERT RECEIVED: 80", "read: sticky: $0000 + 14 again"); + r = write_cmd(h, S("x")); + check(header(r) == 0xFFFF && r.status == "14,TLS ALERT RECEIVED: 80", "read: WRITE -> $FFFF + the same"); + check(info_byte(2) == 1, "read: INFO counts the sticky entry"); + world_module.calls.clear(); + check(close_cmd(h).status == "00,OK" && world_count(0x32) == 0 && !sock(h).open, + "read: CLOSE -> 00,OK, no RPC (module freed it)"); + check(info_byte(2) == 0, "read: entry freed"); + + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('B', 40)); + got = read_all(h, 1472, &last); + check(last == "16,TLS SESSION FAILED: -0x7180", "read: a bad record -> 16 with the mbedTLS code (%s)", + last.c_str()); + + fresh(); + h = open_ok(); + world_module.forced.push_back(Forced()); + world_module.forced.back().result = WIFI_TLS_BUSY; + server_push(h, EV_DATA, record('D', 10, 1)); + t0 = world_ms(); + r = read_cmd(h, 100); + check(header(r) == 0 && r.status == "17,TLS MODULE NOT RESPONDING" && world_count(0x32) == 1, + "read: a STEP timeout -> $0000 + 17, and CLOSE(slot, tag) at once"); + check(world_ms() - t0 <= 11100, "read: within READ_TOTAL_MS + CLOSE (%u ms)", world_ms() - t0); + check(read_cmd(h, 10).status == "17,TLS MODULE NOT RESPONDING", "read: 17 is sticky"); + world_module.calls.clear(); + check(close_cmd(h).status == "00,OK" && world_count(0x32) == 0, "read: CLOSE after a cleanup CLOSE sends no RPC"); + + fresh(); + h = open_ok(); + world_module.forced.push_back(Forced()); + world_module.forced.back().result = WIFI_TLS_REFUSED; + world_module.forced.back().esp_err = WIFI_TLS_ESP_NOT_FOUND; + server_push(h, EV_DATA, record('D', 10, 1)); + r = read_cmd(h, 100); + check(r.status == "17,TLS MODULE NOT RESPONDING" && world_count(0x32) == 0, + "read: NOT_FOUND -> 17, no CLOSE (the module has no session)"); + + // A big record over many READs, and the byte-exact slicing (S13). + int sizes[] = { 1, 100, 893, 894, 1472 }; + for (int i = 0; i < 5; i++) { + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 16000, 9)); + server_push(h, EV_DATA, record('C', 0)); + got = read_all(h, sizes[i], &last, NULL, 20000); + check(got == expected(9, 16000) && last == "01,CONNECTION CLOSED BY HOST", + "read: a 16 KB record with maxlen %d is byte exact (%d)", sizes[i], (int)got.size()); + } + // A reply of more than one block carries the whole count in its header. + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 960, 3)); + r = read_cmd(h, 1472); + check(header(r) == 960 && body(r) == expected(3, 960) && r.status == "00,OK", + "read: 960 B over two blocks, header 960, status once"); + + // Tickets ahead of data: the READs go on stepping until the data arrives. + fresh(); + h = open_ok(); + for (int i = 0; i < 10; i++) { + server_push(h, EV_DATA, record('T', 200, i)); + } + server_push(h, EV_DATA, record('D', 50, 4)); + got = read_all(h, 1472, &last, NULL, 60); + check(got == expected(4, 50), "read: 10 tickets, then the data arrives (S13)"); + + // READ never steps while rx is non-empty. + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 900, 2)); + r = read_cmd(h, 100); + int before = steps_logged(); + r = read_cmd(h, 100); + bytes e900 = expected(2, 900); + check(steps_logged() == before && body(r) == bytes(e900.begin() + 100, e900.begin() + 200), + "read: the second READ comes from rx with no STEP"); + + // AGAIN: the same input goes again, and nothing is lost. + fresh(); + h = open_ok(); + world_module.again_next = 1; + server_push(h, EV_DATA, record('D', 500, 8)); + got = read_all(h, 1472, &last, NULL, 5); + check(got == expected(8, 500), "read: after AGAIN the same ciphertext is sent again (%d)", (int)got.size()); + + // READ_BUDGET: at most 8 steps per READ. + fresh(); + h = open_ok(); + for (int i = 0; i < 30; i++) { + server_push(h, EV_DATA, record('T', 20, i)); + } + before = steps_logged(); + r = read_cmd(h, 100); + check(steps_logged() - before <= 8 && header(r) == 0xFFFF, "read: 8 steps at most, then NO DATA (%d steps)", + steps_logged() - before); + for (size_t i = 0; i < world_module.calls.size(); i++) { + if ((world_module.calls[i].cmd == 0x31) && (world_module.calls[i].flags != 0)) { + check(false, "read: READ steps never carry NO_READ"); + break; + } + } +} + +static void test_write(void) +{ + printf("WRITE on a TLS handle\n"); + fresh(); + int h = open_ok(); + int before = steps_logged(); + Res r = write_cmd(h, bytes()); + check(header(r) == 0 && r.status == "00,OK" && steps_logged() == before, "write: 0 bytes -> 0000, OK, no step"); + bytes data = expected(11, 892); + world_module.calls.clear(); + r = write_cmd(h, data); + check(header(r) == 892 && r.status == "00,OK", "write: 892 B -> header 892, 00,OK"); + check(sock(h).srv.got == data, "write: the server got exactly those bytes"); + bool no_read = true; + int steps = 0; + for (size_t i = 0; i < world_module.calls.size(); i++) { + const RpcCall &c = world_module.calls[i]; + if (c.cmd == 0x31) { + steps++; + no_read = no_read && (c.flags == WIFI_TLS_STEP_NO_READ) && (c.ct_in_len == 0); + } + } + check(no_read && steps <= 4, "write: every step has NO_READ and ct_in_len 0 (%d steps)", steps); + + // WRITE between READs of one record. + for (int w = 0; w < 2; w++) { + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 3000, 12)); + r = read_cmd(h, 100); + bytes got = body(r); + r = write_cmd(h, w ? expected(1, 892) : S("x")); + check(r.status == "00,OK", "write: a %d-B WRITE mid-record -> OK", w ? 892 : 1); + std::string last; + bytes rest = read_all(h, 1472, &last, NULL, 20); + got.insert(got.end(), rest.begin(), rest.end()); + check(got == expected(12, 3000), "write: the READs still give all 3000 B in order (%d)", (int)got.size()); + } + + // Budget, AGAIN, send failures, failures from the module. + fresh(); + h = open_ok(); + world_module.again_next = 10; + r = write_cmd(h, S("hello")); + check(header(r) == 0xFFFF && r.status == "17,TLS MODULE NOT RESPONDING" && world_count(0x32) == 1, + "write: AGAIN past WRITE_BUDGET -> $FFFF + 17, cleanup CLOSE"); + check(write_cmd(h, S("x")).status == "17,TLS MODULE NOT RESPONDING", "write: sticky"); + fresh(); + h = open_ok(); + world_module.again_next = 1; + r = write_cmd(h, S("hello")); + check(header(r) == 5 && sock(h).srv.got == S("hello"), "write: one AGAIN, sent again, once"); + fresh(); + h = open_ok(); + sock(h).send_err = EPIPE; + r = write_cmd(h, S("hello")); + check(header(r) == 0xFFFF && r.status == "12,SEND ERROR: " + num(EPIPE), "write: send error -> $FFFF + 12"); + r = read_cmd(h, 10); + check(header(r) == 0 && r.status == "12,SEND ERROR: " + num(EPIPE), "write: then READ -> $0000 + the same 12"); + fresh(); + h = open_ok(); + sock(h).send_blocked = true; + uint32_t t0 = world_ms(); + r = write_cmd(h, S("hello")); + uint32_t spent = world_ms() - t0; + check(header(r) == 0xFFFF && r.status == "12,SEND ERROR: " + num(ETIMEDOUT) && spent >= 5000 && spent <= 5300, + "write: a stalled send -> 12,SEND ERROR: ETIMEDOUT after SEND_MS (%u ms, S32)", spent); + fresh(); + h = open_ok(); + world_module.forced.push_back(Forced()); + world_module.forced.back().pt_on_no_read = true; + r = write_cmd(h, S("hello")); + check(r.status == "17,TLS MODULE NOT RESPONDING", "write: plaintext on a NO_READ step -> 17 (malformed)"); + fresh(); + h = open_ok(); + world_module.forced.push_back(Forced()); + world_module.forced.back().fail = true; + world_module.forced.back().alert_in = 21; + world_module.forced.back().fail_err = -0x7780; + r = write_cmd(h, S("hello")); + check(header(r) == 0xFFFF && r.status == "14,TLS ALERT RECEIVED: 21", "write: FAILED with an alert -> 14"); + fresh(); + h = open_ok(); + world_module.forced.push_back(Forced()); + world_module.forced.back().result = WIFI_TLS_BUSY; + world_module.forced.back().applied = true; + r = write_cmd(h, S("hello")); + check(header(r) == 0xFFFF && r.status == "17,TLS MODULE NOT RESPONDING" && world_count(0x32) == 1, + "write: a STEP timeout -> 17, cleanup CLOSE, never a partial count"); + // The peer's close_notify ended the session on the module (our reading of the protocol). + fresh(); + h = open_ok(); + server_push(h, EV_DATA, cat(record('D', 20, 1), record('C', 0))); + r = read_cmd(h, 5); + r = write_cmd(h, S("late")); + check(header(r) == 0xFFFF && r.status == "12,SEND ERROR: " + num(EPIPE), + "write: after the peer's close_notify -> $FFFF + 12,SEND ERROR: EPIPE (sticky)"); +} + +static void test_close(void) +{ + printf("CLOSE on a TLS handle\n"); + fresh(); + int h = open_ok(); + uint16_t tag = 0; + for (size_t i = 0; i < world_module.calls.size(); i++) { + if (world_module.calls[i].cmd == 0x30) { + tag = world_module.calls[i].open.tag; + } + } + world_module.calls.clear(); + Res r = close_cmd(h); + check(r.status == "00,OK" && r.data.empty(), "close: 00,OK"); + check(world_count(0x32) == 1 && call_no(0).slot == 0 && call_no(0).tag == tag, + "close: CLOSE(slot, tag) RPC"); + check(sock(h).srv.saw_notify && !sock(h).open, "close: close_notify sent, then the socket closed"); + check(info_byte(2) == 0, "close: the entry is free"); + world_module.close_result = WIFI_TLS_BUSY; + h = open_ok(); + r = close_cmd(h); + check(r.status == "00,OK" && !sock(h).open, "close: 00,OK even when the module does not answer"); +} + +// --- latch-and-drain after a receive error ------------------------------- + +// An established session whose module holds n bytes of plaintext and then +// `terminal`, and whose socket answers the first recv with ECONNRESET. +static int latch_setup(size_t n, char terminal, uint8_t alert = 80) +{ + fresh(); + int h = open_ok(); + FakeSession &s = world_module.sess[0]; + for (size_t i = 0; i < n; i++) { + s.pt.push_back(payload_byte(21, i)); + } + s.terminal = terminal; + s.alert = alert; + server_push(h, EV_ERR, bytes(), ECONNRESET); + return h; +} + +static void test_latch(void) +{ + printf("READ: latch-and-drain after a receive error\n"); + const std::string rst = "12,RECEIVE ERROR: " + num(ECONNRESET); + std::string last; + int reads; + int h = latch_setup(2500, 0); + bytes got = read_all(h, 1472, &last, &reads, 50); + check(got == expected(21, 2500), "latch: every held byte is delivered first (%d of 2500)", (int)got.size()); + check(last == rst, "latch: then $0000 + %s (got %s)", rst.c_str(), last.c_str()); + Res r = read_cmd(h, 10); + check(header(r) == 0 && r.status == rst, "latch: sticky on the next READ"); + check(sock(h).recv_after_err == 0, "latch: no lwip_recv after the latch; the FIRST errno is kept"); + check(close_cmd(h).status == "00,OK" && world_count(0x32) >= 1, "latch: CLOSE -> 00,OK (module session freed)"); + + h = latch_setup(2500, 'C'); + got = read_all(h, 1472, &last, NULL, 50); + check(got == expected(21, 2500) && last == "01,CONNECTION CLOSED BY HOST" && !sock(h).open, + "latch: close_notify held behind the data wins -> all bytes, then 01"); + + h = latch_setup(2500, 'A', 80); + got = read_all(h, 1472, &last, NULL, 50); + check(got == expected(21, 2500) && last == "14,TLS ALERT RECEIVED: 80", + "latch: a fatal alert held behind the data wins -> all bytes, then 14 (%s)", last.c_str()); + + // One quiet input-less step does not end the drain. + h = latch_setup(1500, 0); + world_module.quiet_next = 1; + got = read_all(h, 1472, &last, NULL, 50); + check(got == expected(21, 1500) && last == rst, + "latch: a quiet step while the module still holds plaintext does not end the drain (%d)", (int)got.size()); + + // Quiet and plaintext steps alternating: plaintext breaks the run of quiet steps, so the drain goes on. + h = latch_setup(3000, 0); + world_module.quiet_alternate = true; + got = read_all(h, 1472, &last, NULL, 50); + check(got == expected(21, 3000) && last == rst, + "latch: quiet steps between plaintext steps never add up to the end of the drain (%d)", (int)got.size()); + + h = latch_setup(0, 0); + r = read_cmd(h, 10); + check(header(r) == 0 && r.status == rst, "latch: nothing held -> 12 at once"); + + // (a) WRITE while latched: nothing sent; the end is fixed to that 12. + h = latch_setup(2500, 'C'); + r = read_cmd(h, 100); + bytes first = body(r); + int sends = sock(h).send_calls; + r = write_cmd(h, S("ping")); + check(header(r) == 0xFFFF && r.status == rst && sock(h).send_calls == sends, + "latch (a): WRITE while latched -> $FFFF + %s, no lwip_send", rst.c_str()); + got = read_all(h, 1472, &last, NULL, 50); + first.insert(first.end(), got.begin(), got.end()); + check(first == expected(21, 2500) && last == rst && sock(h).open, + "latch (a): READs deliver every byte and end in that 12, not 01, handle still owned"); + // (a2) the same with a fatal alert behind, READs of 1 byte. + h = latch_setup(1200, 'A', 80); + r = read_cmd(h, 1); + first = body(r); + write_cmd(h, S("ping")); + got = read_all(h, 1, &last, NULL, 3000); + first.insert(first.end(), got.begin(), got.end()); + check(first == expected(21, 1200) && last == rst, + "latch (a2): alert behind the data after a WRITE's 12 -> every byte (%d), then 12 not 14", + (int)first.size()); + // (a3) a record that fails its MAC. + h = latch_setup(1200, 'B'); + r = read_cmd(h, 1); + first = body(r); + write_cmd(h, S("ping")); + got = read_all(h, 1, &last, NULL, 3000); + first.insert(first.end(), got.begin(), got.end()); + check(first == expected(21, 1200) && last == rst, "latch (a3): bad MAC behind -> every byte, then 12 not 16"); + // (b) the RST found by a WRITE first: the held plaintext is discarded. + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('D', 1200, 21)); + r = read_cmd(h, 10); + sock(h).send_err = ECONNRESET; + server_push(h, EV_ERR, bytes(), ECONNRESET); + r = write_cmd(h, S("ping")); + const std::string sent = "12,SEND ERROR: " + num(ECONNRESET); + check(header(r) == 0xFFFF && r.status == sent, "latch (b): WRITE meets the RST -> $FFFF + %s", sent.c_str()); + r = read_cmd(h, 100); + check(header(r) == 0 && r.status == sent, "latch (b): READ -> $0000 + the same 12, held plaintext discarded"); +} + +// --- claims, $25 and ABORT --------------------------------------------- + +static void test_claims(void) +{ + printf("$25 TLS_RELEASE, claims and ABORT (S19e)\n"); + fresh(); + int a = open_ok(); + Res r = release(); + check(r.status == "00,OK" && r.data == B({ 1 }), "release: right after an OPEN -> 1"); + check(!sock(a).open && sock(a).srv.saw_notify && world_count(0x32) == 1, + "release: CLOSE RPC, close_notify, socket closed"); + check(release().data == B({ 0 }), "release: again -> 0 (idempotent)"); + r = read_cmd(a, 10); + check(header(r) == 0xFFFF && r.status == "02,NO DATA: " + num(EBADF), "release: READ on the number -> 02,NO DATA: 9"); + + fresh(); + a = open_ok(); + check(info_byte(14) == 1, "claims: INFO $FF [14] = 1 after an OPEN"); + check(info_byte(14) == 1, "claims: $23 $FF does not claim"); + check(release().data == B({ 1 }), "claims: $23 $FF, then $25 -> 1"); + + fresh(); + a = open_ok(); + read_cmd(a, 10); + check(release().data == B({ 0 }) && sock(a).open, "claims: any command claims (READ) -> $25 answers 0"); + fresh(); + a = open_ok(); + run(B({ 0x03, 0x01 })); + check(release().data == B({ 0 }), "claims: even IDENTIFY claims"); + fresh(); + a = open_ok(); + info(a); + check(release().data == B({ 0 }), "claims: INFO on a handle claims"); + fresh(); + a = open_ok(); + r = run(B({ 0x03, 0x25, 0x00 })); + check(r.status == "81,INVALID PARAMS" && info_byte(14) == 1, "claims: `03 25 00` -> 81, claims nothing"); + check(release().data == B({ 1 }), "claims: the corrected $25 still closes it"); + fresh(); + a = open_ok(); + run(B({ 0x03, 0x23, 0xFF, 0x00 })); + check(release().data == B({ 0 }), "claims: `03 23 FF 00` claims"); + fresh(); + a = open_ok(); + run(B({ 0x03, 0x23 })); + check(release().data == B({ 0 }), "claims: `03 23` claims"); + fresh(); + a = open_ok(); + r = run(B({ 0x83, 0x25 })); + check(!sock(a).open, "claims: $25 with the no-reply bit still closes"); + + // $25 spares claimed sessions (S19e2) and TCP sockets. + fresh(); + int t = open_tcp(); + a = open_ok(); + read_cmd(a, 10); + int b = open_ok(); + check(release().data == B({ 1 }) && sock(a).open && !sock(b).open && sock(t).open, + "claims: A claimed, B unclaimed -> $25 closes B only, TCP untouched"); + sock(a).srv.echo = true; + r = write_cmd(a, S("still")); + std::string last; + bytes got = read_all(a, 100, &last, NULL, 5); + check(got == S("still"), "claims: A still echoes"); + // START_TLS creates an unclaimed entry too. + fresh(); + t = open_tcp(); + run(start_cmd(t, 2, 0, "", PIN())); + check(release().data == B({ 1 }) && !sock(t).open, "claims: START_TLS's entry is unclaimed until the next command"); + + // ABORT never closes, frees or claims; does not touch a CA upload. + fresh(); + a = open_ok(); + net.abort(0); + check(sock(a).open && info_byte(14) == 1, "abort: the session stays, and stays unclaimed"); + check(release().data == B({ 1 }), "abort: $25 after an ABORTed OPEN closes it (S19e)"); + fresh(); + world_module.set_ca_result = 0; + run(cat(B({ 0x03, 0x22, 0, 0, 0x64, 0 }), bytes(50, 0x30))); + net.abort(0); + r = run(cat(B({ 0x03, 0x22, 50, 0, 0x64, 0 }), bytes(50, 0x31))); + check(r.status == "00,OK" && world_count(0x35) == 1, "abort: an ABORT between CA chunks does not end the upload"); +} + +// --- TRUST_CA ($22) --------------------------------------------------------------------------- + +static Res chunk(uint16_t offset, uint16_t total, const bytes &data) +{ + return run(cat(B({ 0x03, 0x22, offset & 0xFF, offset >> 8, total & 0xFF, total >> 8 }), data)); +} + +static bool loaded(void) +{ + Res r = info(0xFF); + return (r.data.size() == 16) && (r.data[4] & 0x08); +} + +// --- socket-free commands are commands too ------------------------------------------------ + +// IDENTIFY and its kin answer on the UCI Server task, apart from the worker that owns the TLS state. They must +// still count as "the next command" for the two rules that depend on one arriving. +static void test_quick_commands(void) +{ + printf("Socket-free commands (UCI Server task) and the TLS rules about a next command\n"); + fresh(); + int a = open_ok(); + run(B({ 0x03, 0x01 })); // IDENTIFY + check(release().data == B({ 0 }) && sock(a).open, "quick: IDENTIFY claims the session, so $25 frees nothing"); + fresh(); + a = open_ok(); + check(release().data == B({ 1 }) && !sock(a).open, "quick: with no command in between, $25 frees the unclaimed session"); + + fresh(); + world_module.set_ca_result = 0; + chunk(0, 100, bytes(50, 1)); + run(B({ 0x03, 0x01 })); + check(chunk(50, 100, bytes(50, 1)).status == "81,INVALID PARAMS" && world_count(0x35) == 0, + "quick: IDENTIFY between CA chunks ends the upload"); +} + +static void test_ca(void) +{ + printf("TRUST_CA ($22): the Nios's CA state\n"); + fresh(); + world_module.set_ca_result = 0; + bytes der = expected(33, 1400); + Res r = chunk(0, 1400, bytes(der.begin(), der.begin() + 600)); + check(r.status == "00,OK" && r.data.empty(), "ca: first chunk -> 00,OK, empty"); + r = chunk(600, 1400, bytes(der.begin() + 600, der.begin() + 1200)); + check(r.status == "00,OK" && world_count(0x35) == 0, "ca: an intermediate chunk sends nothing"); + r = chunk(1200, 1400, bytes(der.begin() + 1200, der.end())); + check(r.status == "00,OK" && world_count(0x35) == 1 && world_module.ca_der == der, + "ca: final chunk -> SET_CA with all 1400 bytes -> LOADED"); + uint16_t tag = world_module.ca_tag; + check(tag != 0 && loaded(), "ca: INFO bit3 set, ca_tag %u != 0", tag); + world_module.calls.clear(); + int h = open_ok(1); + check(h >= 0 && call_no(0).open.ca_tag == tag, "ca: OPEN CUSTOM carries the ca_tag"); + close_cmd(h); + r = chunk(1200, 1400, bytes(der.begin() + 1200, der.end())); + check(r.status == "81,INVALID PARAMS" && loaded(), "ca: a duplicate final chunk -> 81, still LOADED"); + r = chunk(700, 1473, bytes(10, 1)); + check(r.status == "81,INVALID PARAMS" && loaded(), "ca: total > 1472 at a non-zero offset -> 81, CA untouched"); + r = chunk(0, 1473, bytes()); + check(r.status == "82,PARAMETER(S) OUT OF RANGE" && !loaded(), "ca: offset 0, total 1473 over a LOADED CA -> 82, EMPTY"); + chunk(0, 10, bytes(10, 1)); + uint16_t old_tag = world_module.ca_tag; + check(loaded(), "ca: loaded again"); + world_module.calls.clear(); + chunk(0, 10, bytes(10, 2)); + check(last_call().cmd == 0x35 && last_call().tag != old_tag, "ca: a new upload is sent under a new ca_tag (%u, was %u)", + last_call().tag, old_tag); + r = chunk(0, 1400, bytes(10, 1)); + check(!loaded(), "ca: offset 0 of a new upload drops the CA at once"); + r = run(cat(B({ 0x03, 0x22, 10, 0, 0x78, 0x05 }), bytes(10, 2))); + check(r.status == "81,INVALID PARAMS", "ca: (the INFO above ended that upload) a continuation -> 81"); + + fresh(); + world_module.set_ca_result = 0; + chunk(0, 100, bytes(50, 1)); + info(0xFF); + r = chunk(50, 100, bytes(50, 1)); + check(r.status == "81,INVALID PARAMS" && world_count(0x35) == 0, "ca: chunk, INFO, chunk -> 81, EMPTY (interleave)"); + chunk(0, 100, bytes(50, 1)); + release(); + check(chunk(50, 100, bytes(50, 1)).status == "81,INVALID PARAMS", "ca: $25 ends an upload too"); + chunk(0, 100, bytes(50, 1)); + check(chunk(40, 100, bytes(50, 1)).status == "81,INVALID PARAMS", "ca: a wrong offset -> 81"); + check(chunk(50, 100, bytes(50, 1)).status == "81,INVALID PARAMS", "ca: ... and the upload is gone"); + chunk(0, 100, bytes(50, 1)); + check(chunk(50, 100, bytes(51, 1)).status == "81,INVALID PARAMS", "ca: a chunk past total -> 81"); + check(chunk(0, 0, bytes(3, 1)).status == "81,INVALID PARAMS", "ca: total 0 with data -> 81"); + check(chunk(0, 1473, bytes()).status == "82,PARAMETER(S) OUT OF RANGE", "ca: offset 0, total 1473 -> 82"); + check(run(B({ 0x03, 0x22, 0, 0, 0 })).status == "81,INVALID PARAMS", "ca: 5 bytes -> 81"); + chunk(0, 10, bytes(10, 1)); + check(loaded(), "ca: a one-chunk upload loads"); + uint16_t before = world_module.ca_tag; + check(chunk(0, 0, bytes()).status == "00,OK" && !loaded(), "ca: offset 0 total 0 clears -> EMPTY"); + world_module.calls.clear(); + chunk(0, 10, bytes(10, 1)); + check(last_call().tag != before, "ca: every new upload has a new ca_tag"); + + struct { int result; int err; uint8_t reject; const char *want; } cases[] = { + { WIFI_TLS_REFUSED, -0x2180, 0, "97,CUSTOM CA INVALID: -0x2180" }, + { WIFI_TLS_REFUSED, WIFI_TLS_ESP_INVALID_ARG, 1, "97,CUSTOM CA REJECTED: RSA KEY < 2048" }, + { WIFI_TLS_REFUSED, WIFI_TLS_ESP_INVALID_ARG, 3, "97,CUSTOM CA REJECTED: CURVE" }, + { WIFI_TLS_REFUSED, WIFI_TLS_ESP_INVALID_ARG, 4, "97,CUSTOM CA REJECTED: NOT A CA" }, + { WIFI_TLS_REFUSED, WIFI_TLS_ESP_NOT_SUPPORTED, 0, "90,TLS NOT AVAILABLE" }, + { WIFI_TLS_INVALID, 0, 0, "17,TLS MODULE NOT RESPONDING" }, + { WIFI_TLS_BUSY, 0, 0, "17,TLS MODULE NOT RESPONDING" }, + { WIFI_TLS_NO_MODULE, 0, 0, "90,TLS NOT AVAILABLE" }, + }; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + fresh(); + world_module.set_ca_result = cases[i].result; + world_module.set_ca_esp_err = cases[i].err; + world_module.set_ca_reject = cases[i].reject; + r = chunk(0, 20, bytes(20, 7)); + check(r.status == cases[i].want && !loaded(), "ca: SET_CA answer %d/%d/%d -> %s, EMPTY (got %s)", + cases[i].result, cases[i].err, cases[i].reject, cases[i].want, r.status.c_str()); + } + fresh(); + world_module.available = false; + r = chunk(0, 20, bytes(20, 7)); + check(r.status == "90,TLS NOT AVAILABLE", "ca: no module at the final chunk -> 90"); +} + +// --- c64_reset, run_prg and module restarts --------------------------------------------- + +static void test_cleanup(void) +{ + printf("Cleanup: C64 reset and module restart (S14)\n"); + fresh(); + world_module.set_ca_result = 0; + chunk(0, 10, bytes(10, 1)); + int a = open_ok(1), b = open_ok(0); + world_module.calls.clear(); + reset_c64(); + check(!sock(a).open && !sock(b).open, "reset: both TLS sockets closed"); + check(world_module.close_alls == 1, "reset: CLOSE_ALL once"); + Res r = info(0xFF); + check(at(r, 2) == 0 && !(at(r, 4) & 0x08), "reset: no entries, CA bit clear"); + world_module.ca_loaded = true; // CLOSE_ALL lost: the module still has the old CA + world_module.calls.clear(); + r = run(open_cmd(1, 0, "example.com")); + check(r.status == "97,NO CUSTOM CA" && world_module.calls.empty(), "reset: OPEN CUSTOM -> 97, even if CLOSE_ALL was lost"); + a = open_ok(0); + check(a >= 0 && last_call().slot <= 1, "reset: the table is usable again"); + + fresh(); + world_module.set_ca_result = 0; + chunk(0, 10, bytes(10, 1)); + a = open_ok(); + world_module.generation++; + r = read_cmd(a, 10); + check(header(r) == 0 && r.status == "17,TLS MODULE NOT RESPONDING", "restart: a new generation -> $0000 + 17"); + check(!loaded(), "restart: the CA is EMPTY"); + world_module.calls.clear(); + check(close_cmd(a).status == "00,OK" && world_count(0x32) == 0 && !sock(a).open, + "restart: CLOSE sends no RPC and closes the socket"); +} + +// Every TLS status line is at most 40 bytes. The longest +// templates, with the widest values each field can take (a 3-digit newlib +// errno, 4 hex digits of mbedTLS code, 8 of flags). +static void test_status_lengths(void) +{ + printf("Status lines: at most 40 bytes\n"); + const int E = 999; + const uint8_t N = WIFI_TLS_ALERT_NONE; + fresh(); + world_socks[0].srv.on_hello = SRV_RST; + world_socks[0].srv.rst_err = E; + Res r = run(open_cmd(0, 0, "example.com")); + check(r.status == "13,TLS HANDSHAKE FAILED: PEER RESET: 999" && r.status.size() == 40, + "status cap: '%s' is %d bytes", r.status.c_str(), (int)r.status.size()); + fresh(); + world_socks[0].srv.send_err = E; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "13,TLS HANDSHAKE FAILED: SEND ERROR: 999" && r.status.size() == 40, + "status cap: '%s' is %d bytes (SEND ERROR wording, 3-digit errno)", r.status.c_str(), (int)r.status.size()); + expect_fail(0, 4, 0xFFFFFFFE, N, -0x2700, "94,CERTIFICATE NAME MISMATCH: 0xFFFFFFFE", "widest 94"); + expect_fail(0, 4, 0xFFFFFFFF, N, -0x2700, "93,CERTIFICATE NOT TRUSTED: 0xFFFFFFFF", "widest 93"); + expect_fail(0, 4, 0xFFFFFFFB, N, -0x2700, "95,CERTIFICATE EXPIRED: 0xFFFFFFFB", "widest 95"); + expect_fail(0, 0, 0, N, -0xFFFF, "13,TLS HANDSHAKE FAILED: -0xFFFF", "widest 13"); + expect_fail(0, 0, 0, 254, -0x7780, "14,TLS ALERT RECEIVED: 254", "widest 14 (255 means none)"); + expect_fail(0, 1, 0xFFFF, N, -0x7700, "18,TLS VERSION REFUSED: 0xFFFF", "widest 18"); + fresh(); + world_socks[0].srv.connect_err = E; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "11,ERROR ON CONNECT: 999", "status cap: %s", r.status.c_str()); + fresh(); + int h = open_ok(); + server_push(h, EV_ERR, bytes(), E); + r = read_cmd(h, 10); + check(r.status == "12,RECEIVE ERROR: 999", "status cap: %s", r.status.c_str()); + fresh(); + h = open_ok(); + sock(h).send_err = E; + r = write_cmd(h, S("x")); + check(r.status == "12,SEND ERROR: 999", "status cap: %s", r.status.c_str()); + fresh(); + world_module.set_ca_result = WIFI_TLS_REFUSED; + world_module.set_ca_esp_err = -0xFFFF; + r = chunk(0, 5, bytes(5, 1)); + check(r.status == "97,CUSTOM CA INVALID: -0xFFFF", "status cap: %s", r.status.c_str()); + world_module.set_ca_esp_err = WIFI_TLS_ESP_INVALID_ARG; + world_module.set_ca_reject = 1; + r = chunk(0, 5, bytes(5, 1)); + check(r.status == "97,CUSTOM CA REJECTED: RSA KEY < 2048", "status cap: %s", r.status.c_str()); + fresh(); + h = open_ok(); + server_push(h, EV_DATA, record('B', 10)); + r = read_cmd(h, 10); + check(r.status.compare(0, 23, "16,TLS SESSION FAILED: ") == 0, "status cap: %s", r.status.c_str()); +} + +// A READ on a TLS handle refused before any data (81 wrong +// length, 82 maxlen) has an EMPTY reply, which reads as $00 $00, and changes +// nothing. +static void test_empty_read_reply(void) +{ + printf("READ refusals on a TLS handle: an empty reply, the handle unchanged\n"); + fresh(); + int h = open_ok(); + server_push(h, EV_DATA, record('D', 30, 13)); + Res r = run(B({ 0x03, 0x10, h, 10 })); + check(r.status == "81,INVALID PARAMS" && r.data.empty(), "empty reply: a 4-byte READ -> 81, empty reply"); + r = run(B({ 0x03, 0x10, h, 10, 0, 0 })); + check(r.status == "81,INVALID PARAMS" && r.data.empty(), "empty reply: a 6-byte READ -> 81, empty reply"); + r = read_cmd(h, 0); + check(r.status == "82,PARAMETER(S) OUT OF RANGE" && r.data.empty(), "empty reply: maxlen 0 -> 82, empty reply"); + r = read_cmd(h, 1473); + check(r.status == "82,PARAMETER(S) OUT OF RANGE" && r.data.empty(), "empty reply: maxlen 1473 -> 82, empty reply"); + std::string last; + bytes got = read_all(h, 1472, &last, NULL, 5); + check(got == expected(13, 30) && sock(h).open, "empty reply: the handle is unchanged; its data still arrives"); +} + + +// --- edge cases: latch, STATS cache, drain, WRITE budget, send failures ------------------------- +static void test_edge_cases(void) +{ + printf("Edge cases: latch, STATS cache, drain, WRITE budget, send failures\n"); + const std::string rst = "12,RECEIVE ERROR: " + num(ECONNRESET); + std::string last; + + // A close_notify found by the drain BEFORE the WRITE, with plaintext + // still in rx. The WRITE reports the latched 12; the end must then be that 12, never 01/GONE. + fresh(); + int h = open_ok(); + FakeSession &s = world_module.sess[0]; + for (size_t i = 0; i < 500; i++) { + s.pt.push_back(payload_byte(21, i)); + } + s.terminal = 'C'; + server_push(h, EV_ERR, bytes(), ECONNRESET); + Res r = read_cmd(h, 100); // latches; the step hands out 500 B AND CLOSED + bytes all = body(r); + r = write_cmd(h, S("ping")); + check(header(r) == 0xFFFF && r.status == rst, "latch (c): WRITE while latched -> $FFFF + %s (got %s)", + rst.c_str(), r.status.c_str()); + bytes got = read_all(h, 100, &last, NULL, 50); + all.insert(all.end(), got.begin(), got.end()); + check(all == expected(21, 500), "latch (c): every byte delivered (%d of 500)", (int)all.size()); + check(last == rst && sock(h).open, + "latch (c): after a WRITE said 12, the end is that 12 and the handle is still owned (got '%s', socket %s)", + last.c_str(), sock(h).open ? "open" : "CLOSED"); + + // The STATS cache is cleared only on NO_MODULE, NOT_SUPPORTED or a new + // generation. The ESP32 answers a STATS that finds the TLS queue full with a full-size reply, + // esp_err ESP_ERR_TIMEOUT (tls_rpc.c cmd_tls_busy), which take_stats makes REFUSED. + fresh(); + info(0xFF); + world_module.stats_result = WIFI_TLS_REFUSED; // cmd_tls_busy's full-size reply + world_module.stats_esp_err = 0x107; // ESP_ERR_TIMEOUT + r = info(0xFF); + world_module.stats_result = -1; + world_module.stats_esp_err = 0; + check((at(r, 4) & 0x01) == 0x01, + "info (cache): a STATS refused with ESP_ERR_TIMEOUT (TLS queue full = a timeout) keeps b0 (b4=0x%02X)", at(r, 4)); + + // The drain ends after TWO CONSECUTIVE quiet steps, not two per READ. With + // every step taking 260 ms (> READ_BUDGET 250 ms), each READ gets one step in. + fresh(); + h = open_ok(); + server_push(h, EV_ERR, bytes(), ECONNRESET); + for (int i = 0; i < 60; i++) { + Forced f = Forced(); + f.result = 0; + f.delay_ms = 260; + world_module.forced.push_back(f); + } + int reads = 0; + std::string st; + for (reads = 1; reads <= 20; reads++) { + r = read_cmd(h, 100); + st = r.status; + if (header(r) != 0xFFFF) { + break; + } + } + world_module.forced.clear(); + check(st == rst, "latch: a peer RST with slow (260 ms) steps ends in %s within 20 READs (got '%s' after %d)", + rst.c_str(), st.c_str(), reads > 20 ? 20 : reads); + + // A WRITE ends with a step that returns no + // ciphertext, so 892 B is exactly 2 NO_READ steps; within WRITE_BUDGET 4 that leaves room for 2 + // AGAINs, and a third makes the WRITE a sticky 17, never a partial count. + fresh(); + h = open_ok(); + bytes data = expected(12, 892); + world_module.calls.clear(); + r = write_cmd(h, data); + check(header(r) == 892 && steps_logged() == 2 && last_call().pt_in_len == 0, + "write: 892 B is 2 steps, the last input-less (got %04X, %d steps)", header(r), steps_logged()); + fresh(); + h = open_ok(); + world_module.again_next = 2; + r = write_cmd(h, data); + check(header(r) == 892 && r.status == "00,OK" && sock(h).srv.got == data, + "write: 892 B after 2 AGAINs is 4 steps -> 892, 00,OK (got %04X %s)", header(r), r.status.c_str()); + fresh(); + h = open_ok(); + world_module.again_next = 3; + r = write_cmd(h, data); + check(header(r) == 0xFFFF && r.status == "17,TLS MODULE NOT RESPONDING", + "write: 892 B after 3 AGAINs runs out of WRITE_BUDGET -> $FFFF + sticky 17 (got %04X %s)", header(r), + r.status.c_str()); + + // A send failure during the handshake is a 13; 12 is for READ and WRITE only. + fresh(); + int t = open_tcp(); + sock(t).send_err = ECONNRESET; + r = run(start_cmd(t, 2, 0, "", PIN())); + check(r.status == "13,TLS HANDSHAKE FAILED: SEND ERROR: " + num(ECONNRESET) && !sock(t).open, + "start: START_TLS whose ClientHello send meets an RST -> 13 SEND ERROR: errno, handle closed " + "(got '%s', handle %s)", r.status.c_str(), sock(t).open ? "open" : "closed"); + fresh(); + world_socks[0].srv.send_err = EPIPE; // OPEN_TLS: the new socket's first send fails + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "13,TLS HANDSHAKE FAILED: SEND ERROR: " + num(EPIPE) && world_open_sockets() == 0 && + world_count(0x32) == 1, "open: OPEN_TLS whose ClientHello send fails -> 13 SEND ERROR: errno, CLOSE RPC (got '%s')", + r.status.c_str()); + + // 17 is not a kept code. The module's queue-full answer to OPEN (esp_err + // ESP_ERR_TIMEOUT, reason 0) is a REFUSED 17: START_TLS must close the TCP handle. + fresh(); + t = open_tcp(); + world_module.open_result = WIFI_TLS_REFUSED; + world_module.open_esp_err = 0x107; + world_module.open_reason = 0; + r = run(start_cmd(t, 2, 0, "", PIN())); + world_module.open_result = -1; + check(r.status == "17,TLS MODULE NOT RESPONDING" && !sock(t).open, + "start: START_TLS refused by a busy module -> 17 and the TCP handle is closed (got '%s', %s)", + r.status.c_str(), sock(t).open ? "open" : "closed"); +} + +// Send failures late in the handshake, NO_MODULE from STATS, and a module failure in the drain +// after a WRITE's 12. +static void test_late_send_failures(void) +{ + printf("Late handshake send failures, STATS NO_MODULE, a drain failure after a WRITE\n"); + Res r; + + // A STATS call that finds the module application gone (NO_MODULE, the race with + // wifi_tls_module_available()) clears the cache. + fresh(); + info(0xFF); + world_module.stats_result = WIFI_TLS_NO_MODULE; + r = info(0xFF); + world_module.stats_result = WIFI_TLS_BUSY; + Res r2 = info(0xFF); + world_module.stats_result = -1; + check(!(at(r, 4) & 1) && !(at(r2, 4) & 1), "info (cache): NO_MODULE from STATS clears b0, and it stays 0 (b4=0x%02X, 0x%02X)", + at(r, 4), at(r2, 4)); + + // The Finished's send fails (the 2nd send of the handshake) -> 13 SEND ERROR, never 12, + // never 00,OK. + fresh(); + world_socks[0].srv.send_err_from = 2; + world_socks[0].srv.send_err_late = ECONNRESET; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "13,TLS HANDSHAKE FAILED: SEND ERROR: " + num(ECONNRESET) && world_open_sockets() == 0, + "open: OPEN whose Finished send meets an RST -> 13 SEND ERROR (got '%s')", r.status.c_str()); + fresh(); + int t = open_tcp(); + sock(t).srv.send_err_from = sock(t).send_calls + 2; + sock(t).srv.send_err_late = EPIPE; + r = run(start_cmd(t, 2, 0, "", PIN())); + check(r.status == "13,TLS HANDSHAKE FAILED: SEND ERROR: " + num(EPIPE) && !sock(t).open, + "start: START whose Finished send fails -> 13 SEND ERROR, handle closed (got '%s')", r.status.c_str()); + + // A ClientHello send stalled for SEND_MS, well before the handshake deadline -> + // 13 SEND ERROR: ETIMEDOUT (116 on the Nios); a Finished send stalled into the deadline -> 15. + fresh(); + world_socks[0].srv.send_err_from = 1; + world_socks[0].srv.send_err_late = EWOULDBLOCK; + uint32_t t0 = world_ms(); + r = run(open_cmd(0, 0, "example.com")); + uint32_t spent = world_ms() - t0; + check(r.status == "13,TLS HANDSHAKE FAILED: SEND ERROR: " + num(ETIMEDOUT) && spent >= 5000 && spent < 6000, + "open: a stalled ClientHello send -> 13 SEND ERROR: ETIMEDOUT after SEND_MS (got '%s', %u ms)", + r.status.c_str(), spent); + fresh(); + world_socks[0].srv.delay_ms = 12000; + world_socks[0].srv.send_err_from = 2; + world_socks[0].srv.send_err_late = EWOULDBLOCK; + r = run(open_cmd(0, 0, "example.com")); + check(r.status == "15,TLS HANDSHAKE TIMEOUT", "open: a Finished send stalled into the handshake deadline -> 15 (got '%s')", + r.status.c_str()); + + // Pinned as the current behaviour: after a WRITE has reported the latched 12, a module + // failure in the drain (here a malformed step) ends in a sticky 17, not 12; the handle stays owned. + fresh(); + int h = open_ok(); + for (size_t i = 0; i < 1200; i++) { + world_module.sess[0].pt.push_back(payload_byte(21, i)); + } + server_push(h, EV_ERR, bytes(), ECONNRESET); + read_cmd(h, 1); + r = write_cmd(h, S("ping")); + check(r.status == "12,RECEIVE ERROR: " + num(ECONNRESET), "latch: setup: the WRITE reports the latched 12"); + Forced f = Forced(); + f.result = WIFI_TLS_INVALID; + world_module.forced.push_back(f); + std::string last; + read_all(h, 1472, &last, NULL, 50); + r = read_cmd(h, 10); + check(last == "17,TLS MODULE NOT RESPONDING" && header(r) == 0 && r.status == last && sock(h).open, + "latch: a module failure in the drain after the WRITE's 12 -> sticky 17, handle still owned (got '%s')", + last.c_str()); + check(close_cmd(h).status == "00,OK" && !sock(h).open, "latch: CLOSE -> 00,OK"); +} + +int main(int argc, char **argv) +{ + setvbuf(stdout, NULL, _IOLBF, 0); + world_reset_hook = [] { net.c64_reset(); }; + world_abort_hook = [] { if (net.cancel) { *net.cancel = true; } }; + test_info(); + test_open(); + test_grammar(); + test_precedence(); + test_classify(); + test_dns_connect(); + test_reset_during_open(); + test_start_tls(); + test_abort_during_open(); + test_reset_during_start(); + test_read(); + test_write(); + test_close(); + test_latch(); + test_claims(); + test_ca(); + test_quick_commands(); + test_cleanup(); + test_status_lengths(); + test_empty_read_reply(); + test_edge_cases(); + test_late_send_failures(); + check(longest_status.size() <= 40, "status cap: the longest status of the whole run is %d bytes: '%s'", + (int)longest_status.size(), longest_status.c_str()); + printf("\n%d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/software/test/wifi_tls/net_world.cc b/software/test/wifi_tls/net_world.cc new file mode 100644 index 000000000..50733c53b --- /dev/null +++ b/software/test/wifi_tls/net_world.cc @@ -0,0 +1,1034 @@ +/* + * net_world.cc: see net_world.h. + */ +#include +#include +#include +#include "net_world.h" +#include "wifi_random.h" +#include "FreeRTOS.h" +#include "task.h" +#include "socket.h" +#include "netdb.h" +#include "lwip/dns.h" +#include "lwip/tcpip.h" +#include "command_intf.h" +#include "sntp_time.h" + +uint32_t world_tick; +uint32_t world_reset_at; +uint32_t world_abort_at = 0xFFFFFFFF; +void (*world_reset_hook)(void); +void (*world_abort_hook)(void); +static uint32_t reset_fired_for = 0xFFFFFFFF; +static uint32_t abort_fired_for = 0xFFFFFFFF; +FakeSock world_socks[16]; +std::vector world_dns; +int world_dns_calls; +int world_dns_unlocked_calls; +int world_dns_late_writes; +int world_lock_depth; +int world_lock_bad; +FakeModule world_module; +uint32_t world_sntp; + +CommandInterface cmd_if; +CommandTarget *command_targets[CMD_IF_MAX_TARGET + 1]; +Message c_status_ok = { 5, true, (uint8_t *)"00,OK" }; +Message c_status_unknown_command = { 18, true, (uint8_t *)"21,UNKNOWN COMMAND" }; +Message c_message_empty = { 0, true, (uint8_t *)"" }; +Message c_message_no_target = { 9, true, (uint8_t *)"NO TARGET" }; + +#define MS_TICKS(ms) (((ms) + 4) / 5) + +struct PendingDns { + uint32_t at; + std::string name; + bool ok; + ip_addr_t addr; + dns_found_callback cb; + void *arg; +}; +static std::vector pending_dns; + +static void fire_dns(bool all) +{ + for (size_t i = 0; i < pending_dns.size();) { + if (all || ((int32_t)(world_tick - pending_dns[i].at) >= 0)) { + PendingDns p = pending_dns[i]; + pending_dns.erase(pending_dns.begin() + i); + if (world_lock_depth) { + world_lock_bad++; + } + p.cb(p.name.c_str(), p.ok ? &p.addr : NULL, p.arg); + } else { + i++; + } + } +} + +void world_dns_fire_all(void) +{ + fire_dns(true); +} + +void world_advance(uint32_t ticks) +{ + world_tick += ticks; + fire_dns(false); + // What the UCI Server task does while the worker waits: it sees the reset or the abort in the next + // tick and notes it for the worker (c64_reset(), the job's cancel flag). + if ((world_reset_at == 0xFFFFFFFF) || (world_abort_at == 0xFFFFFFFF)) { + if (world_reset_at == 0xFFFFFFFF) { + reset_fired_for = 0xFFFFFFFF; + } + if (world_abort_at == 0xFFFFFFFF) { + abort_fired_for = 0xFFFFFFFF; + } + } + if ((world_reset_at != 0xFFFFFFFF) && (reset_fired_for != world_reset_at) && + ((int32_t)(world_tick - world_reset_at) >= 0)) { + reset_fired_for = world_reset_at; + if (world_reset_hook) { + world_reset_hook(); + } + } + if ((world_abort_at != 0xFFFFFFFF) && (abort_fired_for != world_abort_at) && + ((int32_t)(world_tick - world_abort_at) >= 0)) { + abort_fired_for = world_abort_at; + if (world_abort_hook) { + world_abort_hook(); + } + } +} + +uint32_t world_ms(void) +{ + return world_tick * 5; +} + +uint8_t payload_byte(uint32_t seed, uint32_t i) +{ + return (uint8_t)(((seed + i) * 2654435761u) >> 24); +} + +bytes record(char type, size_t length, uint32_t seed) +{ + bytes r; + r.push_back((uint8_t)type); + r.push_back((uint8_t)length); + r.push_back((uint8_t)(length >> 8)); + for (size_t i = 0; i < length; i++) { + r.push_back(payload_byte(seed, i)); + } + return r; +} + +void server_push(int s, int kind, const bytes &data, int err, uint32_t after_ms) +{ + if ((s < 0) || (s >= 16)) { + return; // no such socket (a red run) + } + SockEvent e; + e.kind = kind; + e.data = data; + e.err = err; + e.at = world_tick + MS_TICKS(after_ms); + world_socks[s].rx.push_back(e); +} + +void world_reset(void) +{ + world_tick = 1000; + world_reset_at = 0xFFFFFFFF; + world_abort_at = 0xFFFFFFFF; + reset_fired_for = abort_fired_for = 0xFFFFFFFF; + for (int i = 0; i < 16; i++) { + world_socks[i] = FakeSock(); + world_socks[i].srv.saw_alert = -1; + world_socks[i].srv.flight = 2000; + world_socks[i].srv.delay_ms = 20; + world_socks[i].srv.chunk = 1460; + } + world_dns.clear(); + pending_dns.clear(); + world_dns_calls = 0; + world_dns_unlocked_calls = 0; + world_dns_late_writes = 0; + world_lock_depth = 0; + world_lock_bad = 0; + world_module = FakeModule(); + FakeModule &m = world_module; + m.available = true; + m.major = 1; + m.minor = 306; + m.generation = 7; + m.entropy = true; + m.module_time = true; + m.open_result = -1; + m.hello_size = 300; + m.version = 0x0304; + m.suite = 0x1301; + m.group = 0x001D; + for (int i = 0; i < 32; i++) { + m.spki[i] = (uint8_t)(0xA0 + i); + } + m.block_max_ms = 12; + m.stats_result = -1; + m.close_result = -1; + m.in_cap = 18000; // mbedTLS reads a whole record, up to 16 KB + world_sntp = 1790000000u; // 2026 +} + +int world_count(int cmd) +{ + int n = 0; + for (size_t i = 0; i < world_module.calls.size(); i++) { + n += (world_module.calls[i].cmd == cmd); + } + return n; +} + +int world_open_sockets(void) +{ + int n = 0; + for (int i = 0; i < 16; i++) { + n += world_socks[i].open; + } + return n; +} + +// --- FreeRTOS, the command interface, SNTP --------------------------------- + +TickType_t xTaskGetTickCount(void) +{ + return world_tick; +} + +// The network target's worker task and its queue are not run (see run() in net_tls_test.cc). +BaseType_t xTaskCreate(void (*)(void *), const char *, uint16_t, void *, UBaseType_t, TaskHandle_t *) { return 0; } +QueueHandle_t xQueueCreate(UBaseType_t, UBaseType_t) { return NULL; } +BaseType_t xQueueSend(QueueHandle_t, const void *, TickType_t) { return 0; } +UBaseType_t uxQueueMessagesWaiting(QueueHandle_t) { return 0; } +void vQueueDelete(QueueHandle_t) { } +BaseType_t xQueueReceive(QueueHandle_t, void *, TickType_t) { return 0; } +uint32_t command_defer(void) { return 0; } +void command_deferred_done(uint32_t) { } + +void vTaskDelay(TickType_t ticks) +{ + world_advance(ticks ? ticks : 1); +} + +// The UCI Server task clears this at once (command_intf.cc), long before the worker looks, so it is +// never true here: the reset reaches the worker through c64_reset() and its count. +bool CommandInterface :: reset_pending(void) +{ + return false; +} + +uint32_t sntp_utc_now(void) +{ + return world_sntp; +} + +// --- DNS and the core lock -------------------------------------------------- + +void fake_lock_tcpip_core(void) +{ + world_lock_depth++; +} + +void fake_unlock_tcpip_core(void) +{ + world_lock_depth--; +} + +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found, void *callback_arg) +{ + world_dns_calls++; + if (!world_lock_depth) { + world_dns_unlocked_calls++; + } + if (ip4addr_aton(hostname, addr)) { + return ERR_OK; + } + DnsRule rule = { hostname, DNS_ASYNC_OK, htonl(0x0A000002), 20 }; + for (size_t i = 0; i < world_dns.size(); i++) { + if (world_dns[i].host == hostname) { + rule = world_dns[i]; + } + } + switch (rule.mode) { + case DNS_IMMEDIATE: + addr->addr = rule.addr; + return ERR_OK; + case DNS_ERR_VAL: + return ERR_VAL; + case DNS_NEVER: + return ERR_INPROGRESS; + default: { + PendingDns p; + p.at = world_tick + MS_TICKS(rule.delay_ms); + p.name = hostname; + p.ok = (rule.mode == DNS_ASYNC_OK); + p.addr.addr = rule.addr; + p.cb = found; + p.arg = callback_arg; + pending_dns.push_back(p); + return ERR_INPROGRESS; + } + } +} + +// --- sockets ------------------------------------------------------------------ + +static bool valid(int s) +{ + return (s >= 0) && (s < 16) && world_socks[s].open; +} + +int lwip_socket(int domain, int type, int protocol) +{ + for (int s = 0; s < 16; s++) { + if (!world_socks[s].open) { + FakeServer srv = world_socks[s].srv; // what the test set up for this number + world_socks[s] = FakeSock(); + world_socks[s].srv = srv; + world_socks[s].open = true; + world_socks[s].type = type; + return s; + } + } + errno = ENFILE; + return -1; +} + +int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + FakeSock &k = world_socks[s]; + FakeServer &v = k.srv; + k.connect_addr = ((const struct sockaddr_in *)name)->sin_addr.s_addr; + if (k.connected) { + errno = EISCONN; + return -1; + } + if (!k.nonblocking) { + if (v.connect_err) { + errno = v.connect_err; + return -1; + } + k.connected = true; + return 0; + } + if (!k.connect_at) { + k.connect_at = world_tick + MS_TICKS(v.connect_delay_ms ? v.connect_delay_ms : 10); + errno = EINPROGRESS; + return -1; + } + if (v.connect_never || ((int32_t)(world_tick - k.connect_at) < 0)) { + errno = EALREADY; + return -1; + } + if (v.connect_err) { + errno = v.connect_err; + return -1; + } + k.connected = true; + errno = EISCONN; + return -1; +} + +int lwip_ioctl(int s, long cmd, void *argp) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + if (cmd == (long)FIONBIO) { + world_socks[s].nonblocking = *(int *)argp != 0; + } + return 0; +} + +int lwip_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + if ((level == IPPROTO_TCP) && (optname == TCP_NODELAY)) { + world_socks[s].nodelay = *(const int *)optval != 0; + } + if ((level == SOL_SOCKET) && (optname == SO_RCVTIMEO)) { + world_socks[s].rcvtimeo_set = true; + } + if ((level == SOL_SOCKET) && (optname == SO_SNDTIMEO)) { + const struct timeval *tv = (const struct timeval *)optval; + world_socks[s].sndtimeo_ms = tv->tv_sec * 1000 + tv->tv_usec / 1000; + } + return 0; +} + +int lwip_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + if ((level == SOL_SOCKET) && (optname == SO_TYPE)) { + *(int *)optval = world_socks[s].type; + *optlen = sizeof(int); + return 0; + } + if ((level == SOL_SOCKET) && (optname == SO_ERROR)) { + // The result of a non-blocking connect, which connect_sliced() asks for once select() says it is over. + FakeSock &k = world_socks[s]; + *(int *)optval = 0; + *optlen = sizeof(int); + if (k.nonblocking && !k.connected && k.connect_at) { + if (k.srv.connect_err) { + *(int *)optval = k.srv.connect_err; + } else { + k.connected = true; + } + } + return 0; + } + errno = ENOPROTOOPT; + return -1; +} + +static bool available(FakeSock &k) +{ + return !k.rx.empty() && ((int32_t)(world_tick - k.rx.front().at) >= 0); +} + +// The server's side: what the module sent, record by record. +static void server_hears(int s) +{ + FakeSock &k = world_socks[s]; + FakeServer &v = k.srv; + while (v.client_stream.size() >= 3) { + size_t len = v.client_stream[1] | (v.client_stream[2] << 8); + if (v.client_stream.size() < 3 + len) { + break; + } + char type = (char)v.client_stream[0]; + bytes body(v.client_stream.begin() + 3, v.client_stream.begin() + 3 + len); + v.client_stream.erase(v.client_stream.begin(), v.client_stream.begin() + 3 + len); + if (type == 'H') { + v.hellos++; + if (v.on_hello == SRV_RESPOND) { + bytes flight = record('H', v.flight, 77); + for (size_t off = 0; off < flight.size(); off += v.chunk) { + size_t n = flight.size() - off; + if (n > v.chunk) { + n = v.chunk; + } + server_push(s, EV_DATA, bytes(flight.begin() + off, flight.begin() + off + n), 0, v.delay_ms); + } + } else if (v.on_hello == SRV_RST) { + server_push(s, EV_ERR, bytes(), v.rst_err ? v.rst_err : ECONNRESET, v.delay_ms); + } else if (v.on_hello == SRV_FIN) { + server_push(s, EV_FIN, bytes(), 0, v.delay_ms); + } + } else if (type == 'F') { + for (size_t i = 0; i < v.after_finished.size(); i++) { + SockEvent e = v.after_finished[i]; + e.at += world_tick; + k.rx.push_back(e); + } + } else if (type == 'D') { + v.got.insert(v.got.end(), body.begin(), body.end()); + if (v.echo) { + bytes r = body; + r.insert(r.begin(), (uint8_t)(len >> 8)); + r.insert(r.begin(), (uint8_t)len); + r.insert(r.begin(), (uint8_t)'D'); + server_push(s, EV_DATA, r, 0, 5); + } + } else if (type == 'C') { + v.saw_notify = true; + } else if (type == 'A') { + v.saw_alert = body.empty() ? 0 : body[0]; + } + } +} + +ssize_t lwip_send(int s, const void *dataptr, size_t size, int flags) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + FakeSock &k = world_socks[s]; + k.send_calls++; + if (k.srv.send_err_from && (k.send_calls >= k.srv.send_err_from)) { + if (k.srv.send_err_late == EWOULDBLOCK) { + k.send_blocked = true; // from here on, a stall (select advances the clock) + } + errno = k.srv.send_err_late; + return -1; + } + if (k.send_err || k.srv.send_err) { + errno = k.send_err ? k.send_err : k.srv.send_err; + return -1; + } + if (k.send_blocked) { + errno = EWOULDBLOCK; + return -1; + } + const uint8_t *p = (const uint8_t *)dataptr; + k.tx.insert(k.tx.end(), p, p + size); + if (k.type == SOCK_STREAM) { + k.srv.client_stream.insert(k.srv.client_stream.end(), p, p + size); + server_hears(s); + } + return size; +} + +ssize_t lwip_recv(int s, void *mem, size_t len, int flags) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + FakeSock &k = world_socks[s]; + k.recv_calls++; + if (k.err_taken) { + k.recv_after_err++; + errno = ENOTCONN; // lwIP's errno changes on later calls + return -1; + } + if (!available(k)) { + if (!(flags & MSG_DONTWAIT) && !k.nonblocking) { + world_advance(8); // SO_RCVTIMEO 40 ms + if (available(k)) { + return lwip_recv(s, mem, len, flags); + } + } + errno = EWOULDBLOCK; + return -1; + } + SockEvent &e = k.rx.front(); + if (e.kind == EV_FIN) { + return 0; // and again on every later call + } + if (e.kind == EV_ERR) { + k.err_taken = true; + errno = e.err; + return -1; + } + size_t n = (e.data.size() < len) ? e.data.size() : len; + memcpy(mem, e.data.data(), n); + e.data.erase(e.data.begin(), e.data.begin() + n); + if (e.data.empty()) { + k.rx.pop_front(); + } + return n; +} + +ssize_t lwip_recvmsg(int s, struct msghdr *message, int flags) +{ + return lwip_recv(s, message->msg_iov[0].iov_base, message->msg_iov[0].iov_len, flags); +} + +int lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout) +{ + int s = maxfdp1 - 1; + uint32_t wait = MS_TICKS(timeout->tv_sec * 1000 + timeout->tv_usec / 1000); + if (wait == 0) { + wait = 1; + } + if (!valid(s)) { + errno = EBADF; + return -1; + } + FakeSock &k = world_socks[s]; + if (writeset) { + if (k.send_blocked) { + world_advance(wait); + return 0; + } + if (k.nonblocking && !k.connected && k.connect_at) { + if (k.srv.connect_never) { + world_advance(wait); + return 0; + } + int32_t d = (int32_t)(k.connect_at - world_tick); + if (d > (int32_t)wait) { + world_advance(wait); + return 0; + } + if (d > 0) { + world_advance(d); + } + } + return 1; + } + if (available(k)) { + return 1; + } + if (!k.rx.empty()) { + uint32_t d = k.rx.front().at - world_tick; + if (d <= wait) { + world_advance(d); + return 1; + } + } + world_advance(wait); + return 0; +} + +int lwip_close(int s) +{ + if (!valid(s)) { + errno = EBADF; + return -1; + } + world_socks[s].open = false; + world_socks[s].closes++; + return 0; +} + +int gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, + int *h_errnop) +{ + static struct in_addr address; + static char *list[2]; + address.s_addr = htonl(0x0A000009); + list[0] = (char *)&address; + list[1] = NULL; + ret->h_addr_list = list; + *result = ret; + return 0; +} + +// --- the WiFi module ------------------------------------------------------------ + +bool wifi_tls_module_available(void) +{ + return world_module.available; +} + +void wifi_tls_module_version(uint16_t *major, uint16_t *minor) +{ + *major = world_module.major; + *minor = world_module.minor; +} + +uint32_t wifi_tls_generation(void) +{ + return world_module.generation; +} + +// Waits as wifi_dedicated_call does: in slices when there is a cancel. The +// answer comes after answer_ms; true when it came before the timeout and +// before a cancel. +static bool module_wait(uint32_t timeout_ms, const wifi_tls_cancel_t *cancel, uint32_t answer_ms, bool *cancelled) +{ + *cancelled = false; + uint32_t spent = 0; + while (true) { + if (answer_ms <= spent) { + world_advance(1); + return true; + } + if (spent >= timeout_ms) { + return false; + } + uint32_t slice = timeout_ms - spent; + if (cancel && (slice > 100)) { + slice = 100; + } + if (answer_ms - spent < slice) { + world_advance(MS_TICKS(answer_ms - spent)); + return true; + } + world_advance(MS_TICKS(slice)); + spent += slice; + if (cancel && cancel->cancelled(cancel->context)) { + *cancelled = true; + return false; + } + } +} + +static RpcCall &log_call(int cmd, uint8_t slot, uint16_t tag, const wifi_tls_cancel_t *cancel) +{ + RpcCall c = RpcCall(); + c.cmd = cmd; + c.slot = slot; + c.tag = tag; + c.cancel_given = (cancel != NULL); + world_module.calls.push_back(c); + return world_module.calls.back(); +} + +static bool unsent(void) +{ + if (world_module.unsent_next > 0) { + world_module.unsent_next--; + return true; + } + return false; +} + +int wifi_tls_open(const wifi_tls_open_t *open, uint32_t timeout_ms, const wifi_tls_cancel_t *cancel, int *esp_err, + uint8_t *reason) +{ + FakeModule &m = world_module; + *esp_err = 0; + *reason = 0; + if (!m.available) { + return WIFI_TLS_NO_MODULE; + } + if (unsent()) { + return WIFI_TLS_UNSENT; + } + RpcCall &c = log_call(0x30, open->slot, open->tag, cancel); + c.open = *open; + c.sni.assign(open->sni ? open->sni : "", open->sni_len); + if (open->pin) { + c.pin.assign(open->pin, open->pin + 32); + } + bool cancelled; + if (!module_wait(timeout_ms, cancel, m.open_delay_ms, &cancelled)) { + return WIFI_TLS_BUSY; + } + if (m.open_result >= 0) { + *esp_err = m.open_esp_err; + *reason = m.open_reason; + return m.open_result; + } + if (!m.entropy) { + *esp_err = WIFI_TLS_ESP_INVALID_STATE; + *reason = WIFI_TLS_REASON_NO_ENTROPY; + return WIFI_TLS_REFUSED; + } + if ((open->trust != WIFI_TLS_TRUST_PIN) && !m.module_time && (open->time_source == WIFI_TLS_TIME_NONE)) { + *esp_err = WIFI_TLS_ESP_INVALID_STATE; + *reason = WIFI_TLS_REASON_NO_TIME; + return WIFI_TLS_REFUSED; + } + if ((open->trust == WIFI_TLS_TRUST_CUSTOM) && (!m.ca_loaded || (m.ca_tag != open->ca_tag))) { + *esp_err = WIFI_TLS_ESP_INVALID_STATE; + *reason = WIFI_TLS_REASON_NO_CUSTOM_CA; + return WIFI_TLS_REFUSED; + } + FakeSession &s = m.sess[open->slot]; + s = FakeSession(); // a slot held under another tag is freed first + s.live = true; + s.tag = open->tag; + s.trust = open->trust; + s.state = WIFI_TLS_HANDSHAKING; + return 0; +} + +static void emit(bytes &out, char type, const uint8_t *p, size_t n) +{ + out.push_back((uint8_t)type); + out.push_back((uint8_t)n); + out.push_back((uint8_t)(n >> 8)); + out.insert(out.end(), p, p + n); +} + +static void parse_in(FakeSession &s, wifi_tls_step_t *st) +{ + FakeModule &m = world_module; + while ((s.in.size() >= 3) && !s.terminal && (s.state != WIFI_TLS_FAILED)) { + size_t len = s.in[1] | (s.in[2] << 8); + if (s.in.size() < 3 + len) { + break; + } + char type = (char)s.in[0]; + bytes body(s.in.begin() + 3, s.in.begin() + 3 + len); + s.in.erase(s.in.begin(), s.in.begin() + 3 + len); + if (s.state == WIFI_TLS_HANDSHAKING) { + if (type != 'H') { + continue; + } + if (m.hs_fail) { + s.state = WIFI_TLS_FAILED; + st->fail_reason = m.hs_fail_reason; + st->verify_flags = m.hs_verify_flags; + st->alert_in = m.hs_alert_in; + st->esp_err = m.hs_fail_err; + if (m.hs_alert_out) { + uint8_t a = 40; + emit(s.out, 'A', &a, 1); + } + return; + } + s.state = WIFI_TLS_ESTABLISHED; + bytes fin = record('F', 32); + s.out.insert(s.out.end(), fin.begin(), fin.end()); + continue; + } + if (type == 'D') { + s.pt.insert(s.pt.end(), body.begin(), body.end()); + } else if ((type == 'C') || (type == 'B')) { + s.terminal = type; + } else if (type == 'A') { + s.terminal = 'A'; + s.alert = body.empty() ? 0 : body[0]; + } + } +} + +int wifi_tls_step(uint8_t slot, uint16_t tag, wifi_tls_step_t *st, uint32_t timeout_ms, + const wifi_tls_cancel_t *cancel) +{ + FakeModule &m = world_module; + st->ct_out_len = 0; + st->pt_out_len = 0; + st->state = WIFI_TLS_UNKNOWN; + st->esp_err = 0; + st->alert_in = WIFI_TLS_ALERT_NONE; + st->alert_out = WIFI_TLS_ALERT_NONE; + st->fail_reason = 0; + st->verify_flags = 0; + if (!m.available) { + return WIFI_TLS_NO_MODULE; + } + if (unsent()) { + return WIFI_TLS_UNSENT; + } + RpcCall &c = log_call(0x31, slot, tag, cancel); + c.flags = st->flags; + c.ct_in_len = st->ct_in_len; + c.pt_in_len = st->pt_in_len; + + Forced f = Forced(); + bool forced = !m.forced.empty(); + if (forced) { + f = m.forced.front(); + m.forced.pop_front(); + } + bool cancelled; + bool busy = forced && (f.result == WIFI_TLS_BUSY); + if (busy) { + module_wait(timeout_ms, cancel, 0xFFFFFFFF, &cancelled); + if (!f.applied) { + return WIFI_TLS_BUSY; + } + } else if (!module_wait(timeout_ms, cancel, f.delay_ms, &cancelled)) { + return WIFI_TLS_BUSY; + } + if (forced && (f.result == WIFI_TLS_INVALID || f.result == WIFI_TLS_REFUSED || f.result == WIFI_TLS_UNSENT)) { + st->esp_err = f.esp_err; + return f.result; + } + FakeSession &s = m.sess[slot]; + if (!s.live || (s.tag != tag)) { + st->esp_err = WIFI_TLS_ESP_NOT_FOUND; + return WIFI_TLS_REFUSED; // touches nothing (the tag rule) + } + if ((m.quiet_next > 0) && (st->ct_in_len == 0) && (s.state == WIFI_TLS_ESTABLISHED)) { + m.quiet_next--; + st->state = s.state; + return 0; + } + if (m.quiet_alternate && (st->ct_in_len == 0) && (s.state == WIFI_TLS_ESTABLISHED) && !s.pt.empty()) { + m.quiet_last = !m.quiet_last; + if (m.quiet_last) { + st->state = s.state; + return 0; + } + } + bool again = false; + if (m.again_next > 0) { + m.again_next--; + again = true; + } else if (s.in.size() + st->ct_in_len > m.in_cap) { + again = true; + } + if (!again) { + s.in.insert(s.in.end(), st->ct_in, st->ct_in + st->ct_in_len); + if ((s.state == WIFI_TLS_ESTABLISHED) && st->pt_in_len) { + emit(s.out, 'D', st->pt_in, st->pt_in_len); + } + } + if (s.state == WIFI_TLS_HANDSHAKING && !s.sent_hello) { + bytes hello = record('H', m.hello_size); + s.out.insert(s.out.end(), hello.begin(), hello.end()); + s.sent_hello = true; + } + if (!(st->flags & WIFI_TLS_STEP_NO_READ) || (s.state == WIFI_TLS_HANDSHAKING)) { + parse_in(s, st); + } + if (forced && f.fail && (s.state == WIFI_TLS_ESTABLISHED)) { + s.state = WIFI_TLS_FAILED; + st->fail_reason = f.fail_reason; + st->verify_flags = f.verify_flags; + st->alert_in = f.alert_in; + st->esp_err = f.fail_err; + } + size_t ct = s.out.size() < 1024 ? s.out.size() : 1024; + if (ct > st->ct_out_room) { + return WIFI_TLS_INVALID; + } + memcpy(st->ct_out, s.out.data(), ct); + s.out.erase(s.out.begin(), s.out.begin() + ct); + st->ct_out_len = ct; + size_t pt = 0; + if ((s.state == WIFI_TLS_ESTABLISHED) && !(st->flags & WIFI_TLS_STEP_NO_READ)) { + size_t room = 1024 - ct; + if (room > 960) { + room = 960; + } + pt = s.pt.size() < room ? s.pt.size() : room; + for (size_t i = 0; i < pt; i++) { + st->pt_out[i] = s.pt.front(); + s.pt.pop_front(); + } + if (s.terminal && s.pt.empty()) { + if (s.terminal == 'C') { + s.state = WIFI_TLS_CLOSED; + // The engine answers the peer's close_notify with ours, in the same step + bytes notify = record('C', 0); + if (ct + notify.size() <= st->ct_out_room) { + memcpy(st->ct_out + ct, notify.data(), notify.size()); + ct += notify.size(); + st->ct_out_len = ct; + } + } else if (pt == 0) { + s.state = WIFI_TLS_FAILED; + if (s.terminal == 'A') { + st->alert_in = s.alert; + st->esp_err = -0x7780; // MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE + } else { + st->esp_err = -0x7180; // MBEDTLS_ERR_SSL_INVALID_MAC + } + } + } + } + if (forced && f.pt_on_no_read && (st->flags & WIFI_TLS_STEP_NO_READ)) { + return WIFI_TLS_INVALID; // what wifi_tls_take_step makes of it + } + st->pt_out_len = pt; + st->state = s.state; + if ((s.state == WIFI_TLS_FAILED) || (s.state == WIFI_TLS_CLOSED)) { + s.live = false; + } + if (busy) { + return WIFI_TLS_BUSY; // it ran, but its answer came too late + } + if (again) { + if (s.state == WIFI_TLS_CLOSED) { + return 0; + } + return WIFI_TLS_AGAIN; + } + return 0; +} + +int wifi_tls_close(uint8_t slot, uint16_t tag, uint8_t *ct_out, uint16_t room, uint16_t *ct_out_len, int *esp_err, + uint32_t timeout_ms, const wifi_tls_cancel_t *cancel) +{ + FakeModule &m = world_module; + *esp_err = 0; + *ct_out_len = 0; + if (!m.available) { + return WIFI_TLS_NO_MODULE; + } + log_call(0x32, slot, tag, cancel); + bool cancelled; + module_wait(timeout_ms, cancel, 0, &cancelled); + if (m.close_result >= 0) { + return m.close_result; + } + FakeSession &s = m.sess[slot]; + if (!s.live || (s.tag != tag)) { + *esp_err = WIFI_TLS_ESP_NOT_FOUND; + return WIFI_TLS_REFUSED; + } + s.live = false; + bytes notify = record('C', 0); + memcpy(ct_out, notify.data(), notify.size()); + *ct_out_len = notify.size(); + return 0; +} + +int wifi_tls_stats(uint8_t slot, uint16_t tag, wifi_tls_stats_t *stats, int *esp_err, uint32_t timeout_ms, + const wifi_tls_cancel_t *cancel) +{ + FakeModule &m = world_module; + *esp_err = 0; + if (!m.available) { + return WIFI_TLS_NO_MODULE; + } + log_call(0x33, slot, tag, cancel); + bool cancelled; + module_wait(timeout_ms, cancel, 0, &cancelled); + if (m.stats_result >= 0) { + *esp_err = m.stats_esp_err; + return m.stats_result; + } + memset(stats, 0, sizeof(*stats)); + if (slot == WIFI_TLS_SLOT_GLOBAL) { + stats->entropy_source = m.entropy ? 1 : 0; + stats->time_source = m.module_time ? 2 : 0; + stats->block_max_ms = m.block_max_ms; + return 0; + } + FakeSession &s = m.sess[slot]; + if (!s.live || (s.tag != tag)) { + *esp_err = WIFI_TLS_ESP_NOT_FOUND; + return WIFI_TLS_REFUSED; + } + stats->tls_version = m.version; + stats->ciphersuite = m.suite; + stats->group = m.group; + stats->ems = m.ems; + memcpy(stats->spki_sha256, m.spki, 32); + return 0; +} + +int wifi_tls_close_all(int *esp_err, uint32_t timeout_ms) +{ + FakeModule &m = world_module; + *esp_err = 0; + log_call(0x34, 0, 0, NULL); + m.close_alls++; + m.sess[0].live = false; + m.sess[1].live = false; + m.ca_loaded = false; + world_advance(1); + return 0; +} + +int wifi_tls_set_ca(const uint8_t *der, uint16_t der_len, uint16_t ca_tag, int *esp_err, uint8_t *reject, + uint32_t timeout_ms, const wifi_tls_cancel_t *cancel) +{ + FakeModule &m = world_module; + *esp_err = 0; + *reject = 0; + if (!m.available) { + return WIFI_TLS_NO_MODULE; + } + RpcCall &c = log_call(0x35, 0, ca_tag, cancel); + c.pt_in_len = der_len; + m.ca_der.assign(der, der + der_len); + world_advance(1); + m.ca_loaded = false; + if (m.set_ca_result == 0) { + m.ca_loaded = true; + m.ca_tag = ca_tag; + return 0; + } + *esp_err = m.set_ca_esp_err; + *reject = m.set_ca_reject; + return m.set_ca_result; +} + +// GET_RANDOM is not what these checks are about; the module is never asked for bytes +int wifi_get_random(uint8_t *buf, uint16_t len) +{ + return WIFI_RANDOM_NO_MODULE; +} diff --git a/software/test/wifi_tls/net_world.h b/software/test/wifi_tls/net_world.h new file mode 100644 index 000000000..e12c819bc --- /dev/null +++ b/software/test/wifi_tls/net_world.h @@ -0,0 +1,205 @@ +// The world the host tests run network_target.cc in: a clock, lwIP's sockets and DNS, the C64 reset line, and a WiFi +// module with a pretend TLS of [type][length lo][length hi][payload] records; deterministic, time moves only on waits. +// Types: 'H' hello/flight, 'F' Finished, 'D' data, 'C' close_notify, 'A' alert, 'B' bad MAC, 'W' warning, 'T' ticket. +#ifndef NET_WORLD_H_ +#define NET_WORLD_H_ + +#include +#include +#include +#include +#include "wifi_tls.h" + +typedef std::vector bytes; + +// The clock: one tick is 5 ms, as on the U64. +extern uint32_t world_tick; +void world_advance(uint32_t ticks); +uint32_t world_ms(void); // world_tick in ms +extern uint32_t world_reset_at; // the UCI Server task notes a C64 reset at this tick (world_reset_hook); ~0 for never +extern uint32_t world_abort_at; // ... and an abort of the running command (world_abort_hook); ~0 for never +extern void (*world_reset_hook)(void); +extern void (*world_abort_hook)(void); +extern uint32_t world_sntp; // what sntp_utc_now() answers + +// A record of the pretend TLS. +bytes record(char type, size_t length, uint32_t seed = 0); +uint8_t payload_byte(uint32_t seed, uint32_t i); + +// What a socket delivers: data, the peer's FIN, or an error; each from a tick on. +#define EV_DATA 0 +#define EV_FIN 1 +#define EV_ERR 2 +struct SockEvent { + int kind; + bytes data; + int err; + uint32_t at; +}; + +// What the server does when the module's ClientHello has arrived. +#define SRV_RESPOND 0 // its flight, flight bytes, from delay_ms on, in chunks of chunk bytes +#define SRV_STALL 1 +#define SRV_RST 2 +#define SRV_FIN 3 +struct FakeServer { + int on_hello; + size_t flight; + uint32_t delay_ms; + size_t chunk; + std::vector after_finished; // pushed once the module's Finished arrives (at is added to now) + bool echo; + bytes got; // plaintext the server received + bool saw_notify; // the module's close_notify + int saw_alert; // the module's alert, -1 for none + int hellos; + bytes client_stream; // every byte the module sent, unparsed rest + uint32_t connect_delay_ms; // a non-blocking connect takes this long + int connect_err; // ... and then fails with this errno + bool connect_never; + int rst_err; // the errno of SRV_RST; 0 for ECONNRESET + int send_err; // every send on this socket fails with it (set before the socket exists) + int send_err_from; // sends from this call number on (1-based) fail with send_err_late + int send_err_late; // EWOULDBLOCK makes it a stall +}; + +struct FakeSock { + bool open; + int type; + bool nonblocking; + bool nodelay; + bool rcvtimeo_set; + int sndtimeo_ms; // 0 when never set + bool connected; + uint32_t connect_at; // a non-blocking connect completes at this tick; 0 before it started + uint32_t connect_addr; // where to, network order + std::deque rx; + bool err_taken; // the error has been handed out once + bytes tx; + int send_err; // every send fails with this, when set + bool send_blocked; // every send would block + int recv_calls; + int recv_after_err; // recv calls after the first error + int send_calls; + int closes; + FakeServer srv; +}; +extern FakeSock world_socks[16]; +void server_push(int s, int kind, const bytes &data, int err = 0, uint32_t after_ms = 0); + +// DNS: how a name resolves. +#define DNS_IMMEDIATE 0 +#define DNS_ASYNC_OK 1 +#define DNS_ASYNC_NO 2 +#define DNS_ERR_VAL 3 +#define DNS_NEVER 4 +struct DnsRule { + std::string host; + int mode; + uint32_t addr; + uint32_t delay_ms; +}; +extern std::vector world_dns; +extern int world_dns_calls; +extern int world_dns_unlocked_calls; // dns_gethostbyname called without the core lock +extern int world_dns_late_writes; // callbacks that fired for an older lookup +extern int world_lock_depth; +extern int world_lock_bad; // a callback that ran while the core lock was held +void world_dns_fire_all(void); // every pending answer, now + +// A step answer forced on the module instead of the pretend TLS. +struct Forced { + int result; // WIFI_TLS_*: BUSY (no answer), INVALID, REFUSED, UNSENT + int esp_err; + bool applied; // the module still runs the step (for BUSY) + uint32_t delay_ms; // how long before the answer (0: at once) + // For an answer of 0 with FAILED + bool fail; + uint8_t fail_reason; + uint32_t verify_flags; + uint8_t alert_in; + int fail_err; + bool pt_on_no_read; // hand out plaintext on a NO_READ step (malformed) +}; + +struct FakeSession { + bool live; + uint16_t tag; + uint8_t trust; + int state; + bool sent_hello; + bytes in; + std::deque pt; + bytes out; + char terminal; // 'C', 'A' or 'B' waiting behind pt; 0 for none + uint8_t alert; +}; + +struct RpcCall { + int cmd; // 0x30.. as on the wire + uint8_t slot; + uint16_t tag; + uint8_t flags; + int ct_in_len; + int pt_in_len; + wifi_tls_open_t open; + std::string sni; + bytes pin; + bool cancel_given; +}; + +struct FakeModule { + bool available; + uint16_t major, minor; + uint32_t generation; + bool entropy; + bool module_time; // its own SNTP + // OPEN + int open_result; // forced; -1 for the normal checks + int open_esp_err; + uint8_t open_reason; + uint32_t open_delay_ms; + // the handshake + size_t hello_size; + bool hs_fail; + uint8_t hs_fail_reason; + uint32_t hs_verify_flags; + uint8_t hs_alert_in; + int hs_fail_err; + bool hs_alert_out; // send alert 40 with the failure + // STATS + uint16_t version, suite, group; + uint8_t ems; + uint8_t spki[32]; + uint16_t block_max_ms; + int stats_result; // forced; -1 for normal + int stats_esp_err; // with a forced REFUSED + // SET_CA + int set_ca_result; // WIFI_TLS_* to answer; 0 loads + int set_ca_esp_err; + uint8_t set_ca_reject; + bytes ca_der; + uint16_t ca_tag; + bool ca_loaded; + // CLOSE + int close_result; // forced; -1 for normal + int close_alls; + // steps + std::deque forced; + size_t in_cap; // what the module holds of unread ciphertext before AGAIN + int again_next; // answer AGAIN this many times first + FakeSession sess[2]; + std::vector calls; + int unsent_next; // answer UNSENT this many times first (any call) + bool quiet_alternate; // every other input-less step is quiet while plaintext is held + bool quiet_last; + int quiet_next; // input-less steps that hand out nothing although plaintext is held, first + // (the engine's skipped-warning WANT_READ case, tls_engine.c:503-505) +}; +extern FakeModule world_module; + +void world_reset(void); +int world_count(int cmd); +int world_open_sockets(void); + +#endif /* NET_WORLD_H_ */ diff --git a/software/test/wifi_tls/netstub/command_intf.h b/software/test/wifi_tls/netstub/command_intf.h new file mode 100644 index 000000000..1c5fa434c --- /dev/null +++ b/software/test/wifi_tls/netstub/command_intf.h @@ -0,0 +1,14 @@ +// Host stand-in for software/io/command_interface/command_intf.h: the real command_target.h, and of CommandInterface +// only what network_target.cc uses, faked in net_tls_test.cc. +#ifndef COMMAND_INTF_H +#define COMMAND_INTF_H +#include // the real header brings it, through its own includes +#include "command_target.h" + +class CommandInterface +{ +public: + bool reset_pending(void); +}; +extern CommandInterface cmd_if; +#endif diff --git a/software/test/wifi_tls/netstub/dump_hex.h b/software/test/wifi_tls/netstub/dump_hex.h new file mode 100644 index 000000000..c88a2fff8 --- /dev/null +++ b/software/test/wifi_tls/netstub/dump_hex.h @@ -0,0 +1 @@ +// Host stand-in: network_target.cc includes it and uses nothing from it. diff --git a/software/test/wifi_tls/netstub/lwip/dns.h b/software/test/wifi_tls/netstub/lwip/dns.h new file mode 100644 index 000000000..99b689389 --- /dev/null +++ b/software/test/wifi_tls/netstub/lwip/dns.h @@ -0,0 +1,19 @@ +// Host stand-in for lwip/dns.h and its address types (IPv4 only, as LWIP_IPV6 is 0 in lwipopts.h). +// net_tls_test.cc fakes dns_gethostbyname and carries a copy of lwIP's ip4addr_aton. +#ifndef LWIP_DNS_H_NETSTUB +#define LWIP_DNS_H_NETSTUB +#include +typedef int8_t err_t; +#define ERR_OK 0 +#define ERR_MEM -1 +#define ERR_INPROGRESS -5 +#define ERR_VAL -6 +#define ERR_ARG -16 +typedef struct { uint32_t addr; } ip4_addr_t; +typedef ip4_addr_t ip_addr_t; +#define ip_2_ip4(ipaddr) (ipaddr) +#define ip4_addr_get_u32(src_ipaddr) ((src_ipaddr)->addr) +int ip4addr_aton(const char *cp, ip4_addr_t *addr); +typedef void (*dns_found_callback)(const char *name, const ip_addr_t *ipaddr, void *callback_arg); +err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, dns_found_callback found, void *callback_arg); +#endif diff --git a/software/test/wifi_tls/netstub/lwip/opt.h b/software/test/wifi_tls/netstub/lwip/opt.h new file mode 100644 index 000000000..78e5f9061 --- /dev/null +++ b/software/test/wifi_tls/netstub/lwip/opt.h @@ -0,0 +1,5 @@ +// Host stand-in for lwip/opt.h: MEMP_NUM_NETCONN as software/network/config/lwipopts.h sets it. +#ifndef LWIP_OPT_H_NETSTUB +#define LWIP_OPT_H_NETSTUB +#define MEMP_NUM_NETCONN 16 +#endif diff --git a/software/test/wifi_tls/netstub/lwip/tcpip.h b/software/test/wifi_tls/netstub/lwip/tcpip.h new file mode 100644 index 000000000..92cbcc376 --- /dev/null +++ b/software/test/wifi_tls/netstub/lwip/tcpip.h @@ -0,0 +1,8 @@ +// Host stand-in for lwip/tcpip.h: the core lock, faked in net_tls_test.cc. +#ifndef LWIP_TCPIP_H_NETSTUB +#define LWIP_TCPIP_H_NETSTUB +void fake_lock_tcpip_core(void); +void fake_unlock_tcpip_core(void); +#define LOCK_TCPIP_CORE() fake_lock_tcpip_core() +#define UNLOCK_TCPIP_CORE() fake_unlock_tcpip_core() +#endif diff --git a/software/test/wifi_tls/netstub/netdb.h b/software/test/wifi_tls/netstub/netdb.h new file mode 100644 index 000000000..dea531578 --- /dev/null +++ b/software/test/wifi_tls/netstub/netdb.h @@ -0,0 +1,8 @@ +// Host stand-in for lwIP's netdb.h: the host's struct hostent, and lwIP's +// gethostbyname_r, which net_tls_test.cc fakes. +#ifndef NETDB_H_NETSTUB +#define NETDB_H_NETSTUB +#include_next +int gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, + int *h_errnop); +#endif diff --git a/software/test/wifi_tls/netstub/network_interface.h b/software/test/wifi_tls/netstub/network_interface.h new file mode 100644 index 000000000..fc5991f25 --- /dev/null +++ b/software/test/wifi_tls/netstub/network_interface.h @@ -0,0 +1,14 @@ +// Host stand-in for software/network/network_interface.h: what network_target.cc calls. +#ifndef NETWORK_INTERFACE_H_STUB +#define NETWORK_INTERFACE_H_STUB +#include +class NetworkInterface +{ +public: + static int getNumberOfInterfaces(void) { return 0; } + static NetworkInterface *getInterface(int i) { return 0; } + void getIpAddr(uint8_t *a) { } + void getMacAddr(uint8_t *a) { } + void setIpAddr(uint8_t *a) { } +}; +#endif diff --git a/software/test/wifi_tls/netstub/socket.h b/software/test/wifi_tls/netstub/socket.h new file mode 100644 index 000000000..6d706778b --- /dev/null +++ b/software/test/wifi_tls/netstub/socket.h @@ -0,0 +1,42 @@ +// Host stand-in for lwIP's socket API as network_target.cc and network_target_tls.cc see it (through compat/posix/sys/socket.h): the host's +// types and constants, and lwIP's calls, faked in net_tls_test.cc. The BSD names that the TCP and UDP commands use +// go to the same fakes. +#ifndef SOCKET_H_NETSTUB +#define SOCKET_H_NETSTUB +#include +#include +#include +#include +#include +#include +#include +#include + +// lwIP's sockaddr_in has sin_len, which BSD's has and Linux's does not. network_target.cc sets it right before sin_family, +// so there it lands on sin_family, which is then set; the fakes never read it. +#ifdef __linux__ +#define sin_len sin_family +#endif + +#define PP_HTONS(x) ((uint16_t)((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8))) + +int lwip_socket(int domain, int type, int protocol); +int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen); +int lwip_ioctl(int s, long cmd, void *argp); +int lwip_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen); +int lwip_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen); +ssize_t lwip_send(int s, const void *dataptr, size_t size, int flags); +ssize_t lwip_recv(int s, void *mem, size_t len, int flags); +ssize_t lwip_recvmsg(int s, struct msghdr *message, int flags); +int lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout); +int lwip_close(int s); + +#define ioctlsocket(a, b, c) lwip_ioctl(a, b, c) +// socket_slices.h and send_all.h (the sliced connect and send) use the BSD names +#define select(a, b, c, d, e) lwip_select(a, b, c, d, e) +#define getsockopt(a, b, c, d, e) lwip_getsockopt(a, b, c, d, e) +#define send(a, b, c, d) lwip_send(a, b, c, d) +#define socket(a, b, c) lwip_socket(a, b, c) +#define connect(a, b, c) lwip_connect(a, b, c) +#define setsockopt(a, b, c, d, e) lwip_setsockopt(a, b, c, d, e) +#endif diff --git a/software/test/wifi_tls/stub/FreeRTOS.h b/software/test/wifi_tls/stub/FreeRTOS.h new file mode 100644 index 000000000..9d856b8b9 --- /dev/null +++ b/software/test/wifi_tls/stub/FreeRTOS.h @@ -0,0 +1,25 @@ +// Host stand-in for FreeRTOS.h: the types and macros the code under test uses. +#ifndef FREERTOS_H_STUB +#define FREERTOS_H_STUB +#include +#include +typedef uint32_t TickType_t; +typedef long BaseType_t; +typedef unsigned long UBaseType_t; +typedef void *QueueHandle_t; +typedef void *TaskHandle_t; +#define pdTRUE 1 +#define pdFALSE 0 +#define configTICK_RATE_HZ 200 +#define portTICK_PERIOD_MS (1000 / configTICK_RATE_HZ) +// As in software/FreeRTOS/Source/include/projdefs.h. +#define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) +// The worker task of the network target is not run here: net_tls_test.cc calls execute() itself, as the +// worker does, so these only have to compile. +#define pdPASS 1 +#define portMAX_DELAY 0xffffffffUL +#define configMINIMAL_STACK_SIZE 512 +#define PRIO_NETSERVICE 1 +#define portENTER_CRITICAL() do { } while (0) +#define portEXIT_CRITICAL() do { } while (0) +#endif diff --git a/software/test/wifi_tls/stub/lwip/inet.h b/software/test/wifi_tls/stub/lwip/inet.h new file mode 100644 index 000000000..3711a25fa --- /dev/null +++ b/software/test/wifi_tls/stub/lwip/inet.h @@ -0,0 +1,6 @@ +#ifndef LWIP_INET_H_STUB +#define LWIP_INET_H_STUB +#include "lwip/sockets.h" +int fake_inet_aton(const char *cp, struct in_addr *addr); +#define inet_aton(cp, addr) fake_inet_aton(cp, (struct in_addr *)(addr)) +#endif diff --git a/software/test/wifi_tls/stub/lwip/netdb.h b/software/test/wifi_tls/stub/lwip/netdb.h new file mode 100644 index 000000000..8e53a6409 --- /dev/null +++ b/software/test/wifi_tls/stub/lwip/netdb.h @@ -0,0 +1 @@ +// Host stand-in: rpc_calls.h includes it and uses nothing from it. diff --git a/software/test/wifi_tls/stub/lwip/sockets.h b/software/test/wifi_tls/stub/lwip/sockets.h new file mode 100644 index 000000000..86ac73b79 --- /dev/null +++ b/software/test/wifi_tls/stub/lwip/sockets.h @@ -0,0 +1,36 @@ +// Host stand-in for lwIP's sockets.h: u16_t and the socket types that rpc_calls.h needs. +#ifndef LWIP_SOCKETS_H_STUB +#define LWIP_SOCKETS_H_STUB +#include +#include +#include +#include + +typedef uint16_t u16_t; +typedef uint32_t u32_t; +typedef u32_t socklen_t_stub; + +struct in_addr_stub { uint32_t s_addr; }; +struct sockaddr_stub { uint8_t sa_len; uint8_t sa_family; char sa_data[14]; }; +struct sockaddr_in_stub { uint8_t sin_len; uint8_t sin_family; uint16_t sin_port; struct in_addr_stub sin_addr; char sin_zero[8]; }; +#define sockaddr sockaddr_stub +#define sockaddr_in sockaddr_in_stub +#define in_addr in_addr_stub + +#define AF_INET 2 +#define SOCK_STREAM 1 +#define SOL_SOCKET 0xfff +#define SO_SNDTIMEO 0x1005 +#define SO_RCVTIMEO 0x1006 +#define MSG_DONTWAIT 0x08 +#define FIONBIO 0x8004667e +#define PP_HTONS(x) ((uint16_t)((((x) & 0xff) << 8) | (((x) & 0xff00) >> 8))) + +int lwip_socket(int domain, int type, int protocol); +int lwip_connect(int s, const struct sockaddr *name, socklen_t_stub namelen); +int lwip_ioctl(int s, long cmd, void *argp); +int lwip_setsockopt(int s, int level, int optname, const void *optval, socklen_t_stub optlen); +ssize_t lwip_send(int s, const void *dataptr, size_t size, int flags); +ssize_t lwip_recv(int s, void *mem, size_t len, int flags); +int lwip_close(int s); +#endif diff --git a/software/test/wifi_tls/stub/queue.h b/software/test/wifi_tls/stub/queue.h new file mode 100644 index 000000000..1c81345a3 --- /dev/null +++ b/software/test/wifi_tls/stub/queue.h @@ -0,0 +1,9 @@ +#ifndef QUEUE_H_STUB +#define QUEUE_H_STUB +#include "FreeRTOS.h" +BaseType_t xQueueReceive(QueueHandle_t queue, void *item, TickType_t ticks); +QueueHandle_t xQueueCreate(UBaseType_t length, UBaseType_t item_size); +BaseType_t xQueueSend(QueueHandle_t queue, const void *item, TickType_t ticks); +UBaseType_t uxQueueMessagesWaiting(QueueHandle_t queue); +void vQueueDelete(QueueHandle_t queue); +#endif diff --git a/software/test/wifi_tls/stub/sntp_time.h b/software/test/wifi_tls/stub/sntp_time.h new file mode 100644 index 000000000..b3567dd51 --- /dev/null +++ b/software/test/wifi_tls/stub/sntp_time.h @@ -0,0 +1,6 @@ +// Host stand-in for software/network/sntp_time.h, faked in net_world.cc. +#ifndef SNTP_TIME_H_STUB +#define SNTP_TIME_H_STUB +#include +uint32_t sntp_utc_now(void); +#endif diff --git a/software/test/wifi_tls/stub/task.h b/software/test/wifi_tls/stub/task.h new file mode 100644 index 000000000..f1b189274 --- /dev/null +++ b/software/test/wifi_tls/stub/task.h @@ -0,0 +1,9 @@ +#ifndef TASK_H_STUB +#define TASK_H_STUB +#include "FreeRTOS.h" +TickType_t xTaskGetTickCount(void); +void vTaskSuspendAll(void); +BaseType_t xTaskResumeAll(void); +void vTaskDelay(TickType_t ticks); +BaseType_t xTaskCreate(void (*code)(void *), const char *name, uint16_t stack, void *arg, UBaseType_t priority, TaskHandle_t *handle); +#endif diff --git a/software/test/wifi_tls/stub/wifi_cmd.h b/software/test/wifi_tls/stub/wifi_cmd.h new file mode 100644 index 000000000..08f01bb99 --- /dev/null +++ b/software/test/wifi_tls/stub/wifi_cmd.h @@ -0,0 +1,51 @@ +// Host stand-in for software/io/wifi/wifi_cmd.h: only what wifi_dedicated.cc uses, backed by the scripted world in +// world.cc. The declarations mirror the real header; keep them in step with it. +#ifndef WIFI_CMD_H_ +#define WIFI_CMD_H_ + +#include +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "rpc_calls.h" +extern "C" { + #include "cmd_buffer.h" +} + +class DmaUART +{ +public: + volatile uint32_t generation; + BaseType_t GetBuffer(command_buf_t **buf, TickType_t ticks); + BaseType_t TransmitPacket(command_buf_t *buf, uint16_t *ms = NULL); + BaseType_t FreeBuffer(command_buf_t *buf); +}; + +class Esp32 +{ +public: + DmaUART *uart; +}; +extern Esp32 esp32; + +extern uint16_t sequence_nr; +extern const char *no_wifi_buf; + +#define WIFI_DEDICATED_THREAD 0xFC +typedef struct { + command_buf_t *buf; + uint32_t generation; +} dedicated_reply_t; +extern QueueHandle_t dedicated_replies; +extern volatile bool dedicated_waiting; + +void world_enter_safe(void); +void world_leave_safe(void); +#define ENTER_SAFE_SECTION world_enter_safe() +#define LEAVE_SAFE_SECTION world_leave_safe() + +// Everything the code under test prints goes into the trace. +int world_printf(const char *fmt, ...); +#define printf world_printf + +#endif /* WIFI_CMD_H_ */ diff --git a/software/test/wifi_tls/wifi_tls_test.cc b/software/test/wifi_tls/wifi_tls_test.cc new file mode 100644 index 000000000..1f46e869c --- /dev/null +++ b/software/test/wifi_tls/wifi_tls_test.cc @@ -0,0 +1,762 @@ +// Host tests (make -C target/pc/linux/wifitls test) for the TLS calls to the WiFi module in wifi_tls.cc and for the +// channel they use (wifi_dedicated.cc), its cancel predicate included. The real wifi_tls.cc and +// wifi_dedicated.cc are compiled; only the UART, queue, tick and module are the world's. +#include +#include +#include +#include "world.h" +#include "wifi_dedicated.h" +#include "wifi_tls.h" +#include "wifi_random.h" +#include "rpc_calls.h" +#include "check.h" +#undef printf + +int failures; +int checks; + +void check(bool condition, const char *what, ...) +{ + char line[300]; + va_list ap; + va_start(ap, what); + vsnprintf(line, sizeof(line), what, ap); + va_end(ap); + checks++; + if (!condition) { + failures++; + printf(" FAIL %s\n", line); + } else { + printf(" ok %s\n", line); + } +} + + +#define SEQUENCE 0x1234 + +// Word aligned, as the data of a command_buf_t is. +static union { + uint32_t align; + uint8_t bytes[CMD_BUF_SIZE]; +} reply; + +static void header(uint8_t command) +{ + memset(reply.bytes, 0, sizeof(reply.bytes)); + rpc_header_t *hdr = (rpc_header_t *)reply.bytes; + hdr->command = command; + hdr->thread = WIFI_DEDICATED_THREAD; + hdr->sequence = SEQUENCE; +} + +// A step answer: state, esp_err, ct bytes of 0xC0+i and pt bytes of 0x50+i. +static int step_reply(uint8_t state, int esp_err, uint16_t ct, uint16_t pt) +{ + header(CMD_TLS_STEP); + rpc_tls_step_resp *r = (rpc_tls_step_resp *)reply.bytes; + r->esp_err = esp_err; + r->state = state; + r->alert_in = TLS_ALERT_NONE; + r->alert_out = TLS_ALERT_NONE; + r->ct_out_len = ct; + r->pt_out_len = pt; + for (int i = 0; i < ct; i++) { + r->data[i] = (uint8_t)(0xC0 + i); + } + for (int i = 0; i < pt; i++) { + r->data[ct + i] = (uint8_t)(0x50 + i); + } + return offsetof(rpc_tls_step_resp, data) + ct + pt; +} + +static uint8_t ct_out[CMD_BUF_SIZE]; +static uint8_t pt_out[CMD_BUF_SIZE]; + +static void fresh_step(wifi_tls_step_t *st, uint16_t room) +{ + memset(st, 0, sizeof(*st)); + memset(ct_out, 0xEE, sizeof(ct_out)); + memset(pt_out, 0xEE, sizeof(pt_out)); + st->ct_out = ct_out; + st->pt_out = pt_out; + st->ct_out_room = room; + st->pt_out_room = room; + st->ct_out_len = 0x7777; + st->pt_out_len = 0x7777; + st->state = WIFI_TLS_UNKNOWN; + st->esp_err = 0; +} + +static bool untouched(const uint8_t *buf) +{ + for (int i = 0; i < CMD_BUF_SIZE; i++) { + if (buf[i] != 0xEE) { + return false; + } + } + return true; +} + +static bool nothing_out(const wifi_tls_step_t *st) +{ + return untouched(ct_out) && untouched(pt_out) && (st->ct_out_len == 0x7777) && (st->pt_out_len == 0x7777); +} + +static void test_take_step(void) +{ + printf("The check on a STEP answer (20-byte header)\n"); + wifi_tls_step_t st; + const uint16_t sizes[][2] = { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 255, 1 }, { 256, 0 }, { 300, 700 }, { 1024, 0 }, { 0, 1024 } }; + bool all = true; + for (unsigned k = 0; k < sizeof(sizes) / sizeof(sizes[0]); k++) { + uint16_t ct = sizes[k][0], pt = sizes[k][1]; + int size = step_reply(TLS_STATE_ESTABLISHED, 0, ct, pt); + fresh_step(&st, 1024); + int r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + bool ok = (r == 0) && (st.ct_out_len == ct) && (st.pt_out_len == pt) && (st.state == WIFI_TLS_ESTABLISHED) && + (memcmp(ct_out, ((rpc_tls_step_resp *)reply.bytes)->data, ct) == 0) && + (memcmp(pt_out, ((rpc_tls_step_resp *)reply.bytes)->data + ct, pt) == 0) && + (ct_out[ct] == 0xEE) && (pt_out[pt] == 0xEE); + all = all && ok; + } + check(all, "an ESTABLISHED answer hands over exactly its bytes, at lengths from 0 to 1024 and past 255"); + + int size = step_reply(TLS_STATE_ESTABLISHED, 0, 10, 10); + int foreign = 0; + for (int command = 0; command < 256; command++) { + if (command == CMD_TLS_STEP) { + continue; + } + ((rpc_header_t *)reply.bytes)->command = command; + fresh_step(&st, 1024); + foreign += (wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st) == WIFI_TLS_FOREIGN) && nothing_out(&st); + } + check(foreign == 255, "an answer to any other command is foreign and changes nothing (%d of 255)", foreign); + + int shorts = 0; + size = step_reply(TLS_STATE_ESTABLISHED, 0, 10, 10); + for (int s = 0; s < 4; s++) { + fresh_step(&st, 1024); + shorts += (wifi_tls_take_step(reply.bytes, s, SEQUENCE, &st) == WIFI_TLS_FOREIGN) && nothing_out(&st); + } + for (int s = 4; s < 40; s++) { + fresh_step(&st, 1024); + shorts += (wifi_tls_take_step(reply.bytes, s, SEQUENCE, &st) == WIFI_TLS_INVALID) && nothing_out(&st); + } + for (int s = 41; s < 64; s++) { + fresh_step(&st, 1024); + shorts += (wifi_tls_take_step(reply.bytes, s, SEQUENCE, &st) == WIFI_TLS_INVALID) && nothing_out(&st); + } + check(shorts == 63, "an answer of any size but its own (40) hands out nothing (%d of 63), the older 16-byte header too", + shorts); + size = step_reply(TLS_STATE_ESTABLISHED, 0, 20, 0); + fresh_step(&st, 19); + int r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == WIFI_TLS_INVALID) && nothing_out(&st), "more ciphertext than the caller has room for is invalid, not cut"); + + // FAILED carries the reasons, and only FAILED does. + size = step_reply(TLS_STATE_FAILED, -0x2700, 7, 3); + rpc_tls_step_resp *res = (rpc_tls_step_resp *)reply.bytes; + res->fail_reason = TLS_FAIL_CERT_VERIFY; + res->verify_flags = 0x0C; + res->alert_in = 70; + res->alert_out = 42; + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == 0) && (st.state == WIFI_TLS_FAILED) && (st.esp_err == -0x2700) && (st.fail_reason == 4) && + (st.verify_flags == 0x0C) && (st.alert_in == 70) && (st.alert_out == 42) && (st.ct_out_len == 7) && + (st.pt_out_len == 0) && untouched(pt_out), + "FAILED: esp_err, fail_reason, verify_flags, alert_in and alert_out arrive; its plaintext is withheld"); + int reasons = 0; + for (int state = 0; state < 3; state++) { + size = step_reply((uint8_t)state, 0, 5, 0); + ((rpc_tls_step_resp *)reply.bytes)->fail_reason = 4; + fresh_step(&st, 1024); + reasons += (wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st) == WIFI_TLS_INVALID) && nothing_out(&st); + } + check(reasons == 3, "a fail_reason without FAILED is invalid (%d of 3)", reasons); + size = step_reply(TLS_STATE_ESTABLISHED, 0, 5, 0); + ((rpc_tls_step_resp *)reply.bytes)->alert_in = 0xFF; + ((rpc_tls_step_resp *)reply.bytes)->verify_flags = 0; + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == 0) && (st.alert_in == WIFI_TLS_ALERT_NONE) && (st.fail_reason == 0), "no alert is 0xFF"); + + // NO_READ. + size = step_reply(TLS_STATE_ESTABLISHED, 0, 30, 1); + fresh_step(&st, 1024); + st.flags = WIFI_TLS_STEP_NO_READ; + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == WIFI_TLS_INVALID) && nothing_out(&st), "plaintext on a NO_READ step is malformed (-> 17)"); + size = step_reply(TLS_STATE_ESTABLISHED, 0, 30, 0); + fresh_step(&st, 1024); + st.flags = WIFI_TLS_STEP_NO_READ; + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == 0) && (st.ct_out_len == 30), "a NO_READ step with ciphertext only is fine"); + size = step_reply(TLS_STATE_ESTABLISHED, 0, 30, 1); + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == 0) && (st.pt_out_len == 1), "without NO_READ the same answer is fine"); + + // The refusals, AGAIN, CLOSED. + size = step_reply(TLS_STATE_HANDSHAKING, 0x101, 9, 0); + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == WIFI_TLS_AGAIN) && (st.ct_out_len == 9) && (st.state == WIFI_TLS_HANDSHAKING), + "ESP_ERR_NO_MEM: AGAIN, with the output"); + size = step_reply(TLS_STATE_CLOSED, 0x101, 4, 7); + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == 0) && (st.state == WIFI_TLS_CLOSED) && (st.pt_out_len == 7), "CLOSED with NO_MEM: the last plaintext"); + size = step_reply(TLS_STATE_ESTABLISHED, 0x105, 0, 0); + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + check((r == WIFI_TLS_REFUSED) && (st.esp_err == 0x105) && nothing_out(&st), + "ESP_ERR_NOT_FOUND (a stale tag) is refused, nothing taken"); + header(CMD_TLS_STEP); + ((rpc_espcmd_resp *)reply.bytes)->esp_err = 0x105; + fresh_step(&st, 1024); + r = wifi_tls_take_step(reply.bytes, 8, SEQUENCE, &st); + check((r == WIFI_TLS_REFUSED) && (st.esp_err == 0x105) && nothing_out(&st), + "a bare 8-byte refusal is refused with its error"); + fresh_step(&st, 1024); + ((rpc_espcmd_resp *)reply.bytes)->esp_err = 0; + r = wifi_tls_take_step(reply.bytes, 8, SEQUENCE, &st); + check((r == WIFI_TLS_INVALID) && nothing_out(&st), "... but a bare 8-byte answer with no error is invalid"); + int states = 0; + for (int state = 4; state < 256; state++) { + size = step_reply((uint8_t)state, 0, 5, 5); + fresh_step(&st, 1024); + states += (wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st) == WIFI_TLS_INVALID) && nothing_out(&st); + } + check(states == 252, "a state that does not exist is invalid (%d of 252)", states); + + // Random answers: bytes only whole, only from an answer that holds them, + // plaintext only once established and never on a NO_READ step. + world_reset(99, NULL, true); + int broken = 0; + for (int n = 0; n < 300000; n++) { + for (int i = 0; i < 64; i++) { + reply.bytes[i] = (uint8_t)world_rand(256); + } + res = (rpc_tls_step_resp *)reply.bytes; + if (world_rand(2)) { + res->hdr.command = CMD_TLS_STEP; + res->hdr.sequence = SEQUENCE; + } + if (world_rand(2)) { + res->esp_err = world_rand(2) ? 0 : (world_rand(2) ? -0x2700 : 0x101); + } + if (world_rand(2)) { + res->state = world_rand(5); + } + if (world_rand(2)) { + res->fail_reason = world_rand(2) ? 0 : world_rand(8); + } + if (world_rand(2)) { + res->ct_out_len = world_rand(1100); + res->pt_out_len = world_rand(4) ? world_rand(1100) : 0; + } + size = world_rand(2) ? (int)world_rand(CMD_BUF_SIZE + 1) + : (int)(offsetof(rpc_tls_step_resp, data) + res->ct_out_len + res->pt_out_len); + if (size > CMD_BUF_SIZE) { + size = CMD_BUF_SIZE; + } + uint16_t room = (uint16_t)world_rand(1100); + fresh_step(&st, room); + st.flags = world_rand(2) ? WIFI_TLS_STEP_NO_READ : 0; + r = wifi_tls_take_step(reply.bytes, size, SEQUENCE, &st); + if ((r == 0) || (r == WIFI_TLS_AGAIN)) { + uint16_t ct = res->ct_out_len, pt = res->pt_out_len; + bool failed = (res->state == TLS_STATE_FAILED); + bool good = (ct <= room) && (pt <= room) && (size == (int)offsetof(rpc_tls_step_resp, data) + ct + pt) && + (st.ct_out_len == ct) && (res->state <= TLS_STATE_FAILED) && + (failed || (res->fail_reason == 0)) && + !((st.flags & WIFI_TLS_STEP_NO_READ) && pt) && + ((pt == 0) || failed || (res->state != TLS_STATE_HANDSHAKING)) && + (memcmp(ct_out, res->data, ct) == 0) && + (failed ? ((st.pt_out_len == 0) && untouched(pt_out)) + : ((st.pt_out_len == pt) && (memcmp(pt_out, res->data + ct, pt) == 0))); + broken += !good; + } else { + broken += !nothing_out(&st); + } + } + check(broken == 0, "300000 random answers: bytes only whole, only from an answer that holds them (%d not)", broken); +} + +static void test_take_others(void) +{ + printf("The checks on OPEN, CLOSE, STATS, CLOSE_ALL and SET_CA answers\n"); + int esp_err = 0; + uint8_t reason = 0x77; + + header(CMD_TLS_OPEN); + ((rpc_tls_open_resp *)reply.bytes)->slot = 1; + int r = wifi_tls_take_open(reply.bytes, sizeof(rpc_tls_open_resp), SEQUENCE, 1, &esp_err, &reason); + check(r == 0, "OPEN: 12 bytes, no error, slot 1 as asked: the session is open"); + int other = 0; + const uint8_t slots[] = { 0, 2, 0xFF }; + for (unsigned k = 0; k < sizeof(slots); k++) { + ((rpc_tls_open_resp *)reply.bytes)->slot = slots[k]; + other += (wifi_tls_take_open(reply.bytes, 12, SEQUENCE, 1, &esp_err, &reason) == WIFI_TLS_INVALID); + } + ((rpc_tls_open_resp *)reply.bytes)->slot = 1; + check(other == 3, "OPEN: success naming another slot (0, 2, 0xFF) is malformed (%d of 3)", other); + int wrong = 0; + const int open_sizes[] = { 4, 9, 10, 11, 13, 16 }; + for (unsigned k = 0; k < sizeof(open_sizes) / sizeof(open_sizes[0]); k++) { + wrong += (wifi_tls_take_open(reply.bytes, open_sizes[k], SEQUENCE, 1, &esp_err, &reason) == WIFI_TLS_INVALID); + } + check(wrong == 6, "OPEN: any size but 12 without an error is invalid (%d of 6)", wrong); + check(wifi_tls_take_open(reply.bytes, 8, SEQUENCE, 1, &esp_err, &reason) == WIFI_TLS_INVALID, + "OPEN: 8 bytes and no error is invalid"); + ((rpc_tls_open_resp *)reply.bytes)->esp_err = 0x103; + ((rpc_tls_open_resp *)reply.bytes)->reason = TLS_OPEN_REASON_NO_CUSTOM_CA; + r = wifi_tls_take_open(reply.bytes, sizeof(rpc_tls_open_resp), SEQUENCE, 1, &esp_err, &reason); + check((r == WIFI_TLS_REFUSED) && (esp_err == 0x103) && (reason == WIFI_TLS_REASON_NO_CUSTOM_CA), + "OPEN: refused, with reason 3 NO_CUSTOM_CA"); + // The refusal as the ESP32 sends it, slot 0xFF (tls_rpc.c cmd_tls_open). + ((rpc_tls_open_resp *)reply.bytes)->slot = 0xFF; + ((rpc_tls_open_resp *)reply.bytes)->reason = TLS_OPEN_REASON_NO_TIME; + r = wifi_tls_take_open(reply.bytes, sizeof(rpc_tls_open_resp), SEQUENCE, 1, &esp_err, &reason); + check((r == WIFI_TLS_REFUSED) && (reason == WIFI_TLS_REASON_NO_TIME), + "OPEN refused as the ESP32 sends it (slot byte 0xFF) -> REFUSED with its reason, not malformed"); + ((rpc_tls_open_resp *)reply.bytes)->slot = 1; + header(CMD_TLS_OPEN); + ((rpc_espcmd_resp *)reply.bytes)->esp_err = 0x106; + reason = 0; + r = wifi_tls_take_open(reply.bytes, 8, SEQUENCE, 1, &esp_err, &reason); + check((r == WIFI_TLS_REFUSED) && (esp_err == 0x106) && (reason == 0), + "OPEN: a module without TLS answers a bare NOT_SUPPORTED: refused (-> 90)"); + ((rpc_header_t *)reply.bytes)->command = CMD_TLS_STEP; + check(wifi_tls_take_open(reply.bytes, 12, SEQUENCE, 1, &esp_err, &reason) == WIFI_TLS_FOREIGN, "OPEN: a STEP answer is foreign"); + + uint8_t notify[64]; + uint16_t notify_len = 0x7777; + header(CMD_TLS_CLOSE); + rpc_tls_close_resp *c = (rpc_tls_close_resp *)reply.bytes; + c->ct_out_len = 24; + for (int i = 0; i < 24; i++) { + c->data[i] = (uint8_t)(0x90 + i); + } + r = wifi_tls_take_close(reply.bytes, 36, SEQUENCE, notify, sizeof(notify), ¬ify_len, &esp_err); + check((r == 0) && (notify_len == 24) && (notify[0] == 0x90) && (notify[23] == 0xA7), + "CLOSE: 12 + 24 bytes: the close_notify record arrives"); + check(wifi_tls_take_close(reply.bytes, 35, SEQUENCE, notify, sizeof(notify), ¬ify_len, &esp_err) == + WIFI_TLS_INVALID, "CLOSE: a byte short is invalid"); + check(wifi_tls_take_close(reply.bytes, 37, SEQUENCE, notify, sizeof(notify), ¬ify_len, &esp_err) == + WIFI_TLS_INVALID, "CLOSE: a byte long is invalid"); + check(wifi_tls_take_close(reply.bytes, 36, SEQUENCE, notify, 23, ¬ify_len, &esp_err) == WIFI_TLS_INVALID, + "CLOSE: a record past the room is invalid"); + c->ct_out_len = 0; + c->esp_err = 0x105; + r = wifi_tls_take_close(reply.bytes, 12, SEQUENCE, notify, sizeof(notify), ¬ify_len, &esp_err); + check((r == WIFI_TLS_REFUSED) && (esp_err == 0x105), "CLOSE: NOT_FOUND in the full answer is refused, with its error"); + r = wifi_tls_take_close(reply.bytes, 8, SEQUENCE, notify, sizeof(notify), ¬ify_len, &esp_err); + check((r == WIFI_TLS_REFUSED) && (esp_err == 0x105), "CLOSE: ... and as a bare 8-byte answer"); + + header(CMD_TLS_STATS); + rpc_tls_stats_resp *s = (rpc_tls_stats_resp *)reply.bytes; + s->heap_free = 100001; + s->tls_version = 0x0303; + s->ciphersuite = 0xC02F; + s->group = 0x0017; + s->state = TLS_STATE_ESTABLISHED; + s->time_source = 2; + s->entropy_source = 1; + s->ems = 1; + s->block_max_ms = 0x1234; + for (int i = 0; i < 32; i++) { + s->spki_sha256[i] = (uint8_t)(i * 7); + } + wifi_tls_stats_t stats; + memset(&stats, 0, sizeof(stats)); + r = wifi_tls_take_stats(reply.bytes, sizeof(rpc_tls_stats_resp), SEQUENCE, &stats, &esp_err); + check((r == 0) && (stats.heap_free == 100001) && (stats.tls_version == 0x0303) && (stats.ciphersuite == 0xC02F) && + (stats.group == 0x0017) && (stats.time_source == 2) && (stats.entropy_source == 1) && (stats.ems == 1) && + (stats.block_max_ms == 0x1234) && (stats.spki_sha256[0] == 0) && (stats.spki_sha256[31] == 217), + "STATS: 96 bytes, entropy, ems, block_max_ms and the SPKI hash arrive"); + const int stat_sizes[] = { 8, 60, 64, 95, 97 }; + wrong = 0; + for (unsigned k = 0; k < sizeof(stat_sizes) / sizeof(stat_sizes[0]); k++) { + memset(&stats, 0, sizeof(stats)); + wrong += (wifi_tls_take_stats(reply.bytes, stat_sizes[k], SEQUENCE, &stats, &esp_err) == WIFI_TLS_INVALID) && + (stats.heap_free == 0); + } + check(wrong == 5, "STATS: any size but 96, the older 60 included, is invalid (%d of 5)", wrong); + + header(CMD_TLS_CLOSE_ALL); + check(wifi_tls_take_close_all(reply.bytes, 8, SEQUENCE, &esp_err) == 0, "CLOSE_ALL: 8 bytes, no error"); + check(wifi_tls_take_close_all(reply.bytes, 12, SEQUENCE, &esp_err) == WIFI_TLS_INVALID, "CLOSE_ALL: 12 is invalid"); + ((rpc_espcmd_resp *)reply.bytes)->esp_err = 0x106; + check(wifi_tls_take_close_all(reply.bytes, 8, SEQUENCE, &esp_err) == WIFI_TLS_REFUSED, "CLOSE_ALL: an error"); + + struct { int err; int reject; int want; } ca[] = { + { 0, 0, 0 }, + { -0x2180, 0, WIFI_TLS_REFUSED }, + { -2, 0, WIFI_TLS_REFUSED }, + { -1, 0, WIFI_TLS_INVALID }, // ESP_FAIL is not a parse code + { 0, 1, WIFI_TLS_INVALID }, + { 0x102, 1, WIFI_TLS_REFUSED }, + { 0x102, 3, WIFI_TLS_REFUSED }, + { 0x102, 4, WIFI_TLS_REFUSED }, + { 0x102, 0, WIFI_TLS_INVALID }, + { 0x102, 2, WIFI_TLS_INVALID }, // reserved (was WEAK_SIG_HASH) + { 0x102, 5, WIFI_TLS_INVALID }, + { 0x101, 0, WIFI_TLS_INVALID }, // NO_MEM + { -0x2180, 1, WIFI_TLS_INVALID }, + }; + int good = 0; + for (unsigned k = 0; k < sizeof(ca) / sizeof(ca[0]); k++) { + header(CMD_TLS_SET_CA); + ((rpc_tls_set_ca_resp *)reply.bytes)->esp_err = ca[k].err; + ((rpc_tls_set_ca_resp *)reply.bytes)->reject = ca[k].reject; + int e = 0x77; + uint8_t j = 0x77; + r = wifi_tls_take_set_ca(reply.bytes, 12, SEQUENCE, &e, &j); + bool ok = (r == ca[k].want) && ((r != WIFI_TLS_REFUSED) || ((e == ca[k].err) && (j == ca[k].reject))); + if (!ok) { + printf(" SET_CA %d/%d gave %d\n", ca[k].err, ca[k].reject, r); + } + good += ok; + } + check(good == (int)(sizeof(ca) / sizeof(ca[0])), "SET_CA: only the three well formed answers pass"); + header(CMD_TLS_SET_CA); + check(wifi_tls_take_set_ca(reply.bytes, 11, SEQUENCE, &esp_err, &reason) == WIFI_TLS_INVALID, "SET_CA: 11 bytes"); + ((rpc_espcmd_resp *)reply.bytes)->esp_err = 0x106; + check(wifi_tls_take_set_ca(reply.bytes, 8, SEQUENCE, &esp_err, &reason) == WIFI_TLS_REFUSED && esp_err == 0x106, + "SET_CA: a bare NOT_SUPPORTED is refused (-> 90)"); +} + +// Answers to the TLS calls, from what the request asked. +static void tls_maker(command_buf_t *rx, const uint8_t *req, int req_size, int kind) +{ + const rpc_header_t *request = (const rpc_header_t *)req; + memset(rx->data, 0, sizeof(rx->data)); + rpc_header_t *hdr = (rpc_header_t *)rx->data; + *hdr = *request; + switch (request->command) { + case CMD_TLS_OPEN: + ((rpc_tls_open_resp *)rx->data)->slot = ((const rpc_tls_open_req *)req)->slot; + rx->size = sizeof(rpc_tls_open_resp); + break; + case CMD_TLS_STEP: { + rpc_tls_step_resp *r = (rpc_tls_step_resp *)rx->data; + r->state = TLS_STATE_ESTABLISHED; + r->alert_in = 0xFF; + r->alert_out = 0xFF; + r->ct_out_len = 5; + r->pt_out_len = 4; + for (int i = 0; i < 9; i++) { + r->data[i] = (uint8_t)(i + 1); + } + rx->size = offsetof(rpc_tls_step_resp, data) + 9; + break; + } + case CMD_TLS_CLOSE: + rx->size = sizeof(rpc_tls_close_resp); + break; + case CMD_TLS_STATS: + ((rpc_tls_stats_resp *)rx->data)->heap_free = 123456; + rx->size = sizeof(rpc_tls_stats_resp); + break; + case CMD_TLS_SET_CA: + rx->size = sizeof(rpc_tls_set_ca_resp); + break; + default: + rx->size = sizeof(rpc_espcmd_resp); + break; + } +} + +static void late_maker(command_buf_t *rx, const uint8_t *req, int req_size, int kind) +{ + tls_maker(rx, req, req_size, kind); + ((rpc_header_t *)rx->data)->sequence++; +} + +// The request that went out, as the world recorded it: "transmit n: xx xx ...". +static std::string sent(void) +{ + size_t at = world_trace.find("transmit "); + if (at == std::string::npos) { + return ""; + } + size_t end = world_trace.find('\n', at); + return world_trace.substr(at, end - at); +} + +static std::string hex(const uint8_t *bytes, int n) +{ + std::string out; + char b[4]; + for (int i = 0; i < n; i++) { + snprintf(b, sizeof(b), " %02x", bytes[i]); + out += b; + } + return out; +} + +static int cancel_calls; +static int cancel_after; +static bool cancel_after_n(void *context) +{ + return ++cancel_calls >= cancel_after; +} + +static int count(const std::string &text, const std::string &what) +{ + int n = 0; + for (size_t at = text.find(what); at != std::string::npos; at = text.find(what, at + 1)) { + n++; + } + return n; +} + +static void test_calls(void) +{ + printf("The TLS calls through the channel (wire layouts, byte for byte)\n"); + int esp_err = 0x55; + uint8_t reason = 0x55; + + uint8_t pin[32]; + for (int i = 0; i < 32; i++) { + pin[i] = (uint8_t)(0xE0 + i); + } + wifi_tls_open_t o; + memset(&o, 0, sizeof(o)); + o.trust = WIFI_TLS_TRUST_PIN; + o.slot = 1; + o.tag = 0x0203; + o.opts = WIFI_TLS_OPT_REQUIRE_TLS13; + o.time_source = WIFI_TLS_TIME_NIOS; + o.unix_time = 0x6789ABCD; + o.ca_tag = 0x0405; + o.pin = pin; + o.sni = "a.b"; + o.sni_len = 3; + world_reset(1, tls_maker, true); + uint16_t seq = sequence_nr; + int r = wifi_tls_open(&o, 5000, NULL, &esp_err, &reason); + const uint8_t fixed[] = { CMD_TLS_OPEN, WIFI_DEDICATED_THREAD, (uint8_t)seq, (uint8_t)(seq >> 8), 2, 3, 1, 1, + 0xCD, 0xAB, 0x89, 0x67, 0x03, 0x02, 0x01, 0, 0x05, 0x04, 0, 0 }; + std::string want = "transmit 55:" + hex(fixed, 20) + hex(pin, 32) + hex((const uint8_t *)"a.b", 3); + check((r == 0) && (esp_err == 0) && (sent() == want), + "OPEN: hdr, trust, sni_len, slot, time_source, unix_time, tag, opts, 0, ca_tag, 0 0, pin[32], sni"); + o.pin = NULL; + o.sni = NULL; + o.sni_len = 0; + o.trust = 0; + world_reset(2, tls_maker, true); + r = wifi_tls_open(&o, 5000, NULL, &esp_err, &reason); + std::string s = sent(); + check((r == 0) && (s.compare(0, 12, "transmit 52:") == 0) && (count(s, " 00") >= 36), + "OPEN: no name, no pin: 52 bytes, the pin as zeros"); + o.sni_len = 254; + world_reset(3, tls_maker, true); + r = wifi_tls_open(&o, 5000, NULL, &esp_err, &reason); + check((r == WIFI_TLS_TOO_LONG) && (world_trace.find("getbuffer") == std::string::npos), "OPEN: 254 bytes of name send nothing"); + + wifi_tls_step_t st; + uint8_t ct_in[3] = { 0xA1, 0xA2, 0xA3 }; + uint8_t pt_in[2] = { 0xB1, 0xB2 }; + fresh_step(&st, 1024); + st.flags = WIFI_TLS_STEP_NO_READ; + st.ct_in = ct_in; + st.ct_in_len = 3; + st.pt_in = pt_in; + st.pt_in_len = 2; + world_reset(6, tls_maker, true); + seq = sequence_nr; + r = wifi_tls_step(1, 0x0A0B, &st, 5000, NULL); + uint8_t expect_step[] = { CMD_TLS_STEP, WIFI_DEDICATED_THREAD, (uint8_t)seq, (uint8_t)(seq >> 8), 1, 1, 0x0B, + 0x0A, 3, 0, 2, 0, 0xA1, 0xA2, 0xA3, 0xB1, 0xB2 }; + check((r == WIFI_TLS_INVALID) && (sent() == "transmit 17:" + hex(expect_step, sizeof(expect_step))), + "STEP: slot, flags, tag, ct_in_len, pt_in_len, ciphertext, plaintext (and the maker's plaintext on NO_READ is refused)"); + fresh_step(&st, 1024); + st.ct_in = ct_in; + st.ct_in_len = 3; + world_reset(7, tls_maker, true); + r = wifi_tls_step(0, 1, &st, 5000, NULL); + check((r == 0) && (st.ct_out_len == 5) && (st.pt_out_len == 4) && (ct_out[0] == 1) && (pt_out[0] == 6), + "STEP: the answer is split into ciphertext and plaintext"); + static uint8_t big[WIFI_TLS_STEP_MAX_IN + 1]; + fresh_step(&st, 1024); + st.ct_in = big; + st.ct_in_len = 1537; + world_reset(8, tls_maker, true); + r = wifi_tls_step(0, 1, &st, 5000, NULL); + check((r == WIFI_TLS_TOO_LONG) && (world_trace.find("getbuffer") == std::string::npos), "STEP: 1537 bytes in send nothing"); + st.ct_in_len = 1536; + world_reset(8, tls_maker, true); + r = wifi_tls_step(0, 1, &st, 5000, NULL); + check((r == 0) && (sent().compare(0, 15, "transmit 1548: ") == 0), "STEP: 1536 bytes in go in one request"); + + uint8_t notify[64]; + uint16_t notify_len; + world_reset(9, tls_maker, true); + seq = sequence_nr; + r = wifi_tls_close(1, 0xBEEF, notify, sizeof(notify), ¬ify_len, &esp_err, 1000, NULL); + uint8_t expect_close[] = { CMD_TLS_CLOSE, WIFI_DEDICATED_THREAD, (uint8_t)seq, (uint8_t)(seq >> 8), 1, 0, + 0xEF, 0xBE }; + check((r == 0) && (notify_len == 0) && (sent() == "transmit 8:" + hex(expect_close, sizeof(expect_close))), + "CLOSE: slot, 0, tag (8 bytes)"); + wifi_tls_stats_t stats; + world_reset(10, tls_maker, true); + seq = sequence_nr; + r = wifi_tls_stats(WIFI_TLS_SLOT_GLOBAL, 0, &stats, &esp_err, 1000, NULL); + uint8_t expect_stats[] = { CMD_TLS_STATS, WIFI_DEDICATED_THREAD, (uint8_t)seq, (uint8_t)(seq >> 8), 0xFF, 0, + 0, 0 }; + check((r == 0) && (stats.heap_free == 123456) && (sent() == "transmit 8:" + hex(expect_stats, 8)), + "STATS: the module as a whole is slot $FF, tag 0"); + world_reset(11, tls_maker, true); + seq = sequence_nr; + r = wifi_tls_close_all(&esp_err, 500); + uint8_t expect_all[] = { CMD_TLS_CLOSE_ALL, WIFI_DEDICATED_THREAD, (uint8_t)seq, (uint8_t)(seq >> 8) }; + check((r == 0) && (sent() == "transmit 4:" + hex(expect_all, 4)), "CLOSE_ALL: the header only"); + uint8_t der[5] = { 0x30, 0x82, 0x01, 0x02, 0x03 }; + uint8_t reject; + world_reset(12, tls_maker, true); + seq = sequence_nr; + r = wifi_tls_set_ca(der, 5, 0x1122, &esp_err, &reject, 5000, NULL); + uint8_t expect_ca[] = { CMD_TLS_SET_CA, WIFI_DEDICATED_THREAD, (uint8_t)seq, (uint8_t)(seq >> 8), 5, 0, + 0x22, 0x11, 0x30, 0x82, 0x01, 0x02, 0x03 }; + check((r == 0) && (sent() == "transmit 13:" + hex(expect_ca, sizeof(expect_ca))), "SET_CA: der_len, ca_tag, der"); + static uint8_t big_ca[WIFI_TLS_CA_MAX + 1]; + world_reset(12, tls_maker, true); + r = wifi_tls_set_ca(big_ca, WIFI_TLS_CA_MAX + 1, 1, &esp_err, &reject, 5000, NULL); + check((r == WIFI_TLS_TOO_LONG) && (world_trace.find("getbuffer") == std::string::npos), "SET_CA: 1473 bytes send nothing"); + world_reset(12, tls_maker, true); + r = wifi_tls_set_ca(big_ca, WIFI_TLS_CA_MAX, 1, &esp_err, &reject, 5000, NULL); + check((r == 0) && (sent().compare(0, 15, "transmit 1480: ") == 0), "SET_CA: 1472 bytes go in one request"); + + // The waits: each call its caller's timeout; with a cancel, in slices. + world_reset(13, late_maker, true); + fresh_step(&st, 1024); + r = wifi_tls_step(0, 1, &st, 5000, NULL); + check((r == WIFI_TLS_BUSY) && (world_trace.find("receive 1000") != std::string::npos) && !dedicated_waiting, + "no cancel: one wait of the whole timeout (5 s = 1000 ticks), then BUSY"); + world_reset(14, late_maker, true); + cancel_calls = 0; + cancel_after = 1000; + wifi_tls_cancel_t never = { cancel_after_n, NULL }; + fresh_step(&st, 1024); + r = wifi_tls_step(0, 1, &st, 1000, &never); + check((r == WIFI_TLS_BUSY) && (count(world_trace, "receive 20") == 10) && (cancel_calls == 10) && + (world_trace.find("print: TLS Step: no reply.") != std::string::npos), + "a cancel that never fires: ten 100-ms slices, asked after each (%d), then BUSY", cancel_calls); + world_reset(15, late_maker, true); + cancel_calls = 0; + cancel_after = 3; + wifi_tls_cancel_t soon = { cancel_after_n, NULL }; + fresh_step(&st, 1024); + r = wifi_tls_step(0, 1, &st, 5000, &soon); + // The first slice brings the late (foreign) answer and is skipped; three empty ones follow. + check((r == WIFI_TLS_BUSY) && (cancel_calls == 3) && (count(world_trace, "receive 20") == 4) && + (world_trace.find("print: TLS Step: cancelled.") != std::string::npos) && !dedicated_waiting && + (world_queued() == 0) && (st.ct_out_len == 0) && (st.pt_out_len == 0) && untouched(ct_out) && + untouched(pt_out), + "a cancel after 3 slices ends the call with BUSY at once, frees the channel, takes nothing"); + // The answer arrives just as the cancel fires: the call has given up, so + // it is dropped, not taken. + world_reset(20, late_maker, true); + fresh_step(&st, 1024); + struct arriving_right { + static void maker(command_buf_t *rx, const uint8_t *req, int req_size, int kind) + { + tls_maker(rx, req, req_size, kind); + } + static bool now(void *context) + { + world_reset_maker(maker); + world_deliver_now(); + return true; + } + }; + wifi_tls_cancel_t race = { arriving_right::now, NULL }; + r = wifi_tls_step(0, 1, &st, 5000, &race); + check((r == WIFI_TLS_BUSY) && (st.ct_out_len == 0) && untouched(ct_out) && (world_queued() == 0) && + !dedicated_waiting, + "an answer that arrives as the cancel fires is dropped: BUSY, nothing taken, the queue emptied (%d)", r); + + world_reset(16, tls_maker, true); + cancel_calls = 0; + cancel_after = 1; + fresh_step(&st, 1024); + r = wifi_tls_step(0, 1, &st, 5000, &soon); + check((r == 0) && (cancel_calls == 0), "an answer inside the first slice is taken; cancel is not even asked"); + world_reset(17, tls_maker, true); + world_ready = false; + r = wifi_tls_close_all(&esp_err, 500); + check((r == WIFI_TLS_NO_MODULE) && world_trace.empty(), "without the module application nothing is tried"); + world_reset(18, tls_maker, true); + dedicated_waiting = true; + r = wifi_tls_stats(0, 1, &stats, &esp_err, 1000, NULL); + check((r == WIFI_TLS_UNSENT) && dedicated_waiting, "another request outstanding: UNSENT at once"); + // Nothing sent: a failed GetBuffer or TransmitPacket is UNSENT for the TLS calls and BUSY for GET_RANDOM. + uint8_t random_bytes[16]; + world_reset(19, tls_maker, true); + world_no_buffer = true; + r = wifi_tls_stats(0, 1, &stats, &esp_err, 1000, NULL); + check((r == WIFI_TLS_UNSENT) && (world_transmits == 0) && !dedicated_waiting && (world_queued() == 0), + "no buffer: UNSENT (%d), nothing sent, the channel free again", r); + world_reset(19, tls_maker, true); + world_no_buffer = true; + r = wifi_get_random(random_bytes, sizeof(random_bytes)); + check((r == WIFI_RANDOM_BUSY) && (world_transmits == 0) && !dedicated_waiting, + "GET_RANDOM, no buffer: BUSY, not UNSENT (%d)", r); + world_reset(21, tls_maker, true); + world_no_transmit = true; + r = wifi_tls_stats(0, 1, &stats, &esp_err, 1000, NULL); + check((r == WIFI_TLS_UNSENT) && (world_transmits == 0) && !dedicated_waiting && (world_queued() == 0) && + (world_trace.find("print: TLS Stats: no reply.") != std::string::npos), + "a failed transmit: UNSENT, not BUSY (%d): the module never saw the request", r); + world_reset(21, tls_maker, true); + world_no_transmit = true; + r = wifi_get_random(random_bytes, sizeof(random_bytes)); + check((r == WIFI_RANDOM_BUSY) && (world_transmits == 0) && !dedicated_waiting, + "GET_RANDOM, a failed transmit: BUSY, not UNSENT (%d)", r); + world_reset(22, tls_maker, true); + dedicated_waiting = true; + r = wifi_get_random(random_bytes, sizeof(random_bytes)); + check((r == WIFI_RANDOM_BUSY) && dedicated_waiting, "GET_RANDOM, channel taken: BUSY, not UNSENT (%d)", r); + + // The buffer of a taken answer is freed with the scheduler suspended, so that no reset gets in between. + world_reset(23, tls_maker, true); + r = wifi_tls_stats(0, 1, &stats, &esp_err, 1000, NULL); + check((r == 0) && (world_frees == 1) && (world_free_unsuspended == 0) && (world_suspended == 0), + "a taken answer is freed inside the suspended section (%d frees, %d outside)", world_frees, + world_free_unsuspended); + // So is one that is dropped unread after the call gave up. + world_reset(24, late_maker, true); + cancel_calls = 0; + cancel_after = 1; + fresh_step(&st, 1024); + r = wifi_tls_step(0, 1, &st, 5000, &soon); + check((r == WIFI_TLS_BUSY) && (world_frees >= 1) && (world_free_unsuspended == 0) && (world_suspended == 0), + "a skipped answer is freed inside the suspended section (%d frees, %d outside)", world_frees, + world_free_unsuspended); + + // An answer queued before the last buffer pool reset is dropped unread and its buffer not freed. + world_reset(25, tls_maker, true); + world_stale_next = true; + memset(&stats, 0, sizeof(stats)); + r = wifi_tls_stats(0, 1, &stats, &esp_err, 100, NULL); + check((r == WIFI_TLS_BUSY) && (world_isr_calls == 1) && (world_frees == 0) && (stats.heap_free == 0) && + !dedicated_waiting && (world_queued() == 0), + "a right-looking answer of a past generation is not taken and not freed: BUSY (%d)", r); + world_reset(26, tls_maker, true); + world_stale_next = true; + r = wifi_get_random(random_bytes, sizeof(random_bytes)); + check((r == WIFI_RANDOM_BUSY) && (world_frees == 0), "GET_RANDOM: a past generation's answer is dropped (%d)", r); +} + +int main(void) +{ + test_take_step(); + test_take_others(); + test_calls(); + printf("\n%d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/software/test/wifi_tls/world.cc b/software/test/wifi_tls/world.cc new file mode 100644 index 000000000..366133b91 --- /dev/null +++ b/software/test/wifi_tls/world.cc @@ -0,0 +1,283 @@ +/* + * world.cc: see world.h. + */ +#include +#include +#include +#include "world.h" + +Esp32 esp32; +uint16_t sequence_nr; +const char *no_wifi_buf = "No buffer for WiFi command.\n"; +QueueHandle_t dedicated_replies; +volatile bool dedicated_waiting; + +bool world_ready; +bool world_no_buffer; +bool world_no_transmit; +std::string world_trace; +int world_suspended; +int world_transmits; +int world_isr_calls; +int world_frees; +int world_free_unsuspended; +bool world_stale_next; + +#define QUEUE_DEPTH 4 // as wifi_cmd.cc creates it +#define RX_BUFFERS 16 + +static DmaUART uart; +static std::deque queue; +static uint32_t rng; +static TickType_t now; +static command_buf_t tx_buf; +static command_buf_t rx_bufs[RX_BUFFERS]; +static int rx_next; +static uint8_t last_tx[CMD_BUF_SIZE]; +static int last_tx_size; +static world_maker_t make_reply; +static bool calm; +static bool calm_delivered; + +static void trace(const char *fmt, ...) +{ + char line[256]; + va_list ap; + va_start(ap, fmt); + vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + world_trace += line; +} + +uint32_t world_rand(uint32_t n) +{ + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + return n ? (rng % n) : 0; +} + +size_t world_queued(void) +{ + return queue.size(); +} + +void world_reset(uint32_t seed, world_maker_t maker, bool quiet) +{ + rng = (seed * 2654435761u) ^ 0x9E3779B9u; + if (!rng) { + rng = 1; + } + make_reply = maker; + calm = quiet; + calm_delivered = false; + world_trace.clear(); + queue.clear(); + world_suspended = 0; + world_transmits = 0; + world_isr_calls = 0; + world_frees = 0; + world_free_unsuspended = 0; + world_stale_next = false; + rx_next = 0; + last_tx_size = -1; + // Now and then start just short of the tick counter wrapping. + now = (world_rand(4) == 0) ? (0xFFFFFFFFu - world_rand(400)) : world_rand(100000); + sequence_nr = (uint16_t)world_rand(65536); + uart.generation = world_rand(1000); + esp32.uart = &uart; + world_ready = calm || (world_rand(100) >= 3); + world_no_buffer = false; + world_no_transmit = false; + dedicated_replies = (!calm && (world_rand(100) < 2)) ? NULL : (QueueHandle_t)&queue; + dedicated_waiting = !calm && (world_rand(100) < 5); // another caller holds the channel + memset(tx_buf.data, 0xAB, sizeof(tx_buf.data)); + tx_buf.bufnr = 3; + for (int i = 0; i < RX_BUFFERS; i++) { + rx_bufs[i].bufnr = 0x40 | i; + } +} + +// The receive interrupt, as wifi_rx_isr handles a frame on the dedicated thread. +static void isr_deliver(void) +{ + command_buf_t *rx = &rx_bufs[rx_next++ % RX_BUFFERS]; + int kind = calm ? 0 : (int)world_rand(10); + make_reply(rx, last_tx, last_tx_size, kind); + uint32_t generation = uart.generation; + if (!calm && (world_rand(10) == 0)) { + generation--; // tagged before a reset that has since happened + } + if (world_stale_next) { + generation--; // tagged before a reset that has since happened + world_stale_next = false; + } + world_isr_calls++; + if (!dedicated_waiting) { + trace("isr drop b%x (not waiting)\n", rx->bufnr); + } else if (queue.size() >= QUEUE_DEPTH) { + trace("isr drop b%x (full)\n", rx->bufnr); + } else { + dedicated_reply_t reply = { rx, generation }; + queue.push_back(reply); + trace("isr queue b%x g%u k%d\n", rx->bufnr, generation, kind); + } +} + +void world_reset_maker(world_maker_t maker) +{ + make_reply = maker; +} + +void world_deliver_now(void) +{ + isr_deliver(); +} + +TickType_t xTaskGetTickCount(void) +{ + if (!calm && (world_rand(5) == 0)) { + now += world_rand(11); // preempted for a while + } + trace("tick %u\n", now); + return now; +} + +void vTaskSuspendAll(void) +{ + world_suspended++; + trace("suspend\n"); +} + +BaseType_t xTaskResumeAll(void) +{ + world_suspended--; + trace("resume\n"); + return pdFALSE; +} + +void vTaskDelay(TickType_t ticks) +{ + now += ticks; + trace("delay %u\n", ticks); +} + +BaseType_t xQueueReceive(QueueHandle_t q, void *item, TickType_t ticks) +{ + trace("receive %u", ticks); + if (q != (QueueHandle_t)&queue) { + trace(" wrong queue\n"); + return pdFALSE; + } + if (queue.empty() && (ticks > 0)) { + if (calm) { + if (!calm_delivered) { + calm_delivered = true; + now += 1; + isr_deliver(); + } else { + now += ticks; + } + } else if (world_rand(10) < 6) { + TickType_t delay = world_rand(ticks); + now += delay; + if (world_rand(10) == 0) { + uart.generation++; + trace(" reset"); + } + int burst = 1 + world_rand((world_rand(4) == 0) ? 6 : 3); // more than the queue holds, now and then + for (int i = 0; i < burst; i++) { + isr_deliver(); + } + if (queue.empty()) { + now += ticks - delay; // nothing came through; wait it out + } + } else { + now += ticks; + } + } + if (queue.empty()) { + trace(" -> none\n"); + return pdFALSE; + } + *(dedicated_reply_t *)item = queue.front(); + queue.pop_front(); + trace(" -> b%x\n", ((dedicated_reply_t *)item)->buf->bufnr); + return pdTRUE; +} + +BaseType_t DmaUART::GetBuffer(command_buf_t **buf, TickType_t ticks) +{ + trace("getbuffer %u", ticks); + if (world_no_buffer || (!calm && (world_rand(100) < 5))) { + now += ticks; + trace(" -> none\n"); + return pdFALSE; + } + tx_buf.size = 0; + tx_buf.dropped = 0; + *buf = &tx_buf; + trace(" -> b%x\n", tx_buf.bufnr); + return pdTRUE; +} + +BaseType_t DmaUART::TransmitPacket(command_buf_t *buf, uint16_t *ms) +{ + trace("transmit %d:", buf->size); + for (int i = 0; (i < buf->size) && (i < CMD_BUF_SIZE); i++) { + trace(" %02x", buf->data[i]); + } + if (world_no_transmit || (!calm && (world_rand(100) < 5))) { + trace(" -> failed\n"); + return pdFALSE; // the real one frees the buffer itself + } + trace("\n"); + world_transmits++; + memcpy(last_tx, buf->data, CMD_BUF_SIZE); + last_tx_size = buf->size; + // Late replies to earlier requests, or even this one, before the wait. + if (!calm && (world_rand(100) < 15)) { + int burst = 1 + world_rand(2); + for (int i = 0; i < burst; i++) { + isr_deliver(); + } + } + return pdTRUE; +} + +BaseType_t DmaUART::FreeBuffer(command_buf_t *buf) +{ + world_frees++; + if (!world_suspended) { + world_free_unsuspended++; + } + trace("free b%x%s\n", buf->bufnr, world_suspended ? "" : " (not suspended)"); + return pdTRUE; +} + +void world_enter_safe(void) +{ + trace("enter\n"); +} + +void world_leave_safe(void) +{ + trace("leave\n"); +} + +int world_printf(const char *fmt, ...) +{ + char line[256]; + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(line, sizeof(line), fmt, ap); + va_end(ap); + world_trace += "print: "; + world_trace += line; + return n; +} + +bool wifi_module_ready(void) +{ + return world_ready; +} diff --git a/software/test/wifi_tls/world.h b/software/test/wifi_tls/world.h new file mode 100644 index 000000000..6de8196a7 --- /dev/null +++ b/software/test/wifi_tls/world.h @@ -0,0 +1,34 @@ +// The scripted world the host tests run wifi_dedicated.cc in: module replies, receive interrupt, tick, buffer pool and +// resets. Every decision comes from one generator, so two implementations that make the same calls in the same +// order see the same world; they are compared on the trace of those calls. +#ifndef WORLD_H_ +#define WORLD_H_ + +#include +#include "wifi_cmd.h" + +// Builds a reply of the given kind into rx, as an answer to the last request +// sent (req, req_size; req_size is -1 when nothing has been sent). kind 0 is +// the right answer; the others are up to the maker. +typedef void (*world_maker_t)(command_buf_t *rx, const uint8_t *req, int req_size, int kind); + +// Starts a new world from seed. With calm set nothing fails and the first +// wait delivers exactly one right answer. +void world_reset(uint32_t seed, world_maker_t maker, bool calm); +uint32_t world_rand(uint32_t n); + +extern bool world_ready; // what wifi_module_ready answers +extern bool world_no_buffer; // GetBuffer fails, even when calm +extern bool world_no_transmit; // TransmitPacket fails, even when calm +extern std::string world_trace; // every call, in order +extern int world_suspended; // vTaskSuspendAll minus xTaskResumeAll +extern int world_transmits; // requests that went out +extern int world_isr_calls; // replies the interrupt handled +extern int world_frees; // FreeBuffer calls +extern int world_free_unsuspended; // of those, made with the scheduler not suspended +extern bool world_stale_next; // the next reply the interrupt queues is tagged with a pre-reset generation +size_t world_queued(void); // replies still in dedicated_replies +void world_deliver_now(void); // the receive interrupt hands over an answer now +void world_reset_maker(world_maker_t maker); // answers from now on come from maker + +#endif /* WORLD_H_ */ diff --git a/software/u64ctrl/CMakeLists.txt b/software/u64ctrl/CMakeLists.txt index 139b3260c..5b32e4f2b 100755 --- a/software/u64ctrl/CMakeLists.txt +++ b/software/u64ctrl/CMakeLists.txt @@ -3,5 +3,8 @@ cmake_minimum_required(VERSION 3.16) include($ENV{IDF_PATH}/tools/cmake/project.cmake) +if(IDF_VERSION_MAJOR LESS 6) + message(FATAL_ERROR "u64ctrl needs ESP-IDF 6, not ${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR} (see software/u64ctrl/README.md)") +endif() project(u64ctrl) # target_add_binary_data(u64ctrl.elf "/home/gideon/proj/ult64/target/u64_artix/u64_artix.runs/impl_1/u64_mk2_artix.bit" BINARY) diff --git a/software/u64ctrl/README.md b/software/u64ctrl/README.md new file mode 100644 index 000000000..41d234b40 --- /dev/null +++ b/software/u64ctrl/README.md @@ -0,0 +1,22 @@ +# Control module firmware (u64ctrl) + +The ESP32-S3 module of the Ultimate 64 Elite II and the C64 Ultimate: WiFi, power and button control. + +## Building + +The module needs ESP-IDF 6 (CI uses v6.1.1); `CMakeLists.txt` stops an older one at configure. +`docker/Dockerfile` still installs ESP-IDF 5.3.1, so CI builds this project (and raw_u64 and raw_c3) in +`espressif/idf:v6.1.1`, pinned by digest in `.github/workflows/build.yml`. Locally, from the top of +the repository, the same way as CI: + + docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -v "$PWD":/project -w /project/software/u64ctrl \ + espressif/idf:v6.1.1@sha256:2b4f966c37eaedc19542b0637a5f850b2eff9478d8e858192aa0073d92c2dc91 idf.py build + +then `make u64ii_no_esp` packs `build/u64ctrl.bin` into the update files. `make esp32_u64ctrl` and +`make u64ii` work only where `IDF_PATH` is an ESP-IDF 6. Once `build/` exists here, `make clean` also +needs ESP-IDF 6; otherwise delete `software/u64ctrl/build` by hand. + +`software/io/uart/cmd_buffer.c` is compiled into all three ESP32 projects (raw_u64, raw_c3 and u64ctrl). + +`sdkconfig` marks values that follow ESP-IDF's defaults with `# default:`; a reconfigure on a newer +ESP-IDF takes its new defaults there. After any ESP-IDF update, diff the values, not just the build. diff --git a/software/u64ctrl/ca/README.md b/software/u64ctrl/ca/README.md index a2fca83b3..7dda82ae6 100644 --- a/software/u64ctrl/ca/README.md +++ b/software/u64ctrl/ca/README.md @@ -1,4 +1,4 @@ -# Root list for u64ctrl's network recovery +# Root list for u64ctrl's network recovery and the raw_u64 module's TLS `cacert.pem` is curl's copy of Mozilla's root list of 2026-11-05 (112 roots) without the roots in `REMOVED` (see below); its sha256 is pinned in `tests/lib/u64ctrl_ca_test.py` (`CACERT_SHA256`). u64ctrl's recovery trusts it @@ -36,7 +36,8 @@ unless the hash matches, the file is not older than the committed one, the file including ISRG Root X1 and X2 and none in `REMOVED`, and both recovery servers verify against it. Then it replaces `cacert.pem`, updates `CACERT_SHA256` and the date above, and prints the roots added and removed. Review that output, add the removed roots to `REMOVED` in `tests/lib/u64ctrl_ca_test.py`, run that test (again after a firmware build), -and bump `IDENT_MINOR` in `main/rpc_dispatch.h`. The test also fails when the list is more than a year old +and bump `IDENT_MINOR` in `main/rpc_dispatch.h` and in `software/wifi/raw_u64/main/rpc_dispatch.h`, which builds +its bundle from the same file. The test also fails when the list is more than a year old (`MAX_AGE_DAYS`), without needing the network. If the test fails only because the list is older than `MAX_AGE_DAYS` and `refresh.py` says "no change", Mozilla's data diff --git a/software/u64ctrl/main/CMakeLists.txt b/software/u64ctrl/main/CMakeLists.txt index 63e55f4f8..b62a94ecd 100755 --- a/software/u64ctrl/main/CMakeLists.txt +++ b/software/u64ctrl/main/CMakeLists.txt @@ -1,3 +1,5 @@ set(EXTERNAL "../../io/uart") -idf_component_register(SRCS "button_handler.c" "control_main.c" "my_uart.c" "dump_hex.c" "rpc_dispatch.c" "wifi_modem.c" "button_handler.c" "jtag.c" "sntp.c" "power_state.c" "wol_magic.c" "recovery_manifest.c" "recovery_verify.c" "recovery_image.c" "recovery_url.c" "recovery.c" "recovery_trust.c" ${EXTERNAL}/cmd_buffer.c - INCLUDE_DIRS "." ${EXTERNAL}) +set(COMMON "../../wifi/common") +idf_component_register(SRCS "button_handler.c" "control_main.c" "my_uart.c" "dump_hex.c" "rpc_dispatch.c" "wifi_modem.c" "button_handler.c" "jtag.c" "sntp.c" "power_state.c" "wol_magic.c" "recovery_manifest.c" "recovery_verify.c" "recovery_image.c" "recovery_url.c" "recovery.c" "recovery_trust.c" ${EXTERNAL}/cmd_buffer.c ${COMMON}/wifi_radio.c ${COMMON}/wifi_radio_esp.c ${COMMON}/radio_entropy.c ${COMMON}/radio_entropy_esp.c + INCLUDE_DIRS "." ${EXTERNAL} ${COMMON} + LDFRAGMENTS "linker.lf") diff --git a/software/u64ctrl/main/button_handler.c b/software/u64ctrl/main/button_handler.c index 6d60fbb41..78254709f 100644 --- a/software/u64ctrl/main/button_handler.c +++ b/software/u64ctrl/main/button_handler.c @@ -7,6 +7,7 @@ #include "esp_err.h" #include "pinout.h" #include "button_handler.h" +#include "my_uart.h" #include "rpc_dispatch.h" #include "jtag.h" #include "wifi_modem.h" @@ -58,7 +59,7 @@ static void regulator_enable(int enable, int delay) vTaskDelay(100 / portTICK_PERIOD_MS); if (enable) { - ESP_ERROR_CHECK( uart_set_pin(UART_NUM_1, IO_UART_TXD, IO_UART_RXD, IO_UART_RTS, IO_UART_CTS)); + my_uart_connect_pins(); } } diff --git a/software/u64ctrl/main/control_main.c b/software/u64ctrl/main/control_main.c index 6bd49fc40..eb4168053 100755 --- a/software/u64ctrl/main/control_main.c +++ b/software/u64ctrl/main/control_main.c @@ -23,6 +23,7 @@ #include "jtag.h" #include "sntp.h" #include "power_state.h" +#include "radio_entropy.h" #include "recovery.h" static const char *TAG = "u64ctrl"; @@ -97,7 +98,6 @@ static bool adc_calibration_init(adc_unit_t unit, adc_channel_t channel, adc_att } static adc_oneshot_unit_handle_t adc1_handle; -static SemaphoreHandle_t adc_lock = NULL; static adc_cali_handle_t adc1_cali_handle[7] = { 0 }; static void configure_adc(void) @@ -121,8 +121,6 @@ static void configure_adc(void) for(int i=0;i<7;i++) { adc_calibration_init(ADC_UNIT_1, ADC_CHANNEL_0+i, ADC_ATTEN_DB_12, &adc1_cali_handle[i]); } - - adc_lock = xSemaphoreCreateMutex(); } const int adc_scale[7] = { SCALE_VBUS, SCALE_VAUX, SCALE_V50, SCALE_V33, SCALE_V18, SCALE_V10, SCALE_VUSB }; @@ -139,28 +137,39 @@ static uint16_t adc_data_local[7]; // } // } -esp_err_t read_adc_channels(uint16_t *adc_data) +// The last voltages that were read, for a read that cannot get the ADC in time +static uint16_t adc_cache[7]; +static bool adc_cache_valid; + +// With the gate held exclusively, which is what keeps others off the unit +static int read_adc_unit(uint16_t *adc_data) { int adc_raw, voltage; esp_err_t ret = ESP_OK; - xSemaphoreTake(adc_lock, portMAX_DELAY); for(int i=0;i<7;i++) { ret = adc_oneshot_read(adc1_handle, ADC_CHANNEL_0+i, &adc_raw); if (ret != ESP_OK) { - xSemaphoreGive(adc_lock); return ret; } ret = adc_cali_raw_to_voltage(adc1_cali_handle[i], adc_raw, &voltage); if (ret != ESP_OK) { - xSemaphoreGive(adc_lock); return ret; } adc_data[i] = (voltage * adc_scale[i]) >> 16; } - xSemaphoreGive(adc_lock); return ESP_OK; } +// While the radio is off, the SAR ADC feeds the RNG, and a oneshot read takes ADC1 over +// from that source. So a read of the voltages takes the ADC for the length of the read, +// under the entropy gate. When it cannot get it in time it gives the values of the last +// read, never zeros; before there is a last read it waits for the ADC, and if that fails +// too it returns an error and leaves adc_data alone. +esp_err_t read_adc_channels(uint16_t *adc_data) +{ + return radio_entropy_read_adc(adc_data, adc_cache, &adc_cache_valid, 7, read_adc_unit); +} + void setup_modem(); void show_buffer_status(); @@ -200,6 +209,7 @@ void app_main(void) while (1) { read_adc_channels(adc_data_local); + radio_entropy_poll(); ESP_LOGI(TAG, "App Main Alive; 5V_GOOD: %d (Initial: %d). VBus = %d mV", gpio_get_level(IO_5V_GOOD), initial_state, adc_data_local[0]); // show_buffer_status(); if (recovery_owns_leds()) { diff --git a/software/u64ctrl/main/linker.lf b/software/u64ctrl/main/linker.lf new file mode 100644 index 000000000..22e104b6f --- /dev/null +++ b/software/u64ctrl/main/linker.lf @@ -0,0 +1,42 @@ +[mapping:u64ctrl_hot] +archive: libmain.a +entries: + my_uart (noflash) + cmd_buffer (noflash) + wifi_modem:hacked_recv (noflash) + rpc_dispatch:dispatch (noflash) + rpc_dispatch:cmd_send_eth_packet (noflash) + +[mapping:u64ctrl_netif] +archive: libesp_netif.a +entries: + esp_netif_lwip:esp_netif_transmit (noflash) + esp_netif_lwip:esp_netif_receive (noflash) + esp_netif_lwip:esp_netif_free_rx_buffer (noflash) + wlanif:wlanif_input (noflash) + esp_pbuf_ref:esp_pbuf_allocate (noflash) + esp_pbuf_ref:esp_pbuf_free (noflash) + +[mapping:u64ctrl_wifi_netif] +archive: libesp_wifi.a +entries: + wifi_netif:wifi_transmit (noflash) + wifi_netif:wifi_free (noflash) + +[mapping:u64ctrl_pp] +archive: libpp.a +entries: + if_hwctrl:esp_wifi_internal_free_rx_buffer (noflash) + +[mapping:u64ctrl_lwip] +archive: liblwip.a +entries: + pbuf:pbuf_free (noflash) + pbuf:pbuf_alloced_custom (noflash) + pbuf:pbuf_init_alloced_pbuf (noflash) + mem:mem_malloc (noflash) + mem:mem_free (noflash) + sys_arch:sys_arch_protect (noflash) + sys_arch:sys_arch_unprotect (noflash) + sys_arch:sys_mutex_lock (noflash) + sys_arch:sys_mutex_unlock (noflash) diff --git a/software/u64ctrl/main/my_uart.c b/software/u64ctrl/main/my_uart.c index b8c54fe1c..1a7f98d60 100644 --- a/software/u64ctrl/main/my_uart.c +++ b/software/u64ctrl/main/my_uart.c @@ -23,7 +23,7 @@ #include "freertos/ringbuf.h" #include "hal/uart_hal.h" #include "hal/gpio_hal.h" -#include "soc/uart_periph.h" +#include "hal/uart_periph.h" #include "soc/rtc_cntl_reg.h" #include "driver/uart.h" #include "driver/gpio.h" @@ -35,6 +35,9 @@ #include "rpc_dispatch.h" #include "dump_hex.h" #include "my_uart.h" +#include "pinout.h" +#include "esp_brownout.h" +#include "hal/uart_ll.h" #if CONFIG_IDF_TARGET_ESP32 #include "esp32/clk.h" @@ -368,7 +371,7 @@ BaseType_t my_uart_get_buffer(uint8_t uart_num, command_buf_t **buf, TickType_t } #include "esp_check.h" -esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, int intr_alloc_flags, uart_isr_handle_t *handle) +esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, int intr_alloc_flags, intr_handle_t *handle) { int ret; ESP_RETURN_ON_FALSE((uart_num < UART_NUM_MAX), ESP_FAIL, UART_TAG, "uart_num error"); @@ -378,6 +381,27 @@ esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, return ret; } +void my_uart_connect_pins(void) +{ + // ESP-IDF 5.3.1's uart_set_pin() put a pull-up on RX and CTS before connecting them, replacing + // the pull-downs left by check_fpga() and the power-off path; ESP-IDF 6 never touches pulls, so + // do it here, ahead of the routing, as 5.3.1 did. While the machine is off RX and CTS stay routed + // to UART1 and pulled down; a boot that stays off has the pull-ups on for about 100 ms, until + // regulator_enable(0), the same as on 5.3.1. + ESP_ERROR_CHECK( gpio_set_pull_mode(IO_UART_RXD, GPIO_PULLUP_ONLY) ); + ESP_ERROR_CHECK( gpio_set_pull_mode(IO_UART_CTS, GPIO_PULLUP_ONLY) ); + ESP_ERROR_CHECK( uart_set_pin(UART_NUM_1, IO_UART_TXD, IO_UART_RXD, IO_UART_RTS, IO_UART_CTS) ); +} + +// ESP-IDF 6's brownout interrupt waits for every enabled UART's transmitter to drain before it resets +// (5.3.1 reset at once). With CTS held high by its pull-up, because the FPGA lost power with the +// machine, bytes in the UART1 FIFO would never leave and the wait would last until the interrupt +// watchdog. Runs in the brownout ISR, ahead of that wait: stop honouring CTS so the FIFO drains. +static IRAM_ATTR void uart1_brownout_callback(void) +{ + uart_ll_set_hw_flow_ctrl(UART_LL_GET_HW(UART_NUM_1), UART_HW_FLOWCTRL_DISABLE, 0); +} + esp_err_t my_uart_init(command_buf_context_t *buffers, uint8_t uart_num) { UART_CHECK((uart_num < UART_NUM_MAX), "uart_num error", ESP_FAIL); @@ -395,8 +419,8 @@ esp_err_t my_uart_init(command_buf_context_t *buffers, uint8_t uart_num) const uart_intr_config_t interrupt_config = { .intr_enable_mask = UART_INTR_RXFIFO_TOUT | UART_INTR_RXFIFO_FULL, .rx_timeout_thresh = 2, - .txfifo_empty_intr_thresh = 10, - .rxfifo_full_thresh = 120, + .txfifo_empty_intr_thresh = 64, + .rxfifo_full_thresh = 64, }; const uart_config_t uart_config = { @@ -408,6 +432,12 @@ esp_err_t my_uart_init(command_buf_context_t *buffers, uint8_t uart_num) .rx_flow_ctrl_thresh = 122, }; + // Not worth stopping the boot over: without it a brownout resets after the interrupt watchdog. + esp_err_t bo = esp_brownout_register_callback(uart1_brownout_callback); + if (bo != ESP_OK) { + ESP_LOGW(UART_TAG, "brownout callback not registered: %s", esp_err_to_name(bo)); + } + // Configure UART parameters esp_err_t ret = uart_param_config(uart_num, &uart_config); if (ret == ESP_OK) { diff --git a/software/u64ctrl/main/my_uart.h b/software/u64ctrl/main/my_uart.h index 69b2da0e1..cc69f1fa9 100644 --- a/software/u64ctrl/main/my_uart.h +++ b/software/u64ctrl/main/my_uart.h @@ -17,6 +17,8 @@ #define UART_DEBUG_RX 0 #define UART_DEBUG_IRQ 0 +// Routes UART1 to the FPGA pins. Call it for every connection, so the RX and CTS idle levels are the same everywhere. +void my_uart_connect_pins(void); esp_err_t my_uart_init(command_buf_context_t *buffers, uint8_t uart_num); BaseType_t my_uart_get_buffer(uint8_t uart_num, command_buf_t **buf, TickType_t ticks); BaseType_t my_uart_transmit_packet(uint8_t uart_num, command_buf_t *buf); diff --git a/software/u64ctrl/main/recovery.c b/software/u64ctrl/main/recovery.c index 1100aa644..a9b5bf983 100644 --- a/software/u64ctrl/main/recovery.c +++ b/software/u64ctrl/main/recovery.c @@ -18,7 +18,6 @@ #include "esp_http_client.h" #include "esp_log.h" #include "esp_netif.h" -#include "mbedtls/sha256.h" #include "nvs.h" #include "button_handler.h" #include "jtag.h" @@ -27,6 +26,7 @@ #include "recovery_image.h" #include "recovery_manifest.h" #include "recovery_url.h" +#include "recovery_verify.h" #include "rpc_dispatch.h" static const char *TAG = "recovery"; @@ -322,9 +322,12 @@ static bool stream_file(const char *get_url, const recovery_file_t *file, sink_f return false; } - mbedtls_sha256_context sha; - mbedtls_sha256_init(&sha); - mbedtls_sha256_starts(&sha, 0); + recovery_hash_t sha; + if (recovery_hash_start(&sha) != RECOVERY_OK) { + ESP_LOGW(TAG, "%s: cannot start a hash", get_url); + close_client(client); + return false; + } uint32_t total = 0; uint32_t since_yield = 0; bool ok = true; @@ -345,7 +348,11 @@ static bool stream_file(const char *get_url, const recovery_file_t *file, sink_f ok = false; break; } - mbedtls_sha256_update(&sha, read_buf, n); + if (recovery_hash_update(&sha, read_buf, n) != RECOVERY_OK) { + ESP_LOGW(TAG, "%s: cannot hash", get_url); + ok = false; + break; + } ok = sink(ctx, total, read_buf, n); total += n; since_yield += n; @@ -356,19 +363,22 @@ static bool stream_file(const char *get_url, const recovery_file_t *file, sink_f } close_client(client); - uint8_t hash[32]; - mbedtls_sha256_finish(&sha, hash); - mbedtls_sha256_free(&sha); if (cancelled) { + recovery_hash_abort(&sha); return false; } if (ok && total != file->size) { ESP_LOGW(TAG, "%s: %lu bytes, its manifest says %lu", get_url, (unsigned long)total, (unsigned long)file->size); ok = false; } - if (ok && memcmp(hash, file->sha256, sizeof(hash)) != 0) { - ESP_LOGW(TAG, "%s: hash differs from its manifest", get_url); - ok = false; + if (ok) { + recovery_result_t r = recovery_hash_finish(&sha, file); + if (r != RECOVERY_OK) { + ESP_LOGW(TAG, "%s: %s", get_url, r == RECOVERY_ERR_HASH_MISMATCH ? "hash differs from its manifest" : recovery_result_name(r)); + ok = false; + } + } else { + recovery_hash_abort(&sha); } if (ok) { uint32_t ms = (xTaskGetTickCount() - started) * portTICK_PERIOD_MS; diff --git a/software/u64ctrl/main/recovery_manifest.c b/software/u64ctrl/main/recovery_manifest.c index 1016b0439..6fbfc82a9 100644 --- a/software/u64ctrl/main/recovery_manifest.c +++ b/software/u64ctrl/main/recovery_manifest.c @@ -24,6 +24,8 @@ const char *recovery_result_name(recovery_result_t result) case RECOVERY_ERR_DUPLICATE_KEY: return "duplicate key"; case RECOVERY_ERR_MISSING_KEY: return "missing key"; case RECOVERY_ERR_BAD_VALUE: return "bad value"; + case RECOVERY_ERR_CRYPTO: return "crypto library failed"; + case RECOVERY_ERR_HASH_MISMATCH: return "hash differs"; } return "unknown result"; } diff --git a/software/u64ctrl/main/recovery_manifest.h b/software/u64ctrl/main/recovery_manifest.h index bb4b177ef..6a59152a0 100644 --- a/software/u64ctrl/main/recovery_manifest.h +++ b/software/u64ctrl/main/recovery_manifest.h @@ -32,7 +32,8 @@ * checks it, and only then does recovery_manifest_parse() read the signed text. * Only the split and the verify ever see unauthenticated input. * - * Everything but recovery_manifest_verify() is free of ESP-IDF and mbedtls. + * Everything but recovery_manifest_verify() is free of ESP-IDF and the crypto + * library; recovery_verify.h has the hashing of the files the manifest names. */ #ifndef SOFTWARE_U64CTRL_MAIN_RECOVERY_MANIFEST_H_ @@ -63,6 +64,8 @@ typedef enum { RECOVERY_ERR_DUPLICATE_KEY, RECOVERY_ERR_MISSING_KEY, RECOVERY_ERR_BAD_VALUE, + RECOVERY_ERR_CRYPTO, // the crypto library would not start or hash + RECOVERY_ERR_HASH_MISMATCH, // a downloaded file is not the one the manifest names } recovery_result_t; typedef struct { diff --git a/software/u64ctrl/main/recovery_verify.c b/software/u64ctrl/main/recovery_verify.c index 071e1c322..81247f5aa 100644 --- a/software/u64ctrl/main/recovery_verify.c +++ b/software/u64ctrl/main/recovery_verify.c @@ -8,11 +8,9 @@ #include #include "mbedtls/base64.h" #include "mbedtls/pk.h" -#include "mbedtls/sha256.h" -#if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" -#endif #include "recovery_manifest.h" +#include "recovery_verify.h" static bool verify_with_key(const char *key_pem, const uint8_t *hash, const uint8_t *sig, size_t sig_len) { @@ -20,7 +18,7 @@ static bool verify_with_key(const char *key_pem, const uint8_t *hash, const uint mbedtls_pk_init(&pk); // The PEM parser wants the terminating NUL counted in the length. bool ok = mbedtls_pk_parse_public_key(&pk, (const unsigned char *)key_pem, strlen(key_pem) + 1) == 0 && - mbedtls_pk_get_type(&pk) == MBEDTLS_PK_ECKEY && + PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(mbedtls_pk_get_key_type(&pk)) && mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, hash, 32, sig, sig_len) == 0; mbedtls_pk_free(&pk); return ok; @@ -36,16 +34,16 @@ recovery_result_t recovery_manifest_verify(const char *text, const recovery_sign return RECOVERY_ERR_BAD_SIGNATURE; } -#if defined(MBEDTLS_USE_PSA_CRYPTO) - // pk verifies through PSA in this configuration; repeated calls are harmless. + // pk and the hash both go through PSA; repeated calls are harmless. if (psa_crypto_init() != PSA_SUCCESS) { - return RECOVERY_ERR_BAD_SIGNATURE; + return RECOVERY_ERR_CRYPTO; } -#endif uint8_t hash[32]; - if (mbedtls_sha256((const unsigned char *)text, sig->signed_len, hash, 0) != 0) { - return RECOVERY_ERR_BAD_SIGNATURE; + size_t hash_len = 0; + if (psa_hash_compute(PSA_ALG_SHA_256, (const uint8_t *)text, sig->signed_len, hash, sizeof(hash), + &hash_len) != PSA_SUCCESS || hash_len != sizeof(hash)) { + return RECOVERY_ERR_CRYPTO; } for (int i = 0; i < n_keys; i++) { if (verify_with_key(keys_pem[i], hash, der, der_len)) { @@ -54,3 +52,37 @@ recovery_result_t recovery_manifest_verify(const char *text, const recovery_sign } return RECOVERY_ERR_BAD_SIGNATURE; } + +recovery_result_t recovery_hash_start(recovery_hash_t *h) +{ + h->op = (psa_hash_operation_t)PSA_HASH_OPERATION_INIT; + if (psa_crypto_init() != PSA_SUCCESS || psa_hash_setup(&h->op, PSA_ALG_SHA_256) != PSA_SUCCESS) { + return RECOVERY_ERR_CRYPTO; + } + return RECOVERY_OK; +} + +recovery_result_t recovery_hash_update(recovery_hash_t *h, const uint8_t *data, size_t len) +{ + if (psa_hash_update(&h->op, data, len) != PSA_SUCCESS) { + psa_hash_abort(&h->op); + return RECOVERY_ERR_CRYPTO; + } + return RECOVERY_OK; +} + +recovery_result_t recovery_hash_finish(recovery_hash_t *h, const recovery_file_t *expected) +{ + uint8_t hash[32]; + size_t hash_len = 0; + if (psa_hash_finish(&h->op, hash, sizeof(hash), &hash_len) != PSA_SUCCESS || hash_len != sizeof(hash)) { + psa_hash_abort(&h->op); + return RECOVERY_ERR_CRYPTO; + } + return memcmp(hash, expected->sha256, sizeof(hash)) == 0 ? RECOVERY_OK : RECOVERY_ERR_HASH_MISMATCH; +} + +void recovery_hash_abort(recovery_hash_t *h) +{ + psa_hash_abort(&h->op); +} diff --git a/software/u64ctrl/main/recovery_verify.h b/software/u64ctrl/main/recovery_verify.h new file mode 100644 index 000000000..1dada90c9 --- /dev/null +++ b/software/u64ctrl/main/recovery_verify.h @@ -0,0 +1,40 @@ +/* + * recovery_verify.h + * + * What the recovery needs from the crypto library: the signature check of + * recovery_manifest.h, and the SHA-256 of a downloaded file checked against + * the manifest entry for it. Both are built on PSA Crypto (mbedTLS 4), and both + * start it themselves, so neither depends on who initialised it first. + * + * Unlike recovery_manifest.h this needs the crypto library's headers, so + * only the files that hash include it. + */ + +#ifndef SOFTWARE_U64CTRL_MAIN_RECOVERY_VERIFY_H_ +#define SOFTWARE_U64CTRL_MAIN_RECOVERY_VERIFY_H_ + +#include "psa/crypto.h" +#include "recovery_manifest.h" + +typedef struct { + psa_hash_operation_t op; +} recovery_hash_t; + +/* Starts hashing a file. RECOVERY_ERR_CRYPTO when the crypto library will not + start or will not hash. */ +recovery_result_t recovery_hash_start(recovery_hash_t *h); + +/* Adds the next `len` bytes of the file. RECOVERY_ERR_CRYPTO on a failure, + which ends the hash. */ +recovery_result_t recovery_hash_update(recovery_hash_t *h, const uint8_t *data, size_t len); + +/* Ends the hash and compares it with the manifest's. RECOVERY_OK when they are + equal, RECOVERY_ERR_HASH_MISMATCH when they differ, RECOVERY_ERR_CRYPTO on a + failure. Either way the hash is over. */ +recovery_result_t recovery_hash_finish(recovery_hash_t *h, const recovery_file_t *expected); + +/* Ends a hash that is not going to be finished, e.g. a download that failed. + Harmless on a hash that is already over. */ +void recovery_hash_abort(recovery_hash_t *h); + +#endif /* SOFTWARE_U64CTRL_MAIN_RECOVERY_VERIFY_H_ */ diff --git a/software/u64ctrl/main/rpc_calls.h b/software/u64ctrl/main/rpc_calls.h index bf1947aab..672d6454a 100644 --- a/software/u64ctrl/main/rpc_calls.h +++ b/software/u64ctrl/main/rpc_calls.h @@ -20,6 +20,8 @@ typedef struct { uint16_t sequence; } rpc_header_t; +#include "rpc_shared.h" + typedef struct { rpc_header_t hdr; int esp_err; // to be casted to esp_err_t @@ -234,6 +236,7 @@ typedef struct { #define CMD_GET_WAKE_ON_WIFI 0x19 #define CMD_SET_RECOVERY_URL 0x1A #define CMD_GET_RECOVERY_URL 0x1B +// 0x20 is CMD_GET_RANDOM, in rpc_shared.h #define EVENT_CONNECTED 0x40 #define EVENT_GOTIP 0x41 diff --git a/software/u64ctrl/main/rpc_dispatch.c b/software/u64ctrl/main/rpc_dispatch.c index 59ae75946..4623bd2e0 100644 --- a/software/u64ctrl/main/rpc_dispatch.c +++ b/software/u64ctrl/main/rpc_dispatch.c @@ -15,6 +15,7 @@ #include "nvs_flash.h" #include "power_state.h" #include "driver/uart.h" +#include "esp_random.h" #include "rpc_calls.h" #include "rpc_dispatch.h" #include "my_uart.h" @@ -246,11 +247,10 @@ void cmd_wifi_endisable(command_buf_t *buf) void cmd_get_voltages(command_buf_t *buf) { - extern esp_err_t read_adc_channels(uint16_t *adc_data); - rpc_get_voltages_resp *resp = (rpc_get_voltages_resp *)buf->data; - resp->esp_err = ESP_OK; - read_adc_channels(&(resp->vbus)); + // The answer overlays the request: an error must not carry what was in the buffer + memset(&resp->vbus, 0, sizeof(rpc_get_voltages_resp) - offsetof(rpc_get_voltages_resp, vbus)); + resp->esp_err = read_adc_channels(&(resp->vbus)); ESP_LOGI(TAG, "Vbus = %d, Vaux = %d, V50 = %d, V33 = %d, V18 = %d, V10 = %d, Vusb = %d", resp->vbus, resp->vaux, resp->v50, resp->v33, resp->v18, resp->v10, resp->vusb); buf->size = sizeof(rpc_get_voltages_resp); my_uart_transmit_packet(UART_CHAN, buf); @@ -410,6 +410,15 @@ void cmd_get_recovery_url(command_buf_t *buf) my_uart_transmit_packet(UART_CHAN, buf); } +_Static_assert(RPC_ERR_ENTROPY_BUSY == ESP_ERR_TIMEOUT, "RPC_ERR_ENTROPY_BUSY is an esp_err_t"); + +void cmd_get_random(command_buf_t *buf) +{ + buf->size = radio_entropy_serve_get_random(buf->data, buf->size, (void (*)(void *, size_t))esp_fill_random); + // The gate is released: the answer is sent without it + my_uart_transmit_packet(UART_CHAN, buf); +} + void cmd_not_implemented(command_buf_t *buf) { rpc_espcmd_resp *resp = (rpc_espcmd_resp *)buf->data; @@ -549,6 +558,9 @@ void dispatch(void *ct) case CMD_GET_RECOVERY_URL: cmd_get_recovery_url(pbuffer); break; + case CMD_GET_RANDOM: + cmd_get_random(pbuffer); + break; default: cmd_not_implemented(pbuffer); break; @@ -558,7 +570,8 @@ void dispatch(void *ct) void start_dispatch(QueueHandle_t queue) { - xTaskCreate( dispatch, "Dispatch Task", DISPATCHER_STACK, queue, tskIDLE_PRIORITY + 1, NULL ); + // Core 1, above the system tasks: the UART ISR that feeds this queue runs on core 1 too + xTaskCreatePinnedToCore( dispatch, "Dispatch Task", DISPATCHER_STACK, queue, 19, NULL, 1 ); } #if MULTITHREADED diff --git a/software/u64ctrl/main/rpc_dispatch.h b/software/u64ctrl/main/rpc_dispatch.h index 4e4f877ce..f1965dbf5 100644 --- a/software/u64ctrl/main/rpc_dispatch.h +++ b/software/u64ctrl/main/rpc_dispatch.h @@ -26,8 +26,14 @@ void start_dispatch(QueueHandle_t queue); void send_button_event(uint8_t button); void send_keepalive(); -#define IDENT_STRING "ESP32 WiFi Bridge V1.30" +#define IDENT_STRING "ESP32 WiFi Bridge V1.33" #define IDENT_MAJOR 1 +// 1.33: the recovery's root list drops the roots NSS master has deleted, no longer trusts +// for websites or distrusts for every certificate still valid (Buypass Class 2 and 3, +// QuoVadis Root CA 1 and 3 G3, Certigna Root CA, Izenpe.com). +// 1.32: CMD_GET_RANDOM, served with the radio off too, from the SAR ADC source; starts and +// stops the radio through the code it shares with the U64 module. +// 1.31: built with ESP-IDF 6.1.1; the recovery code uses PSA Crypto (mbedTLS 4). // 1.30: the recovery's root list drops the roots NSS master has deleted, no longer trusts // for websites or distrusts for every certificate still valid (Buypass Class 2 and 3, // QuoVadis Root CA 1 and 3 G3, Certigna Root CA, Izenpe.com). @@ -53,7 +59,7 @@ void send_keepalive(); // when this is higher than what the module reports, so a module change that // does not bump it is silently never installed, and an older release never // replaces a newer module. -#define IDENT_MINOR 30 +#define IDENT_MINOR 33 #define MULTITHREADED 0 #define DISPATCHER_STACK 3072 diff --git a/software/u64ctrl/main/wifi_modem.c b/software/u64ctrl/main/wifi_modem.c index 5733ae7b8..9e8ce10bf 100644 --- a/software/u64ctrl/main/wifi_modem.c +++ b/software/u64ctrl/main/wifi_modem.c @@ -33,6 +33,7 @@ #include "button_handler.h" #include "wol_magic.h" #include "recovery.h" +#include "wifi_radio.h" #define NET_CMD_BUFSIZE 512 @@ -125,7 +126,8 @@ static err_t hacked_recv(struct pbuf *p, struct netif *inp) return ERR_OK; } else { ESP_LOGW(TAG, "No buffer to send packet."); - return ERR_BUF; + pbuf_free(p); // dropped, and reported as handled + return ERR_OK; } } else { // dropped, wrong mac and no broadcast pbuf_free(p); @@ -368,7 +370,7 @@ static void wifi_init() ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE)); - ESP_ERROR_CHECK(esp_wifi_start()); + ESP_ERROR_CHECK(radio_start()); ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, @@ -787,7 +789,7 @@ esp_err_t enable_wifi_if_needed(ConnectState_t state) if (state == Disabled) { ESP_LOGI(TAG, "Starting WiFi."); xQueueReset(connect_events); // nothing from before the start applies - esp_err_t err = esp_wifi_start(); + esp_err_t err = radio_start(); if (err == ESP_OK) { send_event(EVENT_DISCONNECTED, 0); disabled_g = 0; @@ -818,7 +820,7 @@ int handle_connect_command(ConnectCommand_t *cmd, ConnectState_t *state) } } ESP_LOGI(TAG, "Stopping WiFi."); - err = esp_wifi_stop(); + err = radio_stop(); if (err == ESP_OK) { // What the radio reported before it stopped does not apply to the next // start. The event of the stop itself can come after this, so every @@ -839,7 +841,7 @@ int handle_connect_command(ConnectCommand_t *cmd, ConnectState_t *state) user_disconnected = false; ESP_LOGI(TAG, "Starting WiFi."); xQueueReset(connect_events); // nothing from before the start applies - err = esp_wifi_start(); + err = radio_start(); if (err == ESP_OK) { send_event(EVENT_DISCONNECTED, 0); *state = LastAP; @@ -1098,6 +1100,18 @@ static void start_connector() xTaskCreate(connect_thread, "Connector", 4096, NULL, tskIDLE_PRIORITY + 1, NULL); } +static SemaphoreHandle_t uart_init_done; +static esp_err_t uart_init_result; + +// esp_intr_alloc() binds the interrupt to the core it is called on. The UART ISR must not share +// core 0 with the WiFi task, so the init runs on core 1. +static void uart_init_task(void *a) +{ + uart_init_result = my_uart_init(&work_buffers, UART_NUM_1); + xSemaphoreGive(uart_init_done); + vTaskDelete(NULL); +} + void setup_modem() { // Initialize NVS @@ -1122,17 +1136,28 @@ void setup_modem() #endif ESP_LOGI(TAG, "my_uart_init..."); // Now install the driver for UART1. We use our own buffer mechanism and interrupt routine - ESP_ERROR_CHECK(my_uart_init(&work_buffers, UART_NUM_1)); + uart_init_done = xSemaphoreCreateBinary(); + ESP_ERROR_CHECK(uart_init_done ? ESP_OK : ESP_ERR_NO_MEM); + ESP_ERROR_CHECK(xTaskCreatePinnedToCore(uart_init_task, "uart_init", 3072, NULL, tskIDLE_PRIORITY + 2, NULL, 1) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM); + xSemaphoreTake(uart_init_done, portMAX_DELAY); + ESP_ERROR_CHECK(uart_init_result); ESP_LOGI(TAG, "wifi_init..."); wifi_init(); + radio_entropy_init(); + // The first read of the voltages, so that a later one that cannot get the ADC has + // values to give + uint16_t seed_voltages[7]; + if (read_adc_channels(seed_voltages) != ESP_OK) { + ESP_LOGW(TAG, "No first read of the voltages"); + } ESP_LOGI(TAG, "start wifi connector..."); start_connector(); ESP_LOGI(TAG, "dispatch... switching UART pins!"); vTaskDelay(100 / portTICK_PERIOD_MS); ESP_ERROR_CHECK( uart_set_pin(UART_NUM_0, 0, -1, -1, -1)); - ESP_ERROR_CHECK( uart_set_pin(UART_NUM_1, IO_UART_TXD, IO_UART_RXD, IO_UART_RTS, IO_UART_CTS)); + my_uart_connect_pins(); start_dispatch(work_buffers.receivedQueue); } diff --git a/software/u64ctrl/main/wifi_modem.h b/software/u64ctrl/main/wifi_modem.h index d978e80d6..5615aabcf 100644 --- a/software/u64ctrl/main/wifi_modem.h +++ b/software/u64ctrl/main/wifi_modem.h @@ -2,6 +2,7 @@ #define WIFI_MODEM_H #include "rpc_calls.h" +#include "radio_entropy.h" extern QueueHandle_t connect_commands; extern SemaphoreHandle_t connect_semaphore; @@ -31,6 +32,7 @@ void wake_on_wifi_update(int machine_on); uint8_t wifi_get_connection(); void wifi_send_connected_event(); +esp_err_t read_adc_channels(uint16_t *adc_data); void show_buffer_status(); #endif diff --git a/software/u64ctrl/sdkconfig b/software/u64ctrl/sdkconfig index 690e00ced..dd2d57b11 100644 --- a/software/u64ctrl/sdkconfig +++ b/software/u64ctrl/sdkconfig @@ -1,365 +1,636 @@ # # Automatically generated file. DO NOT EDIT. -# Espressif IoT Development Framework (ESP-IDF) 5.3.1 Project Configuration +# Espressif IoT Development Framework (ESP-IDF) 6.1.1 Project Configuration # -CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 -CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 +# default: CONFIG_SOC_ADC_SUPPORTED=y +# default: CONFIG_SOC_UART_SUPPORTED=y +# default: CONFIG_SOC_PCNT_SUPPORTED=y +# default: CONFIG_SOC_PHY_SUPPORTED=y +# default: CONFIG_SOC_WIFI_SUPPORTED=y +# default: CONFIG_SOC_TWAI_SUPPORTED=y +# default: CONFIG_SOC_GDMA_SUPPORTED=y +# default: +CONFIG_SOC_UHCI_SUPPORTED=y +# default: CONFIG_SOC_AHB_GDMA_SUPPORTED=y +# default: CONFIG_SOC_GPTIMER_SUPPORTED=y -CONFIG_SOC_LCDCAM_SUPPORTED=y +# default: +CONFIG_SOC_LCDCAM_CAM_SUPPORTED=y +# default: +CONFIG_SOC_LCDCAM_I80_LCD_SUPPORTED=y +# default: +CONFIG_SOC_LCDCAM_RGB_LCD_SUPPORTED=y +# default: +CONFIG_SOC_LCD_I80_SUPPORTED=y +# default: +CONFIG_SOC_LCD_RGB_SUPPORTED=y +# default: CONFIG_SOC_MCPWM_SUPPORTED=y +# default: CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y +# default: CONFIG_SOC_CACHE_SUPPORT_WRAP=y +# default: CONFIG_SOC_ULP_SUPPORTED=y +# default: CONFIG_SOC_ULP_FSM_SUPPORTED=y +# default: CONFIG_SOC_RISCV_COPROC_SUPPORTED=y +# default: CONFIG_SOC_BT_SUPPORTED=y +# default: CONFIG_SOC_USB_OTG_SUPPORTED=y +# default: +CONFIG_SOC_USB_DFU_SUPPORTED=y +# default: +CONFIG_SOC_USB_OTG_CONSOLE_SUPPORTED=y +# default: CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y +# default: CONFIG_SOC_CCOMP_TIMER_SUPPORTED=y +# default: CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y +# default: CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y +# default: CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y +# default: CONFIG_SOC_EFUSE_SUPPORTED=y +# default: CONFIG_SOC_SDMMC_HOST_SUPPORTED=y +# default: CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y +# default: CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED=y +# default: CONFIG_SOC_RTC_MEM_SUPPORTED=y +# default: +CONFIG_SOC_RTC_TIMER_SUPPORTED=y +# default: CONFIG_SOC_PSRAM_DMA_CAPABLE=y +# default: CONFIG_SOC_XT_WDT_SUPPORTED=y +# default: CONFIG_SOC_I2S_SUPPORTED=y +# default: CONFIG_SOC_RMT_SUPPORTED=y +# default: CONFIG_SOC_SDM_SUPPORTED=y +# default: CONFIG_SOC_GPSPI_SUPPORTED=y +# default: CONFIG_SOC_LEDC_SUPPORTED=y +# default: CONFIG_SOC_I2C_SUPPORTED=y +# default: CONFIG_SOC_SYSTIMER_SUPPORTED=y +# default: CONFIG_SOC_SUPPORT_COEXISTENCE=y +# default: CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y +# default: CONFIG_SOC_AES_SUPPORTED=y +# default: CONFIG_SOC_MPI_SUPPORTED=y +# default: CONFIG_SOC_SHA_SUPPORTED=y +# default: CONFIG_SOC_HMAC_SUPPORTED=y +# default: CONFIG_SOC_DIG_SIGN_SUPPORTED=y +# default: CONFIG_SOC_FLASH_ENC_SUPPORTED=y +# default: CONFIG_SOC_SECURE_BOOT_SUPPORTED=y +# default: CONFIG_SOC_MEMPROT_SUPPORTED=y +# default: CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y +# default: CONFIG_SOC_BOD_SUPPORTED=y +# default: CONFIG_SOC_CLK_TREE_SUPPORTED=y +# default: +CONFIG_SOC_REGI2C_SUPPORTED=y +# default: CONFIG_SOC_MPU_SUPPORTED=y +# default: CONFIG_SOC_WDT_SUPPORTED=y +# default: +CONFIG_SOC_RTC_WDT_SUPPORTED=y +# default: CONFIG_SOC_SPI_FLASH_SUPPORTED=y +# default: CONFIG_SOC_RNG_SUPPORTED=y +# default: CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y +# default: CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y +# default: CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y +# default: CONFIG_SOC_PM_SUPPORTED=y +# default: +CONFIG_SOC_SIMD_INSTRUCTION_SUPPORTED=y +# default: +CONFIG_SOC_SPI_EXTERNAL_NOR_FLASH_SUPPORTED=y +# default: CONFIG_SOC_XTAL_SUPPORT_40M=y +# default: CONFIG_SOC_APPCPU_HAS_CLOCK_GATING_BUG=y +# default: CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y +# default: CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y +# default: CONFIG_SOC_ADC_ARBITER_SUPPORTED=y +# default: CONFIG_SOC_ADC_DIG_IIR_FILTER_SUPPORTED=y +# default: CONFIG_SOC_ADC_MONITOR_SUPPORTED=y +# default: CONFIG_SOC_ADC_DMA_SUPPORTED=y +# default: CONFIG_SOC_ADC_PERIPH_NUM=2 +# default: CONFIG_SOC_ADC_MAX_CHANNEL_NUM=10 +# default: CONFIG_SOC_ADC_ATTEN_NUM=4 +# default: CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2 +# default: CONFIG_SOC_ADC_PATT_LEN_MAX=24 +# default: CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12 +# default: CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 +# default: CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4 +# default: CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 +# default: CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2 +# default: CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2 +# default: CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333 +# default: CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611 +# default: CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12 +# default: CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 +# default: CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y +# default: CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y +# default: CONFIG_SOC_ADC_SHARED_POWER=y +# default: CONFIG_SOC_APB_BACKUP_DMA=y +# default: CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y +# default: CONFIG_SOC_CACHE_WRITEBACK_SUPPORTED=y +# default: CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y +# default: +CONFIG_SOC_CACHE_ACS_INVALID_STATE_ON_PANIC=y +# default: CONFIG_SOC_CPU_CORES_NUM=2 +# default: CONFIG_SOC_CPU_INTR_NUM=32 +# default: CONFIG_SOC_CPU_HAS_FPU=y +# default: CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y +# default: CONFIG_SOC_CPU_BREAKPOINTS_NUM=2 +# default: CONFIG_SOC_CPU_WATCHPOINTS_NUM=2 -CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=64 +# default: +CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x40 +# default: +CONFIG_SOC_SIMD_PREFERRED_DATA_ALIGNMENT=16 +# default: CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=4096 +# default: CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16 +# default: CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100 +# default: CONFIG_SOC_AHB_GDMA_VERSION=1 -CONFIG_SOC_GDMA_NUM_GROUPS_MAX=1 -CONFIG_SOC_GDMA_PAIRS_PER_GROUP=5 -CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=5 -CONFIG_SOC_AHB_GDMA_SUPPORT_PSRAM=y +# default: CONFIG_SOC_GPIO_PORT=1 +# default: CONFIG_SOC_GPIO_PIN_COUNT=49 +# default: CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y -CONFIG_SOC_GPIO_FILTER_CLK_SUPPORT_APB=y -CONFIG_SOC_GPIO_SUPPORT_RTC_INDEPENDENT=y +# default: CONFIG_SOC_GPIO_SUPPORT_FORCE_HOLD=y +# default: CONFIG_SOC_GPIO_VALID_GPIO_MASK=0x1FFFFFFFFFFFF +# default: CONFIG_SOC_GPIO_IN_RANGE_MAX=48 +# default: CONFIG_SOC_GPIO_OUT_RANGE_MAX=48 +# default: CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0x0001FFFFFC000000 +# default: CONFIG_SOC_GPIO_CLOCKOUT_BY_IO_MUX=y +# default: CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=3 -CONFIG_SOC_DEDIC_GPIO_OUT_CHANNELS_NUM=8 -CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8 -CONFIG_SOC_DEDIC_GPIO_OUT_AUTO_ENABLE=y +# default: +CONFIG_SOC_GPIO_SUPPORT_HP_PERIPH_PD_SLEEP_WAKEUP=y +# default: +CONFIG_SOC_GPIO_HP_PERIPH_PD_SLEEP_WAKEABLE_MASK=0 +# default: CONFIG_SOC_I2C_NUM=2 +# default: CONFIG_SOC_HP_I2C_NUM=2 -CONFIG_SOC_I2C_FIFO_LEN=32 -CONFIG_SOC_I2C_CMD_REG_NUM=8 -CONFIG_SOC_I2C_SUPPORT_SLAVE=y -CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y +# default: CONFIG_SOC_I2C_SUPPORT_XTAL=y +# default: CONFIG_SOC_I2C_SUPPORT_RTC=y +# default: CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y +# default: +CONFIG_SOC_I2C_SUPPORT_SLAVE=y +# default: CONFIG_SOC_I2C_SLAVE_SUPPORT_BROADCAST=y -CONFIG_SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS=y -CONFIG_SOC_I2S_NUM=2 +# default: +CONFIG_SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE=y +# default: CONFIG_SOC_I2S_HW_VERSION_2=y -CONFIG_SOC_I2S_SUPPORTS_XTAL=y -CONFIG_SOC_I2S_SUPPORTS_PLL_F160M=y +# default: CONFIG_SOC_I2S_SUPPORTS_PCM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y -CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 +# default: +CONFIG_SOC_I2S_SUPPORTS_PCM2PDM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y +# default: +CONFIG_SOC_I2S_SUPPORTS_PDM2PCM=y +# default: +CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 +# default: CONFIG_SOC_I2S_PDM_MAX_RX_LINES=4 +# default: CONFIG_SOC_I2S_SUPPORTS_TDM=y +# default: CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y +# default: CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y +# default: +CONFIG_SOC_LEDC_TIMER_NUM=4 +# default: CONFIG_SOC_LEDC_CHANNEL_NUM=8 +# default: CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=14 +# default: CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y -CONFIG_SOC_MCPWM_GROUPS=2 -CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3 -CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3 -CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2 -CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2 -CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2 -CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3 -CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y -CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3 -CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3 +# default: CONFIG_SOC_MCPWM_SWSYNC_CAN_PROPAGATE=y +# default: CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=1 +# default: CONFIG_SOC_MMU_PERIPH_NUM=1 -CONFIG_SOC_PCNT_GROUPS=1 -CONFIG_SOC_PCNT_UNITS_PER_GROUP=4 -CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2 -CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2 -CONFIG_SOC_RMT_GROUPS=1 -CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=4 -CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=4 -CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8 +# default: +CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 +# default: +CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 +# default: CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48 +# default: CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y -CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y -CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y +# default: CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y +# default: CONFIG_SOC_RMT_SUPPORT_TX_LOOP_AUTO_STOP=y -CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y -CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y -CONFIG_SOC_RMT_SUPPORT_XTAL=y -CONFIG_SOC_RMT_SUPPORT_RC_FAST=y -CONFIG_SOC_RMT_SUPPORT_APB=y +# default: CONFIG_SOC_RMT_SUPPORT_DMA=y -CONFIG_SOC_LCD_I80_SUPPORTED=y -CONFIG_SOC_LCD_RGB_SUPPORTED=y -CONFIG_SOC_LCD_I80_BUSES=1 -CONFIG_SOC_LCD_RGB_PANELS=1 -CONFIG_SOC_LCD_I80_BUS_WIDTH=16 -CONFIG_SOC_LCD_RGB_DATA_WIDTH=16 -CONFIG_SOC_LCD_SUPPORT_RGB_YUV_CONV=y +# default: CONFIG_SOC_RTC_CNTL_CPU_PD_DMA_BUS_WIDTH=128 +# default: CONFIG_SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM=549 +# default: CONFIG_SOC_RTC_CNTL_TAGMEM_PD_DMA_BUS_WIDTH=128 +# default: +CONFIG_SOC_RTC_CNTL_NEEDS_ATOMIC_ACCESS=y +# default: CONFIG_SOC_RTCIO_PIN_COUNT=22 +# default: CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED=y +# default: CONFIG_SOC_RTCIO_HOLD_SUPPORTED=y +# default: CONFIG_SOC_RTCIO_WAKE_SUPPORTED=y -CONFIG_SOC_SDM_GROUPS=y -CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8 -CONFIG_SOC_SDM_CLK_SUPPORT_APB=y +# default: +CONFIG_SOC_LP_IO_CLOCK_IS_INDEPENDENT=y +# default: CONFIG_SOC_SPI_PERIPH_NUM=3 -CONFIG_SOC_SPI_MAX_CS_NUM=6 +# default: CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 -CONFIG_SOC_SPI_SUPPORT_DDRCLK=y -CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y -CONFIG_SOC_SPI_SUPPORT_CD_SIG=y -CONFIG_SOC_SPI_SUPPORT_CONTINUOUS_TRANS=y +# default: CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y -CONFIG_SOC_SPI_SUPPORT_CLK_APB=y -CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y -CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y -CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y -CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16 +# default: CONFIG_SOC_SPI_SUPPORT_OCT=y -CONFIG_SOC_SPI_SCT_SUPPORTED=y -CONFIG_SOC_SPI_SCT_REG_NUM=14 -CONFIG_SOC_SPI_SCT_BUFFER_NUM_MAX=y -CONFIG_SOC_SPI_SCT_CONF_BITLEN_MAX=0x3FFFA -CONFIG_SOC_MEMSPI_SRC_FREQ_120M=y -CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y +# default: CONFIG_SOC_SPIRAM_SUPPORTED=y +# default: CONFIG_SOC_SPIRAM_XIP_SUPPORTED=y -CONFIG_SOC_SYSTIMER_COUNTER_NUM=2 -CONFIG_SOC_SYSTIMER_ALARM_NUM=3 -CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32 -CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20 -CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y -CONFIG_SOC_SYSTIMER_INT_LEVEL=y -CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y -CONFIG_SOC_TIMER_GROUPS=2 -CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2 -CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54 -CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y -CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y -CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4 +# default: +CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 +# default: +CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 +# default: +CONFIG_SOC_RTC_TIMER_V1=y +# default: CONFIG_SOC_TOUCH_SENSOR_VERSION=2 -CONFIG_SOC_TOUCH_SENSOR_NUM=15 +# default: +CONFIG_SOC_TOUCH_MIN_CHAN_ID=1 +# default: +CONFIG_SOC_TOUCH_MAX_CHAN_ID=14 +# default: +CONFIG_SOC_TOUCH_SUPPORT_BENCHMARK=y +# default: CONFIG_SOC_TOUCH_SUPPORT_SLEEP_WAKEUP=y +# default: CONFIG_SOC_TOUCH_SUPPORT_WATERPROOF=y +# default: CONFIG_SOC_TOUCH_SUPPORT_PROX_SENSING=y +# default: +CONFIG_SOC_TOUCH_SUPPORT_DENOISE_CHAN=y +# default: CONFIG_SOC_TOUCH_PROXIMITY_CHANNEL_NUM=3 -CONFIG_SOC_TOUCH_PROXIMITY_MEAS_DONE_SUPPORTED=y +# default: CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM=1 +# default: CONFIG_SOC_TWAI_CONTROLLER_NUM=1 -CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y -CONFIG_SOC_TWAI_BRP_MIN=2 -CONFIG_SOC_TWAI_BRP_MAX=16384 -CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y +# default: +CONFIG_SOC_TWAI_MASK_FILTER_NUM=1 +# default: CONFIG_SOC_UART_NUM=3 +# default: CONFIG_SOC_UART_HP_NUM=3 +# default: CONFIG_SOC_UART_FIFO_LEN=128 +# default: CONFIG_SOC_UART_BITRATE_MAX=5000000 -CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y +# default: CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y +# default: CONFIG_SOC_UART_SUPPORT_APB_CLK=y +# default: CONFIG_SOC_UART_SUPPORT_RTC_CLK=y +# default: CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y +# default: +CONFIG_SOC_UART_WAKEUP_SUPPORT_ACTIVE_THRESH_MODE=y +# default: CONFIG_SOC_USB_OTG_PERIPH_NUM=1 +# default: +CONFIG_SOC_USB_FSLS_PHY_NUM=1 +# default: CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968 +# default: CONFIG_SOC_SHA_SUPPORT_DMA=y +# default: CONFIG_SOC_SHA_SUPPORT_RESUME=y +# default: CONFIG_SOC_SHA_GDMA=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA1=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA224=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA256=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA384=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA512=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA512_224=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA512_256=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA512_T=y +# default: CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 +# default: CONFIG_SOC_MPI_OPERATIONS_NUM=3 +# default: CONFIG_SOC_RSA_MAX_BIT_LEN=4096 +# default: CONFIG_SOC_AES_SUPPORT_DMA=y +# default: CONFIG_SOC_AES_GDMA=y +# default: CONFIG_SOC_AES_SUPPORT_AES_128=y +# default: CONFIG_SOC_AES_SUPPORT_AES_256=y +# default: CONFIG_SOC_PM_SUPPORT_EXT0_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_EXT_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_BT_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_CPU_PD=y +# default: CONFIG_SOC_PM_SUPPORT_TAGMEM_PD=y +# default: CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y +# default: CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y +# default: CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y +# default: CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y +# default: CONFIG_SOC_PM_SUPPORT_MODEM_PD=y +# default: CONFIG_SOC_CONFIGURABLE_VDDSDIO_SUPPORTED=y +# default: CONFIG_SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY=y +# default: CONFIG_SOC_PM_CPU_RETENTION_BY_RTCCNTL=y +# default: CONFIG_SOC_PM_MODEM_RETENTION_BY_BACKUPDMA=y +# default: +CONFIG_SOC_PM_MODEM_PD_BY_SW=y +# default: +CONFIG_SOC_PM_RTC_NOT_SUPPORT_UART2_WAKEUP=y +# default: CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y +# default: CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y +# default: CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y +# default: CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y +# default: +CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL_D2=y +# default: CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE=y +# default: CONFIG_SOC_EFUSE_DIS_DOWNLOAD_DCACHE=y +# default: CONFIG_SOC_EFUSE_HARD_DIS_JTAG=y +# default: CONFIG_SOC_EFUSE_DIS_USB_JTAG=y +# default: CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y +# default: CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y +# default: CONFIG_SOC_EFUSE_DIS_ICACHE=y +# default: CONFIG_SOC_EFUSE_BLOCK9_KEY_PURPOSE_QUIRK=y +# default: +CONFIG_SOC_EFUSE_XTS_AES_KEY_128=y +# default: +CONFIG_SOC_EFUSE_XTS_AES_KEY_256=y +# default: CONFIG_SOC_SECURE_BOOT_V2_RSA=y +# default: CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3 +# default: CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y +# default: CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y +# default: CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=64 +# default: CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y +# default: CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS=y +# default: CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y +# default: CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256=y +# default: CONFIG_SOC_MEMPROT_CPU_PREFETCH_PAD_SIZE=16 +# default: CONFIG_SOC_MEMPROT_MEM_ALIGN_SIZE=256 +# default: CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 +# default: CONFIG_SOC_MAC_BB_PD_MEM_SIZE=192 +# default: CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12 +# default: CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y -CONFIG_SOC_SPI_MEM_SUPPORT_OPI_MODE=y +# default: +CONFIG_SOC_SPI_MEM_SUPPORT_FLASH_OPI_MODE=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_TIMING_TUNING=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_WRAP=y +# default: CONFIG_SOC_MEMSPI_TIMING_TUNING_BY_MSPI_DELAY=y +# default: CONFIG_SOC_MEMSPI_CORE_CLK_SHARED_WITH_PSRAM=y +# default: +CONFIG_SOC_SPI_MEM_SUPPORT_CACHE_32BIT_ADDR_MAP=y +# default: +CONFIG_SOC_SPI_MEM_FLASH_SUPPORT_HPM=y +# default: +CONFIG_SOC_MEMSPI_SUPPORT_CONTROL_DUMMY_OUT=y +# default: +CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y +# default: +CONFIG_SOC_MEMSPI_ENCRYPTION_ALIGNMENT=16 +# default: CONFIG_SOC_COEX_HW_PTI=y +# default: CONFIG_SOC_EXTERNAL_COEX_LEADER_TX_LINE=y +# default: CONFIG_SOC_SDMMC_USE_GPIO_MATRIX=y +# default: CONFIG_SOC_SDMMC_NUM_SLOTS=2 -CONFIG_SOC_SDMMC_SUPPORT_XTAL_CLOCK=y +# default: +CONFIG_SOC_SDMMC_DATA_WIDTH_MAX=8 +# default: CONFIG_SOC_SDMMC_DELAY_PHASE_NUM=4 +# default: CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y +# default: CONFIG_SOC_WIFI_HW_TSF=y +# default: CONFIG_SOC_WIFI_FTM_SUPPORT=y +# default: CONFIG_SOC_WIFI_GCMP_SUPPORT=y +# default: CONFIG_SOC_WIFI_WAPI_SUPPORT=y +# default: +CONFIG_SOC_WIFI_TXOP_SUPPORT=y +# default: CONFIG_SOC_WIFI_CSI_SUPPORT=y +# default: CONFIG_SOC_WIFI_MESH_SUPPORT=y +# default: CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +# default: CONFIG_SOC_WIFI_PHY_NEEDS_USB_WORKAROUND=y +# default: CONFIG_SOC_BLE_SUPPORTED=y +# default: CONFIG_SOC_BLE_MESH_SUPPORTED=y +# default: CONFIG_SOC_BLE_50_SUPPORTED=y +# default: CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y +# default: CONFIG_SOC_BLUFI_SUPPORTED=y +# default: CONFIG_SOC_ULP_HAS_ADC=y +# default: CONFIG_SOC_PHY_COMBO_MODULE=y +# default: +CONFIG_SOC_LCDCAM_CAM_SUPPORT_RGB_YUV_CONV=y +# default: CONFIG_IDF_CMAKE=y +# default: CONFIG_IDF_TOOLCHAIN="gcc" +# default: +CONFIG_IDF_TOOLCHAIN_GCC=y +# default: CONFIG_IDF_TARGET_ARCH_XTENSA=y +# default: CONFIG_IDF_TARGET_ARCH="xtensa" +# default: CONFIG_IDF_TARGET="esp32s3" +# default: CONFIG_IDF_INIT_VERSION="5.3.1" +# default: CONFIG_IDF_TARGET_ESP32S3=y +# default: CONFIG_IDF_FIRMWARE_CHIP_ID=0x0009 # @@ -367,13 +638,29 @@ CONFIG_IDF_FIRMWARE_CHIP_ID=0x0009 # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_RAM is not set +# default: CONFIG_APP_BUILD_GENERATE_BINARIES=y +# default: CONFIG_APP_BUILD_BOOTLOADER=y +# default: CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y + +# +# Minimize binary changes between builds +# +# default: +# CONFIG_APP_BUILD_MINIMIZE_BINARY_CHANGES is not set +# end of Minimize binary changes between builds + # CONFIG_APP_REPRODUCIBLE_BUILD is not set # CONFIG_APP_NO_BLOBS is not set # end of Build type +# +# App Update config +# +# end of App Update config + # # Bootloader config # @@ -385,19 +672,61 @@ CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y CONFIG_BOOTLOADER_PROJECT_VER=1 # end of Bootloader manager +# +# Application Rollback +# +# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set +# end of Application Rollback + +# +# Recovery Bootloader and Rollback +# +# end of Recovery Bootloader and Rollback + +# default: CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x0 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set -# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set + +# +# Log +# +# default: +CONFIG_BOOTLOADER_LOG_VERSION_1=y +# default: +CONFIG_BOOTLOADER_LOG_VERSION=1 # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set +# default: CONFIG_BOOTLOADER_LOG_LEVEL=3 +# +# Format +# +# default: +# CONFIG_BOOTLOADER_LOG_COLORS is not set +# default: +CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y +# end of Format + +# +# Settings +# +# default: +CONFIG_BOOTLOADER_LOG_MODE_TEXT_EN=y +# default: +CONFIG_BOOTLOADER_LOG_MODE_TEXT=y +# end of Settings +# end of Log + +# default: +CONFIG_BOOTLOADER_CPU_CLK_FREQ_MHZ=80 + # # Serial Flash Configurations # @@ -412,10 +741,10 @@ CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 -# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set +# default: CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config @@ -423,11 +752,18 @@ CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # # Security features # +# default: CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y +# default: CONFIG_SECURE_BOOT_V2_PREFERRED=y # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set +# default: +CONFIG_SECURE_BOOT_IMAGE_DIGEST_LEN=32 +# default: +CONFIG_SECURE_BOOT_ROM_FAST_WAKE_RESERVE_SIZE=0 # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set +# default: CONFIG_SECURE_ROM_DL_MODE_ENABLED=y # end of Security features @@ -441,33 +777,70 @@ CONFIG_APP_COMPILE_TIME_DATE=y CONFIG_APP_RETRIEVE_LEN_ELF_SHA=16 # end of Application manager +# default: CONFIG_ESP_ROM_HAS_CRC_LE=y +# default: CONFIG_ESP_ROM_HAS_CRC_BE=y +# default: CONFIG_ESP_ROM_HAS_MZ_CRC32=y +# default: CONFIG_ESP_ROM_HAS_JPEG_DECODE=y +# default: CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y +# default: CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y +# default: CONFIG_ESP_ROM_USB_OTG_NUM=3 +# default: CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=4 +# default: CONFIG_ESP_ROM_HAS_ERASE_0_REGION_BUG=y +# default: CONFIG_ESP_ROM_HAS_ENCRYPTED_WRITES_USING_LEGACY_DRV=y +# default: CONFIG_ESP_ROM_GET_CLK_FREQ=y +# default: CONFIG_ESP_ROM_HAS_HAL_WDT=y +# default: CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y +# default: CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y +# default: CONFIG_ESP_ROM_HAS_SPI_FLASH=y +# default: +CONFIG_ESP_ROM_HAS_SPI_FLASH_MMAP=y +# default: CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y +# default: CONFIG_ESP_ROM_NEEDS_SET_CACHE_MMU_SIZE=y +# default: CONFIG_ESP_ROM_RAM_APP_NEEDS_MMU_INIT=y +# default: CONFIG_ESP_ROM_HAS_FLASH_COUNT_PAGES_BUG=y +# default: CONFIG_ESP_ROM_HAS_CACHE_SUSPEND_WAITI_BUG=y +# default: CONFIG_ESP_ROM_HAS_CACHE_WRITEBACK_BUG=y +# default: CONFIG_ESP_ROM_HAS_SW_FLOAT=y +# default: CONFIG_ESP_ROM_HAS_VERSION=y +# default: CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y +# default: +CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y +# default: +CONFIG_ESP_ROM_CONSOLE_OUTPUT_SECONDARY=y +# default: +CONFIG_ESP_ROM_HAS_REGI2C_IMPL=y +# default: +CONFIG_ESP_ROM_BOOTLOADER_OFFSET_FLASH=0x0 # # Boot ROM Behavior @@ -489,12 +862,15 @@ CONFIG_ESPTOOLPY_FLASH_MODE_AUTO_DETECT=y CONFIG_ESPTOOLPY_FLASHMODE_DIO=y # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y +# default: CONFIG_ESPTOOLPY_FLASHMODE="dio" +# default: +CONFIG_ESPTOOLPY_FLASHMODE_VAL=3 # CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set CONFIG_ESPTOOLPY_FLASHFREQ_80M=y # CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y +# default: CONFIG_ESPTOOLPY_FLASHFREQ="80m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set @@ -504,14 +880,18 @@ CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +# default: CONFIG_ESPTOOLPY_FLASHSIZE="8MB" # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set -CONFIG_ESPTOOLPY_BEFORE="default_reset" +# default: +CONFIG_ESPTOOLPY_BEFORE="default-reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set -CONFIG_ESPTOOLPY_AFTER="hard_reset" +# default: +CONFIG_ESPTOOLPY_AFTER="hard-reset" +# default: CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config @@ -521,8 +901,10 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # CONFIG_PARTITION_TABLE_SINGLE_APP is not set # CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set +# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" +# default: CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y @@ -531,9 +913,13 @@ CONFIG_PARTITION_TABLE_MD5=y # # Example Configuration # +# default: CONFIG_ENV_GPIO_RANGE_MIN=0 +# default: CONFIG_ENV_GPIO_RANGE_MAX=48 +# default: CONFIG_ENV_GPIO_IN_RANGE_MAX=48 +# default: CONFIG_ENV_GPIO_OUT_RANGE_MAX=48 CONFIG_BLINK_GPIO=18 CONFIG_BLINK_PERIOD=1000 @@ -549,7 +935,10 @@ CONFIG_COMPILER_OPTIMIZATION_DEBUG=y CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set +# default: +# CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE is not set CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y +# default: CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set CONFIG_COMPILER_HIDE_PATHS_MACROS=y @@ -559,117 +948,120 @@ CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set +# default: +# CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS is not set # CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_GCC15_WARNINGS is not set # CONFIG_COMPILER_DUMP_RTL_FILES is not set CONFIG_COMPILER_RT_LIB_GCCLIB=y +# default: CONFIG_COMPILER_RT_LIB_NAME="gcc" +# CONFIG_COMPILER_ORPHAN_SECTIONS_ERROR is not set # CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y +# default: +# CONFIG_COMPILER_STATIC_ANALYZER is not set +# default: +CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y +# default: +# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD_CONSTEXPR is not set +# default: +# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set # end of Compiler options # # Component config # -# -# Application Level Tracing -# -# CONFIG_APPTRACE_DEST_JTAG is not set -CONFIG_APPTRACE_DEST_NONE=y -# CONFIG_APPTRACE_DEST_UART1 is not set -# CONFIG_APPTRACE_DEST_UART2 is not set -# CONFIG_APPTRACE_DEST_USB_CDC is not set -CONFIG_APPTRACE_DEST_UART_NONE=y -CONFIG_APPTRACE_UART_TASK_PRIO=1 -CONFIG_APPTRACE_LOCK_ENABLE=y -# end of Application Level Tracing - # # Bluetooth # # CONFIG_BT_ENABLED is not set -CONFIG_BT_ALARM_MAX_NUM=50 -# end of Bluetooth # -# Console Library +# Common Options # -# CONFIG_CONSOLE_SORTED_HELP is not set -# end of Console Library # -# Driver Configurations +# BT Logs # # -# TWAI Configuration -# -# CONFIG_TWAI_ISR_IN_IRAM is not set -CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y -# end of TWAI Configuration - -# -# Legacy ADC Driver Configuration +# Log Sources # -# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set +# end of Log Sources -# -# Legacy ADC Calibration Configuration -# -# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy ADC Calibration Configuration -# end of Legacy ADC Driver Configuration +# default: +# CONFIG_BT_LOG_CRITICAL_ONLY is not set +# default: +# CONFIG_BLE_LOG_ENABLED is not set # -# Legacy MCPWM Driver Configurations +# Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) # -# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy MCPWM Driver Configurations +# default: +# CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set +# end of Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) +# end of BT Logs -# -# Legacy Timer Group Driver Configurations -# -# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy Timer Group Driver Configurations +# default: +# CONFIG_BT_LE_USED_MEM_STATISTICS_ENABLED is not set +# end of Common Options +# end of Bluetooth # -# Legacy RMT Driver Configurations +# Console Library # -# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy RMT Driver Configurations +# CONFIG_CONSOLE_SORTED_HELP is not set +# end of Console Library # -# Legacy I2S Driver Configurations +# Legacy Driver Configurations # -# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy I2S Driver Configurations # -# Legacy PCNT Driver Configurations +# Legacy TWAI Driver Configurations # -# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy PCNT Driver Configurations +# default: +# CONFIG_TWAI_ISR_IN_IRAM_LEGACY is not set +# default: +# CONFIG_TWAI_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_TWAI_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy TWAI Driver Configurations # -# Legacy SDM Driver Configurations +# Legacy I2C Driver Configurations # -# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy SDM Driver Configurations +# default: +# CONFIG_I2C_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy I2C Driver Configurations # -# Legacy Temperature Sensor Driver Configurations +# Legacy Touch Sensor Driver Configurations # -# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy Temperature Sensor Driver Configurations -# end of Driver Configurations +# default: +# CONFIG_TOUCH_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_TOUCH_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy Touch Sensor Driver Configurations +# end of Legacy Driver Configurations # # eFuse Bit Manager # # CONFIG_EFUSE_CUSTOM_TABLE is not set # CONFIG_EFUSE_VIRTUAL is not set +# default: CONFIG_EFUSE_MAX_BLK_LEN=256 # end of eFuse Bit Manager @@ -677,6 +1069,7 @@ CONFIG_EFUSE_MAX_BLK_LEN=256 # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y +# CONFIG_ESP_TLS_CUSTOM_STACK is not set CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set @@ -684,6 +1077,8 @@ CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # CONFIG_ESP_TLS_INSECURE is not set +# default: +CONFIG_ESP_TLS_DYN_BUF_STRATEGY_SUPPORTED=y # end of ESP-TLS # @@ -698,8 +1093,11 @@ CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # # Wireless Coexistence # +# default: CONFIG_ESP_COEX_ENABLED=y # CONFIG_ESP_COEX_EXTERNAL_COEXIST_ENABLE is not set +# default: +# CONFIG_ESP_COEX_GPIO_DEBUG is not set # end of Wireless Coexistence # @@ -708,6 +1106,24 @@ CONFIG_ESP_COEX_ENABLED=y CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # end of Common ESP-related +# +# ESP-Driver:Camera Controller Configurations +# +# default: +# CONFIG_CAM_CTLR_DVP_CAM_ISR_CACHE_SAFE is not set +# end of ESP-Driver:Camera Controller Configurations + +# +# GDMA Configurations +# +CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y +# default: +CONFIG_GDMA_ISR_HANDLER_IN_IRAM=y +# default: +CONFIG_GDMA_OBJ_DRAM_SAFE=y +# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set +# end of GDMA Configurations + # # ESP-Driver:GPIO Configurations # @@ -719,7 +1135,9 @@ CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set -# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set +# CONFIG_GPTIMER_ISR_CACHE_SAFE is not set +# default: +CONFIG_GPTIMER_OBJ_CACHE_SAFE=y # CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:GPTimer Configurations @@ -728,15 +1146,30 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # CONFIG_I2C_ISR_IRAM_SAFE is not set # CONFIG_I2C_ENABLE_DEBUG_LOG is not set +# default: +CONFIG_I2C_MASTER_ISR_HANDLER_IN_IRAM=y # end of ESP-Driver:I2C Configurations # # ESP-Driver:I2S Configurations # # CONFIG_I2S_ISR_IRAM_SAFE is not set +# default: +# CONFIG_I2S_CTRL_FUNC_IN_IRAM is not set # CONFIG_I2S_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:I2S Configurations +# +# ESP-Driver:I3C Master Configurations +# +# default: +# CONFIG_I3C_MASTER_ISR_CACHE_SAFE is not set +# default: +# CONFIG_I3C_MASTER_ENABLE_DEBUG_LOG is not set +# default: +# CONFIG_I3C_MASTER_ISR_HANDLER_IN_IRAM is not set +# end of ESP-Driver:I3C Master Configurations + # # ESP-Driver:LEDC Configurations # @@ -746,8 +1179,12 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # ESP-Driver:MCPWM Configurations # -# CONFIG_MCPWM_ISR_IRAM_SAFE is not set +# default: +CONFIG_MCPWM_ISR_HANDLER_IN_IRAM=y +# CONFIG_MCPWM_ISR_CACHE_SAFE is not set # CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set +# default: +CONFIG_MCPWM_OBJ_CACHE_SAFE=y # CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:MCPWM Configurations @@ -762,9 +1199,21 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # ESP-Driver:RMT Configurations # -# CONFIG_RMT_ISR_IRAM_SAFE is not set +# default: +CONFIG_RMT_ENCODER_FUNC_IN_IRAM=y +# default: +CONFIG_RMT_TX_ISR_HANDLER_IN_IRAM=y +# default: +CONFIG_RMT_RX_ISR_HANDLER_IN_IRAM=y # CONFIG_RMT_RECV_FUNC_IN_IRAM is not set +# default: +# CONFIG_RMT_TX_ISR_CACHE_SAFE is not set +# default: +# CONFIG_RMT_RX_ISR_CACHE_SAFE is not set +# default: +CONFIG_RMT_OBJ_CACHE_SAFE=y # CONFIG_RMT_ENABLE_DEBUG_LOG is not set +# CONFIG_RMT_ISR_IRAM_SAFE is not set # end of ESP-Driver:RMT Configurations # @@ -774,9 +1223,17 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_SDM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Sigma Delta Modulator Configurations +# +# ESP-Driver:SD Host SDMMC Controller Configurations +# +# default: +# CONFIG_SD_HOST_SDMMC_ISR_CACHE_SAFE is not set +# end of ESP-Driver:SD Host SDMMC Controller Configurations + # # ESP-Driver:SPI Configurations # +# default: # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set @@ -789,6 +1246,8 @@ CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set # CONFIG_TOUCH_ISR_IRAM_SAFE is not set # CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set +# default: +# CONFIG_TOUCH_SKIP_FSM_CHECK is not set # end of ESP-Driver:Touch Sensor Configurations # @@ -797,12 +1256,37 @@ CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Temperature Sensor Configurations +# +# ESP-Driver:TWAI Configurations +# +# CONFIG_TWAI_ISR_IN_IRAM is not set +# default: +# CONFIG_TWAI_IO_FUNC_IN_IRAM is not set +# default: +# CONFIG_TWAI_ISR_CACHE_SAFE is not set +# default: +# CONFIG_TWAI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:TWAI Configurations + # # ESP-Driver:UART Configurations # # CONFIG_UART_ISR_IN_IRAM is not set # end of ESP-Driver:UART Configurations +# +# ESP-Driver:UHCI Configurations +# +# default: +# CONFIG_UHCI_ISR_HANDLER_IN_IRAM is not set +# default: +# CONFIG_UHCI_RECV_FUNC_IN_IRAM is not set +# default: +# CONFIG_UHCI_ISR_CACHE_SAFE is not set +# default: +# CONFIG_UHCI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:UHCI Configurations + # # ESP-Driver:USB Serial/JTAG Configuration # @@ -812,11 +1296,9 @@ CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y # # Ethernet # +# default: CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_SPI_ETHERNET=y -# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set -# CONFIG_ETH_SPI_ETHERNET_W5500 is not set -# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set # CONFIG_ETH_USE_OPENETH is not set # CONFIG_ETH_TRANSMIT_MUTEX is not set # end of Ethernet @@ -826,18 +1308,30 @@ CONFIG_ETH_USE_SPI_ETHERNET=y # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y +# default: +CONFIG_ESP_EVENT_POST_FROM_ISR_SIZE=4 CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # +# default: CONFIG_ESP_GDBSTUB_ENABLED=y # CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y CONFIG_ESP_GDBSTUB_MAX_TASKS=32 # end of GDB Stub +# +# ESP HID +# +# default: +CONFIG_ESPHID_TASK_SIZE_BT=2048 +# default: +CONFIG_ESPHID_TASK_SIZE_BLE=4096 +# end of ESP HID + # # ESP HTTP client # @@ -845,6 +1339,14 @@ CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set +# default: +# CONFIG_ESP_HTTP_CLIENT_ENABLE_GET_CONTENT_RANGE is not set +# default: +CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 +# default: +# CONFIG_ESP_HTTP_CLIENT_SAVE_RESPONSE_HEADERS is not set +# default: +CONFIG_ESP_HTTP_CLIENT_STRICT_HEADER_BUFFER=y # end of ESP HTTP client # @@ -857,6 +1359,10 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set +# default: +CONFIG_HTTPD_ENABLE_EVENTS=y +# default: +CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 # end of HTTP Server # @@ -864,17 +1370,27 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 # # CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set # CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set +# default: +CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 +# default: +# CONFIG_ESP_HTTPS_OTA_ENABLE_PARTIAL_DOWNLOAD is not set +# default: +CONFIG_ESP_HTTPS_OTA_VERIFY_SPI_MODE=y # end of ESP HTTPS OTA # # ESP HTTPS server # # CONFIG_ESP_HTTPS_SERVER_ENABLE is not set +# default: +# CONFIG_ESP_HTTPS_SERVER_CERT_SELECT_HOOK is not set # end of ESP HTTPS server # # Hardware Settings # +# default: +CONFIG_ESP_HW_SUPPORT_FUNC_IN_IRAM=y # # Chip revision @@ -882,27 +1398,46 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 CONFIG_ESP32S3_REV_MIN_0=y # CONFIG_ESP32S3_REV_MIN_1 is not set # CONFIG_ESP32S3_REV_MIN_2 is not set +# default: CONFIG_ESP32S3_REV_MIN_FULL=0 +# default: CONFIG_ESP_REV_MIN_FULL=0 # # Maximum Supported ESP32-S3 Revision (Rev v0.99) # +# default: CONFIG_ESP32S3_REV_MAX_FULL=99 +# default: CONFIG_ESP_REV_MAX_FULL=99 +# default: +CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 +# default: +CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=199 + +# +# Maximum Supported ESP32-S3 eFuse Block Revision (eFuse Block Rev v1.99) +# # end of Chip revision # # MAC Config # +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y +# default: CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y +# default: CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_TWO is not set CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES_FOUR=y +# default: CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set # end of MAC Config @@ -913,12 +1448,15 @@ CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP_SLEEP_POWER_DOWN_FLASH is not set CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU=y +# default: CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND=y CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=2000 # CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set # CONFIG_ESP_SLEEP_DEBUG is not set CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y +# default: +# CONFIG_ESP_SLEEP_SET_FLASH_DPD is not set # end of Sleep Config # @@ -929,60 +1467,118 @@ CONFIG_RTC_CLK_SRC_INT_RC=y # CONFIG_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_RTC_CLK_CAL_CYCLES=1024 +# default: +CONFIG_RTC_CLK_FUNC_IN_IRAM=y +# default: +CONFIG_RTC_TIME_FUNC_IN_IRAM=y # end of RTC Clock Config # # Peripheral Control # -CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM=y +# default: +CONFIG_ESP_REGI2C_CTRL_FUNC_IN_IRAM=y # end of Peripheral Control -# -# GDMA Configurations -# -CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y -# CONFIG_GDMA_ISR_IRAM_SAFE is not set -# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set -# end of GDMA Configurations - # # Main XTAL Config # CONFIG_XTAL_FREQ_40=y +# default: CONFIG_XTAL_FREQ=40 # end of Main XTAL Config -CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y -# end of Hardware Settings - # -# LCD and Touch Panel +# Power Supplier # # -# LCD Touch Drivers are maintained in the IDF Component Registry +# Brownout Detector # +CONFIG_ESP_BROWNOUT_DET=y +CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set +# default: +CONFIG_ESP_BROWNOUT_DET_LVL=7 +# default: +CONFIG_ESP_BROWNOUT_USE_INTR=y +# end of Brownout Detector +# end of Power Supplier + +# default: +CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y +# default: +CONFIG_ESP_INTR_IN_IRAM=y +# end of Hardware Settings # -# LCD Peripheral Configuration +# ESP-Driver:LCD Controller Configurations # -CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE=32 -# CONFIG_LCD_ENABLE_DEBUG_LOG is not set # CONFIG_LCD_RGB_ISR_IRAM_SAFE is not set # CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set -# end of LCD Peripheral Configuration -# end of LCD and Touch Panel +# CONFIG_LCD_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:LCD Controller Configurations + +# +# LibC +# +# default: +# CONFIG_LIBC_NEWLIB is not set +# default: +CONFIG_LIBC_PICOLIBC=y +# default: +CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY=y +# default: +CONFIG_LIBC_MISC_IN_IRAM=y +# default: +CONFIG_LIBC_LOCKS_PLACE_IN_IRAM=y +CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_LIBC_STDOUT_LINE_ENDING_LF is not set +# CONFIG_LIBC_STDOUT_LINE_ENDING_CR is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_LF is not set +CONFIG_LIBC_STDIN_LINE_ENDING_CR=y +CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT=y +# CONFIG_LIBC_TIME_SYSCALL_USE_RTC is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_HRT is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_NONE is not set +# default: +CONFIG_LIBC_ASSERT_BUFFER_SIZE=200 +# end of LibC + +# +# ESP-MM: Memory Management Configurations +# +# default: +# CONFIG_ESP_MM_CACHE_MSYNC_C2M_CHUNKED_OPS is not set +# end of ESP-MM: Memory Management Configurations # # ESP NETIF Adapter # +# default: +CONFIG_ESP_NETIF_LOST_IP_TIMER_ENABLE=y CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 +# default: +# CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set +# default: CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y -# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set +# default: +CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y +# default: +CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS=y # CONFIG_ESP_NETIF_L2_TAP is not set # CONFIG_ESP_NETIF_BRIDGE_EN is not set +# default: +# CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set # end of ESP NETIF Adapter # @@ -993,10 +1589,12 @@ CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y # # PHY # +# default: CONFIG_ESP_PHY_ENABLED=y CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20 +# default: CONFIG_ESP_PHY_MAX_TX_POWER=20 # CONFIG_ESP_PHY_REDUCE_TX_POWER is not set CONFIG_ESP_PHY_ENABLE_USB=y @@ -1004,16 +1602,33 @@ CONFIG_ESP_PHY_ENABLE_USB=y CONFIG_ESP_PHY_RF_CAL_PARTIAL=y # CONFIG_ESP_PHY_RF_CAL_NONE is not set # CONFIG_ESP_PHY_RF_CAL_FULL is not set +# default: CONFIG_ESP_PHY_CALIBRATION_MODE=0 +# default: +CONFIG_ESP_PHY_PLL_TRACK_PERIOD_MS=1000 # CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set +# default: +# CONFIG_ESP_PHY_RECORD_USED_TIME is not set +# default: +CONFIG_ESP_PHY_IRAM_OPT=y +# default: +# CONFIG_ESP_PHY_DEBUG is not set +# default: +CONFIG_ESP_PHY_ENABLE_VERSION_PRINT=y # end of PHY # # Power Management # +# default: +# CONFIG_PM_SLEEP_FUNC_IN_IRAM is not set # CONFIG_PM_ENABLE is not set +# default: +# CONFIG_PM_SLP_IRAM_OPT is not set CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y CONFIG_PM_RESTORE_CACHE_TAGMEM_AFTER_LIGHT_SLEEP=y +# default: +CONFIG_PM_ESP_SLEEP_POWER_DOWN_CPU=y # end of Power Management # @@ -1025,15 +1640,52 @@ CONFIG_PM_RESTORE_CACHE_TAGMEM_AFTER_LIGHT_SLEEP=y # # ESP Ringbuf # -# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set +# default: +CONFIG_RINGBUF_IN_IRAM=y # end of ESP Ringbuf +# +# ESP-ROM +# +# default: +CONFIG_ESP_ROM_PRINT_IN_IRAM=y +# end of ESP-ROM + +# +# ESP Security Specific +# +# end of ESP Security Specific + +# +# ESP-STDIO +# +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +# CONFIG_ESP_CONSOLE_USB_CDC is not set +# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set +# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set +# CONFIG_ESP_CONSOLE_NONE is not set +# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set +CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y +# default: +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y +# default: +CONFIG_ESP_CONSOLE_UART=y +# default: +CONFIG_ESP_CONSOLE_UART_NUM=0 +# default: +CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 +CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 +# default: +CONFIG_ESP_STDIO_MAX_VFS_ENTRIES=2 +# end of ESP-STDIO + # # ESP System Settings # # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240 is not set +# default: CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160 # @@ -1041,23 +1693,29 @@ CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160 # CONFIG_ESP32S3_INSTRUCTION_CACHE_16KB=y # CONFIG_ESP32S3_INSTRUCTION_CACHE_32KB is not set +# default: CONFIG_ESP32S3_INSTRUCTION_CACHE_SIZE=0x4000 # CONFIG_ESP32S3_INSTRUCTION_CACHE_4WAYS is not set CONFIG_ESP32S3_INSTRUCTION_CACHE_8WAYS=y +# default: CONFIG_ESP32S3_ICACHE_ASSOCIATED_WAYS=8 # CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_16B is not set CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_32B=y +# default: CONFIG_ESP32S3_INSTRUCTION_CACHE_LINE_SIZE=32 # CONFIG_ESP32S3_DATA_CACHE_16KB is not set CONFIG_ESP32S3_DATA_CACHE_32KB=y # CONFIG_ESP32S3_DATA_CACHE_64KB is not set +# default: CONFIG_ESP32S3_DATA_CACHE_SIZE=0x8000 # CONFIG_ESP32S3_DATA_CACHE_4WAYS is not set CONFIG_ESP32S3_DATA_CACHE_8WAYS=y +# default: CONFIG_ESP32S3_DCACHE_ASSOCIATED_WAYS=8 # CONFIG_ESP32S3_DATA_CACHE_LINE_16B is not set CONFIG_ESP32S3_DATA_CACHE_LINE_32B=y # CONFIG_ESP32S3_DATA_CACHE_LINE_64B is not set +# default: CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE=32 # end of Cache config @@ -1072,44 +1730,33 @@ CONFIG_ESP32S3_DATA_CACHE_LINE_SIZE=32 # Trace memory # # CONFIG_ESP32S3_TRAX is not set +# default: CONFIG_ESP32S3_TRACEMEM_RESERVE_DRAM=0x0 # end of Trace memory +# default: +CONFIG_ESP_SYSTEM_IN_IRAM=y # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 +# default: CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y - -# -# Memory protection -# -CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y -CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y -# end of Memory protection - +CONFIG_ESP_SYSTEM_MEMPROT=y +# default: +CONFIG_ESP_SYSTEM_MEMPROT_PMS=y +CONFIG_ESP_SYSTEM_MEMPROT_PMS_LOCK=y CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584 CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y # CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set # CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set +# default: CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 -CONFIG_ESP_CONSOLE_UART_DEFAULT=y -# CONFIG_ESP_CONSOLE_USB_CDC is not set -# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set -# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set -# CONFIG_ESP_CONSOLE_NONE is not set -# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set -CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y -CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y -CONFIG_ESP_CONSOLE_UART=y -CONFIG_ESP_CONSOLE_UART_NUM=0 -CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 -CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 CONFIG_ESP_INT_WDT_CHECK_CPU1=y @@ -1123,61 +1770,74 @@ CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP_DEBUG_STUBS_ENABLE is not set CONFIG_ESP_DEBUG_OCDAWARE=y CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y - -# -# Brownout Detector -# -CONFIG_ESP_BROWNOUT_DET=y -CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set -CONFIG_ESP_BROWNOUT_DET_LVL=7 -# end of Brownout Detector - -CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y CONFIG_ESP_SYSTEM_BBPLL_RECALIB=y # end of ESP System Settings # # IPC (Inter-Processor Call) # +# default: +CONFIG_ESP_IPC_ENABLE=y CONFIG_ESP_IPC_TASK_STACK_SIZE=1280 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y +# default: CONFIG_ESP_IPC_ISR_ENABLE=y # end of IPC (Inter-Processor Call) # # ESP Timer (High Resolution Timer) # +# default: +CONFIG_ESP_TIMER_IN_IRAM=y # CONFIG_ESP_TIMER_PROFILING is not set +# default: CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y +# default: CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 # CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set +# default: CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y # CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set +# default: CONFIG_ESP_TIMER_IMPL_SYSTIMER=y # end of ESP Timer (High Resolution Timer) +# +# ESP Trace Configuration +# +# default: +# CONFIG_ESP_TRACE_LIB_EXTERNAL is not set +# default: +CONFIG_ESP_TRACE_LIB_NONE=y +# default: +CONFIG_ESP_TRACE_LIB_NAME="none" +# default: +# CONFIG_ESP_TRACE_TRANSPORT_APPTRACE is not set +# default: +CONFIG_ESP_TRACE_TRANSPORT_NONE=y +# default: +CONFIG_ESP_TRACE_TRANSPORT_NAME="none" +# end of ESP Trace Configuration + # # Wi-Fi # +# default: CONFIG_ESP_WIFI_ENABLED=y CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32 # CONFIG_ESP_WIFI_STATIC_TX_BUFFER is not set CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y +# default: CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1 CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y # CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set +# default: CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0 CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5 # CONFIG_ESP_WIFI_CSI_ENABLED is not set @@ -1191,14 +1851,24 @@ CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752 CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32 CONFIG_ESP_WIFI_IRAM_OPT=y -# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set +CONFIG_ESP_WIFI_EXTRA_IRAM_OPT=y CONFIG_ESP_WIFI_RX_IRAM_OPT=y CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y +# default: +CONFIG_ESP_WIFI_ENABLE_SAE_H2E=y CONFIG_ESP_WIFI_ENABLE_SAE_PK=y CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y +# default: +CONFIG_ESP_WIFI_WPA3_COMPATIBLE_SUPPORT=y +# default: +# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_SOFTAP is not set +# default: +# CONFIG_ESP_WIFI_PASN_SUPPORT is not set # CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# default: +# CONFIG_ESP_WIFI_BSS_MAX_IDLE_SUPPORT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10 CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 # CONFIG_ESP_WIFI_FTM_ENABLE is not set @@ -1214,6 +1884,8 @@ CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y # CONFIG_ESP_WIFI_SUITE_B_192 is not set # CONFIG_ESP_WIFI_11KV_SUPPORT is not set # CONFIG_ESP_WIFI_MBO_SUPPORT is not set +# default: +# CONFIG_ESP_WIFI_ENABLE_ROAMING_APP is not set # CONFIG_ESP_WIFI_DPP_SUPPORT is not set # CONFIG_ESP_WIFI_11R_SUPPORT is not set # CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set @@ -1223,14 +1895,198 @@ CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y # # CONFIG_ESP_WIFI_WPS_STRICT is not set # CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set +# default: +# CONFIG_ESP_WIFI_WPS_RECONNECT_ON_FAIL is not set # end of WPS Configuration Options # CONFIG_ESP_WIFI_DEBUG_PRINT is not set -# CONFIG_ESP_WIFI_TESTING_OPTIONS is not set CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y # CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set +# default: +# CONFIG_ESP_WIFI_PASSIVE_HIDDEN_AP_SUPPORT is not set +# default: +# CONFIG_ESP_WIFI_PRIVACY_ENHANCEMENTS_ENABLED is not set # end of Wi-Fi +# +# Wi-Fi Remote +# +# default: +CONFIG_ESP_WIFI_REMOTE_IN_IDF=y +# default: +CONFIG_ESP_WIFI_REMOTE_ENABLED=y +# default: +CONFIG_SLAVE_IDF_TARGET_ESP32=y +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S2 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C3 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S3 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C2 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C6 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C5 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C61 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S31 is not set +# default: +CONFIG_SLAVE_SOC_WIFI_SUPPORTED=y +# default: +CONFIG_SLAVE_SOC_WIFI_WAPI_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_CSI_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_MESH_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +# default: +CONFIG_SLAVE_SOC_WIFI_NAN_SUPPORT=y +# default: +CONFIG_SLAVE_IDF_TARGET_ARCH_XTENSA=y + +# +# Wi-Fi configuration +# +# default: +CONFIG_WIFI_RMT_STATIC_RX_BUFFER_NUM=10 +# default: +CONFIG_WIFI_RMT_DYNAMIC_RX_BUFFER_NUM=32 +# default: +# CONFIG_WIFI_RMT_STATIC_TX_BUFFER is not set +# default: +CONFIG_WIFI_RMT_DYNAMIC_TX_BUFFER=y +# default: +CONFIG_WIFI_RMT_TX_BUFFER_TYPE=1 +# default: +CONFIG_WIFI_RMT_DYNAMIC_TX_BUFFER_NUM=32 +# default: +CONFIG_WIFI_RMT_STATIC_RX_MGMT_BUFFER=y +# default: +# CONFIG_WIFI_RMT_DYNAMIC_RX_MGMT_BUFFER is not set +# default: +CONFIG_WIFI_RMT_DYNAMIC_RX_MGMT_BUF=0 +# default: +CONFIG_WIFI_RMT_RX_MGMT_BUF_NUM_DEF=5 +# default: +# CONFIG_WIFI_RMT_CSI_ENABLED is not set +# default: +CONFIG_WIFI_RMT_AMPDU_TX_ENABLED=y +# default: +CONFIG_WIFI_RMT_TX_BA_WIN=6 +# default: +CONFIG_WIFI_RMT_AMPDU_RX_ENABLED=y +# default: +CONFIG_WIFI_RMT_RX_BA_WIN=6 +# default: +CONFIG_WIFI_RMT_NVS_ENABLED=y +# default: +CONFIG_WIFI_RMT_TASK_PINNED_TO_CORE_0=y +# default: +# CONFIG_WIFI_RMT_TASK_PINNED_TO_CORE_1 is not set +# default: +CONFIG_WIFI_RMT_SOFTAP_BEACON_MAX_LEN=752 +# default: +CONFIG_WIFI_RMT_MGMT_SBUF_NUM=32 +# default: +CONFIG_WIFI_RMT_IRAM_OPT=y +# default: +# CONFIG_WIFI_RMT_EXTRA_IRAM_OPT is not set +# default: +CONFIG_WIFI_RMT_RX_IRAM_OPT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_SAE=y +# default: +CONFIG_WIFI_RMT_ENABLE_SAE_H2E=y +# default: +CONFIG_WIFI_RMT_ENABLE_SAE_PK=y +# default: +CONFIG_WIFI_RMT_SOFTAP_SAE_SUPPORT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_OWE_STA=y +# default: +CONFIG_WIFI_RMT_WPA3_COMPATIBLE_SUPPORT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_OWE_SOFTAP=y +# default: +# CONFIG_WIFI_RMT_PASN_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_SLP_IRAM_OPT is not set +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# default: +# CONFIG_WIFI_RMT_BSS_MAX_IDLE_SUPPORT is not set +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_MAX_ACTIVE_TIME=10 +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 +# default: +CONFIG_WIFI_RMT_STA_DISCONNECTED_PM_ENABLE=y +# default: +CONFIG_WIFI_RMT_GMAC_SUPPORT=y +# default: +CONFIG_WIFI_RMT_SOFTAP_SUPPORT=y +# default: +# CONFIG_WIFI_RMT_SLP_BEACON_LOST_OPT is not set +# default: +CONFIG_WIFI_RMT_ESPNOW_MAX_ENCRYPT_NUM=7 +# default: +# CONFIG_WIFI_RMT_NAN_SYNC_ENABLE is not set +# default: +CONFIG_WIFI_RMT_MBEDTLS_CRYPTO=y +# default: +CONFIG_WIFI_RMT_MBEDTLS_TLS_CLIENT=y +# default: +# CONFIG_WIFI_RMT_WAPI_PSK is not set +# default: +# CONFIG_WIFI_RMT_11KV_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_MBO_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_ENABLE_ROAMING_APP is not set +# default: +# CONFIG_WIFI_RMT_DPP_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_11R_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_WPS_SOFTAP_REGISTRAR is not set + +# +# WPS Configuration Options +# +# default: +# CONFIG_WIFI_RMT_WPS_STRICT is not set +# default: +# CONFIG_WIFI_RMT_WPS_PASSPHRASE is not set +# default: +# CONFIG_WIFI_RMT_WPS_RECONNECT_ON_FAIL is not set +# end of WPS Configuration Options + +# default: +# CONFIG_WIFI_RMT_DEBUG_PRINT is not set +# default: +CONFIG_WIFI_RMT_ENTERPRISE_SUPPORT=y +# default: +# CONFIG_WIFI_RMT_ENT_FREE_DYNAMIC_BUFFER is not set +# default: +# CONFIG_WIFI_RMT_PASSIVE_HIDDEN_AP_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_PRIVACY_ENHANCEMENTS_ENABLED is not set +# end of Wi-Fi configuration + +# default: +CONFIG_ESP_WIFI_REMOTE_LIBRARY_HOSTED=y +# default: +# CONFIG_ESP_WIFI_REMOTE_LIBRARY_EPPP is not set +# default: +# CONFIG_ESP_WIFI_REMOTE_LIBRARY_CUSTOM is not set +# default: +CONFIG_ESP_WIFI_REMOTE_EAP_ENABLED=y +# end of Wi-Fi Remote + # # Core dump # @@ -1270,15 +2126,35 @@ CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set +# default: CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y +# default: +CONFIG_FATFS_ALLOC_PREFER_ALIGNED_WORK_BUFFERS=y # CONFIG_FATFS_USE_FASTSEEK is not set +# default: +CONFIG_FATFS_USE_STRFUNC_NONE=y +# default: +# CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set +# default: +# CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 # CONFIG_FATFS_IMMEDIATE_FSYNC is not set # CONFIG_FATFS_USE_LABEL is not set CONFIG_FATFS_LINK_LOCK=y +# default: +CONFIG_FATFS_USE_DYN_BUFFERS=y + +# +# File system free space calculation behavior +# +# default: +CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 +# default: +CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 +# end of File system free space calculation behavior # end of FAT Filesystem support # @@ -1288,7 +2164,6 @@ CONFIG_FATFS_LINK_LOCK=y # # Kernel # -# CONFIG_FREERTOS_SMP is not set # CONFIG_FREERTOS_UNICORE is not set CONFIG_FREERTOS_HZ=100 # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set @@ -1300,10 +2175,13 @@ CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 # CONFIG_FREERTOS_USE_TICK_HOOK is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 # CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set +# default: +CONFIG_FREERTOS_USE_TIMERS=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y +# default: CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 @@ -1323,24 +2201,37 @@ CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y # CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set -# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set +# default: CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y CONFIG_FREERTOS_ISR_STACKSIZE=1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y +# default: +# CONFIG_FREERTOS_FPU_IN_ISR is not set +# default: CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y # CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set +# default: CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y -# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set +# default: +CONFIG_FREERTOS_IN_IRAM=y # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set # end of Port +# +# Extra +# +# end of Extra + +# default: CONFIG_FREERTOS_PORT=y +# default: CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF +# default: CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y +# default: CONFIG_FREERTOS_DEBUG_OCDAWARE=y -CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y -CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y +# default: CONFIG_FREERTOS_NUMBER_OF_CORES=2 # end of FreeRTOS @@ -1351,10 +2242,11 @@ CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y # CONFIG_HAL_ASSERTION_DISABLE is not set # CONFIG_HAL_ASSERTION_SILENT is not set # CONFIG_HAL_ASSERTION_ENABLE is not set +# default: CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 CONFIG_HAL_WDT_USE_ROM_IMPL=y -CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y -CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y +# default: +CONFIG_HAL_GPIO_USE_ROM_IMPL=y # end of Hardware Abstraction Layer (HAL) and Low Level (LL) # @@ -1373,7 +2265,17 @@ CONFIG_HEAP_TRACING_OFF=y # end of Heap memory debugging # -# Log output +# Log +# +# default: +CONFIG_LOG_VERSION_1=y +# default: +# CONFIG_LOG_VERSION_2 is not set +# default: +CONFIG_LOG_VERSION=1 + +# +# Log Level # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set @@ -1381,23 +2283,61 @@ CONFIG_HEAP_TRACING_OFF=y CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set +# default: CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y # CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set # CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set +# default: CONFIG_LOG_MAXIMUM_LEVEL=3 + +# +# Level Settings +# # CONFIG_LOG_MASTER_LEVEL is not set +# default: +CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y +# default: +# CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set +# default: +# CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set +# default: +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y +# default: +# CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set +# default: +CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y +# default: +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 +# end of Level Settings +# end of Log Level + +# +# Format +# CONFIG_LOG_COLORS=y CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set -# end of Log output +# end of Format + +# +# Settings +# +# default: +CONFIG_LOG_MODE_TEXT_EN=y +# default: +CONFIG_LOG_MODE_TEXT=y +# end of Settings + +# default: +CONFIG_LOG_IN_IRAM=y +# end of Log # # LWIP # CONFIG_LWIP_ENABLE=y CONFIG_LWIP_LOCAL_HOSTNAME="espressif" -# CONFIG_LWIP_NETIF_API is not set CONFIG_LWIP_TCPIP_TASK_PRIO=18 # CONFIG_LWIP_TCPIP_CORE_LOCKING is not set # CONFIG_LWIP_CHECK_THREAD_SAFETY is not set @@ -1407,6 +2347,8 @@ CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y +# default: +# CONFIG_LWIP_ND6_SUPPORT_STATIC_ENTRIES is not set # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set CONFIG_LWIP_MAX_SOCKETS=10 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set @@ -1421,6 +2363,8 @@ CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 +# default: +CONFIG_LWIP_IPV6_DUP_DETECT_ATTEMPTS=1 # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y @@ -1429,10 +2373,12 @@ CONFIG_LWIP_ESP_MLDV6_REPORT=y CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y +# CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set +# CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set -CONFIG_LWIP_DHCP_OPTIONS_LEN=68 +CONFIG_LWIP_DHCP_OPTIONS_LEN=69 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 @@ -1440,8 +2386,12 @@ CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 # DHCP server # CONFIG_LWIP_DHCPS=y +# default: +CONFIG_LWIP_DHCPS_REPORT_CLIENT_HOSTNAME=y CONFIG_LWIP_DHCPS_LEASE_UNIT=60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 +# default: +CONFIG_LWIP_DHCPS_MAX_HOSTNAME_LEN=64 CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y # end of DHCP server @@ -1452,6 +2402,8 @@ CONFIG_LWIP_IPV6=y CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 # CONFIG_LWIP_IPV6_FORWARD is not set # CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set +# default: +# CONFIG_LWIP_NETIF_LINK_CALLBACK is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 @@ -1500,10 +2452,19 @@ CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set +# default: CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF -# CONFIG_LWIP_PPP_SUPPORT is not set CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 +# default: +# CONFIG_LWIP_IPV6_ND6_ROUTE_INFO_OPTION_SUPPORT is not set +# CONFIG_LWIP_PPP_SUPPORT is not set # CONFIG_LWIP_SLIP_SUPPORT is not set # @@ -1533,8 +2494,14 @@ CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 # # DNS # +# default: +CONFIG_LWIP_DNS_MAX_HOST_IP=1 CONFIG_LWIP_DNS_MAX_SERVERS=3 # CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set +# default: +# CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set +# default: +# CONFIG_LWIP_USE_ESP_GETADDRINFO is not set # end of DNS CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 @@ -1555,9 +2522,19 @@ CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set +# default: +CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE=y +# default: +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_DEFAULT is not set +# default: +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_CUSTOM is not set CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set +# default: +CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y +# default: +# CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y # CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set @@ -1569,6 +2546,33 @@ CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y # # mbedTLS # + +# +# Core Configuration +# +# default: +CONFIG_MBEDTLS_VER_4_X_SUPPORT=y +# default: +# CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_NONE is not set +# default: +CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE=y +# default: +# CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_PERF is not set +# default: +CONFIG_MBEDTLS_FS_IO=y +# default: +# CONFIG_MBEDTLS_PSA_ITS_CUSTOM_STORAGE_BACKEND is not set +CONFIG_MBEDTLS_THREADING_C=y +# default: +# CONFIG_MBEDTLS_THREADING_ALT is not set +# default: +CONFIG_MBEDTLS_THREADING_PTHREAD=y +CONFIG_MBEDTLS_ERROR_STRINGS=y +# default: +CONFIG_MBEDTLS_VERSION_C=y +CONFIG_MBEDTLS_HAVE_TIME=y +# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set +# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set @@ -1576,159 +2580,257 @@ CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set +# default: +# CONFIG_MBEDTLS_VERSION_FEATURES is not set # CONFIG_MBEDTLS_DEBUG is not set +# default: +CONFIG_MBEDTLS_SELF_TEST=y +# end of Core Configuration # -# mbedTLS v3.x related +# Certificates # -# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set -# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set -# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set -# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set -CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y -CONFIG_MBEDTLS_PKCS7_C=y -# end of mbedTLS v3.x related +# default: +CONFIG_MBEDTLS_X509_USE_C=y +CONFIG_MBEDTLS_PEM_PARSE_C=y +CONFIG_MBEDTLS_PEM_WRITE_C=y +# default: +CONFIG_MBEDTLS_PK_C=y +# default: +CONFIG_MBEDTLS_PK_PARSE_C=y +# default: +CONFIG_MBEDTLS_PK_WRITE_C=y +# default: +# CONFIG_MBEDTLS_X509_REMOVE_INFO is not set +CONFIG_MBEDTLS_X509_CRL_PARSE_C=y +# default: +CONFIG_MBEDTLS_X509_CRT_PARSE_C=y +CONFIG_MBEDTLS_X509_CSR_PARSE_C=y +# default: +# CONFIG_MBEDTLS_X509_CREATE_C is not set +# default: +CONFIG_MBEDTLS_X509_RSASSA_PSS_SUPPORT=y +CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK=y +# default: +CONFIG_MBEDTLS_ASN1_PARSE_C=y +# default: +CONFIG_MBEDTLS_ASN1_WRITE_C=y +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y # -# Certificate Bundle +# Certificate Bundle Configuration # -CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE=y CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH="ca/cacert.pem" CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 -# end of Certificate Bundle +# end of Certificate Bundle Configuration -# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set -CONFIG_MBEDTLS_CMAC_C=y -CONFIG_MBEDTLS_HARDWARE_AES=y -CONFIG_MBEDTLS_AES_USE_INTERRUPT=y -CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 -CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y -CONFIG_MBEDTLS_HARDWARE_MPI=y -# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set -CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y -CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 -CONFIG_MBEDTLS_HARDWARE_SHA=y -CONFIG_MBEDTLS_ROM_MD5=y -# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set -# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set -CONFIG_MBEDTLS_HAVE_TIME=y -# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set -# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set -CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y -CONFIG_MBEDTLS_SHA512_C=y +# default: +# CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set +# default: +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_CROSS_SIGNED_VERIFY=y +# end of Certificates + +CONFIG_MBEDTLS_TLS_ENABLED=y + +# +# TLS Protocol Configuration +# +CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y +# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set +# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set +# default: +CONFIG_MBEDTLS_TLS_SERVER=y +# default: +CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set -# CONFIG_MBEDTLS_TLS_DISABLED is not set -CONFIG_MBEDTLS_TLS_SERVER=y -CONFIG_MBEDTLS_TLS_CLIENT=y -CONFIG_MBEDTLS_TLS_ENABLED=y +CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y +# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set +# default: +CONFIG_MBEDTLS_SSL_CACHE_C=y +# default: +CONFIG_MBEDTLS_SSL_ALL_ALERT_MESSAGES=y # -# TLS Key Exchange Methods +# TLS Key Exchange Configuration # # CONFIG_MBEDTLS_PSK_MODES is not set CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y -CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y -CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y -# end of TLS Key Exchange Methods +# end of TLS Key Exchange Configuration -CONFIG_MBEDTLS_SSL_RENEGOTIATION=y -CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y -# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set -# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set +# default: +CONFIG_MBEDTLS_SSL_SERVER_NAME_INDICATION=y CONFIG_MBEDTLS_SSL_ALPN=y +# default: +CONFIG_MBEDTLS_SSL_MAX_FRAGMENT_LENGTH=y +# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set +CONFIG_MBEDTLS_SSL_RENEGOTIATION=y CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y +# default: +# CONFIG_MBEDTLS_SSL_KEYING_MATERIAL_EXPORT is not set +# end of TLS Protocol Configuration + +# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set +# default: +# CONFIG_MBEDTLS_ARIA_C is not set # CONFIG_MBEDTLS_DES_C is not set -# CONFIG_MBEDTLS_BLOWFISH_C is not set -# CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CBC=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CFB=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CTR=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_OFB=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_XTS=y CONFIG_MBEDTLS_GCM_C=y # CONFIG_MBEDTLS_NIST_KW_C is not set +# default: +CONFIG_MBEDTLS_AES_ROM_TABLES=y +# default: +# CONFIG_MBEDTLS_AES_FEWER_TABLES is not set +# default: +# CONFIG_MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is not set +CONFIG_MBEDTLS_CMAC_C=y # end of Symmetric Ciphers -# CONFIG_MBEDTLS_RIPEMD160_C is not set - # -# Certificates +# Asymmetric Ciphers # -CONFIG_MBEDTLS_PEM_PARSE_C=y -CONFIG_MBEDTLS_PEM_WRITE_C=y -CONFIG_MBEDTLS_X509_CRL_PARSE_C=y -CONFIG_MBEDTLS_X509_CSR_PARSE_C=y -# end of Certificates - +# default: +CONFIG_MBEDTLS_RSA_C=y CONFIG_MBEDTLS_ECP_C=y -# CONFIG_MBEDTLS_DHM_C is not set -CONFIG_MBEDTLS_ECDH_C=y -CONFIG_MBEDTLS_ECDSA_C=y -# CONFIG_MBEDTLS_ECJPAKE_C is not set -CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y + +# +# Supported Curves +# CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y +# CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED is not set CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y +# end of Supported Curves + +# +# Elliptic Curve Ciphers Configuration +# CONFIG_MBEDTLS_ECP_NIST_OPTIM=y CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM=y -# CONFIG_MBEDTLS_POLY1305_C is not set -# CONFIG_MBEDTLS_CHACHA20_C is not set -# CONFIG_MBEDTLS_HKDF_C is not set -# CONFIG_MBEDTLS_THREADING_C is not set -CONFIG_MBEDTLS_ERROR_STRINGS=y -# end of mbedTLS +# CONFIG_MBEDTLS_DHM_C is not set +CONFIG_MBEDTLS_ECDH_C=y +# CONFIG_MBEDTLS_ECJPAKE_C is not set +CONFIG_MBEDTLS_ECDSA_C=y +# default: +CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y +# default: +CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y +CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y +# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set +# end of Elliptic Curve Ciphers Configuration +# end of Asymmetric Ciphers # -# ESP-MQTT Configurations +# Hash functions # -CONFIG_MQTT_PROTOCOL_311=y -# CONFIG_MQTT_PROTOCOL_5 is not set -CONFIG_MQTT_TRANSPORT_SSL=y -CONFIG_MQTT_TRANSPORT_WEBSOCKET=y -CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y -# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set -# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set -# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set -# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set -# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set -# CONFIG_MQTT_CUSTOM_OUTBOX is not set -# end of ESP-MQTT Configurations +# CONFIG_MBEDTLS_RIPEMD160_C is not set +# default: +CONFIG_MBEDTLS_MD_C=y +# default: +CONFIG_MBEDTLS_MD5_C=y +# default: +CONFIG_MBEDTLS_SHA1_C=y +# default: +# CONFIG_MBEDTLS_SHA224_C is not set +# default: +CONFIG_MBEDTLS_SHA256_C=y +# default: +CONFIG_MBEDTLS_SHA384_C=y +CONFIG_MBEDTLS_SHA512_C=y +# default: +# CONFIG_MBEDTLS_SHA3_C is not set +CONFIG_MBEDTLS_ROM_MD5=y +# end of Hash functions # -# Newlib +# Hardware Acceleration # -CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y -# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set -# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set -# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set -# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set -CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y -# CONFIG_NEWLIB_NANO_FORMAT is not set -CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y -# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set -# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set -# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set -# end of Newlib +CONFIG_MBEDTLS_HARDWARE_SHA=y +CONFIG_MBEDTLS_HARDWARE_MPI=y +# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set +CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y +CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 + +# +# Security hardening +# +# default: +# CONFIG_MBEDTLS_CONSTANT_TIME_PRIME_GEN is not set +# end of Security hardening + +CONFIG_MBEDTLS_HARDWARE_AES=y +# default: +# CONFIG_MBEDTLS_AES_SOFT_FALLBACK is not set +CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y +CONFIG_MBEDTLS_AES_USE_INTERRUPT=y +CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 +# default: +CONFIG_MBEDTLS_AES_HW_SMALL_DATA_LEN_OPTIM=y +# CONFIG_MBEDTLS_SECURE_ELEMENT_DRIVER_ENABLED is not set +# default: +CONFIG_MBEDTLS_HARDWARE_RSA_DS_PERIPHERAL=y +# end of Hardware Acceleration + +# +# Entropy and Random Number Generation +# +# default: +# CONFIG_MBEDTLS_ENTROPY_FORCE_SHA256 is not set +# default: +CONFIG_MBEDTLS_CTR_DRBG_C=y +# default: +CONFIG_MBEDTLS_HMAC_DRBG_C=y +# end of Entropy and Random Number Generation + +# +# Encoding/Decoding +# +# default: +CONFIG_MBEDTLS_BASE64_C=y +# default: +CONFIG_MBEDTLS_PKCS5_C=y +CONFIG_MBEDTLS_PKCS7_C=y +# default: +CONFIG_MBEDTLS_PKCS1_V15=y +# default: +CONFIG_MBEDTLS_PKCS1_V21=y +# end of Encoding/Decoding + +# +# Stream Cipher +# +# CONFIG_MBEDTLS_CHACHA20_C is not set +# end of Stream Cipher +# end of mbedTLS # # NVS @@ -1736,6 +2838,10 @@ CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_NVS_ENCRYPTION is not set # CONFIG_NVS_ASSERT_ERROR_CHECK is not set # CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set +# default: +# CONFIG_NVS_BDL_STACK is not set +# default: +# CONFIG_NVS_FLASH_VERIFY_ERASE is not set # end of NVS # @@ -1744,25 +2850,13 @@ CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_OPENTHREAD_ENABLED is not set # -# Thread Operational Dataset +# OpenThread Spinel # -CONFIG_OPENTHREAD_NETWORK_NAME="OpenThread-ESP" -CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX="fd00:db8:a0:0::/64" -CONFIG_OPENTHREAD_NETWORK_CHANNEL=15 -CONFIG_OPENTHREAD_NETWORK_PANID=0x1234 -CONFIG_OPENTHREAD_NETWORK_EXTPANID="dead00beef00cafe" -CONFIG_OPENTHREAD_NETWORK_MASTERKEY="00112233445566778899aabbccddeeff" -CONFIG_OPENTHREAD_NETWORK_PSKC="104810e2315100afd6bc9215a6bfac53" -# end of Thread Operational Dataset - -CONFIG_OPENTHREAD_XTAL_ACCURACY=130 # CONFIG_OPENTHREAD_SPINEL_ONLY is not set -CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y +# end of OpenThread Spinel -# -# Thread Address Query Config -# -# end of Thread Address Query Config +# default: +# CONFIG_OPENTHREAD_DEBUG is not set # end of OpenThread # @@ -1771,6 +2865,8 @@ CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y +# default: +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y # end of Protocomm # @@ -1782,15 +2878,28 @@ CONFIG_PTHREAD_STACK_MIN=768 CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y # CONFIG_PTHREAD_DEFAULT_CORE_0 is not set # CONFIG_PTHREAD_DEFAULT_CORE_1 is not set +# default: CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads +# +# SD Protocol Layer Configuration +# +# default: +CONFIG_SD_ENABLE_SDIO_SUPPORT=y +# default: +CONFIG_SD_READY_POLL_PERIOD_START_US=100 +# end of SD Protocol Layer Configuration + # # MMU Config # +# default: CONFIG_MMU_PAGE_SIZE_64KB=y +# default: CONFIG_MMU_PAGE_MODE="64KB" +# default: CONFIG_MMU_PAGE_SIZE=0x10000 # end of MMU Config @@ -1802,6 +2911,7 @@ CONFIG_MMU_PAGE_SIZE=0x10000 # SPI Flash behavior when brownout # CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y +# default: CONFIG_SPI_FLASH_BROWNOUT_RESET=y # end of SPI Flash behavior when brownout @@ -1815,12 +2925,18 @@ CONFIG_SPI_FLASH_BROWNOUT_RESET=y # CONFIG_SPI_FLASH_HPM_ENA is not set CONFIG_SPI_FLASH_HPM_AUTO=y # CONFIG_SPI_FLASH_HPM_DIS is not set +# default: CONFIG_SPI_FLASH_HPM_ON=y CONFIG_SPI_FLASH_HPM_DC_AUTO=y # CONFIG_SPI_FLASH_HPM_DC_DISABLE is not set -CONFIG_SPI_FLASH_SUSPEND_QVL_SUPPORTED=y # CONFIG_SPI_FLASH_AUTO_SUSPEND is not set CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 +# default: +# CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set +# default: +# CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set +# default: +CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM=y # end of Optional and Experimental Features (READ DOCS FIRST) # end of Main Flash configuration @@ -1829,7 +2945,6 @@ CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set -CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y # CONFIG_SPI_FLASH_ROM_IMPL is not set CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set @@ -1846,13 +2961,20 @@ CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 # # Auto-detect flash chips # -CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_TH_SUPPORTED=y +# default: +CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_GD_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_TH_SUPPORT_ENABLED=y CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y @@ -1937,27 +3059,6 @@ CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y # CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set # end of Unity unit testing library -# -# USB-OTG -# -CONFIG_USB_HOST_CONTROL_TRANSFER_MAX_SIZE=256 -CONFIG_USB_HOST_HW_BUFFER_BIAS_BALANCED=y -# CONFIG_USB_HOST_HW_BUFFER_BIAS_IN is not set -# CONFIG_USB_HOST_HW_BUFFER_BIAS_PERIODIC_OUT is not set - -# -# Root Hub configuration -# -CONFIG_USB_HOST_DEBOUNCE_DELAY_MS=250 -CONFIG_USB_HOST_RESET_HOLD_MS=30 -CONFIG_USB_HOST_RESET_RECOVERY_MS=30 -CONFIG_USB_HOST_SET_ADDR_RECOVERY_MS=10 -# end of Root Hub configuration - -# CONFIG_USB_HOST_ENABLE_ENUM_FILTER_CALLBACK is not set -CONFIG_USB_OTG_SUPPORTED=y -# end of USB-OTG - # # Virtual file system # @@ -1968,12 +3069,17 @@ CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y # CONFIG_VFS_SELECT_IN_RAM is not set CONFIG_VFS_SUPPORT_TERMIOS=y CONFIG_VFS_MAX_COUNT=8 +# default: +# CONFIG_VFS_SUPPRESS_CTX_DEPRECATION is not set # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # end of Host File System I/O (Semihosting) + +# default: +CONFIG_VFS_INITIALIZE_DEV_NULL=y # end of Virtual file system # @@ -1981,18 +3087,9 @@ CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y +# default: CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling - -# -# Wi-Fi Provisioning Manager -# -CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 -CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 -# CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION is not set -CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y -# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set -# end of Wi-Fi Provisioning Manager # end of Component config # CONFIG_IDF_EXPERIMENTAL_FEATURES is not set @@ -2000,6 +3097,8 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y # Deprecated options for backward compatibility # CONFIG_APP_BUILD_TYPE_ELF_RAM is not set # CONFIG_NO_BLOBS is not set +# CONFIG_APP_ROLLBACK_ENABLE is not set +# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set @@ -2007,7 +3106,6 @@ CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 -# CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set # CONFIG_FLASHMODE_QIO is not set # CONFIG_FLASHMODE_QOUT is not set @@ -2029,12 +3127,11 @@ CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set -# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set -CONFIG_ESP32_APPTRACE_DEST_NONE=y -CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y # CONFIG_EXTERNAL_COEX_ENABLE is not set # CONFIG_ESP_WIFI_EXTERNAL_COEXIST_ENABLE is not set -# CONFIG_MCPWM_ISR_IN_IRAM is not set +# CONFIG_CAM_CTLR_DVP_CAM_ISR_IRAM_SAFE is not set +# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set +# CONFIG_MCPWM_ISR_IRAM_SAFE is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y @@ -2049,6 +3146,42 @@ CONFIG_ESP32S3_RTC_CLK_SRC_INT_RC=y # CONFIG_ESP32S3_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_ESP32S3_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_ESP32S3_RTC_CLK_CAL_CYCLES=1024 +CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_BROWNOUT_DET=y +CONFIG_ESP32S3_BROWNOUT_DET=y +CONFIG_BROWNOUT_DET_LVL_SEL_7=y +CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_7=y +# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set +# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_1 is not set +CONFIG_BROWNOUT_DET_LVL=7 +CONFIG_ESP32S3_BROWNOUT_DET_LVL=7 +CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y +CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set +CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y +CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y +CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_SYSTIMER=y +CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_FRC1=y +# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set +# CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set +# CONFIG_ESP32S3_TIME_SYSCALL_USE_SYSTIMER is not set +# CONFIG_ESP32S3_TIME_SYSCALL_USE_FRC1 is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set +# CONFIG_ESP32S3_TIME_SYSCALL_USE_NONE is not set CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20 @@ -2058,13 +3191,6 @@ CONFIG_ESP32_PHY_MAX_TX_POWER=20 CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU=y CONFIG_PM_POWER_DOWN_TAGMEM_IN_LIGHT_SLEEP=y # CONFIG_ESP32S3_SPIRAM_SUPPORT is not set -# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_80 is not set -CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160=y -# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240 is not set -CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=160 -CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 -CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 -CONFIG_MAIN_TASK_STACK_SIZE=3584 CONFIG_CONSOLE_UART_DEFAULT=y # CONFIG_CONSOLE_UART_CUSTOM is not set # CONFIG_CONSOLE_UART_NONE is not set @@ -2072,6 +3198,17 @@ CONFIG_CONSOLE_UART_DEFAULT=y CONFIG_CONSOLE_UART=y CONFIG_CONSOLE_UART_NUM=0 CONFIG_CONSOLE_UART_BAUDRATE=115200 +# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_80 is not set +CONFIG_ESP32S3_DEFAULT_CPU_FREQ_160=y +# CONFIG_ESP32S3_DEFAULT_CPU_FREQ_240 is not set +CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ=160 +CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_VIA_TEE=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y +CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 +CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 +CONFIG_MAIN_TASK_STACK_SIZE=3584 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_INT_WDT_CHECK_CPU1=y @@ -2083,27 +3220,9 @@ CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set CONFIG_ESP32S3_DEBUG_OCDAWARE=y -CONFIG_BROWNOUT_DET=y -CONFIG_ESP32S3_BROWNOUT_DET=y -CONFIG_ESP32S3_BROWNOUT_DET=y -CONFIG_BROWNOUT_DET_LVL_SEL_7=y -CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_7=y -# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set -# CONFIG_ESP32S3_BROWNOUT_DET_LVL_SEL_1 is not set -CONFIG_BROWNOUT_DET_LVL=7 -CONFIG_ESP32S3_BROWNOUT_DET_LVL=7 CONFIG_IPC_TASK_STACK_SIZE=1280 CONFIG_TIMER_TASK_STACK_SIZE=3584 +# CONFIG_ESP32_APPTRACE_ENABLE is not set CONFIG_ESP32_WIFI_ENABLED=y CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 @@ -2115,8 +3234,6 @@ CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP32_WIFI_TX_BA_WIN=6 CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y -CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y -CONFIG_ESP32_WIFI_RX_BA_WIN=6 CONFIG_ESP32_WIFI_RX_BA_WIN=6 CONFIG_ESP32_WIFI_NVS_ENABLED=y CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y @@ -2138,7 +3255,33 @@ CONFIG_WPA_MBEDTLS_TLS_CLIENT=y # CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set # CONFIG_WPA_WPS_STRICT is not set # CONFIG_WPA_DEBUG_PRINT is not set -# CONFIG_WPA_TESTING_OPTIONS is not set +CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 +CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 +CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=1 +CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 +# CONFIG_ESP32_WIFI_CSI_ENABLED is not set +CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y +CONFIG_ESP32_WIFI_TX_BA_WIN=6 +CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y +CONFIG_ESP32_WIFI_RX_BA_WIN=6 +CONFIG_ESP32_WIFI_NVS_ENABLED=y +CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 +CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 +CONFIG_ESP32_WIFI_IRAM_OPT=y +CONFIG_ESP32_WIFI_RX_IRAM_OPT=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y +CONFIG_WPA_MBEDTLS_CRYPTO=y +CONFIG_WPA_MBEDTLS_TLS_CLIENT=y +# CONFIG_WPA_WAPI_PSK is not set +# CONFIG_WPA_SUITE_B_192 is not set +# CONFIG_WPA_11KV_SUPPORT is not set +# CONFIG_WPA_MBO_SUPPORT is not set +# CONFIG_WPA_DPP_SUPPORT is not set +# CONFIG_WPA_11R_SUPPORT is not set +# CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set +# CONFIG_WPA_WPS_STRICT is not set +# CONFIG_WPA_DEBUG_PRINT is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y @@ -2169,12 +3312,8 @@ CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set -CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_SYSTIMER=y -CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC_FRC1=y -# CONFIG_ESP32S3_TIME_SYSCALL_USE_RTC is not set -# CONFIG_ESP32S3_TIME_SYSCALL_USE_SYSTIMER is not set -# CONFIG_ESP32S3_TIME_SYSCALL_USE_FRC1 is not set -# CONFIG_ESP32S3_TIME_SYSCALL_USE_NONE is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 diff --git a/software/wifi/common/radio_entropy.c b/software/wifi/common/radio_entropy.c new file mode 100644 index 000000000..834e202c1 --- /dev/null +++ b/software/wifi/common/radio_entropy.c @@ -0,0 +1,392 @@ +/* + * radio_entropy.c + * + * See radio_entropy.h. Free of ESP-IDF and FreeRTOS, so that the host test tests what + * ships: everything the chip and the RTOS do goes through radio_entropy_port.h. + */ + +#include +#include "radio_entropy.h" +#include "radio_entropy_port.h" +#include "wifi_radio.h" + +#define MAX_READERS 8 + +// The gate. All of it is changed under re_port_lock() only, and a waiter polls, so that no +// state needs a wake up, and a waiter that gives up leaves nothing behind. +static struct { + int readers; + bool writer_active; + int writers_pending; + uintptr_t writer_task; + uintptr_t reader_task[MAX_READERS]; // 0 for a free slot +} gate; + +// Changed under the exclusive hold, read by anyone +static volatile entropy_source_t source = ENTROPY_NONE; + +// Changed under the exclusive hold only +static bool hw_enabled; // bootloader_random_enable() was called, and no disable since +static bool adc_off; // radio_entropy_adc_begin() switched the source off +static uint32_t adc_begin_ms; +static bool retry_pending; +static int retries_left; + +static radio_entropy_stats_t stats; + +// A line for the log, set under the exclusive hold and written after it is released: a +// holder does not touch the UART +static const char *pending_log; + +entropy_source_t entropy_source(void) +{ + return source; +} + +uint32_t entropy_epoch(void) +{ + return radio_epoch(); +} + +static bool expired(uint32_t deadline) +{ + return (int32_t)(re_port_now_ms() - deadline) >= 0; +} + +// Under re_port_lock() +static bool holds(uintptr_t me) +{ + if (gate.writer_active && (gate.writer_task == me)) { + return true; + } + for (int i = 0; i < MAX_READERS; i++) { + if (gate.reader_task[i] == me) { + return true; + } + } + return false; +} + +int radio_entropy_acquire_shared(uint32_t timeout_ms) +{ + uintptr_t me = re_port_task(); + uint32_t deadline = re_port_now_ms() + timeout_ms; + for (;;) { + re_port_lock(); + if (holds(me)) { + stats.recursion++; + re_port_unlock(); + return RE_ERR_RECURSION; + } + // A pending writer keeps new readers out, so that back to back readers + // cannot starve a radio change + if (!gate.writer_active && (gate.writers_pending == 0)) { + for (int i = 0; i < MAX_READERS; i++) { + if (gate.reader_task[i] == 0) { + gate.reader_task[i] = me; + gate.readers++; + re_port_unlock(); + return RE_OK; + } + } + } + re_port_unlock(); + if (expired(deadline)) { + re_port_lock(); + stats.busy++; + re_port_unlock(); + return RE_ERR_BUSY; + } + re_port_delay_ms(1); + } +} + +void radio_entropy_release_shared(void) +{ + uintptr_t me = re_port_task(); + re_port_lock(); + for (int i = 0; i < MAX_READERS; i++) { + if (gate.reader_task[i] == me) { + gate.reader_task[i] = 0; + gate.readers--; + break; + } + } + re_port_unlock(); +} + +static int acquire_exclusive(uint32_t timeout_ms) +{ + uintptr_t me = re_port_task(); + uint32_t deadline = re_port_now_ms() + timeout_ms; + + re_port_lock(); + if (holds(me)) { + stats.recursion++; + re_port_unlock(); + return RE_ERR_RECURSION; + } + gate.writers_pending++; + re_port_unlock(); + + for (;;) { + re_port_lock(); + if (!gate.writer_active && (gate.readers == 0)) { + gate.writer_active = true; + gate.writer_task = me; + gate.writers_pending--; + re_port_unlock(); + return RE_OK; + } + re_port_unlock(); + if (expired(deadline)) { + re_port_lock(); + gate.writers_pending--; + stats.busy++; + re_port_unlock(); + return RE_ERR_BUSY; + } + re_port_delay_ms(1); + } +} + +static void release_exclusive(void) +{ + re_port_lock(); + gate.writer_active = false; + gate.writer_task = 0; + const char *line = pending_log; + pending_log = NULL; + re_port_unlock(); + if (line) { + re_port_log("%s", line); + } +} + +bool radio_entropy_held_exclusive(void) +{ + re_port_lock(); + bool mine = gate.writer_active && (gate.writer_task == re_port_task()); + re_port_unlock(); + return mine; +} + +//---------------------------------- +// The source. Everything below runs under the exclusive hold. + +// Switches the ADC source off if it is on +static void disable_source(void) +{ + if (hw_enabled) { + re_port_random_disable(); + hw_enabled = false; + } +} + +// Only a source that reads back correctly is ENTROPY_ADC. The first attempt of a transition +// starts the retry budget; nothing else gives it back. +static void enable_source(bool first) +{ + if (first) { + retries_left = RE_RETRIES; + } + re_port_random_enable(); + hw_enabled = true; + if (re_port_random_readback()) { + source = ENTROPY_ADC; + retry_pending = false; + } else { + source = ENTROPY_NONE; + stats.readback_failures++; + retry_pending = true; + // Once the retries are spent there is nothing more to say + if (first || (retries_left > 0)) { + pending_log = "radio_entropy: ADC source readback mismatch"; + } + } +} + +void radio_entropy_init(void) +{ + if (acquire_exclusive(RE_WAIT_TRANSITION_MS) != RE_OK) { + return; + } + if (!radio_is_on() && !hw_enabled) { + enable_source(true); + } + release_exclusive(); +} + +int radio_entropy_change_begin(void) +{ + return acquire_exclusive(RE_WAIT_TRANSITION_MS); +} + +void radio_entropy_changing(bool starting) +{ + source = ENTROPY_NONE; + if (starting) { + // The radio and the ADC source do not run together + disable_source(); + } +} + +void radio_entropy_changed(bool radio_on) +{ + if (radio_on) { + source = ENTROPY_RADIO; + } else { + enable_source(true); + } +} + +void radio_entropy_change_end(void) +{ + release_exclusive(); +} + +int radio_entropy_adc_begin(uint32_t timeout_ms) +{ + int rc = acquire_exclusive(timeout_ms); + if (rc != RE_OK) { + return rc; + } + adc_begin_ms = re_port_now_ms(); + // With the radio running the RNG does not depend on the ADC, and the ADC is free as it is + adc_off = hw_enabled; + if (adc_off) { + source = ENTROPY_NONE; + disable_source(); + } + // Also with the radio on: an enable since the unit was created leaves the clock off + re_port_adc_ready(); + return RE_OK; +} + +void radio_entropy_adc_end(void) +{ + if (!radio_entropy_held_exclusive()) { + re_port_log("radio_entropy: adc_end without adc_begin"); + return; + } + if (adc_off) { + adc_off = false; + // The retries of a transition are spent once, by whoever needs them: a source that + // went bad does not get a new budget from a voltage read + bool failing = retry_pending; + if (!failing || (retries_left > 0)) { + if (failing) { + retries_left--; + stats.retries++; + } + enable_source(false); + } + } + uint32_t held = re_port_now_ms() - adc_begin_ms; + if (held > stats.adc_hold_max_ms) { + stats.adc_hold_max_ms = held; + } + release_exclusive(); +} + +void radio_entropy_poll(void) +{ + // A look without the gate; the decision is made again under it + if (!retry_pending || (retries_left <= 0) || radio_is_on()) { + return; + } + if (acquire_exclusive(RE_WAIT_RETRY_MS) != RE_OK) { + return; + } + if (retry_pending && (retries_left > 0) && !radio_is_on()) { + retries_left--; + stats.retries++; + source = ENTROPY_NONE; + disable_source(); + enable_source(false); + } + release_exclusive(); +} + +void radio_entropy_get_stats(radio_entropy_stats_t *out) +{ + re_port_lock(); + *out = stats; + re_port_unlock(); +} + +//---------------------------------- +// The answer to GET_RANDOM, and the voltage read. Here so that the host test runs them. + +int radio_entropy_serve_get_random(void *data, int size, void (*fill)(void *, size_t)) +{ + rpc_get_random_req *req = (rpc_get_random_req *)data; + rpc_get_random_resp *resp = (rpc_get_random_resp *)data; + + // The response overlays the request, so take what we need from it first + uint16_t length = (size >= (int)sizeof(rpc_get_random_req)) ? req->length : 0; + + // Clear the fixed part, padding included, so no stale buffer bytes go out + memset(&resp->esp_err, 0, sizeof(rpc_get_random_resp) - sizeof(rpc_header_t)); + if ((length == 0) || (length > RANDOM_MAX_BYTES)) { + resp->esp_err = RE_ESP_ERR_INVALID_ARG; + } else if (radio_entropy_acquire_shared(RE_WAIT_RANDOM_MS) != RE_OK) { + // A radio change or a read of the voltages holds the source. Nothing is drawn. + resp->esp_err = RPC_ERR_ENTROPY_BUSY; + } else { + uint32_t epoch = entropy_epoch(); + entropy_source_t src = entropy_source(); + resp->source = src; + if (src == ENTROPY_NONE) { + resp->esp_err = RE_ESP_ERR_INVALID_STATE; + } else { + fill(resp->data, length); + // The gate keeps the radio from changing while it is held; this is a second guard + if ((entropy_source() == ENTROPY_NONE) || (entropy_epoch() != epoch)) { + resp->source = ENTROPY_NONE; + resp->esp_err = RE_ESP_ERR_INVALID_STATE; + } else { + resp->esp_err = 0; + resp->length = length; + } + } + radio_entropy_release_shared(); + } + return sizeof(rpc_get_random_resp) + resp->length; +} + +int radio_entropy_read_adc(uint16_t *out, uint16_t *cache, bool *valid, int n, + int (*read_unit)(uint16_t *)) +{ + uint16_t fresh[16]; + if (n > 16) { + return RE_ESP_ERR_INVALID_ARG; + } + re_port_lock(); + bool have = *valid; + re_port_unlock(); + + if (radio_entropy_adc_begin(have ? RE_WAIT_ADC_MS : RE_WAIT_TRANSITION_MS) != RE_OK) { + if (!have) { + return RE_ERR_BUSY; + } + re_port_lock(); + memcpy(out, cache, n * sizeof(uint16_t)); + re_port_unlock(); + return 0; + } + int rc = read_unit(fresh); + radio_entropy_adc_end(); + + re_port_lock(); + if (rc == 0) { + memcpy(cache, fresh, n * sizeof(uint16_t)); + *valid = true; + } + have = *valid; + if (have) { + memcpy(out, cache, n * sizeof(uint16_t)); + } + re_port_unlock(); + return rc; +} diff --git a/software/wifi/common/radio_entropy.h b/software/wifi/common/radio_entropy.h new file mode 100644 index 000000000..3997d196a --- /dev/null +++ b/software/wifi/common/radio_entropy.h @@ -0,0 +1,117 @@ +/* + * radio_entropy.h + * + * What feeds the hardware RNG of the WiFi modules, with the radio on or off. + * + * esp_fill_random() gives true random numbers only while Wi-Fi runs or while the + * bootloader_random SAR ADC source is on (esp_random.h). The bootloader switches that + * source off before the application starts. So with the radio off, this enables it again + * and reads the hardware back, and only a source that read back correctly is reported as + * ENTROPY_ADC. + * + * A writer-preferring reader/writer gate keeps those transitions away from the draws: + * - shared holders: a GET_RANDOM draw, and a draw of the TLS task's handshake + * (software/wifi/tls/tls_rng_gate.c, one draw at a time); + * - exclusive holders: a radio start or stop (wifi_radio.c), a read of the voltages that + * needs the SAR ADC, and a retry of a failed readback. + * Rules for every holder: no re-acquire (it is refused, never waited for), no UART, queue + * or event-loop wait while holding, and event handlers never take the gate. + * + * Built into both ESP modules (software/wifi/raw_u64 and software/u64ctrl). The logic is + * in radio_entropy.c, the chip side in radio_entropy_esp.c, and the host test + * (target/pc/linux/radioentropy) replaces the latter. + */ + +#ifndef SOFTWARE_WIFI_COMMON_RADIO_ENTROPY_H_ +#define SOFTWARE_WIFI_COMMON_RADIO_ENTROPY_H_ + +#include +#include +#include +#include "rpc_calls.h" +#include "rpc_shared.h" // entropy_source_t; the U2+L module's rpc_calls.h does not include it + +// Results; the values are those of the esp_err_t they are passed on as (asserted in +// radio_entropy_esp.c) +#define RE_OK 0 +#define RE_ERR_BUSY 0x107 // ESP_ERR_TIMEOUT: the gate was not free in time +#define RE_ERR_RECURSION 0x103 // ESP_ERR_INVALID_STATE: the caller holds the gate already + +// esp_err_t values the GET_RANDOM answer uses (asserted in radio_entropy_esp.c) +#define RE_ESP_ERR_INVALID_ARG 0x102 +#define RE_ESP_ERR_INVALID_STATE 0x103 + +// How long a caller waits for the gate +#define RE_WAIT_RANDOM_MS 20 // a GET_RANDOM draw +#define RE_WAIT_TRANSITION_MS 5000 // a radio start or stop +#define RE_WAIT_ADC_MS 50 // the voltage read, which gives up and uses its cache +#define RE_WAIT_RETRY_MS 50 + +// Readback attempts after the first one failed, per transition +#define RE_RETRIES 3 + +// The source now feeding the RNG, and a count of the radio's stops so far +entropy_source_t entropy_source(void); +uint32_t entropy_epoch(void); + +// Once, after wifi_init() and before the first RPC is served. The U64 module starts with +// its radio off, so it enables the ADC source here; a boot that started the radio does not. +void radio_entropy_init(void); + +// Around every radio start and stop, by wifi_radio.c only. begin takes the gate +// exclusively: RE_OK, RE_ERR_BUSY or RE_ERR_RECURSION. changing() is called when the +// radio is about to change: the source goes off for the change. changed() gives the state +// the radio is in afterwards: ENTROPY_RADIO when on, else the ADC source, read back. end +// releases the gate. +int radio_entropy_change_begin(void); +void radio_entropy_changing(bool starting); +void radio_entropy_changed(bool radio_on); +void radio_entropy_change_end(void); + +// Shared hold of the gate. Returns RE_OK, RE_ERR_BUSY after timeout_ms, or +// RE_ERR_RECURSION. Every RE_OK is matched by one release by the same task. +int radio_entropy_acquire_shared(uint32_t timeout_ms); +void radio_entropy_release_shared(void); + +// Exclusive hold around a use of the SAR ADC1 by someone else (the voltage read). Takes +// the gate, and switches the ADC source off if it is on. The end enables the source again +// and reads it back. RE_OK or RE_ERR_BUSY. +int radio_entropy_adc_begin(uint32_t timeout_ms); +void radio_entropy_adc_end(void); + +// True while the calling task holds the gate exclusively +bool radio_entropy_held_exclusive(void); + +// The whole of a GET_RANDOM answer, up to its transmission: data is the request on the way +// in (size bytes) and the answer on the way out, whose size is returned. fill is +// esp_fill_random(). The gate is held shared for the draw only and is free when this +// returns, so the caller transmits with it released. +int radio_entropy_serve_get_random(void *data, int size, void (*fill)(void *, size_t)); + +// Reads n voltages with the SAR ADC lent out for the read (radio_entropy_adc_begin), through +// read_unit, which returns 0 or an error. cache holds the last good values, and *valid says +// it does. When the ADC is not free in time the cache is given, never zeros; while there is +// no cache yet, the wait is as long as a radio change's. Returns 0, or an error when there +// is nothing to give: out is then left alone. +int radio_entropy_read_adc(uint16_t *out, uint16_t *cache, bool *valid, int n, + int (*read_unit)(uint16_t *)); + +// Retries a failed readback, at most RE_RETRIES times per transition. Call it about every +// 10 s from a task that may wait. +void radio_entropy_poll(void); + +// The chip side, radio_entropy_esp.c only: a task for radio_entropy_poll(), for a module +// that has no loop of its own +void radio_entropy_start_poll_task(void); + +typedef struct { + uint32_t readback_failures; // enables whose readback did not match + uint32_t retries; // attempts made by radio_entropy_poll() + uint32_t recursion; // acquires refused + uint32_t busy; // acquires that timed out + uint32_t adc_hold_max_ms; // longest radio_entropy_adc_begin() to _end() +} radio_entropy_stats_t; + +void radio_entropy_get_stats(radio_entropy_stats_t *stats); + +#endif /* SOFTWARE_WIFI_COMMON_RADIO_ENTROPY_H_ */ diff --git a/software/wifi/common/radio_entropy_esp.c b/software/wifi/common/radio_entropy_esp.c new file mode 100644 index 000000000..e25f86b4c --- /dev/null +++ b/software/wifi/common/radio_entropy_esp.c @@ -0,0 +1,151 @@ +/* + * radio_entropy_esp.c + * + * The chip side of radio_entropy.c, for the ESP32 (software/wifi/raw_u64) and the + * ESP32-S3 (software/u64ctrl). + */ + +#include +#include +#include "sdkconfig.h" +#include "esp_err.h" +#include "esp_idf_version.h" +#include "esp_log.h" +#include "esp_timer.h" +#include "bootloader_random.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/timers.h" +#include "soc/soc.h" +#include "esp_private/periph_ctrl.h" +#if CONFIG_IDF_TARGET_ESP32S3 +#include "soc/apb_saradc_reg.h" +#include "soc/system_reg.h" +#include "soc/sens_reg.h" +#elif CONFIG_IDF_TARGET_ESP32 +#include "soc/dport_access.h" +#include "soc/dport_reg.h" +#include "soc/i2s_reg.h" +#include "soc/sens_reg.h" +#else +#error "radio_entropy: no readback for this chip" +#endif +#include "radio_entropy.h" +#include "radio_entropy_port.h" + +_Static_assert(RE_ERR_BUSY == ESP_ERR_TIMEOUT, "RE_ERR_BUSY is an esp_err_t"); +_Static_assert(RE_ERR_RECURSION == ESP_ERR_INVALID_STATE, "RE_ERR_RECURSION is an esp_err_t"); +_Static_assert(RE_ESP_ERR_INVALID_ARG == ESP_ERR_INVALID_ARG, "an esp_err_t"); +_Static_assert(RE_ESP_ERR_INVALID_STATE == ESP_ERR_INVALID_STATE, "an esp_err_t"); + +// On ESP-IDF 5 the S3's bootloader_random_disable() leaves the SAR ADC's digital block in +// reset, so that every later enable fails its readback (measured on the S3 with 5.3.1), +// and it writes the SAR power force behind the reference count that the PHY and the ADC +// driver share. ESP-IDF 6 does neither, and the module is built with it. +#if CONFIG_IDF_TARGET_ESP32S3 && (ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(6, 0, 0)) +#error "radio_entropy: the ESP32-S3 needs ESP-IDF 6 for the SAR ADC source" +#endif + +static const char *TAG = "radio_entropy"; + +static portMUX_TYPE lock_mux = portMUX_INITIALIZER_UNLOCKED; + +void re_port_lock(void) +{ + portENTER_CRITICAL(&lock_mux); +} + +void re_port_unlock(void) +{ + portEXIT_CRITICAL(&lock_mux); +} + +uint32_t re_port_now_ms(void) +{ + return (uint32_t)(esp_timer_get_time() / 1000); +} + +void re_port_delay_ms(uint32_t ms) +{ + TickType_t ticks = pdMS_TO_TICKS(ms); + vTaskDelay(ticks ? ticks : 1); +} + +uintptr_t re_port_task(void) +{ + return (uintptr_t)xTaskGetCurrentTaskHandle(); +} + +void re_port_random_enable(void) +{ + bootloader_random_enable(); +} + +void re_port_random_disable(void) +{ + bootloader_random_disable(); +} + +void re_port_adc_ready(void) +{ +#if CONFIG_IDF_TARGET_ESP32S3 + // The same register and lock as the ADC driver's own claim (adc_apb_periph_claim()) + PERIPH_RCC_ATOMIC() { + SET_PERI_REG_MASK(SYSTEM_PERIP_CLK_EN0_REG, SYSTEM_APB_SARADC_CLK_EN); + } +#endif +} + +// The registers that bootloader_random_enable() sets, on both ESP-IDF versions +bool re_port_random_readback(void) +{ +#if CONFIG_IDF_TARGET_ESP32S3 + return ((REG_READ(APB_SARADC_CTRL2_REG) & APB_SARADC_TIMER_EN) != 0) && + ((REG_READ(SENS_SAR_MEAS1_MUX_REG) & SENS_SAR1_DIG_FORCE) != 0); +#else + return ((REG_READ(SENS_SAR_START_FORCE_REG) & SENS_SAR2_EN_TEST) != 0) && + ((REG_READ(I2S_CONF_REG(0)) & I2S_RX_START) != 0) && + ((DPORT_REG_READ(DPORT_PERIP_CLK_EN_REG) & DPORT_I2S0_CLK_EN) != 0); +#endif +} + +void re_port_log(const char *fmt, ...) +{ + char line[96]; + va_list args; + va_start(args, fmt); + vsnprintf(line, sizeof(line), fmt, args); + va_end(args); + ESP_LOGW(TAG, "%s", line); +} + +//---------------------------------- +// radio_entropy_poll() every 10 s, for the module that has no loop of its own. The timer +// only notifies; the task takes the gate. + +static TaskHandle_t poll_task; + +static void poll_timer(TimerHandle_t timer) +{ + xTaskNotifyGive(poll_task); +} + +static void poll_loop(void *arg) +{ + for (;;) { + ulTaskNotifyTake(pdTRUE, portMAX_DELAY); + radio_entropy_poll(); + } +} + +void radio_entropy_start_poll_task(void) +{ + if (xTaskCreate(poll_loop, "re_poll", 3072, NULL, 1, &poll_task) != pdPASS) { + ESP_LOGE(TAG, "no poll task"); + return; + } + TimerHandle_t timer = xTimerCreate("re_poll", pdMS_TO_TICKS(10000), pdTRUE, NULL, poll_timer); + if (!timer || (xTimerStart(timer, 0) != pdPASS)) { + ESP_LOGE(TAG, "no poll timer"); + } +} diff --git a/software/wifi/common/radio_entropy_port.h b/software/wifi/common/radio_entropy_port.h new file mode 100644 index 000000000..48cd63fe9 --- /dev/null +++ b/software/wifi/common/radio_entropy_port.h @@ -0,0 +1,34 @@ +/* + * radio_entropy_port.h + * + * What radio_entropy.c needs from the chip and the RTOS. radio_entropy_esp.c implements + * it for the modules; the host test implements it with recording stubs. + */ + +#ifndef SOFTWARE_WIFI_COMMON_RADIO_ENTROPY_PORT_H_ +#define SOFTWARE_WIFI_COMMON_RADIO_ENTROPY_PORT_H_ + +#include +#include + +// A short critical section, never blocking, never held across any other call +void re_port_lock(void); +void re_port_unlock(void); + +uint32_t re_port_now_ms(void); +void re_port_delay_ms(uint32_t ms); // at least one RTOS tick +uintptr_t re_port_task(void); // never 0 + +void re_port_random_enable(void); // bootloader_random_enable() +void re_port_random_disable(void); // bootloader_random_disable() +bool re_port_random_readback(void); // the registers it sets are set + +// Before every use of the SAR ADC1 by the voltage read. ESP32-S3: bootloader_random_enable() +// pulses the SAR ADC's reset and leaves its bus clock off, behind the reference count of the +// oneshot ADC driver, which set the clock on when it created its unit and does not set it +// again; this sets it on again. Nothing on the classic ESP32. +void re_port_adc_ready(void); + +void re_port_log(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +#endif /* SOFTWARE_WIFI_COMMON_RADIO_ENTROPY_PORT_H_ */ diff --git a/software/wifi/common/rpc_shared.h b/software/wifi/common/rpc_shared.h new file mode 100644 index 000000000..045ca6d67 --- /dev/null +++ b/software/wifi/common/rpc_shared.h @@ -0,0 +1,67 @@ +/* + * rpc_shared.h + * + * What the Ultimate and the WiFi modules of the Ultimate 64 (software/wifi/raw_u64) + * and of the Ultimate 64 Elite II and C64 Ultimate (software/u64ctrl) must agree + * on, in one place. Included by each module's + * rpc_calls.h, after rpc_header_t, and by the Ultimate through it. + */ + +#ifndef SOFTWARE_WIFI_COMMON_RPC_SHARED_H_ +#define SOFTWARE_WIFI_COMMON_RPC_SHARED_H_ + +#include +#include + +// The Nios updater is still built as C++98 +#if defined(__cplusplus) && (__cplusplus < 201103L) +#define RPC_CONCAT_(a, b) a ## b +#define RPC_CONCAT(a, b) RPC_CONCAT_(a, b) +#define RPC_STATIC_ASSERT(cond, msg) typedef char RPC_CONCAT(rpc_assert_, __LINE__)[(cond) ? 1 : -1] +#elif defined(__cplusplus) +#define RPC_STATIC_ASSERT static_assert +#else +#define RPC_STATIC_ASSERT _Static_assert +#endif + +//---------------------------------- +// hardware random bytes +#define CMD_GET_RANDOM 0x20 // u64ctrl's own commands run from 0x13 and may reach 0x1F; kept apart so the maps agree +#define RANDOM_MAX_BYTES 512 + +typedef enum { + ENTROPY_NONE = 0, // RNG not fed by a live entropy source; no bytes are returned + ENTROPY_RADIO = 1, // Wi-Fi is running, so the RNG gives true random numbers + ENTROPY_ADC = 2, // Wi-Fi is off, and the bootloader_random SAR ADC source feeds the RNG +} entropy_source_t; + +// esp_err of a GET_RANDOM answer that was not given because a radio change, or a read of +// the voltages, holds the entropy source. Nothing was drawn; asking again is safe. Equal +// to ESP_ERR_TIMEOUT, which each module asserts. +#define RPC_ERR_ENTROPY_BUSY 0x107 + +typedef struct { + rpc_header_t hdr; + uint16_t length; +} rpc_get_random_req; + +typedef struct { + rpc_header_t hdr; + int esp_err; // to be casted to esp_err_t + uint8_t source; // to be casted to entropy_source_t + uint16_t length; + uint8_t data[]; // sizeof() excludes it, so it is exactly the header size +} rpc_get_random_resp; + +// The Ultimate decodes these by offset: a layout change must break the build, +// on every compiler that includes this, not the wire +RPC_STATIC_ASSERT(sizeof(rpc_get_random_req) == 6, "rpc_get_random_req changed"); +RPC_STATIC_ASSERT(offsetof(rpc_get_random_req, length) == 4, "rpc_get_random_req changed"); +RPC_STATIC_ASSERT(sizeof(rpc_get_random_resp) == 12, "rpc_get_random_resp changed"); +RPC_STATIC_ASSERT(offsetof(rpc_get_random_resp, esp_err) == 4, "rpc_get_random_resp changed"); +RPC_STATIC_ASSERT(offsetof(rpc_get_random_resp, source) == 8, "rpc_get_random_resp changed"); +RPC_STATIC_ASSERT(offsetof(rpc_get_random_resp, length) == 10, "rpc_get_random_resp changed"); +RPC_STATIC_ASSERT(offsetof(rpc_get_random_resp, data) == 12, "rpc_get_random_resp changed"); +RPC_STATIC_ASSERT(ENTROPY_NONE == 0, "ENTROPY_NONE changed"); + +#endif /* SOFTWARE_WIFI_COMMON_RPC_SHARED_H_ */ diff --git a/software/wifi/common/wifi_radio.c b/software/wifi/common/wifi_radio.c index 29954c952..004d4f4ce 100644 --- a/software/wifi/common/wifi_radio.c +++ b/software/wifi/common/wifi_radio.c @@ -6,35 +6,59 @@ #include "wifi_radio.h" #include "wifi_radio_port.h" +#include "radio_entropy.h" // Written by the task that starts and stops the radio, read by any static volatile bool radio_on = false; +static volatile uint32_t epoch = 0; bool radio_is_on(void) { return radio_on; } +uint32_t radio_epoch(void) +{ + return epoch; +} + +// Every change runs under the exclusive hold of the entropy gate, which also switches the +// RNG's source between the radio and the SAR ADC (radio_entropy.h) int radio_start(void) { - if (radio_on) { - return 0; + int rc = radio_entropy_change_begin(); + if (rc != 0) { + return rc; } - int rc = wr_port_wifi_start(); - if (rc == 0) { - radio_on = true; + if (!radio_on) { + radio_entropy_changing(true); + rc = wr_port_wifi_start(); + if (rc == 0) { + radio_on = true; + } + radio_entropy_changed(radio_on); } + radio_entropy_change_end(); return rc; } int radio_stop(void) { - if (!radio_on) { - return 0; + int rc = radio_entropy_change_begin(); + if (rc != 0) { + return rc; } - int rc = wr_port_wifi_stop(); - if (rc == 0) { + if (radio_on) { + // A GET_RANDOM draw that overlaps the stop must not count as drawn with the radio on + epoch++; radio_on = false; + radio_entropy_changing(false); + rc = wr_port_wifi_stop(); + if (rc != 0) { + radio_on = true; + } + radio_entropy_changed(radio_on); } + radio_entropy_change_end(); return rc; } diff --git a/software/wifi/common/wifi_radio.h b/software/wifi/common/wifi_radio.h index 8a5274206..b81575d65 100644 --- a/software/wifi/common/wifi_radio.h +++ b/software/wifi/common/wifi_radio.h @@ -14,15 +14,21 @@ #define SOFTWARE_WIFI_COMMON_WIFI_RADIO_H_ #include +#include // Both are idempotent: asking for the state the radio is in already does nothing and // returns 0. Otherwise they return 0 or the esp_err_t of the start or stop, and a failed // call leaves the state as it was. Called by one task at a time (the boot, then the -// connector). +// connector). They also return the radio_entropy.h gate's RE_ERR_BUSY or +// RE_ERR_RECURSION, and change nothing then. int radio_start(void); int radio_stop(void); -// True from a successful start until a successful stop +// True from a successful start until a stop begins: while a stop runs the radio no +// longer counts as on, and a stop that fails makes it count again bool radio_is_on(void); +// The number of stops begun so far, so that a caller can tell the radio went off under it +uint32_t radio_epoch(void); + #endif /* SOFTWARE_WIFI_COMMON_WIFI_RADIO_H_ */ diff --git a/software/wifi/raw_c3/CMakeLists.txt b/software/wifi/raw_c3/CMakeLists.txt index a8abcf637..8856ac62d 100644 --- a/software/wifi/raw_c3/CMakeLists.txt +++ b/software/wifi/raw_c3/CMakeLists.txt @@ -1,6 +1,9 @@ # The following lines of boilerplate have to be in your project's CMakeLists # in this exact order for cmake to work correctly -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) include($ENV{IDF_PATH}/tools/cmake/project.cmake) +if(IDF_VERSION_MAJOR LESS 6) + message(FATAL_ERROR "raw_c3 needs ESP-IDF 6, not ${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR} (see software/wifi/raw_c3/README.md)") +endif() project(bridge) diff --git a/software/wifi/raw_c3/README.md b/software/wifi/raw_c3/README.md index dec4d5ebb..ae062b616 100644 --- a/software/wifi/raw_c3/README.md +++ b/software/wifi/raw_c3/README.md @@ -1,4 +1,24 @@ -# Wifi SCAN Example +# ESP32-C3 WiFi bridge (raw_c3) + +The WiFi module of the U2+L. + +## Building + +The bridge needs ESP-IDF 6 (CI uses v6.1.1); `CMakeLists.txt` stops an older one at configure. +`docker/Dockerfile` still installs ESP-IDF 5.3.1, so CI builds this project (and raw_u64 and u64ctrl) in +`espressif/idf:v6.1.1`, pinned by digest in `.github/workflows/build.yml`. Locally, from the top of the +repository, the same way as CI: + + docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -v "$PWD":/project -w /project/software/wifi/raw_c3 \ + espressif/idf:v6.1.1@sha256:2b4f966c37eaedc19542b0637a5f850b2eff9478d8e858192aa0073d92c2dc91 idf.py build + +then `make u2pl_no_esp` packs `build/bridge.bin` into the update file. `make esp32_raw_c3` (and so +`make u2pl`) works only where `IDF_PATH` is an ESP-IDF 6. Once `build/` exists here, `make clean` also +needs ESP-IDF 6; otherwise delete `software/wifi/raw_c3/build` by hand. + +`sdkconfig` marks values that follow ESP-IDF's defaults with `# default:`; a reconfigure on a newer +ESP-IDF takes its new defaults there. After any ESP-IDF update, diff the values, not just the build. + This example shows how to use the scan functionality of the Wi-Fi driver of ESP32. diff --git a/software/wifi/raw_c3/main/CMakeLists.txt b/software/wifi/raw_c3/main/CMakeLists.txt index 2400eeadf..a9393b4ce 100644 --- a/software/wifi/raw_c3/main/CMakeLists.txt +++ b/software/wifi/raw_c3/main/CMakeLists.txt @@ -1,4 +1,5 @@ set(EXTERNAL "../../../io/uart") set(COMMON "../../common") -idf_component_register(SRCS "main.c" "my_uart.c" "rpc_dispatch.c" "dump_hex.c" "wifi_modem.c" "sntp.c" ${EXTERNAL}/cmd_buffer.c ${COMMON}/wifi_radio.c ${COMMON}/wifi_radio_esp.c ${COMMON}/radio_boot.c - INCLUDE_DIRS "." ${EXTERNAL} ${COMMON}) \ No newline at end of file +idf_component_register(SRCS "main.c" "my_uart.c" "rpc_dispatch.c" "dump_hex.c" "wifi_modem.c" "sntp.c" ${EXTERNAL}/cmd_buffer.c ${COMMON}/wifi_radio.c ${COMMON}/wifi_radio_esp.c ${COMMON}/radio_boot.c "radio_entropy_none.c" + INCLUDE_DIRS "." ${EXTERNAL} ${COMMON} + LDFRAGMENTS "linker.lf") diff --git a/software/wifi/raw_c3/main/linker.lf b/software/wifi/raw_c3/main/linker.lf new file mode 100644 index 000000000..9cf1c705d --- /dev/null +++ b/software/wifi/raw_c3/main/linker.lf @@ -0,0 +1,42 @@ +[mapping:raw_c3_hot] +archive: libmain.a +entries: + my_uart (noflash) + cmd_buffer (noflash) + wifi_modem:hacked_recv (noflash) + rpc_dispatch:dispatch (noflash) + rpc_dispatch:cmd_send_eth_packet (noflash) + +[mapping:raw_c3_netif] +archive: libesp_netif.a +entries: + esp_netif_lwip:esp_netif_transmit (noflash) + esp_netif_lwip:esp_netif_receive (noflash) + esp_netif_lwip:esp_netif_free_rx_buffer (noflash) + wlanif:wlanif_input (noflash) + esp_pbuf_ref:esp_pbuf_allocate (noflash) + esp_pbuf_ref:esp_pbuf_free (noflash) + +[mapping:raw_c3_wifi_netif] +archive: libesp_wifi.a +entries: + wifi_netif:wifi_transmit (noflash) + wifi_netif:wifi_free (noflash) + +[mapping:raw_c3_pp] +archive: libpp.a +entries: + if_hwctrl:esp_wifi_internal_free_rx_buffer (noflash) + +[mapping:raw_c3_lwip] +archive: liblwip.a +entries: + pbuf:pbuf_free (noflash) + pbuf:pbuf_alloced_custom (noflash) + pbuf:pbuf_init_alloced_pbuf (noflash) + mem:mem_malloc (noflash) + mem:mem_free (noflash) + sys_arch:sys_arch_protect (noflash) + sys_arch:sys_arch_unprotect (noflash) + sys_arch:sys_mutex_lock (noflash) + sys_arch:sys_mutex_unlock (noflash) diff --git a/software/wifi/raw_c3/main/my_uart.c b/software/wifi/raw_c3/main/my_uart.c index 3dadc9529..99a15f869 100644 --- a/software/wifi/raw_c3/main/my_uart.c +++ b/software/wifi/raw_c3/main/my_uart.c @@ -23,7 +23,7 @@ #include "freertos/ringbuf.h" #include "hal/uart_hal.h" #include "hal/gpio_hal.h" -#include "soc/uart_periph.h" +#include "hal/uart_periph.h" #include "soc/rtc_cntl_reg.h" #include "driver/uart.h" #include "driver/gpio.h" @@ -368,7 +368,7 @@ BaseType_t my_uart_get_buffer(uint8_t uart_num, command_buf_t **buf, TickType_t } #include "esp_check.h" -esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, int intr_alloc_flags, uart_isr_handle_t *handle) +esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, int intr_alloc_flags, intr_handle_t *handle) { int ret; ESP_RETURN_ON_FALSE((uart_num < UART_NUM_MAX), ESP_FAIL, UART_TAG, "uart_num error"); diff --git a/software/wifi/raw_c3/main/radio_entropy_none.c b/software/wifi/raw_c3/main/radio_entropy_none.c new file mode 100644 index 000000000..fb91ef94e --- /dev/null +++ b/software/wifi/raw_c3/main/radio_entropy_none.c @@ -0,0 +1,26 @@ +/* + * radio_entropy_none.c + * + * The U2+L module does not serve GET_RANDOM, so it has no entropy source to switch when + * wifi_radio.c starts or stops the radio: its hooks do nothing here. + */ + +#include +#include "radio_entropy.h" + +int radio_entropy_change_begin(void) +{ + return RE_OK; +} + +void radio_entropy_changing(bool starting) +{ +} + +void radio_entropy_changed(bool radio_on) +{ +} + +void radio_entropy_change_end(void) +{ +} diff --git a/software/wifi/raw_c3/main/rpc_dispatch.h b/software/wifi/raw_c3/main/rpc_dispatch.h index 0cc791bde..b95891392 100644 --- a/software/wifi/raw_c3/main/rpc_dispatch.h +++ b/software/wifi/raw_c3/main/rpc_dispatch.h @@ -24,8 +24,11 @@ void start_dispatch(QueueHandle_t queue); void send_button_event(uint8_t button); void send_keepalive(); -#define IDENT_STRING "ESP32 WiFi Bridge V1.11" +#define IDENT_STRING "ESP32 WiFi Bridge V1.14" #define IDENT_MAJOR 1 +// 1.14: starts and stops the radio under the entropy gate of wifi_radio.c, which this module +// does not use (radio_entropy_none.c). +// 1.13: built with ESP-IDF 6.1.1. Labels the image; the U2+L updater does not compare it. // 1.11: the idle connector handles every queued command and event before it waits, so a // Disable behind an Enable is not left queued; the wait for its own disconnect is bounded // (3 s); events from before a radio stop are dropped; a CMD_WIFI_CONNECT must hold the @@ -42,7 +45,7 @@ void send_keepalive(); // Disconnected forever. The Ultimate's updater only reflashes the module // when this differs from what the module reports, so a module change that // does not bump it is silently never installed. -#define IDENT_MINOR 11 +#define IDENT_MINOR 14 #define MULTITHREADED 0 #define DISPATCHER_STACK 3072 diff --git a/software/wifi/raw_c3/main/wifi_modem.c b/software/wifi/raw_c3/main/wifi_modem.c index 35c6bc84f..69015b92e 100644 --- a/software/wifi/raw_c3/main/wifi_modem.c +++ b/software/wifi/raw_c3/main/wifi_modem.c @@ -147,7 +147,8 @@ static err_t hacked_recv(struct pbuf *p, struct netif *inp) return ERR_OK; } else { ESP_LOGW(TAG, "No buffer to send packet."); - return ERR_BUF; + pbuf_free(p); // dropped, and reported as handled + return ERR_OK; } } else { // dropped, wrong mac and no broadcast pbuf_free(p); diff --git a/software/wifi/raw_c3/sdkconfig b/software/wifi/raw_c3/sdkconfig index fccff6441..4bcdd124b 100644 --- a/software/wifi/raw_c3/sdkconfig +++ b/software/wifi/raw_c3/sdkconfig @@ -1,290 +1,494 @@ # # Automatically generated file. DO NOT EDIT. -# Espressif IoT Development Framework (ESP-IDF) 5.3.1 Project Configuration +# Espressif IoT Development Framework (ESP-IDF) 6.1.1 Project Configuration # +# default: CONFIG_SOC_ADC_SUPPORTED=y +# default: CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y +# default: CONFIG_SOC_UART_SUPPORTED=y +# default: CONFIG_SOC_GDMA_SUPPORTED=y +# default: +CONFIG_SOC_UHCI_SUPPORTED=y +# default: CONFIG_SOC_AHB_GDMA_SUPPORTED=y +# default: CONFIG_SOC_GPTIMER_SUPPORTED=y +# default: CONFIG_SOC_TWAI_SUPPORTED=y +# default: CONFIG_SOC_BT_SUPPORTED=y +# default: CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y +# default: CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y +# default: CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y +# default: CONFIG_SOC_XT_WDT_SUPPORTED=y +# default: CONFIG_SOC_PHY_SUPPORTED=y +# default: CONFIG_SOC_WIFI_SUPPORTED=y +# default: CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y +# default: CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y +# default: CONFIG_SOC_EFUSE_HAS_EFUSE_RST_BUG=y +# default: CONFIG_SOC_EFUSE_SUPPORTED=y +# default: CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y +# default: CONFIG_SOC_RTC_MEM_SUPPORTED=y +# default: +CONFIG_SOC_RTC_TIMER_SUPPORTED=y +# default: CONFIG_SOC_I2S_SUPPORTED=y +# default: CONFIG_SOC_RMT_SUPPORTED=y +# default: CONFIG_SOC_SDM_SUPPORTED=y +# default: CONFIG_SOC_GPSPI_SUPPORTED=y +# default: CONFIG_SOC_LEDC_SUPPORTED=y +# default: CONFIG_SOC_I2C_SUPPORTED=y +# default: CONFIG_SOC_SYSTIMER_SUPPORTED=y +# default: CONFIG_SOC_SUPPORT_COEXISTENCE=y +# default: CONFIG_SOC_AES_SUPPORTED=y +# default: CONFIG_SOC_MPI_SUPPORTED=y +# default: CONFIG_SOC_SHA_SUPPORTED=y +# default: CONFIG_SOC_HMAC_SUPPORTED=y +# default: CONFIG_SOC_DIG_SIGN_SUPPORTED=y +# default: CONFIG_SOC_FLASH_ENC_SUPPORTED=y +# default: CONFIG_SOC_SECURE_BOOT_SUPPORTED=y +# default: CONFIG_SOC_MEMPROT_SUPPORTED=y +# default: CONFIG_SOC_BOD_SUPPORTED=y +# default: CONFIG_SOC_CLK_TREE_SUPPORTED=y +# default: +CONFIG_SOC_REGI2C_SUPPORTED=y +# default: CONFIG_SOC_ASSIST_DEBUG_SUPPORTED=y +# default: CONFIG_SOC_WDT_SUPPORTED=y +# default: +CONFIG_SOC_RTC_WDT_SUPPORTED=y +# default: CONFIG_SOC_SPI_FLASH_SUPPORTED=y +# default: CONFIG_SOC_RNG_SUPPORTED=y +# default: CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y +# default: CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y +# default: CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y +# default: CONFIG_SOC_PM_SUPPORTED=y +# default: +CONFIG_SOC_SPI_EXTERNAL_NOR_FLASH_SUPPORTED=y +# default: CONFIG_SOC_XTAL_SUPPORT_40M=y +# default: CONFIG_SOC_AES_SUPPORT_DMA=y +# default: CONFIG_SOC_AES_GDMA=y +# default: CONFIG_SOC_AES_SUPPORT_AES_128=y +# default: CONFIG_SOC_AES_SUPPORT_AES_256=y +# default: CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y +# default: CONFIG_SOC_ADC_ARBITER_SUPPORTED=y +# default: CONFIG_SOC_ADC_DIG_IIR_FILTER_SUPPORTED=y +# default: CONFIG_SOC_ADC_MONITOR_SUPPORTED=y +# default: CONFIG_SOC_ADC_DMA_SUPPORTED=y +# default: CONFIG_SOC_ADC_PERIPH_NUM=2 +# default: CONFIG_SOC_ADC_MAX_CHANNEL_NUM=5 +# default: CONFIG_SOC_ADC_ATTEN_NUM=4 +# default: CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=1 +# default: CONFIG_SOC_ADC_PATT_LEN_MAX=8 +# default: CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12 +# default: CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 +# default: CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4 +# default: CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 +# default: CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2 +# default: CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2 +# default: CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333 +# default: CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611 +# default: CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12 +# default: CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 +# default: CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y +# default: CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y +# default: CONFIG_SOC_ADC_SHARED_POWER=y +# default: CONFIG_SOC_APB_BACKUP_DMA=y +# default: CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y +# default: CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y +# default: +CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y +# default: CONFIG_SOC_CACHE_MEMORY_IBANK_SIZE=0x4000 +# default: CONFIG_SOC_CPU_CORES_NUM=1 +# default: CONFIG_SOC_CPU_INTR_NUM=32 +# default: CONFIG_SOC_CPU_HAS_FLEXIBLE_INTC=y +# default: CONFIG_SOC_CPU_HAS_CSR_PC=y +# default: CONFIG_SOC_CPU_BREAKPOINTS_NUM=8 +# default: CONFIG_SOC_CPU_WATCHPOINTS_NUM=8 +# default: CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x80000000 +# default: CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=3072 +# default: CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16 +# default: CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100 +# default: CONFIG_SOC_AHB_GDMA_VERSION=1 -CONFIG_SOC_GDMA_NUM_GROUPS_MAX=1 -CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=3 +# default: CONFIG_SOC_GPIO_PORT=1 +# default: CONFIG_SOC_GPIO_PIN_COUNT=22 +# default: CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y -CONFIG_SOC_GPIO_FILTER_CLK_SUPPORT_APB=y +# default: CONFIG_SOC_GPIO_SUPPORT_FORCE_HOLD=y -CONFIG_SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP=y +# default: +CONFIG_SOC_GPIO_SUPPORT_HP_PERIPH_PD_SLEEP_WAKEUP=y +# default: CONFIG_SOC_GPIO_IN_RANGE_MAX=21 +# default: CONFIG_SOC_GPIO_OUT_RANGE_MAX=21 -CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_VALID_GPIO_MASK=0 -CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_SUPPORTED_PIN_CNT=6 +# default: +CONFIG_SOC_GPIO_HP_PERIPH_PD_SLEEP_WAKEABLE_MASK=0 +# default: CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0x00000000003FFFC0 +# default: CONFIG_SOC_GPIO_CLOCKOUT_BY_GPIO_MATRIX=y +# default: CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=3 -CONFIG_SOC_DEDIC_GPIO_OUT_CHANNELS_NUM=8 -CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8 -CONFIG_SOC_DEDIC_PERIPH_ALWAYS_ENABLE=y +# default: CONFIG_SOC_I2C_NUM=1 +# default: CONFIG_SOC_HP_I2C_NUM=1 -CONFIG_SOC_I2C_FIFO_LEN=32 -CONFIG_SOC_I2C_CMD_REG_NUM=8 -CONFIG_SOC_I2C_SUPPORT_SLAVE=y -CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y +# default: CONFIG_SOC_I2C_SUPPORT_XTAL=y +# default: CONFIG_SOC_I2C_SUPPORT_RTC=y +# default: CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y +# default: +CONFIG_SOC_I2C_SUPPORT_SLAVE=y +# default: CONFIG_SOC_I2C_SLAVE_SUPPORT_BROADCAST=y +# default: CONFIG_SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE=y -CONFIG_SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS=y -CONFIG_SOC_I2S_NUM=1 +# default: CONFIG_SOC_I2S_HW_VERSION_2=y -CONFIG_SOC_I2S_SUPPORTS_XTAL=y -CONFIG_SOC_I2S_SUPPORTS_PLL_F160M=y +# default: CONFIG_SOC_I2S_SUPPORTS_PCM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y +# default: +CONFIG_SOC_I2S_SUPPORTS_PCM2PDM=y +# default: +CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y +# default: CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 +# default: +CONFIG_SOC_I2S_PDM_MAX_RX_LINES=1 +# default: CONFIG_SOC_I2S_SUPPORTS_TDM=y +# default: CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y +# default: CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y +# default: +CONFIG_SOC_LEDC_TIMER_NUM=4 +# default: CONFIG_SOC_LEDC_CHANNEL_NUM=6 +# default: CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=14 +# default: CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y +# default: CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=1 +# default: CONFIG_SOC_MMU_PERIPH_NUM=1 +# default: CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 +# default: CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 -CONFIG_SOC_RMT_GROUPS=1 -CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=2 -CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=2 -CONFIG_SOC_RMT_CHANNELS_PER_GROUP=4 +# default: CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48 +# default: CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y -CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y -CONFIG_SOC_RMT_SUPPORT_TX_ASYNC_STOP=y +# default: CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y -CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y -CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y -CONFIG_SOC_RMT_SUPPORT_XTAL=y -CONFIG_SOC_RMT_SUPPORT_APB=y -CONFIG_SOC_RMT_SUPPORT_RC_FAST=y +# default: CONFIG_SOC_RTC_CNTL_CPU_PD_DMA_BUS_WIDTH=128 +# default: CONFIG_SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM=108 +# default: +CONFIG_SOC_RTC_CNTL_NEEDS_ATOMIC_ACCESS=y +# default: CONFIG_SOC_SLEEP_SYSTIMER_STALL_WORKAROUND=y +# default: CONFIG_SOC_SLEEP_TGWDT_STOP_WORKAROUND=y +# default: CONFIG_SOC_RTCIO_PIN_COUNT=0 +# default: CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 +# default: CONFIG_SOC_MPI_OPERATIONS_NUM=3 +# default: CONFIG_SOC_RSA_MAX_BIT_LEN=3072 +# default: CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968 +# default: CONFIG_SOC_SHA_SUPPORT_DMA=y +# default: CONFIG_SOC_SHA_SUPPORT_RESUME=y +# default: CONFIG_SOC_SHA_GDMA=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA1=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA224=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA256=y -CONFIG_SOC_SDM_GROUPS=1 -CONFIG_SOC_SDM_CHANNELS_PER_GROUP=4 -CONFIG_SOC_SDM_CLK_SUPPORT_APB=y +# default: CONFIG_SOC_SPI_PERIPH_NUM=2 -CONFIG_SOC_SPI_MAX_CS_NUM=6 +# default: CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 -CONFIG_SOC_SPI_SUPPORT_DDRCLK=y -CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y -CONFIG_SOC_SPI_SUPPORT_CD_SIG=y -CONFIG_SOC_SPI_SUPPORT_CONTINUOUS_TRANS=y +# default: CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y -CONFIG_SOC_SPI_SUPPORT_CLK_APB=y -CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y -CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y -CONFIG_SOC_SPI_SCT_SUPPORTED=y -CONFIG_SOC_SPI_SCT_REG_NUM=14 -CONFIG_SOC_SPI_SCT_BUFFER_NUM_MAX=y -CONFIG_SOC_SPI_SCT_CONF_BITLEN_MAX=0x3FFFA -CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y -CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16 +# default: CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_IDLE_INTR=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_CHECK_SUS=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_WRAP=y -CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_26M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y -CONFIG_SOC_SYSTIMER_COUNTER_NUM=2 -CONFIG_SOC_SYSTIMER_ALARM_NUM=3 -CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32 -CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20 -CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y -CONFIG_SOC_SYSTIMER_INT_LEVEL=y -CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y -CONFIG_SOC_TIMER_GROUPS=2 -CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=1 -CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54 -CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y -CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y -CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=2 +# default: +CONFIG_SOC_MEMSPI_SUPPORT_CONTROL_DUMMY_OUT=y +# default: +CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y +# default: +CONFIG_SOC_MEMSPI_ENCRYPTION_ALIGNMENT=16 +# default: +CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 +# default: +CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 +# default: +CONFIG_SOC_RTC_TIMER_V1=y +# default: CONFIG_SOC_MWDT_SUPPORT_XTAL=y +# default: CONFIG_SOC_TWAI_CONTROLLER_NUM=1 -CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y -CONFIG_SOC_TWAI_BRP_MIN=2 -CONFIG_SOC_TWAI_BRP_MAX=16384 -CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y +# default: +CONFIG_SOC_TWAI_MASK_FILTER_NUM=1 +# default: CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE=y +# default: CONFIG_SOC_EFUSE_DIS_PAD_JTAG=y +# default: CONFIG_SOC_EFUSE_DIS_USB_JTAG=y +# default: CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y +# default: CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y +# default: CONFIG_SOC_EFUSE_DIS_ICACHE=y +# default: CONFIG_SOC_EFUSE_BLOCK9_KEY_PURPOSE_QUIRK=y +# default: +CONFIG_SOC_EFUSE_XTS_AES_KEY_128=y +# default: CONFIG_SOC_SECURE_BOOT_V2_RSA=y +# default: CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3 +# default: CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y +# default: CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y +# default: CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=32 +# default: CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y +# default: CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y +# default: CONFIG_SOC_MEMPROT_CPU_PREFETCH_PAD_SIZE=16 +# default: CONFIG_SOC_MEMPROT_MEM_ALIGN_SIZE=512 +# default: CONFIG_SOC_UART_NUM=2 +# default: CONFIG_SOC_UART_HP_NUM=2 +# default: CONFIG_SOC_UART_FIFO_LEN=128 +# default: CONFIG_SOC_UART_BITRATE_MAX=5000000 +# default: CONFIG_SOC_UART_SUPPORT_APB_CLK=y +# default: CONFIG_SOC_UART_SUPPORT_RTC_CLK=y +# default: CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y +# default: CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y -CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y +# default: +CONFIG_SOC_UART_WAKEUP_SUPPORT_ACTIVE_THRESH_MODE=y +# default: CONFIG_SOC_COEX_HW_PTI=y +# default: CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 +# default: CONFIG_SOC_MAC_BB_PD_MEM_SIZE=192 +# default: CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12 +# default: CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_BT_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_CPU_PD=y +# default: CONFIG_SOC_PM_SUPPORT_WIFI_PD=y +# default: CONFIG_SOC_PM_SUPPORT_BT_PD=y +# default: CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y +# default: CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y +# default: CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y +# default: CONFIG_SOC_PM_CPU_RETENTION_BY_RTCCNTL=y +# default: CONFIG_SOC_PM_MODEM_RETENTION_BY_BACKUPDMA=y +# default: +CONFIG_SOC_PM_MODEM_PD_BY_SW=y +# default: CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y +# default: CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y +# default: CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y +# default: CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y +# default: +CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL_D2=y +# default: CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y +# default: CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_XTAL=y +# default: CONFIG_SOC_WIFI_HW_TSF=y +# default: CONFIG_SOC_WIFI_FTM_SUPPORT=y +# default: CONFIG_SOC_WIFI_GCMP_SUPPORT=y +# default: CONFIG_SOC_WIFI_WAPI_SUPPORT=y +# default: +CONFIG_SOC_WIFI_TXOP_SUPPORT=y +# default: CONFIG_SOC_WIFI_CSI_SUPPORT=y +# default: CONFIG_SOC_WIFI_MESH_SUPPORT=y +# default: CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +# default: CONFIG_SOC_WIFI_PHY_NEEDS_USB_WORKAROUND=y +# default: CONFIG_SOC_BLE_SUPPORTED=y +# default: CONFIG_SOC_BLE_MESH_SUPPORTED=y +# default: CONFIG_SOC_BLE_50_SUPPORTED=y +# default: CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y +# default: CONFIG_SOC_BLUFI_SUPPORTED=y +# default: CONFIG_SOC_PHY_COMBO_MODULE=y +# default: CONFIG_IDF_CMAKE=y +# default: CONFIG_IDF_TOOLCHAIN="gcc" +# default: +CONFIG_IDF_TOOLCHAIN_GCC=y +# default: CONFIG_IDF_TARGET_ARCH_RISCV=y +# default: CONFIG_IDF_TARGET_ARCH="riscv" +# default: CONFIG_IDF_TARGET="esp32c3" +# default: CONFIG_IDF_INIT_VERSION="5.3.1" +# default: CONFIG_IDF_TARGET_ESP32C3=y +# default: CONFIG_IDF_FIRMWARE_CHIP_ID=0x0005 # @@ -292,13 +496,29 @@ CONFIG_IDF_FIRMWARE_CHIP_ID=0x0005 # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_RAM is not set +# default: CONFIG_APP_BUILD_GENERATE_BINARIES=y +# default: CONFIG_APP_BUILD_BOOTLOADER=y +# default: CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y + +# +# Minimize binary changes between builds +# +# default: +# CONFIG_APP_BUILD_MINIMIZE_BINARY_CHANGES is not set +# end of Minimize binary changes between builds + # CONFIG_APP_REPRODUCIBLE_BUILD is not set # CONFIG_APP_NO_BLOBS is not set # end of Build type +# +# App Update config +# +# end of App Update config + # # Bootloader config # @@ -310,19 +530,61 @@ CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y CONFIG_BOOTLOADER_PROJECT_VER=1 # end of Bootloader manager +# +# Application Rollback +# +# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set +# end of Application Rollback + +# +# Recovery Bootloader and Rollback +# +# end of Recovery Bootloader and Rollback + +# default: CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x0 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set -# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set + +# +# Log +# +# default: +CONFIG_BOOTLOADER_LOG_VERSION_1=y +# default: +CONFIG_BOOTLOADER_LOG_VERSION=1 # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set +# default: CONFIG_BOOTLOADER_LOG_LEVEL=3 +# +# Format +# +# default: +# CONFIG_BOOTLOADER_LOG_COLORS is not set +# default: +CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y +# end of Format + +# +# Settings +# +# default: +CONFIG_BOOTLOADER_LOG_MODE_TEXT_EN=y +# default: +CONFIG_BOOTLOADER_LOG_MODE_TEXT=y +# end of Settings +# end of Log + +# default: +CONFIG_BOOTLOADER_CPU_CLK_FREQ_MHZ=80 + # # Serial Flash Configurations # @@ -336,10 +598,10 @@ CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 -# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set +# default: CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config @@ -347,11 +609,18 @@ CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # # Security features # +# default: CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y +# default: CONFIG_SECURE_BOOT_V2_PREFERRED=y # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set +# default: +CONFIG_SECURE_BOOT_IMAGE_DIGEST_LEN=32 +# default: +CONFIG_SECURE_BOOT_ROM_FAST_WAKE_RESERVE_SIZE=0 # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set +# default: CONFIG_SECURE_ROM_DL_MODE_ENABLED=y # end of Security features @@ -365,29 +634,62 @@ CONFIG_APP_COMPILE_TIME_DATE=y CONFIG_APP_RETRIEVE_LEN_ELF_SHA=16 # end of Application manager +# default: CONFIG_ESP_ROM_HAS_CRC_LE=y +# default: CONFIG_ESP_ROM_HAS_CRC_BE=y +# default: CONFIG_ESP_ROM_HAS_MZ_CRC32=y +# default: CONFIG_ESP_ROM_HAS_JPEG_DECODE=y +# default: CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y +# default: CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=3 +# default: CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y +# default: CONFIG_ESP_ROM_HAS_ERASE_0_REGION_BUG=y +# default: CONFIG_ESP_ROM_HAS_ENCRYPTED_WRITES_USING_LEGACY_DRV=y +# default: CONFIG_ESP_ROM_GET_CLK_FREQ=y +# default: CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y +# default: CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y +# default: CONFIG_ESP_ROM_HAS_SPI_FLASH=y +# default: +CONFIG_ESP_ROM_HAS_SPI_FLASH_MMAP=y +# default: CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y +# default: CONFIG_ESP_ROM_NEEDS_SET_CACHE_MMU_SIZE=y +# default: CONFIG_ESP_ROM_RAM_APP_NEEDS_MMU_INIT=y +# default: CONFIG_ESP_ROM_HAS_SW_FLOAT=y +# default: CONFIG_ESP_ROM_USB_OTG_NUM=-1 +# default: CONFIG_ESP_ROM_HAS_VERSION=y +# default: CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y +# default: +CONFIG_ESP_ROM_CONSOLE_OUTPUT_SECONDARY=y +# default: +CONFIG_ESP_ROM_HAS_SUBOPTIMAL_NEWLIB_ON_MISALIGNED_MEMORY=y +# default: +CONFIG_ESP_ROM_HAS_REGI2C_IMPL=y +# default: +CONFIG_ESP_ROM_BOOTLOADER_OFFSET_FLASH=0x0 # # Boot ROM Behavior @@ -407,12 +709,15 @@ CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y CONFIG_ESPTOOLPY_FLASHMODE_DIO=y # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y +# default: CONFIG_ESPTOOLPY_FLASHMODE="dio" +# default: +CONFIG_ESPTOOLPY_FLASHMODE_VAL=3 CONFIG_ESPTOOLPY_FLASHFREQ_80M=y # CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y +# default: CONFIG_ESPTOOLPY_FLASHFREQ="80m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y @@ -422,14 +727,18 @@ CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +# default: CONFIG_ESPTOOLPY_FLASHSIZE="2MB" # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set -CONFIG_ESPTOOLPY_BEFORE="default_reset" +# default: +CONFIG_ESPTOOLPY_BEFORE="default-reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set -CONFIG_ESPTOOLPY_AFTER="hard_reset" +# default: +CONFIG_ESPTOOLPY_AFTER="hard-reset" +# default: CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config @@ -439,8 +748,10 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 CONFIG_PARTITION_TABLE_SINGLE_APP=y # CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set +# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set # CONFIG_PARTITION_TABLE_CUSTOM is not set CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" +# default: CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y @@ -456,7 +767,10 @@ CONFIG_COMPILER_OPTIMIZATION_DEBUG=y CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set +# default: +# CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE is not set CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y +# default: CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set CONFIG_COMPILER_HIDE_PATHS_MACROS=y @@ -466,105 +780,112 @@ CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set +# default: +# CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set # CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS is not set +# default: +# CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS is not set # CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_GCC15_WARNINGS is not set # CONFIG_COMPILER_DUMP_RTL_FILES is not set CONFIG_COMPILER_RT_LIB_GCCLIB=y +# default: CONFIG_COMPILER_RT_LIB_NAME="gcc" +# CONFIG_COMPILER_ORPHAN_SECTIONS_ERROR is not set # CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y +# default: +# CONFIG_COMPILER_STATIC_ANALYZER is not set +# default: +CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y +# default: +# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD_CONSTEXPR is not set +# default: +# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set # end of Compiler options # # Component config # -# -# Application Level Tracing -# -# CONFIG_APPTRACE_DEST_JTAG is not set -CONFIG_APPTRACE_DEST_NONE=y -# CONFIG_APPTRACE_DEST_UART1 is not set -# CONFIG_APPTRACE_DEST_USB_CDC is not set -CONFIG_APPTRACE_DEST_UART_NONE=y -CONFIG_APPTRACE_UART_TASK_PRIO=1 -CONFIG_APPTRACE_LOCK_ENABLE=y -# end of Application Level Tracing - # # Bluetooth # # CONFIG_BT_ENABLED is not set -CONFIG_BT_ALARM_MAX_NUM=50 -# end of Bluetooth # -# Console Library +# Common Options # -# CONFIG_CONSOLE_SORTED_HELP is not set -# end of Console Library # -# Driver Configurations +# BT Logs # # -# TWAI Configuration +# Log Sources # -# CONFIG_TWAI_ISR_IN_IRAM is not set -CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y -# end of TWAI Configuration +# end of Log Sources -# -# Legacy ADC Driver Configuration -# -# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_BT_LOG_CRITICAL_ONLY is not set +# default: +# CONFIG_BLE_LOG_ENABLED is not set # -# Legacy ADC Calibration Configuration +# Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) # -# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy ADC Calibration Configuration -# end of Legacy ADC Driver Configuration +# default: +# CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set +# end of Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) +# end of BT Logs -# -# Legacy Timer Group Driver Configurations -# -# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy Timer Group Driver Configurations +# default: +# CONFIG_BT_LE_USED_MEM_STATISTICS_ENABLED is not set +# end of Common Options +# end of Bluetooth # -# Legacy RMT Driver Configurations +# Console Library # -# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy RMT Driver Configurations +# CONFIG_CONSOLE_SORTED_HELP is not set +# end of Console Library # -# Legacy I2S Driver Configurations +# Legacy Driver Configurations # -# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy I2S Driver Configurations # -# Legacy SDM Driver Configurations +# Legacy TWAI Driver Configurations # -# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy SDM Driver Configurations +# default: +# CONFIG_TWAI_ISR_IN_IRAM_LEGACY is not set +# default: +# CONFIG_TWAI_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_TWAI_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy TWAI Driver Configurations # -# Legacy Temperature Sensor Driver Configurations +# Legacy I2C Driver Configurations # -# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy Temperature Sensor Driver Configurations -# end of Driver Configurations +# default: +# CONFIG_I2C_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy I2C Driver Configurations +# end of Legacy Driver Configurations # # eFuse Bit Manager # # CONFIG_EFUSE_CUSTOM_TABLE is not set # CONFIG_EFUSE_VIRTUAL is not set +# default: CONFIG_EFUSE_MAX_BLK_LEN=256 # end of eFuse Bit Manager @@ -572,6 +893,7 @@ CONFIG_EFUSE_MAX_BLK_LEN=256 # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y +# CONFIG_ESP_TLS_CUSTOM_STACK is not set CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set @@ -579,6 +901,8 @@ CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # CONFIG_ESP_TLS_INSECURE is not set +# default: +CONFIG_ESP_TLS_DYN_BUF_STRATEGY_SUPPORTED=y # end of ESP-TLS # @@ -594,8 +918,11 @@ CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y # # Wireless Coexistence # +# default: CONFIG_ESP_COEX_ENABLED=y # CONFIG_ESP_COEX_EXTERNAL_COEXIST_ENABLE is not set +# default: +# CONFIG_ESP_COEX_GPIO_DEBUG is not set # end of Wireless Coexistence # @@ -604,6 +931,17 @@ CONFIG_ESP_COEX_ENABLED=y CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # end of Common ESP-related +# +# GDMA Configurations +# +CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y +# default: +CONFIG_GDMA_ISR_HANDLER_IN_IRAM=y +# default: +CONFIG_GDMA_OBJ_DRAM_SAFE=y +# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set +# end of GDMA Configurations + # # ESP-Driver:GPIO Configurations # @@ -615,7 +953,9 @@ CONFIG_ESP_ERR_TO_NAME_LOOKUP=y # CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set -# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set +# CONFIG_GPTIMER_ISR_CACHE_SAFE is not set +# default: +CONFIG_GPTIMER_OBJ_CACHE_SAFE=y # CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:GPTimer Configurations @@ -624,15 +964,30 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # CONFIG_I2C_ISR_IRAM_SAFE is not set # CONFIG_I2C_ENABLE_DEBUG_LOG is not set +# default: +CONFIG_I2C_MASTER_ISR_HANDLER_IN_IRAM=y # end of ESP-Driver:I2C Configurations # # ESP-Driver:I2S Configurations # # CONFIG_I2S_ISR_IRAM_SAFE is not set +# default: +# CONFIG_I2S_CTRL_FUNC_IN_IRAM is not set # CONFIG_I2S_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:I2S Configurations +# +# ESP-Driver:I3C Master Configurations +# +# default: +# CONFIG_I3C_MASTER_ISR_CACHE_SAFE is not set +# default: +# CONFIG_I3C_MASTER_ENABLE_DEBUG_LOG is not set +# default: +# CONFIG_I3C_MASTER_ISR_HANDLER_IN_IRAM is not set +# end of ESP-Driver:I3C Master Configurations + # # ESP-Driver:LEDC Configurations # @@ -642,9 +997,21 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # ESP-Driver:RMT Configurations # -# CONFIG_RMT_ISR_IRAM_SAFE is not set +# default: +CONFIG_RMT_ENCODER_FUNC_IN_IRAM=y +# default: +CONFIG_RMT_TX_ISR_HANDLER_IN_IRAM=y +# default: +CONFIG_RMT_RX_ISR_HANDLER_IN_IRAM=y # CONFIG_RMT_RECV_FUNC_IN_IRAM is not set +# default: +# CONFIG_RMT_TX_ISR_CACHE_SAFE is not set +# default: +# CONFIG_RMT_RX_ISR_CACHE_SAFE is not set +# default: +CONFIG_RMT_OBJ_CACHE_SAFE=y # CONFIG_RMT_ENABLE_DEBUG_LOG is not set +# CONFIG_RMT_ISR_IRAM_SAFE is not set # end of ESP-Driver:RMT Configurations # @@ -657,6 +1024,7 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # ESP-Driver:SPI Configurations # +# default: # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set @@ -669,12 +1037,37 @@ CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Temperature Sensor Configurations +# +# ESP-Driver:TWAI Configurations +# +# CONFIG_TWAI_ISR_IN_IRAM is not set +# default: +# CONFIG_TWAI_IO_FUNC_IN_IRAM is not set +# default: +# CONFIG_TWAI_ISR_CACHE_SAFE is not set +# default: +# CONFIG_TWAI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:TWAI Configurations + # # ESP-Driver:UART Configurations # # CONFIG_UART_ISR_IN_IRAM is not set # end of ESP-Driver:UART Configurations +# +# ESP-Driver:UHCI Configurations +# +# default: +# CONFIG_UHCI_ISR_HANDLER_IN_IRAM is not set +# default: +# CONFIG_UHCI_RECV_FUNC_IN_IRAM is not set +# default: +# CONFIG_UHCI_ISR_CACHE_SAFE is not set +# default: +# CONFIG_UHCI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:UHCI Configurations + # # ESP-Driver:USB Serial/JTAG Configuration # @@ -684,11 +1077,9 @@ CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y # # Ethernet # +# default: CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_SPI_ETHERNET=y -# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set -# CONFIG_ETH_SPI_ETHERNET_W5500 is not set -# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set # CONFIG_ETH_USE_OPENETH is not set # CONFIG_ETH_TRANSMIT_MUTEX is not set # end of Ethernet @@ -698,18 +1089,30 @@ CONFIG_ETH_USE_SPI_ETHERNET=y # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y +# default: +CONFIG_ESP_EVENT_POST_FROM_ISR_SIZE=4 CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # +# default: CONFIG_ESP_GDBSTUB_ENABLED=y # CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y CONFIG_ESP_GDBSTUB_MAX_TASKS=32 # end of GDB Stub +# +# ESP HID +# +# default: +CONFIG_ESPHID_TASK_SIZE_BT=2048 +# default: +CONFIG_ESPHID_TASK_SIZE_BLE=4096 +# end of ESP HID + # # ESP HTTP client # @@ -717,6 +1120,14 @@ CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set # CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set +# default: +# CONFIG_ESP_HTTP_CLIENT_ENABLE_GET_CONTENT_RANGE is not set +# default: +CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 +# default: +# CONFIG_ESP_HTTP_CLIENT_SAVE_RESPONSE_HEADERS is not set +# default: +CONFIG_ESP_HTTP_CLIENT_STRICT_HEADER_BUFFER=y # end of ESP HTTP client # @@ -729,6 +1140,10 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set +# default: +CONFIG_HTTPD_ENABLE_EVENTS=y +# default: +CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 # end of HTTP Server # @@ -736,17 +1151,27 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 # # CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set # CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set +# default: +CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 +# default: +# CONFIG_ESP_HTTPS_OTA_ENABLE_PARTIAL_DOWNLOAD is not set +# default: +CONFIG_ESP_HTTPS_OTA_VERIFY_SPI_MODE=y # end of ESP HTTPS OTA # # ESP HTTPS server # # CONFIG_ESP_HTTPS_SERVER_ENABLE is not set +# default: +# CONFIG_ESP_HTTPS_SERVER_CERT_SELECT_HOOK is not set # end of ESP HTTPS server # # Hardware Settings # +# default: +CONFIG_ESP_HW_SUPPORT_FUNC_IN_IRAM=y # # Chip revision @@ -757,27 +1182,46 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 CONFIG_ESP32C3_REV_MIN_3=y # CONFIG_ESP32C3_REV_MIN_4 is not set # CONFIG_ESP32C3_REV_MIN_101 is not set +# default: CONFIG_ESP32C3_REV_MIN_FULL=3 +# default: CONFIG_ESP_REV_MIN_FULL=3 # # Maximum Supported ESP32-C3 Revision (Rev v1.99) # +# default: CONFIG_ESP32C3_REV_MAX_FULL=199 +# default: CONFIG_ESP_REV_MAX_FULL=199 +# default: +CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 +# default: +CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=199 + +# +# Maximum Supported ESP32-C3 eFuse Block Revision (eFuse Block Rev v1.99) +# # end of Chip revision # # MAC Config # +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y +# default: CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y +# default: CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES_TWO is not set CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES_FOUR=y +# default: CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set # end of MAC Config @@ -793,6 +1237,8 @@ CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=0 # CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set # CONFIG_ESP_SLEEP_DEBUG is not set CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y +# default: +# CONFIG_ESP_SLEEP_SET_FLASH_DPD is not set # end of Sleep Config # @@ -803,57 +1249,115 @@ CONFIG_RTC_CLK_SRC_INT_RC=y # CONFIG_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_RTC_CLK_CAL_CYCLES=1024 +# default: +CONFIG_RTC_CLK_FUNC_IN_IRAM=y +# default: +CONFIG_RTC_TIME_FUNC_IN_IRAM=y # end of RTC Clock Config # # Peripheral Control # -CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM=y +# default: +CONFIG_ESP_REGI2C_CTRL_FUNC_IN_IRAM=y # end of Peripheral Control -# -# GDMA Configurations -# -CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y -# CONFIG_GDMA_ISR_IRAM_SAFE is not set -# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set -# end of GDMA Configurations - # # Main XTAL Config # CONFIG_XTAL_FREQ_40=y +# default: CONFIG_XTAL_FREQ=40 # end of Main XTAL Config -CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y -# end of Hardware Settings - # -# LCD and Touch Panel +# Power Supplier # # -# LCD Touch Drivers are maintained in the IDF Component Registry +# Brownout Detector # +CONFIG_ESP_BROWNOUT_DET=y +CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set +# default: +CONFIG_ESP_BROWNOUT_DET_LVL=7 +# default: +CONFIG_ESP_BROWNOUT_USE_INTR=y +# end of Brownout Detector +# end of Power Supplier + +# default: +CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y +# default: +CONFIG_ESP_INTR_IN_IRAM=y +# end of Hardware Settings # -# LCD Peripheral Configuration +# ESP-Driver:LCD Controller Configurations # # CONFIG_LCD_ENABLE_DEBUG_LOG is not set -# end of LCD Peripheral Configuration -# end of LCD and Touch Panel +# end of ESP-Driver:LCD Controller Configurations + +# +# LibC +# +# default: +# CONFIG_LIBC_NEWLIB is not set +# default: +CONFIG_LIBC_PICOLIBC=y +# default: +CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY=y +# default: +CONFIG_LIBC_MISC_IN_IRAM=y +# default: +CONFIG_LIBC_LOCKS_PLACE_IN_IRAM=y +CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_LIBC_STDOUT_LINE_ENDING_LF is not set +# CONFIG_LIBC_STDOUT_LINE_ENDING_CR is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_LF is not set +CONFIG_LIBC_STDIN_LINE_ENDING_CR=y +CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT=y +# CONFIG_LIBC_TIME_SYSCALL_USE_RTC is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_HRT is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_NONE is not set +# default: +CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS=y +# default: +CONFIG_LIBC_ASSERT_BUFFER_SIZE=200 +# end of LibC + +# +# ESP-MM: Memory Management Configurations +# +# end of ESP-MM: Memory Management Configurations # # ESP NETIF Adapter # +# default: +CONFIG_ESP_NETIF_LOST_IP_TIMER_ENABLE=y CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 +# default: +# CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set +# default: CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y -# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set +# default: +CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y +# default: +CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS=y # CONFIG_ESP_NETIF_L2_TAP is not set # CONFIG_ESP_NETIF_BRIDGE_EN is not set +# default: +# CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set # end of ESP NETIF Adapter # @@ -864,10 +1368,12 @@ CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y # # PHY # +# default: CONFIG_ESP_PHY_ENABLED=y CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20 +# default: CONFIG_ESP_PHY_MAX_TX_POWER=20 # CONFIG_ESP_PHY_REDUCE_TX_POWER is not set CONFIG_ESP_PHY_ENABLE_USB=y @@ -875,15 +1381,32 @@ CONFIG_ESP_PHY_ENABLE_USB=y CONFIG_ESP_PHY_RF_CAL_PARTIAL=y # CONFIG_ESP_PHY_RF_CAL_NONE is not set # CONFIG_ESP_PHY_RF_CAL_FULL is not set +# default: CONFIG_ESP_PHY_CALIBRATION_MODE=0 +# default: +CONFIG_ESP_PHY_PLL_TRACK_PERIOD_MS=1000 # CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set +# default: +# CONFIG_ESP_PHY_RECORD_USED_TIME is not set +# default: +CONFIG_ESP_PHY_IRAM_OPT=y +# default: +# CONFIG_ESP_PHY_DEBUG is not set +# default: +CONFIG_ESP_PHY_ENABLE_VERSION_PRINT=y # end of PHY # # Power Management # +# default: +# CONFIG_PM_SLEEP_FUNC_IN_IRAM is not set # CONFIG_PM_ENABLE is not set +# default: +# CONFIG_PM_SLP_IRAM_OPT is not set CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y +# default: +CONFIG_PM_ESP_SLEEP_POWER_DOWN_CPU=y # end of Power Management # @@ -893,50 +1416,80 @@ CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y # # ESP Ringbuf # -# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set +# default: +CONFIG_RINGBUF_IN_IRAM=y # end of ESP Ringbuf +# +# ESP-ROM +# +# default: +CONFIG_ESP_ROM_PRINT_IN_IRAM=y +# end of ESP-ROM + +# +# ESP Security Specific +# +# end of ESP Security Specific + +# +# ESP-STDIO +# +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set +# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set +# CONFIG_ESP_CONSOLE_NONE is not set +# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set +CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y +# default: +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y +# default: +CONFIG_ESP_CONSOLE_UART=y +# default: +CONFIG_ESP_CONSOLE_UART_NUM=0 +# default: +CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 +CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 +# default: +CONFIG_ESP_STDIO_MAX_VFS_ENTRIES=2 +# end of ESP-STDIO + # # ESP System Settings # # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y +# default: CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160 +# default: +CONFIG_ESP_SYSTEM_IN_IRAM=y # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 +# default: CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE=y +# default: CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y +# default: +CONFIG_ESP_SYSTEM_NO_BACKTRACE=y # CONFIG_ESP_SYSTEM_USE_EH_FRAME is not set - -# -# Memory protection -# -CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y -CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y -# end of Memory protection - +# default: +# CONFIG_ESP_SYSTEM_USE_FRAME_POINTER is not set +CONFIG_ESP_SYSTEM_MEMPROT=y +# default: +CONFIG_ESP_SYSTEM_MEMPROT_PMS=y +CONFIG_ESP_SYSTEM_MEMPROT_PMS_LOCK=y CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584 CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y # CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set +# default: CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 -CONFIG_ESP_CONSOLE_UART_DEFAULT=y -# CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG is not set -# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set -# CONFIG_ESP_CONSOLE_NONE is not set -# CONFIG_ESP_CONSOLE_SECONDARY_NONE is not set -CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y -CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y -CONFIG_ESP_CONSOLE_UART=y -CONFIG_ESP_CONSOLE_UART_NUM=0 -CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 -CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 CONFIG_ESP_TASK_WDT_EN=y @@ -948,21 +1501,6 @@ CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y # CONFIG_ESP_DEBUG_STUBS_ENABLE is not set CONFIG_ESP_DEBUG_OCDAWARE=y CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y - -# -# Brownout Detector -# -CONFIG_ESP_BROWNOUT_DET=y -CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set -CONFIG_ESP_BROWNOUT_DET_LVL=7 -# end of Brownout Detector - -CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y CONFIG_ESP_SYSTEM_HW_STACK_GUARD=y CONFIG_ESP_SYSTEM_HW_PC_RECORD=y # end of ESP System Settings @@ -976,31 +1514,57 @@ CONFIG_ESP_IPC_TASK_STACK_SIZE=1024 # # ESP Timer (High Resolution Timer) # +# default: +CONFIG_ESP_TIMER_IN_IRAM=y # CONFIG_ESP_TIMER_PROFILING is not set +# default: CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y +# default: CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 # CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set +# default: CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y # CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set +# default: CONFIG_ESP_TIMER_IMPL_SYSTIMER=y # end of ESP Timer (High Resolution Timer) +# +# ESP Trace Configuration +# +# default: +# CONFIG_ESP_TRACE_LIB_EXTERNAL is not set +# default: +CONFIG_ESP_TRACE_LIB_NONE=y +# default: +CONFIG_ESP_TRACE_LIB_NAME="none" +# default: +# CONFIG_ESP_TRACE_TRANSPORT_APPTRACE is not set +# default: +CONFIG_ESP_TRACE_TRANSPORT_NONE=y +# default: +CONFIG_ESP_TRACE_TRANSPORT_NAME="none" +# end of ESP Trace Configuration + # # Wi-Fi # +# default: CONFIG_ESP_WIFI_ENABLED=y CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32 # CONFIG_ESP_WIFI_STATIC_TX_BUFFER is not set CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y +# default: CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1 CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y # CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set +# default: CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0 CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5 # CONFIG_ESP_WIFI_CSI_ENABLED is not set @@ -1012,14 +1576,24 @@ CONFIG_ESP_WIFI_NVS_ENABLED=y CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752 CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32 CONFIG_ESP_WIFI_IRAM_OPT=y -# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set +CONFIG_ESP_WIFI_EXTRA_IRAM_OPT=y CONFIG_ESP_WIFI_RX_IRAM_OPT=y CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y +# default: +CONFIG_ESP_WIFI_ENABLE_SAE_H2E=y CONFIG_ESP_WIFI_ENABLE_SAE_PK=y CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y +# default: +CONFIG_ESP_WIFI_WPA3_COMPATIBLE_SUPPORT=y +# default: +# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_SOFTAP is not set +# default: +# CONFIG_ESP_WIFI_PASN_SUPPORT is not set # CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# default: +# CONFIG_ESP_WIFI_BSS_MAX_IDLE_SUPPORT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10 CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 # CONFIG_ESP_WIFI_FTM_ENABLE is not set @@ -1035,6 +1609,8 @@ CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y # CONFIG_ESP_WIFI_SUITE_B_192 is not set # CONFIG_ESP_WIFI_11KV_SUPPORT is not set # CONFIG_ESP_WIFI_MBO_SUPPORT is not set +# default: +# CONFIG_ESP_WIFI_ENABLE_ROAMING_APP is not set # CONFIG_ESP_WIFI_DPP_SUPPORT is not set # CONFIG_ESP_WIFI_11R_SUPPORT is not set # CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set @@ -1044,14 +1620,198 @@ CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y # # CONFIG_ESP_WIFI_WPS_STRICT is not set # CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set +# default: +# CONFIG_ESP_WIFI_WPS_RECONNECT_ON_FAIL is not set # end of WPS Configuration Options # CONFIG_ESP_WIFI_DEBUG_PRINT is not set -# CONFIG_ESP_WIFI_TESTING_OPTIONS is not set CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y # CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set +# default: +# CONFIG_ESP_WIFI_PASSIVE_HIDDEN_AP_SUPPORT is not set +# default: +# CONFIG_ESP_WIFI_PRIVACY_ENHANCEMENTS_ENABLED is not set # end of Wi-Fi +# +# Wi-Fi Remote +# +# default: +CONFIG_ESP_WIFI_REMOTE_IN_IDF=y +# default: +CONFIG_ESP_WIFI_REMOTE_ENABLED=y +# default: +CONFIG_SLAVE_IDF_TARGET_ESP32=y +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S2 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C3 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S3 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C2 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C6 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C5 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C61 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S31 is not set +# default: +CONFIG_SLAVE_SOC_WIFI_SUPPORTED=y +# default: +CONFIG_SLAVE_SOC_WIFI_WAPI_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_CSI_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_MESH_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +# default: +CONFIG_SLAVE_SOC_WIFI_NAN_SUPPORT=y +# default: +CONFIG_SLAVE_IDF_TARGET_ARCH_XTENSA=y + +# +# Wi-Fi configuration +# +# default: +CONFIG_WIFI_RMT_STATIC_RX_BUFFER_NUM=10 +# default: +CONFIG_WIFI_RMT_DYNAMIC_RX_BUFFER_NUM=32 +# default: +# CONFIG_WIFI_RMT_STATIC_TX_BUFFER is not set +# default: +CONFIG_WIFI_RMT_DYNAMIC_TX_BUFFER=y +# default: +CONFIG_WIFI_RMT_TX_BUFFER_TYPE=1 +# default: +CONFIG_WIFI_RMT_DYNAMIC_TX_BUFFER_NUM=32 +# default: +CONFIG_WIFI_RMT_STATIC_RX_MGMT_BUFFER=y +# default: +# CONFIG_WIFI_RMT_DYNAMIC_RX_MGMT_BUFFER is not set +# default: +CONFIG_WIFI_RMT_DYNAMIC_RX_MGMT_BUF=0 +# default: +CONFIG_WIFI_RMT_RX_MGMT_BUF_NUM_DEF=5 +# default: +# CONFIG_WIFI_RMT_CSI_ENABLED is not set +# default: +CONFIG_WIFI_RMT_AMPDU_TX_ENABLED=y +# default: +CONFIG_WIFI_RMT_TX_BA_WIN=6 +# default: +CONFIG_WIFI_RMT_AMPDU_RX_ENABLED=y +# default: +CONFIG_WIFI_RMT_RX_BA_WIN=6 +# default: +CONFIG_WIFI_RMT_NVS_ENABLED=y +# default: +CONFIG_WIFI_RMT_TASK_PINNED_TO_CORE_0=y +# default: +# CONFIG_WIFI_RMT_TASK_PINNED_TO_CORE_1 is not set +# default: +CONFIG_WIFI_RMT_SOFTAP_BEACON_MAX_LEN=752 +# default: +CONFIG_WIFI_RMT_MGMT_SBUF_NUM=32 +# default: +CONFIG_WIFI_RMT_IRAM_OPT=y +# default: +# CONFIG_WIFI_RMT_EXTRA_IRAM_OPT is not set +# default: +CONFIG_WIFI_RMT_RX_IRAM_OPT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_SAE=y +# default: +CONFIG_WIFI_RMT_ENABLE_SAE_H2E=y +# default: +CONFIG_WIFI_RMT_ENABLE_SAE_PK=y +# default: +CONFIG_WIFI_RMT_SOFTAP_SAE_SUPPORT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_OWE_STA=y +# default: +CONFIG_WIFI_RMT_WPA3_COMPATIBLE_SUPPORT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_OWE_SOFTAP=y +# default: +# CONFIG_WIFI_RMT_PASN_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_SLP_IRAM_OPT is not set +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# default: +# CONFIG_WIFI_RMT_BSS_MAX_IDLE_SUPPORT is not set +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_MAX_ACTIVE_TIME=10 +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 +# default: +CONFIG_WIFI_RMT_STA_DISCONNECTED_PM_ENABLE=y +# default: +CONFIG_WIFI_RMT_GMAC_SUPPORT=y +# default: +CONFIG_WIFI_RMT_SOFTAP_SUPPORT=y +# default: +# CONFIG_WIFI_RMT_SLP_BEACON_LOST_OPT is not set +# default: +CONFIG_WIFI_RMT_ESPNOW_MAX_ENCRYPT_NUM=7 +# default: +# CONFIG_WIFI_RMT_NAN_SYNC_ENABLE is not set +# default: +CONFIG_WIFI_RMT_MBEDTLS_CRYPTO=y +# default: +CONFIG_WIFI_RMT_MBEDTLS_TLS_CLIENT=y +# default: +# CONFIG_WIFI_RMT_WAPI_PSK is not set +# default: +# CONFIG_WIFI_RMT_11KV_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_MBO_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_ENABLE_ROAMING_APP is not set +# default: +# CONFIG_WIFI_RMT_DPP_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_11R_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_WPS_SOFTAP_REGISTRAR is not set + +# +# WPS Configuration Options +# +# default: +# CONFIG_WIFI_RMT_WPS_STRICT is not set +# default: +# CONFIG_WIFI_RMT_WPS_PASSPHRASE is not set +# default: +# CONFIG_WIFI_RMT_WPS_RECONNECT_ON_FAIL is not set +# end of WPS Configuration Options + +# default: +# CONFIG_WIFI_RMT_DEBUG_PRINT is not set +# default: +CONFIG_WIFI_RMT_ENTERPRISE_SUPPORT=y +# default: +# CONFIG_WIFI_RMT_ENT_FREE_DYNAMIC_BUFFER is not set +# default: +# CONFIG_WIFI_RMT_PASSIVE_HIDDEN_AP_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_PRIVACY_ENHANCEMENTS_ENABLED is not set +# end of Wi-Fi configuration + +# default: +CONFIG_ESP_WIFI_REMOTE_LIBRARY_HOSTED=y +# default: +# CONFIG_ESP_WIFI_REMOTE_LIBRARY_EPPP is not set +# default: +# CONFIG_ESP_WIFI_REMOTE_LIBRARY_CUSTOM is not set +# default: +CONFIG_ESP_WIFI_REMOTE_EAP_ENABLED=y +# end of Wi-Fi Remote + # # Core dump # @@ -1091,15 +1851,35 @@ CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set +# default: CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y +# default: +# CONFIG_FATFS_ALLOC_PREFER_ALIGNED_WORK_BUFFERS is not set # CONFIG_FATFS_USE_FASTSEEK is not set +# default: +CONFIG_FATFS_USE_STRFUNC_NONE=y +# default: +# CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set +# default: +# CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 # CONFIG_FATFS_IMMEDIATE_FSYNC is not set # CONFIG_FATFS_USE_LABEL is not set CONFIG_FATFS_LINK_LOCK=y +# default: +CONFIG_FATFS_USE_DYN_BUFFERS=y + +# +# File system free space calculation behavior +# +# default: +CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 +# default: +CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 +# end of File system free space calculation behavior # end of FAT Filesystem support # @@ -1109,7 +1889,6 @@ CONFIG_FATFS_LINK_LOCK=y # # Kernel # -# CONFIG_FREERTOS_SMP is not set CONFIG_FREERTOS_UNICORE=y CONFIG_FREERTOS_HZ=100 CONFIG_FREERTOS_OPTIMIZED_SCHEDULER=y @@ -1122,9 +1901,12 @@ CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 # CONFIG_FREERTOS_USE_TICK_HOOK is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 # CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set +# default: +CONFIG_FREERTOS_USE_TIMERS=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y +# default: CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 @@ -1144,24 +1926,35 @@ CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y # CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set -# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set +# default: CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y CONFIG_FREERTOS_ISR_STACKSIZE=1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y +# default: CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y # CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set +# default: CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y -# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set +# default: +CONFIG_FREERTOS_IN_IRAM=y # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set # end of Port +# +# Extra +# +# end of Extra + +# default: CONFIG_FREERTOS_PORT=y +# default: CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF +# default: CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y +# default: CONFIG_FREERTOS_DEBUG_OCDAWARE=y -CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y -CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y +# default: CONFIG_FREERTOS_NUMBER_OF_CORES=1 # end of FreeRTOS @@ -1172,9 +1965,10 @@ CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y # CONFIG_HAL_ASSERTION_DISABLE is not set # CONFIG_HAL_ASSERTION_SILENT is not set # CONFIG_HAL_ASSERTION_ENABLE is not set +# default: CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 -CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y -CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y +# default: +CONFIG_HAL_GPIO_USE_ROM_IMPL=y # end of Hardware Abstraction Layer (HAL) and Low Level (LL) # @@ -1193,7 +1987,17 @@ CONFIG_HEAP_TRACING_OFF=y # end of Heap memory debugging # -# Log output +# Log +# +# default: +CONFIG_LOG_VERSION_1=y +# default: +# CONFIG_LOG_VERSION_2 is not set +# default: +CONFIG_LOG_VERSION=1 + +# +# Log Level # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set @@ -1201,23 +2005,61 @@ CONFIG_HEAP_TRACING_OFF=y CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set +# default: CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y # CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set # CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set +# default: CONFIG_LOG_MAXIMUM_LEVEL=3 + +# +# Level Settings +# # CONFIG_LOG_MASTER_LEVEL is not set +# default: +CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y +# default: +# CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set +# default: +# CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set +# default: +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y +# default: +# CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set +# default: +CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y +# default: +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 +# end of Level Settings +# end of Log Level + +# +# Format +# CONFIG_LOG_COLORS=y CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set -# end of Log output +# end of Format + +# +# Settings +# +# default: +CONFIG_LOG_MODE_TEXT_EN=y +# default: +CONFIG_LOG_MODE_TEXT=y +# end of Settings + +# default: +CONFIG_LOG_IN_IRAM=y +# end of Log # # LWIP # CONFIG_LWIP_ENABLE=y CONFIG_LWIP_LOCAL_HOSTNAME="espressif" -# CONFIG_LWIP_NETIF_API is not set CONFIG_LWIP_TCPIP_TASK_PRIO=18 # CONFIG_LWIP_TCPIP_CORE_LOCKING is not set # CONFIG_LWIP_CHECK_THREAD_SAFETY is not set @@ -1227,6 +2069,8 @@ CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y +# default: +# CONFIG_LWIP_ND6_SUPPORT_STATIC_ENTRIES is not set # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set CONFIG_LWIP_MAX_SOCKETS=10 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set @@ -1241,6 +2085,8 @@ CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 +# default: +CONFIG_LWIP_IPV6_DUP_DETECT_ATTEMPTS=1 # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y @@ -1249,10 +2095,12 @@ CONFIG_LWIP_ESP_MLDV6_REPORT=y CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y +# CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set +# CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set -CONFIG_LWIP_DHCP_OPTIONS_LEN=68 +CONFIG_LWIP_DHCP_OPTIONS_LEN=69 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 @@ -1260,8 +2108,12 @@ CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 # DHCP server # CONFIG_LWIP_DHCPS=y +# default: +CONFIG_LWIP_DHCPS_REPORT_CLIENT_HOSTNAME=y CONFIG_LWIP_DHCPS_LEASE_UNIT=60 CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 +# default: +CONFIG_LWIP_DHCPS_MAX_HOSTNAME_LEN=64 CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y # end of DHCP server @@ -1272,6 +2124,8 @@ CONFIG_LWIP_IPV6=y CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 # CONFIG_LWIP_IPV6_FORWARD is not set # CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set +# default: +# CONFIG_LWIP_NETIF_LINK_CALLBACK is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 @@ -1319,10 +2173,19 @@ CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set +# default: CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF -# CONFIG_LWIP_PPP_SUPPORT is not set CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 +# default: +# CONFIG_LWIP_IPV6_ND6_ROUTE_INFO_OPTION_SUPPORT is not set +# CONFIG_LWIP_PPP_SUPPORT is not set # CONFIG_LWIP_SLIP_SUPPORT is not set # @@ -1352,8 +2215,14 @@ CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 # # DNS # +# default: +CONFIG_LWIP_DNS_MAX_HOST_IP=1 CONFIG_LWIP_DNS_MAX_SERVERS=3 # CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set +# default: +# CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set +# default: +# CONFIG_LWIP_USE_ESP_GETADDRINFO is not set # end of DNS CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 @@ -1374,9 +2243,19 @@ CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set +# default: +CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE=y +# default: +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_DEFAULT is not set +# default: +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_CUSTOM is not set CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set +# default: +CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y +# default: +# CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y # CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set @@ -1388,6 +2267,33 @@ CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y # # mbedTLS # + +# +# Core Configuration +# +# default: +CONFIG_MBEDTLS_VER_4_X_SUPPORT=y +# default: +# CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_NONE is not set +# default: +CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE=y +# default: +# CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_PERF is not set +# default: +CONFIG_MBEDTLS_FS_IO=y +# default: +# CONFIG_MBEDTLS_PSA_ITS_CUSTOM_STORAGE_BACKEND is not set +CONFIG_MBEDTLS_THREADING_C=y +# default: +# CONFIG_MBEDTLS_THREADING_ALT is not set +# default: +CONFIG_MBEDTLS_THREADING_PTHREAD=y +CONFIG_MBEDTLS_ERROR_STRINGS=y +# default: +CONFIG_MBEDTLS_VERSION_C=y +CONFIG_MBEDTLS_HAVE_TIME=y +# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set +# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set @@ -1395,159 +2301,257 @@ CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set +# default: +# CONFIG_MBEDTLS_VERSION_FEATURES is not set # CONFIG_MBEDTLS_DEBUG is not set +# default: +CONFIG_MBEDTLS_SELF_TEST=y +# end of Core Configuration # -# mbedTLS v3.x related +# Certificates # -# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set -# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set -# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set -# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set -CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y -CONFIG_MBEDTLS_PKCS7_C=y -# end of mbedTLS v3.x related +# default: +CONFIG_MBEDTLS_X509_USE_C=y +CONFIG_MBEDTLS_PEM_PARSE_C=y +CONFIG_MBEDTLS_PEM_WRITE_C=y +# default: +CONFIG_MBEDTLS_PK_C=y +# default: +CONFIG_MBEDTLS_PK_PARSE_C=y +# default: +CONFIG_MBEDTLS_PK_WRITE_C=y +# default: +# CONFIG_MBEDTLS_X509_REMOVE_INFO is not set +CONFIG_MBEDTLS_X509_CRL_PARSE_C=y +# default: +CONFIG_MBEDTLS_X509_CRT_PARSE_C=y +CONFIG_MBEDTLS_X509_CSR_PARSE_C=y +# default: +# CONFIG_MBEDTLS_X509_CREATE_C is not set +# default: +CONFIG_MBEDTLS_X509_RSASSA_PSS_SUPPORT=y +CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK=y +# default: +CONFIG_MBEDTLS_ASN1_PARSE_C=y +# default: +CONFIG_MBEDTLS_ASN1_WRITE_C=y +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y # -# Certificate Bundle +# Certificate Bundle Configuration # -CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set # CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 -# end of Certificate Bundle +# end of Certificate Bundle Configuration -# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set -CONFIG_MBEDTLS_CMAC_C=y -CONFIG_MBEDTLS_HARDWARE_AES=y -CONFIG_MBEDTLS_AES_USE_INTERRUPT=y -CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 -CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y -CONFIG_MBEDTLS_HARDWARE_MPI=y -CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI=y -CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y -CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 -CONFIG_MBEDTLS_HARDWARE_SHA=y -CONFIG_MBEDTLS_ROM_MD5=y -# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set -# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set -CONFIG_MBEDTLS_HAVE_TIME=y -# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set -# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set -CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y -CONFIG_MBEDTLS_SHA512_C=y +# default: +# CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set +# default: +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_CROSS_SIGNED_VERIFY=y +# end of Certificates + +CONFIG_MBEDTLS_TLS_ENABLED=y + +# +# TLS Protocol Configuration +# +CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y +# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set +# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set +# default: +CONFIG_MBEDTLS_TLS_SERVER=y +# default: +CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y # CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set # CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set -# CONFIG_MBEDTLS_TLS_DISABLED is not set -CONFIG_MBEDTLS_TLS_SERVER=y -CONFIG_MBEDTLS_TLS_CLIENT=y -CONFIG_MBEDTLS_TLS_ENABLED=y +CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y +# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set +# default: +CONFIG_MBEDTLS_SSL_CACHE_C=y +# default: +CONFIG_MBEDTLS_SSL_ALL_ALERT_MESSAGES=y # -# TLS Key Exchange Methods +# TLS Key Exchange Configuration # # CONFIG_MBEDTLS_PSK_MODES is not set CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y -CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y -CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y -# end of TLS Key Exchange Methods +# end of TLS Key Exchange Configuration -CONFIG_MBEDTLS_SSL_RENEGOTIATION=y -CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y -# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set -# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set +# default: +CONFIG_MBEDTLS_SSL_SERVER_NAME_INDICATION=y CONFIG_MBEDTLS_SSL_ALPN=y +# default: +CONFIG_MBEDTLS_SSL_MAX_FRAGMENT_LENGTH=y +# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set +CONFIG_MBEDTLS_SSL_RENEGOTIATION=y CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y +# default: +# CONFIG_MBEDTLS_SSL_KEYING_MATERIAL_EXPORT is not set +# end of TLS Protocol Configuration + +# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set +# default: +# CONFIG_MBEDTLS_ARIA_C is not set # CONFIG_MBEDTLS_DES_C is not set -# CONFIG_MBEDTLS_BLOWFISH_C is not set -# CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CBC=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CFB=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CTR=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_OFB=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_XTS=y CONFIG_MBEDTLS_GCM_C=y # CONFIG_MBEDTLS_NIST_KW_C is not set +# default: +CONFIG_MBEDTLS_AES_ROM_TABLES=y +# default: +# CONFIG_MBEDTLS_AES_FEWER_TABLES is not set +# default: +# CONFIG_MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is not set +CONFIG_MBEDTLS_CMAC_C=y # end of Symmetric Ciphers -# CONFIG_MBEDTLS_RIPEMD160_C is not set - # -# Certificates +# Asymmetric Ciphers # -CONFIG_MBEDTLS_PEM_PARSE_C=y -CONFIG_MBEDTLS_PEM_WRITE_C=y -CONFIG_MBEDTLS_X509_CRL_PARSE_C=y -CONFIG_MBEDTLS_X509_CSR_PARSE_C=y -# end of Certificates - +# default: +CONFIG_MBEDTLS_RSA_C=y CONFIG_MBEDTLS_ECP_C=y -# CONFIG_MBEDTLS_DHM_C is not set -CONFIG_MBEDTLS_ECDH_C=y -CONFIG_MBEDTLS_ECDSA_C=y -# CONFIG_MBEDTLS_ECJPAKE_C is not set -CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y + +# +# Supported Curves +# CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y +# CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED is not set CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y +# end of Supported Curves + +# +# Elliptic Curve Ciphers Configuration +# CONFIG_MBEDTLS_ECP_NIST_OPTIM=y CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM=y -# CONFIG_MBEDTLS_POLY1305_C is not set -# CONFIG_MBEDTLS_CHACHA20_C is not set -# CONFIG_MBEDTLS_HKDF_C is not set -# CONFIG_MBEDTLS_THREADING_C is not set -CONFIG_MBEDTLS_ERROR_STRINGS=y -# end of mbedTLS +# CONFIG_MBEDTLS_DHM_C is not set +CONFIG_MBEDTLS_ECDH_C=y +# CONFIG_MBEDTLS_ECJPAKE_C is not set +CONFIG_MBEDTLS_ECDSA_C=y +# default: +CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y +# default: +CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y +CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y +# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set +# end of Elliptic Curve Ciphers Configuration +# end of Asymmetric Ciphers # -# ESP-MQTT Configurations +# Hash functions # -CONFIG_MQTT_PROTOCOL_311=y -# CONFIG_MQTT_PROTOCOL_5 is not set -CONFIG_MQTT_TRANSPORT_SSL=y -CONFIG_MQTT_TRANSPORT_WEBSOCKET=y -CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y -# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set -# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set -# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set -# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set -# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set -# CONFIG_MQTT_CUSTOM_OUTBOX is not set -# end of ESP-MQTT Configurations +# CONFIG_MBEDTLS_RIPEMD160_C is not set +# default: +CONFIG_MBEDTLS_MD_C=y +# default: +CONFIG_MBEDTLS_MD5_C=y +# default: +CONFIG_MBEDTLS_SHA1_C=y +# default: +# CONFIG_MBEDTLS_SHA224_C is not set +# default: +CONFIG_MBEDTLS_SHA256_C=y +# default: +CONFIG_MBEDTLS_SHA384_C=y +CONFIG_MBEDTLS_SHA512_C=y +# default: +# CONFIG_MBEDTLS_SHA3_C is not set +CONFIG_MBEDTLS_ROM_MD5=y +# end of Hash functions # -# Newlib +# Hardware Acceleration # -CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y -# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set -# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set -# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set -# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set -CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y -# CONFIG_NEWLIB_NANO_FORMAT is not set -CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y -# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set -# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set -# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set -# end of Newlib +CONFIG_MBEDTLS_HARDWARE_SHA=y +CONFIG_MBEDTLS_HARDWARE_MPI=y +CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI=y +CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y +CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 + +# +# Security hardening +# +# default: +# CONFIG_MBEDTLS_CONSTANT_TIME_PRIME_GEN is not set +# end of Security hardening + +CONFIG_MBEDTLS_HARDWARE_AES=y +# default: +# CONFIG_MBEDTLS_AES_SOFT_FALLBACK is not set +CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y +CONFIG_MBEDTLS_AES_USE_INTERRUPT=y +CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 +# default: +CONFIG_MBEDTLS_AES_HW_SMALL_DATA_LEN_OPTIM=y +# CONFIG_MBEDTLS_SECURE_ELEMENT_DRIVER_ENABLED is not set +# default: +CONFIG_MBEDTLS_HARDWARE_RSA_DS_PERIPHERAL=y +# end of Hardware Acceleration + +# +# Entropy and Random Number Generation +# +# default: +# CONFIG_MBEDTLS_ENTROPY_FORCE_SHA256 is not set +# default: +CONFIG_MBEDTLS_CTR_DRBG_C=y +# default: +CONFIG_MBEDTLS_HMAC_DRBG_C=y +# end of Entropy and Random Number Generation + +# +# Encoding/Decoding +# +# default: +CONFIG_MBEDTLS_BASE64_C=y +# default: +CONFIG_MBEDTLS_PKCS5_C=y +CONFIG_MBEDTLS_PKCS7_C=y +# default: +CONFIG_MBEDTLS_PKCS1_V15=y +# default: +CONFIG_MBEDTLS_PKCS1_V21=y +# end of Encoding/Decoding + +# +# Stream Cipher +# +# CONFIG_MBEDTLS_CHACHA20_C is not set +# end of Stream Cipher +# end of mbedTLS # # NVS @@ -1555,6 +2559,10 @@ CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_NVS_ENCRYPTION is not set # CONFIG_NVS_ASSERT_ERROR_CHECK is not set # CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set +# default: +# CONFIG_NVS_BDL_STACK is not set +# default: +# CONFIG_NVS_FLASH_VERIFY_ERASE is not set # end of NVS # @@ -1563,25 +2571,13 @@ CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_OPENTHREAD_ENABLED is not set # -# Thread Operational Dataset +# OpenThread Spinel # -CONFIG_OPENTHREAD_NETWORK_NAME="OpenThread-ESP" -CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX="fd00:db8:a0:0::/64" -CONFIG_OPENTHREAD_NETWORK_CHANNEL=15 -CONFIG_OPENTHREAD_NETWORK_PANID=0x1234 -CONFIG_OPENTHREAD_NETWORK_EXTPANID="dead00beef00cafe" -CONFIG_OPENTHREAD_NETWORK_MASTERKEY="00112233445566778899aabbccddeeff" -CONFIG_OPENTHREAD_NETWORK_PSKC="104810e2315100afd6bc9215a6bfac53" -# end of Thread Operational Dataset - -CONFIG_OPENTHREAD_XTAL_ACCURACY=130 # CONFIG_OPENTHREAD_SPINEL_ONLY is not set -CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y +# end of OpenThread Spinel -# -# Thread Address Query Config -# -# end of Thread Address Query Config +# default: +# CONFIG_OPENTHREAD_DEBUG is not set # end of OpenThread # @@ -1590,6 +2586,8 @@ CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y +# default: +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y # end of Protocomm # @@ -1598,15 +2596,28 @@ CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_PTHREAD_STACK_MIN=768 +# default: CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads +# +# SD Protocol Layer Configuration +# +# default: +CONFIG_SD_ENABLE_SDIO_SUPPORT=y +# default: +CONFIG_SD_READY_POLL_PERIOD_START_US=100 +# end of SD Protocol Layer Configuration + # # MMU Config # +# default: CONFIG_MMU_PAGE_SIZE_64KB=y +# default: CONFIG_MMU_PAGE_MODE="64KB" +# default: CONFIG_MMU_PAGE_SIZE=0x10000 # end of MMU Config @@ -1618,6 +2629,7 @@ CONFIG_MMU_PAGE_SIZE=0x10000 # SPI Flash behavior when brownout # CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y +# default: CONFIG_SPI_FLASH_BROWNOUT_RESET=y # end of SPI Flash behavior when brownout @@ -1628,9 +2640,14 @@ CONFIG_SPI_FLASH_BROWNOUT_RESET=y # # Features here require specific hardware (READ DOCS FIRST!) # -CONFIG_SPI_FLASH_SUSPEND_QVL_SUPPORTED=y # CONFIG_SPI_FLASH_AUTO_SUSPEND is not set CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 +# default: +# CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set +# default: +# CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set +# default: +CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM=y # end of Optional and Experimental Features (READ DOCS FIRST) # end of Main Flash configuration @@ -1639,7 +2656,6 @@ CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set -CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y # CONFIG_SPI_FLASH_ROM_IMPL is not set CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set @@ -1656,13 +2672,20 @@ CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 # # Auto-detect flash chips # -CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_TH_SUPPORTED=y +# default: +CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_GD_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_TH_SUPPORT_ENABLED=y CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y @@ -1745,12 +2768,17 @@ CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y # CONFIG_VFS_SELECT_IN_RAM is not set CONFIG_VFS_SUPPORT_TERMIOS=y CONFIG_VFS_MAX_COUNT=8 +# default: +# CONFIG_VFS_SUPPRESS_CTX_DEPRECATION is not set # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # end of Host File System I/O (Semihosting) + +# default: +CONFIG_VFS_INITIALIZE_DEV_NULL=y # end of Virtual file system # @@ -1758,18 +2786,9 @@ CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y +# default: CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling - -# -# Wi-Fi Provisioning Manager -# -CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 -CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 -# CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION is not set -CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y -# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set -# end of Wi-Fi Provisioning Manager # end of Component config # CONFIG_IDF_EXPERIMENTAL_FEATURES is not set @@ -1777,6 +2796,8 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y # Deprecated options for backward compatibility # CONFIG_APP_BUILD_TYPE_ELF_RAM is not set # CONFIG_NO_BLOBS is not set +# CONFIG_APP_ROLLBACK_ENABLE is not set +# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set @@ -1784,7 +2805,6 @@ CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 -# CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set # CONFIG_FLASHMODE_QIO is not set # CONFIG_FLASHMODE_QOUT is not set @@ -1806,11 +2826,9 @@ CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set -# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set -CONFIG_ESP32_APPTRACE_DEST_NONE=y -CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y # CONFIG_EXTERNAL_COEX_ENABLE is not set # CONFIG_ESP_WIFI_EXTERNAL_COEXIST_ENABLE is not set +# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y @@ -1824,6 +2842,38 @@ CONFIG_ESP32C3_RTC_CLK_SRC_INT_RC=y # CONFIG_ESP32C3_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_ESP32C3_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_ESP32C3_RTC_CLK_CAL_CYCLES=1024 +CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_BROWNOUT_DET=y +CONFIG_ESP32C3_BROWNOUT_DET=y +CONFIG_BROWNOUT_DET_LVL_SEL_7=y +CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_7=y +# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_2 is not set +CONFIG_BROWNOUT_DET_LVL=7 +CONFIG_ESP32C3_BROWNOUT_DET_LVL=7 +CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y +CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set +CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y +CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y +CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC_SYSTIMER=y +# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set +# CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set +# CONFIG_ESP32C3_TIME_SYSCALL_USE_SYSTIMER is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set +# CONFIG_ESP32C3_TIME_SYSCALL_USE_NONE is not set CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20 @@ -1831,21 +2881,25 @@ CONFIG_ESP32_PHY_MAX_TX_POWER=20 # CONFIG_REDUCE_PHY_TX_POWER is not set # CONFIG_ESP32_REDUCE_PHY_TX_POWER is not set CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU=y +CONFIG_CONSOLE_UART_DEFAULT=y +# CONFIG_CONSOLE_UART_CUSTOM is not set +# CONFIG_CONSOLE_UART_NONE is not set +# CONFIG_ESP_CONSOLE_UART_NONE is not set +CONFIG_CONSOLE_UART=y +CONFIG_CONSOLE_UART_NUM=0 +CONFIG_CONSOLE_UART_BAUDRATE=115200 # CONFIG_ESP32C3_DEFAULT_CPU_FREQ_80 is not set CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y CONFIG_ESP32C3_DEFAULT_CPU_FREQ_MHZ=160 +CONFIG_ESP_SYSTEM_PMP_IDRAM_SPLIT=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_VIA_TEE=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y CONFIG_ESP32C3_MEMPROT_FEATURE=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y CONFIG_ESP32C3_MEMPROT_FEATURE_LOCK=y CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_MAIN_TASK_STACK_SIZE=3584 -CONFIG_CONSOLE_UART_DEFAULT=y -# CONFIG_CONSOLE_UART_CUSTOM is not set -# CONFIG_CONSOLE_UART_NONE is not set -# CONFIG_ESP_CONSOLE_UART_NONE is not set -CONFIG_CONSOLE_UART=y -CONFIG_CONSOLE_UART_NUM=0 -CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_TASK_WDT=y @@ -1855,25 +2909,9 @@ CONFIG_TASK_WDT_TIMEOUT_S=5 CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y # CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set CONFIG_ESP32C3_DEBUG_OCDAWARE=y -CONFIG_BROWNOUT_DET=y -CONFIG_ESP32C3_BROWNOUT_DET=y -CONFIG_ESP32C3_BROWNOUT_DET=y -CONFIG_BROWNOUT_DET_LVL_SEL_7=y -CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_7=y -# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_2 is not set -CONFIG_BROWNOUT_DET_LVL=7 -CONFIG_ESP32C3_BROWNOUT_DET_LVL=7 CONFIG_IPC_TASK_STACK_SIZE=1024 CONFIG_TIMER_TASK_STACK_SIZE=3584 +# CONFIG_ESP32_APPTRACE_ENABLE is not set CONFIG_ESP32_WIFI_ENABLED=y CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 @@ -1885,8 +2923,33 @@ CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP32_WIFI_TX_BA_WIN=6 CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y -CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y CONFIG_ESP32_WIFI_RX_BA_WIN=6 +CONFIG_ESP32_WIFI_NVS_ENABLED=y +CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 +CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 +CONFIG_ESP32_WIFI_IRAM_OPT=y +CONFIG_ESP32_WIFI_RX_IRAM_OPT=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y +CONFIG_WPA_MBEDTLS_CRYPTO=y +CONFIG_WPA_MBEDTLS_TLS_CLIENT=y +# CONFIG_WPA_WAPI_PSK is not set +# CONFIG_WPA_SUITE_B_192 is not set +# CONFIG_WPA_11KV_SUPPORT is not set +# CONFIG_WPA_MBO_SUPPORT is not set +# CONFIG_WPA_DPP_SUPPORT is not set +# CONFIG_WPA_11R_SUPPORT is not set +# CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set +# CONFIG_WPA_WPS_STRICT is not set +# CONFIG_WPA_DEBUG_PRINT is not set +CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 +CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 +CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=1 +CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 +# CONFIG_ESP32_WIFI_CSI_ENABLED is not set +CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y +CONFIG_ESP32_WIFI_TX_BA_WIN=6 +CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y CONFIG_ESP32_WIFI_RX_BA_WIN=6 CONFIG_ESP32_WIFI_NVS_ENABLED=y CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 @@ -1906,7 +2969,6 @@ CONFIG_WPA_MBEDTLS_TLS_CLIENT=y # CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set # CONFIG_WPA_WPS_STRICT is not set # CONFIG_WPA_DEBUG_PRINT is not set -# CONFIG_WPA_TESTING_OPTIONS is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y @@ -1936,10 +2998,8 @@ CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set -CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC_SYSTIMER=y -# CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC is not set -# CONFIG_ESP32C3_TIME_SYSCALL_USE_SYSTIMER is not set -# CONFIG_ESP32C3_TIME_SYSCALL_USE_NONE is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 diff --git a/software/wifi/raw_u64/CMakeLists.txt b/software/wifi/raw_u64/CMakeLists.txt index a8abcf637..ecffda6a1 100644 --- a/software/wifi/raw_u64/CMakeLists.txt +++ b/software/wifi/raw_u64/CMakeLists.txt @@ -1,6 +1,9 @@ # The following lines of boilerplate have to be in your project's CMakeLists # in this exact order for cmake to work correctly -cmake_minimum_required(VERSION 3.5) +cmake_minimum_required(VERSION 3.16) include($ENV{IDF_PATH}/tools/cmake/project.cmake) +if(IDF_VERSION_MAJOR LESS 6) + message(FATAL_ERROR "raw_u64 needs ESP-IDF 6, not ${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR} (see software/wifi/raw_u64/README.md)") +endif() project(bridge) diff --git a/software/wifi/raw_u64/README.md b/software/wifi/raw_u64/README.md index dec4d5ebb..6be9402a5 100644 --- a/software/wifi/raw_u64/README.md +++ b/software/wifi/raw_u64/README.md @@ -1,4 +1,47 @@ -# Wifi SCAN Example +# ESP32 WiFi bridge (raw_u64) + +## Building + +The bridge needs ESP-IDF 6 (CI uses v6.1.1); `CMakeLists.txt` stops an older one at configure. +`docker/Dockerfile` still installs ESP-IDF 5.3.1, so CI builds this project (and raw_c3 and u64ctrl) in +`espressif/idf:v6.1.1`, pinned by digest in `.github/workflows/build.yml`. Locally, from the top of the +repository, the same way as CI: + + docker run --rm --user $(id -u):$(id -g) -e HOME=/tmp -v "$PWD":/project -w /project/software/wifi/raw_u64 \ + espressif/idf:v6.1.1@sha256:2b4f966c37eaedc19542b0637a5f850b2eff9478d8e858192aa0073d92c2dc91 idf.py build + +then `make u64_no_esp` packs `build/bridge.bin` into `update.u64`. `make esp32_raw_u64` (and so +`make u64`) works only where `IDF_PATH` is an ESP-IDF 6. Once `build/` exists here, +`make clean` also needs ESP-IDF 6; otherwise delete `software/wifi/raw_u64/build` by hand. + +`software/io/uart/cmd_buffer.c` is compiled into all three ESP32 projects (raw_u64, raw_c3 and u64ctrl). + +`sdkconfig` marks values that follow ESP-IDF's defaults with `# default:`; a reconfigure on a newer +ESP-IDF takes its new defaults there. After any ESP-IDF update, diff the values, not just the build. + +mbedTLS is ESP-IDF's own, as ESP-IDF imports it: the build carries no patch to it. Known issue: +stock mbedTLS refuses a cookie in a TLS 1.3 HelloRetryRequest (Mbed-TLS/mbedtls#9543), so a +server that sends one, as OpenJDK's JSSE does, fails the handshake. + +## Testing the TLS engine + +The engine (`../tls/tls_engine.c`, `../tls/tls_rpc.c`; `software/wifi/tls` is shared by module firmware, and holds the RPC layout, `rpc_tls.h`) is checked from the C64's side by the E2E +suite `tests/e2e/io/command_interface/net_tls_test.py` (against a device) and `net_tls_selftest.py` +(against a simulated one), and the Ultimate's side of the module calls by +`make -C target/pc/linux/wifitls test`. The engine can also be run on its own, on QEMU or an +ESP32 dev board, with a red/green gate: . + +## The certificate bundle + +The roots the bridge trusts in BUNDLE mode are the ones `software/u64ctrl/ca/cacert.pem` holds, the +Mozilla root list the control module's recovery trusts, not ESP-IDF's copy (v6.1.1 ships Mozilla's +data of 2026-02-11, with roots Mozilla has since dropped). There is one file for both modules: +`sdkconfig` selects `CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE`, so none of ESP-IDF's roots are +merged in, and points `CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH` at `../../u64ctrl/ca/cacert.pem`. +`CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_CROSS_SIGNED_VERIFY=y` is set explicitly, and `../tls/tls_engine.c` +refuses to build without it. How the list is checked and refreshed is in `software/u64ctrl/ca/README.md`. + +## The Wi-Fi scan (from the ESP-IDF example this project started as) This example shows how to use the scan functionality of the Wi-Fi driver of ESP32. diff --git a/software/wifi/raw_u64/main/CMakeLists.txt b/software/wifi/raw_u64/main/CMakeLists.txt index 2400eeadf..95d6b07c3 100644 --- a/software/wifi/raw_u64/main/CMakeLists.txt +++ b/software/wifi/raw_u64/main/CMakeLists.txt @@ -1,4 +1,15 @@ set(EXTERNAL "../../../io/uart") +# The TLS engine and its RPC commands are shared with other module firmware: software/wifi/tls +set(TLS_DIR "../../tls") +# BRIDGE_TLS_STUB (idf.py -D BRIDGE_TLS_STUB=1) builds a size-measurement image without the TLS engine +if(BRIDGE_TLS_STUB) + set(TLS_SRCS "${TLS_DIR}/tls_engine_stub.c" "${TLS_DIR}/tls_rng_gate.c") +else() + set(TLS_SRCS "${TLS_DIR}/tls_engine.c" "${TLS_DIR}/tls_rng_gate.c") +endif() set(COMMON "../../common") -idf_component_register(SRCS "main.c" "my_uart.c" "rpc_dispatch.c" "dump_hex.c" "wifi_modem.c" "sntp.c" ${EXTERNAL}/cmd_buffer.c ${COMMON}/wifi_radio.c ${COMMON}/wifi_radio_esp.c ${COMMON}/radio_boot.c - INCLUDE_DIRS "." ${EXTERNAL} ${COMMON}) \ No newline at end of file +idf_component_register(SRCS "main.c" "my_uart.c" "rpc_dispatch.c" "dump_hex.c" "wifi_modem.c" "sntp.c" "${TLS_DIR}/tls_rpc.c" ${TLS_SRCS} ${EXTERNAL}/cmd_buffer.c ${COMMON}/wifi_radio.c ${COMMON}/wifi_radio_esp.c ${COMMON}/radio_boot.c ${COMMON}/radio_entropy.c ${COMMON}/radio_entropy_esp.c + INCLUDE_DIRS "." ${TLS_DIR} ${EXTERNAL} ${COMMON} + LDFRAGMENTS "linker.lf") +# The TLS task's random draws hold the entropy gate (tls_rng_gate.h): every draw of mbedTLS goes through this function +target_link_options(${COMPONENT_LIB} INTERFACE "-Wl,--wrap=mbedtls_psa_external_get_random") diff --git a/software/wifi/raw_u64/main/linker.lf b/software/wifi/raw_u64/main/linker.lf new file mode 100644 index 000000000..8b37f736a --- /dev/null +++ b/software/wifi/raw_u64/main/linker.lf @@ -0,0 +1,39 @@ +[mapping:raw_u64_hot] +archive: libmain.a +entries: + my_uart (noflash) + cmd_buffer (noflash) + wifi_modem:hacked_recv (noflash) + rpc_dispatch:dispatch (noflash) + rpc_dispatch:dispatch_command (noflash) + tls_rpc:tls_rpc_note_block (noflash) + +[mapping:raw_u64_netif] +archive: libesp_netif.a +entries: + esp_netif_lwip:esp_netif_transmit (noflash) + esp_netif_lwip:esp_netif_receive (noflash) + esp_netif_lwip:esp_netif_free_rx_buffer (noflash) + wlanif:wlanif_input (noflash) + esp_pbuf_ref:esp_pbuf_allocate (noflash) + esp_pbuf_ref:esp_pbuf_free (noflash) + +[mapping:raw_u64_wifi_netif] +archive: libesp_wifi.a +entries: + wifi_netif:wifi_transmit (noflash) + wifi_netif:wifi_free (noflash) + +[mapping:raw_u64_pp] +archive: libpp.a +entries: + if_hwctrl:esp_wifi_internal_free_rx_buffer (noflash) + +[mapping:raw_u64_lwip] +archive: liblwip.a +entries: + pbuf:pbuf_free (noflash) + pbuf:pbuf_alloced_custom (noflash) + mem:mem_malloc (noflash) + mem:mem_free (noflash) + sys_arch (noflash) diff --git a/software/wifi/raw_u64/main/my_uart.c b/software/wifi/raw_u64/main/my_uart.c index 824c9d65a..992649445 100644 --- a/software/wifi/raw_u64/main/my_uart.c +++ b/software/wifi/raw_u64/main/my_uart.c @@ -23,7 +23,7 @@ #include "freertos/ringbuf.h" #include "hal/uart_hal.h" #include "hal/gpio_hal.h" -#include "soc/uart_periph.h" +#include "hal/uart_periph.h" #include "soc/rtc_cntl_reg.h" #include "driver/uart.h" #include "driver/gpio.h" @@ -368,7 +368,7 @@ BaseType_t my_uart_get_buffer(uint8_t uart_num, command_buf_t **buf, TickType_t } #include "esp_check.h" -esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, int intr_alloc_flags, uart_isr_handle_t *handle) +esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void *), void *arg, int intr_alloc_flags, intr_handle_t *handle) { int ret; ESP_RETURN_ON_FALSE((uart_num < UART_NUM_MAX), ESP_FAIL, UART_TAG, "uart_num error"); @@ -395,8 +395,8 @@ esp_err_t my_uart_init(command_buf_context_t *buffers, uint8_t uart_num) const uart_intr_config_t interrupt_config = { .intr_enable_mask = UART_INTR_RXFIFO_TOUT | UART_INTR_RXFIFO_FULL, .rx_timeout_thresh = 2, - .txfifo_empty_intr_thresh = 10, - .rxfifo_full_thresh = 120, + .txfifo_empty_intr_thresh = 64, + .rxfifo_full_thresh = 64, }; const uart_config_t uart_config = { diff --git a/software/wifi/raw_u64/main/rpc_calls.h b/software/wifi/raw_u64/main/rpc_calls.h index 031ca9d50..51481eb89 100644 --- a/software/wifi/raw_u64/main/rpc_calls.h +++ b/software/wifi/raw_u64/main/rpc_calls.h @@ -20,6 +20,8 @@ typedef struct { uint16_t sequence; } rpc_header_t; +#include "rpc_shared.h" + typedef struct { rpc_header_t hdr; int esp_err; // to be casted to esp_err_t @@ -126,6 +128,10 @@ typedef struct { esp_datetime_t datetime; } rpc_get_time_resp; +//---------------------------------- +//---------------------------------- +#include "rpc_tls.h" // CMD_TLS_* opcodes and the TLS session layouts, software/wifi/tls + //---------------------------------- // send raw packet typedef struct { @@ -177,6 +183,8 @@ typedef struct { #define CMD_GET_TIME 0x10 #define CMD_CLEAR_APS 0x11 #define CMD_WIFI_AUTOCONNECT 0x12 +// 0x13-0x1F are u64ctrl's; 0x20 is CMD_GET_RANDOM, in rpc_shared.h +// CMD_TLS_OPEN .. CMD_TLS_SET_CA (0x30-0x35): rpc_tls.h /* #define CMD_SOCKET 0x11 diff --git a/software/wifi/raw_u64/main/rpc_dispatch.c b/software/wifi/raw_u64/main/rpc_dispatch.c index 4168da6bf..0286062c2 100644 --- a/software/wifi/raw_u64/main/rpc_dispatch.c +++ b/software/wifi/raw_u64/main/rpc_dispatch.c @@ -12,6 +12,9 @@ #include "esp_wifi.h" #include "esp_log.h" #include "driver/uart.h" +#include "esp_random.h" +#include "esp_heap_caps.h" +#include "esp_timer.h" #include "rpc_calls.h" #include "rpc_dispatch.h" #include "my_uart.h" @@ -19,6 +22,7 @@ #include "pinout.h" #include "wifi_modem.h" #include "sntp.h" +#include "tls_rpc.h" // not officially supported #include "../lwip/esp_netif_lwip_internal.h" @@ -168,7 +172,7 @@ extern esp_netif_t *my_sta_netif; void cmd_send_eth_packet(command_buf_t *buf) { rpc_send_eth_req *param = (rpc_send_eth_req *)buf->data; - err_t _err = esp_netif_transmit(my_sta_netif, ¶m->data, param->length); + esp_netif_transmit(my_sta_netif, ¶m->data, param->length); my_uart_free_buffer(UART_CHAN, buf); } @@ -251,6 +255,16 @@ void cmd_clear_aps(command_buf_t *buf) my_uart_transmit_packet(UART_CHAN, buf); } +_Static_assert(RPC_ERR_ENTROPY_BUSY == ESP_ERR_TIMEOUT, "RPC_ERR_ENTROPY_BUSY is an esp_err_t"); + +void cmd_get_random(command_buf_t *buf) +{ + buf->size = radio_entropy_serve_get_random(buf->data, buf->size, (void (*)(void *, size_t))esp_fill_random); + // The gate is released: the answer is sent without it + my_uart_transmit_packet(UART_CHAN, buf); +} + + void cmd_not_implemented(command_buf_t *buf) { rpc_espcmd_resp *resp = (rpc_espcmd_resp *)buf->data; @@ -274,11 +288,85 @@ void send_keepalive() } } +// One command on the dispatcher. TLS commands go to the TLS task, so a handshake never blocks +// Wi-Fi TX; the time each command holds the dispatcher is what TLS_STATS reports as block_max_ms. +void dispatch_command(command_buf_t *pbuffer) +{ + rpc_header_t *hdr = (rpc_header_t *)(pbuffer->data); + int64_t start = esp_timer_get_time(); + switch(hdr->command) { + case CMD_SEND_PACKET: + cmd_send_eth_packet(pbuffer); + break; + case CMD_ECHO: + cmd_echo(pbuffer); + break; + case CMD_IDENTIFY: + cmd_identify(pbuffer); + break; + case CMD_SET_BAUD: + cmd_setbaud(pbuffer); + break; + case CMD_WIFI_SCAN: + cmd_scan(pbuffer); + break; + case CMD_WIFI_CONNECT: + cmd_wifi_connect(pbuffer); + break; + case CMD_WIFI_DISCONNECT: + cmd_wifi_disconnect(pbuffer); + break; + case CMD_WIFI_AUTOCONNECT: + cmd_wifi_autoconnect(pbuffer); + break; + case CMD_WIFI_GETMAC: + cmd_getmac(pbuffer); + break; + case CMD_MACHINE_OFF: + cmd_off(pbuffer); + break; + case CMD_MODEM_ON: + cmd_modem_on(pbuffer); + break; + case CMD_MODEM_OFF: + cmd_modem_off(pbuffer); + break; + case CMD_WIFI_DISABLE: + case CMD_WIFI_ENABLE: + cmd_wifi_endisable(pbuffer); + break; + case CMD_WIFI_IS_CONNECTED: + cmd_get_connection(pbuffer); + break; + case CMD_GET_TIME: + cmd_get_time(pbuffer); + break; + case CMD_CLEAR_APS: + cmd_clear_aps(pbuffer); + break; + case CMD_GET_RANDOM: + cmd_get_random(pbuffer); + break; + case CMD_TLS_OPEN: + case CMD_TLS_STEP: + case CMD_TLS_CLOSE: + case CMD_TLS_STATS: + case CMD_TLS_CLOSE_ALL: + case CMD_TLS_SET_CA: + tls_rpc_dispatch(pbuffer); + break; + default: + cmd_not_implemented(pbuffer); + break; + } + int64_t ms = (esp_timer_get_time() - start) / 1000; + tls_rpc_note_block(ms); +} + void dispatch(void *ct) { QueueHandle_t queue = (QueueHandle_t)ct; command_buf_t *pbuffer; - rpc_header_t *hdr; int led = 0; printf("Dispatcher Start. Queue = %p\n", queue); @@ -293,67 +381,15 @@ void dispatch(void *ct) #if UART_DEBUG_RX printf("Received buffer %d with %d bytes.\n", pbuffer->bufnr, pbuffer->size); #endif - hdr = (rpc_header_t *)(pbuffer->data); - switch(hdr->command) { - case CMD_SEND_PACKET: - cmd_send_eth_packet(pbuffer); - break; - case CMD_ECHO: - cmd_echo(pbuffer); - break; - case CMD_IDENTIFY: - cmd_identify(pbuffer); - break; - case CMD_SET_BAUD: - cmd_setbaud(pbuffer); - break; - case CMD_WIFI_SCAN: - cmd_scan(pbuffer); - break; - case CMD_WIFI_CONNECT: - cmd_wifi_connect(pbuffer); - break; - case CMD_WIFI_DISCONNECT: - cmd_wifi_disconnect(pbuffer); - break; - case CMD_WIFI_AUTOCONNECT: - cmd_wifi_autoconnect(pbuffer); - break; - case CMD_WIFI_GETMAC: - cmd_getmac(pbuffer); - break; - case CMD_MACHINE_OFF: - cmd_off(pbuffer); - break; - case CMD_MODEM_ON: - cmd_modem_on(pbuffer); - break; - case CMD_MODEM_OFF: - cmd_modem_off(pbuffer); - break; - case CMD_WIFI_DISABLE: - case CMD_WIFI_ENABLE: - cmd_wifi_endisable(pbuffer); - break; - case CMD_WIFI_IS_CONNECTED: - cmd_get_connection(pbuffer); - break; - case CMD_GET_TIME: - cmd_get_time(pbuffer); - break; - case CMD_CLEAR_APS: - cmd_clear_aps(pbuffer); - break; - default: - cmd_not_implemented(pbuffer); - break; - } + dispatch_command(pbuffer); } } void start_dispatch(QueueHandle_t queue) { - xTaskCreate( dispatch, "Dispatch Task", DISPATCHER_STACK, queue, tskIDLE_PRIORITY + 1, NULL ); + tls_rpc_start(); + // Core 1, above the system tasks: the UART ISR that feeds this queue runs on core 1 too + xTaskCreatePinnedToCore( dispatch, "Dispatch Task", DISPATCHER_STACK, queue, 19, NULL, 1 ); } #if MULTITHREADED diff --git a/software/wifi/raw_u64/main/rpc_dispatch.h b/software/wifi/raw_u64/main/rpc_dispatch.h index 025d9c87a..64e003e1c 100644 --- a/software/wifi/raw_u64/main/rpc_dispatch.h +++ b/software/wifi/raw_u64/main/rpc_dispatch.h @@ -22,12 +22,23 @@ typedef struct { void create_dispatchers(int stacksize, command_buf_context_t *bufs); void dispatch(void *ct); +void dispatch_command(command_buf_t *buf); void start_dispatch(QueueHandle_t queue); void send_button_event(uint8_t button); void send_keepalive(); -#define IDENT_STRING "ESP32 WiFi Bridge V1.18" +#define IDENT_STRING "ESP32 WiFi Bridge V1.26" #define IDENT_MAJOR 1 +// 1.26: the TLS root list (software/u64ctrl/ca) drops the roots NSS master has deleted, no longer trusts +// for websites or distrusts for every certificate still valid (Buypass Class 2 and 3, QuoVadis Root CA 1 +// and 3 G3, Certigna Root CA, Izenpe.com). +// 1.25: every random draw of the TLS task holds the entropy gate for that draw (tls_rng_gate), so a radio +// start or stop or a read of the voltages cannot switch the random source off in the middle of one; +// a draw with no source ends the handshake as NO ENTROPY. +// 1.22: TLS client sessions (CMD_TLS_*) on their own task, and the Mozilla root list of +// software/u64ctrl/ca as the certificate bundle. +// 1.21: CMD_GET_RANDOM, served with the radio off too, from the SAR ADC source. +// 1.20: built with ESP-IDF 6.1.1. // 1.18: the idle connector handles every queued command and event before it waits, so a // Disable behind an Enable is not left queued; the wait for its own disconnect is bounded // (3 s); events from before a radio stop are dropped; a CMD_WIFI_CONNECT must hold the @@ -44,8 +55,8 @@ void send_keepalive(); // Disconnected forever. The Ultimate's updater only reflashes the module // when this differs from what the module reports, so a module change that // does not bump it is silently never installed. -#define IDENT_MINOR 18 +#define IDENT_MINOR 26 #define MULTITHREADED 0 -#define DISPATCHER_STACK 3072 +#define DISPATCHER_STACK 3072 // TLS runs on its own task, so this stays small #endif /* SOFTWARE_WIFI_SCAN_MAIN_RPC_DISPATCH_H_ */ diff --git a/software/wifi/raw_u64/main/sntp.c b/software/wifi/raw_u64/main/sntp.c index 0b471d5df..271a15d28 100644 --- a/software/wifi/raw_u64/main/sntp.c +++ b/software/wifi/raw_u64/main/sntp.c @@ -21,6 +21,12 @@ #include "rpc_calls.h" static const char *TAG = "sntp"; +static volatile int time_synced; + +int sntp_has_time(void) +{ + return time_synced; +} void ____sntp_sync_time(struct timeval *tv) { @@ -33,6 +39,7 @@ void time_sync_notification_cb(struct timeval *tv) { ESP_LOGI(TAG, "Notification of a time synchronization event, time set to %ld s %ld us", (long int)tv->tv_sec, (long int)tv->tv_usec); settimeofday(tv, NULL); + time_synced = 1; } #ifndef INET6_ADDRSTRLEN diff --git a/software/wifi/raw_u64/main/sntp.h b/software/wifi/raw_u64/main/sntp.h index 5b4b64099..6ad2f14db 100644 --- a/software/wifi/raw_u64/main/sntp.h +++ b/software/wifi/raw_u64/main/sntp.h @@ -8,6 +8,7 @@ void configure_sntp_servers(void); void obtain_time(void); void print_time(void); void sntp_get_time(const char *zone, esp_datetime_t *datetime); +int sntp_has_time(void); // nonzero once an SNTP sync has set the clock void print_all_zones(void); void print_time_for_zone(const char *zone); diff --git a/software/wifi/raw_u64/main/wifi_modem.c b/software/wifi/raw_u64/main/wifi_modem.c index 35c6bc84f..a28398147 100644 --- a/software/wifi/raw_u64/main/wifi_modem.c +++ b/software/wifi/raw_u64/main/wifi_modem.c @@ -147,7 +147,8 @@ static err_t hacked_recv(struct pbuf *p, struct netif *inp) return ERR_OK; } else { ESP_LOGW(TAG, "No buffer to send packet."); - return ERR_BUF; + pbuf_free(p); // dropped, and reported as handled + return ERR_OK; } } else { // dropped, wrong mac and no broadcast pbuf_free(p); @@ -1073,6 +1074,18 @@ static void start_connector() xTaskCreate(connect_thread, "Connector", 4096, NULL, tskIDLE_PRIORITY + 1, NULL); } +static SemaphoreHandle_t uart_init_done; +static esp_err_t uart_init_result; + +// esp_intr_alloc() binds the interrupt to the core it is called on. The UART ISR must not share +// core 0 (and its cache) with the WiFi task, so the init runs on core 1. +static void uart_init_task(void *a) +{ + uart_init_result = my_uart_init(&work_buffers, UART_NUM_1); + xSemaphoreGive(uart_init_done); + vTaskDelete(NULL); +} + void setup_modem() { // Initialize NVS @@ -1097,10 +1110,16 @@ void setup_modem() #endif ESP_LOGI(TAG, "my_uart_init..."); // Now install the driver for UART1. We use our own buffer mechanism and interrupt routine - ESP_ERROR_CHECK(my_uart_init(&work_buffers, UART_NUM_1)); + uart_init_done = xSemaphoreCreateBinary(); + ESP_ERROR_CHECK(uart_init_done ? ESP_OK : ESP_ERR_NO_MEM); + ESP_ERROR_CHECK(xTaskCreatePinnedToCore(uart_init_task, "uart_init", 3072, NULL, tskIDLE_PRIORITY + 2, NULL, 1) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM); + xSemaphoreTake(uart_init_done, portMAX_DELAY); + ESP_ERROR_CHECK(uart_init_result); ESP_LOGI(TAG, "wifi_init..."); wifi_init(); + radio_entropy_init(); + radio_entropy_start_poll_task(); ESP_LOGI(TAG, "start wifi connector..."); // A restart that neither a power-up nor the Ultimate caused (the Ultimate drives the // module's enable pin, which reads as a power-up or an external reset) diff --git a/software/wifi/raw_u64/main/wifi_modem.h b/software/wifi/raw_u64/main/wifi_modem.h index 8c232c63e..13d50ba1d 100644 --- a/software/wifi/raw_u64/main/wifi_modem.h +++ b/software/wifi/raw_u64/main/wifi_modem.h @@ -2,6 +2,7 @@ #define WIFI_MODEM_H #include "rpc_calls.h" +#include "radio_entropy.h" extern QueueHandle_t connect_commands; extern SemaphoreHandle_t connect_semaphore; diff --git a/software/wifi/raw_u64/sdkconfig b/software/wifi/raw_u64/sdkconfig index c1c68ab8e..2a2211c53 100644 --- a/software/wifi/raw_u64/sdkconfig +++ b/software/wifi/raw_u64/sdkconfig @@ -1,246 +1,428 @@ # # Automatically generated file. DO NOT EDIT. -# Espressif IoT Development Framework (ESP-IDF) 5.3.1 Project Configuration +# Espressif IoT Development Framework (ESP-IDF) 6.1.1 Project Configuration # -CONFIG_SOC_BROWNOUT_RESET_SUPPORTED="Not determined" -CONFIG_SOC_TWAI_BRP_DIV_SUPPORTED="Not determined" -CONFIG_SOC_DPORT_WORKAROUND="Not determined" +# default: CONFIG_SOC_CAPS_ECO_VER_MAX=301 +# default: CONFIG_SOC_ADC_SUPPORTED=y +# default: CONFIG_SOC_DAC_SUPPORTED=y +# default: CONFIG_SOC_UART_SUPPORTED=y +# default: CONFIG_SOC_MCPWM_SUPPORTED=y +# default: CONFIG_SOC_GPTIMER_SUPPORTED=y +# default: CONFIG_SOC_SDMMC_HOST_SUPPORTED=y +# default: CONFIG_SOC_BT_SUPPORTED=y +# default: CONFIG_SOC_PCNT_SUPPORTED=y +# default: CONFIG_SOC_PHY_SUPPORTED=y +# default: CONFIG_SOC_WIFI_SUPPORTED=y +# default: CONFIG_SOC_SDIO_SLAVE_SUPPORTED=y +# default: CONFIG_SOC_TWAI_SUPPORTED=y +# default: CONFIG_SOC_EFUSE_SUPPORTED=y +# default: CONFIG_SOC_EMAC_SUPPORTED=y +# default: CONFIG_SOC_ULP_SUPPORTED=y +# default: CONFIG_SOC_CCOMP_TIMER_SUPPORTED=y +# default: CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y +# default: CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED=y +# default: CONFIG_SOC_RTC_MEM_SUPPORTED=y +# default: +CONFIG_SOC_RTC_TIMER_SUPPORTED=y +# default: CONFIG_SOC_I2S_SUPPORTED=y +# default: +CONFIG_SOC_I2S_I80_LCD_SUPPORTED=y +# default: +CONFIG_SOC_LCD_I80_SUPPORTED=y +# default: CONFIG_SOC_RMT_SUPPORTED=y +# default: CONFIG_SOC_SDM_SUPPORTED=y +# default: CONFIG_SOC_GPSPI_SUPPORTED=y +# default: CONFIG_SOC_LEDC_SUPPORTED=y +# default: CONFIG_SOC_I2C_SUPPORTED=y +# default: CONFIG_SOC_SUPPORT_COEXISTENCE=y +# default: CONFIG_SOC_AES_SUPPORTED=y +# default: CONFIG_SOC_MPI_SUPPORTED=y +# default: CONFIG_SOC_SHA_SUPPORTED=y +# default: CONFIG_SOC_FLASH_ENC_SUPPORTED=y +# default: CONFIG_SOC_SECURE_BOOT_SUPPORTED=y +# default: CONFIG_SOC_TOUCH_SENSOR_SUPPORTED=y +# default: CONFIG_SOC_BOD_SUPPORTED=y +# default: CONFIG_SOC_ULP_FSM_SUPPORTED=y +# default: CONFIG_SOC_CLK_TREE_SUPPORTED=y +# default: +CONFIG_SOC_REGI2C_SUPPORTED=y +# default: CONFIG_SOC_MPU_SUPPORTED=y +# default: CONFIG_SOC_WDT_SUPPORTED=y +# default: +CONFIG_SOC_RTC_WDT_SUPPORTED=y +# default: CONFIG_SOC_SPI_FLASH_SUPPORTED=y +# default: CONFIG_SOC_RNG_SUPPORTED=y +# default: CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y +# default: CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y +# default: CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y +# default: CONFIG_SOC_PM_SUPPORTED=y +# default: +CONFIG_SOC_SPI_EXTERNAL_NOR_FLASH_SUPPORTED=y +# default: CONFIG_SOC_DPORT_WORKAROUND_DIS_INTERRUPT_LVL=5 +# default: CONFIG_SOC_XTAL_SUPPORT_26M=y +# default: CONFIG_SOC_XTAL_SUPPORT_40M=y -CONFIG_SOC_XTAL_SUPPORT_AUTO_DETECT=y +# default: CONFIG_SOC_ADC_RTC_CTRL_SUPPORTED=y +# default: CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y +# default: CONFIG_SOC_ADC_DMA_SUPPORTED=y +# default: CONFIG_SOC_ADC_PERIPH_NUM=2 +# default: CONFIG_SOC_ADC_MAX_CHANNEL_NUM=10 +# default: CONFIG_SOC_ADC_ATTEN_NUM=4 +# default: CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=2 +# default: CONFIG_SOC_ADC_PATT_LEN_MAX=16 +# default: CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=9 +# default: CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 +# default: CONFIG_SOC_ADC_DIGI_RESULT_BYTES=2 +# default: CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 +# default: CONFIG_SOC_ADC_DIGI_MONITOR_NUM=0 -CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=2 -CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=20 +# default: +CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=2000000 +# default: +CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=20000 +# default: CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=9 +# default: CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 +# default: CONFIG_SOC_ADC_SHARED_POWER=y +# default: +CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y +# default: CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y +# default: CONFIG_SOC_IDCACHE_PER_CORE=y +# default: CONFIG_SOC_CPU_CORES_NUM=2 +# default: CONFIG_SOC_CPU_INTR_NUM=32 +# default: CONFIG_SOC_CPU_HAS_FPU=y +# default: CONFIG_SOC_HP_CPU_HAS_MULTIPLE_CORES=y +# default: CONFIG_SOC_CPU_BREAKPOINTS_NUM=2 +# default: CONFIG_SOC_CPU_WATCHPOINTS_NUM=2 -CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=64 +# default: +CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x40 +# default: CONFIG_SOC_DAC_CHAN_NUM=2 +# default: CONFIG_SOC_DAC_RESOLUTION=8 +# default: CONFIG_SOC_DAC_DMA_16BIT_ALIGN=y +# default: CONFIG_SOC_GPIO_PORT=1 +# default: CONFIG_SOC_GPIO_PIN_COUNT=40 +# default: +CONFIG_SOC_GPIO_SUPPORT_HP_PERIPH_PD_SLEEP_WAKEUP=y +# default: +CONFIG_SOC_GPIO_HP_PERIPH_PD_SLEEP_WAKEABLE_MASK=0 +# default: CONFIG_SOC_GPIO_VALID_GPIO_MASK=0xFFFFFFFFFF +# default: CONFIG_SOC_GPIO_IN_RANGE_MAX=39 +# default: CONFIG_SOC_GPIO_OUT_RANGE_MAX=33 +# default: CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0xEF0FEA +# default: CONFIG_SOC_GPIO_CLOCKOUT_BY_IO_MUX=y +# default: CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=3 +# default: CONFIG_SOC_I2C_NUM=2 +# default: CONFIG_SOC_HP_I2C_NUM=2 -CONFIG_SOC_I2C_FIFO_LEN=32 -CONFIG_SOC_I2C_CMD_REG_NUM=16 -CONFIG_SOC_I2C_SUPPORT_SLAVE=y +# default: CONFIG_SOC_I2C_SUPPORT_APB=y +# default: +CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y +# default: +CONFIG_SOC_I2C_SUPPORT_SLAVE=y +# default: CONFIG_SOC_I2C_STOP_INDEPENDENT=y -CONFIG_SOC_I2S_NUM=2 +# default: CONFIG_SOC_I2S_HW_VERSION_1=y +# default: CONFIG_SOC_I2S_SUPPORTS_APLL=y -CONFIG_SOC_I2S_SUPPORTS_PLL_F160M=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y -CONFIG_SOC_I2S_PDM_MAX_TX_LINES=1 +# default: +CONFIG_SOC_I2S_SUPPORTS_PCM2PDM=y +# default: CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y +# default: +CONFIG_SOC_I2S_SUPPORTS_PDM2PCM=y +# default: +CONFIG_SOC_I2S_PDM_MAX_TX_LINES=1 +# default: CONFIG_SOC_I2S_PDM_MAX_RX_LINES=1 -CONFIG_SOC_I2S_SUPPORTS_ADC_DAC=y -CONFIG_SOC_I2S_SUPPORTS_ADC=y -CONFIG_SOC_I2S_SUPPORTS_DAC=y -CONFIG_SOC_I2S_SUPPORTS_LCD_CAMERA=y -CONFIG_SOC_I2S_TRANS_SIZE_ALIGN_WORD=y -CONFIG_SOC_I2S_LCD_I80_VARIANT=y -CONFIG_SOC_LCD_I80_SUPPORTED=y -CONFIG_SOC_LCD_I80_BUSES=2 -CONFIG_SOC_LCD_I80_BUS_WIDTH=24 +# default: CONFIG_SOC_LEDC_HAS_TIMER_SPECIFIC_MUX=y +# default: CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y +# default: CONFIG_SOC_LEDC_SUPPORT_REF_TICK=y +# default: CONFIG_SOC_LEDC_SUPPORT_HS_MODE=y +# default: +CONFIG_SOC_LEDC_TIMER_NUM=4 +# default: CONFIG_SOC_LEDC_CHANNEL_NUM=8 +# default: CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=20 -CONFIG_SOC_MCPWM_GROUPS=2 -CONFIG_SOC_MCPWM_TIMERS_PER_GROUP=3 -CONFIG_SOC_MCPWM_OPERATORS_PER_GROUP=3 -CONFIG_SOC_MCPWM_COMPARATORS_PER_OPERATOR=2 -CONFIG_SOC_MCPWM_GENERATORS_PER_OPERATOR=2 -CONFIG_SOC_MCPWM_TRIGGERS_PER_OPERATOR=2 -CONFIG_SOC_MCPWM_GPIO_FAULTS_PER_GROUP=3 -CONFIG_SOC_MCPWM_CAPTURE_TIMERS_PER_GROUP=y -CONFIG_SOC_MCPWM_CAPTURE_CHANNELS_PER_TIMER=3 -CONFIG_SOC_MCPWM_GPIO_SYNCHROS_PER_GROUP=3 +# default: CONFIG_SOC_MMU_PERIPH_NUM=2 +# default: CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=3 +# default: CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 +# default: CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 -CONFIG_SOC_PCNT_GROUPS=1 -CONFIG_SOC_PCNT_UNITS_PER_GROUP=8 -CONFIG_SOC_PCNT_CHANNELS_PER_UNIT=2 -CONFIG_SOC_PCNT_THRES_POINT_PER_UNIT=2 -CONFIG_SOC_RMT_GROUPS=1 -CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=8 -CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=8 -CONFIG_SOC_RMT_CHANNELS_PER_GROUP=8 +# default: CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=64 -CONFIG_SOC_RMT_SUPPORT_REF_TICK=y -CONFIG_SOC_RMT_SUPPORT_APB=y -CONFIG_SOC_RMT_CHANNEL_CLK_INDEPENDENT=y +# default: CONFIG_SOC_RTCIO_PIN_COUNT=18 +# default: CONFIG_SOC_RTCIO_INPUT_OUTPUT_SUPPORTED=y +# default: CONFIG_SOC_RTCIO_HOLD_SUPPORTED=y +# default: CONFIG_SOC_RTCIO_WAKE_SUPPORTED=y -CONFIG_SOC_SDM_GROUPS=1 -CONFIG_SOC_SDM_CHANNELS_PER_GROUP=8 -CONFIG_SOC_SDM_CLK_SUPPORT_APB=y -CONFIG_SOC_SPI_HD_BOTH_INOUT_SUPPORTED=y -CONFIG_SOC_SPI_AS_CS_SUPPORTED=y +# default: +CONFIG_SOC_RTC_CNTL_NEEDS_ATOMIC_ACCESS=y +# default: CONFIG_SOC_SPI_PERIPH_NUM=3 -CONFIG_SOC_SPI_DMA_CHAN_NUM=2 -CONFIG_SOC_SPI_MAX_CS_NUM=3 -CONFIG_SOC_SPI_SUPPORT_CLK_APB=y +# default: +CONFIG_SOC_SPI_HD_BOTH_INOUT_SUPPORTED=y +# default: CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 -CONFIG_SOC_SPI_MAX_PRE_DIVIDER=8192 -CONFIG_SOC_MEMSPI_SRC_FREQ_80M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_40M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_26M_SUPPORTED=y -CONFIG_SOC_MEMSPI_SRC_FREQ_20M_SUPPORTED=y -CONFIG_SOC_TIMER_GROUPS=2 -CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2 -CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=64 -CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4 -CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y +# default: +CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 +# default: +CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 +# default: +CONFIG_SOC_RTC_TIMER_V1=y +# default: CONFIG_SOC_TOUCH_SENSOR_VERSION=1 -CONFIG_SOC_TOUCH_SENSOR_NUM=10 +# default: +CONFIG_SOC_TOUCH_MIN_CHAN_ID=0 +# default: +CONFIG_SOC_TOUCH_MAX_CHAN_ID=9 +# default: +CONFIG_SOC_TOUCH_SUPPORT_SLEEP_WAKEUP=y +# default: CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM=1 +# default: CONFIG_SOC_TWAI_CONTROLLER_NUM=1 -CONFIG_SOC_TWAI_BRP_MIN=2 -CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y -CONFIG_SOC_TWAI_SUPPORT_MULTI_ADDRESS_LAYOUT=y +# default: +CONFIG_SOC_TWAI_MASK_FILTER_NUM=1 +# default: CONFIG_SOC_UART_NUM=3 +# default: CONFIG_SOC_UART_HP_NUM=3 +# default: CONFIG_SOC_UART_SUPPORT_APB_CLK=y +# default: CONFIG_SOC_UART_SUPPORT_REF_TICK=y +# default: CONFIG_SOC_UART_FIFO_LEN=128 +# default: CONFIG_SOC_UART_BITRATE_MAX=5000000 +# default: +CONFIG_SOC_UART_WAKEUP_SUPPORT_ACTIVE_THRESH_MODE=y +# default: CONFIG_SOC_SPIRAM_SUPPORTED=y +# default: CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y +# default: +CONFIG_SOC_MEMSPI_ENCRYPTION_ALIGNMENT=16 +# default: CONFIG_SOC_SHA_SUPPORT_PARALLEL_ENG=y +# default: CONFIG_SOC_SHA_ENDIANNESS_BE=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA1=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA256=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA384=y +# default: CONFIG_SOC_SHA_SUPPORT_SHA512=y +# default: CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 -CONFIG_SOC_MPI_OPERATIONS_NUM=y +# default: +CONFIG_SOC_MPI_OPERATIONS_NUM=1 +# default: CONFIG_SOC_RSA_MAX_BIT_LEN=4096 +# default: CONFIG_SOC_AES_SUPPORT_AES_128=y +# default: CONFIG_SOC_AES_SUPPORT_AES_192=y +# default: CONFIG_SOC_AES_SUPPORT_AES_256=y +# default: CONFIG_SOC_SECURE_BOOT_V1=y -CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=y +# default: +CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=1 +# default: CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=32 +# default: CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 +# default: CONFIG_SOC_PM_SUPPORT_EXT0_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_EXT1_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_EXT_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP=y +# default: CONFIG_SOC_PM_SUPPORT_RTC_PERIPH_PD=y +# default: CONFIG_SOC_PM_SUPPORT_RTC_FAST_MEM_PD=y +# default: CONFIG_SOC_PM_SUPPORT_RTC_SLOW_MEM_PD=y +# default: CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y +# default: CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y +# default: CONFIG_SOC_PM_SUPPORT_MODEM_PD=y +# default: CONFIG_SOC_CONFIGURABLE_VDDSDIO_SUPPORTED=y +# default: +CONFIG_SOC_PM_MODEM_PD_BY_SW=y +# default: +CONFIG_SOC_PM_RTC_NOT_SUPPORT_UART2_WAKEUP=y +# default: CONFIG_SOC_CLK_APLL_SUPPORTED=y +# default: CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y +# default: CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y +# default: CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y +# default: CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y +# default: +CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL_D4=y +# default: CONFIG_SOC_SDMMC_USE_IOMUX=y +# default: CONFIG_SOC_SDMMC_NUM_SLOTS=2 +# default: +CONFIG_SOC_SDMMC_DATA_WIDTH_MAX=8 +# default: CONFIG_SOC_WIFI_WAPI_SUPPORT=y +# default: CONFIG_SOC_WIFI_CSI_SUPPORT=y +# default: CONFIG_SOC_WIFI_MESH_SUPPORT=y +# default: CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +# default: CONFIG_SOC_WIFI_NAN_SUPPORT=y +# default: CONFIG_SOC_BLE_SUPPORTED=y +# default: CONFIG_SOC_BLE_MESH_SUPPORTED=y +# default: CONFIG_SOC_BT_CLASSIC_SUPPORTED=y +# default: CONFIG_SOC_BLUFI_SUPPORTED=y +# default: CONFIG_SOC_BT_H2C_ENC_KEY_CTRL_ENH_VSC_SUPPORTED=y +# default: +CONFIG_SOC_BLE_MULTI_CONN_OPTIMIZATION=y +# default: CONFIG_SOC_ULP_HAS_ADC=y +# default: CONFIG_SOC_PHY_COMBO_MODULE=y +# default: CONFIG_SOC_EMAC_RMII_CLK_OUT_INTERNAL_LOOPBACK=y +# default: +CONFIG_SOC_EMAC_REF_CLK_FROM_APLL=y +# default: CONFIG_IDF_CMAKE=y +# default: CONFIG_IDF_TOOLCHAIN="gcc" +# default: +CONFIG_IDF_TOOLCHAIN_GCC=y +# default: CONFIG_IDF_TARGET_ARCH_XTENSA=y +# default: CONFIG_IDF_TARGET_ARCH="xtensa" +# default: CONFIG_IDF_TARGET="esp32" +# default: CONFIG_IDF_INIT_VERSION="5.3.1" +# default: CONFIG_IDF_TARGET_ESP32=y +# default: CONFIG_IDF_FIRMWARE_CHIP_ID=0x0000 # @@ -248,15 +430,31 @@ CONFIG_IDF_FIRMWARE_CHIP_ID=0x0000 # CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y # CONFIG_APP_BUILD_TYPE_RAM is not set +# default: CONFIG_APP_BUILD_GENERATE_BINARIES=y +# default: CONFIG_APP_BUILD_BOOTLOADER=y +# default: CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y + +# +# Minimize binary changes between builds +# +# default: +# CONFIG_APP_BUILD_MINIMIZE_BINARY_CHANGES is not set +# end of Minimize binary changes between builds + # CONFIG_APP_REPRODUCIBLE_BUILD is not set # CONFIG_APP_NO_BLOBS is not set # CONFIG_APP_COMPATIBLE_PRE_V2_1_BOOTLOADERS is not set # CONFIG_APP_COMPATIBLE_PRE_V3_1_BOOTLOADERS is not set # end of Build type +# +# App Update config +# +# end of App Update config + # # Bootloader config # @@ -268,19 +466,61 @@ CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y CONFIG_BOOTLOADER_PROJECT_VER=1 # end of Bootloader manager +# +# Application Rollback +# +# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set +# end of Application Rollback + +# +# Recovery Bootloader and Rollback +# +# end of Recovery Bootloader and Rollback + +# default: CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x1000 CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set -# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set + +# +# Log +# +# default: +CONFIG_BOOTLOADER_LOG_VERSION_1=y +# default: +CONFIG_BOOTLOADER_LOG_VERSION=1 # CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set # CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set # CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y # CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set # CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set +# default: CONFIG_BOOTLOADER_LOG_LEVEL=3 +# +# Format +# +# default: +# CONFIG_BOOTLOADER_LOG_COLORS is not set +# default: +CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y +# end of Format + +# +# Settings +# +# default: +CONFIG_BOOTLOADER_LOG_MODE_TEXT_EN=y +# default: +CONFIG_BOOTLOADER_LOG_MODE_TEXT=y +# end of Settings +# end of Log + +# default: +CONFIG_BOOTLOADER_CPU_CLK_FREQ_MHZ=80 + # # Serial Flash Configurations # @@ -296,10 +536,10 @@ CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y CONFIG_BOOTLOADER_WDT_ENABLE=y # CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set CONFIG_BOOTLOADER_WDT_TIME_MS=9000 -# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set # CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set +# default: CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set # end of Bootloader config @@ -307,8 +547,13 @@ CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 # # Security features # +# default: CONFIG_SECURE_BOOT_V1_SUPPORTED=y # CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set +# default: +CONFIG_SECURE_BOOT_IMAGE_DIGEST_LEN=32 +# default: +CONFIG_SECURE_BOOT_ROM_FAST_WAKE_RESERVE_SIZE=0 # CONFIG_SECURE_BOOT is not set # CONFIG_SECURE_FLASH_ENC_ENABLED is not set # end of Security features @@ -323,19 +568,38 @@ CONFIG_APP_COMPILE_TIME_DATE=y CONFIG_APP_RETRIEVE_LEN_ELF_SHA=16 # end of Application manager +# default: CONFIG_ESP_ROM_HAS_CRC_LE=y +# default: CONFIG_ESP_ROM_HAS_CRC_BE=y +# default: CONFIG_ESP_ROM_HAS_MZ_CRC32=y +# default: CONFIG_ESP_ROM_HAS_JPEG_DECODE=y +# default: CONFIG_ESP_ROM_HAS_UART_BUF_SWITCH=y +# default: CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y +# default: CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y +# default: CONFIG_ESP_ROM_HAS_SW_FLOAT=y +# default: CONFIG_ESP_ROM_USB_OTG_NUM=-1 +# default: CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=-1 +# default: CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y +# default: +CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC=y +# default: +CONFIG_ESP_ROM_HAS_REGI2C_IMPL=y +# default: +CONFIG_ESP_ROM_BOOTLOADER_OFFSET_FLASH=0x1000 # # Serial flasher config @@ -346,11 +610,15 @@ CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y CONFIG_ESPTOOLPY_FLASHMODE_DIO=y # CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y +# default: CONFIG_ESPTOOLPY_FLASHMODE="dio" +# default: +CONFIG_ESPTOOLPY_FLASHMODE_VAL=3 # CONFIG_ESPTOOLPY_FLASHFREQ_80M is not set CONFIG_ESPTOOLPY_FLASHFREQ_40M=y # CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set # CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set +# default: CONFIG_ESPTOOLPY_FLASHFREQ="40m" # CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y @@ -360,14 +628,18 @@ CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +# default: CONFIG_ESPTOOLPY_FLASHSIZE="2MB" # CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set -CONFIG_ESPTOOLPY_BEFORE="default_reset" +# default: +CONFIG_ESPTOOLPY_BEFORE="default-reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set -CONFIG_ESPTOOLPY_AFTER="hard_reset" +# default: +CONFIG_ESPTOOLPY_AFTER="hard-reset" +# default: CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 # end of Serial flasher config @@ -377,8 +649,10 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 CONFIG_PARTITION_TABLE_SINGLE_APP=y # CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set # CONFIG_PARTITION_TABLE_TWO_OTA is not set +# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set # CONFIG_PARTITION_TABLE_CUSTOM is not set CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" +# default: CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv" CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_MD5=y @@ -404,14 +678,17 @@ CONFIG_EXAMPLE_FAST_SCAN_WEAKEST_AUTHMODE_OPEN=y # # Compiler options # -CONFIG_COMPILER_OPTIMIZATION_DEBUG=y +# CONFIG_COMPILER_OPTIMIZATION_DEBUG is not set # CONFIG_COMPILER_OPTIMIZATION_SIZE is not set -# CONFIG_COMPILER_OPTIMIZATION_PERF is not set +CONFIG_COMPILER_OPTIMIZATION_PERF=y # CONFIG_COMPILER_OPTIMIZATION_NONE is not set CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set # CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set +# default: +# CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE is not set CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y +# default: CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 # CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set CONFIG_COMPILER_HIDE_PATHS_MACROS=y @@ -421,118 +698,113 @@ CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y # CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set # CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set # CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set +# default: +# CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set # CONFIG_COMPILER_WARN_WRITE_STRINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS is not set # CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set # CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set +# default: +# CONFIG_COMPILER_DISABLE_GCC15_WARNINGS is not set # CONFIG_COMPILER_DUMP_RTL_FILES is not set CONFIG_COMPILER_RT_LIB_GCCLIB=y +# default: CONFIG_COMPILER_RT_LIB_NAME="gcc" +# CONFIG_COMPILER_ORPHAN_SECTIONS_ERROR is not set # CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y +# default: +# CONFIG_COMPILER_STATIC_ANALYZER is not set +# default: +CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_NO_CHANGE=y +# default: +# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD_CONSTEXPR is not set +# default: +# CONFIG_COMPILER_CXX_GLIBCXX_CONSTEXPR_COLD is not set # end of Compiler options # # Component config # -# -# Application Level Tracing -# -# CONFIG_APPTRACE_DEST_JTAG is not set -CONFIG_APPTRACE_DEST_NONE=y -# CONFIG_APPTRACE_DEST_UART1 is not set -# CONFIG_APPTRACE_DEST_UART2 is not set -CONFIG_APPTRACE_DEST_UART_NONE=y -CONFIG_APPTRACE_UART_TASK_PRIO=1 -CONFIG_APPTRACE_LOCK_ENABLE=y -# end of Application Level Tracing - # # Bluetooth # # CONFIG_BT_ENABLED is not set -CONFIG_BT_ALARM_MAX_NUM=50 -# end of Bluetooth - -# -# Console Library -# -# CONFIG_CONSOLE_SORTED_HELP is not set -# end of Console Library # -# Driver Configurations +# Common Options # # -# TWAI Configuration +# BT Logs # -# CONFIG_TWAI_ISR_IN_IRAM is not set -# CONFIG_TWAI_ERRATA_FIX_BUS_OFF_REC is not set -# CONFIG_TWAI_ERRATA_FIX_TX_INTR_LOST is not set -# CONFIG_TWAI_ERRATA_FIX_RX_FRAME_INVALID is not set -# CONFIG_TWAI_ERRATA_FIX_RX_FIFO_CORRUPT is not set -CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y -# end of TWAI Configuration # -# Legacy ADC Driver Configuration +# Log Sources # -CONFIG_ADC_DISABLE_DAC=y -# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set +# end of Log Sources -# -# Legacy ADC Calibration Configuration -# -CONFIG_ADC_CAL_EFUSE_TP_ENABLE=y -CONFIG_ADC_CAL_EFUSE_VREF_ENABLE=y -CONFIG_ADC_CAL_LUT_ENABLE=y -# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy ADC Calibration Configuration -# end of Legacy ADC Driver Configuration +# default: +# CONFIG_BT_LOG_CRITICAL_ONLY is not set +# default: +# CONFIG_BLE_LOG_ENABLED is not set # -# Legacy DAC Driver Configurations +# Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) # -# CONFIG_DAC_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy DAC Driver Configurations +# default: +# CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set +# end of Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) +# end of BT Logs -# -# Legacy MCPWM Driver Configurations -# -# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy MCPWM Driver Configurations +# default: +# CONFIG_BT_LE_USED_MEM_STATISTICS_ENABLED is not set +# end of Common Options +# end of Bluetooth # -# Legacy Timer Group Driver Configurations +# Console Library # -# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy Timer Group Driver Configurations +# CONFIG_CONSOLE_SORTED_HELP is not set +# end of Console Library # -# Legacy RMT Driver Configurations +# Legacy Driver Configurations # -# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy RMT Driver Configurations # -# Legacy I2S Driver Configurations +# Legacy TWAI Driver Configurations # -# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy I2S Driver Configurations +# default: +# CONFIG_TWAI_ISR_IN_IRAM_LEGACY is not set +# default: +# CONFIG_TWAI_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_TWAI_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy TWAI Driver Configurations # -# Legacy PCNT Driver Configurations +# Legacy I2C Driver Configurations # -# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy PCNT Driver Configurations +# default: +# CONFIG_I2C_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy I2C Driver Configurations # -# Legacy SDM Driver Configurations +# Legacy Touch Sensor Driver Configurations # -# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set -# end of Legacy SDM Driver Configurations -# end of Driver Configurations +# default: +# CONFIG_TOUCH_SUPPRESS_DEPRECATE_WARN is not set +# default: +# CONFIG_TOUCH_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy Touch Sensor Driver Configurations +# end of Legacy Driver Configurations # # eFuse Bit Manager @@ -542,6 +814,7 @@ CONFIG_ADC_CAL_LUT_ENABLE=y # CONFIG_EFUSE_CODE_SCHEME_COMPAT_NONE is not set CONFIG_EFUSE_CODE_SCHEME_COMPAT_3_4=y # CONFIG_EFUSE_CODE_SCHEME_COMPAT_REPEAT is not set +# default: CONFIG_EFUSE_MAX_BLK_LEN=192 # end of eFuse Bit Manager @@ -549,13 +822,15 @@ CONFIG_EFUSE_MAX_BLK_LEN=192 # ESP-TLS # CONFIG_ESP_TLS_USING_MBEDTLS=y -# CONFIG_ESP_TLS_USE_SECURE_ELEMENT is not set +# CONFIG_ESP_TLS_CUSTOM_STACK is not set # CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set # CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set # CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set # CONFIG_ESP_TLS_PSK_VERIFICATION is not set # CONFIG_ESP_TLS_INSECURE is not set +# default: +CONFIG_ESP_TLS_DYN_BUF_STRATEGY_SUPPORTED=y # end of ESP-TLS # @@ -579,7 +854,10 @@ CONFIG_ADC_DISABLE_DAC_OUTPUT=y # # Wireless Coexistence # +# default: CONFIG_ESP_COEX_ENABLED=y +# default: +# CONFIG_ESP_COEX_GPIO_DEBUG is not set # end of Wireless Coexistence # @@ -600,7 +878,6 @@ CONFIG_DAC_DMA_AUTO_16BIT_ALIGN=y # # ESP-Driver:GPIO Configurations # -# CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL is not set # CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set # end of ESP-Driver:GPIO Configurations @@ -609,7 +886,9 @@ CONFIG_DAC_DMA_AUTO_16BIT_ALIGN=y # CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set -# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set +# CONFIG_GPTIMER_ISR_CACHE_SAFE is not set +# default: +CONFIG_GPTIMER_OBJ_CACHE_SAFE=y # CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:GPTimer Configurations @@ -618,15 +897,30 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # CONFIG_I2C_ISR_IRAM_SAFE is not set # CONFIG_I2C_ENABLE_DEBUG_LOG is not set +# default: +CONFIG_I2C_MASTER_ISR_HANDLER_IN_IRAM=y # end of ESP-Driver:I2C Configurations # # ESP-Driver:I2S Configurations # # CONFIG_I2S_ISR_IRAM_SAFE is not set +# default: +# CONFIG_I2S_CTRL_FUNC_IN_IRAM is not set # CONFIG_I2S_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:I2S Configurations +# +# ESP-Driver:I3C Master Configurations +# +# default: +# CONFIG_I3C_MASTER_ISR_CACHE_SAFE is not set +# default: +# CONFIG_I3C_MASTER_ENABLE_DEBUG_LOG is not set +# default: +# CONFIG_I3C_MASTER_ISR_HANDLER_IN_IRAM is not set +# end of ESP-Driver:I3C Master Configurations + # # ESP-Driver:LEDC Configurations # @@ -636,8 +930,12 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # ESP-Driver:MCPWM Configurations # -# CONFIG_MCPWM_ISR_IRAM_SAFE is not set +# default: +CONFIG_MCPWM_ISR_HANDLER_IN_IRAM=y +# CONFIG_MCPWM_ISR_CACHE_SAFE is not set # CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set +# default: +CONFIG_MCPWM_OBJ_CACHE_SAFE=y # CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:MCPWM Configurations @@ -652,9 +950,21 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # # ESP-Driver:RMT Configurations # -# CONFIG_RMT_ISR_IRAM_SAFE is not set +# default: +CONFIG_RMT_ENCODER_FUNC_IN_IRAM=y +# default: +CONFIG_RMT_TX_ISR_HANDLER_IN_IRAM=y +# default: +CONFIG_RMT_RX_ISR_HANDLER_IN_IRAM=y # CONFIG_RMT_RECV_FUNC_IN_IRAM is not set +# default: +# CONFIG_RMT_TX_ISR_CACHE_SAFE is not set +# default: +# CONFIG_RMT_RX_ISR_CACHE_SAFE is not set +# default: +CONFIG_RMT_OBJ_CACHE_SAFE=y # CONFIG_RMT_ENABLE_DEBUG_LOG is not set +# CONFIG_RMT_ISR_IRAM_SAFE is not set # end of ESP-Driver:RMT Configurations # @@ -664,9 +974,17 @@ CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y # CONFIG_SDM_ENABLE_DEBUG_LOG is not set # end of ESP-Driver:Sigma Delta Modulator Configurations +# +# ESP-Driver:SD Host SDMMC Controller Configurations +# +# default: +# CONFIG_SD_HOST_SDMMC_ISR_CACHE_SAFE is not set +# end of ESP-Driver:SD Host SDMMC Controller Configurations + # # ESP-Driver:SPI Configurations # +# default: # CONFIG_SPI_MASTER_IN_IRAM is not set CONFIG_SPI_MASTER_ISR_IN_IRAM=y # CONFIG_SPI_SLAVE_IN_IRAM is not set @@ -679,31 +997,58 @@ CONFIG_SPI_SLAVE_ISR_IN_IRAM=y # CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set # CONFIG_TOUCH_ISR_IRAM_SAFE is not set # CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set +# default: +# CONFIG_TOUCH_SKIP_FSM_CHECK is not set # end of ESP-Driver:Touch Sensor Configurations +# +# ESP-Driver:TWAI Configurations +# +# CONFIG_TWAI_ISR_IN_IRAM is not set +# default: +# CONFIG_TWAI_IO_FUNC_IN_IRAM is not set +# default: +# CONFIG_TWAI_ISR_CACHE_SAFE is not set +# default: +# CONFIG_TWAI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:TWAI Configurations + # # ESP-Driver:UART Configurations # # CONFIG_UART_ISR_IN_IRAM is not set # end of ESP-Driver:UART Configurations +# +# ESP-Driver:UHCI Configurations +# +# default: +# CONFIG_UHCI_ISR_HANDLER_IN_IRAM is not set +# default: +# CONFIG_UHCI_RECV_FUNC_IN_IRAM is not set +# default: +# CONFIG_UHCI_ISR_CACHE_SAFE is not set +# default: +# CONFIG_UHCI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:UHCI Configurations + # # Ethernet # +# default: CONFIG_ETH_ENABLED=y CONFIG_ETH_USE_ESP32_EMAC=y -CONFIG_ETH_PHY_INTERFACE_RMII=y -CONFIG_ETH_RMII_CLK_INPUT=y -# CONFIG_ETH_RMII_CLK_OUTPUT is not set -CONFIG_ETH_RMII_CLK_IN_GPIO=0 CONFIG_ETH_DMA_BUFFER_SIZE=512 CONFIG_ETH_DMA_RX_BUFFER_NUM=10 CONFIG_ETH_DMA_TX_BUFFER_NUM=10 # CONFIG_ETH_IRAM_OPTIMIZATION is not set + +# +# Ethernet Clock +# +# end of Ethernet Clock + CONFIG_ETH_USE_SPI_ETHERNET=y -# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set -# CONFIG_ETH_SPI_ETHERNET_W5500 is not set -# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set # CONFIG_ETH_USE_OPENETH is not set # CONFIG_ETH_TRANSMIT_MUTEX is not set # end of Ethernet @@ -713,18 +1058,30 @@ CONFIG_ETH_USE_SPI_ETHERNET=y # # CONFIG_ESP_EVENT_LOOP_PROFILING is not set CONFIG_ESP_EVENT_POST_FROM_ISR=y +# default: +CONFIG_ESP_EVENT_POST_FROM_ISR_SIZE=4 CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y # end of Event Loop Library # # GDB Stub # +# default: CONFIG_ESP_GDBSTUB_ENABLED=y # CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y CONFIG_ESP_GDBSTUB_MAX_TASKS=32 # end of GDB Stub +# +# ESP HID +# +# default: +CONFIG_ESPHID_TASK_SIZE_BT=2048 +# default: +CONFIG_ESPHID_TASK_SIZE_BLE=4096 +# end of ESP HID + # # ESP HTTP client # @@ -732,6 +1089,14 @@ CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH=y # CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set +# default: +# CONFIG_ESP_HTTP_CLIENT_ENABLE_GET_CONTENT_RANGE is not set +# default: +CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 +# default: +# CONFIG_ESP_HTTP_CLIENT_SAVE_RESPONSE_HEADERS is not set +# default: +CONFIG_ESP_HTTP_CLIENT_STRICT_HEADER_BUFFER=y # end of ESP HTTP client # @@ -744,6 +1109,10 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 # CONFIG_HTTPD_LOG_PURGE_DATA is not set # CONFIG_HTTPD_WS_SUPPORT is not set # CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set +# default: +CONFIG_HTTPD_ENABLE_EVENTS=y +# default: +CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 # end of HTTP Server # @@ -751,17 +1120,26 @@ CONFIG_HTTPD_PURGE_BUF_LEN=32 # # CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set # CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set +# default: +CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 +# default: +# CONFIG_ESP_HTTPS_OTA_ENABLE_PARTIAL_DOWNLOAD is not set +# default: +CONFIG_ESP_HTTPS_OTA_VERIFY_SPI_MODE=y # end of ESP HTTPS OTA # # ESP HTTPS server # -# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set +# default: +# CONFIG_ESP_HTTPS_SERVER_CERT_SELECT_HOOK is not set # end of ESP HTTPS server # # Hardware Settings # +# default: +CONFIG_ESP_HW_SUPPORT_FUNC_IN_IRAM=y # # Chip revision @@ -772,28 +1150,48 @@ CONFIG_ESP32_REV_MIN_0=y # CONFIG_ESP32_REV_MIN_2 is not set # CONFIG_ESP32_REV_MIN_3 is not set # CONFIG_ESP32_REV_MIN_3_1 is not set +# default: CONFIG_ESP32_REV_MIN=0 +# default: CONFIG_ESP32_REV_MIN_FULL=0 +# default: CONFIG_ESP_REV_MIN_FULL=0 # # Maximum Supported ESP32 Revision (Rev v3.99) # +# default: CONFIG_ESP32_REV_MAX_FULL=399 +# default: CONFIG_ESP_REV_MAX_FULL=399 +# default: +CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 +# default: +CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=99 + +# +# Maximum Supported ESP32 eFuse Block Revision (eFuse Block Rev v0.99) +# # end of Chip revision # # MAC Config # +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y +# default: CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y +# default: CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y +# default: CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_TWO is not set CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR=y +# default: CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES=4 # CONFIG_ESP_MAC_IGNORE_MAC_CRC_ERROR is not set # CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set @@ -803,6 +1201,11 @@ CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES=4 # Sleep Config # CONFIG_ESP_SLEEP_POWER_DOWN_FLASH=y +# default: +CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y +# default: +# CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set +# default: CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND=y CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=2000 @@ -819,52 +1222,118 @@ CONFIG_RTC_CLK_SRC_INT_RC=y # CONFIG_RTC_CLK_SRC_EXT_OSC is not set # CONFIG_RTC_CLK_SRC_INT_8MD256 is not set CONFIG_RTC_CLK_CAL_CYCLES=1024 +# default: +CONFIG_RTC_CLK_FUNC_IN_IRAM=y +# default: +CONFIG_RTC_TIME_FUNC_IN_IRAM=y # end of RTC Clock Config # # Peripheral Control # -CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM=y +# default: +CONFIG_ESP_REGI2C_CTRL_FUNC_IN_IRAM=y # end of Peripheral Control # # Main XTAL Config # # CONFIG_XTAL_FREQ_26 is not set +# CONFIG_XTAL_FREQ_32 is not set CONFIG_XTAL_FREQ_40=y # CONFIG_XTAL_FREQ_AUTO is not set +# default: CONFIG_XTAL_FREQ=40 # end of Main XTAL Config +# +# Power Supplier +# + +# +# Brownout Detector +# +CONFIG_ESP_BROWNOUT_DET=y +CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0=y +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7 is not set +# default: +CONFIG_ESP_BROWNOUT_DET_LVL=0 +# default: +CONFIG_ESP_BROWNOUT_USE_INTR=y +# end of Brownout Detector +# end of Power Supplier + +# default: CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y +# default: +CONFIG_ESP_INTR_IN_IRAM=y # end of Hardware Settings # -# LCD and Touch Panel +# ESP-Driver:LCD Controller Configurations # +# CONFIG_LCD_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:LCD Controller Configurations # -# LCD Touch Drivers are maintained in the IDF Component Registry +# LibC # +# default: +# CONFIG_LIBC_NEWLIB is not set +# default: +CONFIG_LIBC_PICOLIBC=y +# default: +CONFIG_LIBC_PICOLIBC_NEWLIB_COMPATIBILITY=y +# default: +CONFIG_LIBC_MISC_IN_IRAM=y +# default: +CONFIG_LIBC_LOCKS_PLACE_IN_IRAM=y +CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_LIBC_STDOUT_LINE_ENDING_LF is not set +# CONFIG_LIBC_STDOUT_LINE_ENDING_CR is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_LF is not set +CONFIG_LIBC_STDIN_LINE_ENDING_CR=y +CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT=y +# CONFIG_LIBC_TIME_SYSCALL_USE_RTC is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_HRT is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_NONE is not set +# default: +CONFIG_LIBC_ASSERT_BUFFER_SIZE=200 +# end of LibC # -# LCD Peripheral Configuration +# ESP-MM: Memory Management Configurations # -CONFIG_LCD_PANEL_IO_FORMAT_BUF_SIZE=32 -# CONFIG_LCD_ENABLE_DEBUG_LOG is not set -# end of LCD Peripheral Configuration -# end of LCD and Touch Panel +# end of ESP-MM: Memory Management Configurations # # ESP NETIF Adapter # +# default: +CONFIG_ESP_NETIF_LOST_IP_TIMER_ENABLE=y CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 +# default: +# CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set CONFIG_ESP_NETIF_TCPIP_LWIP=y # CONFIG_ESP_NETIF_LOOPBACK is not set +# default: CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y -# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set +# default: +CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y +# default: +CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS=y # CONFIG_ESP_NETIF_L2_TAP is not set # CONFIG_ESP_NETIF_BRIDGE_EN is not set +# default: +# CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set # end of ESP NETIF Adapter # @@ -875,23 +1344,42 @@ CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y # # PHY # +# default: CONFIG_ESP_PHY_ENABLED=y CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20 +# default: CONFIG_ESP_PHY_MAX_TX_POWER=20 CONFIG_ESP_PHY_REDUCE_TX_POWER=y +# default: +# CONFIG_ESP_PHY_ENABLE_CERT_TEST is not set CONFIG_ESP_PHY_RF_CAL_PARTIAL=y # CONFIG_ESP_PHY_RF_CAL_NONE is not set # CONFIG_ESP_PHY_RF_CAL_FULL is not set +# default: CONFIG_ESP_PHY_CALIBRATION_MODE=0 +# default: +CONFIG_ESP_PHY_PLL_TRACK_PERIOD_MS=1000 # CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set +# default: +# CONFIG_ESP_PHY_RECORD_USED_TIME is not set +# default: +CONFIG_ESP_PHY_IRAM_OPT=y +# default: +# CONFIG_ESP_PHY_DEBUG is not set +# default: +CONFIG_ESP_PHY_ENABLE_VERSION_PRINT=y # end of PHY # # Power Management # +# default: +# CONFIG_PM_SLEEP_FUNC_IN_IRAM is not set # CONFIG_PM_ENABLE is not set +# default: +CONFIG_PM_SLP_IRAM_OPT=y # end of Power Management # @@ -903,15 +1391,46 @@ CONFIG_ESP_PHY_CALIBRATION_MODE=0 # # ESP Ringbuf # -# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set +# default: +CONFIG_RINGBUF_IN_IRAM=y # end of ESP Ringbuf +# +# ESP-ROM +# +# default: +CONFIG_ESP_ROM_PRINT_IN_IRAM=y +# end of ESP-ROM + +# +# ESP Security Specific +# +# end of ESP Security Specific + +# +# ESP-STDIO +# +CONFIG_ESP_CONSOLE_UART_DEFAULT=y +# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set +# CONFIG_ESP_CONSOLE_NONE is not set +# default: +CONFIG_ESP_CONSOLE_UART=y +# default: +CONFIG_ESP_CONSOLE_UART_NUM=0 +# default: +CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 +CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 +# default: +CONFIG_ESP_STDIO_MAX_VFS_ENTRIES=2 +# end of ESP-STDIO + # # ESP System Settings # # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y # CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240 is not set +# default: CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160 # @@ -930,35 +1449,26 @@ CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160 # Trace memory # # CONFIG_ESP32_TRAX is not set +# default: CONFIG_ESP32_TRACEMEM_RESERVE_DRAM=0x0 # end of Trace memory +# default: +CONFIG_ESP_SYSTEM_IN_IRAM=y # CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y # CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set # CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 - -# -# Memory protection -# -# end of Memory protection - CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584 CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y # CONFIG_ESP_MAIN_TASK_AFFINITY_CPU1 is not set # CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set +# default: CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 -CONFIG_ESP_CONSOLE_UART_DEFAULT=y -# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set -# CONFIG_ESP_CONSOLE_NONE is not set -CONFIG_ESP_CONSOLE_UART=y -CONFIG_ESP_CONSOLE_UART_NUM=0 -CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0 -CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200 CONFIG_ESP_INT_WDT=y CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 CONFIG_ESP_INT_WDT_CHECK_CPU1=y @@ -973,62 +1483,74 @@ CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU1=y CONFIG_ESP_DEBUG_OCDAWARE=y # CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_5 is not set CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y - -# -# Brownout Detector -# -CONFIG_ESP_BROWNOUT_DET=y -CONFIG_ESP_BROWNOUT_DET_LVL_SEL_0=y -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_1 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7 is not set -CONFIG_ESP_BROWNOUT_DET_LVL=0 -# end of Brownout Detector - # CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE is not set -CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y # end of ESP System Settings # # IPC (Inter-Processor Call) # +# default: +CONFIG_ESP_IPC_ENABLE=y CONFIG_ESP_IPC_TASK_STACK_SIZE=1024 CONFIG_ESP_IPC_USES_CALLERS_PRIORITY=y +# default: CONFIG_ESP_IPC_ISR_ENABLE=y # end of IPC (Inter-Processor Call) # # ESP Timer (High Resolution Timer) # +# default: +CONFIG_ESP_TIMER_IN_IRAM=y # CONFIG_ESP_TIMER_PROFILING is not set +# default: CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y +# default: CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 # CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set +# default: CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y # CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set +# default: CONFIG_ESP_TIMER_IMPL_TG0_LAC=y # end of ESP Timer (High Resolution Timer) +# +# ESP Trace Configuration +# +# default: +# CONFIG_ESP_TRACE_LIB_EXTERNAL is not set +# default: +CONFIG_ESP_TRACE_LIB_NONE=y +# default: +CONFIG_ESP_TRACE_LIB_NAME="none" +# default: +# CONFIG_ESP_TRACE_TRANSPORT_APPTRACE is not set +# default: +CONFIG_ESP_TRACE_TRANSPORT_NONE=y +# default: +CONFIG_ESP_TRACE_TRANSPORT_NAME="none" +# end of ESP Trace Configuration + # # Wi-Fi # +# default: CONFIG_ESP_WIFI_ENABLED=y CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32 # CONFIG_ESP_WIFI_STATIC_TX_BUFFER is not set CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y +# default: CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1 CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y # CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set +# default: CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0 CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5 # CONFIG_ESP_WIFI_CSI_ENABLED is not set @@ -1042,14 +1564,24 @@ CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0=y CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752 CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32 CONFIG_ESP_WIFI_IRAM_OPT=y -# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set +CONFIG_ESP_WIFI_EXTRA_IRAM_OPT=y CONFIG_ESP_WIFI_RX_IRAM_OPT=y CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y +# default: +CONFIG_ESP_WIFI_ENABLE_SAE_H2E=y CONFIG_ESP_WIFI_ENABLE_SAE_PK=y CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y +# default: +CONFIG_ESP_WIFI_WPA3_COMPATIBLE_SUPPORT=y +# default: +# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_SOFTAP is not set +# default: +# CONFIG_ESP_WIFI_PASN_SUPPORT is not set # CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# default: +# CONFIG_ESP_WIFI_BSS_MAX_IDLE_SUPPORT is not set CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10 CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 # CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE is not set @@ -1057,12 +1589,14 @@ CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y # CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT is not set CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM=7 -# CONFIG_ESP_WIFI_NAN_ENABLE is not set +# CONFIG_ESP_WIFI_NAN_SYNC_ENABLE is not set CONFIG_ESP_WIFI_MBEDTLS_CRYPTO=y -CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y +# CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT is not set # CONFIG_ESP_WIFI_WAPI_PSK is not set # CONFIG_ESP_WIFI_11KV_SUPPORT is not set # CONFIG_ESP_WIFI_MBO_SUPPORT is not set +# default: +# CONFIG_ESP_WIFI_ENABLE_ROAMING_APP is not set # CONFIG_ESP_WIFI_DPP_SUPPORT is not set # CONFIG_ESP_WIFI_11R_SUPPORT is not set # CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set @@ -1072,14 +1606,198 @@ CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y # # CONFIG_ESP_WIFI_WPS_STRICT is not set # CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set +# default: +# CONFIG_ESP_WIFI_WPS_RECONNECT_ON_FAIL is not set # end of WPS Configuration Options # CONFIG_ESP_WIFI_DEBUG_PRINT is not set -# CONFIG_ESP_WIFI_TESTING_OPTIONS is not set CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y # CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set +# default: +# CONFIG_ESP_WIFI_PASSIVE_HIDDEN_AP_SUPPORT is not set +# default: +# CONFIG_ESP_WIFI_PRIVACY_ENHANCEMENTS_ENABLED is not set # end of Wi-Fi +# +# Wi-Fi Remote +# +# default: +CONFIG_ESP_WIFI_REMOTE_IN_IDF=y +# default: +CONFIG_ESP_WIFI_REMOTE_ENABLED=y +# default: +CONFIG_SLAVE_IDF_TARGET_ESP32=y +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S2 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C3 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S3 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C2 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C6 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C5 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32C61 is not set +# default: +# CONFIG_SLAVE_IDF_TARGET_ESP32S31 is not set +# default: +CONFIG_SLAVE_SOC_WIFI_SUPPORTED=y +# default: +CONFIG_SLAVE_SOC_WIFI_WAPI_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_CSI_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_MESH_SUPPORT=y +# default: +CONFIG_SLAVE_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +# default: +CONFIG_SLAVE_SOC_WIFI_NAN_SUPPORT=y +# default: +CONFIG_SLAVE_IDF_TARGET_ARCH_XTENSA=y + +# +# Wi-Fi configuration +# +# default: +CONFIG_WIFI_RMT_STATIC_RX_BUFFER_NUM=10 +# default: +CONFIG_WIFI_RMT_DYNAMIC_RX_BUFFER_NUM=32 +# default: +# CONFIG_WIFI_RMT_STATIC_TX_BUFFER is not set +# default: +CONFIG_WIFI_RMT_DYNAMIC_TX_BUFFER=y +# default: +CONFIG_WIFI_RMT_TX_BUFFER_TYPE=1 +# default: +CONFIG_WIFI_RMT_DYNAMIC_TX_BUFFER_NUM=32 +# default: +CONFIG_WIFI_RMT_STATIC_RX_MGMT_BUFFER=y +# default: +# CONFIG_WIFI_RMT_DYNAMIC_RX_MGMT_BUFFER is not set +# default: +CONFIG_WIFI_RMT_DYNAMIC_RX_MGMT_BUF=0 +# default: +CONFIG_WIFI_RMT_RX_MGMT_BUF_NUM_DEF=5 +# default: +# CONFIG_WIFI_RMT_CSI_ENABLED is not set +# default: +CONFIG_WIFI_RMT_AMPDU_TX_ENABLED=y +# default: +CONFIG_WIFI_RMT_TX_BA_WIN=6 +# default: +CONFIG_WIFI_RMT_AMPDU_RX_ENABLED=y +# default: +CONFIG_WIFI_RMT_RX_BA_WIN=6 +# default: +CONFIG_WIFI_RMT_NVS_ENABLED=y +# default: +CONFIG_WIFI_RMT_TASK_PINNED_TO_CORE_0=y +# default: +# CONFIG_WIFI_RMT_TASK_PINNED_TO_CORE_1 is not set +# default: +CONFIG_WIFI_RMT_SOFTAP_BEACON_MAX_LEN=752 +# default: +CONFIG_WIFI_RMT_MGMT_SBUF_NUM=32 +# default: +CONFIG_WIFI_RMT_IRAM_OPT=y +# default: +# CONFIG_WIFI_RMT_EXTRA_IRAM_OPT is not set +# default: +CONFIG_WIFI_RMT_RX_IRAM_OPT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_SAE=y +# default: +CONFIG_WIFI_RMT_ENABLE_SAE_H2E=y +# default: +CONFIG_WIFI_RMT_ENABLE_SAE_PK=y +# default: +CONFIG_WIFI_RMT_SOFTAP_SAE_SUPPORT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_OWE_STA=y +# default: +CONFIG_WIFI_RMT_WPA3_COMPATIBLE_SUPPORT=y +# default: +CONFIG_WIFI_RMT_ENABLE_WPA3_OWE_SOFTAP=y +# default: +# CONFIG_WIFI_RMT_PASN_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_SLP_IRAM_OPT is not set +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# default: +# CONFIG_WIFI_RMT_BSS_MAX_IDLE_SUPPORT is not set +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_MAX_ACTIVE_TIME=10 +# default: +CONFIG_WIFI_RMT_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 +# default: +CONFIG_WIFI_RMT_STA_DISCONNECTED_PM_ENABLE=y +# default: +CONFIG_WIFI_RMT_GMAC_SUPPORT=y +# default: +CONFIG_WIFI_RMT_SOFTAP_SUPPORT=y +# default: +# CONFIG_WIFI_RMT_SLP_BEACON_LOST_OPT is not set +# default: +CONFIG_WIFI_RMT_ESPNOW_MAX_ENCRYPT_NUM=7 +# default: +# CONFIG_WIFI_RMT_NAN_SYNC_ENABLE is not set +# default: +CONFIG_WIFI_RMT_MBEDTLS_CRYPTO=y +# default: +CONFIG_WIFI_RMT_MBEDTLS_TLS_CLIENT=y +# default: +# CONFIG_WIFI_RMT_WAPI_PSK is not set +# default: +# CONFIG_WIFI_RMT_11KV_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_MBO_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_ENABLE_ROAMING_APP is not set +# default: +# CONFIG_WIFI_RMT_DPP_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_11R_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_WPS_SOFTAP_REGISTRAR is not set + +# +# WPS Configuration Options +# +# default: +# CONFIG_WIFI_RMT_WPS_STRICT is not set +# default: +# CONFIG_WIFI_RMT_WPS_PASSPHRASE is not set +# default: +# CONFIG_WIFI_RMT_WPS_RECONNECT_ON_FAIL is not set +# end of WPS Configuration Options + +# default: +# CONFIG_WIFI_RMT_DEBUG_PRINT is not set +# default: +CONFIG_WIFI_RMT_ENTERPRISE_SUPPORT=y +# default: +# CONFIG_WIFI_RMT_ENT_FREE_DYNAMIC_BUFFER is not set +# default: +# CONFIG_WIFI_RMT_PASSIVE_HIDDEN_AP_SUPPORT is not set +# default: +# CONFIG_WIFI_RMT_PRIVACY_ENHANCEMENTS_ENABLED is not set +# end of Wi-Fi configuration + +# default: +CONFIG_ESP_WIFI_REMOTE_LIBRARY_HOSTED=y +# default: +# CONFIG_ESP_WIFI_REMOTE_LIBRARY_EPPP is not set +# default: +# CONFIG_ESP_WIFI_REMOTE_LIBRARY_CUSTOM is not set +# default: +CONFIG_ESP_WIFI_REMOTE_EAP_ENABLED=y +# end of Wi-Fi Remote + # # Core dump # @@ -1119,15 +1837,35 @@ CONFIG_FATFS_CODEPAGE_437=y # CONFIG_FATFS_CODEPAGE_936 is not set # CONFIG_FATFS_CODEPAGE_949 is not set # CONFIG_FATFS_CODEPAGE_950 is not set +# default: CONFIG_FATFS_CODEPAGE=437 CONFIG_FATFS_FS_LOCK=0 CONFIG_FATFS_TIMEOUT_MS=10000 CONFIG_FATFS_PER_FILE_CACHE=y +# default: +CONFIG_FATFS_ALLOC_PREFER_ALIGNED_WORK_BUFFERS=y # CONFIG_FATFS_USE_FASTSEEK is not set +# default: +CONFIG_FATFS_USE_STRFUNC_NONE=y +# default: +# CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set +# default: +# CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 # CONFIG_FATFS_IMMEDIATE_FSYNC is not set # CONFIG_FATFS_USE_LABEL is not set CONFIG_FATFS_LINK_LOCK=y +# default: +CONFIG_FATFS_USE_DYN_BUFFERS=y + +# +# File system free space calculation behavior +# +# default: +CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 +# default: +CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 +# end of File system free space calculation behavior # end of FAT Filesystem support # @@ -1149,10 +1887,13 @@ CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 # CONFIG_FREERTOS_USE_TICK_HOOK is not set CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 # CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set +# default: +CONFIG_FREERTOS_USE_TIMERS=y CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set # CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y +# default: CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 @@ -1168,29 +1909,39 @@ CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1 # # Port # -CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y # CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y # CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set -# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set +# default: CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y CONFIG_FREERTOS_ISR_STACKSIZE=1536 CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y # CONFIG_FREERTOS_FPU_IN_ISR is not set +# default: CONFIG_FREERTOS_TICK_SUPPORT_CORETIMER=y CONFIG_FREERTOS_CORETIMER_0=y # CONFIG_FREERTOS_CORETIMER_1 is not set +# default: CONFIG_FREERTOS_SYSTICK_USES_CCOUNT=y -# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set +# default: +CONFIG_FREERTOS_IN_IRAM=y # CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set # end of Port +# +# Extra +# +# end of Extra + +# default: CONFIG_FREERTOS_PORT=y +# default: CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF +# default: CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y +# default: CONFIG_FREERTOS_DEBUG_OCDAWARE=y -CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y -CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y +# default: CONFIG_FREERTOS_NUMBER_OF_CORES=2 # end of FreeRTOS @@ -1201,14 +1952,17 @@ CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y # CONFIG_HAL_ASSERTION_DISABLE is not set # CONFIG_HAL_ASSERTION_SILENT is not set # CONFIG_HAL_ASSERTION_ENABLE is not set +# default: CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 -CONFIG_HAL_SPI_MASTER_FUNC_IN_IRAM=y -CONFIG_HAL_SPI_SLAVE_FUNC_IN_IRAM=y +# default: +CONFIG_HAL_GPIO_USE_ROM_IMPL=y # end of Hardware Abstraction Layer (HAL) and Low Level (LL) # # Heap memory debugging # +# default: +CONFIG_HEAP_HAS_EXEC_HEAP=y CONFIG_HEAP_POISONING_DISABLED=y # CONFIG_HEAP_POISONING_LIGHT is not set # CONFIG_HEAP_POISONING_COMPREHENSIVE is not set @@ -1222,7 +1976,17 @@ CONFIG_HEAP_TRACING_OFF=y # end of Heap memory debugging # -# Log output +# Log +# +# default: +CONFIG_LOG_VERSION_1=y +# default: +# CONFIG_LOG_VERSION_2 is not set +# default: +CONFIG_LOG_VERSION=1 + +# +# Log Level # # CONFIG_LOG_DEFAULT_LEVEL_NONE is not set # CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set @@ -1230,23 +1994,61 @@ CONFIG_HEAP_TRACING_OFF=y CONFIG_LOG_DEFAULT_LEVEL_INFO=y # CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set # CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set +# default: CONFIG_LOG_DEFAULT_LEVEL=3 CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y # CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set # CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set +# default: CONFIG_LOG_MAXIMUM_LEVEL=3 + +# +# Level Settings +# # CONFIG_LOG_MASTER_LEVEL is not set +# default: +CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y +# default: +# CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set +# default: +# CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set +# default: +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y +# default: +# CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set +# default: +CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y +# default: +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 +# end of Level Settings +# end of Log Level + +# +# Format +# CONFIG_LOG_COLORS=y CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y # CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set -# end of Log output +# end of Format + +# +# Settings +# +# default: +CONFIG_LOG_MODE_TEXT_EN=y +# default: +CONFIG_LOG_MODE_TEXT=y +# end of Settings + +# default: +CONFIG_LOG_IN_IRAM=y +# end of Log # # LWIP # CONFIG_LWIP_ENABLE=y CONFIG_LWIP_LOCAL_HOSTNAME="U64-WiFi" -# CONFIG_LWIP_NETIF_API is not set CONFIG_LWIP_TCPIP_TASK_PRIO=18 # CONFIG_LWIP_TCPIP_CORE_LOCKING is not set # CONFIG_LWIP_CHECK_THREAD_SAFETY is not set @@ -1256,6 +2058,8 @@ CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y # CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set CONFIG_LWIP_TIMERS_ONDEMAND=y CONFIG_LWIP_ND6=y +# default: +# CONFIG_LWIP_ND6_SUPPORT_STATIC_ENTRIES is not set # CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set CONFIG_LWIP_MAX_SOCKETS=16 # CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set @@ -1270,6 +2074,8 @@ CONFIG_LWIP_IP6_FRAG=y # CONFIG_LWIP_IP4_REASSEMBLY is not set # CONFIG_LWIP_IP6_REASSEMBLY is not set CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 +# default: +CONFIG_LWIP_IPV6_DUP_DETECT_ATTEMPTS=1 # CONFIG_LWIP_IP_FORWARD is not set # CONFIG_LWIP_STATS is not set CONFIG_LWIP_ESP_GRATUITOUS_ARP=y @@ -1278,10 +2084,12 @@ CONFIG_LWIP_ESP_MLDV6_REPORT=y CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y +# CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set +# CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set # CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y # CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set -CONFIG_LWIP_DHCP_OPTIONS_LEN=68 +CONFIG_LWIP_DHCP_OPTIONS_LEN=69 CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 @@ -1298,6 +2106,8 @@ CONFIG_LWIP_IPV6=y CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 # CONFIG_LWIP_IPV6_FORWARD is not set # CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set +# default: +# CONFIG_LWIP_NETIF_LINK_CALLBACK is not set CONFIG_LWIP_NETIF_LOOPBACK=y CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 @@ -1346,10 +2156,19 @@ CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set # CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU1 is not set +# default: CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF -# CONFIG_LWIP_PPP_SUPPORT is not set CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 +# default: +CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 +# default: +# CONFIG_LWIP_IPV6_ND6_ROUTE_INFO_OPTION_SUPPORT is not set +# CONFIG_LWIP_PPP_SUPPORT is not set # CONFIG_LWIP_SLIP_SUPPORT is not set # @@ -1379,8 +2198,14 @@ CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 # # DNS # +# default: +CONFIG_LWIP_DNS_MAX_HOST_IP=1 CONFIG_LWIP_DNS_MAX_SERVERS=3 # CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set +# default: +# CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set +# default: +# CONFIG_LWIP_USE_ESP_GETADDRINFO is not set # end of DNS CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 @@ -1401,9 +2226,19 @@ CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set +# default: +CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE=y +# default: +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_DEFAULT is not set +# default: +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_CUSTOM is not set CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set # CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set +# default: +CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y +# default: +# CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y # CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT is not set # CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set @@ -1415,6 +2250,31 @@ CONFIG_LWIP_HOOK_IP6_INPUT_NONE=y # # mbedTLS # + +# +# Core Configuration +# +# default: +CONFIG_MBEDTLS_VER_4_X_SUPPORT=y +# default: +# CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_NONE is not set +# default: +CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE=y +# default: +# CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_PERF is not set +# default: +# CONFIG_MBEDTLS_PSA_ITS_CUSTOM_STORAGE_BACKEND is not set +CONFIG_MBEDTLS_THREADING_C=y +# default: +# CONFIG_MBEDTLS_THREADING_ALT is not set +# default: +CONFIG_MBEDTLS_THREADING_PTHREAD=y +CONFIG_MBEDTLS_ERROR_STRINGS=y +# default: +CONFIG_MBEDTLS_VERSION_C=y +CONFIG_MBEDTLS_HAVE_TIME=y +# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set +CONFIG_MBEDTLS_HAVE_TIME_DATE=y CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y # CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set # CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set @@ -1422,161 +2282,279 @@ CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 # CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set +# default: +# CONFIG_MBEDTLS_VERSION_FEATURES is not set # CONFIG_MBEDTLS_DEBUG is not set +# default: +CONFIG_MBEDTLS_SELF_TEST=y +# end of Core Configuration # -# mbedTLS v3.x related +# Certificates # -# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set -# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set -# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set -# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set -CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y -CONFIG_MBEDTLS_PKCS7_C=y -# end of mbedTLS v3.x related +# default: +CONFIG_MBEDTLS_X509_USE_C=y +CONFIG_MBEDTLS_PEM_PARSE_C=y +CONFIG_MBEDTLS_PEM_WRITE_C=y +# default: +CONFIG_MBEDTLS_PK_C=y +# default: +CONFIG_MBEDTLS_PK_PARSE_C=y +# default: +CONFIG_MBEDTLS_PK_WRITE_C=y +# default: +# CONFIG_MBEDTLS_X509_REMOVE_INFO is not set +CONFIG_MBEDTLS_X509_CRL_PARSE_C=y +# default: +CONFIG_MBEDTLS_X509_CRT_PARSE_C=y +CONFIG_MBEDTLS_X509_CSR_PARSE_C=y +# default: +# CONFIG_MBEDTLS_X509_CREATE_C is not set +# default: +CONFIG_MBEDTLS_X509_RSASSA_PSS_SUPPORT=y +CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK=y +# default: +CONFIG_MBEDTLS_ASN1_PARSE_C=y +# default: +CONFIG_MBEDTLS_ASN1_WRITE_C=y +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y # -# Certificate Bundle +# Certificate Bundle Configuration # -CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y -CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y +# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL is not set # CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set -# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set -# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set -# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE=y +CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE=y +CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH="../../u64ctrl/ca/cacert.pem" CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 -# end of Certificate Bundle +# end of Certificate Bundle Configuration + +# default: +# CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set +# default: +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_CROSS_SIGNED_VERIFY=y +# end of Certificates -# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set -CONFIG_MBEDTLS_CMAC_C=y -CONFIG_MBEDTLS_HARDWARE_AES=y -CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y -CONFIG_MBEDTLS_HARDWARE_MPI=y -# CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI is not set -CONFIG_MBEDTLS_HARDWARE_SHA=y -CONFIG_MBEDTLS_ROM_MD5=y -# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set -# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set -CONFIG_MBEDTLS_HAVE_TIME=y -# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set -# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set -CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y -CONFIG_MBEDTLS_SHA512_C=y -CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y -# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set -# CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set -# CONFIG_MBEDTLS_TLS_DISABLED is not set -CONFIG_MBEDTLS_TLS_SERVER=y -CONFIG_MBEDTLS_TLS_CLIENT=y CONFIG_MBEDTLS_TLS_ENABLED=y # -# TLS Key Exchange Methods +# TLS Protocol Configuration +# +CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y +CONFIG_MBEDTLS_SSL_PROTO_TLS1_3=y + +# +# TLS 1.3 Configuration +# +# default: +CONFIG_MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE=y +# default: +CONFIG_MBEDTLS_SSL_TLS1_3_KEXM_PSK=y +# default: +CONFIG_MBEDTLS_SSL_TLS1_3_KEXM_EPHEMERAL=y +# default: +CONFIG_MBEDTLS_SSL_TLS1_3_KEXM_PSK_EPHEMERAL=y +# default: +# CONFIG_MBEDTLS_SSL_EARLY_DATA is not set +# end of TLS 1.3 Configuration + +# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set +# default: +CONFIG_MBEDTLS_TLS_CLIENT=y +# CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT is not set +# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set +CONFIG_MBEDTLS_TLS_CLIENT_ONLY=y +# default: +CONFIG_MBEDTLS_SSL_CID_PADDING_GRANULARITY=16 +CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y +# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set +# default: +CONFIG_MBEDTLS_SSL_CACHE_C=y +# default: +CONFIG_MBEDTLS_SSL_ALL_ALERT_MESSAGES=y + +# +# TLS Key Exchange Configuration # # CONFIG_MBEDTLS_PSK_MODES is not set CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y -CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y -CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y -# end of TLS Key Exchange Methods +# end of TLS Key Exchange Configuration -CONFIG_MBEDTLS_SSL_RENEGOTIATION=y -CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y -# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set -# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set +# default: +CONFIG_MBEDTLS_SSL_SERVER_NAME_INDICATION=y CONFIG_MBEDTLS_SSL_ALPN=y +# default: +CONFIG_MBEDTLS_SSL_MAX_FRAGMENT_LENGTH=y +# default: +# CONFIG_MBEDTLS_SSL_RECORD_SIZE_LIMIT is not set +# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set +# CONFIG_MBEDTLS_SSL_RENEGOTIATION is not set CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y +# default: +# CONFIG_MBEDTLS_SSL_KEYING_MATERIAL_EXPORT is not set +# end of TLS Protocol Configuration + +# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set # # Symmetric Ciphers # CONFIG_MBEDTLS_AES_C=y # CONFIG_MBEDTLS_CAMELLIA_C is not set +# default: +# CONFIG_MBEDTLS_ARIA_C is not set # CONFIG_MBEDTLS_DES_C is not set -# CONFIG_MBEDTLS_BLOWFISH_C is not set -# CONFIG_MBEDTLS_XTEA_C is not set CONFIG_MBEDTLS_CCM_C=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CBC=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CFB=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_CTR=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_OFB=y +# default: +CONFIG_MBEDTLS_CIPHER_MODE_XTS=y CONFIG_MBEDTLS_GCM_C=y # CONFIG_MBEDTLS_NIST_KW_C is not set +# default: +CONFIG_MBEDTLS_AES_ROM_TABLES=y +# default: +# CONFIG_MBEDTLS_AES_FEWER_TABLES is not set +# default: +# CONFIG_MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is not set +CONFIG_MBEDTLS_CMAC_C=y # end of Symmetric Ciphers -# CONFIG_MBEDTLS_RIPEMD160_C is not set - # -# Certificates +# Asymmetric Ciphers # -CONFIG_MBEDTLS_PEM_PARSE_C=y -CONFIG_MBEDTLS_PEM_WRITE_C=y -CONFIG_MBEDTLS_X509_CRL_PARSE_C=y -CONFIG_MBEDTLS_X509_CSR_PARSE_C=y -# end of Certificates - +# default: +CONFIG_MBEDTLS_RSA_C=y CONFIG_MBEDTLS_ECP_C=y -# CONFIG_MBEDTLS_DHM_C is not set -CONFIG_MBEDTLS_ECDH_C=y -CONFIG_MBEDTLS_ECDSA_C=y -# CONFIG_MBEDTLS_ECJPAKE_C is not set -CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y + +# +# Supported Curves +# CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y -CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y +# CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED is not set +# CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED is not set CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y +# end of Supported Curves + +# +# Elliptic Curve Ciphers Configuration +# CONFIG_MBEDTLS_ECP_NIST_OPTIM=y CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM=y -# CONFIG_MBEDTLS_POLY1305_C is not set -# CONFIG_MBEDTLS_CHACHA20_C is not set -# CONFIG_MBEDTLS_HKDF_C is not set -# CONFIG_MBEDTLS_THREADING_C is not set -CONFIG_MBEDTLS_ERROR_STRINGS=y -# end of mbedTLS +# CONFIG_MBEDTLS_DHM_C is not set +CONFIG_MBEDTLS_ECDH_C=y +# CONFIG_MBEDTLS_ECJPAKE_C is not set +CONFIG_MBEDTLS_ECDSA_C=y +# default: +CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y +# default: +CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y +CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y +# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set +# end of Elliptic Curve Ciphers Configuration +# end of Asymmetric Ciphers # -# ESP-MQTT Configurations +# Hash functions # -CONFIG_MQTT_PROTOCOL_311=y -# CONFIG_MQTT_PROTOCOL_5 is not set -CONFIG_MQTT_TRANSPORT_SSL=y -CONFIG_MQTT_TRANSPORT_WEBSOCKET=y -CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y -# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set -# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set -# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set -# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set -# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set -# CONFIG_MQTT_CUSTOM_OUTBOX is not set -# end of ESP-MQTT Configurations +# CONFIG_MBEDTLS_RIPEMD160_C is not set +# default: +CONFIG_MBEDTLS_MD_C=y +# default: +CONFIG_MBEDTLS_MD5_C=y +# default: +CONFIG_MBEDTLS_SHA1_C=y +# default: +# CONFIG_MBEDTLS_SHA224_C is not set +# default: +CONFIG_MBEDTLS_SHA256_C=y +# default: +CONFIG_MBEDTLS_SHA384_C=y +CONFIG_MBEDTLS_SHA512_C=y +# default: +# CONFIG_MBEDTLS_SHA3_C is not set +CONFIG_MBEDTLS_ROM_MD5=y +# end of Hash functions # -# Newlib +# Hardware Acceleration # -CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y -# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set -# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set -# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set -# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set -CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y -# CONFIG_NEWLIB_NANO_FORMAT is not set -CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y -# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set -# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set -# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set -# end of Newlib +CONFIG_MBEDTLS_HARDWARE_SHA=y +CONFIG_MBEDTLS_HARDWARE_MPI=y +CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI=y + +# +# Security hardening +# +# default: +# CONFIG_MBEDTLS_CONSTANT_TIME_PRIME_GEN is not set +# end of Security hardening + +CONFIG_MBEDTLS_HARDWARE_AES=y +# default: +# CONFIG_MBEDTLS_AES_SOFT_FALLBACK is not set +CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y +# CONFIG_MBEDTLS_SECURE_ELEMENT_DRIVER_ENABLED is not set +# end of Hardware Acceleration + +# +# Entropy and Random Number Generation +# +# default: +# CONFIG_MBEDTLS_ENTROPY_FORCE_SHA256 is not set +# default: +CONFIG_MBEDTLS_CTR_DRBG_C=y +# default: +CONFIG_MBEDTLS_HMAC_DRBG_C=y +# end of Entropy and Random Number Generation + +# +# Encoding/Decoding +# +# default: +CONFIG_MBEDTLS_BASE64_C=y +# default: +CONFIG_MBEDTLS_PKCS5_C=y +CONFIG_MBEDTLS_PKCS7_C=y +# default: +CONFIG_MBEDTLS_PKCS1_V15=y +# default: +CONFIG_MBEDTLS_PKCS1_V21=y +# end of Encoding/Decoding + +# +# Stream Cipher +# +# default: +CONFIG_MBEDTLS_CHACHAPOLY_C=y +CONFIG_MBEDTLS_CHACHA20_C=y +# end of Stream Cipher +# end of mbedTLS # # NVS # # CONFIG_NVS_ASSERT_ERROR_CHECK is not set # CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set +# default: +# CONFIG_NVS_BDL_STACK is not set +# default: +# CONFIG_NVS_FLASH_VERIFY_ERASE is not set # end of NVS # @@ -1585,25 +2563,13 @@ CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y # CONFIG_OPENTHREAD_ENABLED is not set # -# Thread Operational Dataset +# OpenThread Spinel # -CONFIG_OPENTHREAD_NETWORK_NAME="OpenThread-ESP" -CONFIG_OPENTHREAD_MESH_LOCAL_PREFIX="fd00:db8:a0:0::/64" -CONFIG_OPENTHREAD_NETWORK_CHANNEL=15 -CONFIG_OPENTHREAD_NETWORK_PANID=0x1234 -CONFIG_OPENTHREAD_NETWORK_EXTPANID="dead00beef00cafe" -CONFIG_OPENTHREAD_NETWORK_MASTERKEY="00112233445566778899aabbccddeeff" -CONFIG_OPENTHREAD_NETWORK_PSKC="104810e2315100afd6bc9215a6bfac53" -# end of Thread Operational Dataset - -CONFIG_OPENTHREAD_XTAL_ACCURACY=130 # CONFIG_OPENTHREAD_SPINEL_ONLY is not set -CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y +# end of OpenThread Spinel -# -# Thread Address Query Config -# -# end of Thread Address Query Config +# default: +# CONFIG_OPENTHREAD_DEBUG is not set # end of OpenThread # @@ -1612,6 +2578,8 @@ CONFIG_OPENTHREAD_RX_ON_WHEN_IDLE=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y +# default: +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y # end of Protocomm # @@ -1623,15 +2591,28 @@ CONFIG_PTHREAD_STACK_MIN=768 CONFIG_PTHREAD_DEFAULT_CORE_NO_AFFINITY=y # CONFIG_PTHREAD_DEFAULT_CORE_0 is not set # CONFIG_PTHREAD_DEFAULT_CORE_1 is not set +# default: CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" # end of PThreads +# +# SD Protocol Layer Configuration +# +# default: +CONFIG_SD_ENABLE_SDIO_SUPPORT=y +# default: +CONFIG_SD_READY_POLL_PERIOD_START_US=100 +# end of SD Protocol Layer Configuration + # # MMU Config # +# default: CONFIG_MMU_PAGE_SIZE_64KB=y +# default: CONFIG_MMU_PAGE_MODE="64KB" +# default: CONFIG_MMU_PAGE_SIZE=0x10000 # end of MMU Config @@ -1643,6 +2624,7 @@ CONFIG_MMU_PAGE_SIZE=0x10000 # SPI Flash behavior when brownout # CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y +# default: CONFIG_SPI_FLASH_BROWNOUT_RESET=y # end of SPI Flash behavior when brownout @@ -1654,6 +2636,12 @@ CONFIG_SPI_FLASH_BROWNOUT_RESET=y # Features here require specific hardware (READ DOCS FIRST!) # CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 +# default: +# CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set +# default: +# CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set +# default: +CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM=y # end of Optional and Experimental Features (READ DOCS FIRST) # end of Main Flash configuration @@ -1662,7 +2650,6 @@ CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 # # CONFIG_SPI_FLASH_VERIFY_WRITE is not set # CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set -CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y # CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set # CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set @@ -1679,11 +2666,16 @@ CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 # # Auto-detect flash chips # -CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_GD_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORTED=y -CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORTED=y +# default: +CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_GD_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORT_ENABLED=y +# default: +CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORT_ENABLED=y CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y @@ -1777,12 +2769,17 @@ CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y # CONFIG_VFS_SELECT_IN_RAM is not set CONFIG_VFS_SUPPORT_TERMIOS=y CONFIG_VFS_MAX_COUNT=8 +# default: +# CONFIG_VFS_SUPPRESS_CTX_DEPRECATION is not set # # Host File System I/O (Semihosting) # CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # end of Host File System I/O (Semihosting) + +# default: +CONFIG_VFS_INITIALIZE_DEV_NULL=y # end of Virtual file system # @@ -1790,18 +2787,9 @@ CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 # # CONFIG_WL_SECTOR_SIZE_512 is not set CONFIG_WL_SECTOR_SIZE_4096=y +# default: CONFIG_WL_SECTOR_SIZE=4096 # end of Wear Levelling - -# -# Wi-Fi Provisioning Manager -# -CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 -CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 -# CONFIG_WIFI_PROV_BLE_FORCE_ENCRYPTION is not set -CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y -# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set -# end of Wi-Fi Provisioning Manager # end of Component config # CONFIG_IDF_EXPERIMENTAL_FEATURES is not set @@ -1812,6 +2800,8 @@ CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y # CONFIG_ESP32_NO_BLOBS is not set # CONFIG_ESP32_COMPATIBLE_PRE_V2_1_BOOTLOADERS is not set # CONFIG_ESP32_COMPATIBLE_PRE_V3_1_BOOTLOADERS is not set +# CONFIG_APP_ROLLBACK_ENABLE is not set +# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set # CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set # CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set @@ -1819,16 +2809,15 @@ CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y # CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set # CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set CONFIG_LOG_BOOTLOADER_LEVEL=3 -# CONFIG_APP_ROLLBACK_ENABLE is not set # CONFIG_FLASH_ENCRYPTION_ENABLED is not set # CONFIG_FLASHMODE_QIO is not set # CONFIG_FLASHMODE_QOUT is not set CONFIG_FLASHMODE_DIO=y # CONFIG_FLASHMODE_DOUT is not set CONFIG_MONITOR_BAUD=115200 -CONFIG_OPTIMIZATION_LEVEL_DEBUG=y -CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG=y -CONFIG_COMPILER_OPTIMIZATION_DEFAULT=y +# CONFIG_OPTIMIZATION_LEVEL_DEBUG is not set +# CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG is not set +# CONFIG_COMPILER_OPTIMIZATION_DEFAULT is not set # CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set # CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y @@ -1841,11 +2830,12 @@ CONFIG_STACK_CHECK_NONE=y # CONFIG_STACK_CHECK_STRONG is not set # CONFIG_STACK_CHECK_ALL is not set # CONFIG_WARN_WRITE_STRINGS is not set -# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set -CONFIG_ESP32_APPTRACE_DEST_NONE=y -CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y -CONFIG_ADC2_DISABLE_DAC=y -# CONFIG_MCPWM_ISR_IN_IRAM is not set +CONFIG_ADC_CAL_EFUSE_TP_ENABLE=y +CONFIG_ADC_CAL_EFUSE_VREF_ENABLE=y +CONFIG_ADC_CAL_LUT_ENABLE=y +CONFIG_ADC_DISABLE_DAC=y +# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set +# CONFIG_MCPWM_ISR_IRAM_SAFE is not set # CONFIG_EVENT_LOOP_PROFILING is not set CONFIG_POST_EVENTS_FROM_ISR=y CONFIG_POST_EVENTS_FROM_IRAM_ISR=y @@ -1867,10 +2857,48 @@ CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_RC=y # CONFIG_ESP32_RTC_CLK_SRC_INT_8MD256 is not set # CONFIG_ESP32_RTC_CLOCK_SOURCE_INTERNAL_8MD256 is not set CONFIG_ESP32_RTC_CLK_CAL_CYCLES=1024 +CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y # CONFIG_ESP32_XTAL_FREQ_26 is not set CONFIG_ESP32_XTAL_FREQ_40=y # CONFIG_ESP32_XTAL_FREQ_AUTO is not set CONFIG_ESP32_XTAL_FREQ=40 +CONFIG_BROWNOUT_DET=y +CONFIG_ESP32_BROWNOUT_DET=y +CONFIG_BROWNOUT_DET_LVL_SEL_0=y +CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_0=y +# CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_1 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_7 is not set +# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_7 is not set +CONFIG_BROWNOUT_DET_LVL=0 +CONFIG_ESP32_BROWNOUT_DET_LVL=0 +CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y +CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set +CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y +CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y +CONFIG_ESP32_TIME_SYSCALL_USE_RTC_HRT=y +CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1=y +# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set +# CONFIG_ESP32_TIME_SYSCALL_USE_RTC is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set +# CONFIG_ESP32_TIME_SYSCALL_USE_HRT is not set +# CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set +# CONFIG_ESP32_TIME_SYSCALL_USE_NONE is not set CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y # CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20 @@ -1879,6 +2907,13 @@ CONFIG_REDUCE_PHY_TX_POWER=y CONFIG_ESP32_REDUCE_PHY_TX_POWER=y # CONFIG_SPIRAM_SUPPORT is not set # CONFIG_ESP32_SPIRAM_SUPPORT is not set +CONFIG_CONSOLE_UART_DEFAULT=y +# CONFIG_CONSOLE_UART_CUSTOM is not set +# CONFIG_CONSOLE_UART_NONE is not set +# CONFIG_ESP_CONSOLE_UART_NONE is not set +CONFIG_CONSOLE_UART=y +CONFIG_CONSOLE_UART_NUM=0 +CONFIG_CONSOLE_UART_BAUDRATE=115200 # CONFIG_ESP32_DEFAULT_CPU_FREQ_80 is not set CONFIG_ESP32_DEFAULT_CPU_FREQ_160=y # CONFIG_ESP32_DEFAULT_CPU_FREQ_240 is not set @@ -1891,13 +2926,6 @@ CONFIG_ESP32_PANIC_PRINT_REBOOT=y CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 CONFIG_MAIN_TASK_STACK_SIZE=3584 -CONFIG_CONSOLE_UART_DEFAULT=y -# CONFIG_CONSOLE_UART_CUSTOM is not set -# CONFIG_CONSOLE_UART_NONE is not set -# CONFIG_ESP_CONSOLE_UART_NONE is not set -CONFIG_CONSOLE_UART=y -CONFIG_CONSOLE_UART_NUM=0 -CONFIG_CONSOLE_UART_BAUDRATE=115200 CONFIG_INT_WDT=y CONFIG_INT_WDT_TIMEOUT_MS=300 CONFIG_INT_WDT_CHECK_CPU1=y @@ -1909,29 +2937,10 @@ CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU1=y # CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set CONFIG_ESP32_DEBUG_OCDAWARE=y -CONFIG_BROWNOUT_DET=y -CONFIG_ESP32_BROWNOUT_DET=y -CONFIG_BROWNOUT_DET_LVL_SEL_0=y -CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_0=y -# CONFIG_BROWNOUT_DET_LVL_SEL_1 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_1 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_2 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_3 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_4 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_5 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_6 is not set -# CONFIG_BROWNOUT_DET_LVL_SEL_7 is not set -# CONFIG_ESP32_BROWNOUT_DET_LVL_SEL_7 is not set -CONFIG_BROWNOUT_DET_LVL=0 -CONFIG_ESP32_BROWNOUT_DET_LVL=0 # CONFIG_DISABLE_BASIC_ROM_CONSOLE is not set CONFIG_IPC_TASK_STACK_SIZE=1024 CONFIG_TIMER_TASK_STACK_SIZE=3584 +# CONFIG_ESP32_APPTRACE_ENABLE is not set CONFIG_ESP32_WIFI_ENABLED=y CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 @@ -1943,8 +2952,6 @@ CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y CONFIG_ESP32_WIFI_TX_BA_WIN=6 CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y -CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y -CONFIG_ESP32_WIFI_RX_BA_WIN=6 CONFIG_ESP32_WIFI_RX_BA_WIN=6 CONFIG_ESP32_WIFI_NVS_ENABLED=y CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_0=y @@ -1955,8 +2962,36 @@ CONFIG_ESP32_WIFI_IRAM_OPT=y CONFIG_ESP32_WIFI_RX_IRAM_OPT=y CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y +# CONFIG_ESP_WIFI_NAN_ENABLE is not set +CONFIG_WPA_MBEDTLS_CRYPTO=y +# CONFIG_WPA_MBEDTLS_TLS_CLIENT is not set +# CONFIG_WPA_WAPI_PSK is not set +# CONFIG_WPA_11KV_SUPPORT is not set +# CONFIG_WPA_MBO_SUPPORT is not set +# CONFIG_WPA_DPP_SUPPORT is not set +# CONFIG_WPA_11R_SUPPORT is not set +# CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set +# CONFIG_WPA_WPS_STRICT is not set +# CONFIG_WPA_DEBUG_PRINT is not set +CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 +CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 +CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=1 +CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 +# CONFIG_ESP32_WIFI_CSI_ENABLED is not set +CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y +CONFIG_ESP32_WIFI_TX_BA_WIN=6 +CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y +CONFIG_ESP32_WIFI_RX_BA_WIN=6 +CONFIG_ESP32_WIFI_NVS_ENABLED=y +CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 +CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 +CONFIG_ESP32_WIFI_IRAM_OPT=y +CONFIG_ESP32_WIFI_RX_IRAM_OPT=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y +# CONFIG_ESP_WIFI_NAN_ENABLE is not set CONFIG_WPA_MBEDTLS_CRYPTO=y -CONFIG_WPA_MBEDTLS_TLS_CLIENT=y +# CONFIG_WPA_MBEDTLS_TLS_CLIENT is not set # CONFIG_WPA_WAPI_PSK is not set # CONFIG_WPA_11KV_SUPPORT is not set # CONFIG_WPA_MBO_SUPPORT is not set @@ -1965,7 +3000,6 @@ CONFIG_WPA_MBEDTLS_TLS_CLIENT=y # CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set # CONFIG_WPA_WPS_STRICT is not set # CONFIG_WPA_DEBUG_PRINT is not set -# CONFIG_WPA_TESTING_OPTIONS is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y @@ -1996,12 +3030,8 @@ CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y # CONFIG_TCPIP_TASK_AFFINITY_CPU1 is not set CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF # CONFIG_PPP_SUPPORT is not set -CONFIG_ESP32_TIME_SYSCALL_USE_RTC_HRT=y -CONFIG_ESP32_TIME_SYSCALL_USE_RTC_FRC1=y -# CONFIG_ESP32_TIME_SYSCALL_USE_RTC is not set -# CONFIG_ESP32_TIME_SYSCALL_USE_HRT is not set -# CONFIG_ESP32_TIME_SYSCALL_USE_FRC1 is not set -# CONFIG_ESP32_TIME_SYSCALL_USE_NONE is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 CONFIG_ESP32_PTHREAD_STACK_MIN=768 diff --git a/software/wifi/tests/Makefile b/software/wifi/tests/Makefile index 4eb872ab5..831f16c37 100644 --- a/software/wifi/tests/Makefile +++ b/software/wifi/tests/Makefile @@ -25,12 +25,17 @@ DIR_raw_u64 := $(PATH_SW)/wifi/raw_u64/main DIR_raw_c3 := $(PATH_SW)/wifi/raw_c3/main DIR_u64ctrl := $(PATH_SW)/u64ctrl/main # The U64 and U2+L modules have the radio switch (radio_boot.h): only they see wifi/common -INC_raw_u64 := -I$(PATH_SW)/wifi/common +INC_raw_u64 := -I$(PATH_SW)/wifi/common -I$(PATH_SW)/wifi/tls INC_raw_c3 := -I$(PATH_SW)/wifi/common +# u64ctrl's rpc_calls.h and wifi_modem.h include rpc_shared.h and radio_entropy.h from there. It has no radio +# switch: module_env.h does not count it as one, although radio_boot.h is on its path now +INC_u64ctrl := -I$(PATH_SW)/wifi/common HOSTTEST := $(PATH_SW)/io/usb/tests CASES := $(wildcard module_*_test.cpp) RADIO := $(wildcard radio_*test.cpp) +# radio_entropy.h includes rpc_calls.h of raw_u64, which needs lwIP's headers; the wifi_random test stubs them out +RADIO_INC := -I$(PATH_SW)/wifi/common -I$(PATH_SW)/wifi/tls -I$(PATH_SW)/wifi/raw_u64/main -I$(PATH_SW)/test/wifi_random COMMON := -g -O0 -Wall -Wno-unused-parameter -D_FORTIFY_SOURCE=0 CFLAGS := -std=gnu11 $(COMMON) -Wno-unused-variable -Wno-unused-function CXXFLAGS := -std=c++14 $(COMMON) -I$(HOSTTEST) -I. -Istub @@ -84,9 +89,9 @@ run: radio: @mkdir -p $(OUT)/radio - $(CC) -std=c99 $(COMMON) -I$(PATH_SW)/wifi/common -c -o $(OUT)/radio/wifi_radio.o $(PATH_SW)/wifi/common/wifi_radio.c + $(CC) -std=c99 $(COMMON) $(RADIO_INC) -c -o $(OUT)/radio/wifi_radio.o $(PATH_SW)/wifi/common/wifi_radio.c $(CC) -std=c99 $(COMMON) -I$(PATH_SW)/wifi/common -c -o $(OUT)/radio/radio_boot.o $(PATH_SW)/wifi/common/radio_boot.c - $(CXX) $(CXXFLAGS) -I$(PATH_SW)/wifi/common -o $(OUT)/radio/wifi_radio_test $(RADIO) $(HOSTTEST)/host_test_main.cpp \ + $(CXX) $(CXXFLAGS) $(RADIO_INC) -o $(OUT)/radio/wifi_radio_test $(RADIO) $(HOSTTEST)/host_test_main.cpp \ $(OUT)/radio/wifi_radio.o $(OUT)/radio/radio_boot.o -lpthread @echo "== radio"; $(OUT)/radio/wifi_radio_test diff --git a/software/wifi/tests/module_env.h b/software/wifi/tests/module_env.h index b1874f6cf..bf0c10686 100644 --- a/software/wifi/tests/module_env.h +++ b/software/wifi/tests/module_env.h @@ -95,7 +95,7 @@ typedef struct { } wifi_event_sta_disconnected_t; enum { WIFI_EVENT_STA_START, WIFI_EVENT_STA_CONNECTED, WIFI_EVENT_STA_DISCONNECTED }; -#if __has_include("radio_boot.h") +#if !defined(MODULE_U64CTRL) && __has_include("radio_boot.h") #include "radio_boot.h" // the U64 and U2+L modules' restart record #define MODULE_HAS_SWITCH 1 #endif diff --git a/software/wifi/tests/radio_test.cpp b/software/wifi/tests/radio_test.cpp index 87367c71a..2444de0bb 100644 --- a/software/wifi/tests/radio_test.cpp +++ b/software/wifi/tests/radio_test.cpp @@ -3,7 +3,8 @@ * * wifi_radio.c (the one place that starts and stops the radio of the U64 and U2+L modules) * against a chip stub that counts the Wi-Fi starts and stops and can be told to fail them, - * and radio_boot.c (the radio's state across a restart of the module). + * and radio_boot.c (the radio's state across a restart of the module), and a stub of the entropy gate + * (radio_entropy.c has its own test, target/pc/linux/radioentropy). */ #include @@ -12,6 +13,7 @@ extern "C" { #include "wifi_radio.h" #include "wifi_radio_port.h" #include "radio_boot.h" +#include "radio_entropy.h" } #define CHECK(cond, what) EXPECT_TRUE((cond) && (what)) @@ -21,10 +23,17 @@ extern "C" { static int starts, stops; static int start_result, stop_result; static int chip_on; // what the chip does, as opposed to what wifi_radio.c believes +static int on_during_stop; // radio_is_on() while the chip was stopping +static int gate_result; // what radio_entropy_change_begin() answers +static int gate_held; // begun and not ended +static int changes; // radio_entropy_changing() calls +static int chip_in_gate; // chip calls made with the gate held + extern "C" int wr_port_wifi_start(void) { starts++; + chip_in_gate += (gate_held == 1); if (start_result == 0) { chip_on = 1; } @@ -34,18 +43,45 @@ extern "C" int wr_port_wifi_start(void) extern "C" int wr_port_wifi_stop(void) { stops++; + chip_in_gate += (gate_held == 1); + on_during_stop = radio_is_on(); if (stop_result == 0) { chip_on = 0; } return stop_result; } +extern "C" int radio_entropy_change_begin(void) +{ + if (gate_result == 0) { + gate_held++; + } + return gate_result; +} + +extern "C" void radio_entropy_changing(bool starting) +{ + (void)starting; + changes++; +} + +extern "C" void radio_entropy_changed(bool radio_on) +{ + (void)radio_on; +} + +extern "C" void radio_entropy_change_end(void) +{ + gate_held--; +} + // Each case starts with the radio off and the stub counting from zero static void reset(void) { start_result = stop_result = 0; + gate_result = 0; radio_stop(); - starts = stops = 0; + starts = stops = changes = chip_in_gate = 0; chip_on = 0; } @@ -137,3 +173,46 @@ TEST(Radio, boot_decisions) rec = on; radio_record_set(&rec, false); CHECK(radio_boot_decision(true, &rec) == RADIO_BOOT_OFF, "rewritten from on to off"); } + +// A GET_RANDOM draw that overlaps a stop is refused: the radio no longer counts as on once the +// stop begins, and the epoch has moved, also when the stop fails +TEST(Radio, a_stop_moves_the_epoch_first) +{ + reset(); + radio_start(); + uint32_t e = radio_epoch(); + on_during_stop = 1; + radio_stop(); + CHECK(!on_during_stop, "off while stopping"); + CHECK(radio_epoch() == e + 1, "one stop, one step"); + radio_start(); + CHECK(radio_epoch() == e + 1, "a start does not move it"); + stop_result = ESP_FAIL_CODE; + radio_stop(); + CHECK(radio_epoch() == e + 2, "a failed stop moves it too"); + radio_stop(); + CHECK(radio_epoch() == e + 3, "and so does its retry"); + stop_result = 0; + radio_stop(); + radio_stop(); + CHECK(radio_epoch() == e + 4, "a stop while off does not"); +} + +// A gate that is not free in time changes nothing; every chip call is made inside it +TEST(Radio, busy_gate_changes_nothing) +{ + reset(); + gate_result = 0x107; + CHECK(radio_start() == 0x107, "the gate's error is passed on"); + CHECK(!radio_is_on() && (starts == 0) && (changes == 0), "nothing touched"); + gate_result = 0; + radio_start(); + gate_result = 0x107; + uint32_t e = radio_epoch(); + CHECK(radio_stop() == 0x107, "on a stop too"); + CHECK(radio_is_on() && (stops == 0) && (radio_epoch() == e), "still on, epoch kept"); + gate_result = 0; + radio_stop(); + CHECK((chip_in_gate == starts + stops) && (gate_held == 0), "chip calls inside the gate, gate released"); + CHECK(changes == 2, "the source told of each change"); +} diff --git a/software/wifi/tls/rpc_tls.h b/software/wifi/tls/rpc_tls.h new file mode 100644 index 000000000..ec7ae3040 --- /dev/null +++ b/software/wifi/tls/rpc_tls.h @@ -0,0 +1,276 @@ +/* rpc_tls.h: the wire contract of the CMD_TLS_* commands: their opcodes and the layout of their requests and answers. + * One definition for every module firmware that runs the TLS engine (software/wifi/tls) and for the Ultimate side + * that decodes them. Include rpc_calls.h, which includes this after the types it builds on. */ + +#ifndef RPC_TLS_H_ +#define RPC_TLS_H_ + +#include +#include +#include "rpc_calls.h" + +// TLS sessions, named by (slot, tag): the ESP32 runs the engine, the Ultimate moves the ciphertext. Fixed fields first, +// variable data last; the asserts at the end of this file and wifi_tls.cc check these layouts at fixed offsets. +#define TLS_MAX_SESSIONS 2 +#define TLS_SNI_MAX_LEN 253 // longest DNS name +#define TLS_STEP_IN_MAX 1536 // ct_in_len + pt_in_len per step +#define TLS_STEP_OUT_MAX 1024 // ct_out_len + pt_out_len per step +#define TLS_SLOT_GLOBAL 0xFF // CMD_TLS_STATS without a session (tag 0) +#define TLS_PIN_LEN 32 // SHA-256 of the server's SubjectPublicKeyInfo, digest order +#define TLS_CA_MAX_LEN 1472 // one DER certificate for trust mode CUSTOM +#define TLS_ALERT_NONE 0xFF + +typedef enum { + TLS_TRUST_BUNDLE = 0, // the ESP-IDF certificate bundle + TLS_TRUST_CUSTOM = 1, // the one CA loaded with CMD_TLS_SET_CA, matched by ca_tag + TLS_TRUST_PIN = 2, // the leaf key's SHA-256 only +} tls_trust_t; + +#define TLS_OPT_REQUIRE_TLS13 0x01 // rpc_tls_open_req.opts: offer TLS 1.3 only +#define TLS_STEP_NO_READ 0x01 // rpc_tls_step_req.flags: no plaintext out of this step + +// rpc_tls_open_resp.reason, telling the ESP_ERR_INVALID_STATE refusals apart +#define TLS_OPEN_REASON_NONE 0 +#define TLS_OPEN_REASON_NO_ENTROPY 1 // no entropy source is on (radio off and no ADC source): no RNG seed +#define TLS_OPEN_REASON_NO_TIME 2 // BUNDLE or CUSTOM, but no trustworthy clock +#define TLS_OPEN_REASON_NO_CUSTOM_CA 3 // CUSTOM, but no CA held under the request's ca_tag + +typedef enum { + TLS_TIME_NONE = 0, // clock not later than the build date + TLS_TIME_NIOS = 1, // set from unix_time in a CMD_TLS_OPEN (the Ultimate's SNTP time) + TLS_TIME_SNTP = 2, // already valid without the Ultimate: SNTP over the ESP32's own Wi-Fi (STATS only) +} tls_time_source_t; + +typedef enum { + TLS_STATE_HANDSHAKING = 0, + TLS_STATE_ESTABLISHED = 1, + TLS_STATE_CLOSED = 2, + TLS_STATE_FAILED = 3, // esp_err holds the mbedTLS error code, fail_reason says more +} tls_state_t; + +// rpc_tls_step_resp.fail_reason, set with FAILED +typedef enum { + TLS_FAIL_NONE = 0, // generic: esp_err has the mbedTLS code (alert_in the alert, if any) + TLS_FAIL_VERSION_REFUSED = 1, // the ServerHello chose a version not offered, or a TLS 1.2 ServerHello carried 0x0304; it is in verify_flags' low 16 bits + TLS_FAIL_DOWNGRADE = 2, // TLS 1.2 chosen by a ServerHello carrying the RFC 8446 downgrade sentinel + TLS_FAIL_NO_EMS = 3, // a TLS 1.2 server without the extended master secret + TLS_FAIL_CERT_VERIFY = 4, // verify_flags = mbedtls_ssl_get_verify_result(), 0xFFFFFFFF if it never completed + TLS_FAIL_PIN_MISMATCH = 5, // PIN: the leaf key is not the pinned one + TLS_FAIL_PEER_CLOSED = 6, // close_notify during the handshake + TLS_FAIL_NO_ENTROPY = 7, // a draw found no entropy source (radio stopped or voltages read mid-handshake) +} tls_fail_reason_t; + +// rpc_tls_set_ca_resp.reject, with ESP_ERR_INVALID_ARG +#define TLS_CA_REJECT_NONE 0 +#define TLS_CA_REJECT_RSA_KEY_SHORT 1 // RSA key below 2048 bits +#define TLS_CA_REJECT_RESERVED 2 // never sent +#define TLS_CA_REJECT_CURVE 3 // EC key on a curve the X.509 profile does not accept +#define TLS_CA_REJECT_NOT_CA 4 // v3 without basicConstraints cA, or a keyUsage without keyCertSign + +typedef struct { + rpc_header_t hdr; + uint8_t trust; // tls_trust_t + uint8_t sni_len; // 0..TLS_SNI_MAX_LEN, no terminator; 0 = no name (PIN only) + uint8_t slot; // 0..TLS_MAX_SESSIONS-1, chosen by the Ultimate + uint8_t time_source; // TLS_TIME_NONE, or TLS_TIME_NIOS when unix_time is the Ultimate's SNTP time + uint32_t unix_time; // UTC seconds + uint16_t tag; // names the session with slot; never 0 + uint8_t opts; // TLS_OPT_* + uint8_t reserved; + uint16_t ca_tag; // CUSTOM: the Ultimate's current ca_tag; 0 otherwise + uint16_t reserved2; + uint8_t pin[TLS_PIN_LEN]; // read only when trust is PIN + char sni[]; +} rpc_tls_open_req; + +typedef struct { + rpc_header_t hdr; + int esp_err; // ESP_OK, an esp_err_t, or a negative mbedTLS code + uint8_t slot; // TLS_SLOT_GLOBAL when esp_err != ESP_OK + uint8_t reason; // TLS_OPEN_REASON_* + uint16_t reserved; // 0 +} rpc_tls_open_resp; + +typedef struct { + rpc_header_t hdr; + uint8_t slot; + uint8_t flags; // TLS_STEP_NO_READ + uint16_t tag; + uint16_t ct_in_len; + uint16_t pt_in_len; + uint8_t data[]; // ct_in, then pt_in +} rpc_tls_step_req; + +typedef struct { + rpc_header_t hdr; + int esp_err; + uint8_t state; // tls_state_t + uint8_t alert_in; // fatal alert received, TLS_ALERT_NONE if none + uint16_t ct_out_len; + uint16_t pt_out_len; + uint8_t alert_out; // alert this engine sent unencrypted, TLS_ALERT_NONE if none (or encrypted) + uint8_t fail_reason; // tls_fail_reason_t, with FAILED + uint32_t verify_flags; // see tls_fail_reason_t + uint8_t data[]; // ct_out, then pt_out +} rpc_tls_step_resp; + +typedef struct { + rpc_header_t hdr; + uint8_t slot; + uint8_t reserved; + uint16_t tag; +} rpc_tls_session_req; // CMD_TLS_CLOSE and CMD_TLS_STATS + +typedef struct { + rpc_header_t hdr; + int esp_err; + uint16_t ct_out_len; + uint16_t reserved; + uint8_t data[]; // the close_notify record +} rpc_tls_close_resp; + +typedef struct { + rpc_header_t hdr; + int esp_err; + uint32_t heap_free; // internal 8-bit capable heap + uint32_t heap_min; // low-water mark since the OPEN that found no session open + uint32_t largest_block; + uint32_t ct_in_bytes; // session counters, 0 for TLS_SLOT_GLOBAL + uint32_t ct_out_bytes; + uint32_t pt_in_bytes; + uint32_t pt_out_bytes; + uint32_t handshake_us; // ESP32 time spent in handshake steps + uint16_t tls_version; // 0x0304 for TLS 1.3 + uint16_t ciphersuite; // IANA id + uint16_t group; // IANA NamedGroup, never 0 once ESTABLISHED + uint8_t state; // tls_state_t + uint8_t sessions_open; + uint32_t stack_free; // TLS task stack high-water mark, bytes + uint32_t esp_time; // ESP32 clock at the session's OPEN (now, for TLS_SLOT_GLOBAL), 0 = no time + uint8_t time_source; // tls_time_source_t of that clock + uint8_t entropy_source; // entropy_source_t, now + uint8_t ems; // 1: TLS 1.2 with the extended master secret + uint8_t reserved; + uint16_t block_max_ms; // longest dispatcher iteration since boot + uint16_t reserved2; + uint8_t spki_sha256[32]; // SHA-256 of the leaf's SubjectPublicKeyInfo, digest order +} rpc_tls_stats_resp; + +typedef struct { + rpc_header_t hdr; + uint16_t der_len; // 1..TLS_CA_MAX_LEN + uint16_t ca_tag; // never 0 + uint8_t der[]; +} rpc_tls_set_ca_req; + +typedef struct { + rpc_header_t hdr; + int esp_err; // ESP_OK, a negative mbedTLS parse code, or ESP_ERR_INVALID_ARG with a reject reason + uint8_t reject; // TLS_CA_REJECT_* + uint8_t reserved[3]; +} rpc_tls_set_ca_resp; + +#define CMD_TLS_OPEN 0x30 +#define CMD_TLS_STEP 0x31 +#define CMD_TLS_CLOSE 0x32 +#define CMD_TLS_STATS 0x33 +#define CMD_TLS_CLOSE_ALL 0x34 +#define CMD_TLS_SET_CA 0x35 + +// TLS. The layout is part of the wire, the header is echoed, and the fixed part of every reply is zeroed +// before it is filled. The Ultimate decodes these by offset and asserts the same ones (wifi_tls.cc): a layout +// change must break the build, not the wire. The asserts here are C only: GCC's C++ front end has no +// _Static_assert, and glibc, unlike newlib, does not supply a macro for it. +#ifndef __cplusplus +_Static_assert(sizeof(rpc_tls_open_req) == 52, "rpc_tls_open_req size"); +_Static_assert(offsetof(rpc_tls_open_req, trust) == 4, "rpc_tls_open_req.trust"); +_Static_assert(offsetof(rpc_tls_open_req, sni_len) == 5, "rpc_tls_open_req.sni_len"); +_Static_assert(offsetof(rpc_tls_open_req, slot) == 6, "rpc_tls_open_req.slot"); +_Static_assert(offsetof(rpc_tls_open_req, time_source) == 7, "rpc_tls_open_req.time_source"); +_Static_assert(offsetof(rpc_tls_open_req, unix_time) == 8, "rpc_tls_open_req.unix_time"); +_Static_assert(offsetof(rpc_tls_open_req, tag) == 12, "rpc_tls_open_req.tag"); +_Static_assert(offsetof(rpc_tls_open_req, opts) == 14, "rpc_tls_open_req.opts"); +_Static_assert(offsetof(rpc_tls_open_req, reserved) == 15, "rpc_tls_open_req.reserved"); +_Static_assert(offsetof(rpc_tls_open_req, ca_tag) == 16, "rpc_tls_open_req.ca_tag"); +_Static_assert(offsetof(rpc_tls_open_req, reserved2) == 18, "rpc_tls_open_req.reserved2"); +_Static_assert(offsetof(rpc_tls_open_req, pin) == 20, "rpc_tls_open_req.pin"); +_Static_assert(offsetof(rpc_tls_open_req, sni) == 52, "rpc_tls_open_req.sni"); +_Static_assert(sizeof(rpc_tls_open_resp) == 12, "rpc_tls_open_resp size"); +_Static_assert(offsetof(rpc_tls_open_resp, esp_err) == 4, "rpc_tls_open_resp.esp_err"); +_Static_assert(offsetof(rpc_tls_open_resp, slot) == 8, "rpc_tls_open_resp.slot"); +_Static_assert(offsetof(rpc_tls_open_resp, reason) == 9, "rpc_tls_open_resp.reason"); +_Static_assert(offsetof(rpc_tls_open_resp, reserved) == 10, "rpc_tls_open_resp.reserved"); +_Static_assert(sizeof(rpc_tls_step_req) == 12, "rpc_tls_step_req size"); +_Static_assert(offsetof(rpc_tls_step_req, slot) == 4, "rpc_tls_step_req.slot"); +_Static_assert(offsetof(rpc_tls_step_req, flags) == 5, "rpc_tls_step_req.flags"); +_Static_assert(offsetof(rpc_tls_step_req, tag) == 6, "rpc_tls_step_req.tag"); +_Static_assert(offsetof(rpc_tls_step_req, ct_in_len) == 8, "rpc_tls_step_req.ct_in_len"); +_Static_assert(offsetof(rpc_tls_step_req, pt_in_len) == 10, "rpc_tls_step_req.pt_in_len"); +_Static_assert(offsetof(rpc_tls_step_req, data) == 12, "rpc_tls_step_req.data"); +_Static_assert(sizeof(rpc_tls_step_resp) == 20, "rpc_tls_step_resp size"); +_Static_assert(offsetof(rpc_tls_step_resp, esp_err) == 4, "rpc_tls_step_resp.esp_err"); +_Static_assert(offsetof(rpc_tls_step_resp, state) == 8, "rpc_tls_step_resp.state"); +_Static_assert(offsetof(rpc_tls_step_resp, alert_in) == 9, "rpc_tls_step_resp.alert_in"); +_Static_assert(offsetof(rpc_tls_step_resp, ct_out_len) == 10, "rpc_tls_step_resp.ct_out_len"); +_Static_assert(offsetof(rpc_tls_step_resp, pt_out_len) == 12, "rpc_tls_step_resp.pt_out_len"); +_Static_assert(offsetof(rpc_tls_step_resp, alert_out) == 14, "rpc_tls_step_resp.alert_out"); +_Static_assert(offsetof(rpc_tls_step_resp, fail_reason) == 15, "rpc_tls_step_resp.fail_reason"); +_Static_assert(offsetof(rpc_tls_step_resp, verify_flags) == 16, "rpc_tls_step_resp.verify_flags"); +_Static_assert(offsetof(rpc_tls_step_resp, data) == 20, "rpc_tls_step_resp.data"); +_Static_assert(sizeof(rpc_tls_session_req) == 8, "rpc_tls_session_req size"); +_Static_assert(offsetof(rpc_tls_session_req, slot) == 4, "rpc_tls_session_req.slot"); +_Static_assert(offsetof(rpc_tls_session_req, reserved) == 5, "rpc_tls_session_req.reserved"); +_Static_assert(offsetof(rpc_tls_session_req, tag) == 6, "rpc_tls_session_req.tag"); +_Static_assert(sizeof(rpc_tls_close_resp) == 12, "rpc_tls_close_resp size"); +_Static_assert(offsetof(rpc_tls_close_resp, esp_err) == 4, "rpc_tls_close_resp.esp_err"); +_Static_assert(offsetof(rpc_tls_close_resp, ct_out_len) == 8, "rpc_tls_close_resp.ct_out_len"); +_Static_assert(offsetof(rpc_tls_close_resp, reserved) == 10, "rpc_tls_close_resp.reserved"); +_Static_assert(offsetof(rpc_tls_close_resp, data) == 12, "rpc_tls_close_resp.data"); +_Static_assert(sizeof(rpc_espcmd_resp) == 8, "rpc_espcmd_resp size"); +_Static_assert(offsetof(rpc_espcmd_resp, esp_err) == 4, "rpc_espcmd_resp.esp_err"); +_Static_assert(sizeof(rpc_tls_stats_resp) == 96, "rpc_tls_stats_resp size"); +_Static_assert(offsetof(rpc_tls_stats_resp, esp_err) == 4, "rpc_tls_stats_resp.esp_err"); +_Static_assert(offsetof(rpc_tls_stats_resp, heap_free) == 8, "rpc_tls_stats_resp.heap_free"); +_Static_assert(offsetof(rpc_tls_stats_resp, heap_min) == 12, "rpc_tls_stats_resp.heap_min"); +_Static_assert(offsetof(rpc_tls_stats_resp, largest_block) == 16, "rpc_tls_stats_resp.largest_block"); +_Static_assert(offsetof(rpc_tls_stats_resp, ct_in_bytes) == 20, "rpc_tls_stats_resp.ct_in_bytes"); +_Static_assert(offsetof(rpc_tls_stats_resp, ct_out_bytes) == 24, "rpc_tls_stats_resp.ct_out_bytes"); +_Static_assert(offsetof(rpc_tls_stats_resp, pt_in_bytes) == 28, "rpc_tls_stats_resp.pt_in_bytes"); +_Static_assert(offsetof(rpc_tls_stats_resp, pt_out_bytes) == 32, "rpc_tls_stats_resp.pt_out_bytes"); +_Static_assert(offsetof(rpc_tls_stats_resp, handshake_us) == 36, "rpc_tls_stats_resp.handshake_us"); +_Static_assert(offsetof(rpc_tls_stats_resp, tls_version) == 40, "rpc_tls_stats_resp.tls_version"); +_Static_assert(offsetof(rpc_tls_stats_resp, ciphersuite) == 42, "rpc_tls_stats_resp.ciphersuite"); +_Static_assert(offsetof(rpc_tls_stats_resp, group) == 44, "rpc_tls_stats_resp.group"); +_Static_assert(offsetof(rpc_tls_stats_resp, state) == 46, "rpc_tls_stats_resp.state"); +_Static_assert(offsetof(rpc_tls_stats_resp, sessions_open) == 47, "rpc_tls_stats_resp.sessions_open"); +_Static_assert(offsetof(rpc_tls_stats_resp, stack_free) == 48, "rpc_tls_stats_resp.stack_free"); +_Static_assert(offsetof(rpc_tls_stats_resp, esp_time) == 52, "rpc_tls_stats_resp.esp_time"); +_Static_assert(offsetof(rpc_tls_stats_resp, time_source) == 56, "rpc_tls_stats_resp.time_source"); +_Static_assert(offsetof(rpc_tls_stats_resp, entropy_source) == 57, "rpc_tls_stats_resp.entropy_source"); +_Static_assert(offsetof(rpc_tls_stats_resp, ems) == 58, "rpc_tls_stats_resp.ems"); +_Static_assert(offsetof(rpc_tls_stats_resp, reserved) == 59, "rpc_tls_stats_resp.reserved"); +_Static_assert(offsetof(rpc_tls_stats_resp, block_max_ms) == 60, "rpc_tls_stats_resp.block_max_ms"); +_Static_assert(offsetof(rpc_tls_stats_resp, reserved2) == 62, "rpc_tls_stats_resp.reserved2"); +_Static_assert(offsetof(rpc_tls_stats_resp, spki_sha256) == 64, "rpc_tls_stats_resp.spki_sha256"); +_Static_assert(sizeof(rpc_tls_set_ca_req) == 8, "rpc_tls_set_ca_req size"); +_Static_assert(offsetof(rpc_tls_set_ca_req, der_len) == 4, "rpc_tls_set_ca_req.der_len"); +_Static_assert(offsetof(rpc_tls_set_ca_req, ca_tag) == 6, "rpc_tls_set_ca_req.ca_tag"); +_Static_assert(offsetof(rpc_tls_set_ca_req, der) == 8, "rpc_tls_set_ca_req.der"); +_Static_assert(sizeof(rpc_tls_set_ca_resp) == 12, "rpc_tls_set_ca_resp size"); +_Static_assert(offsetof(rpc_tls_set_ca_resp, esp_err) == 4, "rpc_tls_set_ca_resp.esp_err"); +_Static_assert(offsetof(rpc_tls_set_ca_resp, reject) == 8, "rpc_tls_set_ca_resp.reject"); +_Static_assert((TLS_TIME_NONE == 0) && (TLS_TIME_NIOS == 1) && (TLS_TIME_SNTP == 2), "tls_time_source_t"); +_Static_assert((TLS_STATE_HANDSHAKING == 0) && (TLS_STATE_ESTABLISHED == 1) && + (TLS_STATE_CLOSED == 2) && (TLS_STATE_FAILED == 3), "tls_state_t"); +_Static_assert((TLS_TRUST_BUNDLE == 0) && (TLS_TRUST_CUSTOM == 1) && (TLS_TRUST_PIN == 2), "tls_trust_t"); +_Static_assert((TLS_FAIL_VERSION_REFUSED == 1) && (TLS_FAIL_DOWNGRADE == 2) && (TLS_FAIL_NO_EMS == 3) && + (TLS_FAIL_CERT_VERIFY == 4) && (TLS_FAIL_PIN_MISMATCH == 5) && (TLS_FAIL_PEER_CLOSED == 6) && + (TLS_FAIL_NO_ENTROPY == 7), "tls_fail_reason_t"); +_Static_assert((TLS_OPEN_REASON_NO_ENTROPY == 1) && (TLS_OPEN_REASON_NO_TIME == 2) && (TLS_OPEN_REASON_NO_CUSTOM_CA == 3), + "rpc_tls_open_resp.reason"); +_Static_assert((TLS_CA_REJECT_RSA_KEY_SHORT == 1) && (TLS_CA_REJECT_CURVE == 3) && (TLS_CA_REJECT_NOT_CA == 4), + "rpc_tls_set_ca_resp.reject"); +_Static_assert(TLS_SNI_MAX_LEN <= 255, "sni_len is a byte"); +#endif /* __cplusplus */ + +#endif /* RPC_TLS_H_ */ diff --git a/software/wifi/tls/tls_engine.c b/software/wifi/tls/tls_engine.c new file mode 100644 index 000000000..1a544dea5 --- /dev/null +++ b/software/wifi/tls/tls_engine.c @@ -0,0 +1,889 @@ +/* tls_engine.c: TLS sessions on the UCI network target. mbedTLS runs a TLS 1.3 client with a hardened TLS 1.2 fallback; + * the Ultimate pumps the ciphertext between its TCP socket and CMD_TLS_STEP. The bio callbacks never block (per-session + * input and output buffers). Everything here runs on the TLS task only. */ + +// Reads a few private mbedtls_ssl_context fields that have no getter (handshake state and version, the message just +// processed). It includes nothing from mbedTLS's library/ (ssl_misc.h): a fork with another +// mbedtls_ssl_handshake_params layout would otherwise be read at the wrong offsets. +#define MBEDTLS_ALLOW_PRIVATE_ACCESS +#include +#include +#include +#include +#include "sdkconfig.h" +#include "freertos/FreeRTOS.h" +#include "esp_err.h" +#include "esp_log.h" +#include "esp_timer.h" +#include "esp_heap_caps.h" +#include "mbedtls/ssl.h" +#include "mbedtls/x509_crt.h" +#include "psa/crypto.h" +#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE +#include "esp_crt_bundle.h" +#endif +#include "cmd_buffer.h" +#include "wifi_modem.h" +#include "tls_rng_gate.h" +#include "sntp.h" +#include "tls_engine.h" + +#if !CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 || !CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 +#error "The engine offers TLS 1.3 with a TLS 1.2 fallback: enable CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 and _TLS1_2" +#endif +#if MBEDTLS_VERSION_MAJOR < 4 +#error "This engine is written for mbedTLS 4 (ESP-IDF 6): randomness and allocation failures come from PSA" +#endif +#if !CONFIG_MBEDTLS_HAVE_TIME_DATE +#error "Without CONFIG_MBEDTLS_HAVE_TIME_DATE certificate dates are ignored: an expired certificate would verify" +#endif +#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE && !CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_CROSS_SIGNED_VERIFY +#error "The bundle needs CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_CROSS_SIGNED_VERIFY: without it most servers' cross-signed chains fail" +#endif +#if !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) +#error "TLS 1.2 needs the extended master secret, which this mbedTLS configuration leaves out" +#endif +#if defined(MBEDTLS_SSL_RENEGOTIATION) +#error "Renegotiation must stay off (CONFIG_MBEDTLS_SSL_RENEGOTIATION)" +#endif + +#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE +// esp_crt_bundle.c's verify callback: external linkage but not in its header (as IDF's own unit test declares it) +int esp_crt_verify_callback(void *buf, mbedtls_x509_crt *crt, int depth, uint32_t *flags); +#endif + +#ifndef TLS_IN_BUF_SIZE // a host test shrinks it to reach a full input buffer while handshaking +#define TLS_IN_BUF_SIZE (2 * TLS_STEP_IN_MAX) // unread ciphertext from the Ultimate +#endif +#define TLS_OUT_BUF_SIZE 2048 // ciphertext not yet collected by a step +// Step room kept free of plaintext for an alert that a failing read writes: header 5 + tag 16 + +// alert padded to at most 32 (CONFIG_MBEDTLS_SSL_CID_PADDING_GRANULARITY range 0..32) = 53 +#define TLS_ALERT_ROOM 64 +// NewSessionTickets one mbedtls_ssl_write() may run into; each is taken on its own, so this only bounds a loop +#define TLS_TICKET_RETRIES 4 + +_Static_assert(TLS_OUT_BUF_SIZE > TLS_STEP_IN_MAX, "one step of plaintext must fit the output buffer"); + +// The CUSTOM CA. A session holds its own reference, so replacing or clearing the CA never frees it under a +// session that is still verifying with it. +typedef struct { + mbedtls_x509_crt crt; + uint16_t tag; + int refs; +} tls_ca_t; + +typedef struct { + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + tls_ca_t *ca; // CUSTOM + uint16_t tag; + uint8_t trust; + uint8_t opts; + uint8_t pin[TLS_PIN_LEN]; + uint8_t pin_mismatch; + uint8_t bundle_rejected; + uint8_t ems_checked; + tls_session_stats_t stats; + int in_off; + int in_len; + int out_len; + uint8_t in_buf[TLS_IN_BUF_SIZE]; + uint8_t out_buf[TLS_OUT_BUF_SIZE]; +} tls_session_t; + +static const char *TAG = "tls"; +static tls_session_t *sessions[TLS_MAX_SESSIONS]; +static tls_ca_t *custom_ca; +// PIN: mbedTLS verifies only with a CA chain configured (and a TLS 1.3 client needs one), so an empty one. +// Zeroed is the state mbedtls_x509_crt_init() leaves; verification only reads it. +static mbedtls_x509_crt tls_empty_ca; +static int psa_ready; +static int clock_set_by_nios; + +// The six hardened TLS 1.2 suites and the three TLS 1.3 ones, in mbedTLS's own order of preference +static const int tls_ciphersuites[] = { + MBEDTLS_TLS1_3_CHACHA20_POLY1305_SHA256, + MBEDTLS_TLS1_3_AES_256_GCM_SHA384, + MBEDTLS_TLS1_3_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, + MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + 0 +}; + +// Key-exchange groups for both versions: mbedTLS 4's default list adds x448 and FFDHE +// 2048-8192 (an 8192-bit modexp on the ESP32). mbedTLS keeps the pointer, so static. +static const uint16_t tls_groups[] = { + MBEDTLS_SSL_IANA_TLS_GROUP_X25519, MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1, + MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1, MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1, + MBEDTLS_SSL_IANA_TLS_GROUP_NONE +}; + +static int tls_bio_send(void *ctx, const unsigned char *buf, size_t len) +{ + tls_session_t *s = (tls_session_t *)ctx; + size_t room = TLS_OUT_BUF_SIZE - s->out_len; + if (room == 0) { + return MBEDTLS_ERR_SSL_WANT_WRITE; + } + if (len > room) { + len = room; + } + memcpy(s->out_buf + s->out_len, buf, len); + s->out_len += len; + return (int)len; +} + +static int tls_bio_recv(void *ctx, unsigned char *buf, size_t len) +{ + tls_session_t *s = (tls_session_t *)ctx; + size_t avail = s->in_len - s->in_off; + if (avail == 0) { + return MBEDTLS_ERR_SSL_WANT_READ; + } + if (len > avail) { + len = avail; + } + memcpy(buf, s->in_buf + s->in_off, len); + s->in_off += len; + return (int)len; +} + +// Every session's verify callback, set on the ssl context (mbedtls_ssl_set_verify) so it overrides the config's and +// esp_crt_bundle_attach() cannot replace it. It returns 0 so the verify result stays decodable; a rejection still +// fails the handshake because it leaves flags set. +static int tls_verify(void *ctx, mbedtls_x509_crt *crt, int depth, uint32_t *flags) +{ + tls_session_t *s = (tls_session_t *)ctx; + int hashed = 0; + if (depth == 0) { + size_t n = 0; + hashed = psa_hash_compute(PSA_ALG_SHA_256, crt->pk_raw.p, crt->pk_raw.len, s->stats.spki_sha256, + sizeof(s->stats.spki_sha256), &n) == PSA_SUCCESS; + if (!hashed) { + memset(s->stats.spki_sha256, 0, sizeof(s->stats.spki_sha256)); + } + } + switch (s->trust) { +#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE + case TLS_TRUST_BUNDLE: + if (esp_crt_verify_callback(NULL, crt, depth, flags) != 0) { + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + s->bundle_rejected = 1; + } + break; +#endif + case TLS_TRUST_PIN: + // The key is the identity: chain, dates and name are not checked. The mode comes from trust alone. + *flags = 0; + if ((depth == 0) && (!hashed || memcmp(s->stats.spki_sha256, s->pin, TLS_PIN_LEN) != 0)) { + s->pin_mismatch = 1; + *flags = MBEDTLS_X509_BADCERT_NOT_TRUSTED; + } + break; + default: // CUSTOM: mbedTLS's own chain verification against the uploaded CA + break; + } + return 0; +} + +// 00:00 UTC on the day this file was compiled: a clock before it cannot be right +static time_t tls_build_time(void) +{ + static const char months[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; + const char *date = __DATE__; // "Mmm dd yyyy" + int m = 1; + while ((m < 12) && strncmp(months + 3 * (m - 1), date, 3)) { + m++; + } + int d = atoi(date + 4); + int y = atoi(date + 7) - (m <= 2); + // Days since 1970-01-01 in the proleptic Gregorian calendar (days_from_civil) + int era = y / 400; + int yoe = y - era * 400; + int doy = (153 * (m + ((m > 2) ? -3 : 9)) + 2) / 5 + d - 1; + int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return (time_t)(era * 146097 + doe - 719468) * 86400; +} + +// The clock an OPEN may use. SNTP wins: the Ultimate's time is only taken when the ESP32 has no SNTP time, +// and only when the Ultimate says it is SNTP time too (time_source). Reports the source used for this OPEN; +// a clock an earlier OPEN set does not count. +static uint8_t tls_set_clock(uint8_t time_source, uint32_t unix_time) +{ + time_t floor = tls_build_time(); + if (sntp_has_time() && (time(NULL) > floor)) { + return TLS_TIME_SNTP; + } + if ((time_source == TLS_TIME_NIOS) && ((time_t)unix_time > floor)) { + struct timeval tv = { .tv_sec = (time_t)unix_time, .tv_usec = 0 }; + if (settimeofday(&tv, NULL) == 0) { + clock_set_by_nios = 1; + return TLS_TIME_NIOS; + } + } + return TLS_TIME_NONE; +} + +// ESP-IDF 6 initialises PSA at startup, so this is a no-op there; it stays for builds that do not. Neither +// the init nor a certificate parse draws random bytes. +static int tls_psa_ready(void) +{ + if (!psa_ready) { + psa_status_t status = psa_crypto_init(); + if (status != PSA_SUCCESS) { + ESP_LOGE(TAG, "psa_crypto_init: %d", (int)status); + return 0; + } + psa_ready = 1; + } + return 1; +} + +static tls_session_t *tls_find(uint8_t slot, uint16_t tag) +{ + if (slot >= TLS_MAX_SESSIONS) { + return NULL; + } + tls_session_t *s = sessions[slot]; + return (s && (s->tag == tag)) ? s : NULL; +} + +static void tls_ca_release(tls_ca_t *ca) +{ + if (ca && (--ca->refs == 0)) { + mbedtls_x509_crt_free(&ca->crt); + free(ca); + } +} + +static void tls_free(tls_session_t *s) +{ + for (int i = 0; i < TLS_MAX_SESSIONS; i++) { + if (sessions[i] == s) { + sessions[i] = NULL; + } + } + mbedtls_ssl_free(&s->ssl); + mbedtls_ssl_config_free(&s->conf); + tls_ca_release(s->ca); + // The certificate bundle is shared: esp_crt_bundle_detach() would free it under the other session + free(s); +} + +int tls_sessions_open(void) +{ + int n = 0; + for (int i = 0; i < TLS_MAX_SESSIONS; i++) { + if (sessions[i]) { + n++; + } + } + return n; +} + +// Builds a complete session without putting it in the table; frees it on failure +static int tls_setup(tls_session_t **out, uint16_t tag, const tls_open_params_t *p, const char *hostname, + uint8_t time_source) +{ + *out = NULL; + tls_session_t *s = calloc(1, sizeof(tls_session_t)); + if (!s) { + return ESP_ERR_NO_MEM; + } + s->tag = tag; + s->trust = p->trust; + s->opts = p->opts; + if (p->trust == TLS_TRUST_PIN) { + memcpy(s->pin, p->pin, TLS_PIN_LEN); + } + s->stats.state = TLS_STATE_HANDSHAKING; + s->stats.time_source = time_source; + s->stats.esp_time = (time_source == TLS_TIME_NONE) ? 0 : (uint32_t)time(NULL); + mbedtls_ssl_init(&s->ssl); + mbedtls_ssl_config_init(&s->conf); + + // Every random byte (client random, key shares) comes from PSA: see tls_open() + int ret = mbedtls_ssl_config_defaults(&s->conf, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); + if (ret == 0) { + // TLS 1.3, and the hardened TLS 1.2 unless the program requires 1.3 + mbedtls_ssl_conf_min_tls_version(&s->conf, (p->opts & TLS_OPT_REQUIRE_TLS13) ? MBEDTLS_SSL_VERSION_TLS1_3 + : MBEDTLS_SSL_VERSION_TLS1_2); + mbedtls_ssl_conf_max_tls_version(&s->conf, MBEDTLS_SSL_VERSION_TLS1_3); + // The CBC suites are compiled in (wpa_supplicant needs AES-CBC): only this list keeps them out + mbedtls_ssl_conf_ciphersuites(&s->conf, tls_ciphersuites); + mbedtls_ssl_conf_groups(&s->conf, tls_groups); + // Offered here, and required after the ServerHello (tls_note_handshake): mbedTLS has no switch for that + mbedtls_ssl_conf_extended_master_secret(&s->conf, MBEDTLS_SSL_EXTENDED_MS_ENABLED); + // No session_ticket extension in TLS 1.2 (TLS 1.3 tickets are taken and dropped as before) + mbedtls_ssl_conf_session_tickets(&s->conf, MBEDTLS_SSL_SESSION_TICKETS_DISABLED); + mbedtls_ssl_conf_authmode(&s->conf, MBEDTLS_SSL_VERIFY_REQUIRED); + // One config per session: a CUSTOM or PIN config never has the bundle attached, since a config with the + // bundle's CA callback makes mbedTLS ignore conf->ca_chain + if (p->trust == TLS_TRUST_CUSTOM) { + s->ca = custom_ca; + s->ca->refs++; + mbedtls_ssl_conf_ca_chain(&s->conf, &s->ca->crt, NULL); + } else if (p->trust == TLS_TRUST_PIN) { + mbedtls_ssl_conf_ca_chain(&s->conf, &tls_empty_ca, NULL); + } +#if CONFIG_MBEDTLS_CERTIFICATE_BUNDLE + if (p->trust == TLS_TRUST_BUNDLE) { + ret = esp_crt_bundle_attach(&s->conf); + } +#endif + } + if (ret == 0) { + ret = mbedtls_ssl_setup(&s->ssl, &s->conf); + } + if (ret == 0) { + // No name: mbedTLS 4 refuses to verify unless set_hostname was called, so NULL explicitly (no SNI) + ret = mbedtls_ssl_set_hostname(&s->ssl, p->sni_len ? hostname : NULL); + } + if (ret != 0) { + ESP_LOGW(TAG, "Open failed: -0x%04x", (unsigned)-ret); + tls_free(s); + return ret; + } + mbedtls_ssl_set_verify(&s->ssl, tls_verify, s); + mbedtls_ssl_set_bio(&s->ssl, s, tls_bio_send, tls_bio_recv, NULL); + *out = s; + return 0; +} + +int tls_open(uint8_t slot, uint16_t tag, const tls_open_params_t *p, uint8_t *reason) +{ + char hostname[TLS_SNI_MAX_LEN + 1]; + + tls_rng_gate_bind_task(); // from here on, this task's random draws hold the entropy gate (tls_rng_gate.h) + *reason = TLS_OPEN_REASON_NONE; + // Verifying without a host name would skip the name check, so only PIN may go without one + if ((slot >= TLS_MAX_SESSIONS) || (tag == 0) || (p->trust > TLS_TRUST_PIN) || + (p->opts & ~TLS_OPT_REQUIRE_TLS13) || (p->time_source > TLS_TIME_NIOS) || + (p->sni_len < 0) || (p->sni_len > TLS_SNI_MAX_LEN) || (memchr(p->sni, 0, p->sni_len) != NULL) || + ((p->trust != TLS_TRUST_PIN) && (p->sni_len == 0))) { + return ESP_ERR_INVALID_ARG; + } + // The slot is the Ultimate's: whatever it still holds there is an orphan (its OPEN or CLOSE was lost) + if (sessions[slot]) { + ESP_LOGW(TAG, "OPEN into slot %d frees the session held there under tag %u", slot, sessions[slot]->tag); + tls_free(sessions[slot]); + } + if (entropy_source() == ENTROPY_NONE) { + *reason = TLS_OPEN_REASON_NO_ENTROPY; + return ESP_ERR_INVALID_STATE; + } + uint8_t time_source = tls_set_clock(p->time_source, p->unix_time); + if ((p->trust != TLS_TRUST_PIN) && (time_source == TLS_TIME_NONE)) { + // Never verify against a 1970 clock: every validity check would be meaningless + ESP_LOGW(TAG, "Open refused: BUNDLE and CUSTOM need a clock, and neither unix_time nor SNTP gave one"); + *reason = TLS_OPEN_REASON_NO_TIME; + return ESP_ERR_INVALID_STATE; + } + if ((p->trust == TLS_TRUST_CUSTOM) && !(custom_ca && (p->ca_tag != 0) && (custom_ca->tag == p->ca_tag))) { + *reason = TLS_OPEN_REASON_NO_CUSTOM_CA; + return ESP_ERR_INVALID_STATE; + } +#if !CONFIG_MBEDTLS_CERTIFICATE_BUNDLE + if (p->trust == TLS_TRUST_BUNDLE) { + return ESP_ERR_NOT_SUPPORTED; + } +#endif + // All randomness comes from PSA, which (MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) keeps no seeded state and draws every byte + // from esp_fill_random() when needed. The check above is at OPEN only: the radio may stop, or the voltages be read, + // before the handshake steps draw. Each draw therefore holds the entropy gate itself (tls_rng_gate.c); a draw with no + // source ends the handshake as TLS_FAIL_NO_ENTROPY (tls_classify). + // + // That covers every draw of this engine because its cipher list is AEAD only. In mbedTLS 4.1.1 (IDF 6.1.1's) + // the draws are the ClientHello random and session id (ssl_client.c), the ECDHE key share (ssl_tls12_client.c, + // ssl_tls13_generic.c), the blinding of the ECDH scalar multiplications (psa_crypto_ecp.c: the public key and the + // shared secret) and, for CBC suites only, the per-record IV (ssl_msg.c); AEAD nonces come from the record + // sequence number, so records, KeyUpdate and NewSessionTicket of an established session draw nothing. A CBC suite, + // DTLS (cookies) or server-side tickets would draw elsewhere: any of them needs the same treatment of its draws. + if (!tls_psa_ready()) { + return ESP_FAIL; + } + memcpy(hostname, p->sni, p->sni_len); + hostname[p->sni_len] = 0; + + if (tls_sessions_open() == 0) { + // heap_min then reports the peak of this burst of sessions, not of the Wi-Fi start + heap_caps_monitor_local_minimum_free_size_stop(); + heap_caps_monitor_local_minimum_free_size_start(); + } + tls_session_t *s = NULL; + int ret = tls_setup(&s, tag, p, hostname, time_source); + if (ret != 0) { + return ret; + } + sessions[slot] = s; + return ESP_OK; +} + +// The handshake message mbedTLS has just processed (ssl->in_msg, reassembled, header included), when it is +// of the given type and complete; NULL otherwise +static const uint8_t *tls_hs_msg(tls_session_t *s, uint8_t type, size_t *len) +{ + const uint8_t *m = s->ssl.in_msg; + size_t n = s->ssl.in_hslen; + if (!m || (s->ssl.in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) || (n < 4) || (m[0] != type) || + ((size_t)((m[1] << 16) | (m[2] << 8) | m[3]) != n - 4)) { + return NULL; + } + *len = n; + return m; +} + +// Finds an extension of a ServerHello (or HelloRetryRequest); returns its data length, -1 when absent (also when +// a TLS 1.2 ServerHello has no extensions block at all), or -2 when the message is malformed +static int tls_sh_ext(const uint8_t *m, size_t len, uint16_t type, const uint8_t **data) +{ + const uint8_t *p = m + 4, *end = m + len; + if (end - p < 2 + 32 + 1) { + return -2; + } + p += 2 + 32; // legacy_version, random + if (end - p < 1 + p[0] + 2 + 1) { + return -2; + } + p += 1 + p[0]; // session id + p += 2 + 1; // cipher suite, compression + if (p == end) { + return -1; + } + if (end - p < 2) { + return -2; + } + const uint8_t *eend = p + 2 + ((p[0] << 8) | p[1]); + p += 2; + if (eend > end) { + return -2; + } + while (eend - p >= 4) { + int t = (p[0] << 8) | p[1], n = (p[2] << 8) | p[3]; + if (eend - p - 4 < n) { + return -2; + } + if (t == type) { + *data = p + 4; + return n; + } + p += 4 + n; + } + return -1; +} + +// After each successful handshake step: records the negotiated group (no mbedTLS getter) from the TLS 1.3 ServerHello +// key_share or the TLS 1.2 ServerKeyExchange curve, and requires EMS in a TLS 1.2 +// ServerHello, as mbedTLS has just parsed them. Also refuses a TLS 1.2 ServerHello that left the version above 1.2. +// Returns an mbedTLS error, with r->fail_reason set, when it refuses. +static int tls_note_handshake(tls_session_t *s, int state_before, int version_before, tls_step_result_t *r) +{ + int state = s->ssl.state; + const uint8_t *m, *d; + size_t len; + if ((state_before == MBEDTLS_SSL_SERVER_HELLO) && (state != MBEDTLS_SSL_SERVER_HELLO)) { + m = tls_hs_msg(s, MBEDTLS_SSL_HS_SERVER_HELLO, &len); + if (version_before == MBEDTLS_SSL_VERSION_TLS1_3) { + if (m && (tls_sh_ext(m, len, 51, &d) >= 2)) { // key_share: the group comes first in both forms + s->stats.group = (d[0] << 8) | d[1]; + } + // Not found: the group stays 0, and tls_handshake() refuses the session. This includes a HelloRetryRequest: + // mbedTLS has already cleared the message when that step returns, so nothing is read from it, and the group + // comes from the ServerHello that follows + } else if (s->ssl.tls_version != MBEDTLS_SSL_VERSION_TLS1_2) { + // mbedTLS's TLS 1.2 ServerHello parser takes legacy_version as the version (ssl_tls12_client.c:1226), so a + // ServerHello claiming 0x0304 would carry on in the TLS 1.3 machine without a key exchange: refuse it + r->fail_reason = TLS_FAIL_VERSION_REFUSED; + r->verify_flags = (uint16_t)s->ssl.tls_version; + mbedtls_ssl_send_alert_message(&s->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION); + return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION; + } else if (!s->ems_checked) { + // mbedtls_ssl_conf_extended_master_secret() only offers it: a server that does not echo it is accepted + // (ssl_tls12_client.c:742-759), so the engine refuses it here, before any key is derived. A ServerHello + // it cannot find counts as one without EMS: fail closed. + s->ems_checked = 1; + s->stats.ems = m && (tls_sh_ext(m, len, 23, &d) == 0); + if (!s->stats.ems) { + ESP_LOGW(TAG, "TLS 1.2 server without the extended master secret: refused"); + r->fail_reason = TLS_FAIL_NO_EMS; + mbedtls_ssl_send_alert_message(&s->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE); + return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE; + } + } + } + if ((state_before == MBEDTLS_SSL_SERVER_KEY_EXCHANGE) && (version_before == MBEDTLS_SSL_VERSION_TLS1_2) && + (m = tls_hs_msg(s, MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE, &len)) != NULL && (len >= 4 + 3) && (m[4] == 3)) { + s->stats.group = (m[5] << 8) | m[6]; // ECParameters: named_curve (3), then the NamedGroup + } + return 0; +} + +// Classifies a failed handshake step for the Ultimate's failure reasons. The Ultimate infers nothing from bare mbedTLS codes. +static void tls_classify(tls_session_t *s, int ret, int state_before, int version_before, tls_step_result_t *r) +{ + if (tls_rng_gate_take_refusal()) { + // A draw found no entropy source (the radio stopped, or a voltage read ran, and the source is off): not the peer's + r->fail_reason = TLS_FAIL_NO_ENTROPY; + } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + r->fail_reason = TLS_FAIL_PEER_CLOSED; + } else if ((state_before == MBEDTLS_SSL_SERVER_HELLO) && (ret == MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION)) { + // A ServerHello whose version mbedTLS refused. Report the version the server sent, from the message (legacy_version, + // or the selected version of supported_versions when present): ssl->tls_version is not that on every mbedTLS + // (a fixed 4.1.x puts it back to 1.2 before returning), and is the fallback only if the message is gone + size_t len; + const uint8_t *d, *m = tls_hs_msg(s, MBEDTLS_SSL_HS_SERVER_HELLO, &len); + r->fail_reason = TLS_FAIL_VERSION_REFUSED; + r->verify_flags = (uint16_t)s->ssl.tls_version; + if (m && (len >= 4 + 2 + 32)) { + r->verify_flags = (m[4] << 8) | m[5]; + if (tls_sh_ext(m, len, 43, &d) == 2) { + r->verify_flags = (d[0] << 8) | d[1]; + } + } + } else if ((state_before == MBEDTLS_SSL_SERVER_HELLO) && (version_before == MBEDTLS_SSL_VERSION_TLS1_3) && + (ret == MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER)) { + // This one step is all of mbedTLS's TLS 1.3 ServerHello processing (ssl_tls13_client.c:1995-2060), so + // ILLEGAL_PARAMETER has many causes. Only a ServerHello without supported_versions chose TLS 1.2 or lower, and + // of those only one whose random ends in the RFC 8446 4.1.3 sentinel is a downgrade; all else is fail_reason 0. + size_t len; + const uint8_t *d, *m = tls_hs_msg(s, MBEDTLS_SSL_HS_SERVER_HELLO, &len); + if (m && (len >= 4 + 2 + 32) && (tls_sh_ext(m, len, 43, &d) == -1)) { + const uint8_t *tail = m + 4 + 2 + 32 - 8; // the last 8 bytes of the random + if (s->opts & TLS_OPT_REQUIRE_TLS13) { + r->fail_reason = TLS_FAIL_VERSION_REFUSED; + r->verify_flags = (m[4] << 8) | m[5]; // legacy_version: the version it chose + } else if (!memcmp(tail, "\x44\x4F\x57\x4E\x47\x52\x44", 7) && (tail[7] <= 1)) { + r->fail_reason = TLS_FAIL_DOWNGRADE; + } + } + } else if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { + r->fail_reason = ((s->trust == TLS_TRUST_PIN) && s->pin_mismatch) ? TLS_FAIL_PIN_MISMATCH : TLS_FAIL_CERT_VERIFY; + r->verify_flags = mbedtls_ssl_get_verify_result(&s->ssl); + } else if (ret == MBEDTLS_ERR_SSL_BAD_CERTIFICATE) { + // A secondary check (usage, TLS 1.2 curve), or a Certificate message refused before verification ran + r->fail_reason = TLS_FAIL_CERT_VERIFY; + r->verify_flags = mbedtls_ssl_get_verify_result(&s->ssl); + } else if (ret == MBEDTLS_ERR_X509_FATAL_ERROR) { + r->fail_reason = TLS_FAIL_CERT_VERIFY; + r->verify_flags = 0xFFFFFFFF; + } +} + +// Runs handshake steps until mbedTLS wants input or output, the handshake is over, or it fails +static int tls_handshake(tls_session_t *s, tls_step_result_t *r) +{ + tls_rng_gate_take_refusal(); // one left by an earlier session is not this one's + while (!mbedtls_ssl_is_handshake_over(&s->ssl)) { + int state_before = s->ssl.state; + int version_before = s->ssl.tls_version; + int64_t start = esp_timer_get_time(); + int ret = mbedtls_ssl_handshake_step(&s->ssl); + s->stats.handshake_us += (uint32_t)(esp_timer_get_time() - start); + int ems = (ret == 0) ? tls_note_handshake(s, state_before, version_before, r) : 0; + if (ems) { + return ems; + } + if ((ret == MBEDTLS_ERR_SSL_WANT_READ) || (ret == MBEDTLS_ERR_SSL_WANT_WRITE)) { + return 0; + } + if (ret != 0) { + tls_classify(s, ret, state_before, version_before, r); + return ret; + } + } + if (s->stats.group == 0) { + // The group is never 0 once ESTABLISHED: if it was not found, the reads above no longer match this + // mbedTLS, and nothing they check (EMS) can be trusted either. Fail closed. + ESP_LOGE(TAG, "Negotiated group not found in the server's messages: session refused"); + mbedtls_ssl_send_alert_message(&s->ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR); + return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE; + } + s->stats.state = TLS_STATE_ESTABLISHED; + s->stats.tls_version = (uint16_t)mbedtls_ssl_get_version_number(&s->ssl); + s->stats.ciphersuite = (uint16_t)mbedtls_ssl_get_ciphersuite_id_from_ssl(&s->ssl); + return 0; +} + +int tls_step(uint8_t slot, uint16_t tag, uint8_t flags, const uint8_t *ct_in, int ct_in_len, const uint8_t *pt_in, + int pt_in_len, uint8_t *out, uint16_t *ct_out_len, uint16_t *pt_out_len, tls_step_result_t *r) +{ + tls_session_t *s = tls_find(slot, tag); + *ct_out_len = 0; + *pt_out_len = 0; + r->alert_in = TLS_ALERT_NONE; + r->alert_out = TLS_ALERT_NONE; + r->fail_reason = TLS_FAIL_NONE; + r->verify_flags = 0; + if (!s) { + r->state = TLS_STATE_CLOSED; + return ESP_ERR_NOT_FOUND; + } + r->state = s->stats.state; + + // Caller errors consume nothing, return nothing and leave the session as it is + if ((flags & ~TLS_STEP_NO_READ) || (ct_in_len < 0) || (pt_in_len < 0) || (ct_in_len + pt_in_len > TLS_STEP_IN_MAX)) { + return ESP_ERR_INVALID_ARG; + } + if (pt_in_len && (s->stats.state != TLS_STATE_ESTABLISHED)) { + return ESP_ERR_INVALID_STATE; + } + // A full buffer refuses the input with ESP_ERR_NO_MEM, but the step still returns output, + // so the Ultimate can send the same step again until it is taken + int ret = 0; + int refused = (ct_in_len > TLS_IN_BUF_SIZE - (s->in_len - s->in_off)) ? ESP_ERR_NO_MEM : ESP_OK; + if (!refused && pt_in_len) { + // mbedtls_ssl_write() must never see WANT_WRITE: it would keep part of pt_in for a + // repeat call, and with output pending it reports len written without copying it + int payload = mbedtls_ssl_get_max_out_record_payload(&s->ssl); + int expansion = mbedtls_ssl_get_record_expansion(&s->ssl); + if (payload <= 0) { + ret = payload ? payload : MBEDTLS_ERR_SSL_INTERNAL_ERROR; + } else if (expansion < 0) { + ret = expansion; + } else { + int need = pt_in_len + ((pt_in_len + payload - 1) / payload) * expansion; + if (need > TLS_OUT_BUF_SIZE) { + return ESP_ERR_INVALID_ARG; // could never fit: send less plaintext per step + } + if (need > TLS_OUT_BUF_SIZE - s->out_len) { + refused = ESP_ERR_NO_MEM; + } + } + } + + if (!refused && (ret == 0)) { + if (s->in_off) { + memmove(s->in_buf, s->in_buf + s->in_off, s->in_len - s->in_off); + s->in_len -= s->in_off; + s->in_off = 0; + } + memcpy(s->in_buf + s->in_len, ct_in, ct_in_len); + s->in_len += ct_in_len; + s->stats.ct_in_bytes += ct_in_len; + } + // While handshaking only the handshake drains in_buf, so it also runs when the input was refused: + // otherwise a full in_buf would refuse every resend of the step + int just_established = 0; + if (ret == 0) { + if (s->stats.state == TLS_STATE_HANDSHAKING) { + ret = tls_handshake(s, r); + just_established = (s->stats.state == TLS_STATE_ESTABLISHED); + } else if (!refused && pt_in_len) { + if (s->ssl.out_left != 0) { + ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; + } + for (int done = 0, tickets = 0; (ret == 0) && (done < pt_in_len); ) { + int n = mbedtls_ssl_write(&s->ssl, pt_in + done, pt_in_len - done); + if (n > 0) { + done += n; + } else if ((n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) && (++tickets <= TLS_TICKET_RETRIES)) { + // A ticket an earlier read left pending: mbedtls_ssl_write() took it first and wrote + // nothing, so write again (ssl_msg.c:5938-5942 in mbedTLS 4.1.1). Not a failure. + continue; + } else { + ret = n ? n : MBEDTLS_ERR_SSL_INTERNAL_ERROR; + } + } + if (ret == 0) { + s->stats.pt_in_bytes += pt_in_len; + } + } + } + // From here on out may be written: the input is either consumed or refused + + // No plaintext from the step that reaches ESTABLISHED (the Ultimate reads STATS right after it), nor from + // a NO_READ step (a WRITE's): what is pending stays in the engine for the next plain step + int ct_len = (s->out_len < TLS_STEP_OUT_MAX) ? s->out_len : TLS_STEP_OUT_MAX; + int pt_len = 0; + while ((ret == 0) && (s->stats.state == TLS_STATE_ESTABLISHED) && !just_established && !(flags & TLS_STEP_NO_READ) && + (ct_len + pt_len + TLS_ALERT_ROOM < TLS_STEP_OUT_MAX)) { + int in_before = s->in_off; + int n = mbedtls_ssl_read(&s->ssl, out + ct_len + pt_len, TLS_STEP_OUT_MAX - TLS_ALERT_ROOM - ct_len - pt_len); + if (n > 0) { + pt_len += n; + } else if ((n == MBEDTLS_ERR_SSL_WANT_READ) && mbedtls_ssl_check_pending(&s->ssl)) { + // A complete ticket makes mbedtls_ssl_read() return WANT_READ with the ticket kept for the + // next call (ssl_msg.c:5466-5473 in mbedTLS 4.1.1), which takes it without new input. + // Take every one now, or the reply behind them waits for a step the Ultimate never sends. + continue; + } else if ((n == MBEDTLS_ERR_SSL_WANT_READ) && (s->in_off > in_before) && (s->in_off < s->in_len)) { + // A record mbedTLS skipped with WANT_READ (a TLS 1.2 no_renegotiation warning alert, + // ssl_msg.c:5002-5006) while more input waits: read on, or the data behind it would wait + // for another step. The read took input, so this ends. + continue; + } else if ((n == MBEDTLS_ERR_SSL_WANT_READ) || (n == MBEDTLS_ERR_SSL_WANT_WRITE)) { + break; + } else if (n == MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET) { + continue; // a TLS 1.3 ticket after the handshake: no plaintext yet, read again (never FAILED) + } else if (n == 0) { + // An empty application data record, which RFC 8446 allows: read on. It never means the + // connection closed, because tls_bio_recv() never reports end of input. + continue; + } else if (n == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + // RFC 8446 6.1 / RFC 5246 7.2.1: answer the peer's close_notify with our own. Best effort, as in + // tls_close(); it lands in out_buf and goes out with this step (TLS_ALERT_ROOM is kept free for it). + mbedtls_ssl_close_notify(&s->ssl); + s->stats.state = TLS_STATE_CLOSED; + } else { + ret = n; + } + } + s->stats.pt_out_bytes += pt_len; + + if (ret != 0) { + s->stats.state = TLS_STATE_FAILED; + if (ret == MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) { + int alert = mbedtls_ssl_get_fatal_alert(&s->ssl); + r->alert_in = (alert >= 0) ? (uint8_t)alert : TLS_ALERT_NONE; + } + // The alert this engine sent, when mbedTLS wrote it before any keys (mbedTLS has no getter for it) + if ((s->ssl.out_msgtype == MBEDTLS_SSL_MSG_ALERT) && (s->ssl.transform_out == NULL) && + (s->ssl.out_msg[0] == MBEDTLS_SSL_ALERT_LEVEL_FATAL)) { + r->alert_out = s->ssl.out_msg[1]; + } + ESP_LOGW(TAG, "Session %d/%u failed: -0x%04x, reason %d, verify 0x%x", slot, tag, (unsigned)-ret, r->fail_reason, + (unsigned)r->verify_flags); + } + + // Ciphertext the reads produced (a fatal alert before the session is freed) goes out in this + // step too: move the plaintext up into the room the reads left for it + int ct_all = (s->out_len < TLS_STEP_OUT_MAX - pt_len) ? s->out_len : TLS_STEP_OUT_MAX - pt_len; + if (ct_all > ct_len) { + memmove(out + ct_all, out + ct_len, pt_len); + ct_len = ct_all; + } + memcpy(out, s->out_buf, ct_len); + memmove(s->out_buf, s->out_buf + ct_len, s->out_len - ct_len); + s->out_len -= ct_len; + s->stats.ct_out_bytes += ct_len; + *ct_out_len = ct_len; + *pt_out_len = pt_len; + + r->state = s->stats.state; + if ((s->stats.state == TLS_STATE_FAILED) || (s->stats.state == TLS_STATE_CLOSED)) { + tls_free(s); + } + return ret ? ret : refused; +} + +int tls_close(uint8_t slot, uint16_t tag, uint8_t *out, uint16_t *ct_out_len) +{ + *ct_out_len = 0; + tls_session_t *s = tls_find(slot, tag); + if (!s) { + return ESP_ERR_NOT_FOUND; + } + // Best effort: close_notify lands in out_buf behind anything still pending there. A session still + // handshaking has nothing to close, and its half flight is not sent. + if (s->stats.state == TLS_STATE_ESTABLISHED) { + mbedtls_ssl_close_notify(&s->ssl); + int n = (s->out_len < TLS_STEP_OUT_MAX) ? s->out_len : TLS_STEP_OUT_MAX; + memcpy(out, s->out_buf, n); + *ct_out_len = n; + } + tls_free(s); + return ESP_OK; +} + +void tls_close_all(void) +{ + for (int i = 0; i < TLS_MAX_SESSIONS; i++) { + if (sessions[i]) { + tls_free(sessions[i]); + } + } + tls_ca_release(custom_ca); + custom_ca = NULL; +} + +// SET_CA: the upload-time refusals, in their order of precedence +static uint8_t tls_ca_reject(const mbedtls_x509_crt *crt) +{ + psa_key_type_t type = mbedtls_pk_get_key_type(&crt->pk); + size_t bits = mbedtls_pk_get_bitlen(&crt->pk); + if (PSA_KEY_TYPE_IS_RSA(type) && (bits < mbedtls_x509_crt_profile_default.rsa_min_bitlen)) { + return TLS_CA_REJECT_RSA_KEY_SHORT; + } + if (PSA_KEY_TYPE_IS_ECC(type)) { + // The curves of mbedtls_x509_crt_profile_default, which the engine verifies with (x509_crt.c:98-104 in + // 4.1.1), not the key-exchange groups + psa_ecc_family_t family = PSA_KEY_TYPE_ECC_GET_FAMILY(type); + int ok = ((family == PSA_ECC_FAMILY_SECP_R1) && ((bits == 256) || (bits == 384) || (bits == 521))) || + ((family == PSA_ECC_FAMILY_BRAINPOOL_P_R1) && ((bits == 256) || (bits == 384) || (bits == 512))); + if (!ok) { + return TLS_CA_REJECT_CURVE; + } + } + // mbedTLS refuses such a certificate as an issuer. A v1 root has no extensions and is an anchor as it is; + // a keyUsage extension that is absent passes check_key_usage. + if (((crt->version >= 3) && (mbedtls_x509_crt_get_ca_istrue(crt) != 1)) || + (mbedtls_x509_crt_check_key_usage(crt, MBEDTLS_X509_KU_KEY_CERT_SIGN) != 0)) { + return TLS_CA_REJECT_NOT_CA; + } + return TLS_CA_REJECT_NONE; +} + +int tls_set_ca(const uint8_t *der, int der_len, uint16_t ca_tag, uint8_t *reject) +{ + *reject = TLS_CA_REJECT_NONE; + // The one held is dropped first: on any error none is held (a session keeps its own reference) + tls_ca_release(custom_ca); + custom_ca = NULL; + if ((der_len <= 0) || (der_len > TLS_CA_MAX_LEN) || (ca_tag == 0)) { + return ESP_ERR_INVALID_ARG; + } + if (!tls_psa_ready()) { + return ESP_ERR_INVALID_STATE; // never ESP_FAIL: the Ultimate reads a SET_CA ESP_FAIL as no reply + } + tls_ca_t *ca = calloc(1, sizeof(tls_ca_t)); + if (!ca) { + return ESP_ERR_NO_MEM; + } + mbedtls_x509_crt_init(&ca->crt); + ca->tag = ca_tag; + ca->refs = 1; + int ret = mbedtls_x509_crt_parse_der(&ca->crt, der, der_len); + if (ret == 0) { + *reject = tls_ca_reject(&ca->crt); + if (*reject != TLS_CA_REJECT_NONE) { + ret = ESP_ERR_INVALID_ARG; + } + } else if (ret > -2) { + ret = MBEDTLS_ERR_X509_INVALID_FORMAT; // never ESP_FAIL (-1), which the Ultimate does not read as a parse code + } + if (ret != 0) { + ESP_LOGW(TAG, "CA refused: %d, reject %d", ret, *reject); + tls_ca_release(ca); + return ret; + } + custom_ca = ca; + return ESP_OK; +} + +int tls_get_stats(uint8_t slot, uint16_t tag, tls_session_stats_t *stats) +{ + memset(stats, 0, sizeof(tls_session_stats_t)); + stats->state = TLS_STATE_CLOSED; + if ((slot == TLS_SLOT_GLOBAL) && (tag == 0)) { + time_t now = time(NULL); + if (now <= tls_build_time()) { + stats->time_source = TLS_TIME_NONE; + } else { + stats->time_source = sntp_has_time() ? TLS_TIME_SNTP : (clock_set_by_nios ? TLS_TIME_NIOS : TLS_TIME_NONE); + } + stats->esp_time = (stats->time_source == TLS_TIME_NONE) ? 0 : (uint32_t)now; + return ESP_OK; + } + tls_session_t *s = tls_find(slot, tag); + if (!s) { + return ESP_ERR_NOT_FOUND; + } + *stats = s->stats; + return ESP_OK; +} diff --git a/software/wifi/tls/tls_engine.h b/software/wifi/tls/tls_engine.h new file mode 100644 index 000000000..7c5f6e345 --- /dev/null +++ b/software/wifi/tls/tls_engine.h @@ -0,0 +1,71 @@ +/* tls_engine.h: TLS client sessions whose ciphertext the Ultimate carries; the ESP32 never touches a socket. + * Every call is lock-step, and all of them run on the TLS task only. */ + +#ifndef TLS_ENGINE_H_ +#define TLS_ENGINE_H_ + +#include +#include "rpc_calls.h" + +#define TLS_HEAP_CAPS (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) // what mbedTLS allocates from (esp_heap_caps.h) + +typedef struct { + uint32_t ct_in_bytes; + uint32_t ct_out_bytes; + uint32_t pt_in_bytes; + uint32_t pt_out_bytes; + uint32_t handshake_us; + uint16_t tls_version; + uint16_t ciphersuite; + uint16_t group; + uint8_t state; + uint8_t time_source; + uint8_t ems; + uint32_t esp_time; + uint8_t spki_sha256[TLS_PIN_LEN]; +} tls_session_stats_t; + +typedef struct { + uint8_t trust; // tls_trust_t + uint8_t opts; // TLS_OPT_* + uint8_t time_source; // TLS_TIME_NONE or TLS_TIME_NIOS: whether unix_time is a clock + uint16_t ca_tag; // CUSTOM: must equal the held CA's + uint32_t unix_time; + const uint8_t *pin; // TLS_PIN_LEN bytes, read for PIN only + const char *sni; // sni_len bytes, no terminator; none (sni_len 0) only with PIN + int sni_len; +} tls_open_params_t; + +typedef struct { + uint8_t state; // tls_state_t + uint8_t alert_in; // TLS_ALERT_NONE unless a fatal alert was received + uint8_t alert_out; // TLS_ALERT_NONE unless this engine sent an unencrypted fatal alert + uint8_t fail_reason; // tls_fail_reason_t, with FAILED + uint32_t verify_flags; +} tls_step_result_t; + +// All return ESP_OK, an esp_err_t, or a negative mbedTLS code. A (slot, tag) that is not the live session in that slot +// gets ESP_ERR_NOT_FOUND and touches nothing. A session is freed on FAILED, on CLOSED, by tls_close() and +// tls_close_all(), and when an OPEN names its slot again. + +// unix_time sets the ESP32 clock (time_source TLS_TIME_NIOS, and no SNTP time of its own). BUNDLE and CUSTOM need a +// trustworthy clock: without one OPEN fails with ESP_ERR_INVALID_STATE, reason NO_TIME. +int tls_open(uint8_t slot, uint16_t tag, const tls_open_params_t *params, uint8_t *reason); + +// Consumes all of ct_in (pt_in only when ESTABLISHED) or none, then writes ct_out and pt_out (no pt with NO_READ) to out, +// at most TLS_STEP_OUT_MAX; out may overlap the inputs. ESP_ERR_NO_MEM: buffer full, nothing consumed, output returned, +// resend. INVALID_ARG/INVALID_STATE/NOT_FOUND: nothing consumed or returned. A negative code comes with state FAILED. +int tls_step(uint8_t slot, uint16_t tag, uint8_t flags, const uint8_t *ct_in, int ct_in_len, const uint8_t *pt_in, + int pt_in_len, uint8_t *out, uint16_t *ct_out_len, uint16_t *pt_out_len, tls_step_result_t *result); + +// Frees the session; out gets its pending ciphertext and a close_notify (at most TLS_STEP_OUT_MAX) +int tls_close(uint8_t slot, uint16_t tag, uint8_t *out, uint16_t *ct_out_len); +// Frees every session and the CUSTOM CA +void tls_close_all(void); +// Parses one DER certificate as the CUSTOM CA under ca_tag, replacing the one held. On any error none is held. +int tls_set_ca(const uint8_t *der, int der_len, uint16_t ca_tag, uint8_t *reject); +// slot TLS_SLOT_GLOBAL with tag 0: the clock only +int tls_get_stats(uint8_t slot, uint16_t tag, tls_session_stats_t *stats); +int tls_sessions_open(void); + +#endif /* TLS_ENGINE_H_ */ diff --git a/software/wifi/tls/tls_engine_stub.c b/software/wifi/tls/tls_engine_stub.c new file mode 100644 index 000000000..7720a394a --- /dev/null +++ b/software/wifi/tls/tls_engine_stub.c @@ -0,0 +1,72 @@ +/* tls_engine_stub.c: stands in for tls_engine.c in a size-measurement build (idf.py -D BRIDGE_TLS_STUB=1). The RPC + * commands stay and every TLS call answers ESP_ERR_NOT_SUPPORTED, so mbedTLS's TLS and X.509 code is not linked. + * Never flashed to a device. */ + +#include +#include "esp_err.h" +#include "tls_engine.h" + +int tls_open(uint8_t slot, uint16_t tag, const tls_open_params_t *params, uint8_t *reason) +{ + (void)slot; + (void)tag; + (void)params; + *reason = TLS_OPEN_REASON_NONE; + return ESP_ERR_NOT_SUPPORTED; +} + +int tls_step(uint8_t slot, uint16_t tag, uint8_t flags, const uint8_t *ct_in, int ct_in_len, const uint8_t *pt_in, + int pt_in_len, uint8_t *out, uint16_t *ct_out_len, uint16_t *pt_out_len, tls_step_result_t *result) +{ + (void)slot; + (void)tag; + (void)flags; + (void)ct_in; + (void)ct_in_len; + (void)pt_in; + (void)pt_in_len; + (void)out; + *ct_out_len = 0; + *pt_out_len = 0; + memset(result, 0, sizeof(tls_step_result_t)); + result->state = TLS_STATE_CLOSED; + result->alert_in = TLS_ALERT_NONE; + result->alert_out = TLS_ALERT_NONE; + return ESP_ERR_NOT_FOUND; +} + +int tls_close(uint8_t slot, uint16_t tag, uint8_t *out, uint16_t *ct_out_len) +{ + (void)slot; + (void)tag; + (void)out; + *ct_out_len = 0; + return ESP_ERR_NOT_FOUND; +} + +void tls_close_all(void) +{ +} + +int tls_set_ca(const uint8_t *der, int der_len, uint16_t ca_tag, uint8_t *reject) +{ + (void)der; + (void)der_len; + (void)ca_tag; + *reject = TLS_CA_REJECT_NONE; + return ESP_ERR_NOT_SUPPORTED; +} + +int tls_get_stats(uint8_t slot, uint16_t tag, tls_session_stats_t *stats) +{ + (void)slot; + (void)tag; + memset(stats, 0, sizeof(tls_session_stats_t)); + stats->state = TLS_STATE_CLOSED; + return ESP_ERR_NOT_SUPPORTED; +} + +int tls_sessions_open(void) +{ + return 0; +} diff --git a/software/wifi/tls/tls_rng_gate.c b/software/wifi/tls/tls_rng_gate.c new file mode 100644 index 000000000..9c4416d54 --- /dev/null +++ b/software/wifi/tls/tls_rng_gate.c @@ -0,0 +1,68 @@ +/* tls_rng_gate.c: see tls_rng_gate.h. Linked in with -Wl,--wrap=mbedtls_psa_external_get_random. */ +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "psa/crypto.h" +#include "radio_entropy.h" +#include "tls_rng_gate.h" + +psa_status_t __real_mbedtls_psa_external_get_random(mbedtls_psa_external_random_context_t *context, uint8_t *output, + size_t output_size, size_t *output_length); + +// How long a draw waits for the gate: RE_WAIT_ADC_MS rounded up to whole ticks, and one tick more. The extra tick is margin +// over the voltage read, not a correction of the rounding: radio_entropy_acquire_shared() measures its deadline in esp_timer +// milliseconds, so RE_WAIT_ADC_MS alone was never short. What the margin covers is the hold of the read itself, which +// nothing bounds and which radio_entropy_stats_t.adc_hold_max_ms records (to be measured on hardware). +#define TLS_RNG_GATE_WAIT_MS ((((RE_WAIT_ADC_MS + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS) + 1) * portTICK_PERIOD_MS) + +// The module runs the tick at 100 Hz (CONFIG_FREERTOS_HZ=100, 10 ms) and the wait is 60 ms: a build that truncates instead of +// rounding up (50), or drops the extra tick (50), fails here. Host builds use a 1 ms stand-in tick and do not check it. +#ifdef ESP_PLATFORM +_Static_assert(TLS_RNG_GATE_WAIT_MS == 60, "TLS_RNG_GATE_WAIT_MS: 50 ms rounded up to whole 10 ms ticks, plus one tick"); +#endif + +static TaskHandle_t tls_task; // set by the TLS task itself, from the engine entry (tls_open) +static volatile int refused; // written and read by the TLS task only + +void tls_rng_gate_bind_task(void) +{ + tls_task = xTaskGetCurrentTaskHandle(); +} + +#ifdef TLS_RNG_GATE_HOST_TEST +void tls_rng_gate_unbind_task_for_test(void) +{ + tls_task = NULL; +} +#endif + +int tls_rng_gate_take_refusal(void) +{ + int was = refused; + refused = 0; + return was; +} + +psa_status_t __wrap_mbedtls_psa_external_get_random(mbedtls_psa_external_random_context_t *context, uint8_t *output, + size_t output_size, size_t *output_length) +{ + if ((tls_task == NULL) || (xTaskGetCurrentTaskHandle() != tls_task)) { + return __real_mbedtls_psa_external_get_random(context, output, output_size, output_length); + } + // No lock, queue or UART is held or waited for in here: the hold is one draw. The wait covers a voltage read (the + // ADC source is off for it; the read itself waits RE_WAIT_ADC_MS for the gate, and the hold it makes is recorded in + // stats.adc_hold_max_ms), so a read whose hold stays under the wait delays a draw and does not fail it; a radio change holds the gate + // longer and the source is off through it, so a draw then fails. + int rc = radio_entropy_acquire_shared(TLS_RNG_GATE_WAIT_MS); + if (rc != RE_OK) { + refused = 1; + return PSA_ERROR_INSUFFICIENT_ENTROPY; + } + if (entropy_source() == ENTROPY_NONE) { + radio_entropy_release_shared(); + refused = 1; + return PSA_ERROR_INSUFFICIENT_ENTROPY; + } + psa_status_t status = __real_mbedtls_psa_external_get_random(context, output, output_size, output_length); + radio_entropy_release_shared(); + return status; +} diff --git a/software/wifi/tls/tls_rng_gate.h b/software/wifi/tls/tls_rng_gate.h new file mode 100644 index 000000000..bfa69bb4f --- /dev/null +++ b/software/wifi/tls/tls_rng_gate.h @@ -0,0 +1,30 @@ +/* tls_rng_gate.h: keeps the radio's entropy source on for the draws of the TLS task. + * + * mbedTLS 4 draws every random byte through mbedtls_psa_external_get_random() (MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG), which + * is esp_fill_random() here. esp_fill_random() is random only while the radio runs or the ADC source is on, and a radio + * start or stop or a read of the voltages switches the source off (radio_entropy.h). The module's link wraps that function + * (-Wl,--wrap=mbedtls_psa_external_get_random, in the component's CMakeLists.txt) with tls_rng_gate.c: + * - a draw made on the TLS task holds the entropy gate shared for that one draw, which is microseconds, so a radio change + * never waits for ECC or RSA work; with no source, or no gate within the wait below, the draw fails with + * PSA_ERROR_INSUFFICIENT_ENTROPY and the engine ends the session with TLS_FAIL_NO_ENTROPY; + * The wait is RE_WAIT_ADC_MS (50 ms) rounded up to whole ticks (10 ms on the module) plus one tick, 60 ms: margin over + * the voltage read's hold of the gate, which nothing bounds (radio_entropy_stats_t.adc_hold_max_ms records it); + * - a draw made on any other task passes straight through, so the Wi-Fi stack's draws are never held up by it. + */ +#ifndef SOFTWARE_WIFI_TLS_TLS_RNG_GATE_H_ +#define SOFTWARE_WIFI_TLS_TLS_RNG_GATE_H_ + +// The TLS task: its draws are the ones that are gated. Idempotent and cheap; tls_open() calls it first, on the TLS task, so +// that the binding is part of the engine and a test of the engine exercises it. A draw made before it is not gated +// (the Wi-Fi stack draws before the TLS task exists, and must never be held). +void tls_rng_gate_bind_task(void); + +#ifdef TLS_RNG_GATE_HOST_TEST +// Host harness only: forgets the binding, so that a case starts unbound and only tls_open() can bind it. +void tls_rng_gate_unbind_task_for_test(void); +#endif + +// 1 once if a draw was refused since the last call (no source, or the gate not free in time), and clears it +int tls_rng_gate_take_refusal(void); + +#endif /* SOFTWARE_WIFI_TLS_TLS_RNG_GATE_H_ */ diff --git a/software/wifi/tls/tls_rpc.c b/software/wifi/tls/tls_rpc.c new file mode 100644 index 000000000..da080bd82 --- /dev/null +++ b/software/wifi/tls/tls_rpc.c @@ -0,0 +1,267 @@ +/* tls_rpc.c: the CMD_TLS_* commands on the module side. They run on their own task, so a handshake never blocks + * the dispatcher (Wi-Fi TX); the dispatcher hands them over with tls_rpc_dispatch(). */ + +#include +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "freertos/task.h" +#include "esp_err.h" +#include "esp_heap_caps.h" +#include "driver/uart.h" +#include "rpc_calls.h" +#include "cmd_buffer.h" // CMD_BUF_SIZE +#include "my_uart.h" +#include "wifi_modem.h" +#include "tls_engine.h" +#include "tls_rpc.h" + +// Every request and reply must fit one command buffer +_Static_assert(sizeof(rpc_tls_open_req) + TLS_SNI_MAX_LEN <= CMD_BUF_SIZE, "largest CMD_TLS_OPEN request"); +_Static_assert(sizeof(rpc_tls_step_req) + TLS_STEP_IN_MAX <= CMD_BUF_SIZE, "largest CMD_TLS_STEP request"); +_Static_assert(sizeof(rpc_tls_step_resp) + TLS_STEP_OUT_MAX <= CMD_BUF_SIZE, "largest CMD_TLS_STEP reply"); +_Static_assert(sizeof(rpc_tls_close_resp) + TLS_STEP_OUT_MAX <= CMD_BUF_SIZE, "largest CMD_TLS_CLOSE reply"); +_Static_assert(sizeof(rpc_tls_set_ca_req) + TLS_CA_MAX_LEN <= CMD_BUF_SIZE, "largest CMD_TLS_SET_CA request"); +_Static_assert(sizeof(rpc_tls_stats_resp) <= CMD_BUF_SIZE, "CMD_TLS_STATS reply"); + +#define UART_CHAN UART_NUM_1 + +void cmd_not_implemented(command_buf_t *buf); + +static QueueHandle_t tls_queue; +static volatile uint16_t block_max_ms; // the longest dispatcher iteration since boot, read by the TLS task + +void cmd_tls_open(command_buf_t *buf) +{ + rpc_tls_open_req *req = (rpc_tls_open_req *)buf->data; + rpc_tls_open_resp *resp = (rpc_tls_open_resp *)buf->data; + + // tls_open() copies the pin and the host name before the response overwrites them + uint8_t slot = TLS_SLOT_GLOBAL; + uint8_t reason = TLS_OPEN_REASON_NONE; + int err = ESP_ERR_INVALID_ARG; + if ((buf->size >= (int)sizeof(rpc_tls_open_req)) && (buf->size == (int)sizeof(rpc_tls_open_req) + req->sni_len)) { + tls_open_params_t p = { + .trust = req->trust, .opts = req->opts, .time_source = req->time_source, .ca_tag = req->ca_tag, + .unix_time = req->unix_time, .pin = req->pin, .sni = req->sni, .sni_len = req->sni_len, + }; + err = tls_open(req->slot, req->tag, &p, &reason); + if (err == ESP_OK) { + slot = req->slot; + } + } + memset(&resp->esp_err, 0, sizeof(rpc_tls_open_resp) - sizeof(rpc_header_t)); + resp->esp_err = err; + resp->slot = slot; + resp->reason = reason; + buf->size = sizeof(rpc_tls_open_resp); + my_uart_transmit_packet(UART_CHAN, buf); +} + +void cmd_tls_step(command_buf_t *buf) +{ + rpc_tls_step_req *req = (rpc_tls_step_req *)buf->data; + rpc_tls_step_resp *resp = (rpc_tls_step_resp *)buf->data; + + // The response overlays the request: tls_step() consumes ct_in and pt_in before it writes resp->data + uint16_t ct_out_len = 0; + uint16_t pt_out_len = 0; + tls_step_result_t result = { .state = TLS_STATE_CLOSED, .alert_in = TLS_ALERT_NONE, .alert_out = TLS_ALERT_NONE }; + int err = ESP_ERR_INVALID_ARG; + if (buf->size >= (int)sizeof(rpc_tls_step_req)) { + int ct_in_len = req->ct_in_len; + int pt_in_len = req->pt_in_len; + if (buf->size == (int)sizeof(rpc_tls_step_req) + ct_in_len + pt_in_len) { + err = tls_step(req->slot, req->tag, req->flags, req->data, ct_in_len, req->data + ct_in_len, pt_in_len, + resp->data, &ct_out_len, &pt_out_len, &result); + } else { + tls_session_stats_t stats; + tls_get_stats(req->slot, req->tag, &stats); + result.state = stats.state; + } + } + memset(&resp->esp_err, 0, sizeof(rpc_tls_step_resp) - sizeof(rpc_header_t)); + resp->esp_err = err; + resp->state = result.state; + resp->alert_in = result.alert_in; + resp->ct_out_len = ct_out_len; + resp->pt_out_len = pt_out_len; + resp->alert_out = result.alert_out; + resp->fail_reason = result.fail_reason; + resp->verify_flags = result.verify_flags; + buf->size = sizeof(rpc_tls_step_resp) + ct_out_len + pt_out_len; + my_uart_transmit_packet(UART_CHAN, buf); +} + +void cmd_tls_close(command_buf_t *buf) +{ + rpc_tls_session_req *req = (rpc_tls_session_req *)buf->data; + rpc_tls_close_resp *resp = (rpc_tls_close_resp *)buf->data; + + // The close_notify goes to resp->data, which starts past the request + uint16_t ct_out_len = 0; + int err = ESP_ERR_INVALID_ARG; + if (buf->size >= (int)sizeof(rpc_tls_session_req)) { + err = tls_close(req->slot, req->tag, resp->data, &ct_out_len); + } + memset(&resp->esp_err, 0, sizeof(rpc_tls_close_resp) - sizeof(rpc_header_t)); + resp->esp_err = err; + resp->ct_out_len = ct_out_len; + buf->size = sizeof(rpc_tls_close_resp) + ct_out_len; + my_uart_transmit_packet(UART_CHAN, buf); +} + +void cmd_tls_stats(command_buf_t *buf) +{ + rpc_tls_session_req *req = (rpc_tls_session_req *)buf->data; + rpc_tls_stats_resp *resp = (rpc_tls_stats_resp *)buf->data; + + // Heap figures come with every reply, also when the session is gone + tls_session_stats_t stats; + int err = ESP_ERR_INVALID_ARG; + if (buf->size >= (int)sizeof(rpc_tls_session_req)) { + err = tls_get_stats(req->slot, req->tag, &stats); + } else { + tls_get_stats(TLS_SLOT_GLOBAL, 0, &stats); + } + memset(&resp->esp_err, 0, sizeof(rpc_tls_stats_resp) - sizeof(rpc_header_t)); + resp->esp_err = err; + resp->heap_free = heap_caps_get_free_size(TLS_HEAP_CAPS); + resp->heap_min = heap_caps_get_minimum_free_size(TLS_HEAP_CAPS); + resp->largest_block = heap_caps_get_largest_free_block(TLS_HEAP_CAPS); + resp->ct_in_bytes = stats.ct_in_bytes; + resp->ct_out_bytes = stats.ct_out_bytes; + resp->pt_in_bytes = stats.pt_in_bytes; + resp->pt_out_bytes = stats.pt_out_bytes; + resp->handshake_us = stats.handshake_us; + resp->tls_version = stats.tls_version; + resp->ciphersuite = stats.ciphersuite; + resp->group = stats.group; + resp->state = stats.state; + resp->sessions_open = tls_sessions_open(); + resp->stack_free = uxTaskGetStackHighWaterMark(NULL); // this runs on the TLS task + resp->esp_time = stats.esp_time; + resp->time_source = stats.time_source; + resp->entropy_source = entropy_source(); + resp->ems = stats.ems; + resp->block_max_ms = block_max_ms; + memcpy(resp->spki_sha256, stats.spki_sha256, sizeof(resp->spki_sha256)); + buf->size = sizeof(rpc_tls_stats_resp); + my_uart_transmit_packet(UART_CHAN, buf); +} + +void cmd_tls_close_all(command_buf_t *buf) +{ + rpc_espcmd_resp *resp = (rpc_espcmd_resp *)buf->data; + tls_close_all(); + resp->esp_err = ESP_OK; + buf->size = sizeof(rpc_espcmd_resp); + my_uart_transmit_packet(UART_CHAN, buf); +} + +void cmd_tls_set_ca(command_buf_t *buf) +{ + rpc_tls_set_ca_req *req = (rpc_tls_set_ca_req *)buf->data; + rpc_tls_set_ca_resp *resp = (rpc_tls_set_ca_resp *)buf->data; + + // tls_set_ca() parses the certificate before the response overwrites it + uint8_t reject = TLS_CA_REJECT_NONE; + int err = ESP_ERR_INVALID_ARG; + if ((buf->size >= (int)sizeof(rpc_tls_set_ca_req)) && (buf->size == (int)sizeof(rpc_tls_set_ca_req) + req->der_len)) { + err = tls_set_ca(req->der, req->der_len, req->ca_tag, &reject); + } else { + tls_set_ca(NULL, 0, 0, &reject); // a malformed upload still leaves no CA held + } + memset(&resp->esp_err, 0, sizeof(rpc_tls_set_ca_resp) - sizeof(rpc_header_t)); + resp->esp_err = err; + resp->reject = reject; + buf->size = sizeof(rpc_tls_set_ca_resp); + my_uart_transmit_packet(UART_CHAN, buf); +} + +// The TLS task's side: runs one TLS command and transmits its reply +void tls_serve(command_buf_t *buf) +{ + rpc_header_t *hdr = (rpc_header_t *)buf->data; + switch (hdr->command) { + case CMD_TLS_OPEN: + cmd_tls_open(buf); + break; + case CMD_TLS_STEP: + cmd_tls_step(buf); + break; + case CMD_TLS_CLOSE: + cmd_tls_close(buf); + break; + case CMD_TLS_STATS: + cmd_tls_stats(buf); + break; + case CMD_TLS_CLOSE_ALL: + cmd_tls_close_all(buf); + break; + case CMD_TLS_SET_CA: + cmd_tls_set_ca(buf); + break; + default: + cmd_not_implemented(buf); + break; + } +} + +static void tls_task(void *arg) +{ + command_buf_t *buf; + while (1) { + if (xQueueReceive(tls_queue, &buf, portMAX_DELAY) == pdTRUE) { + tls_serve(buf); + } + } +} + +// The TLS queue is full: the command's own reply shape, all zero but for ESP_ERR_TIMEOUT +static void cmd_tls_busy(command_buf_t *buf) +{ + rpc_header_t *hdr = (rpc_header_t *)buf->data; + int size; + switch (hdr->command) { + case CMD_TLS_OPEN: size = sizeof(rpc_tls_open_resp); break; + case CMD_TLS_STEP: size = sizeof(rpc_tls_step_resp); break; + case CMD_TLS_CLOSE: size = sizeof(rpc_tls_close_resp); break; + case CMD_TLS_STATS: size = sizeof(rpc_tls_stats_resp); break; + case CMD_TLS_SET_CA: size = sizeof(rpc_tls_set_ca_resp); break; + default: size = sizeof(rpc_espcmd_resp); break; + } + memset(buf->data + sizeof(rpc_header_t), 0, size - sizeof(rpc_header_t)); + ((rpc_espcmd_resp *)buf->data)->esp_err = ESP_ERR_TIMEOUT; + if (hdr->command == CMD_TLS_OPEN) { + ((rpc_tls_open_resp *)buf->data)->slot = TLS_SLOT_GLOBAL; + } else if (hdr->command == CMD_TLS_STEP) { + ((rpc_tls_step_resp *)buf->data)->alert_in = TLS_ALERT_NONE; + ((rpc_tls_step_resp *)buf->data)->alert_out = TLS_ALERT_NONE; + } + buf->size = size; + my_uart_transmit_packet(UART_CHAN, buf); +} + +// The dispatcher's side: queues the command for the TLS task, or answers it at once when the queue is full +void tls_rpc_dispatch(command_buf_t *buf) +{ + if (xQueueSend(tls_queue, &buf, 0) != pdTRUE) { + cmd_tls_busy(buf); + } +} + +// The dispatcher reports how long one command held it, in ms; TLS_STATS returns the longest +void tls_rpc_note_block(int64_t ms) +{ + if (ms > block_max_ms) { + block_max_ms = (ms > 0xFFFF) ? 0xFFFF : (uint16_t)ms; + } +} + +// TLS task on core 1, as Wi-Fi is pinned to core 0 (CONFIG_ESP_WIFI_TASK_PINNED_TO_CORE_0). It runs at +// tskIDLE_PRIORITY + 1, below the dispatch task (priority 19, also core 1), so a handshake yields to command traffic. +void tls_rpc_start(void) +{ + tls_queue = xQueueCreate(TLS_QUEUE_DEPTH, sizeof(command_buf_t *)); + xTaskCreatePinnedToCore(tls_task, "TLS", TLS_TASK_STACK, NULL, tskIDLE_PRIORITY + 1, NULL, 1); +} diff --git a/software/wifi/tls/tls_rpc.h b/software/wifi/tls/tls_rpc.h new file mode 100644 index 000000000..a6005829f --- /dev/null +++ b/software/wifi/tls/tls_rpc.h @@ -0,0 +1,24 @@ +/* tls_rpc.h: what a module firmware's dispatcher needs of the TLS commands (tls_rpc.c). + * + * The firmware that builds tls_rpc.c and tls_engine.c provides, on the include path and at link time: + * rpc_calls.h rpc_header_t and rpc_espcmd_resp, and (through it) rpc_tls.h + * my_uart.h my_uart_transmit_packet(), on UART_NUM_1 + * wifi_modem.h, sntp.h entropy_source() and entropy_source_t, and the clock the engine reads + * cmd_not_implemented() answers a command the TLS task does not know (the dispatcher's own) + * and an sdkconfig with the mbedTLS 4 / PSA configuration the engine needs. */ + +#ifndef TLS_RPC_H_ +#define TLS_RPC_H_ + +#include +#include "cmd_buffer.h" + +#define TLS_TASK_STACK 8192 // twice the stack handshakes were measured to use on the dispatcher +#define TLS_QUEUE_DEPTH 2 // one request outstanding, and a CLOSE behind a step that timed out + +void tls_rpc_start(void); // create the TLS queue and task, before the dispatcher runs +void tls_rpc_dispatch(command_buf_t *buf); // CMD_TLS_*: queue for the TLS task, or answer ESP_ERR_TIMEOUT +void tls_rpc_note_block(int64_t ms); // how long the dispatcher was held by one command +void tls_serve(command_buf_t *buf); // the TLS task's side: run one command and transmit its reply + +#endif /* TLS_RPC_H_ */ diff --git a/target/pc/linux/getrandompaths/Makefile b/target/pc/linux/getrandompaths/Makefile new file mode 100644 index 000000000..9b49fe334 --- /dev/null +++ b/target/pc/linux/getrandompaths/Makefile @@ -0,0 +1,76 @@ +# +# Host tests of the paths GET_RANDOM takes on the Ultimate and the control module that no +# other host test compiles. Each is cut out of its file as it is and built against +# stand-ins (software/test/get_random_paths): +# net_target NetworkTarget::get_random(), the GET_RANDOM case of execute() and the +# status messages, with wifi_random.cc +# isr wifi_rx_isr() from wifi_cmd.cc and DmaUART::ClearRxBuffer() from dma_uart.cc +# voltages cmd_get_voltages() from the u64ctrl module's rpc_dispatch.c +# +# make test build and run all three +# make SRC= test take the files from a copy of software/ (a mutant) +# +PATH_SW = ../../../../software +SRC ?= $(PATH_SW) +TESTDIR = $(PATH_SW)/test/get_random_paths +OUTPUT = output +RESULT = result + +CXX = g++ +CC = gcc +WARN = -Wall -Wno-unused-parameter -Wno-unused-variable -Wno-unused-function -Wno-format -Wno-unknown-warning-option + +# A function from its header line (its start, matched as text) to the first line that is "}" +FN = awk -v f="$(1)" 'index($$0, f "(") == 1 && $$0 !~ /;[[:space:]\r]*$$/ { p = 1 } p { print } p && /^\}/ { p = 0 }' $(2) + +.PHONY: all test clean + +all: $(RESULT)/net_target $(RESULT)/isr $(RESULT)/voltages + +$(OUTPUT)/net.cc: $(SRC)/io/network/network_target.cc $(SRC)/io/command_interface/command_intf.cc + @mkdir -p $(OUTPUT) + @{ echo '#include "net_env.h"'; \ + grep -E '^Message c_(message_empty|status_ok) ' $(SRC)/io/command_interface/command_intf.cc; \ + grep -E '^Message c_status_' $(SRC)/io/network/network_target.cc; \ + $(call FN,void NetworkTarget :: get_random,$(SRC)/io/network/network_target.cc); \ + echo 'void NetworkTarget :: parse_command(Message *command, Message **reply, Message **status) { execute(command, reply, status); }'; \ + echo 'void NetworkTarget :: execute(Message *command, Message **reply, Message **status)'; \ + echo '{'; echo ' switch (command->message[1]) {'; \ + awk '/case NET_CMD_GET_RANDOM:/ { p = 1 } p { print } p && /^ break;\r?$$/ { p = 0 }' $(SRC)/io/network/network_target.cc; \ + echo ' default:'; echo ' break;'; echo ' }'; echo '}'; } > $@ + @grep -q 'NetworkTarget :: get_random' $@ || { echo "getrandompaths: get_random not found"; exit 1; } + @grep -q 'case NET_CMD_GET_RANDOM:' $@ || { echo "getrandompaths: the GET_RANDOM case of execute not found"; exit 1; } + +$(RESULT)/net_target: $(OUTPUT)/net.cc $(TESTDIR)/net_target_test.cc + @mkdir -p $(RESULT) + $(CXX) -std=gnu++11 -g -O0 $(WARN) -DU64=1 -I$(TESTDIR)/stub -I$(TESTDIR) -I$(SRC)/io/network -I$(SRC)/io/wifi \ + -I$(PATH_SW)/test/wifi_random -I$(PATH_SW)/test/wifi_dedicated/stub -I$(SRC)/wifi/raw_u64/main -I$(SRC)/wifi/common -I$(SRC)/wifi/tls -I$(SRC)/io/uart \ + -o $@ $(OUTPUT)/net.cc $(TESTDIR)/net_target_test.cc $(SRC)/io/wifi/wifi_random.cc + +$(OUTPUT)/isr.cc: $(SRC)/io/wifi/wifi_cmd.cc $(SRC)/io/uart/dma_uart.cc + @mkdir -p $(OUTPUT) + @{ echo '#include "isr_env.h"'; \ + $(call FN,BaseType_t wifi_rx_isr,$(SRC)/io/wifi/wifi_cmd.cc); \ + $(call FN,void DmaUART::ClearRxBuffer,$(SRC)/io/uart/dma_uart.cc); } > $@ + @grep -q 'wifi_rx_isr' $@ && grep -q 'ClearRxBuffer' $@ || { echo "getrandompaths: isr functions not found"; exit 1; } + +$(RESULT)/isr: $(OUTPUT)/isr.cc $(TESTDIR)/isr_test.cc + @mkdir -p $(RESULT) + $(CXX) -std=gnu++11 -g -O0 $(WARN) -DU64=1 -I$(TESTDIR)/stub -I$(TESTDIR) -I$(SRC)/io/wifi -I$(SRC)/wifi/raw_u64/main -I$(SRC)/wifi/common -I$(SRC)/wifi/tls -I$(SRC)/io/uart \ + -o $@ $(OUTPUT)/isr.cc $(TESTDIR)/isr_test.cc + +$(OUTPUT)/voltages_extract.c: $(SRC)/u64ctrl/main/rpc_dispatch.c + @mkdir -p $(OUTPUT) + @{ grep -E '^#define UART_CHAN' $<; $(call FN,void cmd_get_voltages,$<); } > $@ + @grep -q 'cmd_get_voltages' $@ || { echo "getrandompaths: cmd_get_voltages not found"; exit 1; } + +$(RESULT)/voltages: $(OUTPUT)/voltages_extract.c $(TESTDIR)/voltages_test.c + @mkdir -p $(RESULT) + $(CC) -std=gnu11 -g -O0 $(WARN) -I$(OUTPUT) -I$(TESTDIR)/stub -I$(SRC)/u64ctrl/main -I$(SRC)/wifi/common \ + -o $@ $(TESTDIR)/voltages_test.c + +test: all + @$(RESULT)/net_target && $(RESULT)/isr && $(RESULT)/voltages + +clean: + @rm -rf $(OUTPUT) $(RESULT) diff --git a/target/pc/linux/radioentropy/Makefile b/target/pc/linux/radioentropy/Makefile new file mode 100644 index 000000000..1036bf3f9 --- /dev/null +++ b/target/pc/linux/radioentropy/Makefile @@ -0,0 +1,40 @@ +# Host build of radio_entropy.c, the helper that keeps the hardware RNG fed with the radio +# on or off, with wifi_radio.c that starts and stops the radio through it, against a model +# of the chip that fails the test on any call the hardware would not allow. `make test` +# builds and runs it. +PRJ = radioentropy +PATH_SW = ../../../../software + +# rpc_calls.h of raw_u64 needs lwIP's headers, which the wifi_random test stubs out +VPATH = $(PATH_SW)/wifi/common $(PATH_SW)/test/radio_entropy $(PATH_SW)/test/wifi_random \ + $(PATH_SW)/wifi/raw_u64/main $(PATH_SW)/wifi/tls $(PATH_SW)/io/uart + +CC = gcc +CFLAGS = -std=gnu11 -g -O0 -Wall -Wextra -Wno-unused-parameter -pthread \ + $(addprefix -I, $(VPATH)) + +OUTPUT = output +RESULT = result +SRCS = radio_entropy.c wifi_radio.c radio_entropy_test.c +OBJS = $(addprefix $(OUTPUT)/, $(SRCS:%.c=%.o)) + +.PHONY: all run test clean + +all: $(RESULT)/$(PRJ) + +$(OUTPUT)/%.o: %.c + @mkdir -p $(OUTPUT) + $(CC) $(CFLAGS) -c -o $@ $< + +$(RESULT)/$(PRJ): $(OBJS) + @mkdir -p $(RESULT) + $(CC) $(CFLAGS) -o $@ $(OBJS) + +run: all + @$(RESULT)/$(PRJ) + + +test: run + +clean: + @rm -rf $(OUTPUT) $(RESULT) diff --git a/target/pc/linux/recoverymanifest/Makefile b/target/pc/linux/recoverymanifest/Makefile index aad0925ec..ee64a7fbb 100644 --- a/target/pc/linux/recoverymanifest/Makefile +++ b/target/pc/linux/recoverymanifest/Makefile @@ -1,7 +1,9 @@ # # Host build of the recovery manifest reader of the control module. The -# signature check is built against the mbedtls that ESP-IDF ships, compiled -# here for the host, so the test needs IDF_PATH but no ESP32 toolchain. +# signature check is built against the TF-PSA-Crypto that ESP-IDF 6 ships +# (mbedTLS 4), compiled here for the host, so the test needs IDF_PATH but no +# ESP32 toolchain. The control module is built against that same library, so +# this must run with an ESP-IDF 6 checkout, not the 5.3.1 of my_docker_image. # # make build # make test build and run @@ -12,17 +14,17 @@ OUTPUT = output PATH_SW = ../../../../software IDF_PATH ?= $(HOME)/esp/esp-idf -MBEDTLS = $(IDF_PATH)/components/mbedtls/mbedtls -LIBMBED = $(OUTPUT)/mbedtls/library/libmbedcrypto.a +TFPSA = $(IDF_PATH)/components/mbedtls/mbedtls/tf-psa-crypto +LIBMBED = $(OUTPUT)/tfpsa/core/libtfpsacrypto.a VPATH = $(PATH_SW)/u64ctrl/main $(PATH_SW)/test/recovery_manifest CC = gcc COPTIONS = -std=c99 -g -O0 -Wall -Wextra -Wno-unused-parameter \ -DVECTORS_DIR=\"$(abspath $(PATH_SW)/test/recovery_manifest/vectors)\" \ - $(addprefix -I, $(VPATH)) -I$(MBEDTLS)/include + $(addprefix -I, $(VPATH)) -I$(PATH_SW)/test/stubs/esp -I$(TFPSA)/include -I$(TFPSA)/drivers/builtin/include -SRCS_C = recovery_manifest.c recovery_verify.c recovery_manifest_test.c +SRCS_C = recovery_manifest.c recovery_verify.c recovery_trust.c recovery_manifest_test.c OBJS = $(addprefix $(OUTPUT)/, $(SRCS_C:%.c=%.o)) .PHONY: all test clean @@ -30,10 +32,15 @@ OBJS = $(addprefix $(OUTPUT)/, $(SRCS_C:%.c=%.o)) all: $(RESULT)/$(PRJ) $(LIBMBED): - @test -f $(MBEDTLS)/CMakeLists.txt || { echo "mbedtls not found; set IDF_PATH to an ESP-IDF checkout"; exit 2; } - @cmake -S $(MBEDTLS) -B $(OUTPUT)/mbedtls -DENABLE_TESTING=OFF -DENABLE_PROGRAMS=OFF \ - -DCMAKE_BUILD_TYPE=Release >/dev/null - @cmake --build $(OUTPUT)/mbedtls --target mbedcrypto -j8 >/dev/null + @test -f $(TFPSA)/CMakeLists.txt || { echo "TF-PSA-Crypto not found; set IDF_PATH to an ESP-IDF 6 checkout"; exit 2; } + @# This ESP-IDF's bignum.c and ecp.c include mbedtls/bignum.h and mbedtls/ecp.h, + @# which only ESP-IDF's own port provides; the shims stand in for it. The + @# pre-generated sources stand in for GEN_FILES, which needs python's jsonschema. + @mkdir -p $(OUTPUT)/shim/mbedtls + @for h in bignum ecp; do echo "#include \"mbedtls/private/$$h.h\"" > $(OUTPUT)/shim/mbedtls/$$h.h; done + @cmake -S $(TFPSA) -B $(OUTPUT)/tfpsa -DENABLE_TESTING=OFF -DENABLE_PROGRAMS=OFF -DGEN_FILES=OFF \ + -DCMAKE_C_FLAGS=-I$(abspath $(OUTPUT))/shim -DCMAKE_BUILD_TYPE=Release >/dev/null + @cmake --build $(OUTPUT)/tfpsa --target tfpsacrypto -j8 >/dev/null $(OUTPUT)/%.o: %.c $(LIBMBED) @mkdir -p $(OUTPUT) @@ -41,7 +48,7 @@ $(OUTPUT)/%.o: %.c $(LIBMBED) $(RESULT)/$(PRJ): $(OBJS) $(LIBMBED) @mkdir -p $(RESULT) - $(CC) -o $@ $(OBJS) $(LIBMBED) + $(CC) -o $@ $(OBJS) $(LIBMBED) -Wl,--wrap=psa_crypto_init -Wl,--wrap=psa_hash_update -Wl,--wrap=psa_hash_finish test: all @$(RESULT)/$(PRJ) diff --git a/target/pc/linux/tlsguard/Makefile b/target/pc/linux/tlsguard/Makefile new file mode 100644 index 000000000..6075fdfdc --- /dev/null +++ b/target/pc/linux/tlsguard/Makefile @@ -0,0 +1,79 @@ +# Host test of the TLS version-confusion guard in software/wifi/tls/tls_engine.c (Mbed TLS advisory 2026-11), device-free. +# tls_engine.c is compiled as is, against Mbed TLS 4.1.1 (the ESP-IDF v6.1.1 submodule) with its default config; ESP-IDF, +# FreeRTOS and the radio entropy gate are stand-ins (software/test/tls_engine/stub). Not part of CI: it needs the IDF image. +# +# How to run (from the repository root; Docker must be able to mount the paths, so use a directory under $HOME): +# LIB=$HOME/tlsguard-lib +# target/pc/linux/tlsguard/build-mbedtls.sh $LIB/411 # Mbed TLS 4.1.1 as in the IDF v6.1.1 image +# MBEDTLS_PATCH= target/pc/linux/tlsguard/build-mbedtls.sh $LIB/fixed # optional: a 4.1.x with the upstream fix +# docker run --rm -v "$PWD:/w" -v "$LIB/411:/build" espressif/idf:v6.1.1 bash -c \ +# 'cd /w/target/pc/linux/tlsguard && make MBEDTLS_SRC=/opt/esp/idf/components/mbedtls/mbedtls MBEDTLS_LIB=/build/libmbed.a test red' +# (MBEDTLS_SRC is the source inside the image, for the headers; MBEDTLS_LIB is the library built above. For the fixed +# library mount $LIB/fixed on /build instead; the headers are the same.) +# +# make test the guard test (default mode) on the tree's engine, then the "barrier" mode on a copy of the engine with the +# guard disabled (the second barrier). Exit 0 only if both pass, on 4.1.1 and on the fixed library alike. +# make red the guard test on that guard-disabled copy: on 4.1.1 it must FAIL (the guard is what stops the attack), and +# make red exits non-zero if it passes. On the fixed library the library refuses before the guard is reached, +# so red is not applicable; it says so and exits 0. +# +# test_key.h and test_cert.h are a throwaway test key (EC P-256, PKCS#8 DER) and its self-signed certificate; the key +# protects nothing. Generated with: +# openssl ecparam -name prime256v1 -genkey -noout | openssl pkcs8 -topk8 -nocrypt -outform der -out key.der +# openssl req -new -x509 -key key.der -keyform der -subj "/CN=tlsguard test server" -days 36500 -sha256 -outform der -out cert.der +# xxd -i key.der | sed 's/unsigned char key_der/static const unsigned char test_key_der/' > test_key.h +# xxd -i cert.der | sed 's/unsigned char cert_der/static const unsigned char test_cert_der/' > test_cert.h +OUTPUT = output +RESULT = result + +PATH_SW = ../../../../software +TEST = $(PATH_SW)/test/tls_engine +TLS_DIR = $(PATH_SW)/wifi/tls + +MBEDTLS_SRC ?= mbedtls +MBEDTLS_LIB ?= libmbed.a +ENGINE_SRC ?= $(abspath $(TLS_DIR)/tls_engine.c) + +MBED_INC = -I$(MBEDTLS_SRC)/include -I$(MBEDTLS_SRC)/library -I$(MBEDTLS_SRC)/tf-psa-crypto/include \ + -I$(MBEDTLS_SRC)/tf-psa-crypto/core -I$(MBEDTLS_SRC)/tf-psa-crypto/extras \ + -I$(MBEDTLS_SRC)/tf-psa-crypto/utilities -I$(MBEDTLS_SRC)/tf-psa-crypto/platform \ + -I$(MBEDTLS_SRC)/tf-psa-crypto/dispatch -I$(MBEDTLS_SRC)/tf-psa-crypto/drivers/builtin/include \ + -I$(MBEDTLS_SRC)/tf-psa-crypto/drivers/builtin/src +CFLAGS = -std=gnu11 -DMBEDTLS_USER_CONFIG_FILE=\"tlsguard_mbedtls_config.h\" -g -O0 -Wall -Wextra -Wno-unused-parameter -Wno-sign-compare -I$(TEST)/stub -I$(TEST) -I$(TLS_DIR) $(MBED_INC) + +# The guard is the TLS 1.2 ServerHello branch of tls_note_handshake() that tests tls_version; the red copy makes it unreachable. +GUARD_LINE = } else if (s->ssl.tls_version != MBEDTLS_SSL_VERSION_TLS1_2) { + +.PHONY: all test noguard red clean + +all: $(RESULT)/tlsguard + +$(RESULT)/tlsguard: $(TEST)/tls_guard_test.c $(TEST)/stub_rng_gate.c $(ENGINE_SRC) $(MBEDTLS_LIB) + @mkdir -p $(RESULT) + $(CC) $(CFLAGS) -DTLS_ENGINE_SRC='"$(ENGINE_SRC)"' -o $@ $(TEST)/tls_guard_test.c $(TEST)/stub_rng_gate.c $(MBEDTLS_LIB) + +test: all noguard + ./$(RESULT)/tlsguard + ./$(OUTPUT)/red/tlsguard barrier + +$(OUTPUT)/tls_engine_noguard.c: $(TLS_DIR)/tls_engine.c + @mkdir -p $(OUTPUT) + @test `grep -cF '$(GUARD_LINE)' $<` = 1 || { echo "guard line not found exactly once"; exit 3; } + sed 's/} else if (s->ssl.tls_version != MBEDTLS_SSL_VERSION_TLS1_2) {/} else if (0 \&\& s->ssl.tls_version != MBEDTLS_SSL_VERSION_TLS1_2) {/' $< > $@ + @test `grep -cF 'else if (0 && s->ssl.tls_version' $@` = 1 || { echo "red copy not made"; exit 3; } + +noguard: $(OUTPUT)/tls_engine_noguard.c + $(MAKE) ENGINE_SRC=$(abspath $<) RESULT=$(OUTPUT)/red all + +# RED must be red: the guard-disabled build has to fail the attack checks. If the library refuses the ServerHello itself +# (a fixed Mbed TLS) the guard is never reached and the comparison means nothing: say so. +red: noguard + @./$(OUTPUT)/red/tlsguard > $(OUTPUT)/red.log; rc=$$?; cat $(OUTPUT)/red.log; \ + if grep -q '^case: library refuses first' $(OUTPUT)/red.log; then \ + echo "RED: not applicable: library refuses first (the guard is not reached on this Mbed TLS)"; exit 0; \ + elif [ $$rc -eq 0 ]; then \ + echo "RED IS NOT RED: the guard-disabled build passed on an Mbed TLS that accepts the ServerHello"; exit 1; \ + else echo "RED is red as expected: the guard-disabled build fails ($$rc)"; exit 0; fi + +clean: + rm -rf $(OUTPUT) $(RESULT) diff --git a/target/pc/linux/tlsguard/build-mbedtls.sh b/target/pc/linux/tlsguard/build-mbedtls.sh new file mode 100755 index 000000000..2e47e78e9 --- /dev/null +++ b/target/pc/linux/tlsguard/build-mbedtls.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# Builds the Mbed TLS the test links against: the ESP-IDF v6.1.1 submodule (4.1.1 plus 18 commits), default config but for +# tlsguard_mbedtls_config.h, as one static lib. Runs in the espressif/idf:v6.1.1 image, which carries the source. +# The submodule copy has no top-level framework/ dir, so upstream's CMake cannot run: the sources are compiled directly. +# usage: [MBEDTLS_PATCH=] build-mbedtls.sh writes /libmbed.a +# With MBEDTLS_PATCH (a unified diff, -p1 against the Mbed TLS tree) the build is of a scratch copy of the tree with the +# diff applied, e.g. a fixed 4.1.x, so the test can be run against a library that refuses the ServerHello itself. +# Any compile or patch error fails the script. +set -e +OUT=$(mkdir -p "$1" && cd "$1" && pwd) +HERE=$(cd "$(dirname "$0")" && pwd) +CFG=$(cd "$HERE/../../../../software/test/tls_engine" && pwd) +PATCH_MOUNT=() +PATCH_PATH= +if [ -n "$MBEDTLS_PATCH" ]; then + PATCH_MOUNT=(-v "$(cd "$(dirname "$MBEDTLS_PATCH")" && pwd)/$(basename "$MBEDTLS_PATCH"):/patch.diff:ro") + PATCH_PATH=/patch.diff +fi +docker run --rm --name "tlsguard2-mbedbuild-$$" -e PATCH_PATH="$PATCH_PATH" "${PATCH_MOUNT[@]}" \ + -v "$CFG:/cfg:ro" -v "$OUT:/build" espressif/idf:v6.1.1 bash -c ' + set -e + SRC=/opt/esp/idf/components/mbedtls/mbedtls + if [ -n "$PATCH_PATH" ]; then rm -rf /tmp/src && cp -r $SRC /tmp/src && SRC=/tmp/src && (cd $SRC && patch -p1 < $PATCH_PATH); fi + cd $SRC + INC="-Iinclude -Itf-psa-crypto/dispatch -Itf-psa-crypto/platform -Ilibrary -Itf-psa-crypto/extras -Itf-psa-crypto/include -Itf-psa-crypto/core -Itf-psa-crypto/utilities -Itf-psa-crypto/drivers/builtin/include -Itf-psa-crypto/drivers/builtin/src -Itf-psa-crypto/drivers/everest/include -I/cfg -I/build/shim" + mkdir -p /build/shim/mbedtls /build/obj + echo "/* the tree names these headers in bignum.c and ecp.c and does not ship them */" | tee /build/shim/mbedtls/bignum.h > /build/shim/mbedtls/ecp.h + rm -f /build/obj/*.o /build/libmbed.a + ls library/*.c tf-psa-crypto/extras/*.c tf-psa-crypto/utilities/*.c tf-psa-crypto/platform/*.c tf-psa-crypto/core/*.c tf-psa-crypto/drivers/builtin/src/*.c | + xargs -P 4 -I{} sh -c "gcc -std=c99 -g -O0 -w -D_DEFAULT_SOURCE -DMBEDTLS_USER_CONFIG_FILE=\\\"tlsguard_mbedtls_config.h\\\" $INC -c {} -o /build/obj/\$(echo {} | tr / _).o" + ar rcs /build/libmbed.a /build/obj/*.o; ls -la /build/libmbed.a' diff --git a/target/pc/linux/wifidedicated/Makefile b/target/pc/linux/wifidedicated/Makefile new file mode 100644 index 000000000..b915358f3 --- /dev/null +++ b/target/pc/linux/wifidedicated/Makefile @@ -0,0 +1,57 @@ +# Host build of the check on the WiFi module's dedicated channel and GET_RANDOM, +# its first user, against stand-ins. `make test` builds and runs it. +PRJ = wifidedicated +PATH_SW = ../../../../software +TEST = $(PATH_SW)/test/wifi_dedicated + +# `make test` runs it against each module's headers: raw_u64 (the U64) and +# u64ctrl (the C64 Ultimate, U64=2). `make U64=2 run` is the second alone. +U64 ?= 1 +ifeq ($(U64),2) +MODULE = $(PATH_SW)/u64ctrl/main +RESULT = result/u64ctrl +OUTPUT = output/u64ctrl +else +MODULE = $(PATH_SW)/wifi/raw_u64/main +RESULT = result +OUTPUT = output +endif + +VPATH = $(TEST)/stub $(TEST) $(PATH_SW)/test/wifi_random $(PATH_SW)/io/wifi $(PATH_SW)/io/uart \ + $(MODULE) $(PATH_SW)/wifi/common $(PATH_SW)/wifi/tls + +CXX = g++ +CPPOPTIONS = -std=gnu++11 -g -O0 -Wall -Wextra -Wno-unused-parameter -DNIOS=1 -DU64=$(U64) \ + $(addprefix -I, $(VPATH)) + +SRCS_CC = wifi_dedicated_test.cc check.cc world.cc wifi_dedicated.cc wifi_random.cc +OBJS = $(addprefix $(OUTPUT)/, $(SRCS_CC:%.cc=%.o)) + +.PHONY: all run test clean + +all: $(RESULT)/$(PRJ) + +$(OUTPUT)/%.o: %.cc + @mkdir -p $(OUTPUT) + $(CXX) $(CPPOPTIONS) -c -o $@ $< + +# Compiled from a copy, so that its "wifi_cmd.h" is the stand-in rather than +# the real header next to it. +$(OUTPUT)/wifi_dedicated.o: $(PATH_SW)/io/wifi/wifi_dedicated.cc + @mkdir -p $(OUTPUT) + cp $< $(OUTPUT)/wifi_dedicated.cc + $(CXX) $(CPPOPTIONS) -c -o $@ $(OUTPUT)/wifi_dedicated.cc + +$(RESULT)/$(PRJ): $(OBJS) + @mkdir -p $(RESULT) + $(CXX) -o $@ $(OBJS) + +run: all + @$(RESULT)/$(PRJ) + +test: + @$(MAKE) --no-print-directory run + @$(MAKE) --no-print-directory U64=2 run + +clean: + @rm -rf $(OUTPUT) $(RESULT) diff --git a/target/pc/linux/wifirandom/Makefile b/target/pc/linux/wifirandom/Makefile new file mode 100644 index 000000000..168520bd8 --- /dev/null +++ b/target/pc/linux/wifirandom/Makefile @@ -0,0 +1,48 @@ +# Host build of the check the Nios applies to the WiFi module's answer to +# GET_RANDOM, with lwIP's headers stubbed out. `make test` builds and runs it +# against each module's headers: raw_u64 (the U64) and u64ctrl (the C64 Ultimate, +# U64=2). `make U64=2 run` is the second alone. +PRJ = wifirandom +PATH_SW = ../../../../software + +U64 ?= 1 +ifeq ($(U64),2) +MODULE = $(PATH_SW)/u64ctrl/main +RESULT = result/u64ctrl +OUTPUT = output/u64ctrl +else +MODULE = $(PATH_SW)/wifi/raw_u64/main +RESULT = result +OUTPUT = output +endif + +VPATH = $(PATH_SW)/io/wifi $(MODULE) $(PATH_SW)/wifi/common $(PATH_SW)/wifi/tls $(PATH_SW)/io/uart $(PATH_SW)/test/wifi_random + +CXX = g++ +CPPOPTIONS = -std=gnu++11 -g -O0 -Wall -Wextra -Wno-unused-parameter -DU64=$(U64) \ + $(addprefix -I, $(VPATH)) + +SRCS_CC = wifi_random.cc wifi_random_test.cc +OBJS = $(addprefix $(OUTPUT)/, $(SRCS_CC:%.cc=%.o)) + +.PHONY: all run test clean + +all: $(RESULT)/$(PRJ) + +$(OUTPUT)/%.o: %.cc + @mkdir -p $(OUTPUT) + $(CXX) $(CPPOPTIONS) -c -o $@ $< + +$(RESULT)/$(PRJ): $(OBJS) + @mkdir -p $(RESULT) + $(CXX) -o $@ $(OBJS) + +run: all + @$(RESULT)/$(PRJ) + +test: + @$(MAKE) --no-print-directory run + @$(MAKE) --no-print-directory U64=2 run + +clean: + @rm -rf $(OUTPUT) $(RESULT) diff --git a/target/pc/linux/wifireply/Makefile b/target/pc/linux/wifireply/Makefile index d025ea974..d24f6a0d1 100644 --- a/target/pc/linux/wifireply/Makefile +++ b/target/pc/linux/wifireply/Makefile @@ -22,7 +22,8 @@ COPTIONS = -std=c99 -g -O0 -Wall -Wextra -Wno-unused-parameter \ CXX = g++ CXXOPTIONS = -std=c++11 -g -O0 -w -DRISCV=1 -DU64=2 -I$(STUBS) $(addprefix -I, $(VPATH)) \ - -I$(PATH_SW)/io/uart -I$(PATH_SW)/u64ctrl/main -I$(PATH_SW)/system + -I$(PATH_SW)/io/uart -I$(PATH_SW)/u64ctrl/main -I$(PATH_SW)/system \ + -I$(PATH_SW)/wifi/common SRCS_C = wifi_reply_test.c OBJS = $(addprefix $(OUTPUT)/, $(SRCS_C:%.c=%.o)) diff --git a/target/pc/linux/wifitls/Makefile b/target/pc/linux/wifitls/Makefile new file mode 100644 index 000000000..8220f4047 --- /dev/null +++ b/target/pc/linux/wifitls/Makefile @@ -0,0 +1,70 @@ +# Host build of the checks on the TLS calls to the WiFi module, on the channel they use (wifi_dedicated.cc) +# and on the network target's TLS commands; FreeRTOS, the UART, lwIP and the module are stand-ins. +# make (build), make test (build and run) +RESULT = result +OUTPUT = output + +PATH_SW = ../../../../software +TEST = $(PATH_SW)/test/wifi_tls + +VPATH = $(TEST)/stub $(TEST) $(PATH_SW)/io/wifi $(PATH_SW)/io/uart $(PATH_SW)/wifi/raw_u64/main $(PATH_SW)/wifi/common $(PATH_SW)/wifi/tls + +CXX = g++ +CPPOPTIONS = -std=gnu++11 -g -O0 -Wall -Wextra -Wno-unused-parameter -DNIOS=1 -DU64=1 \ + $(addprefix -I, $(VPATH)) + +TLS_SRCS = wifi_tls_test.cc world.cc wifi_tls.cc wifi_dedicated.cc wifi_random.cc +TLS_OBJS = $(addprefix $(OUTPUT)/tls/, $(TLS_SRCS:%.cc=%.o)) + +# The network target's sources, which a red run can point at another tree. +NET_DIR = $(PATH_SW)/io/network +NET_PATH = $(TEST)/netstub $(TEST)/stub $(NET_DIR) $(PATH_SW)/io/wifi $(PATH_SW)/io/command_interface $(PATH_SW)/network +NET_OPTIONS = -std=gnu++11 -g -O0 -Wall -Wextra -Wno-unused-parameter -Wno-deprecated-declarations -DNIOS=1 -DU64=1 $(addprefix -I, $(NET_PATH)) +NET_SRCS = net_tls_test.cc net_world.cc ip4addr_aton.cc +NET_OBJS = $(addprefix $(OUTPUT)/net/, $(NET_SRCS:%.cc=%.o)) $(OUTPUT)/net/network_target.o $(OUTPUT)/net/network_target_tls.o $(OUTPUT)/net/wifi_random.o + +.PHONY: all test clean + +all: $(RESULT)/wifitls $(RESULT)/nettls + +$(OUTPUT)/tls/%.o: %.cc + @mkdir -p $(OUTPUT)/tls + $(CXX) $(CPPOPTIONS) -c -o $@ $< + +# wifi_dedicated.cc includes "wifi_cmd.h", which the compiler looks for next to +# the source before anywhere else. A copy compiled from here finds the +# stand-in instead; it is the same file, byte for byte. +$(OUTPUT)/tls/wifi_dedicated.o: $(PATH_SW)/io/wifi/wifi_dedicated.cc + @mkdir -p $(OUTPUT)/tls + cp $< $(OUTPUT)/tls/wifi_dedicated.cc + $(CXX) $(CPPOPTIONS) -c -o $@ $(OUTPUT)/tls/wifi_dedicated.cc + +$(OUTPUT)/net/wifi_random.o: $(PATH_SW)/io/wifi/wifi_random.cc + @mkdir -p $(OUTPUT)/net + $(CXX) $(NET_OPTIONS) $(addprefix -I, $(PATH_SW)/wifi/raw_u64/main $(PATH_SW)/wifi/common $(PATH_SW)/wifi/tls $(PATH_SW)/io/uart) -c -o $@ $< + +$(OUTPUT)/net/%.o: $(TEST)/%.cc + @mkdir -p $(OUTPUT)/net + $(CXX) $(NET_OPTIONS) -c -o $@ $< + +# Compiled from a copy, so that its includes find the stand-ins rather than +# the headers next to it (network_interface.h). +$(OUTPUT)/net/network_target.o $(OUTPUT)/net/network_target_tls.o: $(OUTPUT)/net/%.o: $(NET_DIR)/%.cc $(NET_DIR)/network_target.h + @mkdir -p $(OUTPUT)/net + cp $< $(OUTPUT)/net/$*.cc + $(CXX) $(NET_OPTIONS) -c -o $@ $(OUTPUT)/net/$*.cc + +$(RESULT)/wifitls: $(TLS_OBJS) + @mkdir -p $(RESULT) + $(CXX) -o $@ $(TLS_OBJS) + +$(RESULT)/nettls: $(NET_OBJS) + @mkdir -p $(RESULT) + $(CXX) -o $@ $(NET_OBJS) + +test: all + @$(RESULT)/wifitls + @$(RESULT)/nettls + +clean: + @rm -rf $(OUTPUT) $(RESULT) diff --git a/target/u2/microblaze/mb_ultimate/Makefile b/target/u2/microblaze/mb_ultimate/Makefile index 66960981b..7ca510212 100644 --- a/target/u2/microblaze/mb_ultimate/Makefile +++ b/target/u2/microblaze/mb_ultimate/Makefile @@ -117,6 +117,7 @@ SRCS_CC = small_printf.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ filetype_tap.cc \ socket_stream.cc \ diff --git a/target/u2/riscv/ultimate/Makefile b/target/u2/riscv/ultimate/Makefile index 478054a34..a2a7b3eb0 100755 --- a/target/u2/riscv/ultimate/Makefile +++ b/target/u2/riscv/ultimate/Makefile @@ -131,6 +131,7 @@ SRCS_CC = small_printf.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ filetype_tap.cc \ socket_stream.cc \ diff --git a/target/u2plus/nios/ultimate/Makefile b/target/u2plus/nios/ultimate/Makefile index 8ed0203b1..fedfc561a 100755 --- a/target/u2plus/nios/ultimate/Makefile +++ b/target/u2plus/nios/ultimate/Makefile @@ -140,6 +140,7 @@ SRCS_CC = u2p_init.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ filetype_tap.cc \ socket_stream.cc \ diff --git a/target/u2plus_L/riscv/ultimate/Makefile b/target/u2plus_L/riscv/ultimate/Makefile index 5a8859e0f..32aa3e6da 100755 --- a/target/u2plus_L/riscv/ultimate/Makefile +++ b/target/u2plus_L/riscv/ultimate/Makefile @@ -145,6 +145,7 @@ SRCS_CC = u2pl_init.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ filetype_tap.cc \ socket_stream.cc \ diff --git a/target/u64/nios2/ultimate/Makefile b/target/u64/nios2/ultimate/Makefile index 58d8b14d5..99dd885aa 100755 --- a/target/u64/nios2/ultimate/Makefile +++ b/target/u64/nios2/ultimate/Makefile @@ -149,6 +149,7 @@ SRCS_CC = u2p_init.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ filetype_tap.cc \ socket_stream.cc \ @@ -164,6 +165,9 @@ SRCS_CC = u2p_init.cc \ esp32.cc \ wifi.cc \ wifi_cmd.cc \ + wifi_random.cc \ + wifi_dedicated.cc \ + wifi_tls.cc \ acia.cc \ modem.cc \ listener_socket.cc \ @@ -229,6 +233,8 @@ VPATH += $(BSP)/HAL/inc VPATH += $(BSP)/drivers/inc VPATH += $(PATH_SW)/6502/sidcrt/target VPATH += $(PATH_SW)/wifi/raw_u64/main +VPATH += $(PATH_SW)/wifi/common +VPATH += $(PATH_SW)/wifi/tls # sock_echo.c \ # sys_calls.cc \ diff --git a/target/u64/nios2/updater/Makefile b/target/u64/nios2/updater/Makefile index 338210f92..cdef8b0a2 100755 --- a/target/u64/nios2/updater/Makefile +++ b/target/u64/nios2/updater/Makefile @@ -101,6 +101,8 @@ VPATH += $(PATH_SW)/u64 VPATH += $(PATH_SW)/../html VPATH += $(PATH_SW)/../doc/api VPATH += $(PATH_SW)/wifi/raw_u64/main +VPATH += $(PATH_SW)/wifi/common +VPATH += $(PATH_SW)/wifi/tls VPATH += $(PATH_SW)/wifi/raw_u64/build/bootloader VPATH += $(PATH_SW)/wifi/raw_u64/build/partition_table VPATH += $(PATH_SW)/wifi/raw_u64/build diff --git a/target/u64/riscv/ultimate/Makefile b/target/u64/riscv/ultimate/Makefile index 742fceaae..1b4154a2d 100755 --- a/target/u64/riscv/ultimate/Makefile +++ b/target/u64/riscv/ultimate/Makefile @@ -138,6 +138,7 @@ SRCS_CC = u2p_init.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ softiec_target.cc \ iec.cc \ diff --git a/target/u64ii/riscv/factorytest/Makefile b/target/u64ii/riscv/factorytest/Makefile index 253fc33b6..809d95a60 100755 --- a/target/u64ii/riscv/factorytest/Makefile +++ b/target/u64ii/riscv/factorytest/Makefile @@ -103,6 +103,7 @@ VPATH += $(PATH_SW)/portable/riscv VPATH += $(PATH_SW)/6502/sidcrt/target VPATH += $(PATH_SW)/u64 VPATH += $(PATH_SW)/u64ctrl/main +VPATH += $(PATH_SW)/wifi/common VPATH += $(PATH_SW)/application/u64ii_tester diff --git a/target/u64ii/riscv/ultimate/Makefile b/target/u64ii/riscv/ultimate/Makefile index 045eb4ab8..1adbf1277 100755 --- a/target/u64ii/riscv/ultimate/Makefile +++ b/target/u64ii/riscv/ultimate/Makefile @@ -154,6 +154,7 @@ SRCS_CC = u64ii_init.cc \ command_intf.cc \ dos.cc \ network_target.cc \ + network_target_tls.cc \ control_target.cc \ filetype_tap.cc \ socket_stream.cc \ @@ -200,6 +201,8 @@ SRCS_CC = u64ii_init.cc \ esp32.cc \ network_esp32.cc \ wifi_cmd.cc \ + wifi_random.cc \ + wifi_dedicated.cc \ wifi.cc \ sntp_time.cc \ $(PRJ).cc @@ -229,6 +232,7 @@ VPATH += $(PATH_SW)/6502/sidcrt/target VPATH += $(PATH_SW)/u64ii VPATH += $(PATH_SW)/u64 VPATH += $(PATH_SW)/u64ctrl/main +VPATH += $(PATH_SW)/wifi/common SRCS_ASM = diff --git a/target/u64ii/riscv/update/Makefile b/target/u64ii/riscv/update/Makefile index 04fd855ef..99ccc9c52 100755 --- a/target/u64ii/riscv/update/Makefile +++ b/target/u64ii/riscv/update/Makefile @@ -128,6 +128,7 @@ VPATH += $(PATH_SW)/application/update_u2p VPATH += $(PATH_SW)/../html VPATH += $(PATH_SW)/../doc/api VPATH += $(PATH_SW)/u64ctrl/main +VPATH += $(PATH_SW)/wifi/common VPATH += $(PATH_SW)/u64ctrl/build/bootloader VPATH += $(PATH_SW)/u64ctrl/build/partition_table VPATH += $(PATH_SW)/u64ctrl/build diff --git a/tests/e2e/io/command_interface/.gitignore b/tests/e2e/io/command_interface/.gitignore new file mode 100644 index 000000000..4cb6d85a4 --- /dev/null +++ b/tests/e2e/io/command_interface/.gitignore @@ -0,0 +1,2 @@ +# net_tls_test.py results (run.json, wire.jsonl) when --results is not given +.net_tls_results/ diff --git a/tests/e2e/io/command_interface/internet_hosts.json b/tests/e2e/io/command_interface/internet_hosts.json new file mode 100644 index 000000000..1e70b2501 --- /dev/null +++ b/tests/e2e/io/command_interface/internet_hosts.json @@ -0,0 +1,17 @@ +{ + "comment": "The default real hosts for the BUNDLE scenario that talks to the Internet; \"required\" hosts must answer. recorded_top is the topmost certificate each host sent when it was added, with its issuer and fingerprint. NET_TLS_INTERNET_HOSTS=h1,h2,... replaces this list for a run.", + "hosts": [ + {"id": "H1", "host": "www.google.com", "required": true, + "recorded_top": "CN=GTS Root R4,O=Google Trust Services LLC,C=US", + "recorded_top_issuer": "CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE", + "recorded_top_fp": "76b27b80a58027dc3cf1da68dac17010ed93997d0b603e2fadbe85012493b5a7"}, + {"id": "H2", "host": "wikipedia.org", "required": true, + "recorded_top": "CN=ISRG Root X2,O=Internet Security Research Group,C=US", + "recorded_top_issuer": "CN=ISRG Root X1,O=Internet Security Research Group,C=US", + "recorded_top_fp": "ee5f7abd6981bb0255632cd8f49283451b4b18844d12040b44ee00f07b8fe2c6"}, + {"id": "H3", "host": "example.com", "required": false, + "recorded_top": "CN=SSL.com TLS ECC Root CA 2022,O=SSL Corporation,C=US", + "recorded_top_issuer": "CN=AAA Certificate Services,O=Comodo CA Limited,L=Salford,ST=Greater Manchester,C=GB", + "recorded_top_fp": "ba06d3d3e348fce7478cc84b422d0e638e9e221ef1a0b53adc14cc70e04b8ab8"} + ] +} diff --git a/tests/e2e/io/command_interface/net_target_test.py b/tests/e2e/io/command_interface/net_target_test.py index 17ed5a99f..001b0d622 100644 --- a/tests/e2e/io/command_interface/net_target_test.py +++ b/tests/e2e/io/command_interface/net_target_test.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # E2E: Verifies UCI network target socket reads: length handling and datagram delivery. -"""End-to-end check of the UCI network target's READ_SOCKET command. +"""End-to-end check of the UCI network target's READ_SOCKET and GET_RANDOM commands. Regression guard for GideonZ/1541ultimate#802, reported as "a maxlen above 512 silently returns no data". Everything here was measured on real hardware @@ -40,15 +40,38 @@ suite, and every property under test is visible at 64 bytes as clearly as at 894. +GET_RANDOM hands a C64 program random bytes drawn on the ESP32. Its scenarios +need no network peer except the one that interleaves it with a socket. What +they can check about the bytes is that each reply has the length asked for and +that replies are not stuck, zeroed or patterned; they cannot check that a real +entropy source is behind them, since the output of a post-processed RNG looks +the same either way. Whether bytes are owed at all is taken from the device's +own report, not from GET_RANDOM's answer: an Ultimate 64 or Ultimate 64 +Elite owes them, once "WiFi Enabled" is set and it reports a wifi_mac in +/v1/info. An Ultimate 64-II or C64 Ultimate (the Elite II and the C64 Ultimate) owes them as +soon as its module reports a wifi_mac. Both owe them with the radio off too: the +module then draws them from its SAR ADC entropy source. get-random-radio-off +checks that on the products with the setting, by turning the radio off for the +scenario and on again after it; the Ultimate 64-II has no setting the suite can +switch (its menu's Enable and Disable are actions), so there it skips; it also +skips where the suite reaches the device over WiFi. Any other product has to refuse. + Supported on any Ultimate whose FPGA provides the command interface. The suite -enables the "Command Interface" setting and restores it on exit. +enables the "Command Interface" setting and restores it on exit. On an Ultimate +64 or Ultimate 64 Elite it also sets "WiFi Enabled" and restores the stored +setting on exit; a change of the setting turns the module's radio on or off at +once. An Ultimate 64-II is left as it is. The suite must reach the device over +Ethernet: get-random-radio-off turns the WiFi radio off. """ import argparse +import functools +import math import socket import sys import time from pathlib import Path +from typing import NamedTuple # The one stanza that puts the shared library on sys.path; see tests/lib/bootstrap.py. sys.path.insert(0, str(next(p for p in Path(__file__).resolve().parents @@ -58,11 +81,10 @@ import targets # noqa: E402 from api import UltimateApi # noqa: E402 from report import ( # noqa: E402 - FAIL, Failure, OK, SKIP, check, check_ok, check_skip, check_start, detail, + FAIL, Failure, OK, SKIP, check, check_fail, check_ok, check_skip, check_start, detail, format_exception, section, suite_fail, suite_ok, warn) from uci import ( # noqa: E402 - MAX_BLOCK_BYTES, REPLY_QUEUE_BYTES, TARGET_NETWORK, Uci, Wedged, - interface_present) + MAX_BLOCK_BYTES, REPLY_QUEUE_BYTES, TARGET_NETWORK, Uci, Wedged, interface_present) from uci_native import NativeUci # noqa: E402 CONFIG_CATEGORY = "C64 and Cartridge Settings" @@ -70,15 +92,31 @@ OWNED_SETTINGS = (CFG_CMD_IF,) NET_CMD_IDENTIFY = 0x01 +NET_CMD_GET_INTERFACE_COUNT = 0x02 +NET_CMD_GET_NETADDR = 0x04 NET_CMD_GET_IPADDR = 0x05 NET_CMD_OPEN_TCP = 0x07 NET_CMD_OPEN_UDP = 0x08 NET_CMD_CLOSE_SOCKET = 0x09 NET_CMD_READ_SOCKET = 0x10 NET_CMD_WRITE_SOCKET = 0x11 +NET_CMD_GET_RANDOM = 0x20 STATUS_OK = b"00,OK" +STATUS_INVALID_PARAMS = b"81,INVALID PARAMS" STATUS_OUT_OF_RANGE = b"82,PARAMETER(S) OUT OF RANGE" +# GET_RANDOM's answer when the ESP32 has nothing to draw bytes from: absent, +# not running, timed out, or not yet started its radio. It is only ever +# answered with no data, whatever the reason. +STATUS_NO_ENTROPY = b"87,NO ENTROPY SOURCE" +STATUS_NO_ENTROPY_PREFIX = b"87," +# GET_RANDOM's answer when the ESP32 runs but was busy and did not answer in +# time. The client should try again; like 87 it never carries data. +STATUS_ENTROPY_BUSY = b"88,ENTROPY SOURCE BUSY" +STATUS_ENTROPY_BUSY_PREFIX = b"88," +# What the network target answers for an opcode it does not implement, which +# is what GET_RANDOM is on firmware that predates it. +STATUS_UNKNOWN_COMMAND = b"21,UNKNOWN COMMAND" # Not in the network target document, but what the firmware answers when # lwip_recv returns -1. The number is the errno: 9 is EBADF for a handle that # was never opened, 11 is EAGAIN for an open socket with nothing pending. @@ -148,6 +186,77 @@ SOCKETS_LEFT_OPEN_AT_RESET = 4 RESET_CYCLES = 3 +# The /v1/info products that draw GET_RANDOM bytes on the ESP32 (U64 == 1 in +# product.cc), matched exactly since "Ultimate 64-II" starts with "Ultimate 64". +U64_MK1_PRODUCTS = ("Ultimate 64", "Ultimate 64 Elite") +# U64 == 2, the Ultimate 64 Elite II and the C64 Ultimate. It draws them too, but +# has no "WiFi Enabled" setting: its radio is on from boot and the menu's Enable +# and Disable are actions. Two names, because the name is not the build's: +# - "Ultimate 64-II" is the only one this source tree has (product_name[6], +# product.cc:18, chosen by getProductId() for U64 == 2 at product.cc:96-97). The +# Elite II reports it, and so does a C64 Ultimate running a build of this tree. +# - "C64 Ultimate" is what the C64 Ultimate's release firmware reports in +# /v1/info (read from a C64 Ultimate on 1.1.0, 2026-10-15). Nothing in this tree +# produces it; it is listed so that such a unit is not taken to be a product +# that must refuse. +U64_MK2_PRODUCTS = ("Ultimate 64-II", "C64 Ultimate") +# Every other product answers 87, even with a wifi_mac: its ESP32 runs other code. +GET_RANDOM_PRODUCTS = U64_MK1_PRODUCTS + U64_MK2_PRODUCTS +# The setting that switches the module's radio there, by the store's exact name (the +# answer is keyed by it). Set for the run, and written back on exit; a change takes +# effect at once (network_esp32.cc, wifi_enable_change). +CFG_WIFI_CATEGORY = "WiFi settings" +CFG_WIFI_ENABLED = "WiFi Enabled" +# How long a device with Wi-Fi enabled gets to report its wifi_mac, which it +# does once the module has started; this covers a device that has just booted. +WIFI_MAC_SECONDS = 30.0 +# How long the module gets to stop its radio after "WiFi Enabled" goes to Disabled +# (it takes the request between connect attempts, so this covers one attempt), and to +# associate and get an address again after Enabled. +RADIO_OFF_SECONDS = 30.0 +RADIO_ON_SECONDS = 60.0 +# How many draws get-random-radio-off makes with the radio off +RADIO_OFF_DRAWS = 8 + +# The most GET_RANDOM hands out in one command. 512 bytes fits one reply block, +# so every GET_RANDOM reply arrives in one. +RANDOM_MAX_BYTES = 512 +# The size a program asking for a key or a nonce would use. +RANDOM_TYPICAL = 32 +# A length whose high byte is neither 0 nor that of RANDOM_MAX_BYTES, so a +# handler that reads only the low byte answers with 44 bytes instead of 300. +RANDOM_SPLIT_LENGTH = 300 +# How long a run of pattern() bytes inside a random reply has to be before it +# counts as the socket read buffer handed back. A chance match of eight bytes +# is 1 in 2^56 per position. +STALE_RUN_BYTES = 8 +# Every window of this many bytes, at every offset of every reply in a route, +# has to be new. A route holds at most about 2,500, so honest bytes repeat one by +# chance with a probability of about 2,500^2 / 2 / 2^64, 1 in 10^12. +RANDOM_WINDOW_BYTES = 8 +# Lengths that are not a multiple of 4 or of 16, so a handler that fills whole +# words or blocks leaves a tail it did not draw in every one of them. +RANDOM_ODD_LENGTHS = (3, 17, 31, 257, 511) +# Same-offset matches over a pair of length m are Binomial(m, 1/256). A pair fails +# at the smallest count less likely than this, capped at RANDOM_PAIR_MATCHES_MAX +# (4 in 10^10 for 512 bytes); pairs too short to get there (m = 1, 3) are not judged. +RANDOM_PAIR_FALSE_ALARM = 1e-12 +RANDOM_PAIR_MATCHES_MAX = 16 +# A run of replies of one length, so a byte a handler never draws stays the +# same through all of them. Honest bytes hold one offset through 16 replies +# with a probability of 256^-15 per offset. +RANDOM_SERIES_LENGTH = 17 +RANDOM_SERIES_COUNT = 16 +# How often, and how far apart, a GET_RANDOM that answered 88 is asked again: +# 15 s covers the up to 10 s the ESP32 can block queueing a scan or connect. +# A source still busy after that fails where bytes are owed. +RANDOM_BUSY_RETRIES = 15 +RANDOM_BUSY_DELAY_SECONDS = 1.0 +# How many GET_RANDOM calls in one route may need a retry where bytes are +# owed. On an idle device an 88 is rare, so more than this says the source +# is busy as a matter of course rather than now and then. +RANDOM_BUSY_CALLS_MAX = 2 + # The two ways of reaching the registers, described at the top of this file. ROUTES = ["rest", "native"] @@ -162,8 +271,17 @@ "oversize-request-keeps-the-datagram", "empty-datagram-keeps-udp-open", "multi-block-state-does-not-leak", + "get-random-lengths", + "get-random-bytes-vary", + "get-random-refusals", + "get-random-leaves-sockets-alone", + "get-random-radio-off", + "stalled-write-reset-and-abort", "reset-closes-uci-sockets", ] +# The scenarios that need no network peer, because they open no socket. +PEERLESS_TESTS = ("read-length-limit", "get-random-lengths", "get-random-bytes-vary", + "get-random-refusals", "get-random-radio-off") def pattern(size: int, seed: int = 0) -> bytes: @@ -249,8 +367,19 @@ def describe_mismatch(actual: bytes, expected: bytes) -> str: class Net: """The network target's commands, over the command interface.""" - def __init__(self, uci: Uci) -> None: + def __init__(self, uci: Uci, duty: "RandomDuty | None" = None) -> None: self.uci = uci + # What GET_RANDOM owes on this device, which decides what an 88 is. + # None for a driver that never sends it. + self.duty = duty + # Every GET_RANDOM reply on this driver, and how many calls needed a + # retry after an 88. + self.random_replies = 0 + self.busy_calls = 0 + # Every RANDOM_WINDOW_BYTES window of every GET_RANDOM reply so far, + # with the reply and offset it came from, and every reply itself. + self.random_windows: dict[bytes, tuple[int, int]] = {} + self.random_data: list[tuple[int, bytes]] = [] def identify(self): return self.uci.transact(bytes([TARGET_NETWORK, NET_CMD_IDENTIFY])) @@ -306,6 +435,106 @@ def abort_read(self, handle: int, maxlen: int) -> tuple[int, bool]: def close(self, handle: int): return self.uci.transact(bytes([TARGET_NETWORK, NET_CMD_CLOSE_SOCKET, handle])) + def random_command(self, length: int) -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_GET_RANDOM, length & 0xFF, (length >> 8) & 0xFF]) + + def get_random(self, length: int | None = None, command: bytes | None = None): + """One GET_RANDOM, of `length` bytes or as the raw `command` given. + + Every reply passes the fail-closed rule here, so it holds for each one + the suite provokes rather than only where a scenario thinks to look: a + reply that is not 00,OK carries no data, and an 87 above all. Bytes + handed out when the ESP32 had no entropy source would look exactly as + random as real ones, so the status is the only place a client can learn + not to use them, and a reply that sends both has already lost. + + An 88 fails at once on a product that owes no bytes, which never asks + the ESP32, so its only refusal is an immediate 87. Elsewhere it is asked + again, up to RANDOM_BUSY_RETRIES times, each retried reply held to the + same rule, and more than RANDOM_BUSY_CALLS_MAX calls needing a retry + fails. + """ + if command is None: + command = self.random_command(length) + result = self._random_reply(command) + busy = result.status_text.startswith(STATUS_ENTROPY_BUSY_PREFIX) + if busy and self.duty is not None and not self.duty.owed: + raise Failure(f"GET_RANDOM answered {result.status_text!r} on this " + f"{self.duty.product}, which never asks the ESP32 for bytes; " + f"the only correct refusal there is an immediate " + f"{STATUS_NO_ENTROPY!r}") + if busy: + self.busy_calls += 1 + if self.duty is not None and self.duty.owed and \ + self.busy_calls > RANDOM_BUSY_CALLS_MAX: + raise Failure(f"{self.busy_calls} GET_RANDOM calls on this route answered " + f"{result.status_text!r} and needed a retry; where bytes are " + f"owed an idle device does that at most " + f"{RANDOM_BUSY_CALLS_MAX} times") + for attempt in range(1, RANDOM_BUSY_RETRIES + 1): + if not result.status_text.startswith(STATUS_ENTROPY_BUSY_PREFIX): + break + detail(f"GET_RANDOM answered {result.status_text!r}; retry {attempt} of " + f"{RANDOM_BUSY_RETRIES} in {RANDOM_BUSY_DELAY_SECONDS:.1f}s") + time.sleep(RANDOM_BUSY_DELAY_SECONDS) + result = self._random_reply(command) + return result + + def _random_reply(self, command: bytes): + """One GET_RANDOM exchange, counted and held to the fail-closed rule.""" + result = self.uci.transact(command) + self.random_replies += 1 + for prefix, what in ((STATUS_NO_ENTROPY_PREFIX, "with no entropy source"), + (STATUS_ENTROPY_BUSY_PREFIX, "with the entropy source busy")): + if result.status_text.startswith(prefix) and result.data: + raise Failure(f"GET_RANDOM answered {result.status_text!r} and still handed " + f"out {len(result.data)} bytes; {what} it must hand out none") + if result.status_text != STATUS_OK and result.data: + raise Failure(f"GET_RANDOM answered {result.status_text!r} with {len(result.data)} " + f"data bytes; a refusal carries no data") + if result.status_text == STATUS_OK: + self._remember_random(result.data) + return result + + def _remember_random(self, data: bytes) -> None: + """Fail if any window of `data` was handed out before on this route. + + A sanity check against bytes handed out twice, not an entropy proof. + A handler that fills only part of its buffer still answers with the + full length, and the rest is whatever an earlier reply left there: + random, so no check on one reply sees it, but the same bytes as + before. Every offset is checked rather than aligned blocks, so bytes + served again at a different position are caught as well, and so is + a reply that repeats itself. + """ + reply = self.random_replies + for offset in range(len(data) - RANDOM_WINDOW_BYTES + 1): + window = data[offset:offset + RANDOM_WINDOW_BYTES] + seen = self.random_windows.get(window) + if seen is not None: + raise Failure( + f"bytes {offset}-{offset + RANDOM_WINDOW_BYTES - 1} of GET_RANDOM reply " + f"{reply} ({len(data)} bytes) were handed out before, at offset " + f"{seen[1]} of reply {seen[0]}: {window.hex(' ')}. Random bytes do " + f"not repeat {RANDOM_WINDOW_BYTES} at a time, so part of this reply " + f"was left over rather than drawn") + self.random_windows[window] = (reply, offset) + # Bytes left over at the same offset rather than in a run: a handler + # that draws every other byte, or whole words and not the tail. + for earlier, before in self.random_data: + common = min(len(data), len(before)) + limit = same_offset_limit(common) + if limit is None: + continue + matches = sum(1 for a, b in zip(data, before, strict=False) if a == b) + if matches >= limit: + raise Failure( + f"GET_RANDOM reply {reply} ({len(data)} bytes) has the same byte as reply " + f"{earlier} at {matches} of their {common} common offsets; honest bytes " + f"match at about {common / 256:.1f}, and {limit} or more has a chance " + f"below {RANDOM_PAIR_FALSE_ALARM:g}") + self.random_data.append((reply, data)) + def largest_accepted_length(self) -> int: """The largest length READ_SOCKET accepts, found by bisection. @@ -1136,6 +1365,415 @@ def run_empty_datagram_keeps_udp_open(net: Net, peer: Peer) -> bool: return ok +@functools.cache +def same_offset_limit(common: int) -> int | None: + """How many same-offset matches fail a pair with `common` offsets in common. + + The smallest k with P(Binomial(common, 1/256) >= k) below + RANDOM_PAIR_FALSE_ALARM, capped at RANDOM_PAIR_MATCHES_MAX, or None where + no k up to `common` gets there. + """ + for k in range(1, min(common, RANDOM_PAIR_MATCHES_MAX) + 1): + # P(X >= k), summed directly rather than as 1 - P(X < k) for precision. + tail = sum(math.comb(common, j) * (1 / 256) ** j * (255 / 256) ** (common - j) + for j in range(k, common + 1)) + if tail < RANDOM_PAIR_FALSE_ALARM: + return k + return RANDOM_PAIR_MATCHES_MAX if common >= RANDOM_PAIR_MATCHES_MAX else None + + +def require_random(result, length: int) -> bytes: + """The bytes of a GET_RANDOM reply that has to have succeeded, or Failure.""" + if result.status_text == STATUS_UNKNOWN_COMMAND: + raise Failure(f"GET_RANDOM answered {result.status_text!r}: this firmware does not " + f"implement NET_CMD_GET_RANDOM (${NET_CMD_GET_RANDOM:02X})") + if result.status_text.startswith(STATUS_ENTROPY_BUSY_PREFIX): + raise Failure(f"GET_RANDOM of {length} bytes answered {result.status_text!r}: the " + f"entropy source was still busy when the suite stopped asking, which " + f"is after {RANDOM_BUSY_RETRIES} retries " + f"{RANDOM_BUSY_DELAY_SECONDS:.1f}s apart") + if result.status_text.startswith(STATUS_NO_ENTROPY_PREFIX): + raise Failure(f"GET_RANDOM of {length} bytes answered {result.status_text!r}, expected " + f"{STATUS_OK!r}: the module has bytes with its radio on and with it off, " + f"so 87 means it has no entropy source at all (a module without " + f"GET_RANDOM, or a SAR ADC source that failed its readback)") + if result.status_text != STATUS_OK: + raise Failure(f"GET_RANDOM of {length} bytes answered {result.status_text!r}, " + f"expected {STATUS_OK!r}") + if len(result.data) != length: + raise Failure(f"GET_RANDOM of {length} bytes handed out {len(result.data)}") + if len(result.blocks) != 1: + raise Failure(f"the reply arrived in {len(result.blocks)} blocks; " + f"{RANDOM_MAX_BYTES} bytes fit one, so every reply must") + return result.data + + +def read_wifi_setting(device, info) -> object: + """CFG_WIFI_ENABLED as the device reports it, or None where it has none. + + Asked only of the products that can owe bytes: the others either have no + such store or, on an Ultimate 64-II, one whose Wi-Fi items are actions. + """ + if info.product not in U64_MK1_PRODUCTS: + return None + if CFG_WIFI_CATEGORY not in device.configs.category_names(): + return None + return device.configs.get(CFG_WIFI_CATEGORY, CFG_WIFI_ENABLED) + + +def reports_wifi_mac(info) -> bool: + wifi_mac = info.extra.get("wifi_mac") + return isinstance(wifi_mac, str) and bool(wifi_mac.strip()) + + +def wait_for_wifi_mac(device, info): + """The device's report once it names a wifi_mac, or after WIFI_MAC_SECONDS.""" + deadline = time.monotonic() + WIFI_MAC_SECONDS + while not reports_wifi_mac(info) and time.monotonic() < deadline: + time.sleep(1.0) + info = device.info() + return info + + +def read_duty(device, wifi_original: dict[str, str]) -> "RandomDuty": + """What GET_RANDOM owes on this device, from its report. + + On an Ultimate 64 or Ultimate 64 Elite "WiFi Enabled" is set first, and its + stored value kept in `wifi_original` for the restore. An Ultimate 64-II has + no such setting and is taken as it is, radio on. A device that then cannot + owe bytes fails this check, and the Failure is passed on for the + GET_RANDOM scenarios to fail with. + """ + with check("read whether this device owes GET_RANDOM bytes"): + info = device.info() + wifi_setting = read_wifi_setting(device, info) + if info.product in U64_MK1_PRODUCTS and wifi_setting is None: + raise Failure(f"this {info.product} has no {CFG_WIFI_ENABLED!r} in " + f"{CFG_WIFI_CATEGORY!r}, so the suite cannot start its WiFi module") + if wifi_setting is not None and wifi_setting != "Enabled": + wifi_original[CFG_WIFI_ENABLED] = str(wifi_setting) + device.configs.set(CFG_WIFI_CATEGORY, CFG_WIFI_ENABLED, "Enabled") + wifi_setting = "Enabled" + if wifi_setting == "Enabled" or info.product in U64_MK2_PRODUCTS: + info = wait_for_wifi_mac(device, info) + duty = random_duty(info) + expected = ("has to hand out bytes" if duty.owed else "has to refuse with 87") + mac = "reported" if reports_wifi_mac(info) else "not reported" + detail(f"product {info.product!r}, wifi_mac {mac}, " + f"{CFG_WIFI_ENABLED!r} {wifi_setting!r}" + f"{' (set for the run)' if wifi_original else ''}: GET_RANDOM {expected}") + return duty + + +class RandomDuty(NamedTuple): + """What GET_RANDOM has to answer on one device, decided from its report.""" + + owed: bool # bytes are owed: 87, or 88 past the retries, fails; else only 87 passes + product: str + + +def random_duty(info) -> RandomDuty: + """What a device with "WiFi Enabled" set has to answer to GET_RANDOM. + + Only an Ultimate 64, Ultimate 64 Elite or Ultimate 64-II draws bytes at all, + so on any other product a reply with bytes in it came from somewhere else, which + is the fallback the command must never have. On those two the bytes are + owed, and one whose module never reported a wifi_mac fails rather than + skips; otherwise a firmware that always refuses would pass. + """ + owed = info.product in GET_RANDOM_PRODUCTS + if owed and not reports_wifi_mac(info): + enabled = (f"has {CFG_WIFI_ENABLED!r} set" if info.product in U64_MK1_PRODUCTS + else "is taken as having its radio on") + raise Failure(f"this {info.product} {enabled} but reported no " + f"wifi_mac in /v1/info within {WIFI_MAC_SECONDS:g}s, so its WiFi module " + f"did not start. Check that the WiFi module is fitted and starts, " + f"then run the suite again") + return RandomDuty(owed=owed, product=info.product) + + +def random_expected(net: Net, duty: RandomDuty) -> bool: + """Whether this device should hand out random bytes at all. + + `duty` is decided in main from the device's own report, never from this + answer. Where bytes are owed, 87 is a failure, and so is an 88 that + outlasts its retries. Elsewhere 87 with no data is the one correct answer: + that is checked here, and the checks that need bytes skip; 00,OK fails + here. Anything else, the unknown-command answer of firmware without + GET_RANDOM included, goes on to fail the checks that need bytes. + """ + if duty.owed: + return True + probe = net.get_random(RANDOM_TYPICAL) + if probe.status_text == STATUS_OK: + with check(f"GET_RANDOM on this {duty.product} refuses rather than hand out bytes"): + raise Failure(f"GET_RANDOM answered {STATUS_OK!r} with {len(probe.data)} bytes on " + f"this {duty.product}, which has no source to draw them from: only an " + f"{' or '.join(GET_RANDOM_PRODUCTS)} does. The only correct answer " + f"here is {STATUS_NO_ENTROPY!r}, with no data") + if not probe.status_text.startswith(STATUS_NO_ENTROPY_PREFIX): + return True + with check("where no bytes are owed, GET_RANDOM refuses with 87 and no data"): + if probe.status_text != STATUS_NO_ENTROPY: + raise Failure(f"expected {STATUS_NO_ENTROPY!r}, got {probe.status_text!r}") + check_start("GET_RANDOM hands out random bytes") + check_skip(f"GET_RANDOM answered {probe.status_text[:2].decode()} on a device that owes " + f"no bytes: only an {' or '.join(GET_RANDOM_PRODUCTS)} serves them") + return False + + +def run_get_random_lengths(net: Net, duty: RandomDuty, native: bool) -> bool | None: + """GET_RANDOM hands out exactly the number of bytes asked for. + + At the typical size and the lower bound on both routes. On the native route + also at the upper bound, at a length whose high byte is neither 0 nor 2, so + a handler that drops the high byte is caught on the success path as well as + on the refusals, and at lengths that are not a multiple of 4 or 16, whose + tails Net checks against earlier replies. The REST route reads one byte per + DMA cycle, and the firmware path is the same. + """ + section("get-random-lengths") + if not random_expected(net, duty): + return None + for length in (RANDOM_TYPICAL, 1, + *((RANDOM_MAX_BYTES, RANDOM_SPLIT_LENGTH, *RANDOM_ODD_LENGTHS) if native else ())): + with check(f"GET_RANDOM of {length} bytes answers {STATUS_OK.decode()} with exactly " + f"{length} bytes"): + require_random(net.get_random(length), length) + return True + + +def run_get_random_bytes_vary(net: Net, duty: RandomDuty) -> bool | None: + """No byte of a reply stays the same from one reply to the next. + + A sanity check, NOT a proof of entropy: the bytes are the output of a + post-processed RNG, which looks random whether or not a physical source is + feeding it. Replies handed out again, repeated or patterned are caught on + every reply by Net's window and same-offset checks; what those cannot see + is a tail of one to three bytes that a handler never draws. Native route + only, where it is cheap. + """ + section("get-random-bytes-vary") + if not random_expected(net, duty): + return None + with check(f"no byte stays the same through {RANDOM_SERIES_COUNT} GET_RANDOM of " + f"{RANDOM_SERIES_LENGTH} bytes"): + series = [require_random(net.get_random(RANDOM_SERIES_LENGTH), RANDOM_SERIES_LENGTH) + for _ in range(RANDOM_SERIES_COUNT)] + stuck = [offset for offset in range(RANDOM_SERIES_LENGTH) + if len({reply[offset] for reply in series}) == 1] + if stuck: + raise Failure(f"offsets {stuck} held the same byte in all {RANDOM_SERIES_COUNT} " + f"replies: ${series[0][stuck[0]]:02X} at {stuck[0]}") + return True + + +def run_get_random_refusals(net: Net, duty: RandomDuty) -> bool: + """Malformed and out-of-range requests are refused, with no data. + + Refusals do not need an entropy source, so these run on every device. + The lengths above the limit include ones with the top bit set, which a + handler that holds the length in a signed 16-bit value reads as negative. + """ + section("get-random-refusals") + malformed = [ + ("no length bytes", bytes([TARGET_NETWORK, NET_CMD_GET_RANDOM])), + ("only the low length byte", + bytes([TARGET_NETWORK, NET_CMD_GET_RANDOM, RANDOM_TYPICAL])), + # A valid length with a byte after it: the command is exactly four + # bytes, and a check for "at least four" would take this one. + ("a byte after a valid length", + bytes([TARGET_NETWORK, NET_CMD_GET_RANDOM, RANDOM_TYPICAL, 0, 0])), + ] + for what, command in malformed: + with check(f"GET_RANDOM with {what} answers {STATUS_INVALID_PARAMS.decode()} " + f"and no data"): + result = net.get_random(command=command) + if result.status_text != STATUS_INVALID_PARAMS: + raise Failure(f"expected {STATUS_INVALID_PARAMS!r}, got {result.status_text!r}") + + for length in (0, RANDOM_MAX_BYTES + 1, 0x8000, 0xFFFF): + with check(f"GET_RANDOM of {length} bytes answers {STATUS_OUT_OF_RANGE.decode()} " + f"and no data"): + result = net.get_random(length) + if result.status_text != STATUS_OUT_OF_RANGE: + raise Failure(f"expected {STATUS_OUT_OF_RANGE!r}, got {result.status_text!r}") + + # Refusals must not leave the command unusable. Where there is no entropy + # source the answer is 87 either way, and random_expected says so. + if random_expected(net, duty): + with check("GET_RANDOM still hands out bytes after the refusals"): + require_random(net.get_random(RANDOM_TYPICAL), RANDOM_TYPICAL) + return True + + +def run_get_random_leaves_sockets_alone(net: Net, peer: Peer, duty: RandomDuty, + native: bool) -> bool | None: + """GET_RANDOM does not disturb the network target's socket state. + + It is answered by the same target that holds the socket table and the + buffer READ_SOCKET replies from, so it runs here between an open, a + pending datagram, the read of it, and the close, all of which have to + behave as they do without it. + """ + section("get-random-leaves-sockets-alone") + if not random_expected(net, duty): + return None + baseline = net.identify() + handle = net.open_udp(peer.ip, peer.udp_port) + try: + peer.learn_udp_peer(net, handle) + net.drain_socket(handle) + peer.send_udp(pattern(SAFE_READ)) + time.sleep(DELIVERY_SETTLE_SECONDS) + + with check("GET_RANDOM answers while a socket holds a pending datagram"): + require_random(net.get_random(RANDOM_TYPICAL), RANDOM_TYPICAL) + refused = net.get_random(0) + if refused.status_text != STATUS_OUT_OF_RANGE: + raise Failure(f"a length of 0 answered {refused.status_text!r}, expected " + f"{STATUS_OUT_OF_RANGE!r}") + + with check("the pending datagram is read back whole after GET_RANDOM"): + result = net.read(handle, SAFE_READ) + detail(result.describe()) + if result.status_text != STATUS_OK or result.header != SAFE_READ: + raise Failure(f"expected {STATUS_OK!r} and a header of {SAFE_READ}, got " + f"{result.status_text!r} and {result.header}") + if result.payload != pattern(SAFE_READ): + raise Failure(f"the datagram changed: " + f"{describe_mismatch(result.payload, pattern(SAFE_READ))}") + + if native: # 512 bytes; the REST route reads them one DMA cycle at a time + with check("GET_RANDOM right after a socket read does not hand back the read's bytes"): + # The read just filled the target's buffer with pattern() bytes. A + # handler that answers from that buffer without filling all of it + # hands some of them out again, and they read as a run of pattern(). + data = require_random(net.get_random(RANDOM_MAX_BYTES), RANDOM_MAX_BYTES) + stale = [offset for offset in range(len(data) - STALE_RUN_BYTES + 1) + if run_offset(data[offset:offset + STALE_RUN_BYTES]) is not None] + if stale: + raise Failure(f"bytes from offset {stale[0]} are a run of the datagram just " + f"read: {data[stale[0]:stale[0] + 16].hex(' ')}") + + with check("the socket still sends after GET_RANDOM"): + # learn_udp_peer sends from the device and waits for it here, with + # the retry a lost datagram needs. + peer.learn_udp_peer(net, handle) + + with check("the socket closes with 00,OK"): + closing, handle = handle, None + result = net.close(closing) + if result.status_text != STATUS_OK: + raise Failure(f"CLOSE_SOCKET answered {result.status_text!r}") + + with check("IDENTIFY after GET_RANDOM answers exactly as before it"): + identity = net.identify() + if (identity.data, identity.status_text, len(identity.blocks)) != \ + (baseline.data, baseline.status_text, len(baseline.blocks)): + raise Failure(f"IDENTIFY answered {identity.data!r}, {identity.status_text!r} " + f"in {len(identity.blocks)} block(s); before GET_RANDOM it was " + f"{baseline.data!r}, {baseline.status_text!r} in " + f"{len(baseline.blocks)}") + finally: + if handle is not None: + net.close(handle) + return True + + +def wifi_interface_address(net: Net, wifi_mac: str) -> str | None: + """The address of the network target's interface whose MAC is `wifi_mac`, or None. + + The WiFi interface loses its address when its link goes down (dhcp_stop in + NetworkInterface::link_down), which is what the Ultimate does when the module + reports EVENT_DISABLED, so 0.0.0.0 here means the radio-off reached it. None + means no interface has that MAC. + """ + count = net.uci.transact(bytes([TARGET_NETWORK, NET_CMD_GET_INTERFACE_COUNT])).data + want = bytes.fromhex(wifi_mac.replace(":", "").replace("-", "")) + for index in range(count[0] if count else 0): + mac = net.uci.transact(bytes([TARGET_NETWORK, NET_CMD_GET_NETADDR, index])).data + if bytes(mac[:6]) == want: + reply = net.uci.transact(bytes([TARGET_NETWORK, NET_CMD_GET_IPADDR, index])).data + return ".".join(str(b) for b in reply[:4]) if len(reply) >= 4 else None + return None + + +def wait_for_wifi_address(net: Net, wifi_mac: str, gone: bool, seconds: float) -> str | None: + """Polls the WiFi interface's address until it is gone (0.0.0.0) or back, or the time is up.""" + deadline = time.monotonic() + seconds + while True: + address = wifi_interface_address(net, wifi_mac) + if (address == "0.0.0.0") == gone or time.monotonic() >= deadline: + return address + time.sleep(1.0) + + +def run_get_random_radio_off(net: Net, duty: RandomDuty, device, device_host: str) -> bool | None: + """GET_RANDOM hands out bytes with the WiFi radio off, from the SAR ADC source. + + On an Ultimate 64 or Ultimate 64 Elite, "WiFi Enabled" goes to Disabled for the + scenario, which turns the module's radio off at once, and back to Enabled after + it. The off counts as done once the Ultimate's WiFi interface has lost its address, + which it does on the module's EVENT_DISABLED; if it keeps it, the radio did not go + off and the scenario fails rather than draw with the radio on. That the RF itself + is off is the bench sniffer's check, not this suite's. The draws then come from + the module's SAR ADC entropy source; one that meets the radio change may answer + 88, which Net retries. + + Skips where it cannot work: on the Ultimate 64-II, whose radio is switched only + from its menu; where the suite reaches the device over WiFi (turning it off would + cut the suite off); and where the WiFi interface has no address before the + scenario (with a static address, or no AP), so the off could not be seen. + """ + section("get-random-radio-off") + if not random_expected(net, duty): + return None + check_start("GET_RANDOM hands out bytes with the radio off") + if duty.product not in U64_MK1_PRODUCTS: + check_skip(f"this {duty.product} has no {CFG_WIFI_ENABLED!r} setting to switch its " + f"radio with; its menu's Disable is an action the suite cannot reach") + return None + info = device.info() + wifi_mac = info.extra.get("wifi_mac", "") if reports_wifi_mac(info) else "" + address = wifi_interface_address(net, wifi_mac) if wifi_mac else None + try: + host_address = socket.gethostbyname(device_host) + except OSError: + host_address = device_host + if address is not None and address == host_address: + check_skip(f"the suite reaches the device at {host_address}, its WiFi address; turning " + f"the radio off would cut the suite off. Run it over Ethernet") + return None + if address in (None, "0.0.0.0"): + check_skip(f"the WiFi interface has no address before the scenario ({address!r}: no " + f"AP, or a static address), so the radio going off could not be seen") + return None + with check(f"set {CFG_WIFI_ENABLED!r} to Disabled, and the WiFi interface loses its " + f"address {address} within {RADIO_OFF_SECONDS:g}s"): + device.configs.set(CFG_WIFI_CATEGORY, CFG_WIFI_ENABLED, "Disabled") + after = wait_for_wifi_address(net, wifi_mac, True, RADIO_OFF_SECONDS) + if after != "0.0.0.0": + raise Failure(f"the WiFi interface still has {after!r}: the radio did not go off") + try: + with check(f"{RADIO_OFF_DRAWS} GET_RANDOM of {RANDOM_TYPICAL} bytes with the radio off " + f"answer {STATUS_OK.decode()} with the bytes"): + series = [require_random(net.get_random(RANDOM_TYPICAL), RANDOM_TYPICAL) + for _ in range(RADIO_OFF_DRAWS)] + if len(set(series)) != len(series): + raise Failure("a reply with the radio off repeated an earlier one") + finally: + with check(f"set {CFG_WIFI_ENABLED!r} back to Enabled, and the WiFi interface gets " + f"an address again within {RADIO_ON_SECONDS:g}s"): + device.configs.set(CFG_WIFI_CATEGORY, CFG_WIFI_ENABLED, "Enabled") + back = wait_for_wifi_address(net, wifi_mac, False, RADIO_ON_SECONDS) + if back in (None, "0.0.0.0"): + raise Failure(f"the WiFi interface has {back!r}: the radio did not come back") + with check("GET_RANDOM hands out bytes with the radio on again"): + require_random(net.get_random(RANDOM_TYPICAL), RANDOM_TYPICAL) + return True + + def close_quietly(net: Net, handles: list[int]) -> None: """Close every handle a scenario opened; an error means it was already gone.""" for handle in handles: @@ -1201,6 +1839,92 @@ def run_reset_closes_uci_sockets(net: Net, peer: Peer, reset, device) -> bool: return True +# How long a WRITE has to stay unanswered to count as stalled, and how long the target may take to be +# useful again after the C64 reset that ends it. The send waits in slices (a few hundred milliseconds on +# lwIP), so a worker that sees the reset is free well inside the bound. +STALL_SECONDS = 2.0 +FREE_WITHIN_SECONDS = 3.0 +STALL_FILL_LIMIT = 4096 # WRITEs of 888 bytes, far more than the two buffers hold + + +def stall_a_write(net: Net, handle: int) -> int: + """WRITE until one is still unanswered after STALL_SECONDS because the peer reads nothing. + + The agent keeps waiting in that WRITE; only a reset ends it. Returns how many WRITEs completed first. + """ + uci = net.uci + patient = uci.busy_timeout + uci.busy_timeout = STALL_SECONDS + try: + for done in range(STALL_FILL_LIMIT): + try: + result = net.write(handle, bytes(888)) + except Failure as exc: + if "did not finish" in str(exc): + return done + raise + if result.status_text != STATUS_OK: + raise Failure(f"WRITE #{done + 1} answered {result.status_text!r}") + finally: + uci.busy_timeout = patient + raise Failure(f"{STALL_FILL_LIMIT} WRITEs of 888 bytes all completed: the peer's buffers never filled") + + +def run_stalled_write_reset(net: Net, peer: Peer, reset) -> bool: + """A C64 reset during a WRITE that has stalled on a peer that reads nothing (native route). + + The target must let go of the stalled WRITE: IDENTIFY is answered, the next socket command + (OPEN_UDP + CLOSE_SOCKET) runs within FREE_WITHIN_SECONDS, and the stalled socket is closed. The times are + printed. `reset` resets the C64 and returns a Net that reaches the target afterwards. The abort of a + stalled WRITE is covered by the host test; the REST route cannot fill a socket in reasonable time. + """ + section("stalled-write-reset-and-abort") + conn = None + handle = None + try: + with check("a WRITE to a peer that reads nothing stalls"): + handle = net.open_tcp(peer.ip, peer.tcp_port) + conn = peer.accept_tcp() + conn.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 2048) + completed = stall_a_write(net, handle) + detail(f"{completed} WRITEs completed, the next one has been unanswered for {STALL_SECONDS:.0f} s") + with check("reset the C64 with the WRITE stalled"): + net = reset() + with check("IDENTIFY is answered"): + started = time.time() + identity = net.identify() + if identity.status_text != STATUS_OK: + raise Failure(f"IDENTIFY answered {identity.status_text!r}") + detail(f"{time.time() - started:.2f} s") + with check(f"the next socket command is answered within {FREE_WITHIN_SECONDS:.0f} s"): + took = next_socket_command(net, peer) + detail(f"OPEN_UDP + CLOSE_SOCKET {took:.2f} s") + if took > FREE_WITHIN_SECONDS: + raise Failure(f"took {took:.2f} s: the worker was still held by the stalled WRITE") + with check("the reset closed the socket of the stalled WRITE"): + result = net.close(handle) + if result.status_text == STATUS_OK: + raise Failure("the socket was still open after the reset") + handle = None + finally: + if conn is not None: + try: + conn.close() + except OSError: + pass + return True + + +def next_socket_command(net: Net, peer: Peer) -> float: + """Seconds for an OPEN_UDP and its CLOSE: socket commands run on the worker, IDENTIFY does not.""" + started = time.time() + handle = net.open_udp(peer.ip, peer.udp_port) + result = net.close(handle) + if result.status_text != STATUS_OK: + raise Failure(f"CLOSE_SOCKET answered {result.status_text!r}") + return time.time() - started + + def free_heap(device) -> int | None: """Free FreeRTOS heap, for the record; lwip's pools are static and do not show here.""" try: @@ -1232,7 +1956,8 @@ def build_driver(route: str, computer, busy_timeout: float): def main() -> int: parser = argparse.ArgumentParser( description="Verify how the UCI network target's READ_SOCKET handles the requested " - "length and datagrams larger than it (GideonZ/1541ultimate#802)." + "length and datagrams larger than it (GideonZ/1541ultimate#802), and " + "what GET_RANDOM hands out." ) cli.add_device_arguments(parser, password=None, timeout=30.0, colour=False) parser.add_argument("-b", "--busy-timeout", type=float, default=15.0, @@ -1244,7 +1969,8 @@ def main() -> int: "Ultimate issues, 'native' for 6502 code running on the " "C64. Both by default.") parser.add_argument("--keep-config", action="store_true", - help="Don't restore the original Command Interface setting on exit.") + help="Don't restore the original Command Interface and WiFi Enabled " + "settings on exit.") args = parser.parse_args() selected = TESTS if not args.test or "all" in args.test else [t for t in TESTS if t in args.test] @@ -1265,6 +1991,7 @@ def main() -> int: rest_uci = Uci(computer.machine, args.busy_timeout) original: dict[str, str] = {} + wifi_original: dict[str, str] = {} results: dict[str, bool | None] = {} peer: Peer | None = None interface_enabled = False @@ -1272,6 +1999,10 @@ def main() -> int: cleanup_ok = True setup_failed = False + # Why no GET_RANDOM scenario can be run on this device, when the device + # cannot owe bytes; each of them then fails with it, and the rest run. + duty_failure: str | None = None + def run(route: str, name: str, fn, *fn_args) -> None: """Run one scenario on one route; a failed check ends that scenario only. @@ -1284,6 +2015,11 @@ def run(route: str, name: str, fn, *fn_args) -> None: return label = f"{name} [{route}]" results[label] = False # so an aborted scenario reports FAIL, not "not reached" + if duty_failure is not None and name.startswith("get-random-"): + section(name) + check_start(f"{name} can run on this device") + check_fail(duty_failure) + return try: results[label] = fn(*fn_args) except Wedged: @@ -1293,6 +2029,16 @@ def run(route: str, name: str, fn, *fn_args) -> None: detail(f"{label} stopped: {format_exception(exc)}") try: + # Whether bytes are owed comes from the device's report, not the answer, + # so a firmware that always answers 87 fails. If it cannot be read, only + # the GET_RANDOM scenarios fail. + duty = RandomDuty(owed=False, product="") + if any(name.startswith("get-random-") for name in selected): + try: + duty = read_duty(device, wifi_original) + except Failure as exc: + duty_failure = format_exception(exc) + with check(f"read {CONFIG_CATEGORY!r}"): config = device.configs.category(CONFIG_CATEGORY) if CFG_CMD_IF not in config: @@ -1313,7 +2059,7 @@ def run(route: str, name: str, fn, *fn_args) -> None: return 0 needs_peer = [name for name in TESTS - if name != "read-length-limit" and name in selected] + if name not in PEERLESS_TESTS and name in selected] if needs_peer: check_start("this host can act as the device's network peer") try: @@ -1363,7 +2109,7 @@ def run(route: str, name: str, fn, *fn_args) -> None: computer.machine.reset(force=True) native_started = True driver = build_driver(route, computer, args.busy_timeout) - net = Net(driver) + net = Net(driver, duty) identity = net.identify() if identity.status_text != STATUS_OK or not identity.data: raise Failure(f"NET_CMD_IDENTIFY answered {identity.status_text!r} " @@ -1371,9 +2117,18 @@ def run(route: str, name: str, fn, *fn_args) -> None: detail(identity.data.decode("latin-1")) run(route, "read-length-limit", run_read_length_limit, net) + run(route, "get-random-lengths", run_get_random_lengths, net, duty, route == "native") + if route == "native": + run(route, "get-random-bytes-vary", run_get_random_bytes_vary, net, duty) + run(route, "get-random-refusals", run_get_random_refusals, net, duty) + run(route, "get-random-radio-off", run_get_random_radio_off, net, duty, device, + target.device) if peer is None: for name in needs_peer: - results.setdefault(f"{name} [{route}]", None) + if duty_failure is not None and name.startswith("get-random-"): + run(route, name, None) # records the FAIL without calling anything + else: + results.setdefault(f"{name} [{route}]", None) continue run(route, "reply-blocks-are-drainable", run_reply_blocks_are_drainable, net, peer) run(route, "datagram-spans-reply-blocks", run_datagram_spans_reply_blocks, net, peer) @@ -1388,6 +2143,8 @@ def run(route: str, name: str, fn, *fn_args) -> None: run_empty_datagram_keeps_udp_open, net, peer) run(route, "multi-block-state-does-not-leak", run_multi_block_state_does_not_leak, net, peer) + run(route, "get-random-leaves-sockets-alone", + run_get_random_leaves_sockets_alone, net, peer, duty, route == "native") def reset_and_reopen(route=route): """Reset the C64 and hand back a driver that reaches the target.""" @@ -1397,6 +2154,14 @@ def reset_and_reopen(route=route): native_started = True return Net(build_driver(route, computer, args.busy_timeout)) return Net(rest_uci) + if route == "native": + def reset_into_net(): + nonlocal net, native_started + computer.machine.reset(force=True) + native_started = True + net = Net(build_driver(route, computer, args.busy_timeout)) + return net + run(route, "stalled-write-reset-and-abort", run_stalled_write_reset, net, peer, reset_into_net) # Last on purpose: on the native route the reset inside it ends # the 6502 agent that `net` wraps, so nothing can follow it here. run(route, "reset-closes-uci-sockets", @@ -1411,6 +2176,15 @@ def reset_and_reopen(route=route): finally: if peer is not None: peer.close() + wifi_restored = True + if wifi_original and not args.keep_config: + # First, and caught, so that it runs whatever the restores below raise. + try: + with check(f"restore {CFG_WIFI_ENABLED!r} to {wifi_original[CFG_WIFI_ENABLED]!r}"): + device.configs.set(CFG_WIFI_CATEGORY, CFG_WIFI_ENABLED, + wifi_original[CFG_WIFI_ENABLED]) + except Exception: # check() has reported it + wifi_restored = False # A failed scenario can leave the interface holding a reply, so hand the # data back before the setting goes home. released = rest_uci.release() if interface_enabled else True @@ -1422,7 +2196,7 @@ def reset_and_reopen(route=route): with check("reset the C64 so the 6502 agent releases the machine"): computer.machine.reset(force=True) restored = restore_settings(device, original, args.keep_config) - cleanup_ok = released and restored + cleanup_ok = released and restored and wifi_restored section("summary") all_ok = cleanup_ok and not setup_failed diff --git a/tests/e2e/io/command_interface/net_tls_fixture.py b/tests/e2e/io/command_interface/net_tls_fixture.py new file mode 100644 index 000000000..2329ab9b6 --- /dev/null +++ b/tests/e2e/io/command_interface/net_tls_fixture.py @@ -0,0 +1,506 @@ +#!/usr/bin/env python3 +"""The host side of the UCI TLS suite: a throwaway PKI and TLS servers that log what they saw. + +The servers run on this machine. Everything the device claims is +held against what the server logged for the same connection: the version and +suite the server negotiated, the SNI it received, the sha256 of the plaintext +it received, and whether the client ended with close_notify, a bare FIN or a +reset. The device's own claim is never the evidence for itself. + +The PKI is generated per run in a temporary directory, is never committed and +is never printed (only SPKI hashes are). It needs the `cryptography` package, +which the scenarios that need a local server report as a SKIP when it is +missing, rather than failing for a reason that is not the firmware's. + + root P-256, the CA a CUSTOM upload installs + intermediate P-256, served with every leaf + leaf ecdsa P-256, FIXTURE_NAME + leaf rsa RSA-2048, FIXTURE_NAME + leaf wrong P-256, WRONG_NAME only (94) + leaf expired P-256, FIXTURE_NAME, notAfter a year ago (95) + leaf future P-256, FIXTURE_NAME, notBefore a year ahead (95) + leaf unknown P-256, FIXTURE_NAME, under a root nobody trusts (93) + +A server is one listening socket and a thread per connection, with one +`Behaviour`. The device reaches it at this machine's address on the route to +the device, as net_target_test.py's Peer does. +""" +from __future__ import annotations + +import datetime +import hashlib +import socket +import ssl +import struct +import tempfile +import threading +import time +from dataclasses import dataclass, field +from pathlib import Path + +try: + from cryptography import x509 + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import ec, rsa + from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + HAVE_CRYPTOGRAPHY = True +except ImportError: # pragma: no cover - reported as a SKIP by the suite + HAVE_CRYPTOGRAPHY = False + +FIXTURE_NAME = "fixture.test" +WRONG_NAME = "wrong-host.test" +ACCEPT_TIMEOUT = 60.0 +# Idle limit per connection: it must outlast the slowest route (over REST a device +# took about 250 s to read S13's 16 KB record), yet still bound every wait; +# TlsServer.close() ends whatever is still open. +CONN_TIMEOUT = 600.0 +# How long the server waits for the client's answer to its close_notify. +NOTIFY_REPLY_WAIT = 120.0 + + +def payload(seed: int, length: int) -> bytes: + """A seeded payload neither side can produce by accident: SHA-256 in counter mode.""" + out = bytearray() + counter = 0 + while len(out) < length: + out += hashlib.sha256(struct.pack(" bytes: + """SHA-256 of a certificate's SubjectPublicKeyInfo, digest order.""" + cert = x509.load_der_x509_certificate(cert_der) + spki = cert.public_key().public_bytes(serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo) + return hashlib.sha256(spki).digest() + + +@dataclass +class Chain: + """One server identity: files for ssl.load_cert_chain, and what the device should see.""" + name: str + cert_file: Path # leaf then intermediate, PEM + key_file: Path + leaf_der: bytes + spki_sha256: bytes + + +class Pki: + """The per-run test PKI. Private keys live only in `directory`.""" + + def __init__(self, directory: Path | None = None) -> None: + if not HAVE_CRYPTOGRAPHY: + raise RuntimeError("the `cryptography` package is not installed " + "(pip install cryptography); the local TLS fixture needs it") + self._tmp = None + if directory is None: + self._tmp = tempfile.TemporaryDirectory(prefix="net-tls-pki-") + directory = Path(self._tmp.name) + self.dir = directory + now = datetime.datetime.now(datetime.UTC) + self.now = now + self.root_key = ec.generate_private_key(ec.SECP256R1()) + self.root = self._ca("E2E Test Root", self.root_key, None, None, now) + self.int_key = ec.generate_private_key(ec.SECP256R1()) + self.intermediate = self._ca("E2E Test Intermediate", self.int_key, + self.root, self.root_key, now) + self.unknown_key = ec.generate_private_key(ec.SECP256R1()) + self.unknown_root = self._ca("E2E Unknown Root", self.unknown_key, None, None, now) + self.chains: dict[str, Chain] = {} + day = datetime.timedelta(days=1) + self._leaf("ecdsa", FIXTURE_NAME, ec.generate_private_key(ec.SECP256R1()), + now - day, now + 30 * day) + self._leaf("rsa", FIXTURE_NAME, rsa.generate_private_key(65537, 2048), + now - day, now + 30 * day) + self._leaf("wrong", WRONG_NAME, ec.generate_private_key(ec.SECP256R1()), + now - day, now + 30 * day) + self._leaf("expired", FIXTURE_NAME, ec.generate_private_key(ec.SECP256R1()), + now - 400 * day, now - 365 * day) + self._leaf("future", FIXTURE_NAME, ec.generate_private_key(ec.SECP256R1()), + now + 365 * day, now + 400 * day) + self._leaf("unknown", FIXTURE_NAME, ec.generate_private_key(ec.SECP256R1()), + now - day, now + 30 * day, issuer=(self.unknown_root, self.unknown_key), + with_intermediate=False) + + def close(self) -> None: + if self._tmp is not None: + self._tmp.cleanup() + + @property + def root_der(self) -> bytes: + return self.root.public_bytes(serialization.Encoding.DER) + + def root_pem_file(self) -> Path: + path = self.dir / "root.pem" + path.write_bytes(self.root.public_bytes(serialization.Encoding.PEM)) + return path + + @staticmethod + def _name(cn: str) -> x509.Name: + return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)]) + + def _ca(self, cn, key, issuer, issuer_key, now) -> x509.Certificate: + day = datetime.timedelta(days=1) + builder = (x509.CertificateBuilder() + .subject_name(self._name(cn)) + .issuer_name(issuer.subject if issuer is not None else self._name(cn)) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - 2 * day) + .not_valid_after(now + 60 * day) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), + critical=False) + .add_extension(x509.KeyUsage(digital_signature=False, content_commitment=False, + key_encipherment=False, data_encipherment=False, + key_agreement=False, key_cert_sign=True, + crl_sign=True, encipher_only=False, + decipher_only=False), critical=True)) + signer = issuer_key if issuer_key is not None else key + builder = builder.add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()), critical=False) + return builder.sign(signer, hashes.SHA256()) + + def _leaf(self, label, cn, key, not_before, not_after, issuer=None, + with_intermediate=True) -> None: + ca, ca_key = issuer if issuer is not None else (self.intermediate, self.int_key) + cert = (x509.CertificateBuilder() + .subject_name(self._name(cn)) + .issuer_name(ca.subject) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(not_before) + .not_valid_after(not_after) + .add_extension(x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), + critical=False) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), + critical=False) + .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key( + ca_key.public_key()), critical=False) + .sign(ca_key, hashes.SHA256())) + cert_file = self.dir / f"{label}.pem" + key_file = self.dir / f"{label}.key" + pem = cert.public_bytes(serialization.Encoding.PEM) + if with_intermediate: + pem += self.intermediate.public_bytes(serialization.Encoding.PEM) + cert_file.write_bytes(pem) + key_file.write_bytes(key.private_bytes(serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption())) + der = cert.public_bytes(serialization.Encoding.DER) + self.chains[label] = Chain(label, cert_file, key_file, der, spki_sha256(der)) + + def issue(self, label: str, cn: str) -> Chain: + """One more P-256 leaf under the test root, for a stand-in host (self-test).""" + day = datetime.timedelta(days=1) + self._leaf(label, cn, ec.generate_private_key(ec.SECP256R1()), + self.now - day, self.now + 30 * day) + return self.chains[label] + + +@dataclass +class Behaviour: + """What one server does with each connection.""" + min_version: ssl.TLSVersion = ssl.TLSVersion.TLSv1_3 + max_version: ssl.TLSVersion = ssl.TLSVersion.TLSv1_3 + # OpenSSL cipher string for TLS 1.2; TLS 1.3 suites are left at their default. + ciphers: str | None = None + # One curve name ("prime256v1"), to force an HRR or a P-256 group. + ecdh_curve: str | None = None + num_tickets: int | None = None + # Seconds to hold the ClientHello before answering it. + delay_handshake: float = 0.0 + # Accept the TCP connection and never answer (S10). + stall: bool = False + # Read the ClientHello, then reset the connection (S7c). + rst_after_client_hello: bool = False + # The listener's SO_RCVBUF, so a server that stops reading fills TCP soon. + rcvbuf: int | None = None + # Sent once, as one write, right after the handshake. + send: bytes = b"" + # After `send`: "echo" (until the client ends), "close_notify", "fin" (no + # close_notify), "hold" (read and discard), "http" (one 200, then + # close_notify), or "stall" (never read again, so writes fill TCP; S32). + then: str = "echo" + + +@dataclass +class ConnLog: + """What the server saw on one connection.""" + peer: str + sni: str | None = None + version: str | None = None + cipher: str | None = None + received: bytearray = field(default_factory=bytearray) + sent: int = 0 + # How the client ended it: "close_notify", "fin", "reset", "open" (still + # open when the server gave up), or "handshake" (it never completed). + peer_end: str = "open" + # After the server's own close_notify ("close_notify" mode): whether the + # client answered with one before it closed (True), or ended without it + # (False). None when the server did not close that way. + notify_reply: bool | None = None + error: str | None = None + done: threading.Event = field(default_factory=threading.Event) + + def as_dict(self) -> dict: + return {"peer": self.peer, "sni": self.sni, "version": self.version, + "cipher": self.cipher, "received": len(self.received), + "notify_reply": self.notify_reply, + "received_sha256": hashlib.sha256(self.received).hexdigest(), + "sent": self.sent, "peer_end": self.peer_end, "error": self.error} + + +class TlsServer: + """One TLS server on this machine, with one Behaviour for every connection.""" + + def __init__(self, bind_ip: str, chain: Chain | None, behaviour: Behaviour, + port: int = 0) -> None: + self.behaviour = behaviour + self.chain = chain + self.logs: list[ConnLog] = [] + self._lock = threading.Lock() + self._stop = threading.Event() + self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if behaviour.rcvbuf: + self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, behaviour.rcvbuf) + self.listener.bind((bind_ip, port)) + self.listener.listen(8) + self.listener.settimeout(0.2) + self.ip, self.port = self.listener.getsockname()[:2] + self.context = self._context() if chain is not None else None + self._threads: list[threading.Thread] = [] + # Every accepted socket, so close() can end the ones still waiting. + self._open: set = set() + self._acceptor = threading.Thread(target=self._accept_loop, daemon=True) + self._acceptor.start() + + def _context(self) -> ssl.SSLContext: + b = self.behaviour + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.minimum_version = b.min_version + ctx.maximum_version = b.max_version + ctx.load_cert_chain(str(self.chain.cert_file), str(self.chain.key_file)) + if b.ciphers: + ctx.set_ciphers(b.ciphers) + if b.ecdh_curve: + ctx.set_ecdh_curve(b.ecdh_curve) + if b.num_tickets is not None: + ctx.num_tickets = b.num_tickets + + def sni(sslobj, name, _ctx) -> None: + log = getattr(sslobj, "_net_tls_log", None) + if log is not None: + log.sni = name + ctx.sni_callback = sni + return ctx + + def _accept_loop(self) -> None: + while not self._stop.is_set(): + try: + raw, addr = self.listener.accept() + except TimeoutError: + continue + except OSError: + return + log = ConnLog(f"{addr[0]}:{addr[1]}") + with self._lock: + self.logs.append(log) + thread = threading.Thread(target=self._serve, args=(raw, log), daemon=True) + self._threads.append(thread) + thread.start() + + def _serve(self, raw: socket.socket, log: ConnLog) -> None: + b = self.behaviour + # wrap_socket detaches `raw`, so whichever object owns the descriptor + # is the one to read from and to close. + conn = raw + with self._lock: + self._open.add(raw) + try: + raw.settimeout(CONN_TIMEOUT) + if b.stall: + log.peer_end = self._hold_raw(raw) + return + if b.rst_after_client_hello: + raw.recv(4096) + raw.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + log.peer_end = "handshake" + log.error = "reset after the ClientHello (by design)" + return + if b.delay_handshake: + time.sleep(b.delay_handshake) + tls = self.context.wrap_socket(raw, server_side=True, + do_handshake_on_connect=False, + suppress_ragged_eofs=False) + conn = tls + with self._lock: + self._open.discard(raw) + self._open.add(tls) + tls._net_tls_log = log # read by the SNI callback + try: + tls.do_handshake() + except (ssl.SSLError, OSError) as exc: + log.peer_end = "handshake" + log.error = f"handshake: {exc}" + return + log.version = tls.version() + log.cipher = tls.cipher()[0] if tls.cipher() else None + if b.send: + tls.sendall(b.send) + log.sent += len(b.send) + if b.then in ("close_notify", "fin"): + # Let the device's reads be what ends the stream. + time.sleep(0.5) + if b.then == "close_notify": + # SSL_shutdown sends ours and waits for the peer's. It returns only when the client's + # close_notify arrived; a bare FIN or reset raises instead. + tls.settimeout(NOTIFY_REPLY_WAIT) + try: + tls.unwrap() + log.notify_reply = True + except (ssl.SSLError, OSError): + log.notify_reply = False + # SSLSocket.shutdown drops the TLS layer first, so after + # "fin" this is a bare FIN with no close_notify ahead of it. + tls.shutdown(socket.SHUT_WR) + log.peer_end = self._drain_after_close(tls) + return + if b.then == "stall": + while not self._stop.wait(0.2): + pass + return + if b.then == "http": + self._http(tls, log) + return + self._echo(tls, log, echo=(b.then == "echo")) + except Exception as exc: # the log is the report; the thread must not die silently + log.error = f"{type(exc).__name__}: {exc}" + finally: + with self._lock: + self._open.discard(conn) + self._open.discard(raw) + try: + conn.close() + except OSError: + pass + log.done.set() + + def _echo(self, tls: ssl.SSLSocket, log: ConnLog, echo: bool) -> None: + while not self._stop.is_set(): + try: + data = tls.recv(4096) + except ssl.SSLEOFError: + log.peer_end = "fin" + return + except ssl.SSLZeroReturnError: + log.peer_end = "close_notify" + return + except (ConnectionResetError, BrokenPipeError): + log.peer_end = "reset" + return + except TimeoutError: + log.peer_end = "open" + return + except ssl.SSLError as exc: + log.peer_end = "error" + log.error = f"recv: {exc}" + return + if not data: + log.peer_end = "close_notify" + return + log.received += data + if echo: + tls.sendall(data) + log.sent += len(data) + + def _http(self, tls: ssl.SSLSocket, log: ConnLog) -> None: + while b"\r\n\r\n" not in log.received: + data = tls.recv(4096) + if not data: + log.peer_end = "close_notify" + return + log.received += data + body = b"ok\n" + response = (b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\nConnection: close\r\n\r\n" + % len(body)) + body + tls.sendall(response) + log.sent += len(response) + try: + tls.unwrap() + except (ssl.SSLError, OSError): + pass + log.peer_end = "close_notify" + + @staticmethod + def _hold_raw(raw: socket.socket) -> str: + try: + while raw.recv(4096): + pass + return "fin" + except (ConnectionResetError, BrokenPipeError): + return "reset" + except TimeoutError: + return "open" + + @staticmethod + def _drain_after_close(raw: socket.socket) -> str: + """How the client ended a connection the server has already closed for writing.""" + # The same idle bound: after the server's own close, a REST-route client + # can take minutes to read what is left (S6/S7: about 45 s for 3000 B). + raw.settimeout(CONN_TIMEOUT) + try: + while raw.recv(4096): + pass + return "fin" + except (ConnectionResetError, BrokenPipeError): + return "reset" + except TimeoutError: + return "open" + except OSError: + return "closed" + + def wait_connections(self, count: int, timeout: float = 15.0) -> list[ConnLog]: + """The first `count` connections, once each has finished (or `timeout`).""" + deadline = time.monotonic() + timeout + while True: + with self._lock: + logs = list(self.logs) + if len(logs) >= count and all(log.done.is_set() for log in logs[:count]): + return logs[:count] + if time.monotonic() > deadline: + return logs[:count] + time.sleep(0.05) + + def close(self) -> None: + self._stop.set() + try: + self.listener.close() + except OSError: + pass + with self._lock: + still_open = list(self._open) + for sock in still_open: + # Wakes a thread blocked in recv or unwrap, so it ends now rather + # than at CONN_TIMEOUT. + try: + # The plain socket's shutdown, under any TLS wrapper the other + # thread is still reading through. + socket.socket.shutdown(sock, socket.SHUT_RDWR) + except OSError: + pass + self._acceptor.join(timeout=2) + + +def local_address_towards(device_host: str) -> str: + """This machine's address on the route to the device (as net_target_test.py).""" + probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + probe.connect((device_host, 9)) + return probe.getsockname()[0] + finally: + probe.close() diff --git a/tests/e2e/io/command_interface/net_tls_mock.py b/tests/e2e/io/command_interface/net_tls_mock.py new file mode 100644 index 000000000..ff76bcfbb --- /dev/null +++ b/tests/e2e/io/command_interface/net_tls_mock.py @@ -0,0 +1,507 @@ +#!/usr/bin/env python3 +"""A simulated network target, for checking the UCI TLS suite without hardware. + +Two flavours, each a `net_tls_proto.Link`: + + "tls" answers $21-$25 the way doc/uci_tls.md says, doing + real TLS from this machine with Python's ssl module, so a scenario + that passes against it has exercised its own oracle end to end; + "stock" the firmware without the TLS commands: $21-$25 answer `21,UNKNOWN COMMAND`, and + the plain commands ($01, $07, $09, $10, $11) work. + +And mutants of "tls", each breaking one rule a scenario claims to guard, so +the self-test can show that scenario turning red: + + "bundle-accepts-all" BUNDLE verifies nothing (S5 / S4 must catch it) + "release-noop" $25 never closes anything (S19e must catch it) + "group-zero" the OPEN reply's group is 0 (S2 must catch it) + "info-ff-claims" `03 23 FF` claims every session (S19e2b must catch it) + "no-notify-reply" the peer's close_notify is not answered with ours (S6 must catch it) + "abort-ignored" an ABORT does not cancel an OPEN: it runs to its end and + leaves an unclaimed session (S19e, S19e2b must catch it) + "abort-leaves-entry" an ABORT ends the OPEN within a slice, but the session it + had begun stays open (S19e, S19e2b must catch it) + +It is a model of the contract, not of the firmware: timings are not +simulated, a READ takes what the socket has, and the group is reported as +x25519 because Python's ssl does not expose the negotiated one. Nothing here +is evidence about a device. +""" +from __future__ import annotations + +import hashlib +import ipaddress +import socket +import ssl +import time +from dataclasses import dataclass + +from net_tls_proto import ( + CA_MAX, HANDLE_RANGE, NET_CMD_CLOSE_SOCKET, NET_CMD_IDENTIFY, NET_CMD_OPEN_TCP, + NET_CMD_OPEN_TLS, NET_CMD_READ_SOCKET, NET_CMD_START_TLS, NET_CMD_TLS_INFO, + NET_CMD_TLS_RELEASE, NET_CMD_TLS_TRUST_CA, NET_CMD_WRITE_SOCKET, READ_MAX, + STATUS_INVALID_PARAMS, STATUS_OK, STATUS_OUT_OF_RANGE, STATUS_UNKNOWN_COMMAND, + TLS_COMMANDS, TRUST_BUNDLE, TRUST_CUSTOM, TRUST_PIN, AbortedCommand, Link, Result) + +try: + from cryptography import x509 + from cryptography.hazmat.primitives import serialization +except ImportError: # pragma: no cover + x509 = None + +MUTANTS = ("bundle-accepts-all", "release-noop", "group-zero", "info-ff-claims", + "abort-ignored", "abort-leaves-entry", "no-notify-reply") +FLAVOURS = ("tls", "stock", *MUTANTS) +MAX_TLS = 2 +ABORT_SLICE = 0.1 # a cancelled wait ends within one slice of the ABORT + +SUITES = { + "TLS_AES_128_GCM_SHA256": 0x1301, "TLS_AES_256_GCM_SHA384": 0x1302, + "TLS_CHACHA20_POLY1305_SHA256": 0x1303, + "ECDHE-ECDSA-AES128-GCM-SHA256": 0xC02B, "ECDHE-ECDSA-AES256-GCM-SHA384": 0xC02C, + "ECDHE-RSA-AES128-GCM-SHA256": 0xC02F, "ECDHE-RSA-AES256-GCM-SHA384": 0xC030, + "ECDHE-ECDSA-CHACHA20-POLY1305": 0xCCA9, "ECDHE-RSA-CHACHA20-POLY1305": 0xCCA8, +} +# The six hardened 1.2 suites of 1.7, as OpenSSL names them. +TLS12_CIPHERS = ":".join(name for name, code in SUITES.items() if code >= 0xC000) +ALERTS = {"PROTOCOL_VERSION": 70, "HANDSHAKE_FAILURE": 40, "INTERNAL_ERROR": 80, + "DECODE_ERROR": 50, "ILLEGAL_PARAMETER": 47, "UNEXPECTED_MESSAGE": 10} + + +def is_ipv4_literal(text: bytes) -> bool: + """lwIP's ip4addr_aton is laxer than this (127.1, 0x7f.0.0.1); the mock uses + inet_aton, which accepts the same short and hex forms.""" + try: + socket.inet_aton(text.decode("ascii")) + return True + except (OSError, UnicodeDecodeError): + return False + + +def status(text: str) -> bytes: + return text.encode("ascii") + + +@dataclass +class Entry: + kind: str # "tcp" or "tls" + sock: object + claimed: bool = True + open_reply: bytes = b"" + trust: int = 0 + spki: bytes = b"" + handshake_ms: int = 0 + sticky: bytes | None = None + + +class MockDevice(Link): + """A network target in Python. See the module docstring.""" + + def __init__(self, flavour: str = "tls", bundle_cafile: str | None = None, + resolver: dict[str, str] | None = None, system_bundle: bool = True) -> None: + super().__init__() + if flavour not in FLAVOURS: + raise ValueError(f"unknown flavour {flavour!r}") + self.flavour = flavour + self.name = f"mock-{flavour}" + self.can_abort_in_flight = True + self.bundle_cafile = bundle_cafile + self.system_bundle = system_bundle + self.resolver = resolver or {} + self.handles: dict[int, Entry] = {} + self.ca_state = "EMPTY" + self.ca_buf = bytearray() + self.ca_total = 0 + self.ca_der: bytes | None = None + self.ready = 0x07 # module, entropy, time + + # -- Link ---------------------------------------------------------------- + + def _command(self, command: bytes, bound: float) -> Result: + started = time.monotonic() + data, text = self._dispatch(command) + return Result(command, data, text, time.monotonic() - started) + + def abort_in_flight(self, command: bytes, abort_after: float, + bound: float | None = None) -> AbortedCommand: + # An ABORT cancels an OPEN_TLS / START_TLS within a slice and the module + # closes the session the command had begun (doc/uci_tls.md); the + # "abort-ignored" mutant lets it run to its end instead, and + # "abort-leaves-entry" ends it early but keeps the session. + before = set(self.handles) + started = time.monotonic() + self._dispatch(command) + elapsed = time.monotonic() - started + if self.flavour != "abort-ignored": + elapsed = abort_after + ABORT_SLICE + if self.flavour != "abort-leaves-entry": + for handle in set(self.handles) - before: + try: + self.handles.pop(handle).sock.close() + except OSError: + pass + self.log.append({"t": round(time.time(), 3), "link": self.name, + "command": command.hex(" "), "abort_after": abort_after, + "busy_at_abort": True, "bit2_cleared_after": round(elapsed, 3)}) + return AbortedCommand(command, abort_after, True, elapsed, 0x00) + + def startup_abort(self) -> float: + return 0.0 + + def reset(self) -> None: + """A C64 reset: every socket closed, CA EMPTY.""" + for entry in self.handles.values(): + try: + entry.sock.close() + except OSError: + pass + self.handles.clear() + self.ca_state, self.ca_der = "EMPTY", None + + # -- dispatch ------------------------------------------------------------ + + def _dispatch(self, command: bytes) -> tuple[bytes, bytes]: + if len(command) < 2: + return b"", STATUS_INVALID_PARAMS + code = command[1] + if self.flavour == "stock" and code in TLS_COMMANDS: + return b"", STATUS_UNKNOWN_COMMAND + if command[0] & 0x80: + # The no-reply bit: the reply is thrown away (command_intf.cc:166-171), + # and $21/$24 open nothing (r6 L-i). + if code in (NET_CMD_OPEN_TLS, NET_CMD_START_TLS): + return b"", STATUS_INVALID_PARAMS + exempt = code == NET_CMD_TLS_RELEASE or ( + code == NET_CMD_TLS_INFO and len(command) == 3 and command[2] == 0xFF + and self.flavour != "info-ff-claims") + if self.flavour != "stock" and not exempt: + for entry in self.handles.values(): + entry.claimed = True + if code != NET_CMD_TLS_TRUST_CA and self.ca_state == "UPLOADING": + self.ca_state = "EMPTY" + handler = { + NET_CMD_IDENTIFY: self._identify, NET_CMD_OPEN_TCP: self._open_tcp, + NET_CMD_CLOSE_SOCKET: self._close, NET_CMD_READ_SOCKET: self._read, + NET_CMD_WRITE_SOCKET: self._write, NET_CMD_OPEN_TLS: self._open_tls, + NET_CMD_TLS_TRUST_CA: self._trust_ca, NET_CMD_TLS_INFO: self._info, + NET_CMD_TLS_RELEASE: self._release, + }.get(code) + if handler is None: + return b"", STATUS_UNKNOWN_COMMAND + return handler(command) + + def _free_handle(self) -> int | None: + return next((h for h in HANDLE_RANGE if h not in self.handles), None) + + def _identify(self, command: bytes): + return b"MOCK NETWORK TARGET", STATUS_OK + + def _resolve(self, host: str) -> str | None: + if host in self.resolver: + return self.resolver[host] + try: + ipaddress.IPv4Address(host) + return host + except ValueError: + pass + try: + return socket.gethostbyname(host) + except OSError: + return None + + def _open_tcp(self, command: bytes): + if len(command) < 5: + return b"", STATUS_INVALID_PARAMS + port = command[2] | command[3] << 8 + host = command[4:].split(b"\x00")[0].decode("latin-1") + address = self._resolve(host) + if address is None: + return b"", status("84,UNRESOLVED HOST") + handle = self._free_handle() + if handle is None: + return b"", status("85,ERROR OPENING SOCKET") + try: + sock = socket.create_connection((address, port), timeout=10) + except OSError as exc: + return b"", status(f"11,ERROR ON CONNECT: {exc.errno or 116}") + self.handles[handle] = Entry("tcp", sock) + return bytes([handle]), STATUS_OK + + def _close(self, command: bytes): + if len(command) != 3: + return b"", STATUS_INVALID_PARAMS + entry = self.handles.pop(command[2], None) + if entry is None: + return b"", status("12,ERROR ON CLOSE: 9") + if entry.kind == "tls": + try: + entry.sock.settimeout(0.1) + entry.sock.unwrap() + except (OSError, ValueError, ssl.SSLError): + pass + try: + entry.sock.close() + except OSError: + pass + return b"", STATUS_OK + + def _read(self, command: bytes): + if len(command) != 5: + return b"", STATUS_INVALID_PARAMS + handle, maxlen = command[2], command[3] | command[4] << 8 + entry = self.handles.get(handle) + if entry is None: + return b"\xff\xff", status("02,NO DATA: 9") + if maxlen == 0 or maxlen > READ_MAX: + return b"", STATUS_OUT_OF_RANGE + if entry.sticky is not None: + return b"\x00\x00", entry.sticky + entry.sock.settimeout(0.25) + try: + data = entry.sock.recv(maxlen) + except (TimeoutError, ssl.SSLWantReadError): + return b"\xff\xff", status("02,NO DATA: 11") + except ssl.SSLEOFError: + self.handles.pop(handle, None) + entry.sock.close() + return b"\x00\x00", status("05,TLS CLOSED WITHOUT NOTIFY") + except ConnectionResetError: + entry.sticky = status("12,RECEIVE ERROR: 104") + return b"\x00\x00", entry.sticky + except ssl.SSLError as exc: + alert = self._alert(exc) + entry.sticky = status(f"14,TLS ALERT RECEIVED: {alert}" if alert + else "16,TLS SESSION FAILED: -0x7100") + return b"\x00\x00", entry.sticky + if not data: + self.handles.pop(handle, None) + if entry.kind == "tls" and self.flavour != "no-notify-reply": + try: + entry.sock.settimeout(0.5) + entry.sock.unwrap() # the answer to the peer's close_notify + except (OSError, ValueError, ssl.SSLError): + pass + entry.sock.close() + return b"\x00\x00", status("01,CONNECTION CLOSED BY HOST") + return len(data).to_bytes(2, "little") + data, STATUS_OK + + def _write(self, command: bytes): + if len(command) < 3: + return b"", STATUS_INVALID_PARAMS + entry = self.handles.get(command[2]) + if entry is None: + return b"\xff\xff", status("12,SEND ERROR: 9") + if entry.sticky is not None: + return b"\xff\xff", entry.sticky + data = command[3:] + try: + entry.sock.settimeout(5) + entry.sock.sendall(data) + except OSError as exc: + entry.sticky = status(f"12,SEND ERROR: {exc.errno or 32}") + return b"\xff\xff", entry.sticky + return len(data).to_bytes(2, "little"), STATUS_OK + + @staticmethod + def _alert(exc: Exception) -> int | None: + text = str(exc).upper() + for name, number in ALERTS.items(): + if f"ALERT_{name}" in text: + return number + return None + + # -- TLS ----------------------------------------------------------------- + + def _open_tls(self, command: bytes): + if len(command) < 7: + return b"", STATUS_INVALID_PARAMS + port, trust, flags = command[2] | command[3] << 8, command[4], command[5] + pin = None + if trust == TRUST_PIN: + if len(command) < 39: + return b"", STATUS_INVALID_PARAMS + pin, tail = command[6:38], command[38:] + else: + tail = command[6:] + parts = tail.split(b"\x00") + host, name = parts[0], None + if len(parts) == 2: + name = parts[1] or None + elif len(parts) == 3: + if not parts[1] or parts[2]: + return b"", STATUS_INVALID_PARAMS + name = parts[1] + elif len(parts) > 3: + return b"", STATUS_INVALID_PARAMS + if not host or len(host) > 253 or (name is not None and len(name) > 253): + return b"", STATUS_INVALID_PARAMS + effective = name if name is not None else (None if is_ipv4_literal(host) else host) + if trust in (TRUST_BUNDLE, TRUST_CUSTOM) and (effective is None or is_ipv4_literal(effective)): + return b"", STATUS_INVALID_PARAMS + if trust > TRUST_PIN or flags & 0xFE or (pin is not None and not any(pin)): + return b"", STATUS_OUT_OF_RANGE + if not self.ready & 1: + return b"", status("90,TLS NOT AVAILABLE") + if sum(1 for e in self.handles.values() if e.kind == "tls") >= MAX_TLS: + return b"", status("91,TLS SESSIONS IN USE") + if trust == TRUST_CUSTOM and self.ca_state != "LOADED": + return b"", status("97,NO CUSTOM CA") + if trust == TRUST_PIN and effective is not None and is_ipv4_literal(effective): + effective = None + address = self._resolve(host.decode("latin-1")) + if address is None: + return b"", status("84,UNRESOLVED HOST") + handle = self._free_handle() + if handle is None: + return b"", status("85,ERROR OPENING SOCKET") + try: + raw = socket.create_connection((address, port), timeout=10) + except OSError as exc: + return b"", status(f"11,ERROR ON CONNECT: {exc.errno or 116}") + ctx = self._context(trust, flags) + started = time.monotonic() + try: + raw.settimeout(15) + sock = ctx.wrap_socket(raw, server_hostname=effective.decode("ascii") if effective else None, + suppress_ragged_eofs=False) + except ssl.SSLCertVerificationError as exc: + raw.close() + return b"", self._verify_status(exc) + except TimeoutError: + raw.close() + return b"", status("15,TLS HANDSHAKE TIMEOUT") + except ConnectionResetError: + raw.close() + return b"", status("13,TLS HANDSHAKE FAILED: PEER RESET: 104") + except ssl.SSLError as exc: + raw.close() + alert = self._alert(exc) + return b"", status(f"14,TLS ALERT RECEIVED: {alert}" if alert + else "13,TLS HANDSHAKE FAILED: -0x7780") + except OSError as exc: + raw.close() + return b"", status(f"13,TLS HANDSHAKE FAILED: SEND ERROR: {exc.errno or 32}") + handshake_ms = int((time.monotonic() - started) * 1000) + der = sock.getpeercert(binary_form=True) + spki = self._spki(der) + if trust == TRUST_PIN and spki != pin: + sock.close() + return b"", status("96,PINNED KEY MISMATCH") + version = 0x0304 if sock.version() == "TLSv1.3" else 0x0303 + suite = SUITES.get(sock.cipher()[0], 0) + group = 0 if self.flavour == "group-zero" else 0x001D + bits = 1 if version == 0x0303 else 0 + reply = (bytes([handle]) + version.to_bytes(2, "little") + suite.to_bytes(2, "little") + + group.to_bytes(2, "little") + bytes([bits])) + self.handles[handle] = Entry("tls", sock, claimed=False, open_reply=reply, trust=trust, + spki=spki, handshake_ms=handshake_ms) + return reply, STATUS_OK + + def _context(self, trust: int, flags: int) -> ssl.SSLContext: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.minimum_version = ssl.TLSVersion.TLSv1_3 if flags & 1 else ssl.TLSVersion.TLSv1_2 + ctx.set_ciphers(TLS12_CIPHERS) + if trust == TRUST_PIN or (trust == TRUST_BUNDLE and self.flavour == "bundle-accepts-all"): + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + elif trust == TRUST_BUNDLE: + if self.system_bundle: + ctx.load_default_certs() + if self.bundle_cafile: + ctx.load_verify_locations(cafile=self.bundle_cafile) + else: + ctx.load_verify_locations(cadata=self.ca_der) + return ctx + + @staticmethod + def _spki(der: bytes) -> bytes: + if x509 is None or not der: + return b"\x00" * 32 + cert = x509.load_der_x509_certificate(der) + return hashlib.sha256(cert.public_key().public_bytes( + serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)).digest() + + @staticmethod + def _verify_status(exc: ssl.SSLCertVerificationError) -> bytes: + code = exc.verify_code + if code == 62: + return status("94,CERTIFICATE NAME MISMATCH: 0x00000004") + if code == 10: + return status("95,CERTIFICATE EXPIRED: 0x00000001") + if code == 9: + return status("95,CERTIFICATE EXPIRED: 0x00000200") + if code in (2, 19, 20, 21): + return status("93,CERTIFICATE NOT TRUSTED: 0x00000008") + return status("93,CERTIFICATE NOT TRUSTED: 0xFFFFFFFF") + + def _trust_ca(self, command: bytes): + if len(command) < 6: + return b"", STATUS_INVALID_PARAMS + offset, total = command[2] | command[3] << 8, command[4] | command[5] << 8 + chunk = command[6:] + if offset == 0: + if total == 0: + if chunk: + return b"", STATUS_INVALID_PARAMS + self.ca_state, self.ca_der = "EMPTY", None + return b"", STATUS_OK + if total > CA_MAX: + self.ca_state, self.ca_der = "EMPTY", None + return b"", STATUS_OUT_OF_RANGE + self.ca_state, self.ca_der = "UPLOADING", None + self.ca_buf, self.ca_total = bytearray(), total + elif self.ca_state != "UPLOADING" or offset != len(self.ca_buf) or total != self.ca_total: + if self.ca_state == "UPLOADING": + self.ca_state = "EMPTY" + return b"", STATUS_INVALID_PARAMS + if len(self.ca_buf) + len(chunk) > self.ca_total: + self.ca_state = "EMPTY" + return b"", STATUS_INVALID_PARAMS + self.ca_buf += chunk + if len(self.ca_buf) < self.ca_total: + return b"", STATUS_OK + der = bytes(self.ca_buf) + try: + cert = x509.load_der_x509_certificate(der) + constraints = cert.extensions.get_extension_for_class(x509.BasicConstraints).value + if not constraints.ca: + self.ca_state = "EMPTY" + return b"", status("97,CUSTOM CA REJECTED: NOT A CA") + except Exception: + self.ca_state = "EMPTY" + return b"", status("97,CUSTOM CA INVALID: -0x2180") + self.ca_state, self.ca_der = "LOADED", der + return b"", STATUS_OK + + def _info(self, command: bytes): + if len(command) != 3: + return b"", STATUS_INVALID_PARAMS + handle = command[2] + tls = [e for e in self.handles.values() if e.kind == "tls"] + if handle == 0xFF: + ready = self.ready | (0x08 if self.ca_state == "LOADED" else 0) + record = bytearray(16) + record[0:6] = bytes([1, MAX_TLS, len(tls), 0x07, ready, 0x03]) + record[6:9] = bytes([1]) + (8).to_bytes(2, "little") + record[9:12] = b"\xff\xff\xff" if ready & 1 else b"\x00\x00\x00" + record[12:14] = (3).to_bytes(2, "little") + record[14] = sum(1 for e in tls if not e.claimed) + return bytes(record), STATUS_OK + entry = self.handles.get(handle) + if entry is None or entry.kind != "tls": + return b"", STATUS_INVALID_PARAMS + r = entry.open_reply + record = (r[1:7] + bytes([entry.trust, r[7]]) + entry.spki + + entry.handshake_ms.to_bytes(4, "little") + bytes(4)) + return record, STATUS_OK + + def _release(self, command: bytes): + if len(command) != 2: + return b"", STATUS_INVALID_PARAMS + closed = 0 + if self.flavour != "release-noop": + for handle, entry in list(self.handles.items()): + if entry.kind == "tls" and not entry.claimed: + self._close(bytes([3, NET_CMD_CLOSE_SOCKET, handle])) + closed += 1 + return bytes([closed]), STATUS_OK diff --git a/tests/e2e/io/command_interface/net_tls_proto.py b/tests/e2e/io/command_interface/net_tls_proto.py new file mode 100644 index 000000000..c5d56804e --- /dev/null +++ b/tests/e2e/io/command_interface/net_tls_proto.py @@ -0,0 +1,569 @@ +#!/usr/bin/env python3 +"""The TLS commands of the UCI network target, as bytes, and two ways to send them. + +doc/uci_tls.md is the contract. This module knows the byte layouts of +$21-$25 and of the existing commands a TLS handle uses ($07, $09, $10, $11), +parses the replies, and carries every command over a `Link` with the client +deadlines: + + - B = 45 s from the PUSH for OPEN_TLS / START_TLS, 12 s for every other TLS + command, and 45 s (advice) for OPEN_TCP; + - at PUSH + B with no reply, write ABORT ($04 alone) and wait for $DF1C bit 2 + to read 0, up to the later of PUSH + B and ABORT + 12 s; + - bit 2 still 1 then: the interface is wedged, and the caller resets the C64. + +So no command here can hang a run: the longest any one of them can take is +PUSH + 57 s, after which it has either answered, been ABORTed, or been +reported as a wedge. + +Two links reach the registers, as in net_target_test.py: + RestLink machine:readmem / writemem DMA cycles, one per register access. + It can write ABORT while a command is still in PROCESSING, so it + is the route for the ABORT scenarios (S19e family). + NativeLink the 6502 agent (uci_agent.asm). The real program's timing, but + the agent cannot ABORT a command in flight. +net_tls_mock.py offers a third, a simulated device, for the offline self-test. +""" + +import time +from dataclasses import dataclass, field + +from report import Failure, detail +from uci import (CTRL_ABORT, CTRL_CLR_ERR, CTRL_DATA_ACC, CTRL_PUSH_CMD, MAX_REPLY_BLOCKS, + REG_COMMAND, ST_ABORT_P, ST_ERROR, ST_STATE_BUSY, ST_STATE_DATA_LAST, ST_STATE_DATA_MORE, + ST_STATE_IDLE, ST_STATE_MASK, TARGET_NETWORK, Uci, describe_status) + +# -- command codes (network_target.h) ---------------------------------------- +NET_CMD_IDENTIFY = 0x01 +NET_CMD_OPEN_TCP = 0x07 +NET_CMD_OPEN_UDP = 0x08 +NET_CMD_CLOSE_SOCKET = 0x09 +NET_CMD_READ_SOCKET = 0x10 +NET_CMD_WRITE_SOCKET = 0x11 +NET_CMD_OPEN_TLS = 0x21 +NET_CMD_TLS_TRUST_CA = 0x22 +NET_CMD_TLS_INFO = 0x23 +NET_CMD_START_TLS = 0x24 +NET_CMD_TLS_RELEASE = 0x25 +TLS_COMMANDS = (NET_CMD_OPEN_TLS, NET_CMD_TLS_TRUST_CA, NET_CMD_TLS_INFO, + NET_CMD_START_TLS, NET_CMD_TLS_RELEASE) +# The no-reply bit of byte 0 (command_target.h:9). +NO_REPLY = 0x80 + +TRUST_BUNDLE = 0 +TRUST_CUSTOM = 1 +TRUST_PIN = 2 +FLAG_REQUIRE_TLS13 = 0x01 + +INFO_CAPABILITY = 0xFF +INFO_CAPABILITY_BYTES = 16 +INFO_HANDLE_BYTES = 48 +OPEN_REPLY_BYTES = 8 + +# -- the client deadlines (and the advice for OPEN_TCP) ---------------------- +BOUND_OPEN = 45.0 +BOUND_OTHER = 12.0 +BOUND_OPEN_TCP = 45.0 +POST_ABORT_MIN = 12.0 +# A non-TLS command (IDENTIFY, CLOSE of a plain socket) is immediate. +BOUND_PLAIN = 12.0 + +# -- what the firmware answers, verbatim where the text is fixed ------------ +STATUS_OK = b"00,OK" +STATUS_UNKNOWN_COMMAND = b"21,UNKNOWN COMMAND" +STATUS_INVALID_PARAMS = b"81,INVALID PARAMS" +STATUS_OUT_OF_RANGE = b"82,PARAMETER(S) OUT OF RANGE" +STATUS_CLOSE_UNOWNED = b"12,ERROR ON CLOSE: 9" +STATUS_NO_DATA_IDLE = b"02,NO DATA: 11" +STATUS_NO_DATA_GONE = b"02,NO DATA: 9" +STATUS_PEER_CLOSED = b"01,CONNECTION CLOSED BY HOST" +STATUS_NO_NOTIFY = b"05,TLS CLOSED WITHOUT NOTIFY" +STATUS_HS_TIMEOUT = b"15,TLS HANDSHAKE TIMEOUT" +STATUS_TLS_IN_USE = b"91,TLS SESSIONS IN USE" +STATUS_NO_CUSTOM_CA = b"97,NO CUSTOM CA" +STATUS_PIN_MISMATCH = b"96,PINNED KEY MISMATCH" +# S5: the full text, because the code alone cannot tell an installation-order +# bug (which prints 0xFFFFFFFF) from the right answer. +STATUS_UNKNOWN_ROOT = b"93,CERTIFICATE NOT TRUSTED: 0x00000008" + +READ_MAX = 1472 +WRITE_MAX = 892 +CA_MAX = 1472 +CA_CHUNK = 889 +HANDLE_RANGE = range(16) # this firmware's handles + +# The IANA numbers the OPEN reply and INFO carry. +TLS13 = 0x0304 +TLS12 = 0x0303 +TLS13_SUITES = {0x1301, 0x1302, 0x1303} +TLS12_SUITES = {0xC02B, 0xC02C, 0xC02F, 0xC030, 0xCCA9, 0xCCA8} +GROUPS = {0x001D: "x25519", 0x0017: "secp256r1", 0x0018: "secp384r1", 0x0019: "secp521r1"} + + +def status_code(status: bytes) -> int | None: + """The two-digit code a status line starts with, or None.""" + if len(status) >= 2 and status[:2].isdigit(): + return int(status[:2]) + return None + + +@dataclass +class Result: + """Everything one command showed a client.""" + command: bytes + data: bytes + status: bytes + elapsed: float + # ABORTed at PUSH + B because no reply came in time. The reply, if + # it came later, was dropped by the ABORT. + aborted: bool = False + + @property + def code(self) -> int | None: + return status_code(self.status) + + @property + def ok(self) -> bool: + return self.status == STATUS_OK + + def describe(self) -> str: + shown = self.data[:24].hex(" ") + (" ..." if len(self.data) > 24 else "") + if self.aborted: + return f"no reply within its bound; ABORTed after {self.elapsed:.1f}s" + return f"[{len(self.data)} B: {shown}] {self.status.decode('latin-1')!r} in {self.elapsed:.2f}s" + + +class LinkLost(Failure): + """The route can no longer carry commands: wedged, or the agent stopped. + + The caller resets the C64, which is the recovery (doc/uci_tls.md) for a + wedge, and which also closes every TLS session the network target holds. + """ + + +@dataclass +class AbortedCommand: + """What an ABORT written during a command's PROCESSING left behind.""" + command: bytes + abort_after: float # seconds from the PUSH to the ABORT + busy_at_abort: bool # the command was still in PROCESSING then + bit2_cleared_after: float # seconds from the PUSH until $DF1C bit 2 read 0 + final_status: int # $DF1C once bit 2 was 0 + + +def bound_for(command: bytes) -> float: + """The client deadline B for this command.""" + code = command[1] if len(command) >= 2 else 0 + if code in (NET_CMD_OPEN_TLS, NET_CMD_START_TLS): + return BOUND_OPEN + if code in (NET_CMD_OPEN_TCP, NET_CMD_OPEN_UDP): + return BOUND_OPEN_TCP + if code in TLS_COMMANDS or code in (NET_CMD_READ_SOCKET, NET_CMD_WRITE_SOCKET, + NET_CMD_CLOSE_SOCKET): + return BOUND_OTHER + return BOUND_PLAIN + + +class Link: + """One way of handing commands to the network target.""" + + name = "link" + # Whether this link can write ABORT while a command is in PROCESSING. + can_abort_in_flight = False + + def __init__(self) -> None: + # Every command and its result, in order: the run's wire evidence. + self.log: list[dict] = [] + + def command(self, command: bytes, bound: float | None = None) -> Result: + bound = bound_for(command) if bound is None else bound + result = self._command(command, bound) + self.log.append({"t": round(time.time(), 3), "link": self.name, + "command": command.hex(" "), "data": result.data.hex(" "), + "status": result.status.decode("latin-1"), + "elapsed": round(result.elapsed, 3), "aborted": result.aborted}) + detail(f"{command[:40].hex(' ')}{' ...' if len(command) > 40 else ''} -> {result.describe()}") + return result + + def _command(self, command: bytes, bound: float) -> Result: + raise NotImplementedError + + def abort_in_flight(self, command: bytes, abort_after: float, + bound: float | None = None) -> AbortedCommand: + raise Failure(f"the {self.name} route cannot ABORT a command in flight") + + def startup_abort(self) -> float: + """Startup: presence check, $0C, then wait for bit 2 up to 45 s. Seconds taken.""" + raise NotImplementedError + + +class RestLink(Link): + """The registers over REST DMA, with the client deadlines and ABORT.""" + + name = "rest" + can_abort_in_flight = True + poll = 0.05 + + def __init__(self, uci: Uci) -> None: + super().__init__() + self.uci = uci + + def _wait_bit2(self, deadline: float) -> int: + """Wait for $DF1C bit 2 (ABORT pending) to read 0; the status, or LinkLost.""" + while True: + status = self.uci.status() + if not status & ST_ABORT_P: + return status + if time.monotonic() > deadline: + raise LinkLost(f"$DF1C bit 2 still set at the client deadline: " + f"{describe_status(status)}. The interface is wedged") + time.sleep(self.poll) + + def _abort(self, pushed: float, bound: float) -> int: + aborted = time.monotonic() + self.uci.control(CTRL_ABORT) + status = self._wait_bit2(max(pushed + bound, aborted + POST_ABORT_MIN)) + if status & ST_ERROR: + self.uci.control(CTRL_CLR_ERR) + return status + + def _push(self, command: bytes) -> float: + if not self.uci.release(): + raise LinkLost(f"the interface did not return to Idle before {command.hex(' ')}: " + f"{describe_status(self.uci.status())}") + self.uci.require_idle("before pushing a command") + for byte in command: + self.uci.poke(REG_COMMAND, byte) + pushed = time.monotonic() + self.uci.control(CTRL_PUSH_CMD) + return pushed + + def _command(self, command: bytes, bound: float) -> Result: + pushed = self._push(command) + blocks: list[bytes] = [] + status_text = b"" + wait_from = pushed + wait_bound = bound + while True: + # B bounds the first block; each later block gets 12 s from + # the data-accept of the block before it. + while True: + status = self.uci.status() + state = status & ST_STATE_MASK + if state in (ST_STATE_DATA_LAST, ST_STATE_DATA_MORE): + break + if time.monotonic() - wait_from > wait_bound: + self._abort(pushed, bound) + return Result(command, b"".join(blocks), b"", + time.monotonic() - pushed, aborted=True) + time.sleep(self.poll) + data, text = self.uci.drain() + blocks.append(data) + status_text = text or status_text + if state != ST_STATE_DATA_MORE: + break + if len(blocks) >= MAX_REPLY_BLOCKS: + raise Failure(f"reply to {command.hex(' ')} still said Data More after " + f"{MAX_REPLY_BLOCKS} blocks") + self.uci.control(CTRL_DATA_ACC) + wait_from, wait_bound = time.monotonic(), BOUND_OTHER + elapsed = time.monotonic() - pushed + self.uci.control(CTRL_DATA_ACC) + final = self.uci.status() + if (final & ST_STATE_MASK) != ST_STATE_IDLE or final & ST_ERROR: + raise LinkLost(f"the interface was {describe_status(final)} after the reply to " + f"{command.hex(' ')} was accepted, expected Idle") + return Result(command, b"".join(blocks), status_text, elapsed) + + def abort_in_flight(self, command: bytes, abort_after: float, + bound: float | None = None) -> AbortedCommand: + """PUSH, write ABORT ($04 alone) `abort_after` s later, wait out bit 2. + + This is the client of 1.1 "What a client does": after the ABORT it + writes nothing to $DF1C/$DF1D until bit 2 reads 0, up to the later of + PUSH + B and ABORT + 12 s. The reply, if any, is dropped by the ABORT. + """ + bound = bound_for(command) if bound is None else bound + pushed = self._push(command) + time.sleep(abort_after) + busy = (self.uci.status() & ST_STATE_MASK) == ST_STATE_BUSY + self.uci.control(CTRL_ABORT) + aborted = time.monotonic() + final = self._wait_bit2(max(pushed + bound, aborted + POST_ABORT_MIN)) + cleared = time.monotonic() - pushed + if final & ST_ERROR: + self.uci.control(CTRL_CLR_ERR) + if (final & ST_STATE_MASK) != ST_STATE_IDLE: + # A reply that arrived after bit 2 cleared cannot be: the ABORT is + # serviced right after the command returns. Accept anything left. + self.uci.release() + self.log.append({"t": round(time.time(), 3), "link": self.name, + "command": command.hex(" "), "abort_after": abort_after, + "busy_at_abort": busy, "bit2_cleared_after": round(cleared, 3), + "final": describe_status(final)}) + detail(f"{command[:40].hex(' ')} ABORTed {abort_after:.1f}s after its PUSH " + f"({'in PROCESSING' if busy else 'already answered'}); bit 2 cleared " + f"{cleared:.2f}s after the PUSH, then {describe_status(final)}") + return AbortedCommand(command, abort_after, busy, cleared, final) + + def startup_abort(self) -> float: + ident = self.uci.peek(REG_COMMAND) + if ident not in (0xC9, 0x49): + raise Failure(f"$DF1D reads ${ident:02X}, not $C9/$49: no command interface") + started = time.monotonic() + self.uci.control(CTRL_ABORT | CTRL_CLR_ERR) + self._wait_bit2(started + BOUND_OPEN) + self.uci.release() + return time.monotonic() - started + + +class NativeLink(Link): + """The registers from 6502 code on the C64 (uci_native.NativeUci).""" + + name = "native" + # One wrap of the agent's 16-bit wait counter is about 1.7 s at 1 MHz (by + # cycle count, not measured), so 40 wraps (about 67 s) outlast the host's + # own deadline (57 s for an open), which therefore fires first. + WAIT_WRAPS = 40 + + def __init__(self, agent) -> None: + super().__init__() + self.agent = agent + self.agent.wait_wraps = self.WAIT_WRAPS + + def _command(self, command: bytes, bound: float) -> Result: + # The agent cannot ABORT a command in flight, so its wait is the + # bound plus margin, and a command that outlives it loses the route. + self.agent.busy_timeout = bound + POST_ABORT_MIN + started = time.monotonic() + try: + transaction = self.agent.transact(command, single_part=False) + except Failure as exc: + raise LinkLost(f"the 6502 agent lost {command.hex(' ')}: {exc}") from exc + return Result(command, transaction.data, transaction.status_text, + time.monotonic() - started) + + def startup_abort(self) -> float: + # The agent's own transaction starts by handing back anything pending, + # and the run_prg that started it reset the C64 a moment ago. + return 0.0 + + +# -- command builders -------------------------------------------------------- + +def open_tls_command(port: int, host: str | bytes, trust: int = TRUST_BUNDLE, flags: int = 0, + name: str | bytes | None = None, pin: bytes | None = None, + tail: bytes | None = None, no_reply: bool = False) -> bytes: + """`03 21 port trust flags [pin] tail`, the tail being host [00 name].""" + head = bytes([TARGET_NETWORK | (NO_REPLY if no_reply else 0), NET_CMD_OPEN_TLS, + port & 0xFF, (port >> 8) & 0xFF, trust & 0xFF, flags & 0xFF]) + if pin is not None: + head += pin + if tail is None: + host_b = host.encode("ascii") if isinstance(host, str) else host + tail = host_b + if name is not None: + tail += b"\x00" + (name.encode("ascii") if isinstance(name, str) else name) + return head + tail + + +def open_tcp_command(host: str, port: int) -> bytes: + return (bytes([TARGET_NETWORK, NET_CMD_OPEN_TCP, port & 0xFF, (port >> 8) & 0xFF]) + + host.encode("ascii") + b"\x00") + + +def read_command(handle: int, maxlen: int) -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_READ_SOCKET, handle, maxlen & 0xFF, (maxlen >> 8) & 0xFF]) + + +def write_command(handle: int, data: bytes) -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_WRITE_SOCKET, handle]) + data + + +def close_command(handle: int) -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_CLOSE_SOCKET, handle]) + + +def info_command(handle: int) -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_TLS_INFO, handle]) + + +def release_command() -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_TLS_RELEASE]) + + +def trust_ca_command(offset: int, total: int, chunk: bytes) -> bytes: + return bytes([TARGET_NETWORK, NET_CMD_TLS_TRUST_CA, offset & 0xFF, (offset >> 8) & 0xFF, + total & 0xFF, (total >> 8) & 0xFF]) + chunk + + +def start_tls_command(handle: int, trust: int, flags: int = 0, name: str | None = None, + pin: bytes | None = None) -> bytes: + command = bytes([TARGET_NETWORK, NET_CMD_START_TLS, handle, trust, flags]) + if pin is not None: + command += pin + if name is not None: + command += name.encode("ascii") + return command + + +# -- replies ----------------------------------------------------------------- + +@dataclass +class Capability: + """TLS_INFO $FF: the capability record.""" + raw: bytes + + @property + def version(self) -> int: + return self.raw[0] + + @property + def max_sessions(self) -> int: + return self.raw[1] + + @property + def entries(self) -> int: + return self.raw[2] + + @property + def trust_modes(self) -> int: + return self.raw[3] + + @property + def ready(self) -> int: + return self.raw[4] + + @property + def versions(self) -> int: + return self.raw[5] + + @property + def module_version(self) -> tuple[int, int]: + return self.raw[6], int.from_bytes(self.raw[7:9], "little") + + @property + def store_date(self) -> bytes: + return self.raw[9:12] + + @property + def block_max_ms(self) -> int: + return int.from_bytes(self.raw[12:14], "little") + + @property + def unclaimed(self) -> int: + return self.raw[14] + + def as_dict(self) -> dict: + major, minor = self.module_version + return {"raw": self.raw.hex(" "), "interface": self.version, + "max_sessions": self.max_sessions, "entries": self.entries, + "trust_modes": self.trust_modes, "ready": self.ready, + "ready_bits": {"module": bool(self.ready & 1), "entropy": bool(self.ready & 2), + "time": bool(self.ready & 4), "custom_ca": bool(self.ready & 8)}, + "versions": self.versions, "module_version": f"{major}.{minor}", + "store_date": self.store_date.hex(" "), "block_max_ms": self.block_max_ms, + "unclaimed": self.unclaimed} + + +@dataclass +class OpenReply: + """The 8 bytes of a successful OPEN_TLS / START_TLS.""" + raw: bytes + + @property + def handle(self) -> int: + return self.raw[0] + + @property + def version(self) -> int: + return int.from_bytes(self.raw[1:3], "little") + + @property + def suite(self) -> int: + return int.from_bytes(self.raw[3:5], "little") + + @property + def group(self) -> int: + return int.from_bytes(self.raw[5:7], "little") + + @property + def bits(self) -> int: + return self.raw[7] + + def as_dict(self) -> dict: + return {"handle": self.handle, "version": f"0x{self.version:04X}", + "suite": f"0x{self.suite:04X}", "group": f"0x{self.group:04X}", + "bits": self.bits} + + +@dataclass +class HandleInfo: + """TLS_INFO for a handle: 48 bytes.""" + raw: bytes + + @property + def version(self) -> int: + return int.from_bytes(self.raw[0:2], "little") + + @property + def suite(self) -> int: + return int.from_bytes(self.raw[2:4], "little") + + @property + def group(self) -> int: + return int.from_bytes(self.raw[4:6], "little") + + @property + def trust(self) -> int: + return self.raw[6] + + @property + def bits(self) -> int: + return self.raw[7] + + @property + def spki_sha256(self) -> bytes: + return self.raw[8:40] + + @property + def handshake_ms(self) -> int: + return int.from_bytes(self.raw[40:44], "little") + + def as_dict(self) -> dict: + return {"version": f"0x{self.version:04X}", "suite": f"0x{self.suite:04X}", + "group": f"0x{self.group:04X}", "trust": self.trust, "bits": self.bits, + "spki_sha256": self.spki_sha256.hex(), "handshake_ms": self.handshake_ms} + + +@dataclass +class ReadReply: + """One READ_SOCKET: the 2-byte header, the payload, the status.""" + result: Result + + @property + def header(self) -> int | None: + data = self.result.data + return int.from_bytes(data[:2], "little") if len(data) >= 2 else None + + @property + def payload(self) -> bytes: + return self.result.data[2:] + + @property + def status(self) -> bytes: + return self.result.status + + @property + def gone(self) -> bool: + """01/05: the handle is closed and untracked; never CLOSE it.""" + return self.header == 0 and status_code(self.status) in (1, 5) + + +@dataclass +class TlsSession: + """What the suite knows about one handle it holds.""" + handle: int + reply: OpenReply + gone: bool = False + notes: list[str] = field(default_factory=list) diff --git a/tests/e2e/io/command_interface/net_tls_selftest.py b/tests/e2e/io/command_interface/net_tls_selftest.py new file mode 100644 index 000000000..1fb188371 --- /dev/null +++ b/tests/e2e/io/command_interface/net_tls_selftest.py @@ -0,0 +1,721 @@ +#!/usr/bin/env python3 +# Self-test: the UCI TLS suite against a simulated device; needs no hardware. + +"""Check net_tls_test.py without a device: it must go GREEN, RED, and red for the right reason. + +Seven parts, none of which touches any Ultimate: + +1. The client deadlines on the REST route, against fake registers: a late + reply is ABORTed, and a bit 2 that never clears is a LinkLost, never a hang. +2. The scenarios against net_tls_mock.MockDevice and the real local fixture: + the tls flavour GREEN (except S22, a mock limit), stock RED. +3. Mutants of the mock: the scenario guarding each broken rule must go red. +4. main() over real HTTP (tests/lib/device_double.py) for Tier 1 without S30: + --expect green on tls and red on stock exit 0, and swapped, 1. +5. No verdict without evidence, and setup failures are errors. +6. Setup refusals change no setting; READs and routes are bounded. +7. The fixture outlasts a slow reader (S13 over REST). + +Usage: net_tls_selftest.py [--quick] (--quick skips the tls flavour's 15 s +handshake-timeout scenario and the 16 KB record) +""" + +import argparse +import json +import os +import sys +import tempfile +import threading +import time +from pathlib import Path +from types import SimpleNamespace + +# The one stanza that puts the shared library on sys.path; see tests/lib/bootstrap.py. +sys.path.insert(0, str(next(p for p in Path(__file__).resolve().parents + if (p / "tests" / "lib").is_dir()) / "tests" / "lib")) +import bootstrap # noqa: E402,F401 +from report import Failure, check, check_skip, check_start, detail, section, suite_fail, suite_ok, suite_skip # noqa: E402 +from device_double import DeviceDouble # noqa: E402 +from uci import MAX_BLOCK_BYTES, Uci # noqa: E402 + +sys.path.insert(0, bootstrap.directory("e2e", "io", "command_interface")) +import net_tls_fixture as fx # noqa: E402 +import net_tls_proto as proto # noqa: E402 +import net_tls_test as suite # noqa: E402 +from net_tls_mock import ABORT_SLICE, MockDevice # noqa: E402 + +SUITE = "net_tls_selftest" +STANDINS = (("H1", "h1.standin.test"), ("H2", "h2.standin.test")) + + +# -- part 1: fake registers -------------------------------------------------- + +class FakeRegisters: + """$DF1B-$DF1F as a MachineApi: readmem / writemem, one command at a time.""" + + def __init__(self, busy: float, reply: bytes = b"\x05", text: bytes = b"00,OK", + stuck_abort: bool = False) -> None: + self.busy, self.reply, self.text, self.stuck = busy, reply, text, stuck_abort + self.state = "idle" + self.done_at = 0.0 + self.abort = False + self.resp = bytearray() + self.stat = bytearray() + + def _tick(self) -> None: + if self.state == "busy" and time.monotonic() >= self.done_at: + if self.abort: + # The ABORT is serviced right after the command returns: the + # reply is dropped and the state goes back to Idle. + self.state = "idle" + self.abort = self.stuck + else: + self.state = "reply" + self.resp, self.stat = bytearray(self.reply), bytearray(self.text) + + def _status(self) -> int: + self._tick() + value = {"idle": 0x00, "busy": 0x11, "reply": 0x20}[self.state] + if self.abort: + value |= 0x04 + if self.state == "reply": + value |= (0x80 if self.resp else 0) | (0x40 if self.stat else 0) + return value + + def _read(self, address: int) -> int: + if address == 0xDF1C: + return self._status() + if address == 0xDF1D: + return 0xC9 + if address == 0xDF1E: + return self.resp.pop(0) if self.resp else 0 + if address == 0xDF1F: + return self.stat.pop(0) if self.stat else 0 + return 0x02 + + def readmem(self, address: int, length: int = 1) -> bytes: + return bytes(self._read(address + i) for i in range(length)) + + def writemem(self, address: int, data: bytes, idempotent: bool = False) -> None: + if address != 0xDF1C: + return + for bits in data: + self._tick() + if bits & 0x01: + self.state, self.done_at = "busy", time.monotonic() + self.busy + if bits & 0x02 and self.state == "reply": + self.state = "idle" + if bits & 0x04: + # On an idle interface the ABORT is serviced at once. + self.abort = self.state == "busy" or self.stuck + + +def part1() -> bool: + section("part 1: client deadlines over fake registers") + ok = True + saved = proto.POST_ABORT_MIN + proto.POST_ABORT_MIN = 1.5 + try: + cases = [ + ("a reply inside its bound is collected", FakeRegisters(0.2), 2.0, "reply"), + ("a reply past its bound is ABORTed; bit 2 clears when the command ends", + FakeRegisters(1.0), 0.4, "aborted"), + ("bit 2 that never clears is LinkLost at the deadline, not a hang", + FakeRegisters(5.0, stuck_abort=True), 0.4, "lost"), + ] + for label, regs, bound, wanted in cases: + try: + with check(label): + link = proto.RestLink(Uci(regs, 30.0)) + started = time.monotonic() + try: + result = link.command(proto.info_command(0xFF), bound) + got = "aborted" if result.aborted else "reply" + if got == "reply" and (result.data, result.status) != (b"\x05", b"00,OK"): + raise Failure(f"collected {result.describe()}") + except proto.LinkLost: + got = "lost" + took = time.monotonic() - started + detail(f"{got} after {took:.2f}s") + if got != wanted: + raise Failure(f"{got}, expected {wanted}") + if took > bound + proto.POST_ABORT_MIN + 1.0: + raise Failure(f"took {took:.2f}s, past the client deadline") + except Failure: + ok = False + try: + with check("abort_in_flight: ABORT lands in PROCESSING; bit 2 clears at the command's end"): + regs = FakeRegisters(1.0) + outcome = proto.RestLink(Uci(regs, 30.0)).abort_in_flight( + proto.info_command(0xFF), 0.3, bound=5.0) + if not outcome.busy_at_abort or not 0.9 <= outcome.bit2_cleared_after <= 2.0: + raise Failure(str(outcome)) + except Failure: + ok = False + finally: + proto.POST_ABORT_MIN = saved + return ok + + +# -- parts 2 and 3: the mock ----------------------------------------------- + +class World: + """The fixture PKI, a stand-in public PKI and its HTTP servers.""" + + def __init__(self) -> None: + self.pki = fx.Pki() + self.public = fx.Pki() + self.public_root = str(self.public.root_pem_file()) + self.servers = [] + self.hosts = [] + self.resolver = {} + for hid, name in STANDINS: + chain = self.public.issue(hid, name) + server = fx.TlsServer("127.0.0.1", chain, fx.Behaviour(then="http")) + self.servers.append(server) + self.hosts.append(suite.Host(name, hid, ip="127.0.0.1", port=server.port)) + self.resolver[name] = "127.0.0.1" + + def device(self, flavour: str) -> MockDevice: + return MockDevice(flavour, bundle_cafile=self.public_root, resolver=self.resolver, + system_bundle=False) + + def args(self) -> SimpleNamespace: + return SimpleNamespace(module_minor=8, mac_cafile=self.public_root, strict_sni=True, + hosts=self.hosts) + + def run(self, flavour: str, sids: list[str]) -> dict[str, suite.Outcome]: + device = self.device(flavour) + + def reset(): + device.reset() + return device + scenarios = [s for s in suite.SCENARIOS if s.sid in sids] + outcomes, _ = suite.run_routes([(f"mock-{flavour}", lambda: device, reset)], scenarios, + self.args(), self.pki, "127.0.0.1", + {"peer", "fixture", "crypto", "internet"}) + device.reset() + return {o.scenario.sid: o for o in outcomes} + + def close(self) -> None: + for server in self.servers: + server.close() + self.pki.close() + self.public.close() + + +# -- part 4: main() over HTTP --------------------------------------------------- + +class UciDouble(DeviceDouble): + """The repository's REST double, with a command interface run by a MockDevice.""" + + def __init__(self, device: MockDevice) -> None: + super().__init__() + self.mock = device + self.configs.update({ + "C64 and Cartridge Settings": {"Command Interface": "Disabled"}, + "WiFi settings": {"WiFi Enabled": "Enabled"}, + "Network Settings": {"SNTP Enable": "Disabled"}, + "U64 Specific Settings": {"Turbo Control": "Manual"}, + }) + self.cmd = bytearray() + self.state = "idle" + self.abort = False + self.blocks: list[tuple[bytes, bytes]] = [] + self.resp = bytearray() + self.stat = bytearray() + self.uci_lock = threading.Lock() + + def route(self, method, path): + if path == "/v1/machine:readmem" and method == "GET": + return self._uci_read + if path == "/v1/machine:writemem" and method == "PUT": + return self._uci_write + if path == "/v1/machine:reset" and method == "PUT": + return self._reset + return super().route(method, path) + + def _reset(self, params): + self.mock.reset() + return self._ok_json(params) + + def _run(self, command: bytes) -> None: + # An ABORT cancels the command within a slice and the module closes the session it + # had begun (doc/uci_tls.md): the dispatch runs on a worker, and what it opens after + # the ABORT is closed again when it ends. + before = set(self.mock.handles) + box: list[tuple[bytes, bytes]] = [] + worker = threading.Thread(target=lambda: box.append(self.mock._dispatch(command)), daemon=True) + worker.start() + while worker.is_alive() and not self.abort: + worker.join(0.02) + if self.abort: + time.sleep(ABORT_SLICE) + with self.uci_lock: + self.state, self.abort, self.blocks = "idle", False, [] + threading.Thread(target=self._discard, args=(worker, before), daemon=True).start() + return + data, text = box[0] + with self.uci_lock: + if self.abort: + self.state, self.abort, self.blocks = "idle", False, [] + return + chunks = [data[i:i + MAX_BLOCK_BYTES] for i in range(0, len(data), MAX_BLOCK_BYTES)] + chunks = chunks or [b""] + self.blocks = [(chunk, text if i == len(chunks) - 1 else b"") + for i, chunk in enumerate(chunks)] + self._next_block() + + def _discard(self, worker: threading.Thread, before: set) -> None: + worker.join() + for handle in set(self.mock.handles) - before: + try: + self.mock.handles.pop(handle).sock.close() + except OSError: + pass + + def _next_block(self) -> None: + chunk, text = self.blocks.pop(0) + self.resp, self.stat = bytearray(chunk), bytearray(text) + self.state = "more" if self.blocks else "last" + + def _status(self) -> int: + value = {"idle": 0x00, "busy": 0x11, "last": 0x20, "more": 0x30}[self.state] + if self.abort: + value |= 0x04 + if self.state in ("last", "more"): + value |= (0x80 if self.resp else 0) | (0x40 if self.stat else 0) + return value + + def _byte(self, address: int) -> int: + if address == 0xDF1C: + return self._status() + if address == 0xDF1D: + return 0xC9 + if address == 0xDF1E: + return self.resp.pop(0) if self.resp else 0 + if address == 0xDF1F: + return self.stat.pop(0) if self.stat else 0 + return 0x02 + + def _uci_read(self, params): + address = int(params.get("address", "0"), 16) + if not 0xDF1B <= address <= 0xDF1F: + return super()._readmem(params) + length = int(params.get("length", "1")) + with self.uci_lock: + body = bytes(self._byte(address + i) for i in range(length)) + return 200, body, "application/octet-stream" + + def _uci_write(self, params): + address = int(params.get("address", "0"), 16) + data = bytes.fromhex(params.get("data", "")) + with self.uci_lock: + for value in data: + if address == 0xDF1D: + self.cmd.append(value) + elif address == 0xDF1C: + self._control(value) + return self._ok_json(params) + + def _control(self, bits: int) -> None: + if bits & 0x01 and self.state == "idle": + command, self.cmd = bytes(self.cmd), bytearray() + self.state = "busy" + threading.Thread(target=self._run, args=(command,), daemon=True).start() + if bits & 0x02: + if self.state == "more": + self._next_block() + elif self.state == "last": + self.state = "idle" + if bits & 0x04: + if self.state == "busy": + self.abort = True + else: + self.state, self.blocks, self.cmd = "idle", [], bytearray() + + +def part4(world: "World") -> bool: + section("part 4: main() over HTTP, against a REST double with a mocked network target") + ok = True + tier1 = ["S1", "S20", "S2", "S23", "S5", "S19e"] + for flavour, expect, code in (("tls", "green", 0), ("stock", "red", 0), + ("tls", "red", 1), ("stock", "green", 1)): + double = UciDouble(world.device(flavour)) + saved = {k: os.environ.get(k) for k in double.environment()} + os.environ.update(double.environment()) + try: + with tempfile.TemporaryDirectory() as results: + argv = ["-H", "127.0.0.1", "-t", "10", "--route", "rest", "--expect", expect, + "--results", results, "--module-minor", "8"] + for sid in tier1: + argv += ["--test", sid] + exit_code = suite.main(argv) + run = json.loads((Path(results) / "run.json").read_text()) + try: + with check(f"{flavour} with --expect {expect} exits {code}; run.json and settings"): + if exit_code != code: + raise Failure(f"exit {exit_code}") + settings = run.get("settings", {}) + wanted = {"Command Interface": "Enabled", "WiFi Enabled": "Enabled", + "SNTP Enable": "Enabled", "Turbo Control": "Off"} + if settings != wanted: + raise Failure(f"settings read back {settings}") + restored = double.configs["C64 and Cartridge Settings"]["Command Interface"] + if restored != "Disabled": + raise Failure(f"Command Interface left {restored!r}, not restored") + if double.configs["WiFi settings"]["WiFi Enabled"] != "Enabled": + raise Failure("WiFi Enabled was written back (it is one-way)") + sigs = {o["sid"]: o["signature"] for o in run["scenarios"]} + detail(str(sigs)) + if len(run["scenarios"]) != len(tier1) + 1: + raise Failure(f"{len(run['scenarios'])} scenario records") + resets = double.calls(path="/v1/machine:reset") + if not resets: + raise Failure("the C64 was never reset") + except Failure: + ok = False + finally: + for key, value in saved.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + double.close() + return ok + + +def run_main(world: "World", flavour: str, argv: list[str], fixture: bool = True, + native_fails: bool = False, wifi: str = "Enabled") -> tuple[int, dict, UciDouble]: + """suite.main() against a double; (exit code, run.json, the double).""" + double = UciDouble(world.device(flavour)) + double.configs["WiFi settings"]["WiFi Enabled"] = wifi + saved_env = {k: os.environ.get(k) for k in double.environment()} + os.environ.update(double.environment()) + saved_address, saved_start = fx.local_address_towards, suite.NativeUci.start + + def no_route(*_args, **_kw): + raise OSError("self-test: no route to the device") + + def no_agent(_self): + raise Failure("self-test: the agent did not start (64tass Exec format error)") + if not fixture: + fx.local_address_towards = no_route + if native_fails: + suite.NativeUci.start = no_agent + try: + with tempfile.TemporaryDirectory() as results: + try: + code = suite.main(["-H", "127.0.0.1", "-t", "10", "--results", results, *argv]) + except SystemExit as exc: # argparse refusing an option + code = exc.code + path = Path(results) / "run.json" + run = json.loads(path.read_text()) if path.exists() else {"scenarios": []} + finally: + fx.local_address_towards, suite.NativeUci.start = saved_address, saved_start + for key, value in saved_env.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + double.close() + return code, run, double + + +class SlowReads(proto.Link): + """READs that each take 50 ms and alternate data with `02,NO DATA: 11`.""" + name = "slow" + + def __init__(self) -> None: + super().__init__() + self.turn = 0 + + def _command(self, command: bytes, bound: float) -> proto.Result: + time.sleep(0.05) + self.turn += 1 + if self.turn % 2: + return proto.Result(command, (100).to_bytes(2, "little") + bytes(100), b"00,OK", 0.05) + return proto.Result(command, b"\xff\xff", proto.STATUS_NO_DATA_IDLE, 0.05) + + +def part5(world: "World") -> bool: + section("part 5: no verdict without evidence; setup failures are errors") + ok = True + t1 = ["--test", "tier1", "--module-minor", "8", "--route", "rest"] + cases = [ + ("tls, --expect green, the fixture cannot start -> exit 1", + "tls", ["--expect", "green", *t1], {"fixture": False}, 1), + ("stock, --expect red, the fixture cannot start -> exit 1", + "stock", ["--expect", "red", *t1], {"fixture": False}, 1), + ("mutant bundle-accepts-all, --expect green, no fixture -> exit 1", + "bundle-accepts-all", ["--expect", "green", *t1], {"fixture": False}, 1), + ("stock, --expect green, only S32 on REST (route n/a) -> exit 1", + "stock", ["--expect", "green", "--test", "S32", "--route", "rest"], {}, 1), + ("stock, --expect red, only the S33 measurement -> exit 1", + "stock", ["--expect", "red", "--test", "S33", "--route", "rest"], {}, 1), + ("WiFi Disabled and no --set-wifi: setup refuses, WiFi untouched -> exit 1", + "tls", ["--expect", "green", "--test", "S1", "--route", "rest", "--module-minor", "8"], + {"wifi": "Disabled"}, 1), + ("WiFi Disabled with --set-wifi: set and kept -> exit 0", + "tls", ["--expect", "green", "--test", "S1", "--route", "rest", "--module-minor", "8", + "--set-wifi"], {"wifi": "Disabled"}, 0), + ] + for label, flavour, argv, options, wanted in cases: + try: + with check(label): + code, run, double = run_main(world, flavour, argv, **options) + detail(str([(o["sid"], o["verdict"], o["signature"]) for o in run["scenarios"]])) + if code != wanted: + raise Failure(f"exit {code}") + wifi = double.configs["WiFi settings"]["WiFi Enabled"] + if options.get("wifi") == "Disabled" and "--set-wifi" not in argv and wifi != "Disabled": + raise Failure(f"WiFi Enabled was written ({wifi!r}) without --set-wifi") + if "--set-wifi" in argv and wifi != "Enabled": + raise Failure(f"--set-wifi left WiFi {wifi!r}") + except Failure: + ok = False + try: + with check("the native agent fails to start: REST records kept, native ERROR, exit 1"): + code, run, _ = run_main(world, "tls", ["--expect", "green", "--test", "S1", + "--module-minor", "8"], native_fails=True) + records = [(o["route"], o["sid"], o["verdict"]) for o in run["scenarios"]] + detail(str(records)) + rest = [r for r in records if r[0] == "rest"] + native = [r for r in records if r[0] == "native"] + if code != 1 or not rest or any(v != "PASS" for _, _, v in rest): + raise Failure(f"exit {code}, REST records {rest}") + if not native or any(v != "ERROR" for _, _, v in native): + raise Failure(f"native records {native}") + except Failure: + ok = False + try: + with check("read_until's budget is idle time: 2000 B over 50 ms READs, budget 0.5 s"): + ctx = suite.Ctx(SlowReads(), SimpleNamespace(), None, None, None, []) + got, end = ctx.read_until(0, 2000, budget=0.5) + if len(got) != 2000 or end is not None: + raise Failure(f"{len(got)} bytes, end {end}") + except Failure: + ok = False + return ok + + +class EmptyOk(proto.Link): + """READs that answer 00,OK with header $0000: not a 1.6 answer.""" + name = "empty-ok" + + def __init__(self) -> None: + super().__init__() + self.calls = 0 + + def _command(self, command: bytes, bound: float) -> proto.Result: + self.calls += 1 + if self.calls > 5000: + raise Failure("read_until was still reading after 5000 empty 00,OK READs: unbounded") + return proto.Result(command, b"\x00\x00", b"00,OK", 0.0) + + +def part6(world: "World") -> bool: + section("part 6: setup refusals and bounded reads") + ok = True + try: + with check("WiFi off, no --set-wifi: refused before ANY setting is written"): + code, run, double = run_main(world, "tls", ["--expect", "green", "--test", "S1", "--route", + "rest", "--module-minor", "8"], + wifi="Disabled") + ci = double.configs["C64 and Cartridge Settings"]["Command Interface"] + sntp = double.configs["Network Settings"]["SNTP Enable"] + if code != 1 or ci != "Disabled" or sntp != "Disabled": + raise Failure(f"exit {code}, Command Interface {ci!r}, SNTP {sntp!r}") + if not run.get("settings_before"): + raise Failure("run.json does not record the settings as found") + if double.calls(path="/v1/machine:reset"): + raise Failure("the C64 was reset although nothing was run") + except Failure: + ok = False + try: + with check("--route native with S19e selected: S19e ran on no route -> exit 1"): + outcomes = [suite.Outcome(suite.BY_NAME["S0"], "native", "PASS"), + suite.Outcome(suite.BY_NAME["S1"], "native", "PASS"), + suite.Outcome(suite.BY_NAME["S19e"], "native", "N/A")] + for o in outcomes: + suite.judge(o) + met, problems = suite.expectation_met(outcomes, "green") + detail(str(problems)) + if met: + raise Failure("met") + except Failure: + ok = False + try: + with check("READ answering 00,OK with no data: read_until fails, bounded"): + link = EmptyOk() + ctx = suite.Ctx(link, SimpleNamespace(), None, None, None, []) + try: + ctx.read_until(0, 100, budget=0.5) + raise Failure("read_until returned") + except Failure as exc: + if "unbounded" in str(exc): + raise + detail(f"failed as it should: {exc}") + except Failure: + ok = False + try: + from c64_test_harness.backends.device_lock import DeviceLock # noqa: PLC0415 + except ImportError: + DeviceLock = None + # Without the harness every run with --require-lock is refused for want of a DeviceLock, so this check + # would pass without looking at any lock. + if DeviceLock is None: + check_start("--require-lock with no session lock: refused, nothing changed") + check_skip("c64_test_harness is not installed, so there is no session lock to be missing") + else: + try: + with check("--require-lock with no session lock: refused, nothing changed"): + code, run, double = run_main(world, "tls", ["--expect", "green", "--test", "S1", "--route", + "rest", "--module-minor", "8", + "--require-lock"]) + ci = double.configs["C64 and Cartridge Settings"]["Command Interface"] + if code != 1 or ci != "Disabled": + raise Failure(f"exit {code}, Command Interface {ci!r}") + except Failure: + ok = False + if DeviceLock is None: + check_start("--require-lock inside this process's own lock (NET_TLS_LOCK_PID) runs -> exit 0") + check_skip("c64_test_harness is not installed, so there is no DeviceLock to take") + return ok + try: + with check("--require-lock inside this process's own lock (NET_TLS_LOCK_PID) runs -> exit 0"): + lock = DeviceLock("127.0.0.1") + if not lock.acquire(timeout=10): + raise Failure("could not take the 127.0.0.1 test lock") + os.environ["NET_TLS_LOCK_PID"] = str(os.getpid()) + try: + code, run, _ = run_main(world, "tls", ["--expect", "green", "--test", "S1", "--route", + "rest", "--module-minor", "8", + "--require-lock"]) + finally: + os.environ.pop("NET_TLS_LOCK_PID", None) + lock.release() + if code != 0: + raise Failure(f"exit {code}: {run.get('setup_error')}") + except Failure: + ok = False + return ok + + +SLOW_READER_SECONDS = 65.0 + + +def part7(world: "World") -> bool: + """A device run's S13-over-REST failure, modelled: a client that reads after more than 60 s. + + On the REST route the device needed about 250 s to read a 16 KB record before + it wrote (one REST call per byte). A fixture whose per-connection idle + timeout is shorter than the slowest route gives up and closes, and the + device's WRITE meets a reset: a fixture failure reported against the + firmware. + """ + section("part 7: the fixture outlasts a slow reader (S13 over REST)") + ok = True + try: + with check(f"a client that waits {SLOW_READER_SECONDS:.0f}s before reading 16 KB and " + f"writing 100 B still gets its echo"): + data = fx.payload(13, 16384) + server = fx.TlsServer("127.0.0.1", world.pki.chains["ecdsa"], + fx.Behaviour(send=data, then="echo")) + device = world.device("tls") + ctx = suite.Ctx(device, SimpleNamespace(), world.pki, "127.0.0.1", None, []) + try: + reply = ctx.expect_open(server.port, "127.0.0.1", + pin=world.pki.chains["ecdsa"].spki_sha256) + time.sleep(SLOW_READER_SECONDS) + got, end = ctx.read_until(reply.handle, len(data)) + if got != data: + raise Failure(f"{len(got)} of {len(data)} bytes ({end})") + suite.echo_round_trip(ctx, reply.handle, 100, seed=7) + ctx.close(reply.handle) + finally: + server.close() + device.reset() + detail(str([c.as_dict() for c in server.logs])) + except Failure: + ok = False + return ok + + +def judge_flavour(label: str, outcomes: dict, wanted: dict[str, str]) -> bool: + """`wanted` maps a sid to the signature it must show.""" + ok = True + for sid, signature in wanted.items(): + o = outcomes.get(sid) + try: + with check(f"{label}: {sid} shows {signature}"): + if o is None: + raise Failure("not run") + if o.signature != signature: + raise Failure(f"{o.signature}: {o.reason[:200]}") + except Failure: + ok = False + return ok + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--quick", action="store_true") + args = parser.parse_args() + if not fx.HAVE_CRYPTOGRAPHY: + suite_skip(SUITE, "the `cryptography` package is not installed") + return 0 + ok = part1() + world = World() + try: + everything = [s.sid for s in suite.SCENARIOS if s.default] + if args.quick: + everything = [sid for sid in everything if sid not in ("S10", "S13")] + section("part 2: the tls flavour goes GREEN") + tls = world.run("tls", everything) + wanted = {sid: ("CONTROL-PASS" if suite.BY_NAME[sid].kind == "control" else "GREEN") + for sid in everything} + wanted["S22"] = "FAIL" # the mock cannot report the negotiated group + ok &= judge_flavour("tls", tls, wanted) + section("part 2: the stock flavour goes RED") + stock = world.run("stock", everything) + wanted = {sid: ("CONTROL-PASS" if suite.BY_NAME[sid].kind == "control" else "RED") + for sid in everything} + ok &= judge_flavour("stock", stock, wanted) + try: + with check("--expect red is met by the stock run, and --expect green is not"): + red, problems = suite.expectation_met(list(stock.values()), "red") + green, _ = suite.expectation_met(list(stock.values()), "green") + if not red or green: + raise Failure(f"red met {red}, green met {green}: {problems[:3]}") + except Failure: + ok = False + section("part 3: each mutant turns its guard red") + for flavour, sids in (("bundle-accepts-all", ["S0", "S5"]), + ("release-noop", ["S0", "S19e2"]), + ("group-zero", ["S0", "S2"]), + ("info-ff-claims", ["S0", "S19e2b"])): + outcomes = world.run(flavour, sids) + ok &= judge_flavour(flavour, outcomes, {sid: "FAIL" for sid in sids[1:]}) + outcomes = world.run("no-notify-reply", ["S0", "S6"]) + ok &= judge_flavour("no-notify-reply", outcomes, {"S6": "FAIL"}) + for flavour in ("abort-ignored", "abort-leaves-entry"): + outcomes = world.run(flavour, ["S0", "S19e", "S19e2b"]) + ok &= judge_flavour(flavour, outcomes, {"S19e": "FAIL", "S19e2b": "FAIL"}) + if not args.quick: + ok &= part4(world) + ok &= part5(world) + ok &= part6(world) + if not args.quick: + ok &= part7(world) + finally: + world.close() + if ok: + suite_ok(SUITE, "GREEN with TLS, RED on stock, every mutant caught") + return 0 + suite_fail(SUITE, "see the checks above") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/e2e/io/command_interface/net_tls_test.py b/tests/e2e/io/command_interface/net_tls_test.py new file mode 100644 index 000000000..1444ffaa5 --- /dev/null +++ b/tests/e2e/io/command_interface/net_tls_test.py @@ -0,0 +1,1632 @@ +#!/usr/bin/env python3 +# E2E: TLS sockets on the UCI network target ($21-$25): RED on stock firmware, GREEN with TLS. + +"""End-to-end check of the UCI network target's TLS commands ($21-$25). + +The contract is doc/uci_tls.md; this suite checks it. Every +scenario is RED on firmware without the TLS commands, with the one signature +`21,UNKNOWN COMMAND` to its first TLS command, and GREEN on firmware with +them. The exceptions are marked `control` (they pass on both, and say the +test setup itself works) and `measurement` (they only record a number). + +Tier 1 is the RED signature and the smoke test to run first: + S0 startup sweep (CLOSE 0..15) control + S1 capability: `03 23 FF`, 16 bytes RED 21 / GREEN v1 record + S20 plain TCP round trip control + S2 PIN echo to this machine, TLS 1.3, INFO for the handle + S23 hardened TLS 1.2 fallback (EMS bit, one of the six suites) + S5 a refused certificate: exactly `93,CERTIFICATE NOT TRUSTED: 0x00000008`, + and `96` for a wrong pin + S19e an ABORTed OPEN is cancelled and leaves nothing, then $25 (REST route only) + S30 BUNDLE to real hosts (internet_hosts.json) with an HTTP GET +Tier 2 is the other scenarios this machine can drive (see --list). +Oracles come from the server side (net_tls_fixture.py logs), never from the device's claim. + +The suite first SETS and reads back Command Interface, WiFi Enabled (one-way on the U64: +never written back), SNTP Enable and Turbo Control Off, resets the C64 and sweeps the route. +Every command has a client deadline (45 s for an open, 12 s otherwise), then ABORT and, +if $DF1C bit 2 stays set, a C64 reset: nothing waits forever. +Results: --results (default .net_tls_results/-/): run.json and wire.jsonl. +--expect red exits 0 exactly when every TLS scenario is RED and every control passed. +""" + +import argparse +import datetime +import hashlib +import json +import os +import socket +import ssl +import subprocess +import sys +import time +import traceback +from dataclasses import dataclass, field +from pathlib import Path +from collections.abc import Callable + +# The one stanza that puts the shared library on sys.path; see tests/lib/bootstrap.py. +sys.path.insert(0, str(next(p for p in Path(__file__).resolve().parents + if (p / "tests" / "lib").is_dir()) / "tests" / "lib")) +import bootstrap # noqa: E402,F401 +import cli # noqa: E402 +import targets # noqa: E402 +from api import UltimateApi # noqa: E402 +from report import ( # noqa: E402 + FAIL, OK, SKIP, Failure, check, check_fail, check_ok, check_skip, check_start, check_warn, detail, + format_exception, section, suite_fail, suite_ok, warn) +from uci import Uci, interface_present # noqa: E402 +from uci_native import NativeUci # noqa: E402 + +sys.path.insert(0, bootstrap.directory("e2e", "io", "command_interface")) +import net_tls_fixture as fx # noqa: E402 +from net_tls_proto import ( # noqa: E402 + BOUND_OPEN, CA_CHUNK, GROUPS, HANDLE_RANGE, INFO_CAPABILITY, + INFO_CAPABILITY_BYTES, INFO_HANDLE_BYTES, NET_CMD_TLS_INFO, NET_CMD_TLS_RELEASE, + OPEN_REPLY_BYTES, STATUS_CLOSE_UNOWNED, STATUS_HS_TIMEOUT, STATUS_INVALID_PARAMS, + STATUS_NO_CUSTOM_CA, STATUS_NO_DATA_GONE, STATUS_NO_DATA_IDLE, STATUS_NO_NOTIFY, STATUS_OK, + STATUS_OUT_OF_RANGE, STATUS_PEER_CLOSED, STATUS_PIN_MISMATCH, STATUS_TLS_IN_USE, + STATUS_UNKNOWN_COMMAND, STATUS_UNKNOWN_ROOT, TLS12, TLS12_SUITES, TLS13, TLS13_SUITES, + TLS_COMMANDS, TRUST_BUNDLE, TRUST_CUSTOM, TRUST_PIN, WRITE_MAX, Capability, HandleInfo, + Link, LinkLost, NativeLink, OpenReply, ReadReply, RestLink, Result, close_command, + info_command, open_tcp_command, open_tls_command, read_command, release_command, + status_code, trust_ca_command, write_command) + +SUITE = "net_tls_test" +HERE = Path(__file__).resolve().parent +DEFAULT_RESULTS = HERE / ".net_tls_results" +HOSTS_FILE = HERE / "internet_hosts.json" +HOSTS_ENV = "NET_TLS_INTERNET_HOSTS" + +# What the runner sets, and whether it puts it back afterwards. WiFi Enabled is +# one-way on the U64 (network_esp32.cc:143-146: the disable branch is commented +# out), so writing it back would record a restore that did not happen. +SETTINGS = ( + ("C64 and Cartridge Settings", "Command Interface", "Enabled", True), + ("WiFi settings", "WiFi Enabled", "Enabled", False), + ("Network Settings", "SNTP Enable", "Enabled", True), + ("U64 Specific Settings", "Turbo Control", "Off", True), +) +REQUIRED_SETTING = "Command Interface" +WIFI_SETTING = "WiFi Enabled" +# INFO $FF [4]: module, entropy, trusted time. How long the module and SNTP may +# take to come up after the settings above. +READY_BITS = 0x07 +READY_WAIT_SECONDS = 90.0 + +ECHO_BYTES = 4096 +PEER_STREAM_BYTES = 3000 +BIG_RECORD_BYTES = 16384 +READ_CHUNK = 892 +READ_BUDGET_SECONDS = 20.0 +SLOW_HANDSHAKE_SECONDS = 4.0 +ABORT_AFTER_SECONDS = 1.5 +ABORT_ENDS_WITHIN = 1.5 # seconds after the ABORT, for a cancelled OPEN_TLS (a slice is 100 ms; REST polling adds some) +HANDSHAKE_MS = 15.0 +HTTP_READ_BUDGET_SECONDS = 15.0 +RESAMPLE_AFTER_SECONDS = 30.0 +MAC_SAMPLES = 3 +# A name no resolver answers (RFC 6761), and an address nothing answers SYNs on +# (RFC 5737 TEST-NET-1, dropped rather than refused on most networks). +UNRESOLVABLE = "e2e-unresolvable.invalid" +# S32 stops here: with a 4 KB receive buffer the stall comes within tens of +# WRITEs, and each native WRITE is a body-carrying writemem. +S32_MAX_WRITES = 100 +BLACKHOLE = "192.0.2.1" + + +# -- the record -------------------------------------------------------------- + +@dataclass +class Scenario: + sid: str + name: str + tier: int + kind: str # "tls" (RED on stock), "control", "measurement" + oracle: str + fn: Callable + needs: tuple = () # "fixture", "internet", "abort" + default: bool = True + + +@dataclass +class Outcome: + scenario: Scenario + route: str + verdict: str = "not run" # PASS, FAIL, SKIP, N/A (not on this route), ERROR + signature: str = "" # GREEN, RED, FAIL, CONTROL-PASS, ... + reason: str = "" + first_tls_status: str | None = None + elapsed: float = 0.0 + evidence: dict = field(default_factory=dict) + + def as_dict(self) -> dict: + s = self.scenario + return {"sid": s.sid, "name": s.name, "tier": s.tier, "kind": s.kind, + "route": self.route, "oracle": s.oracle, "verdict": self.verdict, + "signature": self.signature, "reason": self.reason, + "first_tls_status": self.first_tls_status, + "elapsed": round(self.elapsed, 2), "evidence": self.evidence} + + +class Ctx: + """One route's view of the device, the fixture and the open scenario.""" + + def __init__(self, link: Link, args, pki, bind_ip: str | None, + reset_c64: Callable[[], Link] | None, wire: list[dict]) -> None: + self.wire = wire + self.link = link + link.log = wire + self.args = args + self.pki = pki + self.bind_ip = bind_ip + self._reset_c64 = reset_c64 + self.servers: list[fx.TlsServer] = [] + self.outcome: Outcome | None = None + + # -- commands ------------------------------------------------------------ + + def cmd(self, command: bytes, bound: float | None = None) -> Result: + result = self.link.command(command, bound) + o = self.outcome + if o is not None and len(command) >= 2 and command[1] in TLS_COMMANDS: + if o.first_tls_status is None: + o.first_tls_status = result.status.decode("latin-1") + if result.status == STATUS_UNKNOWN_COMMAND: + o.evidence.setdefault("unknown_command", []).append(command[:3].hex(" ")) + if result.aborted: + raise Failure(f"{command[:6].hex(' ')} gave no reply within its client deadline " + f"and was ABORTed after {result.elapsed:.1f}s") + return result + + def expect(self, result: Result, status: bytes, what: str) -> Result: + if result.status != status: + raise Failure(f"{what}: expected {status.decode()!r}, got {result.describe()}") + return result + + def info_ff(self) -> Capability: + r = self.cmd(info_command(INFO_CAPABILITY)) + self.expect(r, STATUS_OK, "TLS_INFO $FF") + if len(r.data) != INFO_CAPABILITY_BYTES: + raise Failure(f"TLS_INFO $FF answered {len(r.data)} bytes, not 16") + return Capability(r.data) + + def info(self, handle: int) -> HandleInfo: + r = self.cmd(info_command(handle)) + self.expect(r, STATUS_OK, f"TLS_INFO {handle}") + if len(r.data) != INFO_HANDLE_BYTES: + raise Failure(f"TLS_INFO {handle} answered {len(r.data)} bytes, not 48") + return HandleInfo(r.data) + + def open_tls(self, port: int, host: str, trust: int = TRUST_PIN, flags: int = 0, + name: str | None = None, pin: bytes | None = None) -> Result: + return self.cmd(open_tls_command(port, host, trust, flags, name, pin)) + + def expect_open(self, port: int, host: str, trust: int = TRUST_PIN, flags: int = 0, + name: str | None = None, pin: bytes | None = None) -> OpenReply: + r = self.open_tls(port, host, trust, flags, name, pin) + self.expect(r, STATUS_OK, "OPEN_TLS") + if len(r.data) != OPEN_REPLY_BYTES: + raise Failure(f"OPEN_TLS answered {len(r.data)} bytes, not 8: {r.data.hex(' ')}") + reply = OpenReply(r.data) + self.note("open", reply.as_dict()) + return reply + + def read(self, handle: int, maxlen: int = READ_CHUNK) -> ReadReply: + return ReadReply(self.cmd(read_command(handle, maxlen))) + + def read_until(self, handle: int, count: int, maxlens=(READ_CHUNK,), + budget: float = READ_BUDGET_SECONDS) -> tuple[bytes, ReadReply | None]: + """READ until `count` bytes or the stream ends; (bytes, the ending reply or None). + + `budget` is IDLE time: the clock restarts on every READ that brings at + least one byte. On the REST route every byte costs one REST call, so a + total-time budget would fail a healthy but slow transfer for the wrong + reason. A READ answering 00,OK with no bytes is not a valid READ answer + and fails at once, so the loop is always bounded. + """ + got = bytearray() + deadline = time.monotonic() + budget + index = 0 + while len(got) < count: + reply = self.read(handle, maxlens[index % len(maxlens)]) + index += 1 + if reply.result.ok: + if reply.header != len(reply.payload): + raise Failure(f"READ header {reply.header} but {len(reply.payload)} bytes") + if not reply.payload: + raise Failure("READ answered 00,OK with header $0000: the protocol has no " + "such answer (data is 1..maxlen; nothing yet is $FFFF + 02)") + got += reply.payload + deadline = time.monotonic() + budget + continue + if reply.header == 0xFFFF and reply.status == STATUS_NO_DATA_IDLE: + if time.monotonic() > deadline: + raise Failure(f"only {len(got)} of {count} bytes: no data for {budget:.0f}s") + time.sleep(0.05) + continue + return bytes(got), reply + return bytes(got), None + + def write(self, handle: int, data: bytes) -> None: + r = self.cmd(write_command(handle, data)) + self.expect(r, STATUS_OK, f"WRITE of {len(data)} bytes") + if r.data[:2] != len(data).to_bytes(2, "little"): + raise Failure(f"WRITE header {r.data[:2].hex(' ')}, expected {len(data)}") + + def close(self, handle: int) -> Result: + return self.cmd(close_command(handle)) + + def release(self) -> int: + r = self.cmd(release_command()) + self.expect(r, STATUS_OK, "TLS_RELEASE") + if len(r.data) != 1: + raise Failure(f"TLS_RELEASE answered {len(r.data)} bytes, not 1") + return r.data[0] + + def entries(self, wanted: int, what: str) -> Capability: + cap = self.info_ff() + if cap.entries != wanted: + raise Failure(f"{what}: INFO $FF [2] = {cap.entries}, expected {wanted}") + return cap + + def upload_ca(self, der: bytes) -> Result: + last = None + for offset in range(0, len(der), CA_CHUNK): + last = self.cmd(trust_ca_command(offset, len(der), der[offset:offset + CA_CHUNK])) + if not last.ok: + return last + return last + + def sweep(self) -> list[int]: + """The startup CLOSE sweep of 0..15; the numbers that were held.""" + held = [] + for handle in HANDLE_RANGE: + r = self.link.command(close_command(handle)) + if r.status == STATUS_OK: + held.append(handle) + elif r.status != STATUS_CLOSE_UNOWNED: + raise Failure(f"CLOSE {handle} in the sweep answered {r.describe()}") + return held + + def reset_c64(self) -> None: + if self._reset_c64 is None: + raise Failure("this route cannot reset the C64") + self.link = self._reset_c64() + self.link.log = self.wire + + # -- fixture ------------------------------------------------------------- + + def server(self, chain: str | None, behaviour: fx.Behaviour) -> fx.TlsServer: + if self.pki is None or self.bind_ip is None: + raise Skipped("no local TLS fixture on this run (see the fixture check)") + server = fx.TlsServer(self.bind_ip, self.pki.chains[chain] if chain else None, behaviour) + self.servers.append(server) + return server + + def note(self, key: str, value) -> None: + if self.outcome is not None: + self.outcome.evidence.setdefault(key, []) + self.outcome.evidence[key].append(value) + + def close_servers(self) -> None: + for server in self.servers: + if self.outcome is not None: + self.outcome.evidence.setdefault("server", []).append( + {"port": server.port, "connections": [c.as_dict() for c in server.logs]}) + server.close() + self.servers.clear() + + +class Skipped(Failure): + """The scenario could not run here. Counts AGAINST every verdict.""" + + +class NotOnRoute(Skipped): + """By design the scenario does not apply to this route (S19e/S19e2b native, S32 REST). + + The only skip a verdict may ignore; the run still needs TLS evidence elsewhere. + """ + + +def tls13_server() -> fx.Behaviour: + return fx.Behaviour() + + +def tls12_server(**kw) -> fx.Behaviour: + return fx.Behaviour(min_version=ssl.TLSVersion.TLSv1_2, max_version=ssl.TLSVersion.TLSv1_2, + ciphers="ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:" + "ECDHE-ECDSA-CHACHA20-POLY1305", **kw) + + +def one_connection(server: fx.TlsServer, timeout: float = 15.0) -> fx.ConnLog: + logs = server.wait_connections(1, timeout) + if not logs: + raise Failure("the server saw no connection") + return logs[0] + + +def pin_of(ctx: Ctx, chain: str = "ecdsa") -> bytes: + return ctx.pki.chains[chain].spki_sha256 + + +def echo_round_trip(ctx: Ctx, handle: int, total: int, seed: int) -> bytes: + data = fx.payload(seed, total) + with check(f"{total} B echoed back byte exact, written in {WRITE_MAX} B WRITEs"): + got = bytearray() + for offset in range(0, total, WRITE_MAX): + ctx.write(handle, data[offset:offset + WRITE_MAX]) + part, end = ctx.read_until(handle, min(offset + WRITE_MAX, total) - len(got)) + got += part + if end is not None: + raise Failure(f"the stream ended early: {end.result.describe()}") + if bytes(got) != data: + raise Failure(f"echo differs (sha256 {hashlib.sha256(got).hexdigest()[:16]} vs " + f"{hashlib.sha256(data).hexdigest()[:16]})") + return data + + +def check_reply_bits(reply: OpenReply, version: int) -> None: + with check(f"OPEN reply: version 0x{version:04X}, a policy suite, a policy group, EMS bit"): + if reply.version != version: + raise Failure(f"version 0x{reply.version:04X}") + suites = TLS13_SUITES if version == TLS13 else TLS12_SUITES + if reply.suite not in suites: + raise Failure(f"suite 0x{reply.suite:04X} is not one of the policy suites") + if reply.group not in GROUPS: + raise Failure(f"group 0x{reply.group:04X} (0 is a FAIL in a GREEN run)") + ems = 1 if version == TLS12 else 0 + if reply.bits != ems: + raise Failure(f"byte 7 = 0x{reply.bits:02X}, expected 0x{ems:02X} (bit0 EMS)") + + +# -- Tier 1 ------------------------------------------------------------------ + +def s0_startup_sweep(ctx: Ctx) -> None: + if ctx.link.can_abort_in_flight: + with check("startup: $DF1D reads $C9/$49, $0C written, bit 2 back to 0 within 45 s"): + seconds = ctx.link.startup_abort() + detail(f"bit 2 cleared {seconds:.2f}s after the $0C") + else: + check_start("startup: $0C and the wait for bit 2") + check_skip("the 6502 agent starts from run_prg's reset, and writes no $0C itself") + with check("startup: CLOSE 0..15 each answers 00,OK or 12,ERROR ON CLOSE: 9"): + held = ctx.sweep() + ctx.note("swept", held) + detail(f"leftover handles closed: {held or 'none'}") + + +def s1_capability(ctx: Ctx) -> None: + with check("`03 23 FF` answers 00,OK with the 16-byte v1 record"): + cap = ctx.info_ff() + ctx.note("info_ff", cap.as_dict()) + detail(json.dumps(cap.as_dict())) + problems = [] + if cap.version != 1: + problems.append(f"[0] interface {cap.version}, not 1") + if cap.max_sessions != 2: + problems.append(f"[1] max sessions {cap.max_sessions}, not 2") + if cap.trust_modes != 0x07: + problems.append(f"[3] trust modes 0x{cap.trust_modes:02X}, not 07") + if cap.versions != 0x03: + problems.append(f"[5] versions 0x{cap.versions:02X}, not 03") + if cap.raw[15] != 0: + problems.append(f"[15] = {cap.raw[15]}, not 0") + if problems: + raise Failure("; ".join(problems)) + with check("the startup sweep left no entries: [2] = 0 and [14] = 0"): + if cap.entries or cap.unclaimed: + raise Failure(f"[2] = {cap.entries}, [14] = {cap.unclaimed}") + with check("ready bits match the configured state: module, entropy, time (0x07)"): + if cap.ready & READY_BITS != READY_BITS: + raise Failure(f"[4] = 0x{cap.ready:02X}: Wi-Fi and SNTP are set on, so b0-b2 are owed") + if cap.ready & 0x08: + raise Failure("[4] b3 (custom CA LOADED) is set after the startup reset") + with check("module version set and [9..11] = FF FF FF while b0 is set"): + major, minor = cap.module_version + if (major, minor) == (0, 0): + raise Failure("[6..8] = 0 with b0 set") + if cap.store_date != b"\xff\xff\xff": + raise Failure(f"[9..11] = {cap.store_date.hex(' ')}") + detail(f"module {major}.{minor}, block_max {cap.block_max_ms} ms") + if ctx.args.module_minor is not None and minor != ctx.args.module_minor: + raise Failure(f"module minor {minor}, expected {ctx.args.module_minor} (--module-minor)") + with check("`03 23 FF 00` (4 bytes) answers 81"): + ctx.expect(ctx.cmd(bytes([3, NET_CMD_TLS_INFO, 0xFF, 0])), STATUS_INVALID_PARAMS, "03 23 FF 00") + with check("`03 25` answers 1 byte, 0, 00,OK; `03 25 00` answers 81"): + if ctx.release() != 0: + raise Failure("$25 closed something with no OPEN before it") + ctx.expect(ctx.cmd(bytes([3, NET_CMD_TLS_RELEASE, 0])), STATUS_INVALID_PARAMS, "03 25 00") + with check("INFO on a handle that is not TLS answers 81 with no data"): + r = ctx.cmd(info_command(0x7F)) + ctx.expect(r, STATUS_INVALID_PARAMS, "03 23 7F") + + +def s20_plain_tcp(ctx: Ctx) -> None: + """Control: OPEN_TCP / WRITE / READ / CLOSE to this machine, on any firmware.""" + if ctx.bind_ip is None: + raise Skipped("this machine is not reachable from the device") + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind((ctx.bind_ip, 0)) + listener.listen(1) + listener.settimeout(10) + try: + with check("OPEN_TCP to this machine answers a handle"): + r = ctx.cmd(open_tcp_command(ctx.bind_ip, listener.getsockname()[1])) + ctx.expect(r, STATUS_OK, "OPEN_TCP") + handle = r.data[0] + conn, _ = listener.accept() + try: + with check("a 100-byte WRITE arrives, and 100 bytes sent back are READ"): + data = fx.payload(20, 100) + ctx.write(handle, data) + conn.settimeout(5) + got = b"" + while len(got) < 100: + got += conn.recv(100) + if got != data: + raise Failure("the bytes that arrived differ") + conn.sendall(data) + back, end = ctx.read_until(handle, 100) + if back != data: + raise Failure(f"READ gave {len(back)} bytes, not the 100 sent ({end})") + with check("CLOSE answers 00,OK"): + ctx.expect(ctx.close(handle), STATUS_OK, "CLOSE") + finally: + conn.close() + finally: + listener.close() + + +def s2_pin_echo(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + with check("OPEN_TLS PIN to this machine's IP (no name) answers 8 bytes, 00,OK"): + reply = ctx.expect_open(server.port, ctx.bind_ip, TRUST_PIN, pin=pin_of(ctx)) + check_reply_bits(reply, TLS13) + with check("INFO $FF: [2] = 1, [14] = 1 (the new entry is unclaimed until the next command)"): + cap = ctx.info_ff() + if (cap.entries, cap.unclaimed) != (1, 1): + raise Failure(f"[2] = {cap.entries}, [14] = {cap.unclaimed}") + with check("INFO for the handle: 48 bytes, the same version/suite/group, trust 2, SPKI = pin"): + info = ctx.info(reply.handle) + ctx.note("info", info.as_dict()) + if (info.version, info.suite, info.group) != (reply.version, reply.suite, reply.group): + raise Failure(f"INFO {info.as_dict()} differs from the OPEN reply {reply.as_dict()}") + if info.trust != TRUST_PIN or info.spki_sha256 != pin_of(ctx): + raise Failure(f"trust {info.trust}, SPKI {info.spki_sha256.hex()[:16]}") + if info.group == 0: + raise Failure("INFO group 0") + sent = echo_round_trip(ctx, reply.handle, ECHO_BYTES, seed=2) + with check("CLOSE answers 00,OK; INFO $FF [2] = 0 afterwards"): + ctx.expect(ctx.close(reply.handle), STATUS_OK, "CLOSE") + ctx.entries(0, "after CLOSE") + with check("server: TLS 1.3, no SNI (an IPv4 host, no name), sha256 of what it got, close_notify"): + log = one_connection(server) + ctx.note("conn", log.as_dict()) + if log.version != "TLSv1.3": + raise Failure(f"server negotiated {log.version}") + if log.sni is not None: + raise Failure(f"SNI {log.sni!r} was sent for an IP literal") + if hashlib.sha256(log.received).digest() != hashlib.sha256(sent).digest(): + raise Failure(f"server received {len(log.received)} bytes that differ from the payload") + if log.peer_end != "close_notify": + raise Failure(f"the client ended with {log.peer_end}, not close_notify") + + +def s23_tls12(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls12_server()) + with check("OPEN_TLS PIN, default flags, to a TLS 1.2-only server answers 00,OK"): + reply = ctx.expect_open(server.port, ctx.bind_ip, TRUST_PIN, pin=pin_of(ctx)) + check_reply_bits(reply, TLS12) + sent = echo_round_trip(ctx, reply.handle, WRITE_MAX, seed=23) + with check("CLOSE 00,OK; server log: TLSv1.2, a hardened suite, the bytes, close_notify"): + ctx.expect(ctx.close(reply.handle), STATUS_OK, "CLOSE") + log = one_connection(server) + ctx.note("conn", log.as_dict()) + if log.version != "TLSv1.2" or not (log.cipher or "").startswith("ECDHE-"): + raise Failure(f"server: {log.version} {log.cipher}") + if bytes(log.received) != sent or log.peer_end != "close_notify": + raise Failure(f"server got {len(log.received)} B, ended by {log.peer_end}") + + +def s5_refused_cert(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + with check("BUNDLE to a local-PKI server answers exactly " + f"{STATUS_UNKNOWN_ROOT.decode()!r} with no data"): + r = ctx.open_tls(server.port, ctx.bind_ip, TRUST_BUNDLE, name=fx.FIXTURE_NAME) + ctx.expect(r, STATUS_UNKNOWN_ROOT, "OPEN_TLS BUNDLE") + if r.data: + raise Failure(f"a refused OPEN answered {len(r.data)} data bytes") + with check("PIN with a key that is not the server's answers 96 with no data"): + r = ctx.open_tls(server.port, ctx.bind_ip, TRUST_PIN, pin=hashlib.sha256(b"x").digest()) + ctx.expect(r, STATUS_PIN_MISMATCH, "OPEN_TLS PIN") + with check("nothing leaked: INFO $FF [2] = 0; the server received 0 application bytes"): + ctx.entries(0, "after two refusals") + logs = server.wait_connections(2) + for log in logs: + ctx.note("conn", log.as_dict()) + if any(log.received for log in logs): + raise Failure("the server received application data on a refused connection") + if ctx.args.strict_sni and logs and logs[0].sni != fx.FIXTURE_NAME: + raise Failure(f"BUNDLE sent SNI {logs[0].sni!r}, expected {fx.FIXTURE_NAME!r}") + + +def s19e_abort_release(ctx: Ctx) -> None: + if not ctx.link.can_abort_in_flight: + raise NotOnRoute(f"the {ctx.link.name} route cannot ABORT a command in flight (REST only)") + with check("TLS_INFO $FF answers before the OPEN (and claims no session)"): + ctx.entries(0, "before the OPEN") + server = ctx.server("ecdsa", fx.Behaviour(delay_handshake=SLOW_HANDSHAKE_SECONDS)) + command = open_tls_command(server.port, ctx.bind_ip, TRUST_PIN, pin=pin_of(ctx)) + with check(f"ABORT {ABORT_AFTER_SECONDS}s into an OPEN_TLS: the command ends within about a slice, " + "long before the server's delay"): + aborted = ctx.link.abort_in_flight(command, ABORT_AFTER_SECONDS) + ctx.note("abort", {"busy_at_abort": aborted.busy_at_abort, + "bit2_cleared_after": round(aborted.bit2_cleared_after, 2)}) + if not aborted.busy_at_abort: + raise Failure("the OPEN had already answered when the ABORT was written, so this " + "run did not test an ABORT in PROCESSING") + # The server holds its answer SLOW_HANDSHAKE_SECONDS; an OPEN that was cancelled ends about a + # slice (100 ms) after the ABORT, plus what the register polling over REST adds. + if aborted.bit2_cleared_after > ABORT_AFTER_SECONDS + ABORT_ENDS_WITHIN: + raise Failure(f"bit 2 cleared {aborted.bit2_cleared_after:.1f}s after the PUSH, " + f"{aborted.bit2_cleared_after - ABORT_AFTER_SECONDS:.1f}s after the ABORT") + with check("`03 23 FF` (allowed in between): [2] = 0 and [14] = 0, the cancelled open left nothing"): + cap = ctx.info_ff() + if (cap.entries, cap.unclaimed) != (0, 0): + raise Failure(f"[2] = {cap.entries}, [14] = {cap.unclaimed}") + with check("`03 25` as the next command closes nothing: 1 byte, 00, 00,OK (harmless after an abort)"): + if (closed := ctx.release()) != 0: + raise Failure(f"$25 closed {closed}") + with check("a second `03 25` answers 0; INFO $FF [2] = 0, [14] = 0"): + if (closed := ctx.release()) != 0: + raise Failure(f"$25 closed {closed} the second time") + cap = ctx.info_ff() + if cap.entries or cap.unclaimed: + raise Failure(f"[2] = {cap.entries}, [14] = {cap.unclaimed}") + + +# -- S30: real hosts ----------------------------------------------------------- + +@dataclass +class Host: + host: str + hid: str = "" + ip: str | None = None # pinned, for the self-test's stand-ins + port: int = 443 + record: dict = field(default_factory=dict) + + +def load_hosts() -> list[Host]: + override = os.environ.get(HOSTS_ENV) + if override: + warn(f"{HOSTS_ENV} replaces the built-in hosts for this run: {override}") + return [Host(h.strip(), f"X{i + 1}") for i, h in enumerate(override.split(",")) if h.strip()] + entries = json.loads(HOSTS_FILE.read_text())["hosts"] + return [Host(e["host"], e["id"], record=e) for e in entries] + + +def mac_context(cafile: str | None) -> tuple[ssl.SSLContext, str]: + ctx = ssl.create_default_context(cafile=cafile) + if cafile: + return ctx, f"cafile {cafile}" + if ctx.cert_store_stats().get("x509_ca", 0) == 0: + try: + import certifi # noqa: PLC0415 - only when the default store is empty + return ssl.create_default_context(cafile=certifi.where()), "certifi" + except ImportError: + pass + return ctx, "the system default store" + + +def mac_view(host: Host, address: str, cafile: str | None) -> dict: + """One verified handshake from this machine to address:port with SNI = host.""" + ctx, store = mac_context(cafile) + with socket.create_connection((address, host.port), timeout=10) as raw: + with ctx.wrap_socket(raw, server_hostname=host.host) as tls: + der = tls.getpeercert(binary_form=True) + chain = [] + getter = getattr(tls, "get_verified_chain", None) + if getter is not None: + for cert in getter(): + chain.append(cert if isinstance(cert, bytes) else cert.public_bytes(1)) + return {"version": tls.version(), "spki": fx.spki_sha256(der).hex(), + "store": store, "chain": [describe_cert(c) for c in chain]} + + +def describe_cert(der: bytes) -> dict: + cert = fx.x509.load_der_x509_certificate(der) + return {"subject": cert.subject.rfc4514_string(), "issuer": cert.issuer.rfc4514_string(), + "sha256": hashlib.sha256(der).hexdigest()} + + +def s30_real_hosts(ctx: Ctx) -> None: + hosts = ctx.args.hosts if ctx.args.hosts is not None else load_hosts() + failures = [] + for host in hosts: + line = f"{host.hid} {host.host}" + try: + verdict = one_real_host(ctx, host) + detail(f"PASS {line}: {verdict}") + ctx.note("hosts", {"host": host.host, "verdict": "PASS", "detail": verdict}) + except Skipped as exc: + failures.append(f"{line}: {exc}") + ctx.note("hosts", {"host": host.host, "verdict": "UNREACHABLE", "detail": str(exc)}) + except Failure as exc: + failures.append(f"{line}: {exc}") + ctx.note("hosts", {"host": host.host, "verdict": "FAIL", "detail": str(exc)}) + with check("S30: INFO $FF [2] = 0 after the hosts"): + ctx.entries(0, "after S30") + if failures: + raise Failure(" | ".join(failures)) + + +def one_real_host(ctx: Ctx, host: Host) -> str: + with check(f"{host.host}: step 1, this machine resolves it and verifies a TLS handshake"): + try: + address = host.ip or socket.getaddrinfo(host.host, host.port, socket.AF_INET)[0][4][0] + except OSError as exc: + raise Skipped(f"FAIL internet unreachable: host: dns {host.host}: {exc}") from exc + try: + first = mac_view(host, address, ctx.args.mac_cafile) + except ssl.SSLError as exc: + raise Skipped(f"FAIL internet path failed TLS verification (this machine): " + f"{host.host} at {address}: {exc}; possible causes: a captive portal, TLS " + f"interception, or a broken or misconfigured host; step 1 cannot " + f"tell which") from exc + except OSError as exc: + raise Skipped(f"FAIL internet unreachable: host: connect {host.host}: {exc}") from exc + detail(f"{address}, {first['version']}, leaf SPKI {first['spki'][:16]}, via {first['store']}") + with check(f"{host.host}: step 2, the device's OPEN_TCP to the name and to {address}"): + for target in (host.host, address): + r = ctx.cmd(open_tcp_command(target, host.port)) + if not r.ok: + raise Skipped(f"FAIL internet unreachable: device: OPEN_TCP {target} " + f"{r.status.decode('latin-1')}") + ctx.expect(ctx.close(r.data[0]), STATUS_OK, "CLOSE") + with check(f"{host.host}: step 3, OPEN_TLS BUNDLE to {address} with name {host.host}"): + r = ctx.open_tls(host.port, address, TRUST_BUNDLE, name=host.host) + if not r.ok: + chain = "; ".join(f"{c['subject']} <- {c['issuer']}" for c in first["chain"]) + raise Failure(f"FAIL {host.host}: {r.status.decode('latin-1')} (this machine's chain: " + f"{chain or 'not available'})") + reply = OpenReply(r.data) + handle = reply.handle + info = ctx.info(handle) + gone = False + try: + with check(f"{host.host}: step 4, version/group policy, " + f"leaf SPKI among this machine's view"): + samples = {first["spki"]} + for _ in range(MAC_SAMPLES - 1): + samples.add(mac_view(host, address, ctx.args.mac_cafile)["spki"]) + if info.version == TLS12 and (info.suite not in TLS12_SUITES or not info.bits & 1): + raise Failure(f"1.2 without the hardened rules: {info.as_dict()}") + if info.version not in (TLS13, TLS12): + raise Failure(f"INFO version 0x{info.version:04X}") + if info.group not in GROUPS: + raise Failure(f"INFO group 0x{info.group:04X}") + if info.spki_sha256.hex() not in samples: + time.sleep(RESAMPLE_AFTER_SECONDS if ctx.args.hosts is None else 0) + samples.add(mac_view(host, address, ctx.args.mac_cafile)["spki"]) + if info.spki_sha256.hex() not in samples: + raise Failure(f"leaf key differs from this machine's view (same IP, same " + f"offer): device {info.spki_sha256.hex()[:16]}, this machine " + f"{sorted(s[:16] for s in samples)}") + with check(f"{host.host}: step 5, an HTTP GET over the session starts with HTTP/1."): + request = (f"GET / HTTP/1.1\r\nHost: {host.host}\r\nUser-Agent: u64-e2e\r\n" + f"Connection: close\r\n\r\n").encode("ascii") + ctx.write(handle, request) + got = bytearray() + deadline = time.monotonic() + HTTP_READ_BUDGET_SECONDS + while b"\r\n" not in got: + reply_r = ctx.read(handle, 512) + if reply_r.result.ok: + got += reply_r.payload + continue + if reply_r.gone: + gone = True + break + if reply_r.status != STATUS_NO_DATA_IDLE: + raise Failure(f"READ answered {reply_r.result.describe()}") + if time.monotonic() > deadline: + raise Failure("no status line within 15 s") + time.sleep(0.05) + status_line = bytes(got).split(b"\r\n")[0] + if not status_line.startswith(b"HTTP/1."): + raise Failure(f"the response starts {bytes(got[:40])!r}") + detail(f"{status_line.decode('latin-1')}, TLS 0x{info.version:04X}, " + f"group {GROUPS[info.group]}, handshake {info.handshake_ms} ms") + finally: + if not gone: + ctx.close(handle) + return (f"0x{info.version:04X} suite 0x{info.suite:04X} group {GROUPS.get(info.group)} " + f"handshake {info.handshake_ms} ms, {status_line.decode('latin-1')}") + + +# -- Tier 2 ------------------------------------------------------------------ + +def s6_peer_close(ctx: Ctx, then: str = "close_notify") -> None: + data = fx.payload(6, PEER_STREAM_BYTES) + server = ctx.server("ecdsa", fx.Behaviour(send=data, then=then)) + end_status = STATUS_PEER_CLOSED if then == "close_notify" else STATUS_NO_NOTIFY + with check(f"all {PEER_STREAM_BYTES} B delivered BEFORE $0000 + {end_status.decode()!r}"): + reply = ctx.expect_open(server.port, ctx.bind_ip, TRUST_PIN, pin=pin_of(ctx)) + got, end = ctx.read_until(reply.handle, PEER_STREAM_BYTES + 1) + if got != data: + raise Failure(f"{len(got)} of {PEER_STREAM_BYTES} bytes, or different bytes") + if end is None or end.header != 0 or end.status != end_status: + raise Failure(f"the stream ended with {end.result.describe() if end else 'nothing'}") + with check("the handle is GONE: a CLOSE answers 12,ERROR ON CLOSE: 9; INFO [2] = 0"): + ctx.expect(ctx.close(reply.handle), STATUS_CLOSE_UNOWNED, "CLOSE after the end") + ctx.entries(0, "after the end") + if then == "close_notify": + with check("the server saw OUR close_notify in answer to its own (RFC 8446 6.1, RFC 5246 7.2.1)"): + log = one_connection(server) + ctx.note("conn", log.as_dict()) + if log.notify_reply is not True: + raise Failure(f"the client ended without answering close_notify (notify_reply {log.notify_reply}, " + f"peer_end {log.peer_end})") + + +def s7_truncation(ctx: Ctx) -> None: + s6_peer_close(ctx, then="fin") + + +def s7c_rst_handshake(ctx: Ctx) -> None: + server = ctx.server(None, fx.Behaviour(rst_after_client_hello=True)) + with check("an RST after the ClientHello: `13,TLS HANDSHAKE FAILED: PEER RESET: 104`"): + r = ctx.open_tls(server.port, ctx.bind_ip, TRUST_PIN, pin=pin_of(ctx)) + ctx.expect(r, b"13,TLS HANDSHAKE FAILED: PEER RESET: 104", "OPEN_TLS") + ctx.entries(0, "after the reset") + + +def s10_handshake_timeout(ctx: Ctx) -> None: + server = ctx.server(None, fx.Behaviour(stall=True)) + with check("a server that never answers: 15 within HANDSHAKE_MS + 2 s; nothing leaked"): + r = ctx.open_tls(server.port, ctx.bind_ip, TRUST_PIN, pin=pin_of(ctx)) + ctx.expect(r, STATUS_HS_TIMEOUT, "OPEN_TLS") + if r.elapsed > HANDSHAKE_MS + 2 + 1: + raise Failure(f"15 after {r.elapsed:.1f}s") + ctx.entries(0, "after the timeout") + + +def s11_cap(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + handles = [] + try: + with check("two OPENs succeed, the third answers 91; after one CLOSE an OPEN works"): + handles.append(ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle) + handles.append(ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle) + ctx.expect(ctx.open_tls(server.port, ctx.bind_ip, pin=pin_of(ctx)), + STATUS_TLS_IN_USE, "third OPEN") + ctx.expect(ctx.close(handles.pop()), STATUS_OK, "CLOSE") + handles.append(ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle) + finally: + for handle in handles: + ctx.close(handle) + ctx.entries(0, "after the cap") + + +def s12_open_close(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + with check("20 x (OPEN PIN, CLOSE): every one 00,OK, INFO [2] = 0 after"): + for _ in range(20): + handle = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle + ctx.expect(ctx.close(handle), STATUS_OK, "CLOSE") + cap = ctx.entries(0, "after 20 cycles") + detail(f"module block_max {cap.block_max_ms} ms (heap is not exported over UCI)") + + +def s13_tickets_big_record(ctx: Ctx) -> None: + data = fx.payload(13, BIG_RECORD_BYTES) + server = ctx.server("ecdsa", fx.Behaviour(num_tickets=10, send=data, then="echo")) + reply = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)) + try: + with check("10 tickets, then one 16 KB record read with maxlen 1, 100, 893, 894, 1472"): + got, end = ctx.read_until(reply.handle, BIG_RECORD_BYTES, + maxlens=(1, 100, 893, 894, 1472), budget=120) + if got != data: + raise Failure(f"{len(got)} bytes, or different bytes ({end})") + echo_round_trip(ctx, reply.handle, 100, seed=131) + finally: + ctx.close(reply.handle) + + +def s3_custom_ca(ctx: Ctx) -> None: + with check("clear the CA (`03 22 00 00 00 00`) answers 00,OK, b3 clear"): + ctx.expect(ctx.cmd(trust_ca_command(0, 0, b"")), STATUS_OK, "clear") + if ctx.info_ff().ready & 0x08: + raise Failure("b3 still set after the clear") + with check("CUSTOM with nothing loaded answers 97,NO CUSTOM CA"): + ctx.expect(ctx.open_tls(1, ctx.bind_ip, TRUST_CUSTOM, name=fx.FIXTURE_NAME), + STATUS_NO_CUSTOM_CA, "OPEN CUSTOM") + with check(f"the test root ({len(ctx.pki.root_der)} B DER) uploads in chunks: 00,OK, b3 set"): + ctx.expect(ctx.upload_ca(ctx.pki.root_der), STATUS_OK, "final chunk") + if not ctx.info_ff().ready & 0x08: + raise Failure("b3 clear after the upload") + for chain in ("ecdsa", "rsa"): + server = ctx.server(chain, tls13_server()) + with check(f"CUSTOM {chain}: OPEN 00,OK; INFO SPKI = the server leaf's; echo"): + reply = ctx.expect_open(server.port, ctx.bind_ip, TRUST_CUSTOM, name=fx.FIXTURE_NAME) + info = ctx.info(reply.handle) + if info.spki_sha256 != pin_of(ctx, chain): + raise Failure("INFO SPKI is not the leaf this machine served") + echo_round_trip(ctx, reply.handle, 500, seed=3) + ctx.expect(ctx.close(reply.handle), STATUS_OK, "CLOSE") + for chain, prefix in (("wrong", b"94,"), ("expired", b"95,"), ("future", b"95,"), + ("unknown", b"93,")): + server = ctx.server(chain, tls13_server()) + with check(f"CUSTOM must-fail {chain}: {prefix.decode()} with no data, nothing leaked"): + r = ctx.open_tls(server.port, ctx.bind_ip, TRUST_CUSTOM, name=fx.FIXTURE_NAME) + if not r.status.startswith(prefix) or r.data: + raise Failure(r.describe()) + ctx.entries(0, "after the must-fails") + ctx.cmd(trust_ca_command(0, 0, b"")) + + +def s14_reset_cleanup(ctx: Ctx) -> None: + server = ctx.server("ecdsa", fx.Behaviour(then="hold")) + with check("two sessions and a LOADED CA, then a C64 reset"): + ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)) + ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)) + ctx.expect(ctx.upload_ca(ctx.pki.root_der), STATUS_OK, "upload") + ctx.reset_c64() + with check("the server sees both TCP connections end; INFO [2] = 0, b3 clear"): + logs = server.wait_connections(2, timeout=10) + ends = [log.peer_end for log in logs] + if len(logs) != 2 or "open" in ends: + raise Failure(f"connection ends seen by the server: {ends}") + cap = ctx.info_ff() + if cap.entries or cap.ready & 0x08: + raise Failure(f"[2] = {cap.entries}, [4] = 0x{cap.ready:02X}") + with check("OPEN CUSTOM after the reset answers 97,NO CUSTOM CA"): + ctx.expect(ctx.open_tls(server.port, ctx.bind_ip, TRUST_CUSTOM, name=fx.FIXTURE_NAME), + STATUS_NO_CUSTOM_CA, "OPEN CUSTOM") + + +def s19_params(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + port, ip, pin = server.port, ctx.bind_ip, pin_of(ctx) + head = bytes([3, 0x21, port & 0xFF, port >> 8]) + cases = [ + ("trust 3", head + bytes([3, 0]) + ip.encode(), STATUS_OUT_OF_RANGE), + ("flags $02", head + bytes([2, 2]) + pin + ip.encode(), STATUS_OUT_OF_RANGE), + ("flags $80", head + bytes([2, 0x80]) + pin + ip.encode(), STATUS_OUT_OF_RANGE), + ("all-zero pin", head + bytes([2, 0]) + bytes(32) + ip.encode(), STATUS_OUT_OF_RANGE), + ("empty host", head + bytes([2, 0]) + pin, STATUS_INVALID_PARAMS), + ("host 00 00", head + bytes([2, 0]) + pin + ip.encode() + b"\0\0", STATUS_INVALID_PARAMS), + ("254-byte host", head + bytes([2, 0]) + pin + b"a" * 254, STATUS_INVALID_PARAMS), + ("short pin", head + bytes([2, 0]) + pin[:20], STATUS_INVALID_PARAMS), + ("BUNDLE, IPv4 host, no name", head + bytes([0, 0]) + ip.encode(), STATUS_INVALID_PARAMS), + ("BUNDLE, explicit IPv4 name", head + bytes([0, 0]) + b"x.test\x00" + ip.encode(), + STATUS_INVALID_PARAMS), + ("BUNDLE, host 127.1", head + bytes([0, 0]) + b"127.1", STATUS_INVALID_PARAMS), + ("INFO, 2 bytes", bytes([3, 0x23]), STATUS_INVALID_PARAMS), + ("INFO, 4 bytes", bytes([3, 0x23, 0xFF, 0x00]), STATUS_INVALID_PARAMS), + ] + for label, command, expected in cases: + with check(f"{label} -> {expected.decode()}"): + r = ctx.cmd(command) + ctx.expect(r, expected, label) + if r.data: + raise Failure(f"{len(r.data)} data bytes with a refusal") + with check("flags $01 (REQUIRE_TLS13) is accepted, and `host 00` is a host with no name"): + r = ctx.cmd(head + bytes([2, 1]) + pin + ip.encode() + b"\0") + ctx.expect(r, STATUS_OK, "flags $01") + handle = r.data[0] + try: + with check("READ maxlen 0 and 1473 on a TLS handle -> 82"): + ctx.expect(ctx.cmd(read_command(handle, 0)), STATUS_OUT_OF_RANGE, "maxlen 0") + ctx.expect(ctx.cmd(read_command(handle, 1473)), STATUS_OUT_OF_RANGE, "maxlen 1473") + finally: + ctx.close(handle) + with check("a closed port -> 11, an unresolvable host -> 84"): + probe = socket.socket() + probe.bind((ip, 0)) + closed_port = probe.getsockname()[1] + probe.close() + r = ctx.open_tls(closed_port, ip, TRUST_PIN, pin=pin) + if status_code(r.status) != 11: + raise Failure(f"closed port: {r.describe()}") + r = ctx.open_tls(443, UNRESOLVABLE, TRUST_PIN, pin=pin) + if status_code(r.status) != 84: + raise Failure(f"unresolvable: {r.describe()}") + ctx.entries(0, "after the parameter cases") + + +def s19e2_release_spares_claimed(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + a = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle + try: + with check("READ on A (claims it), OPEN B (unclaimed), `03 25` -> 1"): + ctx.read(a, 16) + b = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle + if (closed := ctx.release()) != 1: + raise Failure(f"$25 closed {closed}") + with check("A still echoes; a READ on B's number -> $FFFF + 02,NO DATA: 9 (S19e2c)"): + echo_round_trip(ctx, a, 64, seed=192) + r = ctx.read(b, 16) + if r.header != 0xFFFF or r.status != STATUS_NO_DATA_GONE: + raise Failure(f"READ {b}: {r.result.describe()}") + finally: + ctx.close(a) + ctx.entries(0, "after S19e2") + + +def s19e2b_info_does_not_claim(ctx: Ctx) -> None: + if not ctx.link.can_abort_in_flight: + raise NotOnRoute(f"the {ctx.link.name} route cannot ABORT a command in flight (REST only)") + ctx.entries(0, "before the OPENs") + fast = ctx.server("ecdsa", tls13_server()) + slow = ctx.server("ecdsa", fx.Behaviour(delay_handshake=SLOW_HANDSHAKE_SECONDS)) + a = ctx.expect_open(fast.port, ctx.bind_ip, pin=pin_of(ctx)).handle + try: + with check("OPEN A, accept it, unused; `03 23 FF` twice: [2] = 1, [14] = 1 both times (INFO claims nothing)"): + for _ in range(2): + cap = ctx.info_ff() + if (cap.entries, cap.unclaimed) != (1, 1): + raise Failure(f"[2] = {cap.entries}, [14] = {cap.unclaimed}") + with check("ABORTed OPEN B leaves no entry: `03 23 FF` [2] = 1, [14] = 0; $25 -> 0"): + ctx.link.abort_in_flight(open_tls_command(slow.port, ctx.bind_ip, TRUST_PIN, + pin=pin_of(ctx)), ABORT_AFTER_SECONDS) + cap = ctx.info_ff() + if (cap.entries, cap.unclaimed) != (1, 0): + raise Failure(f"[2] = {cap.entries}, [14] = {cap.unclaimed}") + if (closed := ctx.release()) != 0: + raise Failure(f"$25 closed {closed}") + with check("A still echoes"): + echo_round_trip(ctx, a, 64, seed=193) + finally: + ctx.close(a) + + +def s22_groups(ctx: Ctx) -> None: + for curve, group in ((None, 0x001D), ("prime256v1", 0x0017)): + server = ctx.server("ecdsa", fx.Behaviour(ecdh_curve=curve)) + label = "a default 1.3 server" if curve is None else "a P-256-only server (HRR)" + with check(f"{label}: OPEN reply version 0x0304, group 0x{group:04X}"): + reply = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)) + ctx.close(reply.handle) + if (reply.version, reply.group) != (TLS13, group): + raise Failure(json.dumps(reply.as_dict())) + + +def s24_require13(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls12_server()) + with check("REQUIRE_TLS13 to a 1.2-only server: 14 with 70, or 18 with 0x0303 (recorded)"): + r = ctx.open_tls(server.port, ctx.bind_ip, TRUST_PIN, flags=1, pin=pin_of(ctx)) + if r.status not in (b"14,TLS ALERT RECEIVED: 70", b"18,TLS VERSION REFUSED: 0x0303"): + raise Failure(r.describe()) + ctx.note("variant", r.status.decode()) + ctx.entries(0, "after the refusal") + + +def s18_block_max(ctx: Ctx) -> None: + server = ctx.server("ecdsa", tls13_server()) + with check("after a handshake, INFO module_block_max_ms < 50 " + "(it is the longest the module's dispatcher blocked since boot)"): + handle = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)).handle + ctx.close(handle) + cap = ctx.info_ff() + ctx.note("block_max_ms", cap.block_max_ms) + if cap.block_max_ms >= 50: + raise Failure(f"block_max {cap.block_max_ms} ms") + + +def s32_write_stall(ctx: Ctx) -> None: + """S32: a WRITE stall, and the CLOSE time measured on the stalled socket.""" + if ctx.link.name == "rest": + raise NotOnRoute("hundreds of 892-B WRITEs cost a REST call per byte; run it native") + server = ctx.server("ecdsa", fx.Behaviour(then="stall", rcvbuf=4096)) + reply = ctx.expect_open(server.port, ctx.bind_ip, pin=pin_of(ctx)) + chunk = fx.payload(32, WRITE_MAX) + with check("WRITE until TCP is full: FFFF + 12 or 17, sticky; never a partial count"): + for count in range(1, S32_MAX_WRITES + 1): + r = ctx.cmd(write_command(reply.handle, chunk)) + if r.ok: + if r.data[:2] != WRITE_MAX.to_bytes(2, "little"): + raise Failure(f"WRITE {count}: partial count {r.data[:2].hex(' ')}") + continue + ctx.note("stall", {"writes_ok": count - 1, "status": r.status.decode("latin-1"), + "elapsed": round(r.elapsed, 2)}) + if r.data[:2] != b"\xff\xff" or status_code(r.status) not in (12, 17): + raise Failure(f"WRITE {count}: {r.describe()}") + again = ctx.cmd(write_command(reply.handle, b"x")) + if again.status != r.status: + raise Failure(f"not sticky: then {again.describe()}") + break + else: + raise Failure(f"{S32_MAX_WRITES} WRITEs never stalled") + with check("CLOSE on the stalled TLS socket answers 00,OK within 12 s (measured)"): + r = ctx.close(reply.handle) + ctx.note("close_elapsed", round(r.elapsed, 3)) + ctx.expect(r, STATUS_OK, "CLOSE") + detail(f"CLOSE took {r.elapsed:.2f}s (expected: about 1 s at most, then RST)") + + +def s34_big_curves(ctx: Ctx) -> None: + """Measurement: P-384 / P-521 under 1.3 and 1.2, CUSTOM (the TLS-task stack case).""" + ctx.expect(ctx.cmd(trust_ca_command(0, 0, b"")), STATUS_OK, "clear") + ctx.expect(ctx.upload_ca(ctx.pki.root_der), STATUS_OK, "upload") + for curve, group in (("secp384r1", 0x0018), ("secp521r1", 0x0019)): + for label, behaviour in (("1.3", fx.Behaviour(ecdh_curve=curve)), + ("1.2", tls12_server(ecdh_curve=curve))): + server = ctx.server("ecdsa", behaviour) + with check(f"CUSTOM, TLS {label}, {curve}: OPEN 00,OK, group 0x{group:04X}"): + reply = ctx.expect_open(server.port, ctx.bind_ip, TRUST_CUSTOM, + name=fx.FIXTURE_NAME) + info = ctx.info(reply.handle) + ctx.close(reply.handle) + cap = ctx.info_ff() + ctx.note("timing", {"curve": curve, "tls": label, "handshake_ms": info.handshake_ms, + "block_max_ms": cap.block_max_ms}) + detail(f"handshake {info.handshake_ms} ms, block_max {cap.block_max_ms} ms") + if reply.group != group: + raise Failure(f"group 0x{reply.group:04X}") + ctx.cmd(trust_ca_command(0, 0, b"")) + + +def s33_open_tcp_duration(ctx: Ctx) -> None: + """Measurement: how long a plain OPEN_TCP takes to give up.""" + for label, host in (("an address that drops SYNs", BLACKHOLE), + ("an unresolvable name", UNRESOLVABLE)): + check_start(f"OPEN_TCP to {label}: time to 11 / 84") + r = ctx.link.command(open_tcp_command(host, 80)) + ctx.note("open_tcp", {"target": label, "status": r.status.decode("latin-1"), + "elapsed": round(r.elapsed, 2), "aborted": r.aborted}) + if r.ok: + ctx.close(r.data[0]) + check_ok(f"{r.status.decode('latin-1') or 'ABORTed'} after {r.elapsed:.1f}s") + + +SCENARIOS = [ + Scenario("S0", "startup-sweep", 1, "control", "every CLOSE 0..15 answers 00 or 12,…: 9", + s0_startup_sweep), + Scenario("S1", "capability", 1, "tls", "16-byte v1 record, ready 0x07, length checks", + s1_capability), + Scenario("S20", "plain-tcp", 1, "control", "OPEN_TCP/WRITE/READ/CLOSE round trip", + s20_plain_tcp, ("peer",)), + Scenario("S2", "pin-echo", 1, "tls", "PIN, TLS 1.3, 4096 B echo, INFO SPKI = pin", + s2_pin_echo, ("fixture",)), + Scenario("S23", "tls12-fallback", 1, "tls", "0x0303, a hardened suite, EMS bit, echo", + s23_tls12, ("fixture",)), + Scenario("S5", "refused-cert", 1, "tls", "exactly 93 0x00000008; 96 for a wrong pin", + s5_refused_cert, ("fixture",)), + Scenario("S19e", "abort-then-release", 1, "tls", "ABORTed OPEN is cancelled within a slice: [2] = 0, [14] = 0, $25 -> 0", + s19e_abort_release, ("fixture",)), + Scenario("S30", "bundle-real-hosts", 1, "tls", "BUNDLE to H1-H3, SPKI as seen here, HTTP/1.", + s30_real_hosts, ("internet", "crypto")), + Scenario("S6", "peer-close-notify", 2, "tls", "3000 B then $0000 + 01; CLOSE -> 12,…: 9", + s6_peer_close, ("fixture",)), + Scenario("S7", "peer-fin-truncation", 2, "tls", "3000 B then $0000 + 05", s7_truncation, + ("fixture",)), + Scenario("S7c", "rst-mid-handshake", 2, "tls", "13 PEER RESET: 104", s7c_rst_handshake, + ("fixture",)), + Scenario("S10", "handshake-timeout", 2, "tls", "15 within 17 s", s10_handshake_timeout, + ("fixture",)), + Scenario("S11", "session-cap", 2, "tls", "2 OK, 3rd 91, CLOSE one, OPEN OK", s11_cap, + ("fixture",)), + Scenario("S12", "open-close-x20", 2, "tls", "20 cycles, INFO [2] = 0", s12_open_close, + ("fixture",)), + Scenario("S13", "tickets-big-record", 2, "tls", "10 tickets; 16 KB record byte exact", + s13_tickets_big_record, ("fixture",)), + Scenario("S3", "custom-ca", 2, "tls", "CUSTOM echo ECDSA+RSA, SPKI; 94/95/95/93; 97", + s3_custom_ca, ("fixture",)), + Scenario("S19", "params", 2, "tls", "81/82 table, flags $01 OK, maxlen 82, 11, 84", + s19_params, ("fixture",)), + Scenario("S19e2", "release-spares-claimed", 2, "tls", "$25 -> 1; A echoes; B -> 02: 9", + s19e2_release_spares_claimed, ("fixture",)), + Scenario("S19e2b", "info-ff-does-not-claim", 2, "tls", "an ABORTed OPEN leaves no entry: [2] = 1 (A), [14] = 0 after 03 23 FF; $25 -> 0", + s19e2b_info_does_not_claim, ("fixture",)), + Scenario("S22", "group-negotiation", 2, "tls", "0x001D default; 0x0017 via HRR", + s22_groups, ("fixture",)), + Scenario("S24", "require-tls13-vs-1.2", 2, "tls", "14 with 70, or 18 with 0x0303", + s24_require13, ("fixture",)), + Scenario("S18", "dispatcher-not-blocked", 2, "tls", "block_max_ms < 50 after a handshake", + s18_block_max, ("fixture",)), + Scenario("S14", "reset-cleanup", 2, "tls", "reset closes both, b3 clear, then 97", + s14_reset_cleanup, ("fixture",)), + Scenario("S32", "write-stall-close-cap", 2, "tls", "FFFF + 12/17 sticky; CLOSE time", + s32_write_stall, ("fixture",), default=False), + Scenario("S34", "p384-p521-custom", 2, "measurement", "handshake ms for P-384/P-521, 1.3/1.2", + s34_big_curves, ("fixture",), default=False), + Scenario("S33", "open-tcp-duration", 2, "measurement", "seconds to 11 / 84", + s33_open_tcp_duration, (), default=False), +] +BY_NAME = {s.name: s for s in SCENARIOS} | {s.sid: s for s in SCENARIOS} + + +# -- the run ----------------------------------------------------------------- + +def judge(outcome: Outcome) -> None: + """The signature: GREEN, RED (21 to a TLS command), or a plain FAIL.""" + s = outcome.scenario + unknown = outcome.evidence.get("unknown_command") + if outcome.verdict == "PASS": + outcome.signature = {"tls": "GREEN", "control": "CONTROL-PASS", + "measurement": "MEASURED"}[s.kind] + elif outcome.verdict in ("SKIP", "N/A", "ERROR"): + outcome.signature = outcome.verdict + elif unknown and outcome.first_tls_status == STATUS_UNKNOWN_COMMAND.decode(): + outcome.signature = "RED" + else: + outcome.signature = "FAIL" + + +def run_scenario(ctx: Ctx, scenario: Scenario, route: str) -> Outcome: + outcome = Outcome(scenario, route) + ctx.outcome = outcome + section(f"{scenario.sid} {scenario.name} [tier {scenario.tier}, {scenario.kind}, {route}]") + started = time.monotonic() + try: + scenario.fn(ctx) + outcome.verdict = "PASS" + except NotOnRoute as exc: + outcome.verdict, outcome.reason = "N/A", str(exc) + check_start(f"{scenario.sid} applies to this route") + check_skip(str(exc)) + except Skipped as exc: + outcome.verdict, outcome.reason = "SKIP", str(exc) + check_start(f"{scenario.sid} can run here") + check_skip(str(exc)) + except LinkLost: + ctx.outcome = None + ctx.close_servers() + raise + except Failure as exc: + outcome.verdict, outcome.reason = "FAIL", format_exception(exc) + except Exception as exc: # a bug in the suite must not pass for the firmware's + outcome.verdict = "FAIL" + outcome.reason = f"suite error: {type(exc).__name__}: {exc}" + detail(traceback.format_exc()) + finally: + outcome.elapsed = time.monotonic() - started + if ctx.outcome is not None: + ctx.close_servers() + judge(outcome) + detail(f"{scenario.sid}: {outcome.verdict} ({outcome.signature})" + + (f": {outcome.reason}" if outcome.reason else "")) + ctx.outcome = None + if outcome.verdict == "FAIL": + # Leave nothing behind for the next scenario (the startup sweep). + try: + ctx.sweep() + except Failure as exc: + warn(f"the sweep after {scenario.sid} failed: {exc}") + return outcome + + +def expectation_met(outcomes: list[Outcome], expect: str) -> tuple[bool, list[str]]: + """Whether the run shows what --expect asks, from evidence only. + + A SKIP or ERROR of any selected scenario is a problem; only N/A (by design + not on this route) is set aside. green: every control passes, every TLS + scenario is GREEN, no measurement failed. red: every control passes and + every TLS scenario is RED. Either way each route must have produced at least + one TLS outcome of the expected signature, so zero evidence never passes. + """ + problems = [] + evidence: dict[str, int] = {} + routes = [] + for o in outcomes: + label = f"{o.scenario.sid} {o.scenario.name} [{o.route}]" + if o.route not in routes: + routes.append(o.route) + evidence[o.route] = 0 + if o.verdict == "N/A": + continue + if o.verdict in ("SKIP", "ERROR"): + problems.append(f"{label}: {o.verdict}, so it says nothing: {o.reason}") + continue + kind = o.scenario.kind + if kind == "control": + if o.verdict != "PASS": + problems.append(f"{label}: the control failed, so the setup is not sound: {o.reason}") + elif kind == "measurement": + if expect == "green" and o.verdict != "PASS": + problems.append(f"{label}: the measurement failed: {o.reason}") + elif expect == "green": + if o.signature == "GREEN": + evidence[o.route] += 1 + else: + problems.append(f"{label}: {o.signature}: {o.reason}") + elif o.signature == "RED": + evidence[o.route] += 1 + else: + problems.append(f"{label}: {o.signature} where RED (21 to its first TLS command) " + f"was expected: {o.reason or 'it passed'}") + if not outcomes: + problems.append("no scenario ran") + # A scenario selected for this run but N/A on every route of it ran nowhere + # (e.g. --route native with S19e): never evidence. + for sid in dict.fromkeys(o.scenario.sid for o in outcomes): + if all(o.verdict == "N/A" for o in outcomes if o.scenario.sid == sid): + problems.append(f"{sid}: selected, but N/A on every route of this run, so it ran nowhere") + for route in routes: + if not evidence[route]: + problems.append(f"route {route}: no TLS scenario showed {expect.upper()}, so this run " + f"is no evidence either way") + return not problems, problems + + +def ancestor_pids() -> set[int]: + pids, pid = set(), os.getpid() + for _ in range(16): + try: + parent = int(subprocess.run(["ps", "-o", "ppid=", "-p", str(pid)], + capture_output=True, text=True, timeout=5, + check=False).stdout.strip() or 0) + except (OSError, ValueError, subprocess.SubprocessError): + break + if parent <= 1: + break + pids.add(parent) + pid = parent + return pids + + +LOCK_PID_ENV = "NET_TLS_LOCK_PID" + + +def lock_check(host: str, require: bool = False) -> dict: + """The DeviceLock of the optional c64-test-harness package (https://github.com/JC-000/c64-test-harness): + refuse if another live process holds this device. + + With `require` (or when a locking wrapper exported NET_TLS_LOCK_PID), + the lock must be HELD, by that very process, and that process must be this + one or an ancestor of it. A free lock is then a refusal: the user has left + the locked shell, or never entered it. + """ + try: + from c64_test_harness.backends.device_lock import DeviceLock # noqa: PLC0415 + except ImportError as exc: + # The DeviceLock comes from the optional c64-test-harness package, which this tree does not + # require; without it there is nothing to check, unless the run was told to require a lock. + if require or os.environ.get(LOCK_PID_ENV): + raise Failure(f"--require-lock, but the harness DeviceLock is not importable ({exc}); " + f"refusing to run against {host}") from exc + print(f"warning: c64_test_harness (https://github.com/JC-000/c64-test-harness) is not installed: " + f"not checking whether another run holds {host} ({exc})", file=sys.stderr) + return {"lock": "not checked (c64_test_harness not installed)"} + marker = os.environ.get(LOCK_PID_ENV, "") + require = require or bool(marker) + if require: + if not marker.isdigit(): + raise Failure(f"--require-lock, but {LOCK_PID_ENV} is not set: this shell is not the " + f"shell of a locking wrapper. Nothing was run or changed") + if int(marker) == os.getpid() and DeviceLock.held_by_this_process(host): + return {"lock": f"held by this process ({marker})"} + holder = DeviceLock.foreign_holder(host) + if (not holder or holder.get("pid") != int(marker) + or int(marker) not in ancestor_pids()): + raise Failure(f"--require-lock: the session lock on {host} is not held by our " + f"locking wrapper (pid {marker}); holder {holder or 'none'}. Nothing " + f"was run or changed") + return {"lock": f"held by our locking wrapper, pid {marker}"} + holder = DeviceLock.foreign_holder(host) + if not holder: + return {"lock": "free"} + if holder.get("pid") in ancestor_pids(): + return {"lock": f"held by our ancestor pid {holder.get('pid')} (a locking wrapper)"} + raise Failure(f"{host} is held by pid {holder.get('pid')} ({holder}); another run is using " + f"the device. Run under its lock, or wait") + + +def apply_settings(device, set_wifi: bool, original: dict, header: dict) -> dict: + """Read every setting first; refuse before writing anything; then set and read back. + + `original` is the caller's, filled as each setting is written, so whatever + happens after a write the caller can restore it. + """ + before: dict[str, str] = {} + header["settings_before"] = before + with check("read the settings this suite depends on, before changing any"): + for category, item, _value, _restore in SETTINGS: + try: + before[item] = str(device.configs.current(category, item)) + except Failure: + if item == REQUIRED_SETTING: + raise + before[item] = "absent" + detail(json.dumps(before)) + wifi = before.get(WIFI_SETTING, "absent") + if wifi != "absent" and wifi.strip() != "Enabled" and not set_wifi: + # One-way on the U64: switching it on cannot be undone by this suite, so + # only an explicit --set-wifi may do it. + raise SetupRefused(f"{WIFI_SETTING} is {wifi!r}; this suite needs it 'Enabled' and does " + f"not switch it on without --set-wifi (one-way on the U64). Nothing " + f"was changed") + applied = {} + for category, item, value, restore in SETTINGS: + with check(f"set {category} / {item} = {value}"): + current = before[item] + if current == "absent": + check_warn("not on this device; recorded as absent") + applied[item] = "absent" + continue + if current.strip() != value: + if restore: + original[(category, item)] = current + device.configs.set(category, item, value) + applied[item] = str(device.configs.current(category, item)) + if applied[item].strip() != value: + raise Failure(f"read back {applied[item]!r}") + detail(f"{current!r} -> {applied[item]!r}" + ("" if restore else " (one-way: kept)")) + return applied + + +class SetupRefused(Failure): + """Setup refused before changing anything on the device.""" + + +def wait_ready(link: Link) -> dict: + """With TLS, wait for INFO [4] b0-b2; on stock, the 21 says there is nothing to wait for.""" + deadline = time.monotonic() + READY_WAIT_SECONDS + while True: + r = link.command(info_command(INFO_CAPABILITY)) + if r.status == STATUS_UNKNOWN_COMMAND: + return {"tls_info": "21,UNKNOWN COMMAND"} + if r.ok and len(r.data) == INFO_CAPABILITY_BYTES: + cap = Capability(r.data) + if cap.ready & READY_BITS == READY_BITS or time.monotonic() > deadline: + return cap.as_dict() + elif time.monotonic() > deadline: + return {"tls_info": r.status.decode("latin-1")} + time.sleep(2) + + +def git_head() -> str: + try: + return subprocess.run(["git", "-C", str(HERE), "rev-parse", "--short", "HEAD"], + capture_output=True, text=True, timeout=5, + check=False).stdout.strip() + except (OSError, subprocess.SubprocessError): + return "" + + +def parse_args(argv=None): + parser = argparse.ArgumentParser(description="TLS sockets on the UCI network target: " + "RED on stock firmware, GREEN with TLS.") + cli.add_device_arguments(parser, password=None, timeout=30.0, colour=False) + parser.add_argument("--test", action="append", + help="A scenario id or name (repeatable), 'all', or 'tier1'. Default: " + "every default scenario.") + parser.add_argument("--route", action="append", choices=["all", "rest", "native"], + help="How to reach $DF1C-$DF1F. Default: both.") + parser.add_argument("--expect", choices=["green", "red"], default="green", + help="green: every TLS scenario must pass. red: every TLS scenario " + "must show the stock signature (21) and every control pass.") + parser.add_argument("--results", type=Path, help="Where run.json and wire.jsonl go.") + parser.add_argument("--label", default="", help="Free text recorded in run.json.") + parser.add_argument("--module-minor", type=int, + help="S1 also requires INFO [7..8] to equal this (e.g. 8).") + parser.add_argument("--mac-cafile", help="S30 step 1/4: verify with this CA file instead " + "of this machine's default store.") + parser.add_argument("--strict-sni", action="store_true", + help="S5 also requires the BUNDLE ClientHello to carry the SNI.") + parser.add_argument("--require-lock", action="store_true", + help="Refuse unless the device's DeviceLock is held by the process in " + "NET_TLS_LOCK_PID, this process or an ancestor of it.") + parser.add_argument("--set-wifi", action="store_true", + help="Switch 'WiFi Enabled' on if it is off. One-way on the U64 (a " + "reboot is the only way back), so without it the suite refuses.") + parser.add_argument("--keep-config", action="store_true", + help="Don't restore the settings this suite changed.") + parser.add_argument("--list", action="store_true", help="List the scenarios and exit.") + args = parser.parse_args(argv) + args.hosts = None + return args + + +def select(args) -> list[Scenario]: + """The scenarios asked for, always led by S0: every route starts with the startup sweep.""" + wanted = args.test or [] + if not wanted: + return [s for s in SCENARIOS if s.default] + if "all" in wanted: + return list(SCENARIOS) + chosen = [SCENARIOS[0]] + for s in SCENARIOS: + if s is SCENARIOS[0]: + continue + if ("tier1" in wanted and s.tier == 1) or s.sid in wanted or s.name in wanted: + chosen.append(s) + unknown = [w for w in wanted if w not in BY_NAME and w not in ("all", "tier1")] + if unknown: + raise SystemExit(f"unknown scenario(s): {unknown}; see --list") + return chosen + + +def write_results(directory: Path, header: dict, outcomes: list[Outcome], wire: list[dict]) -> None: + directory.mkdir(parents=True, exist_ok=True) + body = dict(header, scenarios=[o.as_dict() for o in outcomes]) + (directory / "run.json").write_text(json.dumps(body, indent=2, default=repr)) + with open(directory / "wire.jsonl", "w", encoding="utf-8") as handle: + for entry in wire: + handle.write(json.dumps(entry) + "\n") + + +def run_routes(links: list[tuple[str, Callable[[], Link], Callable[[], Link] | None]], + scenarios: list[Scenario], args, pki, bind_ip, + available: set[str]) -> tuple[list[Outcome], list[dict]]: + """Every selected scenario on every route; (outcomes, wire log). + + `available` names what this run has: "peer" (the device can reach this + machine), "fixture" (and the local PKI), "crypto", "internet". + """ + outcomes: list[Outcome] = [] + wire: list[dict] = [] + for route, make_link, reset in links: + section(f"route: {route}") + try: + link = make_link() + except Failure as exc: + # The other routes' records stay; this one is an ERROR. + warn(f"the {route} route could not start: {exc}") + for scenario in scenarios: + failed = Outcome(scenario, route, "ERROR", reason=f"the {route} route could not " + f"start: {exc}") + judge(failed) + outcomes.append(failed) + continue + ctx = Ctx(link, args, pki, bind_ip, reset, wire) + pending = list(scenarios) + try: + while pending: + scenario = pending.pop(0) + missing = [need for need in scenario.needs if need not in available] + if missing: + # The run was meant to have it (the fixture could not start, + # say): an ERROR, never a quiet SKIP. + outcome = Outcome(scenario, route, "ERROR", + reason=f"this run has no {', '.join(missing)}") + judge(outcome) + else: + outcome = run_scenario(ctx, scenario, route) + outcomes.append(outcome) + except LinkLost as exc: + outcomes.append(ctx_lost := Outcome(scenario, route, "FAIL", reason=str(exc))) + judge(ctx_lost) + for rest in pending: + lost = Outcome(rest, route, "ERROR", reason=f"the {route} route was lost") + judge(lost) + outcomes.append(lost) + warn(f"the {route} route is lost: {exc}; resetting the C64") + if reset is not None: + try: + reset() + except Failure as again: + warn(f"the reset failed too: {again}") + return outcomes, wire + + +def summarise(outcomes: list[Outcome], expect: str) -> bool: + section("summary") + for o in outcomes: + state = {"PASS": OK, "FAIL": FAIL, "ERROR": FAIL}.get(o.verdict, SKIP) + detail(f"{o.scenario.sid:7} {o.scenario.name:24} tier {o.scenario.tier} " + f"{o.scenario.kind:11} {o.route:7} {state:4} {o.signature}" + + (f" ({o.reason[:110]})" if o.reason and o.verdict != "PASS" else "")) + met, problems = expectation_met(outcomes, expect) + for problem in problems: + detail(f"not {expect.upper()}: {problem}") + return met + + +def main(argv=None) -> int: + args = parse_args(argv) + if args.list: + for s in SCENARIOS: + print(f"{s.sid:7} {s.name:24} tier {s.tier} {s.kind:11} " + f"{'' if s.default else '(opt-in) '}{s.oracle}") + return 0 + scenarios = select(args) + routes = ["rest", "native"] if not args.route or "all" in args.route else args.route + stamp = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ") + results = args.results or DEFAULT_RESULTS / f"{stamp}-{args.expect}" + target = targets.parse(args.host) + device = UltimateApi(target.device, args.password, args.timeout) + computer = UltimateApi(target.computer, args.password, args.timeout) + header = {"suite": SUITE, "suite_commit": git_head(), "started": stamp, "expect": args.expect, + "label": args.label, "host": args.host, "routes": routes, + "scenarios_selected": [s.sid for s in scenarios]} + # Before anything touches the device: a run holding the lock is mid-run, + # and even the reset below would land in the middle of its work. + try: + with check("no other run holds this device (harness DeviceLock)"): + header["lock"] = lock_check(target.device, args.require_lock) + detail(header["lock"]["lock"]) + except Failure as exc: + suite_fail(SUITE, f"nothing was run or changed: {format_exception(exc)}") + return 1 + original: dict = {} + outcomes: list[Outcome] = [] + wire: list[dict] = [] + pki = None + rest_uci = Uci(computer.machine, BOUND_OPEN) + ok = False + setup_error = None + touched = False # whether anything on the device was changed + try: + with check("read /v1/info: product, firmware, core, fpga, git hash"): + info = device.info() + header["device"] = {"product": info.product, "firmware_version": info.firmware_version, + "fpga_version": info.fpga_version, **info.extra} + detail(json.dumps(header["device"])) + header["settings"] = apply_settings(device, args.set_wifi, original, header) + touched = True + with check("reset the C64 so nothing another program left is still driving the UCI"): + computer.machine.reset(force=True) + rest_uci.release() + if not interface_present(rest_uci): + raise Failure("$DF1B-$DF1F all read $FF: no command interface on this machine") + with check("wait for INFO $FF ready bits (module, entropy, time), up to 90 s with TLS"): + header["ready"] = wait_ready(RestLink(rest_uci)) + detail(json.dumps(header["ready"])) + available = {"internet"} + bind_ip = None + check_start("this machine can serve the local TLS fixture to the device") + try: + bind_ip = fx.local_address_towards(target.device) + available.add("peer") + pki = fx.Pki() + available |= {"fixture", "crypto"} + check_ok(bind_ip) + except (RuntimeError, OSError) as exc: + # Every scenario that needs it then records ERROR. + check_fail(f"{exc}; the scenarios that need it will be ERROR") + header["fixture"] = {"bind_ip": bind_ip, "cryptography": fx.HAVE_CRYPTOGRAPHY} + + def reset_rest() -> Link: + computer.machine.reset(force=True) + rest_uci.release() + return RestLink(rest_uci) + + def make_native() -> Link: + computer.machine.reset(force=True) + agent = NativeUci(computer.machine, computer.runners, BOUND_OPEN) + agent.start() + return NativeLink(agent) + + links = [] + for route in routes: + if route == "rest": + links.append(("rest", lambda: RestLink(rest_uci), reset_rest)) + elif target.split: + warn("the native route cannot reach a cartridge's interface; skipped") + else: + links.append(("native", make_native, make_native)) + outcomes, wire = run_routes(links, scenarios, args, pki, bind_ip, available) + ok = summarise(outcomes, args.expect) + except Failure as exc: + setup_error = format_exception(exc) + ok = False + finally: + if pki is not None: + pki.close() + if touched or original: + try: + rest_uci.release() + computer.machine.reset(force=True) + except Failure as exc: + warn(f"final reset: {exc}") + if not args.keep_config: + for (category, item), value in original.items(): + with check(f"restore {category} / {item} to {value!r}"): + device.configs.set(category, item, value) + header["finished"] = datetime.datetime.now(datetime.UTC).strftime("%Y%m%dT%H%M%SZ") + header["expectation_met"] = ok + header["setup_error"] = setup_error + write_results(results, header, outcomes, wire) + print(f"results: {results}") + if ok: + suite_ok(SUITE, f"{args.expect.upper()} as expected over {len(outcomes)} scenario runs") + return 0 + suite_fail(SUITE, setup_error or f"not {args.expect.upper()}; see the summary and " + f"{results}/run.json") + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/e2e/io/command_interface/uci_agent.asm b/tests/e2e/io/command_interface/uci_agent.asm index f00fa03dc..815e643f5 100644 --- a/tests/e2e/io/command_interface/uci_agent.asm +++ b/tests/e2e/io/command_interface/uci_agent.asm @@ -23,7 +23,9 @@ ; OPT_ABRT abandon the reply after the first block, which is what a ; client does when it gives up part way through a Data More ; reply -; $C00A-$C00F and $C440-$C4FF are reserved for further options and results. +; OPT_WAIT how long a wait may last, for a command that legitimately +; runs longer than the default (an OPEN_TLS can take 41 s) +; $C00C-$C00F and $C440-$C4FF are reserved for further options and results. ; New behaviour, as opposed to a new value, belongs in a reserved option byte, ; where zero has to keep meaning what the agent does today: the host writes the ; whole option block at once, so an older host leaves zeroes there. @@ -67,7 +69,8 @@ OPT_CAP = $C006 ; 16 bit cap on the data drain READY = $C008 ; agent writes $A5 here once it is running OPT_ABRT = $C009 ; non-zero: abandon the reply after the first ; block by writing the abort bit -; $C00A-$C00F ; reserved for further options +OPT_WAIT = $C00B ; wraps a wait may take; zero means WAIT_WRAPS +; $C00C-$C00F ; reserved for further options CMDBUF = $C010 ; command bytes, up to 896 ; ------------------------------------------------------------- result block -- @@ -92,10 +95,12 @@ zcap = $05 ; 16 bit remaining drain allowance ztmo = $07 ; 24 bit wait counter zblk = $0A ; block index zstat = $0B ; CTRL as the current block arrived +zwrap = $0C ; wraps this transaction's waits may take ; The wait gives up after this many wraps of a 16 bit counter. Each pass is -; about a dozen cycles, so $08 is roughly six seconds on a 1 MHz 6510: longer -; than any command takes, shorter than the host's own timeout. +; 25 cycles, so a wrap is about 1.7 s and $08 about 14 s on a 1 MHz 6510 +; (counted, not measured): longer than any plain command takes. A host that +; sends a longer command (a TLS open) raises it through OPT_WAIT. WAIT_WRAPS = $08 * = $0801 @@ -115,6 +120,7 @@ start sta GO sta SEQ sta OPT_ABRT ; so a host that never sets it gets the default + sta OPT_WAIT lda #$A5 sta READY main_wait @@ -129,6 +135,11 @@ main_wait ; ---------------------------------------------------------------- transact --- ; Runs one command end to end and fills the result block. transact + lda OPT_WAIT + bne transact_wrap + lda #WAIT_WRAPS +transact_wrap + sta zwrap lda #$00 sta R_FLAGS sta R_BLOCKS @@ -303,7 +314,7 @@ idle_loop bne idle_loop inc ztmo+2 lda ztmo+2 - cmp #WAIT_WRAPS + cmp zwrap bne idle_loop lda R_FLAGS ora #$01 @@ -334,7 +345,7 @@ wait_loop bne wait_loop inc ztmo+2 lda ztmo+2 - cmp #WAIT_WRAPS + cmp zwrap bne wait_loop lda R_FLAGS ora #$01 diff --git a/tests/e2e/lib/uci_native.py b/tests/e2e/lib/uci_native.py index fe00dd2ac..fc8a3a212 100644 --- a/tests/e2e/lib/uci_native.py +++ b/tests/e2e/lib/uci_native.py @@ -36,6 +36,7 @@ OPT_CAP = 0xC006 READY = 0xC008 OPT_ABRT = 0xC009 +OPT_WAIT = 0xC00B CMDBUF = 0xC010 RESULT_BASE = 0xC400 @@ -83,6 +84,10 @@ def __init__(self, machine, runners, self.machine = machine self.runners = runners self.busy_timeout = busy_timeout + # Wraps of the agent's 16-bit wait counter (about 1.7 s each at 1 MHz). + # Zero keeps the agent's default of 8, about 14 s; a caller with a + # longer command raises it together with busy_timeout. + self.wait_wraps = 0 self._sequence = 0 # -- lifecycle ---------------------------------------------------------- @@ -120,9 +125,11 @@ def _run(self, command: bytes, overrun_reads: int, cap: int, len(command) & 0xFF, (len(command) >> 8) & 0xFF, min(overrun_reads, MAX_OVERRUN_READS), max_blocks, cap & 0xFF, (cap >> 8) & 0xFF])) - # Outside the option block above, so it is written every time rather - # than left over from the previous transaction. + # Outside the option block above, so they are written every time + # rather than left over from the previous transaction. OPT_WAIT is not + # next to OPT_ABRT ($C00A is left free), so each gets its own write. self.machine.writemem(OPT_ABRT, bytes([0x01 if abort_first else 0x00])) + self.machine.writemem(OPT_WAIT, bytes([self.wait_wraps & 0xFF])) self.machine.writemem(GO, bytes([0x01])) deadline = time.monotonic() + self.busy_timeout diff --git a/tests/lib/registry_test.py b/tests/lib/registry_test.py index 225a4f836..8063c1e34 100755 --- a/tests/lib/registry_test.py +++ b/tests/lib/registry_test.py @@ -56,10 +56,9 @@ # it. A token outside this set would reach the suite as a literal. TOKENS = {"@HOST@", "@PASS@", "@TIMEOUT@", "@MODE@", "@SOAKPROFILE@", "@KERNAL@"} -# Files ending in _test.py that no profile should select, each with its reason. -# A file that is not a suite belongs here rather than in the registry, so that -# "not registered" always means "nobody can run it". Everything else under -# SEARCHED has to be in the registry. +# Files ending in _test.py that no profile should select, each with its reason: +# not a suite, or a suite that is opt-in by name (run directly). Everything +# else under SEARCHED has to be in the registry. NOT_SUITES: dict[str, str] = { # The four tiers of the observability suite. Importing one registers its # cases in support.CASES; tests/lib/observability_test.py imports all four @@ -70,6 +69,10 @@ "tests/lib/observability/component_test.py": "tier 2 of the observability suite", "tests/lib/observability/pipeline_test.py": "tier 3 of the observability suite", "tests/lib/observability/golden_test.py": "tier 4 of the observability suite", + # Never by a profile: it can switch "WiFi Enabled" on (--set-wifi; one-way + # on the U64), needs this host as a TLS peer and the Internet, and is RED on + # any image without the TLS commands. net_tls_selftest.py checks it offline. + "tests/e2e/io/command_interface/net_tls_test.py": "opt-in TLS suite on a device, run directly", } # tests/lib/bootstrap.py is the one place that may compute a path into the diff --git a/tests/requirements.txt b/tests/requirements.txt index 60a75461d..a1bc0be6c 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -13,6 +13,7 @@ openapi-schema-validator # tests/lib/openapi_contract.py, checks device answers -r requirements-lint.txt # ruff, pinned there because tests/lib/lint_test.py is a gate Pillow # e2e/api/input_test.py, e2e/io/printer/printer_test.py pyftpdlib # e2e/filesystem/ftp_client_test.py +cryptography # e2e/io/command_interface/net_tls_fixture.py, net_tls_mock.py, net_tls_selftest.py, throwaway PKI for the TLS suite selenium # e2e/web/theme_test.py, drives an installed Chrome and Firefox pytesseract # e2e/io/printer/printer_test.py, only under --stage verify PyYAML # tests/lib/openapi_contract.py, reads doc/api/rest_api_openapi_*.yaml