Author SHA1 Message Date
Commander1024 797d2681ac Migrate to IDF 5.5.3 candidate
Pin PlatformIO packages and toolchains, rebase protected SDK
overrides, and add WebSocket receive regression coverage. Document
isolated candidate validation, archive provenance, and remaining gates.
2026-09-18 14:23:13 +02:00
Commander1024 cdc4d4a8df Add Phase 9 validation and advisory review
Record the finite dependency search, Wi-Fi maintenance blocker, and
pinned
icon provenance. Add bounded host orchestration and fixture coverage,
and
update release documentation with current evidence.
2026-09-16 16:26:46 +02:00
Commander1024 51f835c22f Harden SSH parsing and add notice tooling
- Enforce exact service and channel names with bounded failure parsing
- Add hash-pinned offline notice assembly and regression coverage
- Record advisory dispositions, provenance, integration evidence, and
  remaining gates
2026-09-16 15:06:38 +02:00
Commander1024 bea33e1c95 Add restricted wolfSSH ordering fix
Apply hash-pinned generated edits for CVE-2025-14942 while keeping
wolfSSH 1.4.20 managed sources unchanged. Add the ABI header overlay,
provenance records, and real state-machine interoperability contracts.
2026-09-16 14:04:34 +02:00
Commander1024 4d3bb490c9 Harden wolfSSL and wolfSSH validation
Enable validated ECC imports and X25519 all-zero rejection through
PUBLIC build policy. Tighten wolfSSH parser bounds, overflow handling,
and signature framing with guard-page and crypto vector contracts.
2026-09-15 23:54:39 +02:00
Commander1024 c010e1a1d5 Apply Phase 9D security mitigations
- Add fail-closed wolfSSL small-math policy and vectors
- Backport DHCP, EMS, and X.509 allocation fixes
- Extend source override validation and operational documentation
2026-09-15 23:06:23 +02:00
Commander1024 cdc9c7335a Add Phase 9C security hardening
Generate exact-hash SDK source overrides without modifying dependencies.
Harden
SSH allocation and algorithm policy, tighten web authentication cleanup,
and add
focused host contract tests and documentation.
2026-09-15 22:12:57 +02:00
Commander1024 751dfb9ddb Harden SSH Admission And Credential Input 2026-09-15 20:49:04 +02:00
Commander1024 436c27adb1 Enforce crash-safe build policy
Add compile-time checks for silent reboot, disabled core dumps, and
disabled debugger-aware panic handling. Include regression coverage,
hardening guidance, and update Phase 8/9 project status.
2026-09-15 20:11:40 +02:00
Commander1024 f40c09c11a Refine web quick panels and Wi-Fi controls 2026-09-14 00:05:27 +02:00
Commander1024 4a53a21f31 Move console payloads to lazy PSRAM storage 2026-09-13 23:06:42 +02:00
Commander1024 91267b371e Consolidate Phase 8 documentation
Mark web administration complete, centralize current contracts and
acceptance evidence, and remove superseded slice records. Update
roadmap,
architecture notes, and test references without changing firmware
sources.
2026-09-13 22:27:10 +02:00
Commander1024 1608641d50 Close scope for remaining Phase 8D.19 work 2026-09-13 20:25:01 +02:00
Commander1024 8df1d2218b Add SSH host identity rotation controls 2026-09-13 19:58:05 +02:00
Commander1024 aa4bbc2c8c Add HTTPS identity rotation support 2026-09-13 18:21:37 +02:00
Commander1024 36e80811e8 Implement HTTPS lifecycle and reboot controls 2026-09-13 17:24:00 +02:00
Commander1024 737bd29f9e Add Typed SSH Service Controls
Provide admin-only SSH status plus generation-safe start, stop, and
single-session disconnect operations through the bounded dispatcher.
Include
Settings UI coverage, lifecycle safeguards, and host-side regression
tests.
2026-09-13 16:07:04 +02:00
Commander1024 7ccc8799e9 Add Broker client and writer quick dialogs 2026-09-13 14:40:51 +02:00
Commander1024 9f6ebf2053 Add Serial and Wi-Fi quick settings
Reuse the existing settings view and typed controllers for accessible
quick editing while keeping network credentials out of quick mode.
Expand browser and layout coverage for focus, dismissal, bounds, and
expiry.
2026-09-13 14:22:31 +02:00
Commander1024 add399908a Remove stray blank line in Phase 8D plan 2026-09-13 14:01:49 +02:00
Commander1024 fa12440606 Add broker management and writer transfer UI 2026-09-13 13:59:28 +02:00
Commander1024 29a4953df0 Remove network diagnostics from phase 8D plan 2026-09-09 10:32:55 +02:00
Commander1024 d9ec3c08de Add Typed Display Settings Administration
Implements admin-only Display settings with generation-checked
Apply, Save, Load, Defaults, and Reset operations across the web UI,
CLI, SSH dispatcher, and local UI owner. Adds bounded HTTP handling,
session-isolated operation results, browser lifecycle support, and
comprehensive host tests and documentation.
2026-09-09 10:15:23 +02:00
Commander1024 60d9c54bb4 Send binary WebSocket frames in one write 2026-09-08 23:52:00 +02:00
Commander1024 042499e4d6 Add broker and web throughput diagnostics 2026-09-08 22:40:58 +02:00
Commander1024 36d41be422 Document 8D.12/8D.13 Functional Sign-Off 2026-09-08 21:40:18 +02:00
Commander1024 4a4d615c59 Unify Settings Layouts and Add Coverage 2026-09-08 21:22:52 +02:00
Commander1024 989821b7c4 Add Typed Admin Network Settings 2026-09-08 20:57:27 +02:00
Commander1024 d9ac1319aa Document legacy credential cleanup sign-off
Record certificate continuity, existing-user validation, and full-mix
target telemetry while preserving the documented evidence limits.
2026-09-08 19:21:09 +02:00
Commander1024 ac80863d80 Remove Legacy Credential Bootstrap Paths
Decouple user provisioning from HTTPS identity storage while retaining
compatible v1 user records and migrating TLS material to the
credential-free
v2 format. Add focused security regression coverage and update operator
documentation.
2026-09-08 19:09:26 +02:00
Commander1024 82f21d6116 Add Bounded Ordinary HTTPS Idle Cleanup 2026-09-08 18:33:33 +02:00
Commander1024 f6263042ff Add Bounded Web Admission Diagnostics 2026-09-08 18:04:46 +02:00
Commander1024 42f6423d4e Implement SSH authorized key management 2026-09-08 16:37:47 +02:00
Commander1024 22a7c7b0a5 Record 8D.8–8D.10 target sign-off
Document user-supplied telemetry, functional testing, and acceptance of
the implemented Serial and account settings scope.
2026-09-08 15:19:49 +02:00
Commander1024 23c190bcf0 Load the PlatformIO extra script 2026-09-08 15:17:00 +02:00
Commander1024 94433ef975 Add typed account and password settings
- Add admin account list, create, role, delete, and password workflows
- Execute identity-checked mutations through the existing dispatcher
- Bound queued credential lifetime and wipe transient secrets
- Add explicit password generation with saved-value acknowledgement
- Handle self-revocation and uncertain outcomes without automatic
  retries
- Register optional account routes without disrupting terminal
  transports
- Expand host regressions and document contracts and pending target
  checks

Validated host suites and pio run; hardware validation remains pending.
2026-09-08 09:27:02 +02:00
Commander1024 42548f6334 Add typed serial settings operations
Route bounded admin mutations through the existing administration
dispatcher,
covering apply, lifecycle, persistence, authorization, and result
tracking.
Add the browser controls, automatic result refresh, regression coverage,
and
phase documentation.
2026-09-08 00:25:31 +02:00
Commander1024 5a2aa0d4d8 Add admin serial settings view 2026-09-07 20:12:33 +02:00
Commander1024 c73674cda2 Document M2 sign-off and update project status 2026-09-07 19:29:56 +02:00
Commander1024 93d8d1e5ca Mark 8D.7 Implemented Scope Validated 2026-09-07 19:04:49 +02:00
Commander1024 fe1e2d98b4 Enable bounded browser account administration for Phase 8D.7
Allow other-account add/password and forced delete/role commands through
shared dispatcher and handler policy. Keep self-target,
generated-secret,
key, bootstrap, and recovery workflows blocked.

Revalidate currentness after password prompts and before database API
admission. Document that admitted mutations may finish after disconnect,
while subsequent stale operations must reject.

Add policy, transaction-failure, cleanup, and targeted-revocation
regressions. Record completed review, passing host tests and firmware
build, with target validation and M2 acceptance still pending.
2026-09-07 10:03:45 +02:00
Commander1024 326119812f Extend browser admin lifecycle actions
Support browser reboot and HTTPS stop through deferred control, plus
exact
`web certificate rotate --force` handoff to the dispatcher. Add typed
request
validation and focused boundary and lifecycle coverage.
2026-09-07 09:36:38 +02:00
Commander1024 17520b15b7 Configure clangd for ESP-IDF development
Enable PlatformIO compilation database generation and configure
toolchain discovery for Clang-based editors.
2026-09-07 09:35:37 +02:00
Commander1024 0b86fd9c70 Close 8D.6 With Validation Sign-Off 2026-09-06 21:30:26 +02:00
Commander1024 f15491f233 Place admin controls before terminal selector 2026-09-06 20:37:39 +02:00
Commander1024 71f588360a Fix admin ticket validation format mismatch 2026-09-06 20:32:00 +02:00
Commander1024 e6db5428eb Add browser Serial/Admin terminal switching
Keep the serial connection and lease intact while providing a separate,
bounded admin terminal with explicit open and close controls. Fence
retained
terminal state across sessions and add fit-readiness retries with
regression
coverage.
2026-09-06 19:46:38 +02:00
Commander1024 aeb2043396 feat: add bounded admin WebSocket backend (Phase 8D.5)
- Require current admin cookie sessions, Origin checks and single-use
  tickets
- Reuse the shared console with session-aware authorization and slot
  allocation
- Add HTTPD-owned I/O, bounded buffering and revocation cleanup
- Prevent LRU eviction of serial clients and stale admin socket closure
- Reject unsupported web-shell mutations before side effects
- Add host regressions, a smoke client and resource accounting

Validated by user sign-off after a 15-minute full-client soak at 230400
baud, with a few broker drops under heavy output. Browser UI remains
for Phase 8D.6; numeric memory reserves remain open.
2026-09-06 14:41:41 +02:00
Commander1024 e5dce12ed4 Close Phase 8D.4 validation
The user confirmed successful empty-Enter and soak testing, closing
8D.4 while leaving numeric reserve gates open and advancing the next
planned work to 8D.5.
2026-09-06 11:23:58 +02:00
Commander1024 117c694cd4 Add SSH Console Ownership Boundary (Phase 8D.4)
Implement transport-qualified session identity and immutable owner
adapters
for SSH console lifecycle and output-drain operations. Add focused host
tests
covering admission, stale identities, deferred actions, completion
races,
prompts, backpressure, and slot reuse. Update Phase 8D documentation and
current-state tracking.
2026-09-06 09:07:11 +02:00
Commander1024 f9ee6eec9c Record Phase 8D.3 M1 sign-off 2026-09-06 08:38:41 +02:00
Commander1024 5a609fa40b Replace Web Basic Auth With Cookie Sessions
Add bounded login challenges, CSRF/origin enforcement, logout, and
session-bound WebSocket admission. Isolate private HTTPD access behind a
version-guarded adapter and add focused host coverage. Also let empty
admin
SSH input reach the normal console handler.
2026-09-05 23:55:05 +02:00
Commander1024 4435a7fddd Add Standalone Login Page Renderer
Add a hash-bound, no-store login document with focused C and Node host
tests. Keep rendering inert until the 8D.3 authentication cutover.
2026-09-05 18:45:12 +02:00
Commander1024 00f226dc59 Add allocation-free web auth parsers
Implement strict origin, cookie, and login JSON parsing with
fail-closed validation and output wiping. Add focused host contract
tests
and document the preparatory 8D.3 parser split.
2026-09-05 18:22:15 +02:00
Commander1024 a62a655ac1 Bind Serial Transports To Web Sessions 2026-09-05 18:01:39 +02:00
Commander1024 93eef0e676 Added docs. 2026-09-05 17:16:17 +02:00
Commander1024 27c54c0a92 Phase 8D.1 implemented and validated. 2026-09-05 17:15:22 +02:00
Commander1024 d4991658b1 Phase 8D validation completed 2026-09-05 16:11:23 +02:00
Commander1024 d8999cd4a9 Updated memory baselines 2026-09-05 15:20:09 +02:00
Commander1024 02fdeee345 Record Phase 8D baseline and browser contract 2026-09-05 13:08:17 +02:00
Commander1024 af89dd1bd9 Define staged Phase 8D delivery plan 2026-09-05 12:46:27 +02:00
Commander1024 31d3561d47 Document integrated web administration scope 2026-09-01 23:55:48 +02:00
Commander1024 6318f0c770 Unify browser connection controls (Connect / Disconnect) 2026-09-01 22:34:02 +02:00
Commander1024 10b6d65fa9 Mark Phase 8C hardware validation complete 2026-09-01 22:08:48 +02:00
Commander1024 4449131079 Refine Wi-Fi, mDNS, and terminal lifecycles
- Stage disabled station profile edits without restarting the radio
- Make mDNS initialization failure-isolated and reannounce in place
- Document deferred admin actions and explicit browser disconnect
  behavior
2026-08-31 04:29:54 +02:00
Commander1024 3feb3b5916 Add configurable Wi-Fi station mDNS hostname support. Mini-Feature #1 2026-08-31 04:14:38 +02:00
Commander1024 06bf33b3cf Add Explicit Session Exit Controls Mini-Features ä2+3 2026-08-31 04:02:19 +02:00
Commander1024 c37fab67db Avoid Wi-Fi restarts for disabled profiles Fix #3 2026-08-31 03:51:24 +02:00
Commander1024 d9bd86bb84 Move RS-232 status under debug. Fix #2 from list. 2026-08-31 03:45:38 +02:00
Commander1024 2aafff25be Keep USB line coding diagnostic only. Fix cdc connect reconfiguring UART
1
2026-08-31 03:40:55 +02:00
Commander1024 6ad6c00d68 Harden cleanup and reduce internal RAM use. Phase 8C nearly validated
and somewhat stable.
2026-08-31 03:33:43 +02:00
Commander1024 868e9ebc23 Remove outdated startup and SSH banners 2026-08-30 23:20:52 +02:00
Commander1024 26e8bbe905 Revert "Remove SSH console startup instructions"
This reverts commit ec56d20b3e.
2026-08-30 23:14:18 +02:00
Commander1024 ec56d20b3e Remove SSH console startup instructions 2026-08-30 23:11:39 +02:00
Commander1024 5ecd88e19f Align UART completion with SSH behavior 2026-08-30 23:07:59 +02:00
Commander1024 35a6f32e8b Display SSH completion candidates for ambiguous prefixes 2026-08-30 23:00:01 +02:00
Commander1024 21d1b12f31 Share completion and add SSH line editing 2026-08-30 22:45:58 +02:00
Commander1024 2f383cd283 Refresh agent documentation for current behavior 2026-08-30 22:45:33 +02:00
Commander1024 7b87375980 Align Documentation With Current Firmware Behavior 2026-08-30 19:11:39 +02:00
Commander1024 f227a2026f Add Project Guidance For Agents 2026-08-30 18:55:11 +02:00
Commander1024 c2c11fee4e Expand admin SSH command capabilities
Add per-session history, tab completion, interactive prompts, and
bounded input handling. Support deferred lifecycle and host-key actions
after output drains, and document the expanded administration workflow.
2026-08-30 18:34:01 +02:00
Commander1024 0a1bbd6782 Add Serialized SSH Administrative Console 2026-08-30 18:07:02 +02:00
Commander1024 44e3962444 Complete Local Display and Button Interface Validation 2026-08-30 12:27:09 +02:00
Commander1024 302b9065bd Mark Phase 8B complete and add Phase 8E
Document target-hardware validation for role-aware authentication and
outline the planned web session login and logout architecture.
2026-08-30 12:23:01 +02:00
302 changed files with 48476 additions and 1848 deletions
+10
View File
@@ -0,0 +1,10 @@
CompileFlags:
Add:
- -isystem
- /home/mscholz/.platformio/packages/toolchain-xtensa-esp-elf/xtensa-esp-elf/include
Remove:
- -mlongcalls
- -mdisable-hardware-atomics
- -fstrict-volatile-bitfields
- -fno-tree-switch-conversion
- -fno-shrink-wrap
+17
View File
@@ -0,0 +1,17 @@
// Folder-specific settings
//
// For a full list of overridable settings, and general information on folder-specific settings,
// see the documentation: https://zed.dev/docs/configuring-zed#settings-files
{
"lsp": {
"clangd": {
"binary": {
"path": "/usr/bin/clangd",
"arguments": [
"--background-index",
"--query-driver=/home/mscholz/.platformio/packages/**/bin/*"
]
}
}
}
}
+44
View File
@@ -0,0 +1,44 @@
# Agent instructions
## Start with project memory
1. Read `docs/agent/code-map.md` before broad repository exploration.
2. Read the relevant sections of `docs/agent/architecture.md` and `docs/agent/design-decisions.md` before changing cross-cutting behavior.
3. Read `docs/agent/current-state.md` when resuming work or investigating recent changes.
4. Use these files to identify the smallest relevant source set before searching or reading code.
5. Verify stored knowledge against implementation whenever it may be stale or correctness depends on exact behavior. Source code is authoritative.
6. Do not repeatedly scan unrelated modules. Prefer targeted symbol searches and representative header/implementation reads.
7. Update durable agent documentation only when architecture, contracts, ownership, or module responsibilities genuinely change.
8. During long-running tasks, keep `docs/agent/current-state.md` current and update it before handoff or context compaction.
9. Keep temporary debugging notes and speculative hypotheses out of `architecture.md` and `design-decisions.md`; use `current-state.md` instead.
10. Treat `GPT-logs/` as non-authoritative history. Confirm any useful claim against current source.
11. Avoid `managed_components/`, `third_party/`, generated `src/web_assets_data.*`, compressed assets, minified libraries, `compile_commands.json`, `dependencies.lock`, and broad `sdkconfig.*` inspection unless the task specifically requires them.
## Project constraints
- This is ESP-IDF firmware for one physical UART1/MAX3243 RS-232 port shared through USB CDC, HTTPS/WebSocket, and SSH.
- Preserve the broker model: exactly one writer, multiple isolated observers.
- Preserve UART0 as the administrative recovery path and native USB as network-independent UART1 access when network services fail.
- Keep serial transport binary-transparent; do not add in-band control sequences.
- Treat bounded queues, buffers, task ownership, generation tokens, and failure isolation as correctness properties, not incidental implementation details.
- Never expose passwords, private keys, Wi-Fi secrets, ticket values, or verifier material through routine status, logs, completion, or the local display.
- Do not regenerate embedded web assets unless the task explicitly requires it. See `web_assets/SOURCES.md` for provenance and generation policy.
## Build and device commands
The normal build, verified from `platformio.ini` and `README.md`, is:
```sh
pio run
```
Upload and monitor commands documented by the project are:
```sh
pio run --target upload
pio device monitor -b 115200
```
The first migration from the former default/factory layout to the custom partition table requires `pio run --target erase`. Erasing destroys persisted configuration and credentials; never run it without explicit user approval.
No automated host test command is defined in the repository. Hardware validation procedures live in `docs/electrical_tests.md` and `docs/user_administration_tests.md`; do not claim they passed unless actually performed.
+6
View File
@@ -8,8 +8,14 @@ add_compile_definitions(
NO_WOLFSSL_ESP32_CRYPT_AES
NO_WOLFSSL_ESP32_CRYPT_HASH
WOLFSSL_ED25519_STREAMING_VERIFY
# CVE-2025-12888: upstream PR9275 small math policy for enabled algorithms.
# These affect public key layouts; library and consumers must agree.
CURVE25519_SMALL
ED25519_SMALL
)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(PROJECT_VER "0.1.0")
project(esp32_serial_swiss_army_knife)
include(cmake/security_overrides.cmake)
include(cmake/wolf_crypto_policy.cmake)
+48 -12
View File
@@ -10,18 +10,40 @@ ESP32-S3 firmware for a secure, multi-transport RS-232 adapter. It operates one
- ESP32-S3-WROOM-1-N16R8 module
- 16 MB flash
- 8 MB octal PSRAM
- [Adafruit MAX3243 full-pinout male RS-232 breakout](https://www.adafruit.com/product/6253)
- Adafruit MAX3243 full-pinout RS-232 breakout; the male connector version is preferred (see [Hardware wiring](docs/wiring.md) for supported connector variants)
## Development status
Hardware characterization, the serial core, USB CDC-ACM, Wi-Fi, HTTPS/WebSocket, SSH serial transport, and the local display/control interface are implemented and Phase 7 target-hardware validated. Phase 8A's bounded role-based user database and UART0 administration are complete. Phase 8B integrates role-aware HTTPS passwords, SSH passwords/public keys, and per-account session revocation; target-hardware validation is pending. See the [Roadmap](docs/roadmap.md) for phase status and validation details.
Hardware characterization, serial/USB/Wi-Fi/HTTPS/SSH and local display/control are implemented and hardware-validated. **Phase 8 role-based users and administration is complete:** 8A8C were target-hardware validated and the user explicitly signed off tested firmware at **8D.22 (2026-09-13)**. See the [roadmap](docs/roadmap.md#phase-8--role-based-users-and-administrative-access--complete) and [acceptance evidence](docs/web_administration_acceptance.md). Very low internal/DMA lifetime minima remain a nonblocking headroom follow-up, not an approved reserve. **Phase 9 security hardening is in progress**: 9A crash/debug policy, 9B SSH admission/credential handling and 9C library cleanup/protocol policy have passed host/build checks. **9D maintenance and lifecycle is in progress:** an operator runbook, finite SSH parser/caller and IDF applicability reviews, and offline notice assembly tooling are available. Scoped corrections have parent host/build evidence; the [finite dependency search](docs/dependency_advisory_coverage.md) is complete (all 22 IDF advisory entries across three pages plus named managed/browser channels), but fresh findings, explicit coverage gaps, release delivery/source/legal questions and whole-phase target gates remain open. **The fix-bearing vendor Wi-Fi bundle is integrated in the validated IDF 5.5.3 candidate, not radio-hardware closure**: the [update plan](docs/wifi_security_update_plan.md) retains target gates and unchanged PMF/WPA3; **Phase 9 is not complete or production-ready**. The user will validate Phase 9 as a whole; no 9D device validation or license clearance is claimed. See [security hardening](docs/security_hardening.md) for scope, operational profiles, and validation gates.
Latest supplied parent integration: **fresh isolated IDF 5.5.3 application build PASS**, **95,552 B linked RAM / 1,749,493 B flash** (**+1,212 B RAM / 19,408 B flash** versus historical 94,340 / 1,768,901 B). Explicit-candidate Phase 9 validation with interop and web performance **PASS 24/24**. Default root `pio run` timed out at **200 seconds during installation, before compilation**—not a normal root build PASS. See [candidate integration](docs/idf_candidate_integration.md) and [exact command/snapshot evidence](docs/phase9_validation.md#current-candidate-execution--2026-09-18). Linked size and host passes are not target headroom or release acceptance.
### Browser administration
Cookie login/logout supports both roles. Administrators also have an explicitly opened Admin shell sharing the canonical dispatcher, and typed **Serial, Accounts/password/SSH authorized keys, Network, Display, Broker, SSH, and HTTPS/Reboot** settings. Serial/Wi-Fi/client/writer quick controls reuse the same settings controllers. Navigation preserves terminal sessions and serial writer ownership; explicit transfer is confirmed and generation-safe. Browser-shell permissions remain narrower than typed Settings or UART0/admin SSH.
Network uses UTF-8 text/reversible hex SSIDs, explicit password Keep/Replace/disabled-STA Clear (never AP clear), RAM edits and explicit Save. Saved secrets are never prefilled/exported. Next profile follows enabled priority order, not the editor's selected index. Network `accepted` means owner admission, not online/DNS completion; disruption may precede acknowledgement.
HTTPS and SSH identity settings display public fingerprints and confirm both service and identity generations before rotation. HTTPS rotation commits before stop/restart and invalidates web logins; SSH stops before commit/restart and can disconnect clients even when persistence fails. A committed identity is never rolled back on restart failure. A lost response or timeout is not cancellation: inspect state rather than automatically replaying. Verify changed trust on UART0 with `web certificate info` or `ssh host-key info` before renewing browser trust/known_hosts; HTTPS restart requires fresh login. Browser identity reset/recovery/export is excluded; canonical CLI recovery remains available.
Keep UART0 ready for administrative recovery and native USB for network-independent UART1 access. USB is not an admin console, and whole-device reboot interrupts every transport. [Web administration contracts](docs/web_administration.md) cover API bounds, ownership, permissions, uncertainty and recovery. Dedicated typed network diagnostics and the unimplemented browser-session/USB control expansion were removed from scope; existing shell diagnostics and SSH settings remain.
## Documentation
- [Hardware wiring](docs/wiring.md): hardware profile, GPIO assignments, connector guidance, and safety notes.
- [Electrical tests](docs/electrical_tests.md): OLED/buttons, MAX3243, UART loopback, and session-broker verification procedures.
- [Role-based user database and UART0 administration](docs/user_administration_tests.md): user migration and administration, HTTPS/SSH authentication, and session-revocation validation.
- [Command reference](docs/command_reference.md): UART0 administration, serial, broker, USB, Wi-Fi, web, SSH, and diagnostic commands.
- [Role-based user database and UART0 administration](docs/user_administration_tests.md): user provisioning and administration, HTTPS/SSH authentication, session revocation, and reusable integrated web-administration regression procedures (not execution evidence).
- [Web administration](docs/web_administration.md): current bounded API/owner and recovery contracts; [acceptance evidence](docs/web_administration_acceptance.md) records sign-off and telemetry limits.
- [Security hardening](docs/security_hardening.md): Phase 9 scope, crash/debug baseline, diagnostic handling, and pending validation.
- [Security operations](docs/security_operations.md): provisioning, explicit saves, rotation, recovery, reconstruction and approved destructive reset/decommissioning; procedures, not device evidence.
- [Dependency license inventory](docs/dependency_licenses.md): bounded local inventory and unresolved distribution/source/notice obligations, not release clearance.
- [wolfSSL/wolfSSH advisory review](docs/wolf_security_review.md): implemented scoped mitigations, historical research and remaining target/maintenance gates.
- [Remaining SSH parser review](docs/ssh_parser_remaining_review.md): completed finite server-profile dispatch/caller review, corrections and explicit exclusions; not exhaustive parser safety.
- [IDF applicability review](docs/idf_security_review.md): six named findings and a bounded advisory-index feature screen, not all-CVE clearance.
- [Bounded Phase 9 host validation](docs/phase9_validation.md): [orchestrator](tools/validate_phase9.py), 23 default commands; build and OpenSSH interop are separate opt-ins.
- [Exact icon provenance](docs/icon_provenance.md): official 7.4.47 retained SVGs verified; manual bitmap derivation and distinct mockup Wi-Fi path remain unresolved.
- [Release notice packaging](docs/release_packaging.md): offline [notice tool](tools/release_notices.py), deterministic bounded assembly and separate recipient/source/legal gates.
- [Command reference](docs/command_reference.md): UART0/admin-SSH administration, serial, broker, USB, Wi-Fi, mDNS, web, SSH, and diagnostic commands.
## Flash partition layout
@@ -29,18 +51,18 @@ The N16R8 target has 16 MiB flash and 8 MiB octal PSRAM. PlatformIO uses the cus
| Partition | Offset | Size | Purpose |
|---|---:|---:|---|
| `nvs` | `0x009000` | 512 KiB | Serial, Wi-Fi, role-based users, legacy network credential, HTTPS identity, and SSH host-key data |
| `nvs` | `0x009000` | 512 KiB | Serial, Wi-Fi, mDNS hostname, local-display, role-based user, HTTPS identity, and SSH host-key data |
| `otadata` | `0x089000` | 8 KiB | Active OTA-slot selection metadata |
| `phy_init` | `0x08B000` | 4 KiB | Optional PHY initialization data |
| `nvs_key` | `0x08C000` | 4 KiB | Reserved for future encrypted-NVS keys |
| `coredump` | `0x08D000` | 128 KiB | Reserved for flash core dumps |
| `nvs_key` | `0x08C000` | 4 KiB | Unused; retained for layout compatibility (NVS encryption excluded) |
| `coredump` | `0x08D000` | 128 KiB | Unused by the supported crash policy; retained for layout compatibility |
| `ota_0` | `0x0B0000` | 4 MiB | Primary application/OTA slot |
| `ota_1` | `0x4B0000` | 4 MiB | Alternate application/OTA slot |
| `storage` | `0x8B0000` | 7488 KiB | Reserved for future LittleFS web assets, logs, and files |
Application offsets are aligned to the ESP32-S3's required 64 KiB boundary. The final storage partition ends at `0x1000000`, exactly the end of the 16 MiB flash chip.
The table reserves OTA and storage space; it does not implement OTA downloads, rollback confirmation, core-dump handling, NVS encryption, or filesystem mounting.
The table reserves OTA and storage space; it does not implement OTA downloads, rollback confirmation, NVS encryption, or filesystem mounting. Phase 9A disables new core dumps; it does not clear any existing `coredump` contents. The unused `nvs_key` and `coredump` reservations remain unchanged for layout compatibility; neither implies future enablement or secure erasure.
### One-time migration from the default partition table
@@ -52,7 +74,7 @@ pio run --target upload
pio device monitor -b 115200
```
This removes saved serial configuration and all other flash contents. The firmware recreates NVS with safe defaults. Subsequent ordinary uploads do not need a full erase.
**Obtain explicit approval for the target and all flash/NVS data loss before erase.** This removes firmware, accounts, Wi-Fi secrets, server identities and all saved configuration, not just serial settings. Reflash in an isolated RF environment and follow [UART0-first provisioning](docs/security_operations.md#first-provisioning--uart0-first); generated defaults enable fallback Wi-Fi and require deliberate protection. Erase success is not a forensic secure-erasure guarantee. Subsequent ordinary uploads do not need a full erase.
## Build
@@ -60,6 +82,8 @@ This removes saved serial configuration and all other flash contents. The firmwa
pio run
```
The root configuration pins PlatformIO espressif32 **6.13.0**, ESP-IDF **5.5.3** (`framework-espidf@3.50503.0`), and Xtensa/RISC-V toolchains **14.2.0+20251107**, with pinned component sources. Exact version pins do not establish a complete immutable build closure. Nine C overrides plus one forced header retain the reviewed corrections, including five signed WS receive-size checks; see the [semantic rebase review](docs/idf_553_rebase_review.md). It generates audited security corrections under `.pio/build/` without changing the installed SDK/managed components; changed source hashes fail configuration rather than silently dropping a fix. See the [library review and upgrade contract](docs/security_library_review.md). Do not edit generated corrections or update hashes without reviewing the new source.
## Upload and monitor
Connect the board's **USB-to-UART** port for firmware upload and the UART0 development console, then run:
@@ -73,12 +97,24 @@ The firmware provides an interactive UART0 console at `serial-tool>`. Run `help`
The console supports session history, line editing, cursor movement, and hierarchical Tab completion. After an unattended boot, attach an ANSI-capable terminal and press Enter once to enable enhanced editing; this avoids blocking while no terminal is attached.
Serial configuration and Wi-Fi edits remain in RAM until explicitly saved with `serial save` or `wifi save`. Manage role-based HTTPS/SSH passwords and SSH public keys with the physical UART0 `user` command group. `web credentials show` now exposes only the legacy migration/recovery credential, not an active Phase 8B network login.
Serial, Wi-Fi, mDNS hostname and display edits remain in RAM until explicitly saved with `serial save`, `wifi save`, `mdns save` or `display save`. These are same-device persistence commands, not backups; see [lifecycle and persistence semantics](docs/security_operations.md#working-configuration-versus-service-lifecycle). Authenticated admin SSH sessions expose the shared operational administration registry, including interactive secrets, TLS/SSH identity management, network diagnostics, and deferred reboot/SSH lifecycle commands. Create the first administrator on UART0 with `user add <username> admin` (optionally `--generate`). Explicit recovery of an unavailable user database remains UART0-only and rebuilds it empty; it refuses a healthy database. An administrator also cannot generate a replacement password for its own account over SSH, preventing the one-time value from being lost when that mutation revokes the session. Legacy web credential commands and `user bootstrap` are removed.
## Security notes
The HTTPS interface uses a device-specific self-signed certificate and role-aware HTTP Basic authentication over TLS; there is no plaintext HTTP or TCP serial listener. SSH accepts role-based passwords and authorized Ed25519/ECDSA P-256 public keys. User passwords are stored as salted PBKDF2-HMAC-SHA256 verifiers, but the legacy recovery password, HTTPS private key, SSH private key, and Wi-Fi credentials remain recoverable from unencrypted application-owned NVS blobs. Offline password guessing and stale append-oriented flash copies also remain possible. The reserved `nvs_key` partition does not enable encryption. Do not treat this firmware as resistant to physical flash or RAM extraction until the planned hardening work is complete.
The HTTPS interface uses a device-specific self-signed certificate and a same-origin login page with bounded server-side cookie sessions; HTTP Basic is no longer accepted. Open `/` or `/login`, sign in with a user-database password, and use **Sign out** before switching accounts. Four sessions have a one-hour absolute lifetime, including active serial connections; logout closes only that session's serial access. Login is globally limited to five credential verifications per 60 seconds, with explicit capacity/backoff errors. Direct-IP and mDNS access use separate host-only Secure/HttpOnly/SameSite=Strict cookies. Non-browser clients also require cookies, strict Origin and CSRF for mutations rather than Basic credentials. There is no plaintext HTTP or TCP serial listener. SSH accepts role-based passwords and authorized Ed25519/ECDSA P-256 public keys. User passwords are stored as salted PBKDF2-HMAC-SHA256 verifiers, but the HTTPS private key, SSH private key, and Wi-Fi credentials remain recoverable from unencrypted application-owned NVS blobs. Offline password guessing and stale append-oriented flash copies also remain possible. The reserved `nvs_key` partition does not enable encryption. Physical flash/RAM extraction and firmware replacement remain outside the threat model even after Phase 9. Secure boot and encrypted NVS are explicitly excluded; no flash/PSRAM encryption or physical JTAG eFuse restriction is promised.
SSH uses separate, boot-lifetime global admission budgets for handshakes and password/signed-key checks (burst six, one refill per ten seconds), and unsigned key probes (burst twelve, one per five seconds). Reconnect, SSH restart and counter clearing do not replenish them. Rate denial closes the authenticating connection without sleeping the owner task; the three-attempt per-connection failure limit remains. These global limits can temporarily deny legitimate new SSH logins under attack and do not promise fair access or zero CPU impact. Hidden console prompts reject overlong/unsupported input instead of silently accepting a prefix; consumed SSH admin staging bytes are wiped. See [security hardening](docs/security_hardening.md#9b-ssh-admission-and-credential-handling) for exact semantics and remaining review work.
Phase 9C limits HTTPS to TLS 1.2 ECDHE-ECDSA with AES-128/256-GCM, and SSH to AES-128/256-GCM with Curve25519/P-256 key exchange. Legacy-only clients may no longer connect; existing device identities and authorized keys do not need rotation. The HTTPS policy is server-local, leaving outbound-client defaults intact. Pinned dependency corrections address cleanup leaks, parser bounds and secret-bearing storage retirement; secure allocation growth can temporarily require old and new blocks, so target resource validation remains necessary. These fixes are not a complete secret-zeroization or upstream-advisory certification. See the [audit, exact algorithms and limits](docs/security_library_review.md).
The Phase 9A supported build baseline requires disabled core dumps and silent panic reboot, rejecting panic print/halt/GDBstub and software debugger-aware options at compile time. Development, test, and production are operational profiles of the same build baseline, not separate PlatformIO environments. Silent panic reboot sacrifices panic backtraces/register dumps; reset-reason/boot information and ordinary status/logging can remain. This is not a general log-redaction guarantee. Treat raw flash, RAM and dumps as secret-bearing; do not export them as routine diagnostics. No retroactive dump clearing or secure-erase claim is made. See [security hardening](docs/security_hardening.md) for the pending checks and reviewed synthetic-secret debugging procedure.
## License
This project is licensed under the [GNU General Public License version 3 only](LICENSE) (`GPL-3.0-only`). Third-party components remain subject to their respective licenses. The integration baseline uses Espressif registry components `wolfssl/wolfssl` `5.8.2~1` and `wolfssl/wolfssh` `1.4.20`; review upstream security releases before production use.
This project is licensed under the [GNU General Public License version 3 only](LICENSE) (`GPL-3.0-only`). Third-party components remain subject to their respective licenses. The integration baseline uses Espressif registry components `espressif/mdns` `1.12.0`, `wolfssl/wolfssl` `5.8.2~1`, and `wolfssl/wolfssh` `1.4.20`; see the [partial advisory review](docs/wolf_security_review.md) for scoped corrections and remaining review/target gates, not a whole-library safety claim. The [license inventory](docs/dependency_licenses.md) records open radio-blob corresponding-source/exception questions, notice delivery and preferred-source requirements, generated-file modification notices, and wolfSSH packaging clarification. Neither this license declaration nor the inventory clears firmware/device distribution.
### Legacy credential removal
Missing user storage is persisted as an empty database; no shared credential is imported or synchronized. Existing valid v1 user records retain their accounts, roles, IDs, verifiers and keys without a schema change. HTTPS `web_sec/material` upgrades valid 1,392-byte v1 storage to 1,340-byte TLS-only v2, retaining exact certificate/key DER, fingerprint and generation, and committing before publication. Invalid records or migration failures fail closed rather than triggering fallback replacement. `web certificate rotate --force` remains available; `web reset --force` replaces TLS identity only, not users.
**Downgrade warning:** older v1-only firmware cannot read v2 HTTPS material. Logical NVS replacement is not a secure flash wipe; historical plaintext credentials can remain in flash. This cleanup requires no factory/partition erase. See [implementation and evidence limits](docs/legacy_credential_removal.md); final integration build evidence is pending.
+150
View File
@@ -0,0 +1,150 @@
# SPDX-License-Identifier: GPL-3.0-only
# Include after project(): IDF component targets and their final source lists exist.
if(CMAKE_VERSION VERSION_LESS 3.18)
message(FATAL_ERROR "Security overrides need CMake 3.18 source-property directory support")
endif()
set(_sak_security_script "${CMAKE_CURRENT_LIST_DIR}/../tools/security_overrides.py")
get_filename_component(_sak_security_script "${_sak_security_script}" REALPATH)
if(NOT PYTHON)
find_package(Python3 REQUIRED COMPONENTS Interpreter)
set(_sak_security_python "${Python3_EXECUTABLE}")
else()
set(_sak_security_python "${PYTHON}")
endif()
idf_build_get_property(_sak_security_idf IDF_PATH)
execute_process(
COMMAND "${_sak_security_python}" "${_sak_security_script}"
--idf-path "${_sak_security_idf}"
--project-dir "${PROJECT_SOURCE_DIR}"
--binary-dir "${CMAKE_BINARY_DIR}"
RESULT_VARIABLE _sak_security_result
OUTPUT_VARIABLE _sak_security_stdout
ERROR_VARIABLE _sak_security_stderr
)
if(NOT _sak_security_result EQUAL 0)
message(FATAL_ERROR "SDK security override generation failed:\n${_sak_security_stdout}${_sak_security_stderr}")
endif()
include("${CMAKE_BINARY_DIR}/security_overrides/manifest.cmake")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${_sak_security_script}" "${SAK_SECURITY_VERSION_HEADER}")
if(SAK_SECURITY_HEADER_IDS)
get_filename_component(_sak_security_tools "${_sak_security_script}" DIRECTORY)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${_sak_security_tools}/wolfssh_order/delta.json")
endif()
# Public extension point: the Python Entry registry supplies the mapping. This
# function is backend-agnostic; a later pinned project/vendor source uses it too.
function(sak_security_replace_source component original generated nested_target)
idf_component_get_property(_target "${component}" COMPONENT_LIB)
if(NOT TARGET "${_target}")
message(FATAL_ERROR "Security override: missing component target ${component}")
endif()
if(NOT "${nested_target}" STREQUAL "")
if(NOT component STREQUAL "mbedtls" OR
NOT nested_target MATCHES "^(mbedtls|mbedx509|mbedcrypto)$")
message(FATAL_ERROR "Security override: invalid nested target ${component}/${nested_target}")
endif()
if(NOT TARGET "${nested_target}")
message(FATAL_ERROR "Security override: missing nested target ${nested_target}")
endif()
set(_target "${nested_target}")
get_target_property(_imported "${_target}" IMPORTED)
get_target_property(_alias "${_target}" ALIASED_TARGET)
get_target_property(_owner_dir "${_target}" SOURCE_DIR)
get_filename_component(_owner_dir "${_owner_dir}" REALPATH)
get_filename_component(_expected_owner "${_sak_security_idf}/components/mbedtls/mbedtls/library" REALPATH)
if(_imported OR _alias OR NOT _owner_dir STREQUAL _expected_owner)
message(FATAL_ERROR "Security override: unexpected nested target owner ${_target}: ${_owner_dir}")
endif()
endif()
get_target_property(_source_dir "${_target}" SOURCE_DIR)
get_target_property(_sources "${_target}" SOURCES)
get_filename_component(_expected "${original}" REALPATH)
set(_matches 0)
set(_replaced)
foreach(_source IN LISTS _sources)
if(_source MATCHES "\\$<")
# An expression could hide an additional copy of the protected source.
message(FATAL_ERROR "Security override: unaudited source expression in ${component}: ${_source}")
endif()
get_filename_component(_absolute "${_source}" ABSOLUTE BASE_DIR "${_source_dir}")
get_filename_component(_absolute "${_absolute}" REALPATH)
if(_absolute STREQUAL _expected)
math(EXPR _matches "${_matches} + 1")
list(APPEND _replaced "${generated}")
else()
list(APPEND _replaced "${_source}")
endif()
endforeach()
if(NOT _matches EQUAL 1)
message(FATAL_ERROR "Security override: ${component} needs exactly one ${original}; found ${_matches}")
endif()
# Target flags/includes/definitions are retained because the target is not
# replaced. Preserve source-specific properties in the owning directory too.
set(_properties COMPILE_FLAGS COMPILE_OPTIONS COMPILE_DEFINITIONS
INCLUDE_DIRECTORIES OBJECT_DEPENDS OBJECT_OUTPUTS LANGUAGE
SKIP_PRECOMPILE_HEADERS SKIP_UNITY_BUILD_INCLUSION
SKIP_LINTING HEADER_FILE_ONLY)
set(_configs DEBUG RELEASE RELWITHDEBINFO MINSIZEREL
${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE})
foreach(_config IN LISTS _configs)
string(TOUPPER "${_config}" _config)
list(APPEND _properties "COMPILE_DEFINITIONS_${_config}")
endforeach()
foreach(_property IN LISTS _properties)
get_property(_is_set SOURCE "${_expected}" DIRECTORY "${_source_dir}"
PROPERTY "${_property}" SET)
if(_is_set)
get_property(_value SOURCE "${_expected}" DIRECTORY "${_source_dir}"
PROPERTY "${_property}")
set_property(SOURCE "${generated}" DIRECTORY "${_source_dir}"
PROPERTY "${_property}" "${_value}")
endif()
endforeach()
get_filename_component(_original_dir "${original}" DIRECTORY)
get_property(_includes SOURCE "${generated}" DIRECTORY "${_source_dir}"
PROPERTY INCLUDE_DIRECTORIES)
# Restore the implicit quoted-include search directory lost by relocating C.
set_property(SOURCE "${generated}" DIRECTORY "${_source_dir}"
PROPERTY INCLUDE_DIRECTORIES "${_original_dir};${_includes}")
set_property(TARGET "${_target}" PROPERTY SOURCES "${_replaced}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${original}" "${generated}")
message(STATUS "Security override: ${component}: ${original} -> ${generated}")
endfunction()
# HandshakeInfo and WOLFSSH are ABI-sensitive. Force the same generated header
# into the library AND every transitive consumer, even if a consumer adds a
# vendor include directory ahead of the overlay. The original include guard
# then prevents a second, stale definition. This also creates compiler deps.
foreach(_sak_security_id IN LISTS SAK_SECURITY_HEADER_IDS)
if(NOT _sak_security_id STREQUAL "wolfssh_internal_header" OR
NOT SAK_SECURITY_${_sak_security_id}_COMPONENT STREQUAL "wolfssl__wolfssh")
message(FATAL_ERROR "Security override: unaudited header overlay")
endif()
idf_component_get_property(_sak_security_wolfssh wolfssl__wolfssh COMPONENT_LIB)
if(NOT TARGET "${_sak_security_wolfssh}")
message(FATAL_ERROR "Security override: missing wolfSSH overlay target")
endif()
target_include_directories("${_sak_security_wolfssh}" BEFORE PUBLIC
"${SAK_SECURITY_WOLFSSH_INCLUDE}")
# PlatformIO's ESP-IDF adapter sorts app flags and deduplicates component
# flags. Keep option+operand atomic, as with wolf_crypto_policy.h.
target_compile_options("${_sak_security_wolfssh}" PUBLIC
"-include${SAK_SECURITY_${_sak_security_id}_GENERATED}")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${SAK_SECURITY_${_sak_security_id}_ORIGINAL}"
"${SAK_SECURITY_${_sak_security_id}_GENERATED}")
endforeach()
foreach(_sak_security_id IN LISTS SAK_SECURITY_OVERRIDE_IDS)
sak_security_replace_source(
"${SAK_SECURITY_${_sak_security_id}_COMPONENT}"
"${SAK_SECURITY_${_sak_security_id}_ORIGINAL}"
"${SAK_SECURITY_${_sak_security_id}_GENERATED}"
"${SAK_SECURITY_${_sak_security_id}_TARGET}")
endforeach()
+14
View File
@@ -0,0 +1,14 @@
# SPDX-License-Identifier: GPL-3.0-only
# Apply after project(). PUBLIC propagates the resolved-settings guard to every
# wolfSSL consumer, including wolfSSH and the application (ABI-sensitive keys).
idf_component_get_property(_sak_wolf_target wolfssl__wolfssl COMPONENT_LIB)
if(NOT TARGET "${_sak_wolf_target}")
message(FATAL_ERROR "wolf crypto policy: missing wolfSSL component target")
endif()
# Existing upstream checks, not a vendor-source backport. PUBLIC keeps library
# and consumer settings consistent without changing the root build file.
target_compile_definitions("${_sak_wolf_target}" PUBLIC
WOLFSSL_VALIDATE_ECC_IMPORT
WOLFSSL_ECDHX_SHARED_NOT_ZERO)
target_compile_options("${_sak_wolf_target}" PUBLIC
"-include${CMAKE_CURRENT_LIST_DIR}/wolf_crypto_policy.h")
+43
View File
@@ -0,0 +1,43 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#ifndef SAK_WOLF_CRYPTO_POLICY_H
#define SAK_WOLF_CRYPTO_POLICY_H
#include <wolfssl/wolfcrypt/settings.h>
/* PR10133 recommends this existing check for older releases. In 5.8.2 the
* software validator must not be replaced with a successful hardware stub. */
#if !defined(HAVE_ECC) || !defined(WOLFSSL_VALIDATE_ECC_IMPORT) || \
!defined(HAVE_ECC_CHECK_KEY)
#error "wolf crypto policy: ECC requires validated imports"
#endif
#if defined(NO_ECC_CHECK_PUBKEY_ORDER) || defined(WOLF_CRYPTO_CB_ONLY_ECC) || \
defined(WOLFSSL_ATECC508A) || defined(WOLFSSL_ATECC608A) || \
defined(WOLFSSL_CRYPTOCELL) || defined(WOLFSSL_SILABS_SE_ACCEL) || \
defined(WOLFSSL_SE050) || defined(WOLFSSL_STM32_PKA)
#error "wolf crypto policy: review ECC validation backend before changing it"
#endif
#ifndef WOLFSSL_ECDHX_SHARED_NOT_ZERO
#error "wolf crypto policy: X25519 requires all-zero shared-secret rejection"
#endif
/* PR9275 selects small math on Xtensa to avoid compiler-introduced timing
* differences. Check resolved settings, not just command-line intentions.
* https://github.com/wolfSSL/wolfssl/pull/9275
*/
#if !defined(HAVE_CURVE25519) || !defined(CURVE25519_SMALL)
#error "wolf crypto policy: X25519 requires CURVE25519_SMALL"
#endif
#if !defined(HAVE_ED25519) || !defined(ED25519_SMALL)
#error "wolf crypto policy: Ed25519 requires ED25519_SMALL"
#endif
/* 5.8.2 excludes small math from automatic blinding and rejects this pairing.
* Do not force blinding back on: key layout and function signatures differ.
*/
#ifdef WOLFSSL_CURVE25519_BLINDING
#error "wolf crypto policy: small X25519 is incompatible with blinding"
#endif
#if defined(HAVE_CURVE448) || defined(HAVE_ED448)
#error "wolf crypto policy: review PR9275 small math before enabling 448"
#endif
#endif
+13 -2
View File
@@ -29,6 +29,16 @@ dependencies:
registry_url: https://components.espressif.com/
type: service
version: 3.0.3
espressif/mdns:
component_hash: 3ba256ac95e07c274be53cbd73f06cb846c403b61e8fbdf1be57bdb79db7a63e
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.12.0
espressif/tinyusb:
component_hash: a72b7d67472914ab76309340fd50d578b31e310963d45ad0f81144bde3314752
dependencies:
@@ -48,7 +58,7 @@ dependencies:
idf:
source:
type: idf
version: 5.5.0
version: 5.5.3
wolfssl/wolfssh:
component_hash: 24d623360c07374a90b1ade8d1218b24bb7b661fd51ace9135dccf510a338927
dependencies: []
@@ -66,9 +76,10 @@ dependencies:
direct_dependencies:
- espressif/esp_tinyusb
- espressif/led_strip
- espressif/mdns
- idf
- wolfssl/wolfssh
- wolfssl/wolfssl
manifest_hash: 34e93560f67a22e2a43647a4663b450e07ecd9fa3fdc2ac38343c1a76b513f5d
manifest_hash: 4b6fa5a7e06122f9194adfc282a4baf4247d8a114b905e65f6397503e59f0898
target: esp32s3
version: 2.0.0
+234
View File
@@ -0,0 +1,234 @@
# Architecture
## Purpose and system shape
This ESP32-S3 firmware exposes one MAX3243-backed UART1 RS-232 port through three bounded transport families:
- native USB CDC-ACM, which is local and unauthenticated;
- authenticated HTTPS with a browser WebSocket terminal;
- authenticated SSH.
UART0 remains a separate trusted administration and recovery console. A local OLED and three buttons provide status and a deliberately limited control surface. Persistent application configuration and security material are stored in versioned NVS blobs.
The central data-path invariant is one serial writer with multiple observers:
```text
USB CDC ---------\
WebSocket --------> session broker <--> serial service <--> UART1 <--> MAX3243
SSH role=user ---/ |
+-- one writer lease
+-- bounded output per observer
SSH role=admin ------> shared administration dispatcher <------ UART0
(does not join the broker)
```
## Typed Network settings
`web_network_settings` admits bounded current-admin operations to the existing ID-only dispatcher; `wifi_manager` remains radio/event/reannouncement owner and `mdns_service` owns independent hostname persistence. Zero-wait secret-free projections never copy saved PSKs onto HTTPD. Conditional compare/merge preserves omitted secrets, queue admission precedes Wi-Fi publication, and edits require explicit Save. Wi-Fi Load is stored-only; mDNS may load deterministic defaults. SSIDs remain byte-reversible; AP clear is denied. One login-bound slot and one-second timer bound queued secret retention to 30 seconds plus scheduling latency, not cancellation after owner admission. `accepted` is not online/DNS completion. See [Network contracts](../web_administration.md#network).
## Startup and initialization
`app_main()` in `src/main.c` is the composition root. The implemented order matters:
1. Report PSRAM and initialize the sole project-owned application DRBG before Wi-Fi or other radio use.
2. Initialize boot-critical RGB LED state, RS-232 ownership/static-safe hardware, diagnostics, and the shared administration dispatcher resources. RGB LED initialization is currently guarded by `ESP_ERROR_CHECK` and is therefore boot-fatal.
3. Attempt optional OLED initialization and a bounded boot animation. Display failure is nonfatal; a working display can delay later recovery services by about five seconds.
4. Initialize button diagnostics and load local-UI and serial configurations, falling back to RAM defaults on load failure.
5. Initialize the serial service, session broker, and permanent USB transport task. UART1 is not started automatically here.
6. Load/generate HTTPS material, then initialize the independent user database, committing an empty database when storage is missing. User-database failure makes network authentication fail closed.
7. Initialize the HTTPS runtime, SSH host-key material, and permanent SSH owner task.
8. Load Wi-Fi configuration and the independent mDNS hostname configuration, persist generated first-boot Wi-Fi defaults when appropriate, initialize the nonfatal mDNS configuration service and Wi-Fi manager, and start Wi-Fi when configured for boot. The Wi-Fi manager owns subsequent mDNS announcement transitions.
9. Start HTTPS and SSH only when their startup gates pass. The Wi-Fi portion requires valid configuration and successful manager initialization and, when enabled at boot, successful submission of its asynchronous start request; it does not require association, an IP address, or reachability. HTTPS additionally requires its own security/runtime readiness; SSH independently requires its own security/runtime readiness, not HTTPS identity readiness. This reflects `main.c` after accepted legacy-credential cleanup.
10. Start the local status/control task if button initialization succeeded.
11. Construct ESP-IDF's UART REPL to initialize `esp_console`, but do not start the stock REPL task. Register command groups, install completion, and start the custom UART frontend that feeds the shared dispatcher.
Several core initializers use `ESP_ERROR_CHECK`; optional display and network/security paths generally log failure while retaining UART0 administrative recovery and network-independent UART1 access through USB. SSH starts before command registration, so role-`user` sessions can be admitted in that interval while role-`admin` sessions are rejected until the administration frontend is ready.
## Serial service and physical ownership
`serial_service` owns the UART1 driver while running. It exposes bounded RX/TX streams and a task that:
- continuously drains UART RX, even if UART event notification is incomplete;
- moves pending TX to the UART FIFO without blocking indefinitely on CTS;
- discards and accounts queued traffic during shutdown/reconfiguration.
`rs232_port_owner` separately protects the physical UART/MAX3243 resource:
- `NONE`: available;
- `PHASE0`: hardware diagnostics own it;
- `SERVICE`: serial service owns it;
- `FAULT`: cleanup could not establish a safe state; reboot is required.
The owner is cooperative rather than an interceptor for UART/GPIO APIs. Active diagnostic commands claim `PHASE0`, and the running service claims `SERVICE`; boot-time static-safe GPIO initialization and service-owned restoration of that static mode are explicit exceptions. Unsafe cleanup keeps the transceiver disabled and marks a fault rather than attempting continued operation.
Serial configuration is a working RAM value. Applying it while running performs a stop/restart and attempts rollback on failure. Stop/reconfiguration discards and accounts serial-service RX/TX streams and task-local pending TX, but does not disconnect broker clients or clear their writer lease, events, or already-fanned output. An open USB session retries service start after a stop; existing WebSocket and role-`user` SSH sessions do not independently restart it. Persistence is explicit through save/reset commands.
## Session broker and data flow
The permanent `session_broker` task is the intended sole consumer/producer of serial-service data.
### RS-232 to clients
```text
UART RX -> serial-service RX stream -> broker task
-> independent bounded output stream for every connected client
-> USB / WebSocket / SSH transport output
```
The broker drains serial input even with no clients. A full client output stream drops only that client's copy and updates drop counters; it does not block UART reception or other clients.
Binary serial WebSocket output uses the IDF-5.5.3-pinned `web_httpd_ws_send_binary` adapter: one owner-only session-override send of a bounded header+payload copy (516 bytes of local scratch, 512-byte payload). Existing generation validation and one outstanding work item per slot remain required. Non-full sends immediately replace that session's send override with a reject-only guard, mark it closing and shut down the socket before deferred cleanup; this prevents automatic SDK control replies from reentering TLS after incomplete output. HTTPD retains TLS destruction ownership. Text/control and admin output retain the SDK sender. One send call does not imply one TLS record, packet or peer receipt; the user signed off drop-free230400-baud full-client-mix operation at160MHz. Runtime stack-margin validation remains a separate follow-up; evidence and acceptance scope are in `current-state.md`.
Active-client counter snapshots expose ID/type/pending/HWM/UART/queued/read/dropped. HWM is maintained independently of web tracing and counter clear seeds current occupancy. Read means transport handoff, not peer receipt. Disconnect removes the client row while global totals retain traffic and unread-output discards. Independent default-disabled web performance capture uses two fixed slot records and nonwrapping epoch/generation fences; toggles fence in-flight samples, disable freezes aggregates, clear preserves enable state. Binary-only timestamps bound reservation-entry to callback-entry before locking, synchronous send calls and completion to broker-read return; idle and intervening work prevent scheduler-only/backlog-at-completion claims. No new instrumentation allocations or scheduling/buffer changes. Exact fields, overhead and capture contracts: [throughput diagnostics](../web_throughput_diagnostics.md).
### Clients to RS-232
```text
transport input -> broker write check -> serial-service TX stream -> UART TX
```
Only the generation-safe client ID holding the current writer lease may enqueue input. All connected clients, including the writer, observe UART output. Normal requests acquire the lease only when free; disconnect releases it. Administrative APIs can force reassignment or compare-and-release an expected writer.
Broker events are advisory bounded notifications. Transports reconcile against authoritative snapshots because an event queue can overflow. `DTR_ON_CONNECT` follows whether any broker client is connected, not writer ownership.
The broker currently enters nonblocking serial read/write APIs while holding its mutex and takes the serial-service state mutex during first-connect/last-disconnect DTR changes. Keep this ordering acyclic: serial-service code must not call broker APIs while holding its state mutex.
## Transport architecture
### USB CDC
`usb_cdc_transport` has a permanent transport task and TinyUSB callbacks. Attached plus host DTR asserted is treated as open. Opening starts the serial service if necessary, creates the `usb-cdc` broker client, and opportunistically requests writer ownership; otherwise USB observes.
TinyUSB callbacks enqueue/copy data and state; the transport task owns broker lifecycle and forwarding. The line-coding callback records the latest host setting for diagnostics only. It never reconfigures UART1: physical framing and speed remain controlled by the explicit serial configuration, regardless of USB writer ownership.
### HTTPS, WebSocket, and web serial
`web_server` owns HTTPS on port 443 with a persisted self-signed P-256 identity. Phase 9C uses exact-hash build-tree SDK corrections for failed-start/post-handshake TLS cleanup, copied-key wiping, HTTPD scratch retirement and TLS1.2 ECDHE-ECDSA AES-GCM-only server policy. Client defaults/global crypto are unchanged. The checked-in override registry plus pinned original, not installed source alone, define compiled behavior. [Source/ownership contract](../security_library_review.md). `web_serial_transport` mediates two fixed WebSocket slots through the broker; HTTPD owns socket sends/close, the transport task owns broker IO. Four outstanding serial tickets, four cookie sessions, one optional admin WebSocket and six total HTTPD sockets are distinct limits; LRU is disabled. Current handler capacity is 39. Base HTTPS can serve authenticated non-WebSocket routes if optional serial/admin transport initialization fails.
Cookie login/logout replaces Basic/cache. Digest-only records carry copied principals, CSRF state, absolute expiry and nonreused originating-session IDs. Strict same-origin/CSRF mutations and session/principal checks gate admission; logout invalidates its session before transport cleanup, account mutations invalidate only the affected account, and ongoing currentness is authoritative. Authentication initialization failure gates HTTPS; failed start/accepted stop wipes records. A non-consuming quota/epoch check rejects exhausted login requests before body receive; verification reservation remains post-parse and only that reservation charges the existing fixed window. RNG/SHA/database calls run outside short spinlocks with post-call epoch/identity revalidation. [Authentication contract](../web_administration.md#authentication-and-admission).
`web_httpd_adapter` is the sole private IDF 5.5.3 boundary for duplicate headers, admission-before-101, consumed-scratch wiping, staged optional URI registration, combined binary sends and owner-only idle sweeps. Re-audit its version guard on SDK upgrades. The 5.5.3 rebase retains private-layout/ownership contracts and adds a pinned WS receive correction so negative fixed-header reads cannot pass unsigned length comparisons; see [rebase evidence](../idf_553_rebase_review.md). HTTPD debug logging must not expose headers/tickets. `web_diagnostics` independently observes public post-TLS callbacks using six metadata records and a default-disabled 32-event ring; it cannot see preaccept/in-progress/failed TLS. [Admission diagnostics](../web_admission_diagnostics.md).
`web_httpd_idle` uses one one-second timer, six rows and at most one queued owner probe. Current-owner shutdown follows 15 seconds of observed ordinary idle, exempting actual WebSockets/async/pending input. Owner delays prevent hard timeout guarantees; accepted-but-lost work stays reserved until successful destruction, failed stop retains ownership. [Idle lifecycle contract](../https_idle_cleanup.md).
`web_ui`/`web_login_ui` own authored documents/scripts and hash-bound CSP loaders; authentication documents/app are no-store. Checked-in generated xterm/logo assets are compiled, not regenerated by ordinary builds. Browser Serial/Admin/Settings navigation changes view/input only, preserving serial client/lease and hidden output draining. Session-identity changes require a clean document; pagehide/restore revalidates before exposing buffers. One shared quick-settings host/controller preserves drafts, stale selections and pending uncertainty. [Terminal and console contract](../web_administration.md#terminal-and-console-ownership).
### Browser administration and HTTPS lifecycle
`web_admin_transport`/`web_admin_tickets` add one optional admin socket, two session-bound tickets and admission to the same two remote-console slots shared with SSH, never a broker client. HTTPD owns a 1,552-byte PSRAM-only payload and IO; a 20 ms timer queues at most one poll. Current-owner shutdown avoids queued reusable socket pointers. Detach fences submissions and only successful HTTPD stop retires old work. Console/owner checks enforce currentness before sensitive work; unsupported parsed shell commands reject before effects. [Browser-shell policy](../web_administration.md#browser-shell-policy).
`web_lifecycle_settings` uses one original-login slot and send-return → nonreused-ID HTTPD callback → existing dispatcher for self-cutting HTTPS/reboot actions. Two-second ACK and 30-second dequeue bounds precede admission, not receipt/completion. Accepted-but-lost callbacks retain one reservation through failed stop; only callback/successful destruction retires it. Conditional stop/restart reserve saturated lifecycle generation; restart retains ownership through stop/start. Conditional reboot invokes canonical `esp_restart()` outside locks, never HTTPD self-stop or console-cleanup waits.
`web_server_replace_identity` reserves service before identity and retains both through commit → reserved stop/start. Direct security and canonical CLI/browser-shell paths share task-bound nonreused identity reservations. Crypto/NVS run outside short security/service locks; commit precedes publication/wipe. Precommit failure leaves identity/HTTPD/logins unchanged; postcommit lifecycle failure never rolls back identity and can leave served/stored fingerprints different. Failed stop skips start and retains canonical recovery. Public service/security projections are separate observations, not authorization. [HTTPS ownership, generation and recovery contract](../web_administration.md#https-and-reboot).
### SSH
Typed SSH settings use the existing ID dispatcher and original-login result slot, never HTTPD wolfSSH calls or owner waits. Conditional lifecycle/session controls compare a saturated service generation and exact nonreused session ID under canonical locks. `ssh_transport_replace_identity` reserves service then identity before stop, retaining the command mutex across stop → commit → conditional restart. Failed stop skips mutation/start; failed persistence may follow disconnection; committed identity is never rolled back after restart failure. Only the SSH owner frees context after all slots retire, and start rejects orphan handles. Direct security/CLI/deferred SSH callers share task-bound identity reservations; crypto/NVS run outside security locks. HTTPS remains available, so no self-cutting HTTP ACK gate is needed. [SSH contracts](../web_administration.md#ssh).
`ssh_transport` uses wolfSSH on port 22 with two fixed session/handshake slots. Initialization calls `wolfSSH_Init()` in the caller before task creation; after that, one owner task pinned to core 1 exclusively owns runtime contexts/sessions and wolfSSH calls. It enforces bounded handshakes, authentication attempts, receive work, and session buffers. Phase 9B adds owner-only boot-lifetime token buckets for handshake admission, password/signed-key checks and unsigned probes; reconnect/service restart/counter clear do not reset them. Rate rejection closes the authenticating connection without sleeping the owner. Global starvation remains a tradeoff; see [admission policy](../security_hardening.md#9b-ssh-admission-and-credential-handling).
Authentication uses user-database passwords or stored Ed25519/ECDSA-P256 public keys. Phase 9C applies explicit GCM/Curve25519/P-256 algorithm lists before context publication; policy failures discard the candidate. A source-pinned parser correction bounds password fields before callbacks and wipes the method payload afterward (synchronous project callbacks). Global wolfSSL memory hooks wipe retired usable allocations; shrink retains capacity, growth may require old and new blocks simultaneously. These hooks do not replace mbedTLS allocation. [Policy/limits](../security_library_review.md). Public-key lookup authorizes a username/key pair, while wolfSSH verifies signed proof of possession. SSH host identity is a separate persisted P-256 key managed by `ssh_security`. A pending-result marker gates exactly-once signed-key completion/currentness; the reviewed wolfSSH version/feature profile is guarded and keyboard-interactive has an explicit rejecting callback (advertisement is not a dispatch filter). Consumed admin staging bytes and retired slots are wiped; this is not a full library-memory wipe guarantee.
Routing follows the authenticated role:
- `user`: start the serial service if necessary, then create a broker-backed binary-transparent serial stream and opportunistically request writer ownership;
- `admin`: bounded administration console, with no broker client or writer lease.
A shell request is required, but project code does not explicitly require a PTY. Exec and subsystem requests are rejected, and there is no project SFTP, SCP, agent-forwarding, or TCP-forwarding route.
## Authentication, authorization, and revocation
`user_database` is a fixed-capacity, mutex-protected store: at most eight accounts and three authorized keys per account. Accounts have `user` or `admin` role, random account ID, and authentication generation. Passwords are salted PBKDF2-HMAC-SHA256 verifiers; plaintext passwords are not retained in the database.
Network code holds copied, secret-free principals rather than pointers into database records. Principal currentness requires matching username, account ID, role, and authentication generation. Password, role, or key changes increment the generation; deletion/recreation also changes the account ID.
Revocation has two layers:
1. after a database mutation commits, the command layer makes best-effort targeted WebSocket/SSH revocation calls; notification failure does not roll back the mutation;
2. transports periodically and at sensitive boundaries recheck principal currentness, providing authoritative fail-safe closure if notification fails.
The final administrator cannot be deleted or demoted. UART0 establishes the first administrator through normal `user add <username> admin` and owns explicit unavailable-database recovery to empty. Recovery refuses a healthy database. No bootstrap API or command remains. Authenticated admin SSH can run the operational registry but is denied recovery; other secret-bearing commands are remotely available unless their handlers deny them.
NVS is not encrypted. Password verifiers improve password storage, but Wi-Fi credentials and TLS/SSH private keys remain recoverable under physical flash extraction.
## Typed Accounts and Serial settings
`web_account_settings` owns one login-bound slot for create/password/role/delete/key operations; HTTPD reads compact zero-wait metadata and queues only IDs. The database compares target username/account-ID/auth-generation inside its mutation lock and shares canonical invariant/commit logic. Successful commands target-revoke, including self; result loss is uncertain. A one-second timer wipes queued non-executing credentials after 30 seconds plus scheduling latency; admitted work wipes locals on return. Generated password delivery is a separate no-retained-retrieval POST, not mutation; key listing is fingerprint-only with stable sparse indices. [Accounts contracts](../web_administration.md#accounts-and-authorized-keys).
`web_serial_settings` queues bounded typed operations to the same dispatcher, retaining one original-login result and a 30-second dequeue check. Apply/Defaults are RAM-only; Save persists device working state. Reconfiguration can discard serial-service pending bytes while broker clients/lease/output remain. Snapshot reads are zero-wait and consistent; `/api/status` reports unavailable running state as null. Settings navigation preserves both terminals; bounded completion checks and manual uncertainty recovery never replay mutations. [Typed API/lifetime](../web_administration.md#typed-settings-api-and-operation-lifetime).
## Console architecture
UART0 and admin SSH share canonical command implementations:
```text
UART0 linenoise frontend --\
> fixed request queue -> one dispatcher -> esp_console_run()
admin SSH line editor ----/ |
+-> registered *_console handlers
```
`admin_ssh_console` creates the dispatcher before network services but marks command dispatch ready only after ESP-IDF console registration and successful UART frontend task creation. An admin SSH connection during that boot window is rejected rather than racing an incomplete registry.
The dispatcher is the sole caller of `esp_console_run()`, serializing UART0 and all admin SSH commands. This is required because the console registry is treated as non-reentrant, but it also means a long command or interactive prompt blocks all administration entry routes.
The transport-neutral boundary retains `admin_ssh_console_open_owned()` and adds available-slot admission for runtime SSH/browser owners: copied transport-qualified slot/session/generation identity plus a firmware-lifetime immutable owner adapter. The existing two console slots are shared, not multiplied per frontend; active/executing slots cannot be replaced. Owners serialize per-session input, consume output and enforce transport liveness; completion scratch is claimed nonblockingly across owners. The existing control task calls drain/lifecycle adapters outside console locks. SSH uses generation-checked published snapshots, principal copies and its assigned console index, never wolfSSH from the control task. `SELF_CLOSE` is owner-relative; legacy SSH actions remain SSH-specific and unsupported owner actions are rejected. Dispatcher-side owner `is_current` checks run outside console locks, with full identity recheck after validation. Commands revalidate immediately before the runner; prompts revalidate before publication and after waits (250 ms polling plus check/scheduling latency), rejecting revoked submitted input and stale wakes. SSH preserves close intent through external-close consumption. Consumed output is wiped. These checks do not cancel arbitrary executing handlers or replace owner-side input/output and lifecycle validation.
For SSH, standard output/error is redirected to the invoking session's bounded output ring. `console_input` routes visible or hidden prompts to UART0 or the active SSH session. `exit` and Ctrl+D on an empty admin SSH line use bounded deferred self-disconnect after their acknowledgement drains; role-`user` SSH remains a binary-transparent serial stream. Session tokens include slot and generation so late queued work cannot attach to a reused SSH slot. Only the SSH owner task moves ring output through wolfSSH.
Admin SSH `exit`, remote reboot, SSH stop/disconnect, and host-key rotate/reset use deferred control. The control task waits up to ten seconds for command state plus administration and transport application buffers to clear, then adds a short delay; this is a bounded best-effort heuristic, not peer-delivery confirmation. UART0 invokes these actions synchronously. User mutations and their revocations are not part of this mechanism. UART0 linenoise and the SSH editor consume the same manually maintained completion matcher and candidate formatter, so the two administration routes cannot drift in offered or displayed ambiguous completions; the hints can still drift from command registration and are not an authorization list.
Browser stop/reboot uses this same owner-adapter control path. Exact forced certificate rotation instead uses the typed queue union and immutable `dispatcher_actions` mask to hand off after drain/200 ms to the existing 12 KiB dispatcher, not the 4 KiB control stack. Pending input is discarded through execution and an executing slot remains reserved across self-detach. Canonical shared service/identity replacement preserves commit/stop/start failure semantics. Parsed other-account interactive add/password and forced role/delete are allowed, but browser self/generated/key/recovery and restricted network/SSH shell actions are not; typed Settings has separate permissions. Post-prompt currentness is operation admission, not an atomic session-liveness/NVS guarantee. [Browser policy and recovery](../web_administration.md#browser-shell-policy).
## Wi-Fi and persistence
`wifi_config` owns a fixed-width versioned NVS schema with four prioritized station profiles and AP policy `off`, `fallback`, or `always`. Missing configuration generates per-device defaults including a random AP password. Invalid stored data is generally left untouched while RAM defaults are used.
`wifi_manager` is a permanent task with one bounded command/event queue. ESP-IDF callbacks only copy compact events into the queue. The task owns association, DHCP deadlines, profile failover, AP policy, retries/backoff, next-profile requests, and the mDNS announcement lifecycle. `mdns_service` initializes the responder at most once after a validated STA `GOT_IP`; the managed component's own event handlers withdraw and restore the STA announcement across transient connectivity changes, while the project tracks whether announcement is currently expected. Initialization failure is latched rather than retried because partial upstream low-memory initialization is not safely recoverable; mDNS failure is nonfatal. It also reconciles against authoritative driver/netif state so dropped events do not permanently wedge policy. ESP-IDF Wi-Fi storage is RAM-only; the application blob is authoritative, and edits require explicit save. Edits to disabled station profiles are staged in RAM without restarting the radio; enabling/disabling a profile or changing enabled station/AP policy restarts it asynchronously. Start/stop—including local controls—intentionally update the RAM `enabled_at_boot` field. Working-configuration copies contain PSKs and must be securely wiped; routine status and the local UI use secret-free snapshots.
Persistent namespaces/blobs include:
- `serial/config`;
- `wifi_app/config`;
- `mdns_cfg/config`;
- `local_ui/config`;
- `web_sec/material`;
- `user_db/database`;
- `ssh_sec/material`.
Configuration modules generally choose RAM defaults without erasing incompatible storage. Security-material modules fail closed on malformed existing material and require explicit reset. OTA slots, coredump space, an NVS-key partition, and storage are reserved in `partitions.csv`; OTA, NVS encryption, coredump handling, and filesystem mounting are not implemented.
## Typed Display and Broker settings
`web_display_settings` queues IDs; `local_status_ui` owns a nonwrapping configuration generation and zero-wait writer reservation shared with CLI/legacy Apply. NVS runs outside critical sections. Save stabilizes RAM, Load preserves fallback behavior, Reset commits before RAM publication. Buttons/diagnostic holds change independent activity state, not config generation. Settings need an available UI task, not an attached OLED. [Display contract](../web_administration.md#serial-and-display).
`web_broker_settings` exposes compact zero-wait rows and confirmed writer assignment through one login-isolated slot. The broker atomically snapshots clients/writer/lease version and compares selected target/version inside the force-writer lock before effects. Three-bit slot/29-bit client generations retire rather than wrap; a separate saturated 32-bit lease generation advances before advisory event delivery and survives counter clear. Saturation blocks conditional assignment, not ordinary request/release/disconnect/recovery force. Contextual refresh never silently rebases explicit selections or clears sticky stale/absence latches; deliberate reselection is required. [Broker/context contracts](../web_administration.md#broker-and-contextual-controls).
## Local UI and hardware boundaries
`board_pins.h` centralizes project-assigned RS-232, diagnostic, RGB LED, and local-UI hardware resources; UART0 GPIOs remain local to `main.c`, and native USB uses platform wiring. `local_display` solely owns I2C0, the SSD1315-compatible OLED, its static framebuffer, and display mutex. Display frames belong to the initiating task. Dirty-page commits and I2C transactions are bounded.
When button GPIO initialization succeeds, `local_status_ui` starts a firmware-lifetime low-priority task that polls/debounces buttons, renders copied public snapshots, implements aging/wake behavior, and invokes a constrained set of public service APIs for local controls. It collects snapshots before opening a display frame, so service/broker locks are not held across I2C. It never parses CLI output, becomes a broker client, edits credentials, or assigns a writer; emergency action can only release the expected current writer.
The task can run with an absent OLED, and a fresh button press can request one bounded panel reprobe after successful I2C bus setup. Failed I2C bus creation is not recoverable through that path. The `display` configuration commands depend on the UI task. Long confirmation holds protect disruptive local actions, and stuck buttons are quarantined.
Hardware diagnostics are synchronous console commands. RS-232 tests own the physical port exclusively and restore safe GPIO state; OLED tests reuse the display service rather than taking independent I2C ownership.
## Concurrency and lifecycle constraints
- Broker, USB, web-transport, Wi-Fi, and SSH owner tasks are firmware-lifetime tasks; the local-UI task is also firmware-lifetime when button initialization allowed it to start. Stopping a service generally stops its runtime/listener, not the owner task.
- Bounded queues, stream buffers, work bursts, and drop counters are part of slow-client and watchdog isolation.
- Transport slot generations and account authentication generations solve different stale-reference problems; preserve both.
- Library/hardware ownership is centralized: serial task owns UART1 while running, display service owns I2C/framebuffer, the SSH owner task owns post-initialization wolfSSH runtime calls, and the console dispatcher owns `esp_console_run()`.
- Password authentication performs PBKDF2 outside the user-database mutex and revalidates afterward. Some password mutation paths currently derive verifiers while holding the mutation lock; do not generalize the authentication locking pattern without checking the exact path.
- Avoid holding service/database/broker locks across I2C, network sends, or other potentially long operations unless the existing contract explicitly requires it. Preserve the existing broker-before-serial lock order.
- Serial RX/TX stream payloads, broker per-client payloads, the transactional user-database candidate, and selected cryptographic allocations prefer PSRAM with internal fallback. The live user database, FreeRTOS control structures, UART driver buffers, and task stacks remain internal where deterministic/cache-disable access matters.
- Ping's 21-event payload (4,200 bytes) and the public user-console snapshot (2,156 bytes) are lazy PSRAM-only allocations retained for firmware lifetime, with no internal fallback. Queue control and synchronization stay internal; only ping or user status/list/show fails on allocation failure, never registration, mutations or UART0 recovery. Commands retain dispatcher/gate serialization; ping callbacks are task-context producers. The entire user snapshot is wiped after each display attempt. Never introduce ISR/cache-off access or free payloads while callbacks can retain them. Regression coverage: `tests/admin_console_boundary/psram_ping.py` and `accounts.py`.
- The build disables wolfSSL ESP32 AES/SHA acceleration, and the HTTPS path uses software AES for PSRAM-backed records. This preserves the validated workaround for uncoordinated mbedTLS/wolfSSL hardware-crypto locks and a prior mbedTLS external-RAM DMA watchdog stall.
## Legacy credential removal storage boundary
`user_database_init(load_result)` has no credential input. Missing storage is persisted empty; `user_database_recover_empty()` is the unavailable-only destructive recovery API. Valid v1 user bytes load without rewriting or account changes. The private `v1_admin_marker` retains its byte position and is derived from administrator count during mutations; it is not a public bootstrap state, new role or schema change. No user migration/bootstrap/synchronization API remains.
`web_security` owns TLS only. A private reader validates 1,392-byte v1 `web_sec/material`, copies exact key/certificate DER, fingerprint and generation into 1,340-byte v2, commits, then publishes. Temporary v1 credential-bearing input is wiped; no public legacy credential type/getter/rotation remains. Malformed/unknown records and read/validation/commit failures fail closed, with no fallback regeneration or overwrite of rejected records. Missing material may be generated; explicit reset replaces TLS only. Downgrade to v1-only firmware is incompatible. Logical NVS replacement is not secure flash erasure. Contracts/evidence: [legacy compatibility](../legacy_credential_removal.md).
+221
View File
@@ -0,0 +1,221 @@
# Code map
This is a semantic map, not a complete file inventory. Start here, then read the listed headers and only the implementation paths relevant to the task.
## Bootstrap and system composition
**Responsibility:** establish startup order, recovery behavior, configuration loading, service dependencies, and command registration.
- Files: `src/main.c`, `src/CMakeLists.txt`, root `CMakeLists.txt`, `platformio.ini`, `partitions.csv`, `src/idf_component.yml`; inspect targeted settings in `sdkconfig.defaults` when crypto, PSRAM, HTTPS/HTTPD, USB, or socket capacity matters
- Entry point: `app_main()`
- Called by: ESP-IDF runtime
- Dependencies: every subsystem initializer
- Lifecycle constraint: optional display/network failures should not remove UART0 administrative recovery or USB UART1 access; the custom administration frontend starts only after command registration.
## Crash/debug build policy
- Files: `src/security_build_policy.c`, registration in `src/CMakeLists.txt`, diagnostic flags in `sdkconfig.defaults`; tests: `tests/security_build_policy/run.py` (optional `--sdkconfig-header` checks the generated configuration).
- Compile-only guard: require no core dumps and silent panic reboot; reject panic/register output, panic/runtime GDB stubs and OCD-aware panic handling. No runtime allocation/task or physical JTAG restriction. Policy, operational profiles and target gates: [Phase 9 hardening](../security_hardening.md).
## Source-pinned dependency corrections (Phases 9C9D)
- Files: root `CMakeLists.txt` (after `project()`), `cmake/security_overrides.cmake`, `tools/security_overrides.py`; tests: `tests/sdk_security_overrides/run.py --build-dir .pio/build/esp32-s3-devkitc-1-n16r8`.
- Build input is the exact-hash original **plus checked-in edits**, not installed source alone. Generated copies replace nine target C sources plus one PUBLIC forced header without modifying SDK/managed components: HTTPS cleanup/private-key release, HTTPD scratch lifetime/null first read, ESP-TLS server-only protocol list, wolfSSH password bounds/payload wiping plus bounded IGNORE/service/string parsing, channel-window overflow rejection and ECC/Ed25519 label/exact-signature framing, DHCP option bounds (CVE-2026-45160), TLS 1.2 EMS error propagation (CVE-2026-50581), X.509 OID allocation failure (CVE-2026-34874), and five signed WS fixed-header size comparisons on IDF 5.5.3 (982 cases / 10 mutation checks against generated code). The mbedTLS entries explicitly select validated nested `mbedtls`/`mbedx509` targets, not the component wrapper. Original notices and compile properties retained; all outputs carry the 2026-09-15 baseline modification notice and wolfSSH outputs add the 2026-09-16 ordering/provenance notice; source/hash/target ambiguity fails configuration. Never hand-edit generated copies or silently repin.
- Xtensa crypto policy: root `CMakeLists.txt` sets `CURVE25519_SMALL`/`ED25519_SMALL` before component parsing; `cmake/wolf_crypto_policy.cmake` PUBLIC-propagates `cmake/wolf_crypto_policy.h` to wolfSSL consumers. PUBLIC `WOLFSSL_VALIDATE_ECC_IMPORT` and `WOLFSSL_ECDHX_SHARED_NOT_ZERO` enable existing P-256 import and X25519 all-zero-result checks. The resolved-settings guard requires these checks and both small implementations, rejects reviewed ECC validator-disabling/hardware-stub configurations, X25519 blinding and unreviewed Curve448/Ed448 enablement. Tests: `tests/wolf_crypto_policy/run.py` (strict actual production flags, real vendor crypto/ASN vectors and independently specified exact source deltas; candidate injection is not production evidence). [Key-validation review](../ssh_key_validation_review.md) records effective flags, caller/API limits and unmeasured validation cost. [Wolf review](../wolf_security_review.md) distinguishes implemented restricted ordering/crypto/parser mitigations from pending target gates and explicit dormant-profile exclusions; [IDF review](../idf_security_review.md) records three backports, finite six-finding applicability completion and first-page feature exclusions, not exhaustive advisory safety.
- Parser tests: `tests/wolfssh_parser_contract/run.py`, [scope and exclusions](../../tests/wolfssh_parser_contract/README.md): 3,258 base cases per each of two stack modes plus five channel profiles in both modes (2,737/profile/mode for TERM, TERM+SHELL, TERM+SHELL+AGENT; 2,735 for neither/SHELL-only); 11 base + 18 name/length + 2 application-gate mutations rejected. Guard pages/UBSan and crypto doubles test parsing/gating, not arithmetic. [Finite review](../ssh_parser_remaining_review.md) closes exact CHANNEL_FAILURE recipient, ssh-userauth service and nine channel-name dispatch checks; PR899 client skips remain unchanged behind role/ordering gates, forwarding disabled, generic caller trace dispositioned but APIs unpatched. Unknown/trailing behavior is retained; not exhaustive safety. Ordering has its separate suite below.
- Historical IDF 5.5.0 supplied parent `pio run` PASS: **94,340 B linked RAM / 1,768,901 B flash (+200 B versus 1,768,701 B)**. Final parent **all seven suites PASS**: ordering `--interop` (8,028 checks / seven rejected mutations / 12 exact-256-KiB sessions, clean channel close and transport EOF), SDK overrides `--build-dir .pio/build/esp32-s3-devkitc-1-n16r8`, auth (135), protocol, strict crypto, notices (30), and parser (3,258 × two modes plus channel profiles; 11 + 18 + 2 rejected mutations). Interop used unsandboxed approval only for local AF_UNIX sockets; no remote network/device operation. Review's misplaced EOF guard is corrected in `SendChannelEof` before lookup/serialization/state mutation; follow-up verification found no scoped blocker. Not target/runtime-reserve evidence.
- Restricted **CVE-2025-14942** ordering correction implemented: `tools/wolfssh_order/delta.json` supplies exact executable edits to `internal.c`, `ssh.c` and `internal.h`; [README](../../tools/wolfssh_order/README.md) records PR793/819/840/855/921 prerequisite disposition, and `provenance.json` pins archived patch hashes/commit IDs. Existing X25519/P-256 KEX only; independent SELF/PEER bits, expected-message/auth gates and exactly-once queued NEWKEYS under WANT_WRITE. **EXT_INFO intentionally disabled, no `server-sig-algs`; `extInfoSent` stays zero.** No full upstream backport or dependency upgrade. CMake propagates the generated ABI header BEFORE PUBLIC plus PUBLIC forced include with stale-header rejection; joined `-include/path` flags preserve ordering/crypto guards through PlatformIO sorting/deduplication.
- Ordering tests: [tests/wolfssh_order_contract](../../tests/wolfssh_order_contract/README.md), full generated C/real wolfCrypt, **8,028 checks / seven rejected mutations**; `pio_adapter.py` validates installed PlatformIO/SCons flags with a real Xtensa consumer. Initial interop failed a harness close race despite early PASS output; fixed harness awaits peer close and transport EOF and independently reaps the server via fd-passing proxy. Final agent `--interop --interop-repeat 3`: **36/36 sessions**, exact **256 KiB** each, **two or ten** key exchanges and clean client/server exits. [Remaining gates](../wolf_security_review.md#restricted-ordering-correction-and-remaining-gates): target cleanup during rekey, no-EXT_INFO client compatibility, resource/timing and whole-phase validation; no device operation or phase sign-off.
- [Finite dependency advisory snapshot](../dependency_advisory_coverage.md): all 22 IDF index entries across three pages plus named managed/browser channels accounted for; declared search complete, not exhaustive clearance. **Fix-bearing Wi-Fi vendor bundle integrated in the validated IDF 5.5.3 candidate; radio-hardware closure pending**; [Wi-Fi update plan](../wifi_security_update_plan.md) requires coherent vendor framework/toolchain/source/header/binary ABI bundles and override revalidation, not PMF/WPA3 weakening. Residual applicability questions and target gates remain.
- [Bounded Phase 9 runner](../../tools/validate_phase9.py), [usage/evidence](../phase9_validation.md), fixtures `tests/phase9_validation/run.py`: 23 default commands; build and OpenSSH interop are independent opt-ins. After the owning agent fixed the stale console-boundary anchor, final supplied parent `CCACHE_DISABLE=1 python3 -B tools/validate_phase9.py` **PASS 23/23** and orchestrator fixtures **PASS 10 tests**. That default run is historical. Current supplied parent explicit-candidate validation with `--interop --web-performance` **PASS 24/24**; [exact command and pre/post source equality](../phase9_validation.md#current-candidate-execution--2026-09-18). Fresh isolated `app-validated` build PASS: **95,552 B RAM / 1,749,493 B flash (+1,212 / 19,408 B)**. Default root build timed out at 200 seconds during installation before compilation, not a root build PASS. Root now pins platform 6.13.0 / IDF 5.5.3 / both toolchains 14.2.0+20251107; [integration](../idf_candidate_integration.md), [semantic rebase and resolved historical WS blockers](../idf_553_rebase_review.md). Version pins are not complete immutable dependency closure or phase acceptance.
- Policy/evidence/limits: [library review](../security_library_review.md), [Phase 9C](../security_hardening.md#9c-library-cleanup-and-protocol-policy). Source-contract tests must locate and verify actual generated compilation inputs, not assume original vendor paths.
## Offline release notice assembly
- [Procedure and release gates](../release_packaging.md), [tool](../../tools/release_notices.py), catalog `third_party/release-notices/inputs.json`, scope/TLSF provenance under `third_party/release-notices/`; tests: `tests/release_notices/run.py` (supplied agent 36 fixture tests PASS). 75 explicit hash/size-pinned inputs (nine IDF/toolchain notice entries semantically rebased for the candidate; the other 66 unchanged); no recursive collection, fetch, build, asset regeneration or device access; output must be fresh and outside input roots.
- Supplied agent evidence: two actual 75-input bundles verified deterministic, each **77 files / 4,433,930 bytes**; no reassembly here. [Exact retained SVG provenance](../icon_provenance.md) resolves official 7.4.47 sources at `9e04201d4557e729822fb57f62a316c3dea1d4a8` (Google USB, Simran Wi-Fi); manual bitmap derivation and distinct mockup Wi-Fi path remain unresolved. The catalog pins `docs/icon_provenance.md`, not this code map or the edited overview docs; coordinate changes to pinned evidence, never silently repin. Recipient delivery, corresponding source, legal/radio-blob basis and whole-phase target gates remain open. A notice manifest is not a source archive, complete SBOM or release clearance.
## Secure randomness
**Responsibility:** provide the sole project-owned, mutex-serialized application DRBG, seeded before Wi-Fi/radio use.
- Files: `src/secure_random.{h,c}`
- Interfaces: `secure_random_init()`, random-byte helpers, `secure_wipe()`
- Called by: HTTPS material, SSH keys, users, Wi-Fi defaults, tickets, the HTTPS authentication cache, and the wolfCrypt seed callback
- Constraint: initialization order is security-significant; the DRBG deliberately avoids post-radio reseeding and fails closed at its generation limit. Do not add independent weak RNGs or radio-dependent early entropy paths.
## Physical RS-232 and serial service
**Responsibility:** protect the MAX3243/UART resource, own UART1 while running, buffer binary RX/TX, apply serial configuration, and expose status/counters.
- Files: `src/rs232_port_owner.{h,c}`, `src/serial_service.{h,c}`, `src/serial_config.{h,c}`, `src/serial_console.{h,c}`
- Interfaces: owner claim/release/fault; serial init/start/stop/read/write/configuration/snapshots; versioned NVS load/save
- Normal data caller: `session_broker`; USB, WebSocket, role-`user` SSH, console, and local UI also call serial lifecycle/configuration APIs as appropriate
- Dependencies: ESP-IDF UART driver, `board_pins.h`, NVS
- Ownership: the cooperative owner arbitrates active diagnostics (`PHASE0`) against the service (`SERVICE`); boot-time static-safe GPIO initialization and service-owned static-mode restoration are explicit exceptions. Unsafe cleanup marks `FAULT` until reboot.
- Lifecycle: stop/reconfiguration discards serial-service RX/TX and task-local pending bytes, but leaves broker clients, writer ownership, events, and already-fanned output intact. The 16 KiB RX and 8 KiB TX payloads prefer PSRAM; their FreeRTOS controls and UART driver storage remain internal.
## Session broker
**Responsibility:** mediate all transport access to the serial service; provide one writer lease and multiple isolated observers.
- Files: `src/session_broker.{h,c}`, `src/session_console.{h,c}`
- Interfaces: connect/disconnect, request/release/force writer, nonblocking read/write/event APIs, snapshots and counters; `session_broker_get_management_snapshot()` and `session_broker_assign_writer_current()` atomically project/compare target and lease generation. Exhausted 29-bit client generations retire; saturated lease generation preserves ordinary recovery. Tests: `tests/session_broker_diagnostics/run.py`.
- Called by: USB, web serial, role-`user` SSH, console tests, local UI snapshots/actions
- Dependencies: `serial_service`
- Data path: `transport -> broker -> serial service -> UART1`; reverse data is fanned out per client.
- Ownership: client IDs are slot/generation-safe; events are advisory and can drop, so use snapshots as authority.
- Lifecycle: one permanent task and eight preallocated client slots; slow output drops only for the affected client.
- Diagnostics: `broker counters` adds active-client ID/type/pending/HWM/UART/queued/read/dropped rows; clear seeds HWM from pending, disconnect removes rows but retains global discard accounting. `tests/session_broker_diagnostics/run.py`; capture before disconnect, never use consuming `broker read` as a probe. Semantics/recipe: `docs/web_throughput_diagnostics.md`.
## Native USB CDC
**Responsibility:** adapt TinyUSB CDC host state/data to one broker client.
- Files: `src/usb_cdc_transport.{h,c}`, `src/usb_console.{h,c}`
- Interfaces: `usb_cdc_transport_init()`, snapshots/counters, queued writer request/release
- Called by: startup, TinyUSB callbacks, console/local UI
- Dependencies: TinyUSB, broker, serial service
- Flow: `USB host <-> USB task <-> broker`
- Lifecycle: permanent owner task; broker client exists only while attached with host DTR asserted.
- Constraint: callbacks retain the latest host line coding only for diagnostics; it never reconfigures UART1. UART1 framing and speed remain controlled by the serial configuration and its explicit persistence commands.
## Web and WebSocket serial
**Responsibility:** serve authenticated HTTPS UI/API, issue WebSocket tickets, and adapt browser serial sessions to broker clients.
- Files: `src/web_server.{h,c}`, `src/web_serial_transport.{h,c}`, `src/web_ui.{h,c}`, `src/web_console.{h,c}`
- Ordinary HTTPS idle cleanup: `src/web_httpd_idle.{c,h}`, owner sweep in `web_httpd_adapter.{c,h}`, lifecycle/TLS composition in `web_server.c`; `tests/web_httpd_idle/run.py`. Independent of diagnostics/optional transports: 15-second observed idle, one-second timer/one queued probe, six rows, actual WS/async/pending exemptions, safe current-owner shutdown and stop/restart fencing. No LRU/socket/timeout/stack increase. SDK queue/owner-delay and regression contract: `docs/https_idle_cleanup.md`.
- Independent throughput diagnostics: `web_serial_transport.{c,h}` owns two fixed per-slot binary-TX aggregates and epoch fences; `web_console.c` exposes default-disabled `web performance enable|disable|show|clear`. Queue-entry/callback-entry, synchronous-send and completion/drain-return estimates, not peer receipt or scheduler-only latency. `tests/web_serial_performance/run.py`; resource/evidence limits and UART0 paired capture: `docs/web_throughput_diagnostics.md`.
- Storage compatibility: `user_database` persists missing storage empty and preserves valid v1 user bytes; private derived `v1_admin_marker`, no public bootstrap/migration/sync APIs. `web_security` privately migrates v1 1392-byte material to TLS-only v2 1340-byte material, exact identity/generation retained, commit before publish, fail closed without fallback overwrite. Credential commands removed; user generated passwords and TLS rotation remain. Contracts, downgrade and evidence limits: `docs/legacy_credential_removal.md`.
- Security files: `src/web_security.{h,c}`, `src/web_cookie_auth.{h,c}`, `src/web_session_store.{h,c}`, `src/web_auth_parse.{h,c}`. Private IDF boundary: `src/web_httpd_adapter.{h,c}`.
- Phase 9C web login: non-consuming early quota/epoch probe before body receive, authoritative reservation after parse; raw JSON wiped before KDF, credentials before error send. Existing verification-count/window/service-restart semantics retained. `tests/web_cookie_auth/run.py --admission` and domain regressions.
- HTTP policy/UI: `web_cookie_auth` + `web_auth_parse` enforce bounded cookie/Origin/CSRF/admin admission; `web_login_ui.{c,h}` serves login, `web_ui.c` owns session-fenced Serial/Admin/Settings and shared quick controllers. Tests: `tests/web_cookie_auth/run.py` (domain variants), `tests/web_auth_parse/run.py`, `tests/web_login_ui/run.py`, `tests/web_ui_session/run.py`.
- Admission diagnostics: `web_diagnostics.{c,h}`, `tests/web_diagnostics/run.py`; six post-TLS records/32-event opt-in ring, no HTTPD off-owner inspection. [Contract](../web_admission_diagnostics.md).
- Identity/lifecycle: `web_server_replace_identity()` + `web_security` reserve service before identity; commit before reserved stop/start, no rollback after commit. `web_lifecycle_settings.{c,h}` owns original-login ID/ACK handoff. Tests: `tests/web_security/run.py`, `tests/web_admin_transport/server_lifecycle.py`.
- Asset files: authored/generated boundary in `src/web_assets_data.{h,c}`, `web_assets/SOURCES.md`, `web_assets/generate_embedded_assets.py`
- Interfaces: web init/start/stop/snapshots; HTTP handlers; ticket mint/consume; attach/detach; targeted session revocation
- Called by: startup, ESP-IDF HTTPS server, user administration revocation, console/local UI
- Dependencies: user database, secure random, broker, successful Wi-Fi manager initialization at boot, mbedTLS/HTTPS server; actual network reachability is an operational prerequisite, not an initializer invariant
- Flow: `browser -> HTTPS login/cookie session -> CSRF-protected ticket -> cookie/Origin/ticket admission -> WebSocket -> web transport -> broker`
- Ownership: HTTPD owns socket send/close work; transport task owns broker mediation; two fixed WebSocket slots and four outstanding tickets.
- Security constraints: Basic/cache removed; four absolute one-hour cookie sessions revalidate principal currentness. Four pre-login challenges (120 s), five credential attempts/60 s globally, no live session/challenge/ticket eviction. Origin/CSRF required for mutations; Origin/cookie/ticket before upgrade. Disconnect pauses reconnect but retains login; Sign out invalidates its session. Authored loader changes must update their hard-coded CSP hashes atomically.
- Session-store boundary: admitted HTTPS start initializes records; auth-init failure gates HTTPS. Failed start/accepted stop disables and wipes state. Tickets/slots require nonzero non-reused session IDs; session/account/global revocation invalidates store records before socket cleanup. RNG/SHA/database calls run outside short portMUX sections; ID/expiry/epoch checks reject stale work. Run `python3 tests/web_session_store/run.py` and its `--serial` integration mode.
- Asset constraint: `web_assets_data.c` is checked-in generated input to the build; do not hand-edit or regenerate casually.
### Browser admin backend
- Files: `src/web_admin_transport.{c,h}`, `src/web_admin_tickets.{c,h}`, protected registration/lifecycle in `web_server.c`, revocation through `web_serial_transport_revoke_*`, diagnostics in `web_console.c`.
- Routes: CSRF-protected admin-only `POST /api/admin/ws-ticket`; ordinary `GET /ws/admin` with cookie/Origin/ticket/shared-console admission before explicit 101. Admin UI entry is explicit; no admin broker client. One socket, two tickets, existing two shared console slots; six total HTTPD sockets, LRU disabled; current overall capacity is 39 URI handlers.
- Currentness/policy: `admin_ssh_console_open_available()` shares two slots with runtime SSH; transport-qualified tokens and owner adapters revalidate outside console locks before commands/prompts. Parsed browser policy remains narrower than typed Settings; [shell contract](../web_administration.md#browser-shell-policy). Tests: `tests/admin_console_boundary/{run,accounts,lifecycle}.py`, `tests/admin_ssh_policy/run.py`, `tests/web_admin_transport/run.py --tickets`, `tests/web_cookie_auth/run.py --admin`.
- Ownership: 20 ms ESP timer queues at most one HTTPD poll, no new task; HTTPD owns 1,552 B PSRAM-only payload and IO. Closure uses HTTPD-owned `shutdown`, not IDF's reusable-pointer queued close. Detach fences submitters; only successful HTTPD stop retires queued state before restart. Session/principal currentness and generation checks protect all sensitive boundaries.
## Typed settings source and regression map
HTTPD reads zero-wait projections and queues only IDs to the existing dispatcher. One original-login slot per domain; canonical owners compare/reserve at execution. [API/lifetime and failure contracts](../web_administration.md#typed-settings-api-and-operation-lifetime).
| Domain | API / canonical owner | Focused source tests |
|---|---|---|
| Serial | `web_serial_settings.{c,h}` / `serial_service` | `tests/web_cookie_auth/run.py --serial-settings`, `tests/admin_console_boundary/run.py` |
| Accounts / keys | `web_account_settings.{c,h}` / `user_database` | `tests/web_cookie_auth/run.py --accounts`, `tests/admin_console_boundary/accounts.py` |
| Network | `web_network_settings.{c,h}` / `wifi_manager`, `mdns_service` | `tests/web_cookie_auth/run.py --network`, `tests/web_network_settings/run.py` |
| Display | `web_display_settings.{c,h}` / `local_status_ui` | `tests/web_cookie_auth/run.py --display` |
| Broker | `web_broker_settings.{c,h}` / `session_broker` | `tests/web_cookie_auth/run.py --broker`, `tests/session_broker_diagnostics/run.py` |
| SSH | `web_ssh_settings.{c,h}` / `ssh_transport`, `ssh_security` | `tests/web_cookie_auth/run.py --ssh`, `tests/ssh_management/run.py`, `tests/ssh_management/security.py` |
| HTTPS / reboot | `web_lifecycle_settings.{c,h}` / `web_server`, `web_security` | `tests/web_cookie_auth/run.py --lifecycle`, `tests/web_admin_transport/server_lifecycle.py` |
Shared UI regression: `tests/web_ui_session/run.py` and its domain `.cjs` fixtures / `layout.py`. These are navigation pointers, not claims of test execution.
## SSH
**Responsibility:** authenticate SSH, route users to serial and administrators to the command dispatcher, and own wolfSSH lifecycle.
- Files: `src/ssh_transport.{h,c}`, `src/ssh_auth_policy.{h,c}`, `src/ssh_memory.{h,c}`, `src/ssh_protocol_policy.{h,c}`, `src/ssh_security.{h,c}`, `src/ssh_console.{h,c}`
- Phase 9C: global wolfSSL hooks securely retire unpoisoned IDF5.5 usable extents (no header; shrink retains capacity, grow can need both blocks). Five checked static-lifetime algorithm setters before context publication. Tests: `tests/ssh_memory/run.py` (optional `--idf-path` extent audit), `tests/ssh_protocol_policy/run.py` (generated feature/KEXINIT/context failure checks).
- Phase 9B admission: three owner-only boot-lifetime token buckets (handshakes, password/signed-key requests, unsigned probes); no restart/counter-clear reset. Explicit keyboard rejection, pending-result marker and version/feature guard preserve reviewed callback order. Consumed admin RX/accepted TX and retired slots are wiped. Tests: `tests/ssh_auth_policy/run.py`, `tests/ssh_auth_transport/run.py`, `tests/wolfssh_auth_contract/run.py` (requires installed vendor source and production compile database). [Policy/counters/limits](../security_hardening.md#9b-ssh-admission-and-credential-handling).
- Interfaces: init/start/stop, session snapshots/disconnect/revocation, host-key replacement, counters; `ssh_transport_get_management_snapshot()` / `ssh_transport_manage_current()` fence lifecycle and exact session admission. `ssh_transport_replace_identity()` reserves service before task-bound security identity across stop/commit/restart, retains context until all slots retire and rejects orphan starts. Tests: `tests/ssh_management/run.py`, `tests/ssh_management/security.py`, `tests/ssh_management/runtime.py`.
- Called by: startup, network clients, user revocation, console/local UI
- Dependencies: user database, broker, admin SSH console, secure random, wolfSSH/wolfSSL; boot start gate requires Wi-Fi and SSH security/runtime readiness, independently of HTTPS identity readiness (verified in `main.c` after accepted legacy cleanup).
- Flow: role `user` -> broker; role `admin` -> `admin_ssh_console`
- Ownership: after caller-side library initialization, one task pinned to core 1 owns runtime wolfSSH contexts/sessions; two fixed generation-tagged slots.
- Security constraint: an interactive shell request is required; exec and subsystems are rejected, and no project file-transfer or forwarding route exists. PTY is not explicitly required.
## Users, authentication, and authorization
**Responsibility:** persist bounded accounts, verify passwords/SSH keys, issue secret-free principals, and enforce account invariants.
- Files: `src/user_database.{h,c}`, `src/user_console.{h,c}`; `src/admin_command_gate.{h,c}` is currently a narrow recursive wrapper used only by the `user` command handler, not the global command serializer
- Interfaces: credential-independent init/empty recovery, authenticate, principal-currentness, account/password/role/key mutations, snapshots
- Called by: web and SSH authentication/currentness checks and console administration
- Dependencies: NVS, secure random, mbedTLS cryptography; after a committed command-layer mutation, best-effort web/SSH revocation calls supplement authoritative transport currentness checks
- Ownership: database mutex protects the internal live record and PSRAM-preferred transactional candidate; password authentication runs PBKDF2 outside the mutex and revalidates afterward, while mutation locking must be checked per operation.
- Authorization: UART0 establishes the first administrator through normal `user add` and exclusively owns unavailable-database recovery to empty (healthy database refused); current admins may use admin SSH for other commands unless handler policy denies them. HTTPS serial/status permits both roles; administration requires `admin`.
- Constraint: final administrator cannot be deleted or demoted; transport principals must be rechecked after mutations.
## Administration console infrastructure
**Responsibility:** provide one canonical command registry and serialized execution for UART0, admin SSH and browser admin.
- Files: `src/admin_ssh_console.{h,c}`, `src/console_input.{h,c}`, `src/console_completion.{h,c}`, `src/system_console.{h,c}`, `src/network_console.{h,c}` and all `*_console.{h,c}` modules
- Entry points: `admin_ssh_console_init()`, `admin_ssh_console_start_uart_frontend()`, command registration functions
- Called by: startup, UART0 frontend, role-`admin` SSH transport, browser admin transport
- Dependencies: ESP-IDF console/linenoise, all command handlers, user-principal currentness
- Flow: `UART0/admin SSH/browser admin -> bounded request queue -> one dispatcher -> esp_console_run()`
- Ownership: dispatcher is sole `esp_console_run()` caller; the SSH owner exclusively performs post-initialization wolfSSH runtime calls.
- Lifecycle: remote session tokens include slot generation; fixed output/history/prompt state is wiped immediately on idle close or after an executing handler returns. Admin SSH `exit` and Ctrl+D on an empty command line request bounded deferred self-disconnect after best-effort output draining.
- Hidden input: UART0 and shared remote prompts reject overflow/unsupported bytes on submit with wiped output, sticky across edits; visible editing is unchanged. Tests: `tests/hidden_input/run.py` plus console boundary regressions.
- Constraint: one slow command or prompt serializes all administration. Admin SSH is unavailable until command registration and UART frontend creation complete; supported deferred actions wait only for a bounded application-buffer drain heuristic.
## Wi-Fi
**Responsibility:** persist station/AP policy and own asynchronous ESP-NETIF/Wi-Fi state transitions.
- Files: `src/wifi_config.{h,c}`, `src/wifi_manager.{h,c}`, `src/wifi_console.{h,c}`, `src/mdns_config.{h,c}`, `src/mdns_service.{h,c}`, `src/mdns_console.{h,c}`, `src/network_console.{h,c}`
- Interfaces: config defaults/validate/load/save; manager init/start/stop/apply/reconnect/next-profile/snapshot
- Dependencies: secure random for default AP password, NVS, ESP-NETIF/Wi-Fi/events, Espressif mDNS, lwIP diagnostics
- Lifecycle: permanent manager task and bounded queue; callbacks enqueue compact events only.
- Constraint: application NVS is authoritative (`WIFI_STORAGE_RAM`); working edits are not persisted until save. Start/stop, including local controls, intentionally update the RAM `enabled_at_boot` field. Working-config copies contain PSKs and must be tightly scoped and wiped; routine status/local UI must use secret-free snapshots.
## Local display and controls
**Responsibility:** own OLED I2C/framebuffer operations and present status plus constrained button actions.
- Files: `src/local_display.{h,c}`, `src/local_status_ui.{h,c}`, `src/local_boot_animation.{h,c}`, `src/local_ui_config.{h,c}`, `src/local_ui_console.{h,c}`
- Interfaces: display init/frame/draw/commit/snapshot; UI start/activity/config; generation-checked settings projection/update and explicit persistence reservation; versioned NVS settings
- Called by: startup, local UI task, diagnostics, display console
- Dependencies: copied snapshots/public APIs from serial, broker, USB, Wi-Fi, web, SSH
- Ownership: `local_display` solely owns I2C0 and framebuffer mutex; a frame belongs to its initiating task.
- Lifecycle: the low-priority task is firmware-lifetime only if button GPIO initialization succeeds; it still runs with an absent panel so a press can reprobe after successful I2C bus setup. Failed bus creation is not recoverable by that reprobe, and `display` configuration commands depend on the UI task.
- Constraint: collect service snapshots before I2C; local UI never joins broker or handles secrets. All configuration writers honor the UI owner's zero-wait reservation; NVS runs outside timing critical sections. Reset commits defaults before RAM publication, including CLI; buttons/diagnostic holds update activity, not configuration generation.
## Hardware and diagnostics
**Responsibility:** centralize board wiring and provide bounded electrical tests with safe cleanup.
- Files: `src/board_pins.h`, `src/rs232_hw_test.{h,c}`, `src/local_ui_hw_test.{h,c}`, `src/status_led.{h,c}`
- Documentation: `docs/wiring.md`, `docs/electrical_tests.md`
- Called by: startup and `debug` commands
- Dependencies: physical RS-232 owner, serial/display services, ESP-IDF GPIO/UART/I2C/LED drivers
- Ownership: RS-232 diagnostics refuse to run while the service owns the port; display diagnostics reuse `local_display`.
- Constraint: wiring and voltage assumptions are safety-relevant; verify target hardware before running diagnostics. RGB LED initialization is currently boot-fatal, and its colors report diagnostic state rather than aggregate firmware health.
## Where should I look?
| Task | Start here |
|---|---|
| Change boot order or failure behavior | `src/main.c`, then affected subsystem `init/start` contracts |
| Change serial framing, flow control, or persistence | `serial_config.*`, `serial_service.*`, `serial_console.*` |
| Change writer/observer policy | `session_broker.*`, then all three transports |
| Debug missing or duplicated serial bytes | `serial_service.c` -> `session_broker.c` -> relevant transport task |
| Change USB open/DTR or line coding | `usb_cdc_transport.*` |
| Change browser terminal protocol | `web_serial_transport.*`, `web_ui.c`, `web_server.c` |
| Change HTTPS endpoints/authentication | `web_server.*`, `web_security.*`, `user_database.*` |
| Change SSH login or role routing | `ssh_transport.*`, `ssh_security.*`, `user_database.*` |
| Add or change a command | relevant `*_console.c`, `console_completion.c`, `admin_ssh_console.c` policy/deferred handling |
| Change account roles/passwords/keys | `user_database.*`, `user_console.c`, transport revocation APIs |
| Change Wi-Fi policy or profile persistence | `wifi_manager.*`, `wifi_config.*`, `wifi_console.c` |
| Change station mDNS hostname or persistence | `mdns_service.*`, `mdns_config.*`, `mdns_console.c`, then `wifi_manager.c` |
| Change OLED rendering or buttons | `local_status_ui.c`, `local_display.*`, `local_ui_config.*` |
| Change board GPIO or electrical tests | `board_pins.h`, hardware test module, `docs/wiring.md` |
| Change embedded browser assets | `web_assets/SOURCES.md`, generator, then generated data only as an explicit regeneration task |
| Investigate memory/watchdog regressions | broker/web/SSH bounded loops, allocation placement, root `CMakeLists.txt`, relevant roadmap Phase 6 history |
+126
View File
@@ -0,0 +1,126 @@
# Current project state
Working memory, not an implementation timeline. Source is authoritative; begin with [code map](code-map.md), then [architecture](architecture.md) and [decisions](design-decisions.md).
## Phase 9D continuation — IDF 5.5.3 integration — 2026-09-18
- Initial working tree already contained platform6.13/framework3.50503/toolchains14.2.0+20251107 migration, exact version guards/hash rebases and new httpd_ws override; preserved/audited rather than overwrote. Complete official packages archived/verified under .pio/idf-candidate-5.5.3; all WiFi/PHY/coex/supplicant trees match pinned package. PMF/WPA3 unchanged. Vendor radio correction integrated in candidate, not hardware exploit/closure proof.
- Existing eightC+header corrections all retained after semantic audit; new ninth C override corrects five WS signed-receive/unsigned-size comparisons introduced upstream. Dedicated982guard/canary cases plus fivecompile+fivebehavior mutations PASS. HTTPD private layout/owner and heap extent contracts re-audited5.5.3; no weakening guards. Root dependencies.lock updated only IDF5.5.0→5.5.3 to match actual resolver result; six managed dependencies unchanged.
- Default root pio run timed out200s during sharedpackage installation before compilation; no normalrootbuildPASS claim/retry. Separate fresh app-validated stage uses complete verified archives and isolatedcore. Agent buildPASS50.51s **95,552 B linked RAM / 1,749,493 B flash** (+1,212RAM/19,408flash vs old). Staging fresh-only explicitdestination avoids prior app overwrite; manifest includes transformedconfig hashes and records sole resolver lock change. All ninegeneratedC+PUBLICheader actualregistration verified; WS vendororiginal absent.
- Final parent tools/validate_phase9.py with --build-dir .pio/idf-candidate-5.5.3/app-validated/.pio/build/esp32-s3-devkitc-1-n16r8 --idf-path .pio/idf-candidate-5.5.3/core/packages/framework-espidf --platformio-core-dir .pio/idf-candidate-5.5.3/core --interop --web-performance **24/24PASS**. Pre/post3237sourceinputs equal hash3a1af78c15cfdd02da1055a8957b4086f9018862b7aa1c7c52fd2401a1a0a031. Earlier5webcookie failures were stale5.5.0 fixture updated5.5.3; allpassnow. Parent helper5/runner16fixturesPASS. Independent recheck noactionableblocker, reran WS/performance/runner, verified archive/linkpaths/sourceequality/rootlock. No device validation.
- Notice catalog semanticallyrebased9entries, other66unchanged;75inputs36testsPASS twoactualbundles77files4433930bytes. Evidence/docs updated with candidatenotrootbuild distinction and historical baselines. No full environmentclosure or legalclearance claim.
- **Next:** normal package installation/build completion remains unverified after timeout; ask user before retrying longer. Isolated source/currentconfig technically validated; wholePhase9 radio/resource/recovery/noEXTclient/abuse/operations targetgates stillpending, release source/notice/legal obligations open. Candidate5.5.3 is newest available official PlatformIO5.5 package verified, not latest upstream maintenance or alladvisoriesclosed. No upload/erase/assets/secureboot/encryptedNVS changes or commits.
## Phase 9D continuation — broader snapshot / reproducible validation — 2026-09-16
- Initial Git clean. `docs/dependency_advisory_coverage.md` completes finite dated search of all22official IDF advisories/3pages plus specified managed/browser channels. **New current-profile blocker:** PMF-capable mixed WPA2/WPA3 SoftAP matches vendor management-frame memory-corruption path; installed7S3WiFi archives match original5.5. No exploit demonstrated. `docs/wifi_security_update_plan.md` verifies fix/release bundle differences and both callback uint8_t*→size_t* ABI changes. Verified reference IDF5.5.3 commit2c211b236707889e8400c4dc5644dd5c4ee071e0 contains fix; not deployment approval or automatic recommendation over newer releases. Do not C-only patch/swap one archive/disable PMF as guessed mitigation. Next coherent framework/toolchain/source/header/radio update evaluation with audited override rebase; PHY/coexistence/privateABI compatibility unresolved. Direct SDK AES-DMA/PSRAM applicability remains explicit review gap.
- `tools/validate_phase9.py` fixed23command host plan, optional --build/--interop, strict existing build inputs, timeouts/process cleanup, no installs/device commands/permanent log captures. New10fixture tests. Actual run revealed stale admin_console_boundary extraction ending at removed ssh_malloc; replaced with reviewed consume_external_close endpoint and eight unique ordered markers, all existing assertions retained.
- **Final parent default validation23/23PASS and orchestrator fixtures10PASS.** Default intentionally skips build/interop; no firmware rebuild or new device/interoperability claim this slice. Prior firmware94340RAM1768901flash remains historical. Additional boundary accounts/lifecycle/psram suites passed agent. Run full opt-ins only deliberately with prerequisites.
- Exact retained USB/WiFi SVGs verified byte-identical official@mdi/svg7.4.47 commit9e04201d4557e729822fb57f62a316c3dea1d4a8; archive source/license/metadata/tree hashes in third_party/material-design-icons/upstream-7.4.47 and docs/icon_provenance.md. USB Google/WiFi Simran; fullApache text present. Mockup WiFi differs and firmware bitmap manual derivation not mechanically proven. Notice catalog75inputs preserving oldinputs except editedscopeREADME pins,36testsPASS; two actual agent bundles77files4433930bytes deterministic. No assets regenerated.
- Globaldocs/code map reflect fresh blocker, finite review boundaries and final parent results. Remaining release/source/radiolegal/wolf packaging/bitmap preferred-source delivery questions not cleared. Whole-phase hardware still deferred; secureboot/encryptedNVS excluded. No upgrades/device operations/commits. Continue concrete WiFi correction evaluation, not repeat completed finite snapshots.
## Phase 9D continuation — deferred applicability / notice tooling — 2026-09-16
- Initial Git clean. `tools/security_overrides.py` now requires exact ssh-userauth service, exact bounded CHANNEL_FAILURE recipient with existing fatal policy, and length-first exact names for all nine channel requests. Supported bodies and unknown-request ACK/consumption retained. No ordering/crypto/version changes. `docs/ssh_parser_remaining_review.md` closes finite PR899/902/918/919 and generic current signature caller trace: client key-skip functions remain unpatched but blocked by current server ordering; forwarding absent; no current short-digest/OID trigger found. Not exhaustive parser certification.
- `docs/idf_security_review.md` adds six named advisory dispositions with original/generated/config evidence: ECDH callers sized safely, driver-only PK path excluded, no untrusted CA promotion, privileged-local ECC sidechannel excluded not fixed, server tickets off despite compiled support, fixed CN avoids ASN zero-length replacement. No additional current-path source fix established; generic library defects remain explicitly recorded.
- `tools/release_notices.py` + `third_party/release-notices/inputs.json` assemble62 exact hash-pinned allowlisted notice inputs offline into fresh explicit output, descriptor no-follow traversal, bounded preflight, exclusive creates/no overwrite, deterministic names/bytes. No secret scanning/full repo/config/build collection. Tests30PASS; agent+independent reviewer verified two actual deterministic bundles and hashes. Historical64files541147bytes not general future promise. `docs/release_packaging.md` separates notices from source/recipient/legal obligations. No distribution clearance: radio source exception question, wolf package discrepancy, exact icon provenance and recipient delivery remain open.
- Parent `pio run` PASS **94,340 B linked RAM / 1,768,901 B flash** (+200flash). Parent seven suites PASS: parser3,258x2 plus channel production2,737x2 and fouralternate profiles, 11parser+18name+2appgate mutations; release notices30; auth135; protocol; strict crypto; SDK actual8C+header registration; ordering8,028/7mutations and12OpenSSH sessions each256KiB exact with rekey/cleancloseEOF. Independent review no actionable scoped defects, reran parser/notices and actual bundle determinism. Host evidence not hardware/resource/signoff.
- README/roadmap/hardening/wolf/license/code map integrated latest evidence and finite closure. **Next:** use hardeningdoc remaining implementation/maintenance, release/source/delivery and whole-phase target gates rather than repeatedly reopening completed finite reviews. Broader advisory coverage/unpatched unused primitives not certified; release packaging does not solve legal/source/provenance questions. User whole-phase validation remains deferred; secureboot/encryptedNVS excluded. No device/asset regeneration/dependency upgrade/commit.
## Phase 9D continuation — restricted SSH ordering correction — 2026-09-16
- Initial Git status clean. Implemented restricted-profile CVE-2025-14942 correction without upgrading managed pins. `tools/wolfssh_order/` archives exact PR793/819/840/855/921 bytes, hashes/commits, authoritative consolidated delta and scope. Generator now replaces eight C sources plus one internal header. PUBLIC forced overlay and stale-header marker preserve ABI across all consumers; joined `-include/path` avoids PlatformIO argument sorting/dedup failure.
- Independent SELF/PEER keying bits, exact expected-message tracking, wrong-role/preauth/repeated-message rejection, nonblocking NEWKEYS continuation and EOF/window/exit send fences. Only current Curve25519/P256 KEX supported. Existing auth/password/parser/crypto fixes retained. **EXT_INFO deliberately disabled** in advertise/send/receive paths to eliminate skipped continuation: no server-sig-algs on wire. Tested Ed25519/P256/password OpenSSH combinations work; no RSA or broad-client compatibility claim. This is not wholesale upstream backport or unrestricted CVE closure.
- Review caught misplaced EOF guard (on exit-status); corrected real SendChannelEof and retained explicit CHANNEL_REQUEST exit guard. Added actual shutdown/pending-buffer/stale-WANT_WRITE tests, zero output/state mutation during keying. Independent recheck found no remaining scoped blockers. Initial build flag integration failure and obsolete constant warning fixed; no guards weakened.
- Parent `pio run` PASS **94,340 B linked RAM / 1,768,701 B flash** (248 B vs prior slice). Final parent six suites PASS: ordering `--interop` (8,028 checks, seven rejected mutations, 12 sessions each exact256KiB with completed rekey/channel close/transportEOF), SDK actual build registration, auth135, protocol, strict crypto and parser3,124x2. Agent also passed36 consecutive interop sessions. Real generated wolfSSH/wolfCrypt tested with both KEX and three rekey directions; production authentication/broker integration and target timing still separate gates.
- Initial parent interop exposed harness early exit/false-early PASS before peer channel close; corrected harness independently owns server over AF_UNIX fd-passing, waits channel closure/EOF and requires both exit0 plus exact binary data. Final parent AF_UNIX test needed explicit unsandboxed approval; no remote network or device operation. Remaining suites sandboxed.
- Updated review/hardening/roadmap/license/code map with effective restricted scope and evidence. **Next:** finish remaining advisory/parser applicability and release notice/source obligations, then whole-Phase9 target validation including cleanup during rekey, no-EXT client compatibility and validation CPU/heap/stack costs. Secure boot/encrypted NVS excluded; no device operations/assets/version upgrades/commits. Phase9 remains in progress, not production sign-off.
## Phase 9D continuation — SSH parser / key validation — 2026-09-15
- Initial Git status clean; previous 9D work already retained. Current slice keeps managed pins and seven-source override mechanism unchanged. `tools/security_overrides.py` now bounds IGNORE/service/helper parsing, rejects window-add overflow, fixes ECC/Ed25519 label predicates, and enforces ECC nested r/s plus outer signature exact consumption and Ed25519 exact signature-field consumption. Password wipe/async and state ordering unchanged.
- `cmake/wolf_crypto_policy.*` PUBLIC-propagates `WOLFSSL_VALIDATE_ECC_IMPORT` and `WOLFSSL_ECDHX_SHARED_NOT_ZERO`, with fail-closed resolved guards. Verified prior P256 peer point reaches scalar multiplication without equivalent validation; nontrivial low-order X25519 inputs bypassed old precheck. Real vendor tests now reject these inputs. Evidence in `docs/ssh_key_validation_review.md`; generic digest/OID API hardening remains separate, no current short-digest trigger found in inspected callers.
- Parent `pio run` PASS **94,340 B linked RAM / 1,768,949 B flash** (+1,732 flash vs prior9D). Strict crypto suite initially rejected concurrent parser changes; corrected independent exact-delta expectations, not weakened provenance. Final parent five suites PASS: `wolf_crypto_policy`, `wolfssh_parser_contract` (3,124 cases in each of two stack modes, six guard-removal mutations), `wolfssh_auth_contract`135cases, `ssh_protocol_policy`, `sdk_security_overrides --build-dir .pio/build/esp32-s3-devkitc-1-n16r8`. Independent review no scoped blockers; strict crypto/parser suites rerun PASS. Real vendor arithmetic tests and parser doubles remain separate, not live SSH transactions.
- **Ordering CVE-2025-14942 still unresolved.** Official registry queries returned404 for wolfSSH1.5.0/wolfSSL5.9.2; upstream releases exist, so a full upgrade requires deliberate pinned component integration. Temporary-only PR793/819/840/855/921 backport evaluation found manual context adaptation plus unresolved SendNewKeys WANT_WRITE / skipped SendExtInfo continuation and extInfoSent rekey semantics. No partial ordering/header-layout patch installed. Next choose coherent tested nonblocking source+header backport or upstream component integration; preserve all local auth/wiping/parser contracts. Full provenance/rekey/negative-order tests required. Details and official links in wolf review.
- Other remaining work: deferred parser/API applicability, release notices/source obligations, and whole-phase hardware validation. Review recommends a valid-but-inconsistent private/public ECC fixture and parser-to-real-crypto integration gate. No hardware/latency/resource/handshake claims, no device operations/assets/upgrades/secure-boot/encrypted-NVS changes. Do not mark Phase9 complete or require intermediate hardware signoff.
## Phase 9D — advisory mitigation / operational review — 2026-09-15
- Work in progress; user validates Phase 9 as a whole. Secure boot/encrypted NVS excluded. No device operations or dependency upgrades.
- New `security_operations.md`, `dependency_licenses.md`, `wolf_security_review.md`, and `idf_security_review.md` record runbooks, bounded license inventory, and advisory applicability. Phase 9 is not release-ready: wolfSSH message ordering/parser issues and distribution/source-notice questions remain unresolved.
- Current implementation adds consistent Xtensa small X25519/Ed25519 policy and fail-closed compiler guards; seven pinned overrides now include DHCP option bounds, TLS EMS error propagation, and certificate-name allocation failure handling. All generated copies carry dated project modification notices. Nested mbedTLS targets are selected explicitly; installed dependencies remain untouched.
- Parent `pio run` PASS: **94,340 B linked RAM / 1,767,217 B flash** (same RAM, 64,092 B flash vs 9C; not runtime headroom). Parent SDK override suite with actual seven-source registration, strict production wolf crypto policy/vector suite, wolfSSH auth contract135cases, and SSH protocol/context suite all PASS with `CCACHE_DISABLE=1`. Independent review found no actionable implementation defects and repeated the first two suites successfully. DHCP includes196,623 guard-page/equivalence cases; extracted EMS/X509 error tests do not establish full handshake/persistence fault behavior.
- Review docs now distinguish original baseline from implemented mitigations. Seven generated modification/date notices resolved; broader license packaging/source questions remain. No target timing/interoperability, fault-injection or legal-clearance claim. **Next:** coherent wolfSSH message-order/parser correction or reviewed upgrade (1.5.0 candidate, not verified managed compatibility), ECC validation review, remaining advisory inventory and release notices. Do not call Phase9 complete or wait for per-slice target approval.
## Phase 9C — library cleanup / protocol policy — 2026-09-15
- User requested continuation; hardware still deferred to **whole Phase 9**, no per-slice approval gate. Initial Git status clean. Secure boot/encrypted NVS excluded; no eFuse/partition/dependency-version/asset changes, no SDK/managed source mutation.
- `tools/security_overrides.py` + `cmake/security_overrides.cmake` included after root `project()`: require exact IDF5.5/version/originalSHA/edit matches, generate four full notice-preserving source copies in build tree, replace exact component source preserving flags/includes. Compile inputs are pinned originals PLUS checked-in edits. Missing/changed/ambiguous target/source fails; reconfigure tracks originals/script/generated. Never edit derived files or blindly repin. Original sources remain unchanged; compiled dependency behavior intentionally changes.
- Overrides: HTTPS post-handshake allocation-failure TLS deletion, complete failed-start destruction and raw key pre-free wipe (failedstop owns live state); HTTPD scratch allocate/copy/wipe/free preserve old on failure, finalwipe, null first-read/nullable parserpointer fix; server-local TLS1.2 ECDHEECDSA AES128/256GCM, no renegotiation, no change clientdefaults/global primitives; wolfSSH GetSize both password lengths, failed newpassword framing skips callback, checked method suffix wiped before responses with prefix/canaries preserved, library asyncpending retains payload (project synchronous).
- `ssh_memory.{c,h}` installed as globalwolfSSL hooks before initialization, PSRAMpreferred/internalfallback, usableextent securefree/noheaders, shrink wipes tail retains capacity, growth old+new allocation failure preservesold. Guards unpoisonedIDF5.5; dynamicIDF TLS buffers compile-rejected for cleanup contract. These costs need actual peak/latency evidence; liveinline/compaction/stack/hardware intermediates not allwiped.
- `ssh_protocol_policy.{c,h}` applies checked staticlists before contextpublication: Curve25519/P256KEX, P256hostkey, AES128/256GCM, hmacsha256 advertisement, Ed25519/P256userkey advertisement (DB enforcesauth). LegacyCBC/CTR/removedKEX-only clients fail; no identitymigration. TLSpolicy is serveronly so future outboundHTTPS RSAclients unaffected.
- `web_cookie_auth`: nonconsuming earlyquota/epoch probe before receive, final postparse reservation unchanged; JSONwipe beforeKDF, credentialsafter/beforeerrors; handler-lifetime RetryAfter. Existing5verification/60s fixedwindow/restartreset/malformednotcharged retained; no challengefairness/generalrequestlimit claim. All10domain modes passed implementation.
- Final parent `pio run` PASS **94,340 B linked RAM / 1,831,309 B flash** (sameRAM/+1,384flash vs9B). Final fivefocused suites PASS incl installedSDK allocationextent, SDKcleanup/TLS/generator/nullfirstread+actual4source registration, SSHpolicy actual15contextintegration+KEXINIT, generatedwolfSSH135cases, web early admission. 17 related regressioncommands PASS before finalnullablefirstreadpatch; patchedSDKsuite+firmware rerunafter. Two independent reviews no blocking issues; inherited null-pointer subtraction found/fixed/tested. Standard UBSan linking unavailable earlier; new parser/allocator trap instrumentation passed in focused development. No realnetwork/hardware/cryptohandshake or reserveclaims.
- Bounded review in `docs/security_library_review.md`: normal inspected mbedTLS record/MPI/PK/HMAC and wolfECC scalar paths alreadywipe; newhooks cover observed retired DER/buffer gaps, not proof everycopy erased. Password1264ASCII/PBKDF2SHA25650k/generated24of64 unchanged pending costmeasurement; P256selfsigned20252049/trust verification retained; CSP/headers reviewed no blindHSTS or crypto-global removal.
- **Next: Phase9D current upstream advisory/license review and provisioning/rotation/reset/backup/recovery/decommissioning runbooks.** No external advisory/CVE review or full license audit performed by9C; do not describe pinned versions/localfixes as certified current. Any versionupgrade now must re-audit/source-rebase overrides. Target checklist in hardeningdoc adds modern/legacy suite negotiation, rekey, malformed encryptedpassword packets, TLS/scratch failurecleanup, securefree CPU and old+new allocationheadroom under fullmix. Do not wait for9Ctarget signoff tocontinue.
## Phase 9B — SSH admission / credential handling — 2026-09-15
- User requested continued Phase 9 work and will validate **the phase as a whole**. Do not pause between slices for target approval; all target gates remain unrun and collected in `docs/security_hardening.md`. Secure boot/encrypted NVS remain excluded; Phase 8 sign-off stays closed. Initial Git status for this slice was clean.
- `ssh_auth_policy.{c,h}`: 72-byte owner-only boot-lifetime state, independent handshake and password/signed-key buckets (capacity6, refill1/10s), unsigned-probe bucket(capacity12, refill1/5s). No waits, allocations, per-peer maps or NVS writes. Reconnect, stop/start/rotation/counter clear do not replenish; no refunds, idle saturation/no excess credit, clock regression fails closed. Global starvation is a deliberate documented tradeoff; natural refill only after hostile traffic subsides, not fairness/zeroCPU protection.
- `ssh_transport` gates handshake before wolfSSH allocation and credentials before database/ordinary signature work; keeps existing per-slot three-counted-attempt closure and 15s deadline. Explicit pending-result marker fences duplicate/unexpected completion. wolfSSH1.4.20 and certificates/none-disabled guard; keyboard prompt rejection callback/context prevents unregistered callback dispatch while keeping password/publickey advertisement. New aggregate admission/probe/throttle/limit/backend/method counters via `ssh counters`; `add_counter` saturates (do not generalize to unrelated direct lifecycle increments).
- Admin RX consumed spans / TX positively accepted spans are securely wiped; pending retry and serial hot-path bytes unchanged. Whole retired slot securely wiped before generation/fd restoration. `console_input` and shared remote hidden prompts reject overflow/unsupported bytes on submit, sticky across editing; visible CLI behavior preserved; existing callers prevent prefix persistence. Input errors wipe output and return zero length.
- Source audit verified actual pinned wolfSSH auth callback order and `SendChannelData` positive copied/consumed behavior. Tests pin `internal.c` SHA256 and execute extracted vendor parser/send functions with crypto/IO doubles plus actual compiler-feature preprocessing. Followup resolved reviewer concern about keyboard error-path one-byte write: inline buffer initialized, framed packets retain padding reserve, exact-sized protocol-identification pending state cannot reach auth, rejection purges without advancing length. This is a narrow invariant audit, not library security certification.
- Validation: parent `pio run` PASS **94,340 B linked RAM / 1,829,925 B flash** (+144RAM/+1,360flash vs9A; not runtime reserve). Parent and independent review PASS all four new suites `ssh_auth_policy`, `ssh_auth_transport`, `wolfssh_auth_contract` (35 vendor cases+resolved feature profile), `hidden_input`; token policy UB-sanitizer trap mode passed, standard UBSan runtime absent. Related 11 command suite PASS: SSH management/security/runtime, console boundary/accounts/lifecycle, admin SSH policy, web cookie SSH/accounts, web admin transport+tickets, security build policy18. `git diff --check` PASS. No blocking review findings; no upload/erase/device operations/deps/generated assets/commit.
- 9B's planned library/protocol and early web-admission follow-up is implemented and bounded by 9C above. Challenge fairness/full-memory wiping are not guaranteed. External maintenance/lifecycle work is next; no intermediate target sign-off needed.
- Final target checklist includes real SSH clients offering several keys, bad signatures/passwords, keyboard decline, each pool/refill/restart-clear persistence, established mixed transport/USB/UART0 responsiveness and reserve measurements, hidden-input errors/CRLF timing and crash recovery. UART0 paired/delayed LF relies on next-prompt flush; host UART fake does not model timing. No real-crypto/live packet-network or target claims from extracted-function tests.
## Phase 9A — crash/debug baseline — 2026-09-15
- User requested Phase 9 and explicitly excluded secure boot and encrypted NVS. Roadmap now marks Phase 9 in progress; Phase 8 acceptance remains closed. Physical extraction/firmware replacement stay outside the threat model even after hardening; no encryption/eFuse/partition changes.
- `src/security_build_policy.c` enforces resolved no-core-dump + silent-panic-reboot settings and rejects panic/register output, runtime/panic GDB stubs and OCD-aware handling. Registered unconditionally in CMake; explicit defaults. No runtime task/buffer added. This intentionally removes decoded panic traces, not ordinary boot/status logging or physical debug access.
- `docs/security_hardening.md` defines shared operational profiles, secret-bearing artifact handling, evidence limits and target gates. Reserved partitions unchanged; old dump/credential copies are not erased. No generated assets/dependency changes.
- Validation: `pio run` PASS **94,196 B linked RAM / 1,828,565 B flash**. Host policy matrix PASS17; actual generated SDK header PASS as eighteenth case. Initial host test hit read-only ccache storage; `CCACHE_DISABLE=1` rerun passed. Independent review found no actionable issues and repeated both host modes and diff check. No upload, erase, hardware validation or commit.
- **9A target gate remains open:** synthetic-secret controlled panic, no register/UART/flash dump, reboot rather than halt, UART0/USB/network recovery and broker behavior. No test-only panic command was added to production.
- 9A changed no authentication behavior; its planned SSH follow-up is now implemented in 9B above. Whole-phase target validation remains deferred.
## Web popup cosmetics — 2026-09-14
- `src/web_ui.c`: contextual buttons now occupy entire status cards; bounded grid columns and clipped/ellipsized values prevent narrow-window overflow. Quick panels preserve the visible terminal title, admin toolbar and selected-view indication; full-page promotion retains drafts and restores Settings presentation.
- Quick panels hide full-page explanations and duplicate detail readouts while preserving live status, errors and operation results. Wi-Fi exposes configured profile selection/enabled state and AP policy, plus Apply/Save/Refresh/Result; empty profile slots and advanced editors remain full-page-only. Profile selection is an editing target, not a direct-connect command; existing backend operations are unchanged.
- Validation: all 161 UI behavior groups and C/HTML checks PASS; 36 Chromium geometry fixtures PASS at 320/600/900/1200px. `pio run` PASS (94,212 B linked RAM / 1,830,329 B flash). No generated-asset regeneration, upload, erase or hardware validation. Updated regression coverage in `tests/web_ui_session/`.
## Focused cleanup / PSRAM review — 2026-09-13
- User-authorized post-acceptance code review: removed superseded `admin_ssh_console_open()` SSH-only wrapper; production already uses available-slot admission. Updated adapter regression to actual production entry. Wrapper was already linker-discarded: no binary saving attributed to removal.
- Moved ping queue payload4,200 B and public user snapshot2,156 B to lazy PSRAM-only lifetime allocations, no fallback. Queue control/internal locks unchanged; allocation failure affects only ping or status/list/show, not UART0 registration/mutations/recovery. Snapshot fully wiped on success/error. No serial hot-path, stacks, CPU, queue bounds or external-BSS config changes.
- Baseline pio PASS23.79s100,556 RAM/1,828,573 flash. Final parent pio PASS22.11s **94,212 RAM/1,828,809 flash: 6,344 B linked internal RAM/+236 B flash**. Requested lazy PSRAM6,356 B plus allocator overhead; target pointer sizes4 B, controls84 B verified. This is not measured runtime-minimum improvement. CPU160 retained.
- Focused ping allocation/callback/end-capacity and accounts allocation/full-wipe/failure/retry tests PASS; console boundary/lifecycle/policy and SSH management/runtime suites PASS. Independent review found no actionable bugs and reran ping/accounts/boundary/diff PASS. Sanitizer linking unavailable (missing host runtimes), no sanitizer or hardware pass. No upload/erase/commit. Next target check: ping/user list/show repeatedly alongside NVS writes and full mix230400, collect serial/broker counters and memory before/after first allocations.
- Further audited opportunities, not implemented: OLED framebuffer1,024 B (internal I2C staging retained), local/remote completion scratch1,024 B each, optional web diagnostic ring2,816 B, remote console output payload8,192 B. Console rings need explicit secret-output wiping/lifecycle and admission-failure isolation; do not relocate mixed state wholesale. Leave authoritative user database, driver/DMA buffers, locks and task stacks internal. Global external-BSS enable is not surgical: it also changes SDK library placement.
## Accepted state — 2026-09-13
- **8D.22 explicitly signed off by the user:** “Yep, I tested the firmware thats a 8d.22 signoff.” The retained Phase 8D scope is complete; earlier per-slice pending target/review/integration gates are superseded. Roadmap already records 8A/B/C as complete and target-hardware validated, so **Phase 8 is complete**. Acceptance does not manufacture individual unreported test passes.
- [Roadmap](../roadmap.md#phase-8--role-based-users-and-administrative-access--complete) holds the completed-phase gist; [web administration](../web_administration.md) holds current API/owner/recovery contracts; [acceptance evidence](../web_administration_acceptance.md) holds the latest report and limits. The old plan/baseline/per-slice histories are consolidated, not archived as another timeline. Test READMEs now link directly to current contracts and evidence; obsolete forwarding notes were removed too.
- Final prior production build **PASS: 100,556 B linked RAM / 1,828,573 B flash, CPU 160 MHz**. No build/test/device execution is implied by this documentation update. The prior combined binary WebSocket-send fix was separately user-accepted at **160 MHz / 230400 baud with full mix including browser admin**; preserve combined send and bounded failed-send isolation.
- Latest loaded capture: two serial WS, USB, two SSH roles with SSH serial writer; browser admin used then closed, not active in the capture. Internal/DMA/PSRAM free **31,508 / 23,752 / 8,136,624 B**, minima **2,052 / 460 / 8,065,972 B**, largest **18,432 / 18,432 / 7,995,392 B**; SSH minimum-free stack **15,028 B**. Full boot/loaded table is in acceptance evidence. Web send/queue/protocol and SSH IO errors zero; one SSH handshake failure/session revocation. Missing latest broker/serial counters prohibit an exact zero-drop inference.
## Follow-ups, not acceptance blockers
- Extremely low internal/DMA lifetime minima warrant correlated transient-headroom investigation; overlapping capability pools and conservative/non-simultaneous region minima do not prove allocation failure. Numeric reserves, HTTPD/dispatcher stack margins, peak correlation and detailed soak/fault evidence remain unapproved/unreported. Do not reopen functional sign-off or invent a reserve threshold.
- SDK TLS `-0x004C` is generic NET_RECV_FAILED, not OOM. Two boot auth failures plausibly involve stale cookies, but causation is unconfirmed. Prior intermittent web admission issues and accepted idle cleanup do not justify claiming every admission failure fixed.
- Real DNS/reannouncement, NVS power-loss, browser geometry/accessibility, individual fault cases and exact duration claims require explicit evidence if investigated; retained [regression procedures](../user_administration_tests.md) are not execution records.
- The earlier documentation-only handoff is superseded by the user's Phase 9 request; current scope and evidence are recorded above. Device operations remain unperformed.
## Scope and safety to retain
- 8D.15 dedicated typed network diagnostics was removed; shell diagnostics remain subject to frontend policy. Unimplemented 8D.19 ordinary browser-session/native-USB controls were removed; SSH settings remain. No implicit full browser-shell parity or browser identity reset/recovery/export.
- One UART1 broker writer, isolated observers and binary transparency. UART0 is administrative recovery; native USB is network-independent UART1, not administration or uninterrupted reboot.
- Typed operations carry original-login IDs to the existing dispatcher. Owner-reserved generations fence stale/ABA changes; later revocation/timeout does not cancel admitted work. HTTPS commits before stop/restart; SSH stops before commit/restart; committed identity never rolls back on lifecycle failure. Lost ACK/result means uncertainty, never automatic replay.
- Preserve private IDF HTTPD version guards, at-most-one owner-work reservations through failed destruction, retained SSH context until all slots retire, bounded queues/buffers and secret-free metadata. Canonical recovery survives conditional-token exhaustion.
## Previous documentation consolidation handoff
Initial Git status was clean. This task changes root `README.md`, `docs/` and five test-directory READMEs; executable source/tests/config/generated assets remain untouched. Independent documentation review checked acceptance scope, owner contracts and local links. It restored explicit pointer-backed HTTPD response-header lifetime and same-version SDK-patch audit warnings, updated test README links, and removed obsolete forwarding notes without reopening sign-off.
Validation completed: independent Python local-link/anchor audit PASS across 29 authored Markdown files (122 local links, 53 Markdown fragments); 213 authored source/test/document files checked with zero obsolete Phase 8D filename references. Earlier path audit resolved127 expanded navigation references. GPT logs, vendored/generated trees and remote URL fetching excluded. Twenty obsolete phase documents removed, with no forwarding stubs/archive dump. Git diff/scope checks confirm documentation-only changes. No firmware tests/build/device commands run.
+223
View File
@@ -0,0 +1,223 @@
# Durable design constraints and decisions
Only constraints supported by implementation or current project documentation belong here. When original rationale is unknown, the entry describes the observable constraint without inventing intent.
## Display configuration has an owner reservation separate from button activity
**Decision:** `local_status_ui` owns a nonwrapping configuration generation and a zero-wait reservation shared by typed Display and CLI/legacy Apply. NVS runs outside timing critical sections; Save stabilizes selected bytes and Reset commits defaults before RAM publication. Load retains canonical fallback. Buttons/diagnostic holds update activity, not configuration generation.
**Consequence:** Compare before mutation, never overwrite intervening CLI edits, and do not make physical panel presence a configuration prerequisite. A successful config API is not proof of display IO. [Owner and persistence contract](../web_administration.md#serial-and-display).
## Typed Network edits preserve manager ownership and current secret bytes
**Decision:** HTTPD uses zero-wait secret-free projections and an ID-only dispatcher. Wi-Fi compare/merge/whole-candidate validation and queue-before-publication preserve omitted secrets and reject stale changes; its manager alone owns radio/reannouncement. mDNS generation/persistence is independent. Save stabilizes selected RAM; Wi-Fi Load is stored-only, not fallback-secret generation.
**Consequence:** Keep SSIDs reversible bytes, omitted/Replace/disabled-STA Clear distinct, AP clear denied, and Next profile separate from editor selection. mDNS may report RAM applied but reannouncement not queued, without rollback. A one-second queued-secret timer is not hard cancellation; `accepted` is not online/DNS. Recovery and no automatic replay are correctness requirements. [Network contract](../web_administration.md#network).
## One broker mediates all production serial transports
**Decision:** USB CDC, WebSocket, and role-`user` SSH access UART1 through `session_broker`; transports do not independently own the serial service.
**Rationale/evidence:** The broker is initialized after the serial service and all transport implementations connect broker clients. It is the normal serial RX consumer and TX gate. Project documentation requires one writer and multiple observers.
**Consequence for future changes:** New serial transports must become broker clients. Do not bypass writer checks or consume `serial_service` RX directly. `serial_service_start()` is not idempotent, so admission code must reconcile check/start races as the existing transports do. Broker paths enter serial-service APIs while holding the broker mutex; preserve that lock order and do not call back into the broker while holding the serial state mutex. Preserve binary transparency and avoid in-band ownership control.
**Relevant files:** `src/session_broker.{h,c}`, `src/serial_service.{h,c}`, `src/usb_cdc_transport.c`, `src/web_serial_transport.c`, `src/ssh_transport.c`
## Slow clients are isolated by bounded per-client storage
**Decision:** UART RX is drained and copied into independent bounded broker output streams; a full observer loses only its own copy.
**Rationale/evidence:** `session_broker` accounts per-client dropped bytes instead of blocking fan-out. The roadmap records slow-client isolation as a project-wide constraint.
**Consequence for future changes:** Do not replace fan-out with a blocking shared queue. Any added transport must tolerate partial/no-progress reads and expose drop/backpressure counters.
**Throughput observation and controlled experiments:** The initial diagnostic baseline used CPU160MHz; a CPU240MHz-only experiment reduced but did not eliminate browser queue overflow. Combining binary WebSocket header/payload into one bounded session-override send eliminated reported drops, and the user signed off230400-baud full-client-mix operation after returning to160MHz. Retain the combined send, not the frequency increase; evidence and limits are in `current-state.md`. Preserve scheduling/priorities and 4096/512-byte broker/web buffers while gathering per-client HWM/drop attribution and independent opt-in web binary-TX timing. Fixed-slot epoch/generation-fenced aggregates avoid stale attribution; no new runtime allocations. Clear preserves queued data and seeds broker HWM; disconnected rows disappear while global discard counts remain. Callback timestamps precede the transport lock; synchronous send return is not peer receipt. Completion-to-read intervals include broker/mutex/control work and possible idle, even when the first read is nonempty; never label them pure scheduling latency or proof of backlog at completion. Compare enabled/disabled target captures before drawing overhead conclusions. Contracts and reproduction: [throughput diagnostics](../web_throughput_diagnostics.md).
**Relevant files:** `src/session_broker.c`, `src/session_broker.h`, `docs/roadmap.md`
## Physical UART ownership and logical writer ownership remain separate
**Decision:** `rs232_port_owner` controls whether diagnostics or the serial service may manipulate UART/MAX3243 hardware; the broker separately controls which connected client may write.
**Rationale/evidence:** The code has explicit `NONE`, `PHASE0`, `SERVICE`, and `FAULT` hardware states plus broker client/writer IDs.
**Consequence for future changes:** A writer lease never authorizes direct UART/GPIO access. Active hardware tests must claim `PHASE0`; the production service must claim `SERVICE`. Boot-time static-safe GPIO setup and service-owned static-mode restoration are explicit exceptions to this cooperative gate. Ambiguous cleanup must keep the transceiver safe and require reboot rather than clearing fault casually.
**Relevant files:** `src/rs232_port_owner.{h,c}`, `src/rs232_hw_test.c`, `src/serial_service.c`, `src/session_broker.c`
## Resource IDs are generation-safe
**Decision:** Broker/SSH/WebSocket slots, originating web sessions, queued admin operations and account principals carry distinct generation/identity fences. Browser cookie-session identity is not interchangeable with account identity. Invalidate session records before socket cleanup and retain authoritative currentness checks even when notifications fail.
**Consequence:** Never turn selected transport IDs into arbitrary broker IDs/fds, rebase a stale confirmation or wrap a published token. Exhausted broker/SSH slots retire; operation/reservation IDs do not reuse; saturated service/lease generations fence ABA without disabling canonical recovery. Reboot invalidates old logins. Validate/reserve at the owner immediately before effects, not snapshot-check/unlock/unconditional mutation. [Broker](../web_administration.md#broker-and-contextual-controls) and [service](../web_administration.md#service-lifecycle-and-identity-rotation) contracts.
## Confirmed writer transfer compares a lease version inside the broker lock
**Decision:** Compare the connected nonreused target and separate lease generation inside the force-writer lock. A client ID alone cannot fence release/reacquire ABA. Lease generation saturates, survives counter clear and advances before advisory event delivery, potentially twice for force transfer.
**Consequence:** Saturation rejects typed assignment but preserves ordinary request/release/disconnect and recovery force. Accepted serial TX is not recalled. Live contextual refresh must retain the selected versions and sticky stale/absence state until explicit reselection. [Wrap and UI contract](../web_administration.md#broker-and-contextual-controls).
## UART0 is the physical recovery authority
**Decision:** UART0 remains independent of UART1 and networking. The first administrator is created with normal `user add` on UART0; explicit unavailable-user-database recovery to empty is UART0-only and refuses healthy storage. No bootstrap command/API remains.
**Rationale/evidence:** `main.c` configures UART0 separately; command policy and user handlers deny these operations remotely. README/roadmap identify UART0 as the trusted recovery console.
**Consequence for future changes:** Network failures or credential corruption must not remove UART0 recovery. Do not expose unauthenticated first-admin provisioning or recovery through web or admin SSH without an explicit security redesign.
**Relevant files:** `src/main.c`, `src/admin_ssh_console.c`, `src/user_console.c`, `docs/roadmap.md`
## Admin SSH and user SSH are different routes
**Decision:** A role-`user` SSH session becomes a broker serial client. A role-`admin` session enters the administration console and never obtains a broker client/writer lease.
**Rationale/evidence:** Role routing is explicit after SSH authentication. The administrative shell is intended for command execution, not multiplexed serial data.
**Consequence for future changes:** Do not silently give administrators both streams or infer that higher privilege means UART1 ownership. A route-switch feature would require explicit protocol, lifecycle, and authorization design.
**Relevant files:** `src/ssh_transport.c`, `src/admin_ssh_console.{h,c}`, `src/session_broker.c`
## One dispatcher executes the canonical command registry
**Decision:** UART0 and admin SSH submit complete lines to one fixed queue; one task is the sole caller of `esp_console_run()`.
**Rationale/evidence:** The implementation treats ESP-IDF console execution as non-reentrant and removes the need for separate remote command implementations.
**Consequence for future changes:** Register one canonical handler rather than creating a second SSH dispatcher. Long commands/prompts block all administration, so keep handlers bounded or explicitly asynchronous. Preserve output routing and remote principal checks.
**Relevant files:** `src/admin_ssh_console.c`, `src/main.c`, `src/console_input.c`, all `src/*_console.c`
## Selected self-affecting admin SSH actions use bounded deferred control
**Decision:** SSH self-close/reboot/lifecycle/host-key actions use existing bounded application-drain control; browser shell stop/reboot and typed certificate handoff use owner adapters, not command replay. Drain is not peer receipt. Crypto/NVS browser rotation runs on the existing dispatcher, not the small control stack; executing slots remain reserved across self-detach.
**HTTPS typed ACK:** Successful synchronous send return precedes one nonreused-ID HTTPD callback to the existing dispatcher. No captured request/fd/reusable operation pointer or lifecycle wait on HTTPD. Lost accepted work retains one reservation until callback or successful destruction; never release speculatively on timeout. Original-login/current-admin/dequeue deadline checks precede admission. Reserved restart may deliberately invalidate that login; subsequent revocation is not cancellation. Reboot invokes canonical `esp_restart()` outside locks without self-console cleanup.
**Identity replacement:** Compare/reserve service then task-bound nonreused identity token, shared by canonical/direct callers. Crypto/NVS run outside security locks. HTTPS commits before stop/start; SSH stops before commit/restart. Failed SSH stop skips mutation/start; persistence failure can follow client disconnection. Committed material is never rolled back on restart failure. SSH owner retains context until all slots retire; start rejects orphan handles. Public fingerprint projections do not authorize mutation, and stored/served HTTPS identity can differ after failed stop.
**Consequence:** Explicitly communicate partial effects, trusted UART0 fingerprint verification and fresh HTTPS login after restart. Preserve CLI recovery/reset but do not add browser Reset/export as if it were ordinary rotation. Native USB is independent UART1, not administration or uninterrupted reboot. [Lifecycle/identity contract](../web_administration.md#service-lifecycle-and-identity-rotation).
## Authentication uses copied principals and fail-safe currentness checks
**Decision:** Network sessions retain secret-free copied principals. Database/account ID/auth generation and originating web-session identity must be current at admission, before sensitive input and during reconciliation. Best-effort target notifications supplement, never replace, these checks and cannot roll back committed mutations.
**Consequence:** Shared remote-console slots require transport-qualified tokens and immutable owner adapters. Validate owner currentness outside console locks, then recheck identity. Owner-side HTTPD/SSH IO and generation-safe cleanup remain mandatory; session liveness checks do not cancel executing handlers. Browser-shell permissions are parsed and narrower than typed Settings. [Authentication](../web_administration.md#authentication-and-admission), [console policy](../web_administration.md#browser-shell-policy).
## SSH admission budgets survive service and session lifetimes
**Decision:** Three fixed-size owner-only token buckets independently admit handshakes, password/signed-key requests and unsigned probes. Budgets last for the boot, not the slot/service/counter epoch. Rejection closes without sleeping; no per-account/IP storage or persistent lockout is added. Signed-key completion has an explicit pending-result marker and retains authoritative principal checks. Pinned library version/feature/source-contract tests protect callback order; keyboard-interactive is explicitly rejected.
**Consequence:** This bounds admitted work but permits global-budget starvation; restarting SSH is not an immediate recovery override. Established streams bypass admission, while actual load/latency still needs whole-phase device evidence. Counters are observations, never enforcement state. [Policy and tests](../security_hardening.md#9b-ssh-admission-and-credential-handling).
## Hidden input must not accept a truncated credential
**Decision:** Hidden console prompts reject overflow/unsupported bytes at submit, wiping output; rejection stays sticky after edits. Submission, Backspace/Delete and Ctrl-C retain their roles. Visible CLI editing is unchanged. Consumed SSH admin RX and accepted TX spans are wiped without touching pending retry bytes; slot retirement securely wipes before restoring generation/sentinels.
**Consequence:** Overlong/unsupported pastes must be retried; caller errors prevent prefix persistence. Application wipes do not establish library/stack/PSRAM zeroization. The pinned wolfSSH positive-send contract is copied/consumed bytes, not peer receipt. UART0 paired-CRLF timing remains a target check. Tests: `tests/hidden_input/run.py`, `tests/ssh_auth_transport/run.py`, `tests/wolfssh_auth_contract/run.py`.
## Typed serial mutations share the administration dispatcher
**Decision:** Typed domains queue IDs to the existing serialized dispatcher, never CLI strings or secrets. One original-login slot per domain and a nonreused ID fence stale work; session/deadline checks precede canonical admission. Results are replaceable observations, not durable history/idempotency.
**Consequence:** No automatic mutation replay, including after navigation, timeout or logout. Ordinary deadlines limit dequeue admission, not execution. Accounts/Network queued-secret timers wipe only non-executing inputs; locals wipe after admitted work returns. Explicit RAM/NVS/reset semantics and partial-effect uncertainty must match each canonical owner. [API bounds and lifetime](../web_administration.md#typed-settings-api-and-operation-lifetime).
## Typed account selection is checked inside the database mutation lock
**Decision:** Target username/account ID/auth generation compare occurs inside the canonical mutation lock for role/delete/password/key changes. HTTPD uses compact zero-wait secret-free projections, not the blocking CLI snapshot. Successful changes notify only the target's web/SSH sessions, including self.
**Consequence:** Separate generated-value delivery from mutation and retain no retrieval history; context-bound saved acknowledgement is UX, not receipt proof. Self-revocation can deny results, so 401/disconnect cannot mean success or cancellation. Key slots are stable and sparse, fingerprint-only on output; import shares canonical validation. Final-admin invariants and UART0 provisioning/recovery remain. [Accounts contract](../web_administration.md#accounts-and-authorized-keys).
## Browser authentication has a narrow version-pinned HTTPD boundary
**Decision:** `web_httpd_adapter` alone accesses private IDF 5.5.0 parsed-header/session state. Reject duplicate/ambiguous headers; defer 101 until cookie/Origin/ticket/transport admission; wipe consumed scratch while preserving unread bytes. Stage optional Settings descriptor/name allocations before publication. Compile header/ticket debug logging out.
**Consequence:** Re-audit SDK assumptions on upgrade; never patch around Origin `null` by weakening same-origin policy. Browser authentication POST uses CORS mode with fixed same-origin URLs/credentials because no-referrer non-CORS POST can serialize Origin as null. Digest-only cookie/challenge sessions replace Basic without fallback or live-record eviction. CSP loader hashes and authored scripts change atomically. Navigation preserves terminals/lease, while session-identity changes require a clean document before showing retained buffers. [Authentication and terminal contracts](../web_administration.md#authentication-and-admission).
## Dependency corrections are reproducible build inputs, not local SDK edits
**Decision:** Root CMake installs four exact-source-hash corrections after IDF target creation, rendering copies in the build tree and replacing each original target source exactly once. Original notices, includes and source compile properties are retained. Changed hashes/versions/missing/ambiguous sources fail configuration, with no unpatched fallback. Tests verify generated bytes and actual compiler inputs. [Registry and audit](../security_library_review.md).
**Consequence:** Upgrades need source/lifetime/feature re-audit, not just refreshed pins. Installed vendor code alone is not authoritative for overridden functions. Corrections cover HTTPS failure cleanup/key wiping, HTTPD scratch ownership, TLS server-local policy and SSH password packet bounds/wiping. TLS client defaults and global primitives remain unchanged. This is normal reproducibility checking, not tamper-resistant attestation.
## Retired library storage and protocol defaults have explicit policies
**Decision:** wolfSSL/wolfCrypt hooks use reviewed unpoisoned IDF5.5 usable allocation extents to wipe before free. No header overhead; shrink wipes tail but retains capacity; growth allocates/copies/wipes, retaining the old block on failure. Poisoned heaps and dynamic IDF TLS buffers are compile-rejected pending separate lifetime audits. Explicit static TLS/SSH allowlists replace negotiation defaults, without identity migration or weakening user-database authorization.
**Consequence:** Whole-buffer wipes and old-plus-new allocation peaks need combined target measurement; no blanket claim covers live inline residue, compiler spills or every crypto temporary. Legacy-only cipher/KEX clients can lose access; policy setter failure must free unpublished context rather than fall back. Web's early quota check does not change verification counts, service-restart resets or challenge fairness. [Exact algorithms, cleanup and limits](../security_library_review.md).
## Security material and configuration use bounded, versioned NVS records
**Decision:** Application settings, users, and identities use separate fixed/versioned NVS blobs. Serial, Wi-Fi, mDNS-hostname, and local-UI working edits are RAM-only until explicitly saved. User mutations and HTTPS/SSH identity changes commit directly as part of the operation. Invalid ordinary configuration generally selects RAM defaults without erasing storage; malformed security material fails closed and needs explicit reset.
**Rationale/evidence:** Serial, Wi-Fi, local UI, web security, users, and SSH security each validate schema/size and own their namespace. User/security mutations build and validate candidate state before committing it; security modules avoid silently replacing an established identity. The live user database remains internal while its 5,360-byte candidate is a persistent PSRAM-preferred allocation with internal fallback and is wiped after every transaction.
**Consequence for future changes:** Add schema versions and transactional candidate validation. Do not overwrite unknown records automatically; provide explicit migration/reset behavior. Preserve the distinct persistence contracts: explicit save/load/default/reset for working configuration and per-blob commit-before-live-install for user and identity mutation. Keep candidate ownership mutex-local and wipe/free it on initialization or recovery failure. Recheck external-buffer staging in the flash/NVS implementation when upgrading from the pinned ESP-IDF 5.5 baseline. Legacy credential synchronization and reconciliation are removed. Missing user storage commits empty; valid user v1 bytes remain compatible, with private `v1_admin_marker` derived from admin count, not a public bootstrap contract. HTTPS v1 (1,392 bytes) migrates through a private validated reader to TLS-only v2 (1,340 bytes), preserving exact DER/fingerprint/generation and committing before publication. Failures fail closed without fallback regeneration or overwriting rejected records. See [legacy compatibility](../legacy_credential_removal.md).
**Relevant files:** `src/serial_config.c`, `src/wifi_config.c`, `src/mdns_config.c`, `src/mdns_service.c`, `src/local_ui_config.c`, `src/web_security.c`, `src/user_database.c`, `src/ssh_security.c`
## NVS is persistence, not a physical security boundary
**Decision:** The current firmware stores Wi-Fi credentials and TLS/SSH private keys in unencrypted application NVS. The reserved NVS-key partition does not enable encryption. Phase 9 explicitly excludes secure boot and encrypted NVS by user preference; physical extraction and firmware replacement remain outside the supported threat model, not deferred guarantees of this phase.
**Rationale/evidence:** `partitions.csv`, README security notes, and current code show no NVS-encryption setup. Original rationale for deferring encryption is outside the implementation; the observable limitation is explicit.
**Consequence for future changes:** Do not claim resistance to flash extraction. Logical NVS replacement can leave old plaintext credentials in flash and is not secure erasure; no factory erase is required by this cleanup. Older v1-only firmware cannot read v2 HTTPS material. Avoid increasing stored secret exposure. Enabling encryption requires migration/recovery planning, not just changing the partition table.
**Relevant files:** `partitions.csv`, `README.md`, `src/web_security.c`, `src/ssh_security.c`, `src/wifi_config.c`
## Supported builds do not export crash memory
**Decision:** Phase 9A requires disabled core dumps and silent panic reboot, and forbids panic/runtime GDB stubs and OCD-aware panic handling. `src/security_build_policy.c` checks resolved SDK configuration at compile time; defaults alone are insufficient. Development, test and production handling profiles share this baseline, with no bypass flag.
**Consequence:** Decoded panic traces/register output are deliberately lost; ordinary boot/status diagnostics remain and are not universally sanitized by this policy. No eFuse, physical JTAG restriction, partition change or retroactive dump clearing is implied. Target panic/recovery validation remains necessary. [Policy and tests](../security_hardening.md).
## Wi-Fi callbacks enqueue; the manager owns policy
**Decision:** ESP event callbacks copy bounded event data into the Wi-Fi manager queue. A permanent manager task performs driver operations, profile/AP policy, deadlines, reconciliation, and station mDNS announcement transitions. mDNS initializes at most once, remains allocated across transient disconnects while its component handlers withdraw/re-enable the STA interface, and treats failure as nonfatal.
**Rationale/evidence:** Callback paths avoid blocking, NVS, and policy work. Manager deadlines consult authoritative driver/netif state so dropped events are recoverable.
**Consequence for future changes:** Keep callbacks short and nonblocking. Add state transitions to the manager rather than directly invoking Wi-Fi policy from consoles, UI, or callbacks. Preserve queue-drop observability.
**Relevant files:** `src/wifi_manager.{h,c}`, `src/wifi_config.{h,c}`, `src/mdns_service.{h,c}`, `src/mdns_config.{h,c}`
## Optional local UI cannot become a core dependency
**Decision:** The OLED/display may fail without stopping serial, UART0, USB, or networking. The UI consumes copied snapshots and calls public APIs; it never parses CLI output or joins the broker.
**Rationale/evidence:** `main.c` logs display failures and continues. `local_status_ui` collects snapshots before display frames and exposes limited confirmed controls.
**Consequence for future changes:** Keep OLED/I2C work bounded and outside service locks. Do not put credentials or core ownership into UI state. A missing display must remain nonfatal.
**Relevant files:** `src/main.c`, `src/local_display.{h,c}`, `src/local_status_ui.c`, `src/local_ui_config.c`
## Hardware and library access has designated owners
**Decision:** The serial task owns UART1 while active, `local_display` owns I2C/framebuffer access, the SSH owner task owns runtime wolfSSH contexts/calls after caller-side library initialization, and the console dispatcher alone runs registered commands.
**Rationale/evidence:** These constraints are enforced by module structure, mutex/task assertions, and transport indirection. Original rationale varies; the observable effect is serialized library/hardware access.
**Consequence for future changes:** Cross-task requests should use existing queues/public APIs. Do not make post-initialization wolfSSH calls, mutate display frames, or run console handlers from arbitrary tasks.
**Relevant files:** `src/serial_service.c`, `src/local_display.c`, `src/ssh_transport.c`, `src/admin_ssh_console.c`
## Software cryptography settings are a validated concurrency workaround
**Decision:** wolfSSL ESP32 AES/SHA acceleration is disabled, and HTTPS uses software AES for PSRAM-backed TLS records. Internal task stacks are retained where cache-disable safety matters.
**Rationale/evidence:** Root `CMakeLists.txt` disables wolfSSL hardware crypto. The roadmap reports a reproduced watchdog stall involving mbedTLS external-RAM hardware-AES DMA, uncoordinated mbedTLS/wolfSSL hardware locks, and a successful software-crypto concurrency retest; no standalone execution record is checked in.
**Consequence for future changes:** Do not remove these definitions as a performance cleanup. Any re-enablement needs target-hardware concurrency testing with simultaneous USB, WebSocket, SSH, and serial traffic plus watchdog/stack telemetry.
**Relevant files:** `CMakeLists.txt`, `src/CMakeLists.txt`, `docs/roadmap.md`, relevant `sdkconfig.defaults` crypto settings
## Embedded web assets are checked-in generated artifacts
**Decision:** Vendored xterm assets are compressed and embedded ahead of the normal firmware build; `src/web_assets_data.c` is compiled directly.
**Rationale/evidence:** `src/CMakeLists.txt` lists generated data as a source, and `web_assets/SOURCES.md` documents pinned versions, hashes, and deterministic gzip inputs.
**Consequence for future changes:** Edit authored web UI separately. Changes to its inline bootstrap loader must update the hard-coded CSP hash atomically and preserve the response security policy. When dependency assets change, follow the documented provenance/generation process and review generated diffs; do not hand-edit arrays or regenerate assets during unrelated work.
**Relevant files:** `web_assets/SOURCES.md`, `web_assets/generate_embedded_assets.py`, `src/web_assets_data.{h,c}`, `src/web_ui.c`
+57 -24
View File
@@ -1,6 +1,10 @@
# Command reference
Use these commands from the UART0 `serial-tool>` administration console. Run `help` for the available root commands and `<group> help` for a group summary. Configuration changes are RAM-only unless explicitly saved.
UART0 and authenticated `admin` SSH sessions use the same registered command implementations through one serialized dispatcher. Admin SSH exposes the full operational registry, including interactive prompts, network diagnostics, reboot, and HTTPS/SSH material mutation. Create the first administrator through normal `user add <username> admin` on physical UART0; explicit recovery of an unavailable database is UART0-only. Admin SSH also rejects generating a replacement password for its own account so the one-time value cannot be lost when the session is revoked. Run `help` for root commands and `<group> help` for a group summary. Configuration changes are RAM-only unless explicitly saved.
Browser admin uses the same dispatcher with a [narrower parsed frontend policy](web_administration.md#browser-shell-policy), independent of typed Settings permissions. It supports bounded deferred `reboot`, `web stop`, exact `web certificate rotate --force` and owner-relative `exit`. Drain (up to ten seconds plus 200 ms) is best-effort application-buffer acknowledgement, not peer receipt or an execution deadline; pending input is discarded. Certificate work runs on the existing dispatcher through the shared service-before-identity reservation, commits before stop/restart and never rolls back a committed identity after lifecycle failure. Failed stop retains ownership and skips start. Verify changed trust through UART0 `web certificate info`, recover with UART0/admin SSH `web stop` / `web start`, then sign in freshly. HTTPS-only actions leave SSH/native USB/UART0 independent; reboot affects every transport and loses unsaved RAM.
Browser `web` allows only status/stop/exact forced certificate rotation; `wifi`/`mdns` allow status only. Browser `user` allows status/list/show and interactive add/password plus forced role/delete for **other accounts**, not self/generated/key/recovery commands. Restricted SSH stop/disconnect/reset/host-key mutation remains unavailable in the browser shell. Typed Accounts/Network/SSH settings separately provide their documented bounded workflows; this is not shell parity. See [web administration](web_administration.md) for lifecycle/API ownership and uncertainty.
## System
@@ -8,32 +12,31 @@ Use these commands from the UART0 `serial-tool>` administration console. Run `he
|---|---|
| `memory` | Show free memory, minimum free memory, and largest blocks for internal RAM, DMA-capable RAM, and PSRAM. |
| `reboot` | Drain console output briefly and restart the ESP32. |
| `status` | Show quick MAX3243 signal state. |
| `exit` | Close the current administrative SSH or browser session after its acknowledgement drains; unavailable on UART0. Browser `exit` leaves serial connected. Ctrl+D on an empty administrative command line does the same. |
## Role-based users
| Command | Description |
|---|---|
| `user status` / `user list` | Show database generation, capacity, administrator/bootstrap state, and all secret-free account summaries. |
| `user status` / `user list` | Show database generation, capacity, administrator count, and all secret-free account summaries. |
| `user show <username>` | Show one account's role, ID, authentication generation, and SSH-key fingerprints. |
| `user bootstrap` | Set and confirm the `admin` password without echo, then promote the migrated account to `admin`. |
| `user bootstrap --generate` | Bootstrap `admin` with a generated 24-character password displayed once. |
| `user add <username> <user|admin>` | Create an account using a bounded no-echo password and confirmation prompt. |
| `user add <username> <user|admin> --generate` | Create an account with a generated password displayed once. |
| `user delete <username> --force` | Delete an account; the pre-bootstrap migrated `admin` and final administrator are protected. |
| `user delete <username> --force` | Delete an account; the final administrator is protected. |
| `user role <username> <user|admin> --force` | Change a role; the final administrator cannot be demoted. |
| `user password <username>` | Set and confirm a new password without echo. |
| `user password <username> --generate` | Replace a password with a generated value displayed once. |
| `user key add <username>` | Prompt for one bounded OpenSSH public-key line. |
| `user key add <username>` | Prompt on UART0 or authenticated admin SSH for one bounded OpenSSH public-key line. |
| `user key add <username> <type> <base64>` | Import a key non-interactively; intended for authenticated admin SSH and also accepted on UART0. |
| `user key delete <username> <0..2> --force` | Delete one key by the index shown by `user show`. |
| `user key clear <username> --force` | Delete all public keys for an account. |
| `user recover --force` | When normal user-database initialization failed, explicitly replace its blob from the current legacy network credential. |
| `user recover --force` | When normal user-database initialization failed, explicitly replace only its blob with an empty database; UART0-only, refuses a healthy database. |
Usernames must match `[a-z][a-z0-9_-]{0,15}`. Passwords contain 1264 printable ASCII characters. The fixed database supports eight users and three SSH keys per user; initial key types are `ssh-ed25519` and `ecdsa-sha2-nistp256`. A key may belong to only one account. Password verifiers, salts, raw key blobs, and passwords are absent from ordinary status output. `Ctrl-C` cancels a password or key prompt, and generated passwords are shown once.
Usernames must match `[a-z][a-z0-9_-]{0,15}`. Passwords contain 1264 printable ASCII characters. Hidden console prompts reject overflow or unsupported bytes rather than accepting a truncated/normalized prefix, even if later editing reduces the length; submit or cancel and start again. CR/LF submits, Backspace/Delete edits, and Ctrl-C cancels. The fixed database supports eight users and three SSH keys per user; initial key types are `ssh-ed25519` and `ecdsa-sha2-nistp256`. A key may be assigned to multiple accounts but cannot be duplicated within one account. Password verifiers, salts, raw key blobs, and passwords are absent from ordinary status output. `Ctrl-C` cancels a password or key prompt, and generated passwords are shown once.
On the first Phase 8A boot, the old shared `admin` credential is imported as a role-`user` account, not silently granted administrator rights. Run `user bootstrap` from physical UART0 to establish the administrator. Phase 8B now authenticates HTTPS and SSH passwords through this database and enables stored SSH public keys. Before bootstrap, `web credentials rotate --force` and `web reset --force` synchronize the migrated verifier; after bootstrap, that legacy credential is recovery-only and does not authenticate or alter role-based users.
Missing `user_db/database` storage is committed empty. On UART0 run `user add <username> admin`, optionally with `--generate`, to create the first administrator. There is no bootstrap command, imported shared credential, or synchronization with HTTPS material. Existing valid v1 user databases load unchanged, including previously migrated role-`user` accounts; no account is silently promoted.
`user recover --force` is a destructive physical recovery operation and succeeds only while the database is unavailable. It replaces the user blob with one role-`user` account derived from the current legacy credential; run `user bootstrap` afterward. It does not erase unrelated NVS data. Successful password, role, key, bootstrap, and delete operations invalidate only that username's outstanding WebSocket tickets and active WebSocket/SSH sessions; unrelated users remain connected.
`user recover --force` is destructive and succeeds only while the database is unavailable. It rebuilds only the user blob empty, importing no credentials; then create an administrator with normal `user add` on UART0. It refuses a healthy initialized database, including a healthy empty one, and does not erase unrelated NVS data. Successful password, role, key and delete operations invalidate only that username's outstanding tickets and active web/SSH sessions; unrelated users remain connected.
## Local display
@@ -43,10 +46,12 @@ On the first Phase 8A boot, the old shared `admin` credential is imported as a r
| `display set dim-seconds <0..86400>` | Set the RAM inactivity delay before contrast drops to `1`; `0` disables dimming. |
| `display set off-seconds <0..86400>` | Set the RAM inactivity delay before the OLED switches off; `0` disables automatic off. |
| `display save` / `display load` | Save the working aging settings to NVS or load them. |
| `display defaults` / `display reset` | Apply 300/600-second defaults in RAM, or apply and persist them. |
| `display defaults` / `display reset` | Apply 300/600-second defaults in RAM, or save defaults first and then apply them. |
When both transitions are enabled, `off-seconds` must be greater than `dim-seconds`. Applying settings counts as local UI activity. At normal boot, an initialized OLED shows a bounded five-second identity animation before the status UI begins; it scrolls the device name in yellow and draws the compact upright-terminal logo in blue. A missing OLED remains nonfatal; after reconnecting it safely, one new button press requests a bounded reprobe and is consumed without navigating.
Display settings require an available local UI task, not an attached panel. CLI and browser **Settings → Display** share the public configuration owner; concurrent mutations can report busy, and browser operations reject an intervening configuration edit rather than overwrite it. Save persists working RAM, not browser drafts. Load selects defaults when saved storage is absent/incompatible without rewriting NVS. Reset storage failure leaves RAM unchanged (commit-before-publication, no RAM rollback). Browser timeout/navigation does not cancel already-admitted work; Check Result and Refresh before retrying. [Display settings contract](web_administration.md#serial-and-display).
## Serial service
| Command | Description |
@@ -65,7 +70,7 @@ Defaults are 115200 baud, 8 data bits, no parity, one stop bit, no flow control,
| Command | Description |
|---|---|
| `broker status` / `broker clients` | Show broker state or connected clients. |
| `broker counters` / `broker clear-counters` | Show or clear broker counters. |
| `broker counters` / `broker clear-counters` | Show global totals plus active-client ID/type/pending/HWM/UART/queued/read/dropped; clear counters and seed HWM from current pending bytes without draining output. |
| `broker connect <name>` / `broker disconnect <client-id>` | Create or remove a console test client. |
| `broker request-writer <client-id>` / `broker release-writer <client-id>` | Request or relinquish the single writer lease. |
| `broker force-writer <client-id|none>` | Administratively assign or clear the writer lease. |
@@ -73,7 +78,7 @@ Defaults are 115200 baud, 8 data bits, no parity, one stop bit, no flow control,
| `broker read <client-id> [maximum-bytes]` | Read queued serial output for a client. |
| `broker events <client-id>` | Show ownership and connection events for a client. |
Each client has a generation-safe ID. There can be one writer and multiple observers; a slow observer loses only its own queued output.
Each client has a generation-safe ID. There can be one writer and multiple observers; a slow observer loses only its own queued output. HWM is bounded by 4,096 bytes; read counts transport handoff, not peer receipt. Disconnected client rows disappear, while global totals retain traffic and unread-output discards until cleared. Capture counters before disconnect. `broker read` consumes queued data and must not be used as a throughput diagnostic probe. See [Web throughput diagnostics](web_throughput_diagnostics.md).
## Native USB CDC-ACM
@@ -84,7 +89,7 @@ Each client has a generation-safe ID. There can be one writer and multiple obser
| `usb counters` / `usb clear-counters` | Show or clear USB counters. |
| `usb request-writer` / `usb release-writer` | Request or release USB writer ownership. |
Opening `/dev/ttyACM*` with DTR asserted creates the `usb-cdc` broker client, starts UART1 if needed, and requests writer ownership. It becomes an observer if another client is writer. USB data is binary-transparent. Supported host line coding is 1101000000 baud, 7/8 data bits, none/odd/even parity, and 1/2 stop bits; settings apply only while USB owns the writer lease and are not saved automatically.
Opening `/dev/ttyACM*` with DTR asserted creates the `usb-cdc` broker client, starts UART1 if needed, and requests writer ownership. It becomes an observer if another client is writer. USB data is binary-transparent. The host's CDC line coding is shown by `usb status` for diagnostics only; it does not alter UART1. Configure physical baud rate, framing, flow control, and DTR explicitly with `serial` commands and persist them with `serial save`.
## Wi-Fi
@@ -105,7 +110,18 @@ Opening `/dev/ttyACM*` with DTR asserted creates the `usb-cdc` broker client, st
| `wifi nslookup <host>` | Resolve and display unique IPv4/IPv6 addresses. |
| `wifi traceroute <host> [max-hops]` | Run IPv4 ICMP traceroute with up to 30 hops. |
`ping`, `nslookup`, and `traceroute` are root aliases. The four station-profile slots use lower priority values first. Passwords are not displayed by ordinary status output.
`ping`, `nslookup`, and `traceroute` are root aliases. The four station-profile slots use lower priority values first. Edits to a disabled profile's SSID, priority, security mode, or secret are staged in RAM and do not interrupt the current Wi-Fi connection. Enabling or disabling a profile, changing an enabled profile, or changing AP policy/configuration applies the new radio policy and may reconnect Wi-Fi. Use `wifi save` to persist working changes. Passwords are not displayed by ordinary status output.
## mDNS
| Command | Description |
|---|---|
| `mdns status` | Show the configured `sak-<suffix>.local` hostname and announcement state. |
| `mdns suffix <value>` | Set a 155-character lowercase hostname suffix in RAM. |
| `mdns save` / `mdns load` | Save the working suffix to its independent NVS record or load it. |
| `mdns defaults` / `mdns reset` | Restore the MAC-derived suffix in RAM, or restore and persist it. |
When the Wi-Fi station receives an IPv4 address, the Wi-Fi manager announces `sak-<suffix>.local`. The default suffix is the lower-case hexadecimal STA MAC address. Suffixes may contain lowercase ASCII letters, digits, and internal hyphens only. Changing a suffix while online causes a best-effort reannouncement; mDNS failures do not stop Wi-Fi, UART0, UART1, or native USB access.
## HTTPS web terminal
@@ -114,14 +130,16 @@ Opening `/dev/ttyACM*` with DTR asserted creates the `usb-cdc` broker client, st
| `web` / `web help` | Show web-service command usage. |
| `web status` | Show HTTPS and WebSocket state. |
| `web start` / `web stop` | Start or stop HTTPS service. |
| `web counters` / `web clear-counters` | Show or clear web counters. |
| `web credentials show` | Display the physical-console-only legacy migration/recovery credential; it is not a Phase 8B network login. |
| `web credentials rotate --force` | Replace the legacy recovery credential and synchronize the migrated pre-bootstrap account only. |
| `web counters` / `web clear-counters` | Show or clear ordinary HTTPS/serial WebSocket counters, independently of performance capture. |
| `web diagnostics enable\|disable\|show\|clear` | Independent opt-in admission tracing and post-TLS occupancy; not serial throughput timing. |
| `web performance enable\|disable\|show\|clear` | Default-disabled per-slot binary TX timing/count aggregates. Disable freezes; enable resumes; clear preserves enabled state. Each control operation fences in-flight samples with a new epoch. All actions print a snapshot. |
| `web certificate info` | Display certificate identity and fingerprint. |
| `web certificate rotate --force` | Replace the HTTPS certificate and private key. |
| `web reset --force` | Explicitly replace missing, incompatible, or damaged legacy credentials and web material. |
| `web certificate rotate --force` | Replace the HTTPS certificate and private key. Browser admin defers commit and HTTPS restart; both browser routes close and new certificate trust/relogin is required. UART0/admin SSH behavior is unchanged. |
| `web reset --force` | Explicitly replace HTTPS certificate/private key only, including missing, incompatible or damaged material; never changes users. |
HTTPS listens on port 443 only. Authenticate with any current user-database username/password; both `user` and `admin` roles receive the existing status and browser-terminal interface. The device serves vendored xterm.js without Internet access. Browser sessions use one-time account-bound tickets, binary WebSocket frames, and the broker's one-writer rule. Account mutations revoke only that account's tickets and sessions.
Use UART0 for quiet throughput captures (authenticated admin SSH also exposes these commands). Performance output includes current-epoch pending age and count/sum/estimated-average/max timings for queue entry to callback entry, synchronous send, and completion to drain return. These are not peer acknowledgements or scheduler-only measurements; nonempty intervals may include idle. No secrets or serial payloads are printed. See [Web throughput diagnostics](web_throughput_diagnostics.md) for exact semantics, saturation limits and the reset/burst/drain/disable/capture-before-disconnect recipe.
HTTPS listens on port 443 only. Authenticate with any current user-database username/password; both `user` and `admin` roles receive the existing status and browser-terminal interface. The device serves vendored xterm.js without Internet access. Browser sessions use one-time account-bound tickets, binary WebSocket frames, and the broker's one-writer rule. The combined **Connect**/**Disconnect** control closes the current WebSocket and pauses automatic reconnect when active; after a user-paused disconnect, it changes to **Connect** to resume connection attempts. Account mutations revoke only that account's tickets and sessions.
## SSH serial transport
@@ -130,19 +148,32 @@ HTTPS listens on port 443 only. Authenticate with any current user-database user
| `ssh` / `ssh help` | Show SSH command usage. |
| `ssh status` | Show service state and resource information. |
| `ssh start` / `ssh stop` | Start or stop the SSH server. |
| `ssh sessions` | List active SSH sessions with account, user role, authentication method, and broker role. |
| `ssh sessions` | List active SSH sessions with account, user role, authentication method, route, broker role where applicable, and admin-worker state. |
| `ssh disconnect <session-id>` | Disconnect one SSH session. |
| `ssh counters` / `ssh clear-counters` | Show or clear SSH counters. |
| `ssh host-key info` | Display the OpenSSH host-key fingerprint. |
| `ssh host-key rotate --force` | Replace the persistent SSH host key. |
| `ssh reset --force` | Explicitly replace invalid or missing SSH material. |
SSH listens on port 22 and accepts user-database passwords plus stored `ssh-ed25519` and `ecdsa-sha2-nistp256` public keys. wolfSSH verifies key possession after the database authorizes the username/key pair; unsigned key probes do not complete authentication. Both `user` and `admin` currently receive the same broker-backed interactive shell/PTY serial stream. The administrative SSH shell arrives in Phase 8C. SSH does not provide `exec`, SFTP, SCP, forwarding, or subsystems. Verify the host fingerprint from `ssh host-key info` before connecting.
SSH listens on port 22 and accepts user-database passwords plus stored `ssh-ed25519` and `ecdsa-sha2-nistp256` public keys. wolfSSH verifies key possession after the database authorizes the username/key pair; unsigned key probes do not complete authentication. A `user` receives the broker-backed UART1 serial stream. An `admin` receives the administration shell instead, does not become a broker client, and cannot acquire a UART1 writer lease.
SSH algorithm policy is explicit: KEX `curve25519-sha256`/`ecdh-sha2-nistp256`, P-256 host key, AES-128/256-GCM ciphers and `hmac-sha2-256` MAC advertisement (GCM authenticates packets). CBC/CTR-only or excluded-KEX-only clients cannot connect. There is no CLI fallback that weakens this policy; do not rotate keys merely to address a negotiation mismatch. [Exact TLS/SSH policy and upgrade contract](security_library_review.md).
SSH admission uses global boot-lifetime token buckets: handshakes and password/signed-key requests each allow a burst of six and refill one token per ten seconds; unsigned-key probes allow twelve and refill one per five seconds. The existing three-counted-attempt failure closure remains per connection. Reconnect, `ssh stop`/`ssh start`, host-key rotation and `ssh clear-counters` do not replenish these budgets. Rate denial closes the authenticating connection, not an established stream. Restrict hostile traffic and allow natural refill; repeatedly reconnecting consumes shared capacity and can prevent other users from logging in.
`ssh counters` separates handshake/verification/probe admissions and rate rejections, attempt-limit closures, backend errors and rejected methods. Admitted work is not necessarily successful or completed; probes/rate denials are not completed `auth-attempts`. These counters expose no submitted credentials and clearing them does not change enforcement. Keyboard-interactive is explicitly rejected, not merely omitted from the advertised list. See [policy and validation](security_hardening.md#9b-ssh-admission-and-credential-handling).
UART0 and admin SSH submit to one bounded queue, and one dispatcher task is the sole caller of `esp_console_run()`. Consequently, SSH commands execute the canonical UART0 handlers and produce the same status and mutation behavior rather than using a second command implementation. Remote output is routed into the authenticated session's bounded output ring; only the SSH transport task accesses wolfSSH.
UART0 and admin SSH use shared whole-line Tab completion. A unique/common prefix expands inline; a Tab that cannot extend an ambiguous prefix prints the matching candidates and redraws the unchanged input line instead of cycling candidates. Admin SSH additionally supports four-entry per-session command history with Up/Down, inline cursor editing with Left/Right, Home/End (including Pos1/Ende terminal sequences), Backspace/Delete, Ctrl-C, and visible or no-echo interactive prompts. Its history is RAM-only, private to the session, and wiped on disconnect. Ping callbacks enqueue bounded typed results so all formatting remains on the dispatcher task.
`exit`, `reboot`, `ssh stop`, session disconnect, and SSH host-key reset/rotation use bounded deferred control. The firmware waits on a best-effort basis for the administration output ring and transport TX buffer to drain before acting; this is not confirmation that the peer received the acknowledgement. The shell stops accepting another command while such an action is pending. SSH host-key replacement or service stop closes all SSH sessions; reconnect and verify the new fingerprint where applicable. TLS certificate management, Wi-Fi secrets, and interactive user passwords/keys are available to authenticated administrators and must therefore be treated as remotely accessible administrative material. `user recover --force` remains UART0-only; `user bootstrap` and all `web credentials` commands are removed. A connected administrator also cannot generate its own replacement password remotely, preventing the one-time password from being lost during self-revocation. SSH does not provide `exec`, SFTP, SCP, forwarding, or subsystems.
## Hardware diagnostics
| Command | Description |
|---|---|
| `debug status` | Show MAX3243 driver, receiver, VLD, and shutdown states. It requires UART1 to be stopped. |
| `debug transceiver <enable|disable>` | Enable or shut down the MAX3243. |
| `debug drivers <tx 0|1> <dtr 0|1> <rts 0|1>` | Drive static TX, DTR, and RTS logic levels for measurement. |
| `debug loopback-a` / `debug loopback-b` | Test MAX3243 driver/receiver loopback configurations. |
@@ -163,3 +194,5 @@ SSH listens on port 22 and accepts user-database passwords plus stored `ssh-ed25
| `debug buttons test [seconds]` | Run the bounded button event test for 130 seconds; the default is 10 seconds. |
Follow the exact wiring in [Electrical tests](electrical_tests.md) before invoking diagnostics. The OLED must be powered from 3.3 V because module I²C pull-ups may connect to `VCC`; verify that all external pull-ups also terminate at 3.3 V. Display diagnostics probe the standard SSD1315-compatible 7-bit `0x3c`/`0x3d` addresses. The currently tested module acknowledges at `0x3c`, whose 8-bit write/read forms are `0x78`/`0x79`; an explicit `scan --force` is available only for the dedicated local-UI bus. Diagnostics initially run at 100 kHz and treat an absent display as nonfatal. RS-232 diagnostics that require UART1 refuse to use it until `serial stop` releases it. The RGB LED shows test state: blue idle, yellow/orange running, green passed, red failed.
HTTPS storage migration preserves the exact TLS identity and commits TLS-only v2 before publication. Older v1-only firmware cannot read v2. Logical NVS replacement is not secure flash erasure; no factory erase is required. See [legacy removal](legacy_credential_removal.md).
+189
View File
@@ -0,0 +1,189 @@
# Broader dependency advisory coverage
Review date: **2026-09-16**. Documentation-only, finite snapshot; **not security certification, upgrade approval, or Phase 9 sign-off**.
## Result and authority
**New actionable maintenance finding:** the installed IDF 5.5 Wi-Fi bundle predates the official 5.5.3 correction for management-frame memory corruption. The project's PMF-capable WPA2/WPA3 SoftAP supplies the relevant supported configuration. Prioritize a coherent vendor-bundle update/backport investigation; see the exact evidence and limitations below. This is a current-feature exposure candidate supported by the vendor's release/fix description, **not a demonstrated device exploit or independently audited binary implementation**.
No additional current-path security correction was established for `esp_tinyusb`, TinyUSB, mDNS, LED strip, or the two vendored browser packages in this finite search. That statement does not establish that these dependencies are vulnerability-free.
- [IDF security review](idf_security_review.md) remains authoritative for its detailed mbedTLS findings, DHCP-server/EMS/X.509 backports, WebSocket subprotocol exclusion, and first-page feature dispositions. This document completes the previously omitted **IDF advisory-index pages**, without repeating those audits or claiming a fresh override verification.
- [Wolf security review](wolf_security_review.md), [key-validation review](ssh_key_validation_review.md), and [remaining parser review](ssh_parser_remaining_review.md) retain their scopes and outstanding gates. Wolf advisories were not re-searched here.
- Only `docs/dependency_advisory_coverage.md` was created. No sources, pins, manifests, assets, generated outputs, configuration, builds, tests, or devices were changed/run. Existing build metadata was read, not regenerated; it does not establish executable freshness or device state.
## Baseline actually inspected
Managed manifests were read from installed component directories, not inferred from the application's semver constraints. The application requests `mdns: ^1.8.2`, but installed mDNS is **1.12.0**.
| Dependency | Installed/source identity | Current use |
| --- | --- | --- |
| ESP-IDF | Existing reviewed 5.5.0 baseline; additional original SDK sources and Wi-Fi archives inspected below | Wi-Fi AP/STA, lwIP, HTTPS; existing local security overrides remain part of effective inputs |
| `espressif/esp_tinyusb` | **2.2.1**, manifest commit `8e779566ef71d43928cbf7e125e8eb54bab3f542`, path `device/esp_tinyusb` | CDC device wrapper |
| `espressif/tinyusb` | **0.21.0~1**, manifest commit `7049c58a0e895acc92c6407574b05b5536eddfc8` | Espressif fork, not interchangeable with an unqualified upstream 0.21.0 claim |
| `espressif/mdns` | **1.12.0**, manifest commit `db06b19b7be729c163d346f62ec0eba01047b7f1` | STA hostname responder; no registered DNS-SD services or browser/query application calls |
| `espressif/led_strip` | **3.0.3**, manifest commit `7cd447361ca2f0a1c01aa3089e3031f6171b6c7e` | One WS2812, RMT, no DMA |
| `@xterm/xterm` | **5.5.0** per [asset provenance](../web_assets/SOURCES.md); local JS SHA-256 `1f991ac3b4b283ebf96e60ae23a00a52765dd3a2e46fa6fdda9f1aab032f7495` rechecked | Serial and admin browser terminals |
| `@xterm/addon-fit` | **0.10.0**; local JS SHA-256 `bdaefa370b1bfc42ee88d46fe6072400902a4d4b2d45cd93438dda9b23c97089` rechecked | Only loaded addon |
Browser version attribution is to the recorded exact-package provenance plus matching local hashes. No npm install, registry dependency resolution, asset download, decompression, or embedded-asset regeneration was performed. Generated compressed arrays were not independently re-hashed in this slice.
Local configuration evidence is `.pio/build/esp32-s3-devkitc-1-n16r8/config/sdkconfig.h`; compilation evidence is a filtered read of the existing compilation database. Source references under `components/` below are relative to `/home/mscholz/.platformio/packages/framework-espidf/`.
## Finite search ledger: URLs checked and stopping rules
The search ended at the following dated snapshot. Empty official repository advisories mean **no published advisories returned by that endpoint**, not no CVEs anywhere, no undisclosed defects, or a security guarantee. GitHub releases and component changelogs are different publication channels; an empty Releases list is not evidence that component versions stopped shipping.
### IDF advisory index: all snapshot pages
Fetched the official HTML index [page 1](https://github.com/espressif/esp-idf/security/advisories), [page 2](https://github.com/espressif/esp-idf/security/advisories?page=2), and [page 3](https://github.com/espressif/esp-idf/security/advisories?page=3): **10 + 10 + 2 = 22 entries**, oldest June 23, 2022, newest September 3, 2026. Page 3 is the terminal listed page. Full advisory descriptions were read from the official [repository advisory API](https://api.github.com/repos/espressif/esp-idf/security-advisories?per_page=100&page=1), not merely titles.
The [API page=2 request](https://api.github.com/repos/espressif/esp-idf/security-advisories?per_page=100&page=2) unexpectedly returned the same 22 entries with no Link header. **It was not treated as an empty-page proof or 22 additional advisories.** The HTML pagination and unique IDs establish the 22-entry snapshot boundary. No unbounded pagination or general web search followed.
### Other official advisory channels
Each URL below returned the stated number of public advisory records, with no next-page Link header:
| Official endpoint checked | Records | Disposition |
| --- | ---: | --- |
| [esp-usb](https://api.github.com/repos/espressif/esp-usb/security-advisories?per_page=100&page=1) | 3 | HID/UVC **host** issues; device CDC exclusion below |
| [hathach/tinyusb](https://api.github.com/repos/hathach/tinyusb/security-advisories?per_page=100&page=1) | 0 | No published records returned |
| [espressif/tinyusb](https://api.github.com/repos/espressif/tinyusb/security-advisories?per_page=100&page=1) | 0 | Fork checked separately |
| [esp-protocols](https://api.github.com/repos/espressif/esp-protocols/security-advisories?per_page=100&page=1) | 0 | mDNS release fixes screened separately |
| [idf-extra-components](https://api.github.com/repos/espressif/idf-extra-components/security-advisories?per_page=100&page=1) | 0 | LED changelog screened separately |
| [xterm.js](https://api.github.com/repos/xtermjs/xterm.js/security-advisories?per_page=100&page=1) | 0 | Browser release fixes screened separately |
### Release/changelog boundary
- **IDF:** [release API page 1](https://api.github.com/repos/espressif/esp-idf/releases?per_page=100&page=1) returned 100 records; [page 2](https://api.github.com/repos/espressif/esp-idf/releases?per_page=100&page=2) returned 64 and no additional 5.5 tags. Screened published stable **5.5.15.5.5** GitHub release bodies for explicit security, vulnerability, overflow, out-of-bounds, corruption, UAF and double-free descriptions; followed the relevant additional candidates below. This is not a line-by-line audit of every bugfix or another IDF branch. [5.5.4 body](https://api.github.com/repos/espressif/esp-idf/releases/tags/v5.5.4) mainly describes a NimBLE regression. The linked full [5.5.4](https://release-notes.espressif.tools/release/5.5.4) and [5.5.5](https://release-notes.espressif.tools/release/5.5.5) release databases returned **no textual content** through the fetch tool: their database-only contents are an explicit coverage gap, not reviewed pages.
- **esp-usb:** [Releases API](https://api.github.com/repos/espressif/esp-usb/releases?per_page=100&page=1) returned zero. Read the official [component changelog](https://raw.githubusercontent.com/espressif/esp-usb/master/device/esp_tinyusb/CHANGELOG.md) through **2.3.0**, and [current manifest](https://api.github.com/repos/espressif/esp-usb/contents/device/esp_tinyusb/idf_component.yml), also 2.3.0. This establishes a changelog ceiling, not proof of registry publication or compatibility.
- **TinyUSB:** [upstream Releases API](https://api.github.com/repos/hathach/tinyusb/releases?per_page=100&page=1) returned 18 records, newest **0.21.0**, whose full release notes were read. [Fork Releases API](https://api.github.com/repos/espressif/tinyusb/releases?per_page=100&page=1) returned zero. [Installed fork commit API](https://api.github.com/repos/espressif/tinyusb/commits/7049c58a0e895acc92c6407574b05b5536eddfc8) identifies the merge “Necessary fixes for TinyUSB 0.21.” No later published upstream release was present. Two legacy-path requests, [upstream](https://raw.githubusercontent.com/hathach/tinyusb/master/docs/info/changelog.rst) and [fork](https://raw.githubusercontent.com/espressif/tinyusb/master/docs/info/changelog.rst), returned 404; [docs listing](https://api.github.com/repos/hathach/tinyusb/contents/docs) then [changelog directory](https://api.github.com/repos/hathach/tinyusb/contents/docs/changelog) resolved the moved layout and confirmed 0.21.0 as its highest listed version. Unreleased commits/PRs were not exhaustively searched.
- **mDNS:** [esp-protocols release page 1](https://api.github.com/repos/espressif/esp-protocols/releases?per_page=100&page=1) returned 100 records and [page 2](https://api.github.com/repos/espressif/esp-protocols/releases?per_page=100&page=2) 37. Post-pin mDNS releases in that finite list are **1.13.0 (September 14)** and **1.13.1 (September 15)**. Their notes and both production-source fix patches were inspected; other monorepo components are outside this slice.
- **LED:** [Releases API](https://api.github.com/repos/espressif/idf-extra-components/releases?per_page=100&page=1) returned zero. Official [LED changelog](https://raw.githubusercontent.com/espressif/idf-extra-components/master/led_strip/CHANGELOG.md) ends at **3.0.3**, matching installed version.
- **xterm:** [Releases API](https://api.github.com/repos/xtermjs/xterm.js/releases?per_page=100&page=1) returned 89 records with no pagination. Read **5.5.0** baseline and **6.0.0 (December 22, 2025)** post-pin release notes. 5.5.0 explicitly lists addon-fit 0.10.0 as compatible. Screened 6.0.0's security-relevant addon fixes and actual integration below; did not mistake npm development/demo dependency updates for packages served by this firmware.
This completes the **declared finite search**, not every possible vendor/CVE channel. NVD, OSV, npm's global advisory database, private advisories, all historical SDK subdependency advisories, every unreleased commit, and all non-security-labelled release regressions were not exhaustively searched. The failed full-release-database fetches remain visible above.
## IDF pages 23: all twelve previously omitted entries
All linked advisory bodies below were included in the fetched official API response. “Not-current-path” does not mean the underlying library is patched.
| Advisory / CVE | Required feature and snapshot disposition |
| --- | --- |
| [GHSA-9j5x-rf36-54x9](https://github.com/espressif/esp-idf/security/advisories/GHSA-9j5x-rf36-54x9), CVE-2026-25508 | BLE provisioning ATT prepared-write length accumulation. **Not-current-path:** Bluetooth/provisioning absent. |
| [GHSA-m2h2-683f-9mw7](https://github.com/espressif/esp-idf/security/advisories/GHSA-m2h2-683f-9mw7), CVE-2026-25532 | WPS enrollee fragment underflow requires initiating WPS PBC/PIN pairing. **Not-current-path:** no application `esp_wifi_wps_*` calls; no enabled WPS setting in the inspected generated header. Ordinary PSK/SAE association is not WPS. |
| [GHSA-hmjj-rjvv-w8pq](https://github.com/espressif/esp-idf/security/advisories/GHSA-hmjj-rjvv-w8pq), CVE-2025-68473 | Bluedroid Classic SDP UUID-array overflow. **Not-current-path:** Bluetooth absent. |
| [GHSA-43gh-7r4f-qp57](https://github.com/espressif/esp-idf/security/advisories/GHSA-43gh-7r4f-qp57), CVE-2025-68474 | Bluedroid Classic AVRCP vendor-command allocation/write. **Not-current-path:** Bluetooth absent. |
| [GHSA-vcw6-jc3p-4gj8](https://github.com/espressif/esp-idf/security/advisories/GHSA-vcw6-jc3p-4gj8), CVE-2025-65092 | ESP32-P4 hardware JPEG header parser. **Not-current-path:** ESP32-S3, no JPEG driver compilation inputs. |
| [GHSA-qhf9-vr2h-jh96](https://github.com/espressif/esp-idf/security/advisories/GHSA-qhf9-vr2h-jh96), CVE-2025-66409 | Bluedroid Classic AVRCP vendor-command read. **Not-current-path:** Bluetooth absent. |
| [GHSA-8mg7-9qpg-p92v](https://github.com/espressif/esp-idf/security/advisories/GHSA-8mg7-9qpg-p92v), CVE-2025-64342 | Original ESP32 Bluetooth controller invalid access address. **Not-current-path:** S3 explicitly outside affected chip family; Bluetooth also absent. |
| [GHSA-9w88-r2vm-qfc4](https://github.com/espressif/esp-idf/security/advisories/GHSA-9w88-r2vm-qfc4), CVE-2025-55297 | BluFi example credential/DH buffers. **Not-current-path:** no BluFi integration, no Bluetooth host. Not a generic flaw in this project's Wi-Fi password handling. |
| [GHSA-hqhh-cp47-fv5g](https://github.com/espressif/esp-idf/security/advisories/GHSA-hqhh-cp47-fv5g), CVE-2025-52471 | ESP-NOW receive underflow. **Not-current-path:** no application ESP-NOW initialization or receive callback. Does not prove opaque Wi-Fi archives are globally fixed. |
| [GHSA-wm57-466g-mhrr](https://github.com/espressif/esp-idf/security/advisories/GHSA-wm57-466g-mhrr), CVE-2024-53845 | ESPTouch v2 constant AES-CBC IV. **Not-current-path:** no SmartConfig/ESPTouch provisioning calls; PSK/SAE manager is separate. |
| [GHSA-22x6-3756-pfp8](https://github.com/espressif/esp-idf/security/advisories/GHSA-22x6-3756-pfp8), CVE-2024-28183 | Physical flash TOCTOU against anti-rollback. **Excluded/not configured:** no enabled `CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK`; physical firmware replacement is outside current review model. No claim of secure boot or rollback protection. |
| [GHSA-7f7f-jj2q-28wm](https://github.com/espressif/esp-idf/security/advisories/GHSA-7f7f-jj2q-28wm), CVE-2022-24893 | BLE Mesh provisioning `SegN` bounds. **Not-current-path:** Bluetooth/Mesh absent. |
Rechecked local evidence: target `esp32s3`/Xtensa; no enabled `CONFIG_BT_ENABLED`; compilation-entry counts `/bt/host/`, `esp_driver_jpeg`, `/esp_tee/` each zero. Targeted application searches for WPS, ESP-NOW, SmartConfig, BluFi and protocomm found no integration. These exclusions do not depend on later release tables implicitly excluding 5.5.0. Revisit before enabling these features.
Together with the ten entries already dispositioned in [the IDF review](idf_security_review.md#bounded-idf-advisory-index-snapshot-disabledunused-features), this accounts for all **22 unique IDs** in the dated official index.
## New release-note finding: Wi-Fi management-frame corruption
**Priority: prompt coherent vendor correction review for PMF-capable SoftAP operation. Not fixed by existing DHCP/mbedTLS overrides.** Reported to the parent during this review.
Official [IDF 5.5.3 release](https://github.com/espressif/esp-idf/releases/tag/v5.5.3) says “Fixed memory corruption issue by ensuring management frames are only encrypted when they are robust management frames,” referencing **`a3927641`**. Fetched [patch](https://github.com/espressif/esp-idf/commit/a3927641.patch) and [commit API](https://api.github.com/repos/espressif/esp-idf/commits/a3927641): merge commit **`a3927641bfd0aedfaab3514cba3d7fb01378ce4d`**, contained patch commit **`caf4cad3b422be5c2f93afeff4cd07796a262b46`**. The different patch-header ID is the contained commit, not an invented match to the merge hash.
The patch description states that when the supplicant sends an authentication response for an already-connected station with installed keys, unconditional management-packet encryption based on `bss->pmf_enable` assumed extra encryption-header space that was not present. It also mentions incorrect allocation due to RSN IE length mismatch; that second trigger was not independently established for the project's short configured IE set.
### Current application prerequisites and original interface
`src/wifi_manager.c:315331`, `configure_ap()`:
```c
wifi_config.ap.authmode = WIFI_AUTH_WPA2_WPA3_PSK;
wifi_config.ap.max_connection = 4U;
wifi_config.ap.pmf_cfg.capable = true;
wifi_config.ap.pmf_cfg.required = false;
wifi_config.ap.sae_pwe_h2e = WPA3_SAE_PWE_BOTH;
esp_err_t error = esp_wifi_set_config(WIFI_IF_AP, &wifi_config);
```
`required=false` does **not** disable negotiated PMF. AP/APSTA is a supported runtime policy (`wifi_manager.c:382,646`), not an unused SDK feature; generated `CONFIG_ESP_WIFI_SOFTAP_SUPPORT=1` and WPA3 SAE support are enabled. Exposure is conditional on AP operation and the vendor-described station/key/PMF state. No claim is made that an arbitrary unassociated peer can exploit it.
Original configured compilation input `components/wpa_supplicant/esp_supplicant/src/esp_wpa_main.c:146155` still contains:
```c
uint8_t *wpa_ap_get_wpa_ie(uint8_t *ie_len)
{
/* ... existing hostapd checks ... */
*ie_len = hapd->wpa_auth->wpa_ie_len;
return hapd->wpa_auth->wpa_ie;
}
```
`esp_wifi_driver.h:133` has the matching `uint8_t *len` callback signature; `esp_wpa_main.c:489496` registers it under `CONFIG_ESP_WIFI_SOFTAP_SUPPORT`. This is an interface/provenance marker for the old bundle, **not the source location of the opaque management-encryption defect**.
### Exact binary-bundle provenance
The official fix changes **both** callback signatures to `size_t *` and replaces `components/esp_wifi/lib` with **`a4e903fe43bf09a95022f9802db43d39740ccc0b`**. A C-only signature edit is not an adequate or ABI-safe implementation of this correction.
A local `git rev-parse` in the packaged Wi-Fi submodule failed because its Git metadata is not usable. Instead, calculated Git blob SHA-1 values directly from all seven installed `esp32s3/*.a` files and compared them with official content metadata:
- [IDF v5.5 submodule pointer](https://api.github.com/repos/espressif/esp-idf/contents/components/esp_wifi/lib?ref=v5.5): **`8a1b7bbc00e895d040c5c9a6fb9d1db2bbfc7958`**.
- [Baseline ESP32-S3 archive listing](https://api.github.com/repos/espressif/esp32-wifi-lib/contents/esp32s3?ref=8a1b7bbc00e895d040c5c9a6fb9d1db2bbfc7958): **all seven local blob IDs match** (`core`, `espnow`, `mesh`, `net80211`, `pp`, `smartconfig`, `wapi`).
- [Corrected bundle listing](https://api.github.com/repos/espressif/esp32-wifi-lib/contents/esp32s3?ref=a4e903fe43bf09a95022f9802db43d39740ccc0b): all seven differ from installed.
- Installed `libnet80211.a`: Git blob `6ee20bec142638dc0a442b9642de9fa62db6ddd0`, SHA-256 **`dcb524dda8563976cf1a97d4398c7b06cf024b7ef9a5f07788e84c88792d8071`**; corrected bundle's Git blob is `8ce8a2a6a9a753e31508bd609bf0a0d1d44c332f`.
This confirms the installed stock-baseline bundle, not a hidden same-version binary replacement carrying the published fix. It does not independently reverse-engineer the affected routine or establish a reliable remote attack.
**Parent action:** investigate a maintained IDF/vendor bundle carrying the complete correction, with matching supplicant ABI and all existing source-pinned overrides rebased and revalidated. Do not replace one archive or change only the callback type. Preserve USB/UART0 recovery and broker isolation. Target regression should cover PMF-capable WPA2/WPA3 SoftAP association, repeated authentication/reassociation with keys already installed, APSTA transitions and loaded service recovery. These tests were **not performed**. No blind recommendation to weaken PMF or disable recovery AP policy is made.
## Additional IDF release candidates screened
These are supplemental to, not replacements for, the existing detailed IDF review.
| Release candidate / fetched evidence | Actual-use disposition |
| --- | --- |
| 5.5.1 DHCP **client** option/HW-ID length, [bcd56c74 patch](https://github.com/espressif/esp-idf/commit/bcd56c74.patch), contained commit `1ad41e589ff7296c484ba64f206f2278a09dab37` | Original `lwip_default_hooks.c:262269,293300` retains old checks; generated option length **68**, vendor class ID disabled. Client path is used, but current hostname is fixed `CONFIG_LWIP_LOCAL_HOSTNAME="espressif"` and no application `esp_netif_set_hostname()` call exists. Inspected `dhcp_select()`/`dhcp_discover()` build bounded fixed options, short hostname and six-byte MAC, leaving space in 68 bytes; no current long-option trigger established. mDNS suffix is **not** the DHCP hostname. Revisit/backport before longer hostnames or extra options. Distinct from already fixed DHCP **server** CVE-2026-45160. |
| 5.5.2 `esp_timer_dump()` overflow, [a511f3be patch](https://github.com/espressif/esp-idf/commit/a511f3be.patch), contained commit `ec71bd189f6ef42aff2daa99f35d98611bb9faa3` | Original `esp_timer.c:613,616` retains old line-size constants 90/46 (fix 103/47) and profiling branch's incorrect size addition. No application dump call; timer profiling absent. **Not-current application path**, not a globally patched timer library or a ban on ordinary timers. |
| 5.5.3 HTTP **client** Digest OOB read, [6d0a7a01 patch](https://github.com/espressif/esp-idf/commit/6d0a7a01.patch), contained commit `bbcc13be8b38283547883bfee4920331bea80cd1` | Original `esp_http_client/lib/http_auth.c:131132` uses fixed-length `memcmp` on server algorithm string; no application HTTP-client/Digest consumer. **Not-current-path**; the HTTPS server's cookie login is not this function. |
| 5.5.3 AES DMA/PSRAM cache ordering, [3f10cdab patch](https://github.com/espressif/esp-idf/commit/3f10cdab.patch), contained commits `525ef3a2eab239e30cd4cc62f6d23b61743fe4c1`, `0742f3fce3a1779c63ec286342f6d9799e12822f` | Original `esp_aes_dma_core.c:11211128` invalidates after DMA; file is a configured compilation input. S3 has `SOC_PSRAM_DMA_CAPABLE=1`, so **target name alone does not exclude it**. Generated `CONFIG_MBEDTLS_HARDWARE_AES` absent; `esp_config.h:150153` therefore undefines `MBEDTLS_AES_ALT`, and no application `esp_aes_*` call was found. No current application mbedTLS hardware-AES path established. Direct SDK/opaque-radio consumers and their destination buffers were not exhaustively traced: retain this as a **residual SDK applicability question**, not global exclusion or a verified current HTTPS corruption finding. |
| Bluetooth, provisioning, JPEG, TREL/OpenThread, other-chip secure-boot/flash-encryption release fixes | Bluetooth/JPEG/provisioning exclusions above apply; project is not an OpenThread/TREL application. Physical security and other-chip configuration changes do not establish an S3 network attack. These release categories were screened, not their entire implementations audited. |
## Managed USB applicability
Published esp-usb records are [GHSA-gp8r-qjfr-gqfv](https://github.com/espressif/esp-usb/security/advisories/GHSA-gp8r-qjfr-gqfv) (HID host close double-free race), [GHSA-2pm2-62mr-c9x7](https://github.com/espressif/esp-usb/security/advisories/GHSA-2pm2-62mr-c9x7) (HID host descriptor UAF), and [GHSA-g65h-9ggq-9827](https://github.com/espressif/esp-usb/security/advisories/GHSA-g65h-9ggq-9827) (UVC host descriptor-printing stack overflow). Official affected components are `usb_host_hid` through 1.0.4 and `usb_host_uvc` through 2.3.1, **not similarly numbered esp_tinyusb releases**.
`src/usb_cdc_transport.c:763781` calls `TINYUSB_DEFAULT_CONFIG(device_event_callback)`, `tinyusb_driver_install(&usb_config)`, and `tinyusb_cdcacm_init(&cdc_config)` for `TINYUSB_CDC_ACM_0`, using the S3 internal full-speed PHY. Generated settings enable one CDC, 1,024-byte RX/TX buffers, 512-byte CDC endpoint buffer, no HID/MIDI/vendor instances, no DFU/network class. `esp_tinyusb/include/tusb_config.h:88` enables device mode and maps class counts at lines 192201. Filtered compilation database contains **zero** HID-host, UVC-host, or TinyUSB `src/host` entries. Thus all three published host advisories are **not-current-path**, without relying on “USB requires physical access” as an exclusion.
Post-pin wrapper changelog 2.3.0 describes MTP, IDF6 MSC compatibility and power-management/light-sleep integration, not a newly identified CDC memory-safety fix. MSC/MTP is not used; `CONFIG_PM_ENABLE` absent. Upstream TinyUSB's newest published 0.21.0 notes include EP0 OUT copy clamping, HID descriptor bounds and MSC callback-size caps. These are baseline-release fixes rather than evidence that a later release must be backported. Spot-check: installed `src/device/usbd.c:881,920` limits `data_len` to `wLength` and clamps transferred bytes to remaining control data. SHA-256 **`38de54351d81878e6543f2b022d0c39f45d28c8f0888491796398dec45e727be`**. This is not a complete USB control-request audit or proof every upstream fix is in the fork.
## mDNS post-pin fixes
mDNS is network-reachable when STA discovery starts: `src/wifi_manager.c:117` calls the application service, whose `src/mdns_service.c:154160` calls `mdns_init()`, `mdns_hostname_set()` and `mdns_instance_name_set()`. It is **not globally disabled**. The generated profile enables only predefined STA, maximum one interface/service, and has no `CONFIG_MDNS_ENABLE_BROWSE`. No application `mdns_service_add*`, `mdns_query_*` or `mdns_browse_*` calls were found.
1. **1.13.0 duplicate DNS-SD question expansion:** fetched [c56c725dd5e77c83c1a0683fce6dd3521e05cea2](https://github.com/espressif/esp-protocols/commit/c56c725d.patch). Upstream test explicitly calls repeated `_services._dns-sd._udp.local` PTR questions “heap amplification”: each expands the registered service list. Installed `mdns_receive.c:711716` lacks the new `if (parsed_packet->discovery) continue;` guard and allocates inside `while (a)` after `a = mdns_priv_get_services()`. **Primitive unpatched, no current amplification trigger:** no services registered; `mdns_responder.c:3845` zeroes the server and `:102104` returns its initially empty service list. A hostname/instance label is not a service registration, and `MAX_SERVICES=1` is a capacity, not one active service. Reassess before advertising `_https`, `_ssh`, or any DNS-SD service; the guard is a sensible narrow defense-in-depth candidate, not a demonstrated current responder DoS fix.
2. **1.13.1 staged-IP NUL termination:** fetched [b370a9abc29390b4adc612d251cc2dbbb325ff6f](https://github.com/espressif/esp-protocols/commit/b370a9ab.patch). Adds `new_staged_ip->hostname[MDNS_NAME_BUF_LEN - 1] = '\0';`; commit describes a GCC truncation warning. The installed receiver does **not** contain `rx_staged_ip_add()`; browsing is also disabled. Do not assert an installed unterminated-buffer vulnerability simply from version ordering or the release-note title. No current-path defect established.
Installed receiver SHA-256: **`9ada93eb2f89080a28bf2a849871e054032f06889c40397555de527af0e3d7bd`**. Earlier mDNS release notes mention parser/browse hardening, but this slice did not re-audit every pre-pin fix or equate the absence of a GHSA with a safe parser.
## LED strip and offline browser assets
**LED:** `src/status_led.c:1536` fixes `max_leds=1`, WS2812/GRB, RMT, `with_dma=false`; `:7277` sets pixel index zero then refreshes. No peer-controlled strip allocation or index is supplied. No later release/security correction was identified in the declared official channels; no blanket driver safety claim.
**Browser integration:** `src/web_ui.c:15071519` creates a terminal with `allowProposedApi:false`, loads only `FitAddon`, and `:15521554` does the same for admin. `:1531` feeds received bytes to `target.write(new Uint8Array(data), ...)`. Serial-device output is not automatically trustworthy just because a browser session authenticated; escape-sequence rendering remains a real boundary.
Post-pin 6.0.0 candidate dispositions:
- [PR5020 patch](https://github.com/xtermjs/xterm.js/pull/5020.patch), “Escape Unsafe HTML Characters in addon-serialize,” changes **addon-serialize HTML output**, not the core terminal renderer. That addon and `serializeAsHTML()` integration are absent. **Not-current-path**, not an assertion that all xterm 5.5 HTML rendering was repaired.
- [PR5355 patch](https://github.com/xtermjs/xterm.js/pull/5355.patch), “Add note about reverse tabnapping,” is **documentation-only in addon-web-links typings**, warning about iframe/custom-handler behavior. The addon is not loaded. Do not report this as a core security fix missing from 5.5.0.
- Core OSC 8 links exist even without addon-web-links. Checked [5.5.0 upstream provider](https://raw.githubusercontent.com/xtermjs/xterm.js/5.5.0/src/browser/OscLinkProvider.ts) and targeted matching snippets in hash-verified local JS: absent `allowNonHttpProtocols`, protocols are limited to `http:`/`https:`; default activation confirms navigation and sets `newWindow.opener=null` before assigning location. Application supplies no custom `linkHandler`. This rebuts an automatic arbitrary-protocol/tabnapping finding from these release notes, not all phishing/social-engineering risks or browser implementation issues.
- Other release-note changes include OSC parsing/correctness, readonly behavior for disabled input, selection/renderer fixes, and new clipboard/progress functionality. Only fit is installed; search, image, serialize, web-links, ligatures, clipboard and WebGL addons are not supplied. Build/demo updates to Express, ws, webpack, axios, etc. are not automatically firmware/browser runtime dependencies. No additional current security trigger was established from that release-note screen.
A future xterm upgrade would need deliberate addon compatibility, offline asset provenance/regeneration and browser regression review; no asset or version change is authorized by this document.
## Validation and handoff limits
Performed: official bounded advisory/release fetches; all 22 IDF index-entry accounting; targeted source/config/caller and configured-input inspection; managed manifest checks; two local web-asset hash checks; seven Wi-Fi archive Git-blob comparisons; source snippet/hash capture. Final checks passed for document whitespace/final newline, six local links, dated scope, and twelve additional IDF plus three USB advisory IDs. Document-scoped `git diff --check` also passed (the new untracked file was explicitly checked by Python). Final Git status showed concurrent changes in release-notice/validation/icon-provenance files outside this ownership scope; none were edited or reverted here. No firmware build, host regression execution, browser test, USB transaction, radio packet test, fault injection, upload, monitor, erase, or target resource measurement was performed.
**Parent summary:** carry forward the Wi-Fi bundle correction investigation and the residual direct-SDK AES-DMA applicability question. Do not describe either as implemented, or the AES question as an established current-path vulnerability. Preserve prior detailed wolf/IDF review authority and all existing mitigations. The omitted official IDF index pages and named managed/browser publication channels now have a finite dated coverage record; full release-database contents, unpublished issues, opaque implementation analysis and hardware acceptance remain outside the completed evidence. Re-run a bounded publication check before release or when dependencies, enabled features, callers, or trust boundaries change.
+207
View File
@@ -0,0 +1,207 @@
# Dependency license inventory — Phase 9D
## Implementation addendum — updated 2026-09-18
**Missing generated modification/date notices: resolved; current count is nine C sources plus one header.** `tools/security_overrides.py` prepends the baseline project modification notice dated **2026-09-15**, identifying the editable generator and warning against editing derived copies. The wolfSSH `internal.c`, added `ssh.c` and generated `wolfssh/internal.h` also receive a prominent **2026-09-16** ordering-profile/provenance notice. Exact original hashes and exact-once edits remain required; upstream notices are retained. The header is a PUBLIC forced build input, not a C source. Both new mbedTLS copies retain their original Mbed TLS Contributors copyright and **`Apache-2.0 OR GPL-2.0-or-later`** SPDX header; the Apache-2.0 selection in this inventory is unchanged. This resolves the narrow notice-generation finding, **not release packaging or license clearance**.
Offline notice assembly tooling is implemented; actual firmware/device/browser delivery, radio-blob corresponding-source/exception questions, preferred-source packaging, wolfSSH license-package discrepancy, manual bitmap/mockup provenance limits and release-specific runtime/bootloader review remain open; [exact retained SVG provenance](icon_provenance.md) is resolved. [Offline notice assembly](release_packaging.md) is implemented by [tools/release_notices.py](../tools/release_notices.py): 75 mandatory hash/size-pinned inputs (nine IDF/toolchain notice entries semantically rebased for the candidate; the other 66 unchanged), deterministic bounded outputs, fail-closed preflight and no overwrite/fetch/build/device access. Supplied agent evidence: **36 notice fixture tests PASS; two actual bundles verified deterministic, each 77 files / 4,433,930 bytes**. This includes retained SVGs and [exact icon provenance](icon_provenance.md), not corresponding-source delivery or legal clearance. These are agent measurements, not a parent rebuild or reassembly in this documentation turn. Include `cmake/wolf_crypto_policy.{cmake,h}` and the ordering inputs described below with the reproducible build/source package. The IDF 5.5.3 migration is now integrated in the isolated validated candidate; this documentation update performs no upgrade, asset regeneration or device operation. Root pins select platform 6.13.0 / framework 3.50503.0 / both toolchains 14.2.0+20251107; see [integration and build/closure limits](idf_candidate_integration.md). The detailed 5.5.0 SDK/runtime inventory below remains historical, not a newly exhaustive 5.5.3 license audit.
## Historical inventory baseline — 2026-09-15
The original audit scope and artifact counts below describe the audit-time snapshot; generated-source status and the release checklist are updated explicitly where noted. Original research evidence is retained, not a claim that all artifacts were rebuilt or re-audited here.
Local, bounded audit: **2026-09-15**. This is an engineering inventory and release checklist, not legal advice, a legal compatibility opinion, an upstream currency check, or exhaustive file-by-file coverage. No network requests, dependency changes, asset regeneration, firmware build, tests, or device operations were performed. Hardware validation remains deferred for **Phase 9 as a whole**.
## Evidence and counting boundaries
- Project license: [root LICENSE](../LICENSE), [README license declaration](../README.md#license), and representative `src/` SPDX headers establish **`GPL-3.0-only`**, not “or later.” Dependencies keep their own notices and grants.
- Resolution: [application manifest](../src/idf_component.yml), [dependencies.lock](../dependencies.lock), [platformio.ini](../platformio.ini), all six installed managed manifests and top-level license files.
- **7 lock entries = 6 managed packages + IDF**. Managed packages comprise **5 direct + 1 transitive**. IDF is also a direct requirement. wolfSSH uses wolfSSL in this integration, although its resolved manifest declares no dependency edge; both are explicitly pinned by the application.
- Platform: `platformio/espressif32@6.12.0`; installed SDK package `framework-espidf` **3.50500.0**, SDK **5.5.0**, compiler package `toolchain-xtensa-esp-elf` **14.2.0+20241119**. Installed package metadata, not merely requested ranges, was checked.
- Existing `.pio/build/esp32-s3-devkitc-1-n16r8/project_description.json` names **113 nonempty configured components**. Its adjacent `esp32_serial_swiss_army_knife.map` has **68 distinct archive basenames** in the initial “Archive member included” region, before “Discarded input sections.” These are build-selection evidence, **not** 113 independently audited packages or proof all selected bytes survive section garbage collection. These pre-existing artifacts were not rebuilt or certified fresh.
- Below: **6 managed rows, 18 SDK/runtime inventory groups, 2 browser packages, and 1 icon collection containing 2 SVGs**. Groups are not a complete SBOM and must not be summed into a unique package count (e.g. bundled libraries are inside IDF).
- [Web provenance](../web_assets/SOURCES.md): all **8 recorded SHA-256 values** matched (3 JS/CSS, 2 license files, 3 gzip artifacts). Two SVG IDs and the attribution in `src/local_status_ui.c:158161` were inspected for provenance only. Logo ownership is the project's recorded claim, not independently established authorship.
- Initial Git status was clean. An unrelated untracked `docs/security_operations.md` appeared during this audit and was left unread and untouched. This audit creates only this file.
### Local path notation
Repository paths below are relative to the repository root. Installed paths are expressed using these **audit-time roots**, not environment variables that must already be set:
- `SDK/` = `/home/mscholz/.platformio/packages/framework-espidf/`
- `TC/` = `/home/mscholz/.platformio/packages/toolchain-xtensa-esp-elf/`
- `BUILD/` = `.pio/build/esp32-s3-devkitc-1-n16r8/`
`SDK/package.json` identifies <https://github.com/espressif/esp-idf>; `SDK/version.txt` says `5.5.0`. `SDK/LICENSE` is Apache-2.0. **There is no `SDK/COPYRIGHT` in this installed package**, and its `README.md` contains no license/copyright section. Do not assume the root Apache text covers every bundled library or is a complete attribution list. Component license files and source notice headers supply important exceptions.
## Managed components: complete lock-level inventory
All rows have a checked `managed_components/<directory>/idf_component.yml`. Versions below match the lock and installed manifests. Exact component hashes remain in `dependencies.lock`; a manifest-only assertion is not a cryptographic revalidation of all installed package contents.
| Package / resolved version | Relationship | Local license evidence | SPDX interpretation / disposition |
| --- | --- | --- | --- |
| `espressif/esp_tinyusb` **2.2.1** | Direct; requires TinyUSB | `managed_components/espressif__esp_tinyusb/LICENSE` | `Apache-2.0`; retain notices and license. |
| `espressif/led_strip` **3.0.3** | Direct | `managed_components/espressif__led_strip/LICENSE` | `Apache-2.0`. |
| `espressif/mdns` **1.12.0** | Direct; requested `^1.8.2` | `managed_components/espressif__mdns/LICENSE` | `Apache-2.0`; inventory resolved 1.12.0, not minimum 1.8.2. |
| `espressif/tinyusb` **0.21.0~1** | Transitive through esp_tinyusb | `managed_components/espressif__tinyusb/LICENSE` | `MIT`, copyright 20122026 hathach. Nested `hw/bsp/espressif/components/led_strip/LICENSE` is Apache-2.0: it is not a seventh lock package. Retain nested notices if distributing the full package. |
| `wolfssl/wolfssl` **5.8.2~1** | Direct | `managed_components/wolfssl__wolfssl/LICENSE.txt`, `README.md`, `wolfssl/version.h` | `GPL-3.0-or-later` open-source option; GPLv3 can be selected with this project. The commercial alternative is not needed merely because the application is GPLv3-only. |
| `wolfssl/wolfssh` **1.4.20** | Direct | `managed_components/wolfssl__wolfssh/LICENSE.txt`, `README.md`, `src/internal.c` opening notice, `wolfssh/version.h` | **Packaging discrepancy:** LICENSE/README describe *wolfSSL/wolfCrypt*, GPLv2-or-later, and include GPLv2 text; inspected wolfSSH headers explicitly grant **`GPL-3.0-or-later`**. Preserve both evidence sets; select GPLv3 for this integration, and seek upstream packaging clarification before release. Do not label wolfSSH GPL-2.0-only or silently rewrite vendor files. |
Provenance references (not fetched): installed manifests point to [esp-usb](https://github.com/espressif/esp-usb), [esp-protocols](https://github.com/espressif/esp-protocols), [Espressif TinyUSB](https://github.com/espressif/tinyusb), [wolfSSL](https://github.com/wolfSSL/wolfssl), and [wolfSSH](https://github.com/wolfSSL/wolfssh). Installed repository metadata pins esp_tinyusb commit `8e779566ef71d43928cbf7e125e8eb54bab3f542`, mDNS `db06b19b7be729c163d346f62ec0eba01047b7f1`, and TinyUSB `7049c58a0e895acc92c6407574b05b5536eddfc8`. Use the LED strip manifest's repository metadata rather than infer a repository from its package name.
## SDK core, bundled libraries, and compiler runtime
“Selected” means archive-selection evidence in the existing application map, not a full object/license attribution trace. Unversioned rows mean **the installed IDF 5.5.0 snapshot**, not an invented upstream release. Header versions do not identify every Espressif patch; preserve the resolved SDK package itself.
| Group / version evidence | Checked local license / notice paths | SPDX / scope and action |
| --- | --- | --- |
| IDF core and Espressif drivers **5.5.0** | `SDK/LICENSE`, `SDK/package.json`, `SDK/version.txt`; original notices retained in the SDK overlays below | `Apache-2.0` baseline, not an umbrella claim over bundled code. Core archives selected. Include attribution and relevant notices, including bootloader distribution inputs. |
| FreeRTOS **10.5.1**, Espressif port | `SDK/components/freertos/FreeRTOS-Kernel/LICENSE.md`; version in `include/freertos/task.h` under that kernel directory | `MIT`; selected. License text does not substitute for copyright notices in individual files. |
| lwIP **2.2.0 development**, Espressif fork | `SDK/components/lwip/lwip/COPYING`; `src/include/lwip/init.h` under that directory has `LWIP_RC_DEVELOPMENT` | `BSD-3-Clause`; selected. Preserve Swedish Institute of Computer Science attribution; do not call it stock release 2.2.0. |
| Mbed TLS **3.6.3** | `SDK/components/mbedtls/mbedtls/LICENSE`; `include/mbedtls/build_info.h` under that directory | `Apache-2.0 OR GPL-2.0-or-later`; choose Apache-2.0 here. `libmbedtls.a`, `libmbedcrypto.a`, `libmbedx509.a` selected. Framework has a separate `framework/LICENSE` when shipping the full source tree. |
| HTTP parser **2.7.0** | `SDK/components/http_parser/LICENSE.txt`, `http_parser.h` in that component | `MIT`; selected. Preserve NGINX/Igor Sysoev and Joyent/Node attribution in the actual text. |
| argtable3, IDF snapshot | `SDK/components/console/argtable3/LICENSE` | **Aggregate**, including `BSD-3-Clause`, `BSD-2-Clause`, and `TCL` terms. It includes Stewart Heitmann, NetBSD getopt, Tcl, C Hash Table, and Better String notices. Do not reduce the entire file to one BSD label. `libconsole.a` selected; sublibrary/object attribution not exhaustively traced. |
| linenoise, IDF snapshot | `SDK/components/console/linenoise/LICENSE` | `BSD-2-Clause`, Salvatore Sanfilippo and Pieter Noordhuis; console selected. |
| TLSF allocator, IDF snapshot | `SDK/components/heap/tlsf/include/tlsf.h`, `SDK/components/heap/tlsf/tlsf_block_functions.h` | `BSD-3-Clause` SPDX headers, Matthew Conte 20062016; heap selected. No standalone TLSF license text appeared in the historical inventory; offline assembly now retains a scoped full TLSF rendering and provenance. Final object coverage/delivery still require review, not a generic BSD text with another author's name. |
| Xtensa HAL, IDF snapshot | `SDK/components/xtensa/include/xtensa/hal.h` opening notice | `MIT`-style full permission notice, Cadence 19992015; `libxt_hal.a`/`libxtensa.a` selected. Header evidence is not an audit of every HAL object or ROM implementation. |
| Espressif prebuilt radio libraries, IDF snapshot | `SDK/components/esp_wifi/lib/LICENSE`, `SDK/components/esp_phy/lib/LICENSE`, `SDK/components/esp_coex/lib/LICENSE` | All three files are byte-identical to `SDK/LICENSE` (`Apache-2.0`). Map selects Wi-Fi `libcore.a`, `libespnow.a`, `libmesh.a`, `libnet80211.a`, `libpp.a`, and PHY `libbtbb.a`, `libphy.a`. `libesp_coex.a` is selected but that does not prove `libcoexist.a` was selected. **Corresponding-source/system-library question remains open**, despite permissive binary redistribution terms. |
| Newlib **4.3.0** and IDF libc integration | `TC/xtensa-esp-elf/include/_newlib_version.h`; `TC/share/licenses/newlib/COPYING.NEWLIB`; `SDK/components/newlib/COPYING.NEWLIB` | Mixed per-file licenses; **no single SPDX expression established**. Toolchain notice file has 1,293 lines vs SDK copy's 952; preserve the actual runtime package's notices, not just the older SDK summary. `libc.a` and `libnewlib.a` selected. Target-specific LGPL/GPL sections for other architectures/Linux are not proof they apply to ESP32-S3; trace selected objects before making that claim. |
| GCC runtime / libstdc++ **14.2.0**, package **14.2.0+20241119** | `TC/share/licenses/gcc/COPYING.RUNTIME`, `TC/share/licenses/gcc/gcc/COPYING3`; `TC/xtensa-esp-elf/include/c++/14.2.0/xtensa-esp-elf/esp32s3/bits/c++config.h` | Header explicitly supports `GPL-3.0-or-later WITH GCC-exception-3.1`; `libgcc.a`/`libstdc++.a` selected. Check exception eligibility and per-object terms; preserve exception and GPL notices. Package-level `GPL-2.0-or-later` metadata is not a runtime license inventory. `COPYING3.LIB` is LGPL text, **not** the GCC runtime exception. |
| cJSON **1.7.18** | `SDK/components/json/cJSON/LICENSE`, `cJSON.h` there | `MIT`; configured SDK component, no `libjson.a` selection in the inspected initial map region. Retain when distributing the SDK source; not asserted live in this image. |
| FatFs **R0.15 w/patch2** | `SDK/components/fatfs/src/ff.c` opening full notice | `LicenseRef-FatFs-local-notice` (descriptive local identifier, not an official SPDX ID): source-retention permission/disclaimer, ChaN 2022. Configured, no `libfatfs.a` selection observed. |
| SPIFFS, IDF snapshot | `SDK/components/spiffs/spiffs/LICENSE` | `MIT`, Peter Andersson; configured, no `libspiffs.a` selection observed. |
| protobuf-c, IDF snapshot | `SDK/components/protobuf-c/protobuf-c/LICENSE` | `BSD-2-Clause`; configured, no `libprotobuf-c.a` selection observed. |
| ESP-MQTT, IDF snapshot | `SDK/components/mqtt/esp-mqtt/LICENSE` | `Apache-2.0`; configured, no `libmqtt.a` selection observed. |
The eighteenth group is **wpa_supplicant**, recorded separately because its license requires reading two files: `SDK/components/wpa_supplicant/COPYING` redirects to `SDK/components/wpa_supplicant/README`, whose full grant is **`BSD-3-Clause`**. The historical GPLv2 option was retired in 2012 according to COPYING; do not flag a GPLv2-only conflict. `libwpa_supplicant.a` is selected; an independent upstream version was not established (use the IDF snapshot).
The installed license-path inventory also found OpenThread, NimBLE/Bluetooth, micro-ecc, Unity/CMock, and tool/test-specific licenses and NOTICE files. They were not promoted to fully reviewed linked dependencies. A full SDK/source or toolchain redistribution must preserve their applicable texts too. No inference that all of these are absent from every bootloader, ROM, or future build is made. The bootloader map, every bundled file, and every selected runtime object were not audited. Newlib, argtable3, radio blobs, ROM attribution, and nested package contents remain aggregation boundaries needing release-specific review.
## Checked-in assets and existing notice sufficiency
| Asset | Version / local evidence | Finding |
| --- | --- | --- |
| `@xterm/xterm` | **5.5.0**; `web_assets/xterm.js`, `xterm.css`, `xterm.LICENSE`; [SOURCES.md](../web_assets/SOURCES.md) provides exact npm URLs/hashes | `MIT`. Full notice retained in repository; CSS also retains a notice. Minified JS has no `copyright`, `permission is hereby`, or `license` marker. |
| `@xterm/addon-fit` | **0.10.0**; `web_assets/addon-fit.js`, `addon-fit.LICENSE`; same provenance document | `MIT`. Full notice retained in repository; minified JS lacks those notice markers. |
| Pictogrammers Material Design Icons | Official **7.4.47**, immutable commit `9e04201d4557e729822fb57f62a316c3dea1d4a8`; [exact evidence](icon_provenance.md) | Retained SVGs are byte-identical to upstream; metadata credits **Google (USB)** and **Simran (Wi-Fi)**. Apache-2.0 package evidence, full license text and a pinned-tree check finding no NOTICE are retained. Manual firmware bitmap derivation and the distinct Wi-Fi mockup path remain unresolved; source identity is not complete derivative or release clearance. |
| Project logo | `web_assets/logo.png`, derived from `images/logo.png` per SOURCES.md | Project-owned according to provenance document; no independent third-party license assigned. Generator's MIT banner must not be treated as proof that the logo was separately relicensed MIT. |
Historical 2026-09-15 `git ls-files '*LICENSE*' '*COPYING*' '*NOTICE*'` found **4 tracked license files**: root GPLv3, two web MIT texts, and the icon summary. That historical count predates the retained upstream icon evidence and full Apache text now included in the 75-input catalog. Neither repository retention nor assembly proves recipient delivery or release compliance.
`web_assets/generate_embedded_assets.py` embeds three gzip files and the logo, **not either MIT license file**. Its generated-source banner points back to provenance/licenses; it is not the upstream MIT notice itself. This proves the embedding path does not carry the separate notice texts, not that every possible product-delivery channel lacks notices. Coordinate a release notice bundle and a way for recipients of the browser assets to obtain the notices (for example a bundled/served third-party license resource); verify the actual delivery path. Do not assume repository-only notices accompany a standalone firmware/device or a downloaded JS response. No assets or web endpoints were changed in this audit.
Preferred-source availability is a separate issue from retaining MIT notices. For a GPL-covered combined release, preserve exact upstream preferred-form browser sources and build inputs where required; the checked-in minified JS distributions and gzip/C arrays are not automatically the preferred form for modification. Source-map references alone do not provide that source. Whether independent browser packages are mere aggregation should be assessed for the actual distribution, not assumed either way.
## GPLv3 distribution and build-overlay obligations
The inspected MIT, BSD and Apache-2.0 grants provide generally GPLv3-compatible routes; the project's `GPL-3.0-only` choice can use wolfSSL/wolfSSH's version-3 alternatives. This is **not** permission to remove upstream notices or declare all files GPL-only. No commercial wolfSSL/wolfSSH license is recommended on the evidence here. Commercial arrangements would be a separate decision if a planned distribution cannot satisfy the available open-source terms, not a cure for unrelated project/SDK obligations.
For conveyance, review GPLv3 §§1, 46, 7 and 10 in [LICENSE](../LICENSE):
1. Supply required license/copyright/warranty notices and use a §6-compliant corresponding-source delivery method for binaries. A dependency name, registry URL, generic upstream source link, or this inventory alone is not corresponding source or a compliant written offer.
2. Preserve exact application source, lock/manifests, relevant SDK and managed source, configuration/build/link inputs, asset preferred sources and generation scripts. Include the scripts controlling compilation/installation. Generic unmodified build tools may fall outside corresponding source, but record precise versions needed for reproduction; if distributing those tools themselves, satisfy their separate licenses.
3. The Phase 9C9D firmware compiles **pinned originals plus project edits**. Include `tools/security_overrides.py`, `cmake/security_overrides.cmake`, root CMake integration, `cmake/wolf_crypto_policy.{cmake,h}`, the complete `tools/wolfssh_order/` inputs, original hash-matching C/header sources, and the means to reproduce all nine C copies and the PUBLIC forced header. A stock IDF/wolfSSH tarball alone omits the compiled modifications. Generated copies alone are not a substitute for the preferred editable patch/generator inputs.
4. **Resolved; updated 2026-09-18:** all nine generated C files plus one header below retain upstream notices and carry explicit project modification/date notices from the generator (baseline 2026-09-15, plus 2026-09-16 ordering notices on wolfSSH outputs). The historical four-file audit found the notice missing; this narrow defect is repaired. GPLv3 §5(a) calls for a relevant date, and Apache-2.0 §4(b) requires prominent change notices. Continue including notices and reproducible generator inputs in distribution; do not hand-edit generated copies or vendor sources.
5. If distributing a GPLv3 “User Product,” assess and provide required Installation Information under §6. Do not publish device passwords, private keys, Wi-Fi material, account verifiers, tickets, NVS images, or real credential backups as build/source artifacts. Installation compliance should use appropriate documented procedures, not routine secret disclosure. Secure boot was not enabled or altered here.
6. **Prebuilt radio libraries are the principal unresolved compatibility/source risk.** Apache-2.0 permits binary redistribution, but does not itself satisfy GPL corresponding-source obligations for a combined firmware. Establish whether required preferred source is obtainable, or whether a defensible GPL System Library/other exception applies to the actual linked artifacts. Static linkage is not automatically “mere aggregation.” Do not declare distribution cleared or definitely prohibited from this bounded audit. Escalate this before a public binary/device release.
Current generated paths and retained licenses (nine C sources plus one header). Here `BUILD/` denotes the validated candidate build, `.pio/idf-candidate-5.5.3/app-validated/.pio/build/esp32-s3-devkitc-1-n16r8/`, rather than the historical audit root:
- `BUILD/security_overrides/https_server/https_server.c` — Espressif Apache-2.0.
- `BUILD/security_overrides/httpd_parse/httpd_parse.c` — Espressif Apache-2.0.
- `BUILD/security_overrides/httpd_ws/httpd_ws.c` — Espressif Apache-2.0; five signed fixed-header receive-size comparisons, with generated modification/rebase notices.
- `BUILD/security_overrides/esp_tls_mbedtls/esp_tls_mbedtls.c` — Espressif Apache-2.0.
- `BUILD/security_overrides/wolfssh_internal/internal.c` — wolfSSH GPL-3.0-or-later header.
- `BUILD/security_overrides/wolfssh_ssh/ssh.c` — wolfSSH GPL-3.0-or-later header.
- `BUILD/security_overrides/wolfssh_include/wolfssh/internal.h` — wolfSSH GPL-3.0-or-later header; ABI overlay propagated BEFORE PUBLIC and as a PUBLIC forced include, not a C compilation unit.
- `BUILD/security_overrides/dhcpserver/dhcpserver.c` — retained Espressif Apache-2.0 header.
- `BUILD/security_overrides/mbedtls_ssl_tls/ssl_tls.c` — retained Mbed TLS Contributors, `Apache-2.0 OR GPL-2.0-or-later`.
- `BUILD/security_overrides/mbedtls_x509_create/x509_create.c` — retained Mbed TLS Contributors, `Apache-2.0 OR GPL-2.0-or-later`.
### Archived ordering patches and license context
[Ordering provenance](../tools/wolfssh_order/README.md) documents the restricted CVE-2025-14942 correction, not a complete upstream backport or upgrade. [`delta.json`](../tools/wolfssh_order/delta.json) is the preferred editable, executable consolidated delta; archived upstream mail patches are provenance/prerequisite evidence, not a statement that all their hunks compile into the firmware. [`provenance.json`](../tools/wolfssh_order/provenance.json) retains the original URLs and every full embedded commit ID. Archived bytes fetched 2026-09-16 are pinned as follows; future PR responses may differ:
| Archive under `tools/wolfssh_order/` | SHA-256 |
| --- | --- |
| `793.patch` | `66aa999521800371f97b340db2bff162be4e8ffab4b4b953f9d32b8e33f56cea` |
| `819.patch` | `8e63c2b24679a7d831f7dba12e412d2f8a7fdc391fc4e8fd33f029487110219b` |
| `840.patch` | `23e25873cb4dfa36063357111019e0960dfc008a68cc29d6e2d5c37bde47ec94` |
| `855.patch` | `b94393df9528f66f6df1aba94015331fee3110c9ea2007a0eff369d8887b4b29` |
| `921.patch` | `f6c88598d7f3c94d92c31cecc4ef1e6d779b49f9eff6556ac1c57426d272d504` |
Preserve upstream mail authorship, commit metadata and applicable file notices with these archives. They contain upstream wolfSSH code/context, not newly project-authored material automatically relicensed by the generator's `GPL-3.0-only` SPDX line. The compiled wolfSSH C/header derivatives retain the upstream **GPL-3.0-or-later** grants; select GPLv3 for this integration. Patch hashes prove identity, not license permission or full archive-level clearance. Retain the upstream license texts and package discrepancy evidence, and review applicable per-file terms for any archived but unapplied example/test/workflow content when assembling the source package. No standalone blanket license grant for every patch byte is inferred from mail-patch format. Source/notice delivery and release packaging remain open.
For Apache-2.0 components, retain required attribution and any applicable upstream NOTICE contents under §4(d), **if present**; do not fabricate NOTICE text or assert every Apache package must have a NOTICE file. For MIT/BSD components, distribute the actual copyright, permission/conditions and disclaimer, not merely an SPDX name. Preserve mixed notices such as argtable3 and Newlib rather than replacing them with generic templates.
## Actionable release work (not performed)
Notice assembly is implemented; the remaining release actions below have not been completed.
| Priority | Action / completion evidence |
| --- | --- |
| Release blocker to resolve | Document a defensible corresponding-source/exception basis for the **selected radio blobs** and other source-unavailable linked content. This is an unresolved question, not a legal verdict. |
| Assembly tooling implemented; delivery pending | [Offline tool and procedure](release_packaging.md) assemble 75 pinned inputs, retaining GPL/Apache/MIT/BSD texts, mixed SDK/toolchain Newlib and argtable3 notices, GCC exception and a scoped full TLSF rendering. Supplied agent fixture suite: 36 PASS; two actual bundles independently verified deterministic, each 77 files / 4,433,930 bytes. Validate final firmware/device/browser recipient delivery; assembly is not corresponding-source delivery or legal clearance. |
| Before distributing icon derivatives | [Exact retained SVG provenance](icon_provenance.md) is resolved at official 7.4.47; full Apache-2.0 text and attribution are retained, with no NOTICE found in the pinned distribution. Preserve manual bitmap preferred sources and resolve the distinct mockup Wi-Fi path/derivation limits. Recipient delivery remains open; do not invent a NOTICE or rasterizer. |
| Resolved in generator; retain in distribution | Prominent modification notices cover **nine C sources plus one header** (baseline **2026-09-15**, wolfSSH ordering **2026-09-16**), with original notices retained. Release packaging must still include them, archived patches/provenance, consolidated delta and reproducible build inputs. |
| Upstream clarification | Record/resolve wolfSSH 1.4.20 package LICENSE/README vs source-header mismatch without editing the managed package in place. GPLv3 is supported by the inspected headers and is also within the package prose's “or later” wording. |
| Release packaging verification | Archive exact corresponding source/build inputs and required asset preferred sources; validate source delivery/offer and any User Product installation information. Recheck bootloader, runtime objects and aggregation boundaries against the final release map. |
## Minimal offline repeat check
Run from the repository root against an already-resolved local environment. This only reads manifest/license/provenance metadata; it does **not** invoke PlatformIO, install dependencies, regenerate assets, read configuration secrets, or validate legal compliance. It requires Python 3 and PyYAML (the latter is normally available in the component-manager environment). A missing prerequisite must be reported, not automatically downloaded. Adjust the two package roots if auditing another machine.
```sh
python3 - <<'PY'
from pathlib import Path
import hashlib
import json
import re
import yaml
sdk = Path('/home/mscholz/.platformio/packages/framework-espidf')
tc = Path('/home/mscholz/.platformio/packages/toolchain-xtensa-esp-elf')
expected = {
'espressif/esp_tinyusb': ('2.2.1', 'LICENSE'),
'espressif/led_strip': ('3.0.3', 'LICENSE'),
'espressif/mdns': ('1.12.0', 'LICENSE'),
'espressif/tinyusb': ('0.21.0~1', 'LICENSE'),
'wolfssl/wolfssh': ('1.4.20', 'LICENSE.txt'),
'wolfssl/wolfssl': ('5.8.2~1', 'LICENSE.txt'),
}
lock = yaml.safe_load(Path('dependencies.lock').read_text())
assert set(lock['dependencies']) == set(expected) | {'idf'}
assert str(lock['dependencies']['idf']['version']) == '5.5.0'
assert sdk.joinpath('version.txt').read_text().strip() == '5.5.0'
assert json.loads(sdk.joinpath('package.json').read_text())['version'] == '3.50500.0'
assert json.loads(tc.joinpath('package.json').read_text())['version'] == '14.2.0+20241119'
for name, (version, license_name) in expected.items():
directory = Path('managed_components') / name.replace('/', '__')
manifest = yaml.safe_load((directory / 'idf_component.yml').read_text())
assert str(lock['dependencies'][name]['version']) == version
assert str(manifest['version']) == version
license_path = directory / license_name
assert license_path.stat().st_size > 0
print(name, version, license_path,
hashlib.sha256(license_path.read_bytes()).hexdigest())
for name, digest in re.findall(r'\| `([^`]+)` \| `([a-f0-9]{64})`',
Path('web_assets/SOURCES.md').read_text()):
assert hashlib.sha256((Path('web_assets') / name).read_bytes()).hexdigest() == digest
for path in [Path('LICENSE'), Path('third_party/material-design-icons/LICENSE'),
sdk / 'LICENSE', sdk / 'components/wpa_supplicant/README',
sdk / 'components/console/argtable3/LICENSE',
sdk / 'components/newlib/COPYING.NEWLIB',
tc / 'share/licenses/newlib/COPYING.NEWLIB',
tc / 'share/licenses/gcc/COPYING.RUNTIME']:
assert path.stat().st_size > 0
print(path, hashlib.sha256(path.read_bytes()).hexdigest())
for name, digest in {
'dependencies.lock': '2d1c62093cafdb54cd209813c526c35e2e470b62cc6f5b0cde9a040569662726',
'src/idf_component.yml': '7fe8cfd25db36dd23907cd1aa7645f3d5b5f34f7ed587cd2599690b5ffbda053',
'platformio.ini': 'b0139667b13c0e254b5ffa67df6cb323f4554a3657fb100330067d6110d57518',
}.items():
assert hashlib.sha256(Path(name).read_bytes()).hexdigest() == digest, name
print('PASS: scoped manifest versions, notice presence, and recorded hashes')
PY
```
This is a **drift tripwire**, not a full component-content verifier or complete license scanner. On changes, inspect new notices and nested components, trace final application/bootloader maps, revisit the build overlays and regenerate a release inventory deliberately. Do not simply repin expected values. Network/upstream authentication, advisory review, legal aggregation analysis, complete notice assembly and hardware validation remain outside this check.
+10 -8
View File
@@ -1,6 +1,6 @@
# Electrical tests
These procedures verify the Phase 7A OLED and buttons, MAX3243 breakout, UART1 data path, hardware flow control, and session broker. They are manual tests: the firmware never starts one automatically.
These manual procedures verify the OLED and buttons, MAX3243 breakout, UART1 data path, hardware flow control, and session broker. The firmware does not start diagnostic commands automatically, but normal boot does initialize the OLED, play the bounded identity animation, and start the local status/control UI when the hardware responds.
> **Safety:** With power removed, install only the wiring required by the selected test. DE-9 pins 3 (`TX`), 4 (`DTR`), and 7 (`RTS`) are driven outputs. Never connect one of these outputs to another driven output. Keep temporary Dupont wiring short and secure. Power the OLED only from 3.3 V because module-mounted I²C pull-ups may connect SDA and SCL to the OLED `VCC` rail.
@@ -20,11 +20,11 @@ Disconnect both USB connectors and every other power source before checking or c
### 2. Powered idle checks and address probe
Apply power, but do not initialize the OLED yet.
Apply power and allow normal boot to complete. A connected, responsive OLED is normally initialized automatically and may already show the status UI.
1. Measure OLED `VCC` relative to `GND`; it should be approximately 3.3 V.
2. Measure idle SDA on GPIO11 and idle SCL on GPIO12. Both should be near 3.3 V. Power down immediately if either bus line rises toward 5 V; correct the OLED supply or pull-up wiring before continuing.
3. Run `debug display status` and record the diagnostic state.
3. Run `debug display status` and record whether normal boot initialized the display.
4. Run `debug display probe`. Confirm that it tests only 7-bit `0x3c` and `0x3d` at the initial 100 kHz bus rate. The tested module should acknowledge at `0x3c` (8-bit `0x78` write / `0x79` read).
If the expected address does not respond, treat the result as a nonfatal hardware finding. On this dedicated local-UI bus, `debug display scan --force` may identify an unexpected address before further investigation. Otherwise leave the serial core running, power down, and recheck 3.3 V power, common ground, SDA/SCL order, solder joints, and pull-ups. Do not scan a bus shared with unrelated I²C devices.
@@ -103,6 +103,8 @@ With all buttons released, run `debug buttons status`. Confirm previous/back GPI
Run `debug buttons test` for the default 10-second interval. During the test, press and release each button separately with a deliberate short press, then repeat with a sustained long press. Confirm that the correct button and short/long classification are reported exactly once per intended action.
> **Live-UI caution:** The normal local status/control task continues to process button input during this diagnostic. Begin on a status page, watch the OLED, and cancel any Controls confirmation that opens. Do not leave a disruptive action selected while testing long holds.
Repeat with an explicit duration, for example:
```text
@@ -118,9 +120,9 @@ Use the longer run to check:
`debug buttons test [seconds]` accepts 1 through 30 seconds and defaults to 10 seconds when omitted. Record unexpected event duplication, missed transitions, incorrect GPIO mapping, false long presses, or a test that fails to terminate.
### 8. Read-only status UI (Phase 7C)
### 8. Status pages
After boot, the OLED starts on the **OVERVIEW** page. A short previous/back press on GPIO10 and a short next press on GPIO14 must wrap through these read-only pages:
After boot, the OLED starts on the **OVERVIEW** page. A short previous/back press on GPIO10 and a short next press on GPIO14 must wrap through these status pages:
1. **OVERVIEW** — serial, broker, USB, HTTPS/WebSocket, SSH, and Wi-Fi summary.
2. **RS232 MODEM** — framing, modem inputs, byte counters, queue depth, drops, and faults.
@@ -129,7 +131,7 @@ After boot, the OLED starts on the **OVERVIEW** page. A short previous/back pres
Confirm that each page remains entirely within the blue content panel. The yellow panel must retain the same fixed icon positions while pages change: serial, segmented Wi-Fi strength, USB, WebSocket, SSH, broker clients, and alert. Active icons are solid with a value below; inactive icon slots remain completely blank and omit their value. Confirm that page text uses readable upper/lowercase, separates items and values with colons, and displays the active station SSID or AP SSID with its channel on the Overview and Network pages.
The UI refreshes at 4 Hz maximum and is read-only: select (GPIO13) must not change a service, acquire/release a writer, inject serial data, or expose passwords, credentials, tickets, or key material. With UART0, USB CDC, WebSocket, and SSH active, navigate pages and confirm that the display continues to update without disrupting serial traffic or UART0 recovery.
The UI refreshes at 4 Hz maximum. Status pages are observational and must not expose passwords, credentials, tickets, or key material. A short Select press opens the separate Controls menu described below; merely navigating status pages must not change a service, alter writer ownership, or inject serial data. With UART0, USB CDC, WebSocket, and SSH active, navigate pages and confirm that the display continues to update without disrupting serial traffic or UART0 recovery.
For the OLED-aging policy, leave all three buttons untouched and verify:
@@ -138,7 +140,7 @@ For the OLED-aging policy, leave all three buttons untouched and verify:
3. The first debounced press of any button wakes the OLED at contrast `127` without changing the current page.
4. A subsequent previous/next press navigates normally and restarts the inactivity timers.
`debug display status` may verify an individual transition in a separate timing run. Every display diagnostic counts as activity and holds normal UI rendering for 30 seconds, so do not invoke it between the five- and ten-minute observations of one continuous run. Record a missing, stale, clipped, or implausible status value or incorrect dim/off/wake transition before Phase 7C is marked complete.
`debug display status` may verify an individual transition in a separate timing run. Every display diagnostic counts as activity and holds normal UI rendering for 30 seconds, so do not invoke it between the five- and ten-minute observations of one continuous run. Record any missing, stale, clipped, or implausible status value or incorrect dim/off/wake transition.
### 9. Local controls (Phase 7D)
@@ -274,7 +276,7 @@ Each output should be negative. Exact voltages depend on supply, load, meter, an
## Recommended order
1. With no DE-9 jumpers, run `status`.
1. With no DE-9 jumpers and after `serial stop`, run `debug status`.
2. Measure output polarity with `debug drivers 0 0 0` and `debug drivers 1 1 1`.
3. Power down, install configuration A, power up, and run `debug loopback-a`.
4. Run `debug valid-test` with configuration A still installed.
+65
View File
@@ -0,0 +1,65 @@
# Bounded ordinary HTTPS idle retention
Current owner/SDK contract. The user accepted idle cleanup as working; [overall acceptance](web_administration_acceptance.md) records current status and evidence limits. No individual unreported soak, fault or reserve result is inferred.
## Evidence and scope
User-authorized response to the admission capture: post-TLS occupancy **6/6, ordinary4 / serial2 / admin0**, ordinary connection ages **5074 seconds**; admin ticket returned in **14 ms**, no subsequent TLS/upgrade observed, ticket unconsumed. These ages measure connection lifetime, not time since the last request. They support investigating retained ordinary sockets, not claiming every captured socket was idle. Installed HTTPD excludes its listening fd from `select` while full with LRU disabled. New connections can therefore wait before TLS or upgrade even when ticket issuance was fast.
This policy releases **expired idle ordinary HTTPS connections**, not arbitrary ordinary requests to make room. The policy uses the existing six sockets, LRU-disabled operation, one-second receive/send and five-second TLS-handshake timeouts without expanding task stacks or queue capacities. Current overall handler capacity is 39. No new task. UART0 recovery, independent USB access, serial broker ownership, tickets, authentication and both WebSocket transports are unchanged.
## Usage and timeout semantics
- Automatically enabled for every successfully started HTTPS server, including when diagnostic tracing is disabled and either optional transport is unavailable. No new console command, setting or credential migration.
- **15 seconds of observed ordinary idle retention**, checked by a **one-second ESP timer** that requests work on HTTPD. The three existing five-second browser status-poll intervals leave room for normal keepalive reuse instead of a TLS handshake per request.
- A new post-TLS connection that has sent no request gets the same full idle window. Time spent establishing TLS does not consume it.
- The first owner sweep observing a new connection or a changed successful-request completion marker starts a fresh window. The marker covers every ordinary route, including login, assets, status, typed settings, tickets and keepalive errors that return successfully—not just diagnostic wrappers. Failed requests are deleted by the normal SDK path instead.
- HTTPD pending bytes, TLS pending bytes or a readable TCP fd reset the observation window. Negative TLS pending results and `select` errors conservatively reset it too. No bytes are read or discarded by the probe.
- At the threshold, after current SDK classification and zero-time readiness checks, HTTPD calls `shutdown(current_fd, SHUT_RDWR)`. A successful shutdown is latched; a failed call retries on the next probe. The SDK's subsequent read/delete path owns socket close, TLS destruction, diagnostic close notification and freeing the slot. The probe never calls `close`, overrides TLS cleanup, or queues a session-close pointer.
- **WebSockets (serial and admin), closing WebSockets and async requests are exempt.** The check uses actual SDK flags, not diagnostic metadata. Successful explicit 101/classification and request cleanup finish before the owner can sweep, so there is no ordinary-idle interval during upgrade admission.
- Under an available owner and timely successful work delivery, expect 15 seconds plus the initial observation delay (nominally up to one second), the next probe delay (nominally up to one second), and SDK read/cleanup latency. This is a conservative sampled idle policy, **not a strict wall-clock timeout or admission SLA**.
### Deliberate limitations
1. Parsing an incomplete request, synchronous response sends, leftover-body purge and TLS handshakes serialize on HTTPD. The probe cannot interrupt them. Existing per-read/per-send timeouts remain; a peer trickling input can extend overall processing beyond one timeout. This change does not provide a slowloris deadline or solve TLS/memory/global-socket pressure.
2. Four continuously active ordinary connections plus two WebSockets can still fill all six slots. They are not evicted. Likewise, an admission attempt immediately after fresh saturation can hit the browser's existing 15-second timeout before the conservative window expires; the user may still need to retry. Older idle retained sockets are eligible on the next delivered probe.
3. As with any HTTP keepalive timeout, bytes arriving **after** the last readiness check can race a shutdown. Already executing HTTPD requests/responses are protected; future client intent cannot be predicted. A client may need a new connection. No new application-level mutation retry/replay is added. Response completion here means synchronous HTTPD completion, not proof of peer receipt/TCP acknowledgement.
4. `httpd_queue_work` with `CONFIG_HTTPD_QUEUE_WORK_BLOCKING` disabled uses loopback UDP. A reported queue error releases the reservation and retries next tick. **A successful send is not an execution acknowledgement**: an accepted-but-lost control message leaves one reservation pending, disables further probes, and requires successful HTTPS stop/restart to restore probing. There is no speculative reservation timeout: it could accumulate delayed callbacks and violate the one-probe bound. This is explicitly regression-tested, not hidden behind a hard retention guarantee. HTTPD blockage or queue loss also cannot be repaired by raising sockets/LRU/timeouts here.
5. A failed stop leaves cleanup detached and ownership retained for a later stop retry; it does not restart probes on a partially stopped server. Timer allocation/start failure gates HTTPS start with its error rather than silently starting without the policy. UART0/USB recovery is unaffected.
## Exact installed SDK audit
All SDK references below are under `~/.platformio/packages/framework-espidf/components/`; installed framework is ESP-IDF **5.5.0** (`3.50500.0`). Production private access remains solely in `src/web_httpd_adapter.c`, with the existing compile-time version guard extended to require idle-lifecycle re-audit.
- `esp_http_server/src/httpd_main.c`: `httpd_server` selects the listener only with capacity or LRU enabled. Control work runs **before** current data sessions, then accept. `httpd_process_session` skips async sessions and synchronously runs `httpd_sess_process`; errors delete the session before any subsequent owner work. Accept invokes TLS synchronously through `open_fn`.
- `esp_http_server/src/httpd_sess.c`: `httpd_sess_process` calls `httpd_req_new`, then `httpd_req_delete`, and only after both return success assigns `session->lru_counter = ++hd->lru_counter`. This happens even with LRU disabled. New sessions zero the slot, including the marker; the global counter resets when all sessions are deleted. Application calls to `httpd_sess_update_lru_counter` are confined to verified serial-WebSocket send work (`web_serial_transport.c`), which the sweep exempts. This marker is not a timestamp and not an fd-generation token.
- `esp_http_server/src/httpd_parse.c`: `httpd_req_new` synchronously parses and invokes the URI handler. `httpd_req_delete` drains any remaining body; cleanup clears `hd_req_aux.sd` and request pointers. A return from a diagnostic handler wrapper or a response-send call is earlier than this boundary. The sweep requires HTTPD's thread identity and no current `hd_req_aux.sd`, and skips `for_async_req`. Current ordinary handlers do not use async requests, out-of-owner sends, or unfinished chunked responses. Re-audit that contract if introduced.
- `esp_http_server/include/esp_http_server.h` has no global synchronous post-request-cleanup hook. Its event notifications are not such a hook: `esp_http_server_dispatch_event` posts to the event loop. `HTTP_SERVER_EVENT_SENT_DATA` is emitted by `httpd_resp_send` and per `httpd_resp_send_chunk`, **before** handler return/body purge/cleanup. Send/receive overrides belong to HTTPS and do not expose a safe completion hook. URI matching and error handlers likewise cannot supply an all-route post-cleanup boundary.
- `esp_https_server/src/https_server.c`: successful `httpd_ssl_open` stores the transport context and installs TLS send/recv/pending functions before synchronous `HTTPD_SSL_USER_CB_SESS_CREATE`. The application callback invalidates any old row for that fd even if the TLS pointer, socket-slot address and counter value were reused. If fd lookup unexpectedly fails, all observations reset conservatively. The close callback remains the diagnostic observer; SDK destruction remains intact. `httpd_ssl_pending` calls `esp_tls_get_bytes_avail` without consuming data; errors can post an existing SDK error event.
- `httpd_sess_trigger_close` resolves fd to a raw reusable `sock_db *`, then queues `httpd_sess_close`. Its zero-counter/LRU guard does not prove the same connection still occupies that slot. **Not used by this policy.** Direct owner shutdown retains the slot until SDK read cleanup and has no deferred fd/pointer argument that could later close a replacement.
- `httpd_queue_work` uses `cs_send_to_ctrl_sock` / `sendto` in `esp_http_server/src/util/ctrl_sock.c`. The actual generated config leaves `CONFIG_HTTPD_QUEUE_WORK_BLOCKING` undefined/off, selecting the nonblocking queue mode. The idle initializer explicitly rejects builds with that blocking option on. Successful `httpd_stop` waits for `THREAD_STOPPED`, frees HTTPD and ends possible old callback execution; failed stop is not a retirement boundary.
## Ownership and bounded storage
`src/web_httpd_idle.{c,h}` owns one persistent ESP timer, six static observation rows, lifecycle gate/generation and queued/submitting flags. It uses no request data, secret, dynamic per-connection allocation, payload buffer, new task or additional socket. Timer callback performs only short metadata locking and at most one queue submission; all private session access, readiness and shutdown run on HTTPD.
`src/web_server.c` serializes lifecycle. Prepare initializes rows **before** SSL startup; the TLS callback and sweep thereafter share the same owner. Attach publishes a nonzero, nonwrapping `uintptr_t` server generation, passed by value as opaque work argument—not a mutable shared descriptor or raw fd. At most one queued/executing probe is reserved; a separate submitting flag remains set until `httpd_queue_work` returns even if work already finished. That closes the callback-before-submit-return race.
Detach first prevents submissions, then waits at most one second for any submitting call to return. Fence timeout forbids SSL destruction, retaining the handle for retry. An already executing sweep may finish safely while stop waits for HTTPD. Only successful SDK stop retires a discarded queued reservation; restart gets a new generation even if the server handle is reused. A stale generation cannot sweep or clear a newer reservation. No counter wrap or generic off-owner session-list query is accepted.
`src/web_httpd_adapter.{c,h}` defines the six-row bound and 15-second policy and performs the version-pinned owner sweep. `src/CMakeLists.txt` adds only the new module. Diagnostics remains unchanged internally; server composes idle identity reset followed by existing diagnostic publication.
## Regression and resource limits
`tests/web_httpd_idle/run.py` exercises production lifecycle/sweep paths, installed SDK request cleanup, host socketpair/readiness/shutdown/fd reuse and deterministic TLS/timer/queue doubles. `tests/web_admin_transport/server_lifecycle.py` checks server composition. Historical host validation passed; these references do not claim a new run or real target scheduler/TLS timing.
Bounded storage: six observation rows (144 bytes), one persistent timer (installed non-profiled layout 32 bytes before allocator overhead), lifecycle/generation flags and one reserved probe. SDK control UDP/mailbox allocation is transient and separate. No per-connection payload/task/stack/socket growth. Actual HTTPD/timer margins and runtime overhead/reserve floors require target measurement, not host sizes. See [latest firmware resources](web_administration_acceptance.md#latest-firmware-evidence).
## Regression procedure — not execution evidence
1. Start with diagnostic capture disabled: establish two serial WebSockets and ordinary HTTPS fetches. Verify idle ordinary sockets disappear after the observation window while both serial clients/lease remain unchanged. Enable capture only as needed to compare close/open occupancy; ages remain connection ages, not idle timestamps.
2. Reproduce the original ordinary4/serial2 full-slot case; wait beyond the idle window, then issue/open admin. Record client ticket/TLS/upgrade timings and occupancy without recording tickets/cookies. Verify no repeat reload loop is needed for already-old idle saturation. Separately test fresh saturation and acknowledge the existing 15-second browser timeout limit.
3. Leave status polling active for several minutes: no five-second TLS reconnect churn; both WebSockets and binary serial data/broker isolation survive. Repeat Settings/account-key operations, large assets, login/logout and two browser contexts. Compare with polling paused to distinguish genuinely idle slots.
4. Slow incomplete headers/bodies, pipelined requests, slow response readers and slow/failed TLS handshakes: no probe-driven close of an executing response or admitted WebSocket. Record owner delays; do not infer an overall request deadline from the unchanged one-second receive timeout.
5. Repeated close/reopen/fd reuse, full-mix stop/start and certificate rotation via supported UART0/SSH/browser lifecycle paths. Confirm UART0 and USB remain available, queued work never affects replacement connections, failed-stop retries retain ownership, and no start allocates a second server.
6. Capture settled/loaded/post-cleanup internal/DMA/PSRAM values and HTTPD/ESP-timer minimum-free stack. Soak at the accepted full client mix. Investigate control queue loss separately if probing appears stuck; successful stop/start is the safe recovery, not an eviction/capacity increase.
+117
View File
@@ -0,0 +1,117 @@
# Exact USB and Wi-Fi icon provenance
Reviewed 2026-09-16. This record resolves the identity of the **two retained
preferred-form SVG sources at Material Design Icons 7.4.47**, not all project
artwork, historical authorship of manual edits, or release compliance.
No firmware, mockup, web asset, or generated asset was changed or regenerated.
## Official pinned source and licenses
Official SVG distribution: <https://github.com/Templarian/MaterialDesign-SVG>.
Its upstream README identifies this as the production SVG distribution and
points to the main MaterialDesign repository for issues. The main repository
URL with tag `v7.4.47` returned 404; it is not used as version evidence.
- Distribution tag: `v7.4.47`.
- Annotated tag object: `5edde266e281d26a03dcfa89fb651183cbab0f2e`.
- Peeled commit: `9e04201d4557e729822fb57f62a316c3dea1d4a8`.
- Upstream `package.json`: `@mdi/svg`, version `7.4.47`, license `Apache-2.0`.
- Tag timestamp: `2023-12-26T23:33:26Z`; GitHub reports it **unsigned**.
HTTPS retrieval and content pins are evidence, not signature authentication.
Unmodified upstream SVGs, LICENSE, README, package metadata, complete `meta.json`,
and GitHub tag/tree responses are retained in
[`third_party/material-design-icons/upstream-7.4.47/`](../third_party/material-design-icons/upstream-7.4.47/).
`downloads.json` records exact retrieval URLs, sizes and SHA-256 hashes. Raw
source URLs use the immutable commit, not a moving branch or tag. API responses
are retained as fetched; future API formatting is not assumed stable.
The full metadata/tree files intentionally preserve the evidence behind the
per-icon selections and absence check, rather than only project-written claims.
The existing `third_party/material-design-icons/LICENSE` is byte-identical to
the pinned upstream Pictogrammers Free License summary and remains unchanged.
It distinguishes icon Apache-2.0/respective grants from code MIT terms. The
package declares Apache-2.0; the two metadata entries contain authors but no
per-icon alternate grant. This is the scoped upstream licensing evidence for
these two SVGs, not a blanket conclusion about every icon in the collection.
`upstream-7.4.47/Apache-2.0.txt` supplies the **full Apache-2.0 text**, fetched
from <https://www.apache.org/licenses/LICENSE-2.0.txt> (SHA-256
`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`).
It is a separately sourced license text, not a file falsely attributed to the
upstream icon tree. The retained non-truncated recursive tree has no path
containing `notice` (case-insensitive); no upstream NOTICE was found in this
pinned distribution and none is fabricated here. This does not audit unrelated
repositories or assert that a NOTICE is mandatory for every Apache work.
| Icon | Metadata attribution | Stable icon ID | First-version metadata | SVG SHA-256 |
| --- | --- | --- | --- | --- |
| `usb` | Google | `25033E0B-3AD4-414D-9972-559F2690FC1D` | `1.5.54` | `c9918e9a983fbd788378ca4c524e7a07a0d5eedcaeff73d19814e6f6ae221f22` |
| `wifi-strength-4` | Simran | `41B86B22-7245-4A97-9BAA-3E9EBD44CEB0` | `2.3.50` | `89d14daf863076b0f73c76d913212875f2e9bcddaaf49c9e5d1825e0b2dc2d5f` |
The metadata `version` fields describe icon introduction versions, **not** a
contradiction of package 7.4.47. Matching these sources to that release does not
prove they originated in that release or were originally downloaded from it.
## Exact comparison to project derivatives
1. **Retained SVGs:** `third_party/material-design-icons/usb.svg` (403 bytes)
and `wifi-strength-4.svg` (219 bytes) are each byte-for-byte identical to the
pinned upstream originals, including every path command, coordinate, arc
flag and viewBox. Each has one path, `viewBox="0 0 24 24"`, and no transform
on the root or path. No coordinate rounding, normalization or visual-match
inference was used. The files remain unchanged.
2. **USB mockup:** `docs/phase7c_icon_mockup.svg` symbol `usb` has exactly the
upstream `d` string and 24-by-24 viewBox, without symbol/path transforms.
Its two direct use definitions are `(x,y,width,height)=(150,4,30,30)` inside
reusable `status`, and `(8,72,30,30)` on the broker page. These apply uniform
scale `30/24 = 1.25` and the stated translations. Status is instantiated in
page groups translated by `(62,98)`, `(592,98)`, `(62,438)`, `(592,438)`;
the broker use is in `(62,438)`. Thus status USB geometry maps as
`(X,Y)=(pageX+150+1.25*x, pageY+4+1.25*y)` and broker USB as
`(X,Y)=(62+8+1.25*x,438+72+1.25*y)`. CSS adds presentation fill/stroke;
this is path geometry equivalence, not pixel/rendering equivalence.
3. **Wi-Fi mockup:** symbol `wifi` in that same mockup uses a different,
segmented path starting `M1 8q11-9 22 0`. It is **not** an exact copy of
`wifi-strength-4` (which starts `M12,3C7.79,3`). No exact affine derivation
or upstream provenance for that distinct mockup path is established here.
4. **Actual firmware:** `src/local_status_ui.c` explicitly calls the USB mask
hand-rasterized and the Wi-Fi masks compact segmented adaptations. The exact
editable row bytes are:
```text
s_icon_usb: 18 3c 18 5a 3e 18 3c 18
s_icon_wifi_full: 7e 81 3c 42 18 24 00 18
s_icon_wifi_three: 00 00 3c 42 18 24 00 18
s_icon_wifi_two: 00 00 00 00 18 24 00 18
s_icon_wifi_one: 00 00 00 00 00 00 00 18
```
These manual 8-by-8 masks are not SVG coordinates or exact scaled vector
paths. No deterministic rasterizer, sampling/threshold rule or edit history
establishes an exact upstream-to-mask transform. Their declared design
provenance is supported by the now-verified retained sources, but **exact
mechanical derivation of the firmware masks remains unresolved**. Preserve
the C arrays as the preferred editable form of those manual modifications,
together with both original SVGs; do not substitute an invented generator.
The existing source comment is the adaptation notice. This dated record
documents the inspected modifications; it does not invent their edit date.
## Offline checks and release boundary
`python3 tests/release_notices/run.py` verifies the pinned source bytes and Git
blob identities, version/author metadata, catalog inclusion, exact SVG geometry,
USB mockup placement/ancestry, distinct Wi-Fi mockup path, and current manual
mask bytes. Negative checks reject coordinate and transform changes. Tests do
not regenerate artwork or claim raster equivalence.
The notice catalog retains all previous inputs and adds the two existing SVGs,
these source originals, licensing/metadata evidence and this record. The bundle
is still **not corresponding source or release clearance**. Firmware C arrays
and the full mockup remain in the project, not copied into this bounded notice
bundle; include them in a separately reviewed corresponding-source delivery
where required. Radio-blob/source-exception questions, wolfSSH packaging,
recipient notice/source delivery and other release gates remain open.
Older global inventory/packaging/memory documents describe the pre-verification
state and counts. They were intentionally not edited in this scoped task;
this record and the current catalog provide the narrower updated evidence.
+190
View File
@@ -0,0 +1,190 @@
# IDF 5.5.3 uncommitted rebase review
Review date: **2026-09-18**. Baseline Git HEAD: `cdc4d4a8df02c2c44180b9b6d17bf6104c9fbcd2`.
**Current disposition: existing protected corrections are semantically retained; the initial stale compiled WS input and missing receive-error regression blockers are resolved by the supplied final fresh-build/24-suite evidence below.** No evidence found that a protected correction should be removed as superseded. This is a bounded rebase review, not advisory recertification, device acceptance or release clearance.
Initial reviewer-owned change: **this document only**. Existing working changes were preserved. No SDK installation, firmware build, upload, erase, asset regeneration or production edit was performed. A concurrent change to `third_party/release-notices/inputs.json` appeared during review; it was left untouched and was not reviewed in that initial pass. The later supplied notice review semantically rebased nine entries, retaining the other 66 unchanged; this does not turn the initial review into a catalog audit.
## Final follow-up — 2026-09-18
Supplied final parent command, run from the repository root:
```sh
CCACHE_DISABLE=1 python3 -B tools/validate_phase9.py --build-dir .pio/idf-candidate-5.5.3/app-validated/.pio/build/esp32-s3-devkitc-1-n16r8 --idf-path .pio/idf-candidate-5.5.3/core/packages/framework-espidf --platformio-core-dir .pio/idf-candidate-5.5.3/core --interop --web-performance
```
**PASS 24/24.** This selects the actual fresh isolated build, SDK and toolchain core; it is not a default-root-build execution. The separate fresh `.pio/idf-candidate-5.5.3/app-validated` build **PASS** reports **95,552 B linked RAM / 1,749,493 B flash**, versus historical **94,340 / 1,768,901 B** (**+1,212 B RAM / 19,408 B flash**). The default parent `pio run` timed out after **200 seconds during installation, before compilation**; no normal root build PASS is claimed.
Pre/post source equality: **3,237 files**, SHA-256 **`3a1af78c15cfdd02da1055a8957b4086f9018862b7aa1c7c52fd2401a1a0a031`**. Actual generated-input registration covers **nine C sources plus one forced header**. WS receive tests exercise generated code: **982 cases / 10 mutation checks**, including the five signed `sizeof` corrections. The stale web-cookie fixture asserting IDF 5.5.0 was corrected, not bypassed. Historical stale-WS compilation/coverage failures in the [rebase review](idf_553_rebase_review.md) are resolved by this final snapshot, not hidden or retroactively called passes.
The [fix-bearing Wi-Fi bundle](wifi_security_update_plan.md) is integrated in the candidate, with unchanged PMF/WPA3; radio-hardware vulnerability closure and full target/resource/recovery gates remain pending. Nine notice catalog entries were semantically rebased, the other 66 unchanged (75 total); supplied notice evidence is **36 fixtures PASS**, two actual deterministic bundles each **77 files / 4,433,930 bytes**. Archive pins and source equality do not prove complete immutable root/ancillary/Python dependency closure, legal clearance or Phase 9 acceptance. This documentation update records supplied parent evidence; it did not rerun these builds, suites, bundles or hardware tests.
## 1. Historical review inputs, not assumed SDK paths
Paths below are relative to the repository except the explicitly absolute shared SDK:
| Role | Observed path / identity |
| --- | --- |
| Old SDK | `/home/mscholz/.platformio/packages/framework-espidf`, package **3.50500.0** / IDF 5.5.0 |
| Candidate archive | `.pio/idf-candidate-5.5.3/archives/framework-espidf-3.50503.0.tar.gz` |
| Candidate installed SDK | `.pio/idf-candidate-5.5.3/core/packages/framework-espidf`, package **3.50503.0** / IDF 5.5.3 |
| Isolated application | `.pio/idf-candidate-5.5.3/app` |
| Existing candidate build | `.pio/idf-candidate-5.5.3/app/.pio/build/esp32-s3-devkitc-1-n16r8` |
| Candidate compiler in compile database | `.pio/idf-candidate-5.5.3/core/packages/toolchain-xtensa-esp-elf/bin/xtensa-esp32s3-elf-gcc` |
There is no literal `.pio/idf-candidate` directory. The shared SDK is still **old**, not an installed production 5.5.3 SDK. There was no root `.pio/build/esp32-s3-devkitc-1-n16r8` build to validate. Tests defaulting to the shared SDK must explicitly select the candidate.
Recomputed **size and SHA-256 of all four complete archives** against `tools/idf_candidate/artifacts.json`: all matched (platform 6.13.0, framework 3.50503.0, Xtensa and RISC-V 14.2.0+20251107). Framework archive SHA-256: `8353f6fd5030dd7e662500891428fad15d46efd7e4b718cab2fe6bfb9e7f13fc`. Current `platformio.ini` selects that version pairing. Registry version pins in the root configuration are not themselves enforcement of these archive hashes; the isolated application uses local archive URLs.
Loaded the protected-entry registry from **Git HEAD**, verified every old original against its HEAD hash, then compared it with the working registry and actual candidate sources. Every working original hash and exact edit application passed. Also compared candidate protected IDF originals and `esp_httpd_priv.h` directly with members of the hash-verified framework archive: byte-identical. This separates old baseline, downloaded package, installed candidate and generated compilation inputs.
## 2. Historical blockers — resolved in final follow-up
### B1 — Historical candidate firmware does not contain the new WS correction
The staged `app/tools/security_overrides.py` lacks `Entry("httpd_ws", ...)`; the working generator includes it. The staged test runner also differs from the working web-performance runner. The candidate compile database compiles:
```
.../core/packages/framework-espidf/components/esp_http_server/src/httpd_ws.c
```
not `security_overrides/httpd_ws/httpd_ws.c`. The map includes `libesp_http_server.a(httpd_ws.c.o)`. The working SDK override test with this actual build fails:
```
AssertionError: ('httpd_ws', [])
```
All eight previously protected generated C files and the wolfSSH forced header independently match the current generator's bytes. Their compile paths are present; representative wolfSSH and application commands retain the joined forced-header and crypto-policy includes. This is a **specific stale ninth-C-source build**, not evidence that all replacements are missing.
An ELF/bin/map exists, but this reviewer did not build it. Snapshot identities:
- `firmware.elf`: 15,558,488 bytes; SHA-256 `39d12988d80c44787f1d9587d7ba685c990bfac940ba10180b86e60313b60fad`.
- `firmware.bin`: 1,749,888 bytes; SHA-256 `0477958591e0e21269b21fdd62ba855d507a6dd460107647f4f38739f9264e96`.
- `esp32_serial_swiss_army_knife.map`: SHA-256 `346abf8ce619742edd38274eef6267d6d8e0750fea6b1e2c8ffdcc34e5bc0085`.
**Required:** stage the final reviewed inputs in an ownership-safe isolated workspace, rebuild, and verify all **nine C overrides plus one forced header**, exact owners, original-source absence and generated bytes against that build. Do not attribute the current WS correction to the existing binary.
### B2 — Historical vendor-code tests and missing signed-error behavioral matrix
`tests/web_serial_performance/run.py` reads installed `httpd_ws.c`, not generated `httpd_ws.c`. Its enum-aware receive double is a necessary adaptation, but the suite fails compiling `httpd_ws_get_frame_type` against candidate vendor source:
```
error: comparison of integer expressions of different signedness
[-Werror=sign-compare]
```
The new five-edit override is included in generic generator/CMake fixtures. However, `tests/sdk_security_overrides/run.py` has no dedicated WS receive behavior or mutation suite. The web-performance receive double always supplies a successful first byte and the control-frame receiver is a double; it cannot establish the newly changed real frame-receive error paths.
**Required:** consume verified generated WS code without suppressing the warning or editing vendor files. Exercise actual `httpd_ws_get_frame_type`, `httpd_ws_recv_frame` and, where needed, the real `httpd_recv_with_opt` against bounded IO doubles: negative fail/timeout, EOF, short lengths and success at all five fixed-header reads; split/pending bytes; two- and eight-byte lengths; four-byte mask; automatic control-frame failure/close and no subsequent payload/send on failed framing. Require each removed signed cast to be detected by a negative regression/mutation. Passing generic generation alone is insufficient.
### B3 — Historical documentation gap: final snapshot required
At the initial review, `docs/idf_candidate_integration.md` described preparation only, production untouched and smoke not run, while the worktree already had production configuration/guard changes and an isolated application ELF. The generated modification notice pointed to that preparation document as rebase evidence without per-entry dispositions. The integration record now links the semantic dispositions and supplied final build/test evidence. This review's initial artifact inspection is not retroactively a fresh build pass.
Broader wolf ordering/parser/crypto/authentication, browser admission and full phase validation were **not rerun by this reviewer**. Existing historical 5.5.0 results and a stale candidate build cannot stand in for final-snapshot integration validation. Hardware/radio/resource/recovery and distribution/source obligations remain separate established gates, not reasons to repeat completed broad advisory research.
## 3. Per-entry semantic disposition
All old entries preserve exactly their HEAD edit sequences; changed IDF file hashes reflect the vendor differences below. Exact successful replacement is necessary but was not the only check: old/new source differences and relevant ownership/error paths were inspected, and existing behavioral fixtures were executed against candidate-generated sources.
| Protected entry | Disposition and reason |
| --- | --- |
| `dhcpserver` | **Retain unchanged original and six edits.** Vendor source is byte-identical across these SDKs; bounded option header/body, PAD/END handling and minimum lengths are not supplied by this upgrade. Extracted parser passes 196,623 guard-page/equivalence cases. |
| `mbedtls_ssl_tls` | **Rebase original hash; retain EMS error return.** Vendor changes include handshake-state helpers, dynamic-buffer reset handling, PRF label-length plumbing and exporter support. The `calc_verify` error branch still logs without returning; the local return remains necessary before PRF use. SHA256/SHA384 failures, success, PRF failure, non-EMS and resumption fixtures pass. Dynamic TLS buffers remain rejected. This is not a review of every new exporter/TLS1.3 path. |
| `mbedtls_x509_create` | **Rebase original hash; retain OID allocation check.** Vendor now rejects a prepopulated output list instead of clearing it; it still dereferences an unchecked newly allocated `oid.p`. Local OOM return remains needed. Subject/issuer OOM, cleanup and retry fixtures pass. Project certificate generation sets subject and issuer separately once, consistent with the changed empty-list precondition; do not generalize this to repeated setter calls elsewhere. |
| `https_server` | **Rebase original hash; retain all four edits.** Vendor delta adds hardware ECDSA curve/block configuration, not post-handshake allocation-failure cleanup, copied-key wiping or failed-start secure-context destruction. Local TLS delete, wipe-before-free and restored/null-cleared ownership still apply. Existing allocation/handshake/start/stop matrix passes. Failed stop continues to retain live ownership. |
| `httpd_parse` | **Rebase original hash; retain all six edits.** Vendor delta fixes cookie length reporting on truncation, not scratch ownership. Null initial pointer arithmetic, failed `realloc` ownership and unwiped retired scratch still require local fixes. Allocate/copy/wipe/free, preserve-old-on-failure, nullable parser pointer and final wipe remain; null/grow/shrink/failure/pending-unread fixtures pass. |
| `esp_tls_mbedtls` | **Rebase original hash; retain guards and server-only policy.** Vendor adds dynamic-buffer strategy, hardware ECDSA configuration, RSA-ALT cleanup and error/certificate reporting changes. None supplies the project server TLS1.2 ECDHE-ECDSA AES-GCM allowlist or no-renegotiation policy. Injection remains in server configuration; clients retain their defaults. Server/client isolation, feature and dynamic-buffer guard fixtures pass. |
| `wolfssh_internal` | **Retain original hash and all 53 edits.** Managed source matches HEAD. Ordering delta, restricted no-EXT_INFO profile, password bounds/wiping, parser/name/service/signature/window corrections are unchanged; this IDF migration does not supersede them. The initial semantic review did not rerun full wolf behavior; the final supplied 24/24 run includes the established wolf suites. |
| `wolfssh_ssh` | **Retain original hash and ordering edits.** Generated candidate bytes match working output; exact generated compilation path present. |
| `wolfssh_internal_header` | **Retain original hash and ABI/order overlay.** Generated header bytes match; candidate library and representative application commands retain the forced include and overlay include path. PUBLIC direct/transitive consumer fixture passes. |
| `httpd_ws` (new) | **New candidate-specific correction, not a repin.** IDF 5.5.3 changes fixed header reads from nonblocking `<= 0` checks to blocking `< sizeof(...)`. `int` negative receive results convert to unsigned `size_t`, making the checks false. The five `(int)sizeof(...)` changes correctly restore signed rejection for sizes 1, 2, 8, 4 and 1; they retain vendor blocking reads and do not alter payload framing policy. Behavioral regression and current-build evidence were initially blocked by B1/B2; the final follow-up resolves both with 982 cases / 10 mutation checks and actual generated-source registration. |
No protected correction was demonstrated to be **superseded**. Native pre-handshake support is not a reason to delete the application's admission adapter: it is disabled in the candidate configuration and the application deliberately registers the two upgrade routes as ordinary GET handlers.
## 4. Heap extent and HTTPD private boundary
### Heap: guarded 5.5.3 extent contract is supported
`components/heap/heap_caps.c`, `multi_heap.c`, `multi_heap_platform.h` and `tlsf/tlsf.c` are byte-identical old-to-candidate. The audited chain remains:
1. `heap_caps_get_allocated_size` removes any owner offset, locates the containing heap and subtracts owner metadata from the reported size.
2. Unpoisoned `multi_heap_get_allocated_size` aliases the implementation returning `tlsf_block_size`.
3. TLSF obtains the allocated payload block's rounded size, not a containing-block extent for an arbitrary interior pointer.
Candidate resolved config enables `CONFIG_HEAP_POISONING_DISABLED`, disables task tracking and leaves dynamic mbedTLS buffers off. `ssh_memory` still rejects poisoning and all other IDF versions. Actual candidate-source contract checks and host allocation/free/realloc wipe tests pass, including rounded capacity, retained shrink, growth and allocation failure. No new allocator layout/header mechanism was introduced. Target wipe latency and old-plus-new allocation peaks remain unmeasured.
### HTTPD: relevant layouts retained; receive API changed
The private-header diff adds shared control-message declarations, `HTTPD_RECV_OPT_*`, the enum receive parameter and a direct-LRU-close declaration. It does **not** change the adapter-used `httpd_data`, `httpd_req_aux` or `sock_db` field layouts. The application compiles against candidate headers rather than embedding an old SDK struct definition.
Relevant behavior review:
- Session completion still performs request creation/handling, request deletion/purge, then updates the LRU completion marker. New sessions initialize the counter from the server; the adapter already tracks session identity. All 18 idle lifecycle groups pass against candidate completion/purge sources.
- `httpd_main` still processes control work before connection data. New direct LRU close is conditional; application `lru_purge_enable` remains false.
- Header/scratch parser delta is the cookie reporting fix, not a layout/termination change. Right-aligned pending bytes and application wipe preservation remain applicable.
- Optional URI registration still publishes before `strdup` failure cleanup; the application's allocate-both-before-publication correction remains necessary.
- Vendor URI dispatch adds optional pre-handshake callback support. Candidate config disables it; application ordinary-GET upgrade handlers continue to authorize/admit before manually sending 101.
- SDK WS sending remains separate header/payload sends through session `send_fn`; the bounded combined binary adapter still uses that TLS override and replaces it with reject-only behavior after incomplete output. No raw socket bypass was introduced.
- `httpd_recv_with_opt` changes from Boolean to enum and loops for blocking fixed-header reads; `httpd_recv` uses `NONE`. Async completion now wakes the owner with a control message. Application owner/async exclusion rules remain relevant. The receive double was correctly changed to the enum, and the initial WS receive-error/test-input blockers B1/B2 are now resolved as recorded in the final follow-up.
This supports the narrow guard update; it does not certify arbitrary configurations, async use or every HTTPD API.
## 5. Whole radio bundle identity and actual link inputs
Compared **every regular archive member** under these component trees with the corresponding installed candidate file; all were byte-identical:
| Component | Files compared |
| --- | ---: |
| `esp_wifi` | 163 |
| `esp_phy` | 114 |
| `esp_coex` | 41 |
| `wpa_supplicant` | 301 |
This includes packaged source, headers, CMake inputs and all target/optional archives, not only the seven currently discussed S3 Wi-Fi blobs. It establishes coherent delivery from the one locked framework archive, **not** independent upstream PHY/coexistence Git submodule provenance, vendor signature validation or opaque binary correctness.
S3 Git blob identities recomputed from installed bytes:
| Archive | Git blob SHA-1 |
| --- | --- |
| Wi-Fi `libcore.a` | `9f7b14a8bf6eec64973da8adc65d35b5ba9bee49` |
| Wi-Fi `libespnow.a` | `132b4f67e339ca2081d2add91c14eefa39476ff9` |
| Wi-Fi `libmesh.a` | `2e9dc1c8c7afbf033337b4175032e9b1161e3262` |
| Wi-Fi `libnet80211.a` | `2800d447ec385d33869373696ba8191292647694` |
| Wi-Fi `libpp.a` | `8944bcad7371621045f376cf74c62fde6f368cbb` |
| Wi-Fi `libsmartconfig.a` | `4dc759e25617aa00b9e12887fd092a1d5780a170` |
| Wi-Fi `libwapi.a` | `65655b6feab0572a6e8a1200946d53a21f3f4722` |
| PHY `libphy.a` | `75d3c8756c8e0310066fa9a1e5c24df50e6c04e3` |
| PHY `libbtbb.a` | `e94e3c2b476d8abb2757bcb53519ebcfba92b213` |
| PHY `libbttestmode.a` | `06389c391ea55278df6205b6195b6d8182c7b8be` |
| PHY `librfate.a` | `05dc4b69e02dac8e6c75ab8f9dc49c1d33d66c32` |
| PHY `librftest.a` | `45c6dc240287332c8c8790e84a80475dbfe3a842` |
| Coexistence `libcoexist.a` | `21fb35634fbdd421519bc985072fdc0ab54dd1df` |
The seven Wi-Fi identities agree with the already recorded 5.5.3 **release-point** column in `docs/wifi_security_update_plan.md`; they are not a mixed fix-point/release-point bundle. Candidate `esp_wifi_driver.h` declares `wpa_ap_get_wpa_ie(size_t *len)` and `esp_wpa_main.c` defines `wpa_ap_get_wpa_ie(size_t *ie_len)` and assigns that callback. The compile database uses candidate supplicant sources.
Actual candidate map `LOAD` entries select **all seven Wi-Fi blobs plus `libphy.a` and `libbtbb.a` from the candidate SDK path**, and the candidate-built component wrappers/supplicant archive. No old shared-SDK radio path was observed in those inputs. `libcoexist.a` is delivered and verified but is **not a LOAD input** in this configuration: `esp_coex/CMakeLists.txt` adds it only for software/external coexistence, not merely `CONFIG_ESP_COEX_ENABLED`. Optional RF/test PHY archives likewise are packaged identities, not claimed linked inputs. A map `LOAD` line does not prove all members survive link garbage collection.
The whole-package approach avoids a 5.5.0 C/header/blob transplant. This provides stronger delivery/path evidence than the earlier seven-Wi-Fi-only check, but does not demonstrate runtime PMF/WPA3 behavior, radio stability, target reserves or deployment vulnerability closure.
## 6. Historical validation executed and handoff
Commands run from the repository root:
```sh
CCACHE_DISABLE=1 python3 -B tests/ssh_memory/run.py --idf-path .pio/idf-candidate-5.5.3/core/packages/framework-espidf
IDF_PATH=/home/mscholz/Repos/ESP32_serial_swiss_army_knife/.pio/idf-candidate-5.5.3/core/packages/framework-espidf CCACHE_DISABLE=1 python3 -B tests/web_httpd_idle/run.py
IDF_PATH=/home/mscholz/Repos/ESP32_serial_swiss_army_knife/.pio/idf-candidate-5.5.3/core/packages/framework-espidf CCACHE_DISABLE=1 python3 -B tests/web_serial_performance/run.py
CCACHE_DISABLE=1 python3 -B tests/sdk_security_overrides/run.py --idf-path .pio/idf-candidate-5.5.3/core/packages/framework-espidf --build-dir .pio/idf-candidate-5.5.3/app/.pio/build/esp32-s3-devkitc-1-n16r8
```
Results:
- **PASS:** SSH allocator behavior, six invalid poisoning profiles, explicit disabled profile, seven rejected IDF versions, real candidate extent-source checks and compile with candidate version header.
- **PASS:** all 18 idle lifecycle groups and candidate completion/owner-order guards.
- **FAIL:** web serial performance compile against original WS source, B2.
- **PARTIAL PASS / overall FAIL:** SDK generator, HTTPS/scratch/TLS/DHCP/EMS/X509 behavior and CMake replacement/forced-header/extension fixtures pass; actual build registration rejects missing generated WS input, B1. Do not report this command as passing.
- **PASS:** read-only HEAD/current original-hash and edit comparisons; all four archive identities; protected candidate/archive comparisons; all four radio component trees; candidate compile/map path inspection.
The initial next actions were generated-WS regression coverage, a fresh staged snapshot/build and final-input integration validation. Those actions are now complete in the supplied final follow-up; the historical failures above remain failures of the old snapshot, not current blockers or retroactive passes. No production defect was found in the retained old overrides or reviewed heap/private-layout assumptions. Normal root build completion, immutable full dependency closure, target/radio/resource/recovery and release gates remain open. Preserve PMF/WPA3, broker isolation, native USB independence and UART0 recovery.
+100
View File
@@ -0,0 +1,100 @@
# Official PlatformIO IDF 5.5.3 candidate integration
Initial package preparation: **2026-09-16**, Linux x86_64; integration update: **2026-09-18**. Preparation-only statements below describe the earlier stage. Root `platformio.ini` and reviewed guards/overrides are now migrated; shared-SDK installation is not claimed complete and no device/deployment acceptance is claimed.
## Final integration evidence — 2026-09-18
Supplied final parent command, run from the repository root:
```sh
CCACHE_DISABLE=1 python3 -B tools/validate_phase9.py --build-dir .pio/idf-candidate-5.5.3/app-validated/.pio/build/esp32-s3-devkitc-1-n16r8 --idf-path .pio/idf-candidate-5.5.3/core/packages/framework-espidf --platformio-core-dir .pio/idf-candidate-5.5.3/core --interop --web-performance
```
**PASS 24/24.** This selects the actual fresh isolated build, SDK and toolchain core; it is not a default-root-build execution. The separate fresh `.pio/idf-candidate-5.5.3/app-validated` build **PASS** reports **95,552 B linked RAM / 1,749,493 B flash**, versus historical **94,340 / 1,768,901 B** (**+1,212 B RAM / 19,408 B flash**). The default parent `pio run` timed out after **200 seconds during installation, before compilation**; no normal root build PASS is claimed.
Pre/post source equality: **3,237 files**, SHA-256 **`3a1af78c15cfdd02da1055a8957b4086f9018862b7aa1c7c52fd2401a1a0a031`**. Actual generated-input registration covers **nine C sources plus one forced header**. WS receive tests exercise generated code: **982 cases / 10 mutation checks**, including the five signed `sizeof` corrections. The stale web-cookie fixture asserting IDF 5.5.0 was corrected, not bypassed. Historical stale-WS compilation/coverage failures in the [rebase review](idf_553_rebase_review.md) are resolved by this final snapshot, not hidden or retroactively called passes.
The [fix-bearing Wi-Fi bundle](wifi_security_update_plan.md) is integrated in the candidate, with unchanged PMF/WPA3; radio-hardware vulnerability closure and full target/resource/recovery gates remain pending. Nine notice catalog entries were semantically rebased, the other 66 unchanged (75 total); supplied notice evidence is **36 fixtures PASS**, two actual deterministic bundles each **77 files / 4,433,930 bytes**. Archive pins and source equality do not prove complete immutable root/ancillary/Python dependency closure, legal clearance or Phase 9 acceptance. This documentation update records supplied parent evidence; it did not rerun these builds, suites, bundles or hardware tests.
## Concrete result
**Select official `platformio/espressif32@6.13.0` + `platformio/framework-espidf@3.50503.0` (IDF 5.5.3) + `platformio/toolchain-xtensa-esp-elf@14.2.0+20251107`.** The official adapter also selects `platformio/toolchain-riscv32-esp@14.2.0+20251107` for ESP32-S3 ULP; include it even when evaluating the Xtensa application.
This is an explicitly released supported pairing, not a speculative package override. Exact downloaded archive hashes below make the selected inputs content-pinned; tags/version labels alone are not treated as immutable.
Official channels checked:
- [Platform registry](https://api.registry.platformio.org/v3/packages/platformio/platform/espressif32): latest stable **7.1.3**, published September 11, 2026. [Latest release API](https://api.github.com/repos/platformio/platform-espressif32/releases/latest) agrees (`prerelease=false`). Its [manifest](https://raw.githubusercontent.com/platformio/platform-espressif32/v7.1.3/platform.json) selects `~4.60100.0`, **IDF 6.1**, not IDF 5.5.
- [Framework registry](https://api.registry.platformio.org/v3/packages/platformio/tool/framework-espidf): newest published 5.5 package is **3.50503.0**, published February 18, 2026. Returned 5.5 versions are 3.50503.0, 3.50502.0 and 3.50500.0. No 5.5.4/5.5.5 package appears in that response. Thus 5.5.3 is the **latest available official PlatformIO 5.5 candidate**, not the latest upstream Espressif 5.5 maintenance release. Registry framework metadata labels its tier `community` but its owner is `platformio`; the platform itself is tier `official`.
- [6.13.0 release](https://github.com/platformio/platform-espressif32/releases/tag/v6.13.0), [release API](https://api.github.com/repos/platformio/platform-espressif32/releases/tags/v6.13.0): explicitly adds IDF **5.5.3** and updates IDF toolchains to **14.2.0+20251107**. Stable release, February 26, 2026.
- [6.13.0 manifest](https://raw.githubusercontent.com/platformio/platform-espressif32/v6.13.0/platform.json): framework `~3.50503.0`, Xtensa `14.2.0+20251107`. [Adapter](https://raw.githubusercontent.com/platformio/platform-espressif32/v6.13.0/platform.py) removes the legacy chip-specific Xtensa toolchains for standalone IDF, enables unified Xtensa for S3, and selects the same-date PlatformIO RISC-V package for S3 ULP.
- [Xtensa registry](https://api.registry.platformio.org/v3/packages/platformio/tool/toolchain-xtensa-esp-elf) and [RISC-V registry](https://api.registry.platformio.org/v3/packages/platformio/tool/toolchain-riscv32-esp) both publish the selected Linux x86_64 artifacts.
If the requirement is specifically upstream **5.5.5**, rather than the newest officially delivered 5.5 maintenance release, that requirement remains **blocked on official packaging/support**. Do not substitute 7.1.3 plus an arbitrary 5.5 override or a raw GitHub source archive.
## Actual downloaded identities
All four complete archives were downloaded into `.pio/idf-candidate-5.5.3/archives/` and their **local bytes** passed both registry size and SHA-256 checks. These are measured download checks, not just registry advertisements. No archive was unpacked into the shared PlatformIO SDK. Total compressed size: **992,746,039 bytes**.
| Artifact | Bytes | SHA-256 |
| --- | ---: | --- |
| `espressif32-6.13.0.tar.gz` | 1,009,115 | `5d1032b43828773ba87cf2e509432202c0bfe64f7304b58c9d669f13b116c6e0` |
| `framework-espidf-3.50503.0.tar.gz` | 76,402,966 | `8353f6fd5030dd7e662500891428fad15d46efd7e4b718cab2fe6bfb9e7f13fc` |
| `toolchain-xtensa-esp-elf-linux_x86_64-14.2.0+20251107.tar.gz` | 322,439,270 | `a5de49ce3299b0d9253ab6a423648bc23113db96b34a7cc8e57702cae1bb190e` |
| `toolchain-riscv32-esp-linux_x86_64-14.2.0+20251107.tar.gz` | 592,894,688 | `1af8e233931500b8712079808e4974413d95d3601d03275dff79665c436e9d33` |
Machine-readable registry URLs, artifact URLs, versions, system selectors, sizes and hashes: [`artifacts.json`](../tools/idf_candidate/artifacts.json). No automatic repinning occurs.
The verifier reads members directly from the hash-verified archives without extracting or executing vendor files. Actual checks passed:
- Platform manifest version, framework range and exact Xtensa requirement.
- SDK package version and SDK `tools/tools.json` recommendation `esp-14.2.0_20251107`.
- Fixed `wpa_ap_get_wpa_ie(size_t *len)` callback declaration.
- All seven packaged ESP32-S3 Wi-Fi libraries match the **5.5.3 release-point Git blob identities**, not the fix-point-only bundle, recorded in [the existing Wi-Fi plan](wifi_security_update_plan.md#bundle-identity-baseline-fix-point-release-point-are-different). The plan already establishes release commit `2c211b236707889e8400c4dc5644dd5c4ee071e0` and Wi-Fi submodule `e0befaa593277b4e80726079fbd521b4681754c2`; this task does not repeat fix research.
Whole-archive SHA-256 pins include the delivered PHY/coexistence/source/header contents, preventing changes to those bytes going unnoticed by this verifier. The subsequent [semantic rebase review](idf_553_rebase_review.md#5-whole-radio-bundle-identity-and-actual-link-inputs) compared every regular packaged file in `esp_wifi` (163), `esp_phy` (114), `esp_coex` (41), and `wpa_supplicant` (301) against the installed candidate: all matched. This is complete comparison of those delivered component trees, not merely seven Wi-Fi archives. This is **not** an independent recursive source-to-package audit, vendor signature verification, proof of opaque implementation correctness, or execution of the compiler binaries.
## Reproduce preparation and verification
From the repository root, with Python 3.9+ on Linux x86_64:
```sh
python3 -B tools/idf_candidate/test_prepare.py
python3 -B tools/idf_candidate/prepare.py
```
The second command is offline, verifies all four already-downloaded archives, and makes no installation. Missing or altered inputs fail. Four offline helper tests cover corrupted hash/size, URL restrictions, contract failure, and absent/ambiguous archive members.
On a fresh checkout, download and create the isolated project:
```sh
python3 -B tools/idf_candidate/prepare.py --fetch --prepare
```
Network is restricted by the tool to HTTPS `dl.registry.platformio.org` and `dl.registry.nm1.platformio.org`, including redirects. Approximately 993 MB download space is needed plus substantial unpacked/build space for the later test. `--sdk-only --fetch` obtains/verifies only the platform and SDK. Existing mismatched archives fail rather than being overwritten. A killed download may leave a `.partial` file; inspect/remove that candidate-only partial before retrying. `--prepare` deliberately refuses an existing smoke directory rather than overwriting it. **Preparation already succeeded here**; use offline verification, not a second `--prepare`.
Generated smoke project: `.pio/idf-candidate-5.5.3/smoke/`. Its configuration uses the verified local official platform archive and exact local framework/toolchain archives, with `core_dir` under `.pio/idf-candidate-5.5.3/core/`. Its sources are a separate empty `app_main`; it neither inherits production config nor imports application overrides. Generic official ESP32-S3 board is intentional: this tests package integration, **not** the production N16R8 board or feature configuration.
### Command to test the isolated candidate
After successful verification, from the repository root:
```sh
env -u PLATFORMIO_PACKAGES_DIR -u PLATFORMIO_PLATFORMS_DIR -u PLATFORMIO_BUILD_DIR -u PLATFORMIO_CACHE_DIR -u IDF_PATH -u IDF_TOOLS_PATH -u IDF_PYTHON_ENV_PATH PLATFORMIO_CORE_DIR=/home/mscholz/Repos/ESP32_serial_swiss_army_knife/.pio/idf-candidate-5.5.3/core CCACHE_DISABLE=1 pio run --project-dir .pio/idf-candidate-5.5.3/smoke
```
For another checkout location, replace the absolute `PLATFORMIO_CORE_DIR` accordingly. Run in a normal clean PlatformIO shell, not an activated unrelated IDF environment. The initial preparation task did **not run this smoke invocation**; the later fresh application build PASS is recorded above and does not retroactively claim execution of this exact smoke command. It may download platform ancillary packages and IDF Python dependencies (registry/mirror, PyPI/files.pythonhosted.org and Espressif download endpoints as requested by the adapter); grant those hosts separately as needed. Those ancillary/Python dependencies are not yet a complete frozen build closure. The prepared four-input lock is not advertised as a fully reproducible toolchain environment/SBOM. No upload, monitor or erase command is part of this evaluation.
## Rebase disposition and remaining integration gates
The official package-availability/toolchain mismatch question and bounded application build/host compatibility checks are resolved for the validated candidate. The [per-entry semantic review](idf_553_rebase_review.md#3-per-entry-semantic-disposition) retains every old protected correction (rebasing changed IDF original hashes), retains wolfSSH C/ABI overlays, and adds the ninth C override for five signed WS receive-size comparisons. Nothing was removed as superseded or bypassed by a permissive version guard. Reviewed heap extent/private HTTPD guards now target 5.5.3; generated-input ownership/include order and behavioral suites pass on the final build.
Remaining gates:
1. A successful normal root build: the default attempt stopped during installation, before compilation. Exact root version pins are not enforcement of the downloaded archive hashes.
2. Complete immutable ancillary/Python/tool/managed-component dependency closure; four verified primary archives and source equality are not a full reproducible environment or SBOM.
3. Target/radio/resource/recovery validation in the [Wi-Fi plan](wifi_security_update_plan.md), including the exact trigger and unchanged PMF/WPA3. Candidate integration is not hardware vulnerability closure.
4. Recipient notices, corresponding source, radio-blob legal basis and release-specific runtime/bootloader attribution. Nine notice entries have been semantically rebased and 66 retained unchanged, but assembly is not delivery or legal clearance.
5. Explicit whole-Phase-9 target acceptance. No upload, erase, credential migration, PMF weakening or generated-asset regeneration is part of this documentation update.
+267
View File
@@ -0,0 +1,267 @@
# Focused installed ESP-IDF security applicability review
## Finite applicability completion — 2026-09-16
**Current disposition supersedes the historical recommendations below.** This slice covers exactly the six previously named mbedTLS findings and the disabled/unused-feature entries on the first page of the official IDF advisory index. It is **not an exhaustive CVE inventory, security certification, upgrade approval, or Phase 9 sign-off**. Only this document was edited; no source/configuration/generated-file edits, build, test compilation, or device commands were performed.
### Effective source and configuration evidence
Rechecked installed **ESP-IDF 5.5.0 / mbedTLS 3.6.3**, not just upstream release ranges. Evidence is the existing `.pio/build/esp32-s3-devkitc-1-n16r8/` configuration and compilation database, installed source under `/home/mscholz/.platformio/packages/framework-espidf/`, and the checked-in override renderer. This establishes configured inputs, **not executable freshness or the firmware running on a device**.
- The current registry has **eight C replacements plus one wolfSSH internal-header overlay**. The seven-source count in the September 15 addendum is historical. Read-only `python3 -B` inspection called `verify_version()` and `render_entry()` only for the **six IDF-owned entries**, checked original hashes, and compared rendered bytes against existing generated copies: all six matched. No generator or build was run; wolfSSH bytes were outside this slice.
- Filtered compilation entries select generated `dhcpserver.c`, `ssl_tls.c` and `x509_create.c`, but original `ecdh.c`, `pk_ecc.c`, `pkparse.c`, `ecp_curves.c`, `asn1write.c`, `x509_crt.c`, `ssl_tls12_server.c` and `httpd_ws.c`. None of the six newly classified findings has a project source backport. The mbedTLS entries use `MBEDTLS_CONFIG_FILE="mbedtls/esp_config.h"`; inspected command flags add no alternative user config. `esp_config.h` includes the generated `sdkconfig.h` and maps its ECP/NIST options to the library macros.
- Generated header: `CONFIG_MBEDTLS_ECP_C=1`, `CONFIG_MBEDTLS_ECP_NIST_OPTIM=1`, `CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=1`, TLS 1.2 and client/server support enabled, TLS 1.3 absent. P-521 is enabled (maximum ECP output 66 bytes). Hardware MPI support is enabled, **not** a replacement for all software ECC reduction. Both mbedTLS client/server ticket options are enabled, but **`CONFIG_ESP_TLS_SERVER_SESSION_TICKETS` is absent**. Do not describe tickets as globally compiled out.
- Rechecked generated EMS error branch (`mbedtls_ssl_tls/ssl_tls.c:70837086`) returns before derivation, and generated X.509 OID allocation (`mbedtls_x509_create/x509_create.c:313317`) checks NULL before copying. These fixes are separate from ECDH, PK parsing, basicConstraints and ASN.1 value-state issues.
Additional installed-source SHA-256 evidence (paths below relative to `components/mbedtls/mbedtls/library/`; earlier original hashes remain unchanged):
| Source | SHA-256 |
| --- | --- |
| `ecdh.c` | `85439414902f8421db8921c69a0be771ed69a7c69f0722127298f41a1d330ba8` |
| `pk_ecc.c` | `19ba6ca1251a610a53e3654a7727ba881c358a29d46f4586ab3c7e07c846b5bf` |
| `pkparse.c` | `36c0590c516a1b4ad99bfefc213da1a19a2e27638ee3f267ea3365cc738ecf17` |
| `x509_crt.c` | `799f6993d323d9158bf832967f404e9c63b0d76c0a72023be7a80c42630020fd` |
| `ecp_curves.c` | `29329ed2ecad6e68f615b1b5a3e7c592a0b625c4d1a1090280e305fa9afb51d3` |
| `ssl_tls12_server.c` | `ddf8d37e862d4176d27b928592b1971d2f397f50c4b1fac2443d099c3e9cab99` |
### Disposition matrix
**Addressed** means the specified source correction exists, not target acceptance. **Not-current-path** means this finding's prerequisite is absent in the inspected configuration/callers, not that the library is patched. **Excluded** is a threat-model boundary, not technical immunity. **Unresolved** marks evidence/coverage still absent.
| Finding | Disposition | Current evidence and boundary |
| --- | --- | --- |
| CVE-2026-45160 DHCP; CVE-2026-50581 TLS 1.2 EMS; CVE-2026-34874 X.509 OID OOM | **Addressed, scoped source corrections** | Existing pinned generated inputs match the renderer. Earlier host/build evidence remains attributed below; not rerun. EMS correction is TLS 1.2 only. |
| CVE-2026-35336 ECDH small output buffer | **Not-current-path; primitive unpatched** | `ecdh.c:649659` compares `mpi_size(z)` but writes curve-width bytes. HTTPS TLS premaster storage includes `MBEDTLS_ECP_MAX_BYTES`; no application direct caller supplies a small buffer. See caller qualification below. |
| CVE-2026-50583 zero-length ECC PK parse | **Not-current-path / configuration not affected** | Advisory explicitly excludes built-in ECC in 3.x. `MBEDTLS_ECP_C` is enabled; `pk.h:179182` requires it to be **absent** for `MBEDTLS_PK_USE_PSA_EC_DATA`. Active ECP-backed parser rejects `ilen < 1` before inspecting the point. |
| CVE-2026-49300 basicConstraints | **Not-current-path; parser unpatched** | Both lax parsing behaviors exist. No untrusted certificate/trust-root enrollment or HTTPS client-certificate authentication was found; local identity validation requires CA=false. No current cross-validator CA promotion path established. |
| CVE-2026-54435 ECC optimized reduction side channel | **Excluded attacker model; affected code active** | NIST optimization and deterministic ECDSA are enabled; P-256 identities use mbedTLS. Privileged-local precise execution traces / physical side channels are outside this network-focused review. No constant-time, hardware immunity, or key-extraction-resistance claim. |
| CVE-2026-50586 NewSessionTicket disclosure | **Not-current-path; server tickets disabled, primitive unpatched** | HTTPS defaults `session_tickets=false`, application does not override it; ESP-TLS callback registration is additionally compiled out. mbedTLS ticket machinery itself remains enabled. |
| CVE-2025-48965 stale ASN.1 value length | **Not-current-path; primitive unpatched** | `asn1write.c:412415` still clears pointer without length. Certificate creation uses fresh subject/issuer lists, each a single fixed-format nonempty CN. Exact upstream one-line fix is now resolved below. |
| CVE-2026-45541 WS subprotocol | **Not-current-path; SDK unpatched** | Existing manual-admission/NULL-subprotocol disposition below remains; not reclassified as globally fixed by this slice. |
| Target fault behavior, local side-channel feasibility, running firmware, advisories beyond this finite set/index page | **Unresolved / not evaluated** | No runtime measurements, fault injection, exhaustive inventory or target acceptance supplied by this review. Revisit applicability whenever callers, features or trust enrollment change. |
### Evidence for the six named findings
**CVE-2026-35336:** fetched the official [ECDH advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-07-possible-buffer-overflow-ecdh-calc-secret.md) and [source fix `1d71bcc31cb8080b14b0dcbc6bc859c11d622c0f`](https://github.com/Mbed-TLS/mbedtls/commit/1d71bcc31cb8080b14b0dcbc6bc859c11d622c0f.patch). First fixed 3.6.x release: **3.6.7**. Installed vulnerable comparison matches the removed hunk. `ssl_tls12_server.c:37853789` passes `handshake->premaster`; `ssl_misc.h:990` sizes it as `MBEDTLS_PREMASTER_SIZE`, whose union in `ssl.h:691724` includes `_pms_ecdh[MBEDTLS_ECP_MAX_BYTES]`. Although the TLS call's `blen` argument is `MBEDTLS_MPI_MAX_SIZE`, the **actual object**, not merely that argument, is sufficient for every enabled ECDH curve. The advisory explicitly says TLS ECDH is unaffected. Targeted `src/` search found no direct `mbedtls_ecdh_calc_secret()` caller.
Also checked the installed Wi-Fi adapter rather than assuming HTTPS is the only SDK consumer: `wpa_supplicant/esp_supplicant/src/crypto/crypto_mbedtls-ec.c:803` uses the DPP maximum 66; DPP is not enabled in the generated configuration. Its `crypto_ecdh_set_peerkey()` at line 1290 uses `pbits / 8`; the inspected OWE caller in `src/rsn_supp/wpa.c` restricts both offered/received group to **19 (P-256)**, so this does not supply the advisory's non-byte-aligned P-521/floor-size trigger. OWE support **is** compiled in; this is not a blanket audit of its parsing or every SDK ECDH wrapper. Future arbitrary-curve callers must allocate and pass at least `(pbits + 7) / 8`, or use `MBEDTLS_ECP_MAX_BYTES`. A pinned `ecdh.c` backport is defense in depth, not a demonstrated current HTTPS overflow correction.
**CVE-2026-50583:** fetched the official [zero-length ECC public-key advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-07-zero-length-ecc-public-key-oob-read.md). It affects driver-only PSA ECC in 3.5.03.6.6, not built-in ECC. Original `pk_ecc.c:204220` has the unchecked `*pub` only under `MBEDTLS_PK_USE_PSA_EC_DATA`; its active `#else` calls `mbedtls_ecp_point_read_binary()`, whose `ecp.c:775777` checks `ilen < 1`. Application PK parsing **does occur**, in `src/web_security.c:409414` and `src/ssh_security.c:156181`, as well as ESP-TLS identity loading. Neither trusted storage nor a post-parse key check is being used as the exclusion: the decisive evidence is the built-in ECP path. Advisory identifies `0e2d7037db4048dbf1c194508c07384a818261d5` as the 3.6.x fix; no backport is installed or needed to close this configuration-specific finding. Reassess before moving to driver-only ECC.
**CVE-2026-49300:** fetched the official [basicConstraints advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-07-x509-ca-bit-forgery-invalid-basicconstraints.md). Installed `x509_crt.c:494555` lacks the inner-SEQUENCE length equality check and accepts INTEGER in place of BOOLEAN. The extension caller at line 966 supplies `end_ext_octet`, so comparison against the exact inner sequence is still necessary. First fixed 3.6.x release: **3.6.7**.
Current `src/web_security.c` generates its own P-256 self-signed identity, `basicConstraints(false, -1)`, and parses persisted identity at lines 409414. Validation checks matching keys, expected subject/issuer, self-signature, and specifically rejects `ca_istrue != 0` at lines 442444. `src/web_server.c:673691` retains default `cacert_pem=NULL`; generated ESP-TLS selects `MBEDTLS_SSL_VERIFY_NONE` for server peer authentication (`CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL` absent). Application authentication is not certificate-chain enrollment. Targeted application searches found no outbound ESP-TLS/HTTP client or untrusted certificate/CSR import; Wi-Fi configuration uses personal PSK/SAE profiles, not EAP credential/CA provisioning. These are current-use observations, **not global removal of X.509/client/enterprise support** (those libraries/features are available). A corrupt local blob being rejected is not evidence that the library parser is fixed.
Backport provenance correction: fetched [sequence fix `07f45b87681c1a0680c260089d3e6349b25fdd08`](https://github.com/Mbed-TLS/mbedtls/commit/07f45b87681c1a0680c260089d3e6349b25fdd08.patch). The advisory's listed “Basic fix #2,” [`4fb9c9e439fd1e7e44697d23d50f00b4642fbe08`](https://github.com/Mbed-TLS/mbedtls/commit/4fb9c9e439fd1e7e44697d23d50f00b4642fbe08.patch), changes **test encodings only**. A bounded official commit-history query for `library/x509_crt.c` at tag `mbedtls-3.6.7` located the actual [INTEGER-rejection source change `f67b8e5bded0c531b29480b8c5b7285366b1b153`](https://github.com/Mbed-TLS/mbedtls/commit/f67b8e5bded0c531b29480b8c5b7285366b1b153.patch), also fetched and compared. Do not backport the advisory's two listed hashes and claim both source defects fixed. No parser backport or runtime vector validation was performed here.
**CVE-2026-54435:** fetched the official [optimized modp side-channel advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-07-ecc-optimized-modp-side-channel.md). First fixed 3.6.x release: **3.6.7**. Installed `ecp_curves.c` retains specialized P-256 reduction and data-dependent carry/sign handling (`NEXT`, `LAST`, `mbedtls_ecp_fix_negative`, around lines 49005036); no override replaces it. Application key generation/loading and certificate signing genuinely use P-256; this is **not an unused-crypto finding**. Upstream requires privileged-local sufficiently precise traces (typically an untrusted OS attacking an enclave); physical side channels are also possible, not measured here. Disabling NIST optimization is an upstream workaround for NIST curves only, carries substantial performance cost, and does not cover Koblitz/Montgomery curves. No configuration change is recommended blindly on this resource-constrained target. Reopen for a local/physical attacker threat model or deliberate maintained-library update; the upstream multi-commit fix range was identified in the advisory but not patch-audited in this excluded slice.
**CVE-2026-50586:** fetched the official [TLS 1.2 ticket disclosure advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-07-tls12-newsessionticket-information-disclosure.md). First fixed 3.6.x release: **3.6.7**. Original `ssl_tls12_server.c:42424246` still declares uninitialized `tlen`/`lifetime`; failed ticket generation may disclose four stack bytes. `esp_https_server.h:183192` defaults client CA to NULL and `session_tickets=false`; the application preserves both. Generated HTTPS `create_secure_context()` initializes tickets only under `config->session_tickets`; generated ESP-TLS registers callbacks only under `CONFIG_ESP_TLS_SERVER_SESSION_TICKETS` and non-NULL `cfg->ticket_ctx`. Neither prerequisite holds. This is disabled **server-side TLS session tickets**, not application WebSocket/admin tickets, cookies, or compiled-out mbedTLS ticket support. Reassess and backport/init both outputs before enabling the feature; advisory lists `99ccd257e2d6c5fc53bc970e3e533a90c363f8e1` and `548ed19f707565db5fb4c2487edd7ae1bea50199` (not patch-verified here).
**CVE-2025-48965:** re-fetched the official [ASN.1 advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2025-06-6.md). First fixed release: **3.6.4**. Rechecked original stale-length branch and fixed-format CN generation (`src/web_security.c:92111,128240`); subject and issuer are separate fresh lists, not repeated OIDs within one list. No application direct named-data/string-name API consumer besides those fixed name setters was identified. This is not the separately addressed OID-allocation failure. A bounded official history query for `library/asn1write.c` at `mbedtls-3.6.4` resolved and fetched [fix `2df7ab7c0c3d5bb8a31481073c494521d10d4eba`](https://github.com/Mbed-TLS/mbedtls/commit/2df7ab7c0c3d5bb8a31481073c494521d10d4eba.patch): exactly `cur->val.len = 0;` after clearing `cur->val.p`, plus repeated-OID tests. Its context matches installed lines 412415. **The older unresolved-fix-commit statement below is now resolved; the source bug remains unpatched.** If backported defensively, select actual nested target `mbedcrypto`, retain source pin/notices and allocation-failure preservation, and test nonempty→empty→same-length replacement and serialization.
### Bounded IDF advisory-index snapshot: disabled/unused features
Fetched [official IDF index, page 1](https://github.com/espressif/esp-idf/security/advisories) on **2026-09-16**: ten entries spanning February 3September 3, 2026, newest listed A2DP/L2CAP. Fetched each of the eight remaining feature advisories below; the other two are DHCP and WS already covered above. **Pages 23, broader historical/vendor advisory coverage and future publications were not reviewed.** Later affected-release labels do not establish that installed 5.5.0 is fixed; dispositions here rely on feature/target/caller absence, not release-table inference.
| Official advisory / CVE | Required feature | Snapshot disposition and local evidence |
| --- | --- | --- |
| [GHSA-xcpr-5mqp-9qvv](https://github.com/espressif/esp-idf/security/advisories/GHSA-xcpr-5mqp-9qvv), CVE-2026-81508 | Bluedroid Classic A2DP sink; paired BR/EDR source | **Not-current-path**: BT disabled; no BT host compile inputs. |
| [GHSA-v335-fxwc-rc44](https://github.com/espressif/esp-idf/security/advisories/GHSA-v335-fxwc-rc44), CVE-2026-81507 | Bluedroid Classic L2CAP configuration | **Not-current-path**: same disabled BT evidence; no claim that authentication would mitigate this unauthenticated path. |
| [GHSA-3pp8-42fh-3j3c](https://github.com/espressif/esp-idf/security/advisories/GHSA-3pp8-42fh-3j3c), CVE-2026-46532 | Bluedroid AVRCP target, paired BR/EDR peer | **Not-current-path**: same disabled BT evidence. |
| [GHSA-9r76-858f-v6jh](https://github.com/espressif/esp-idf/security/advisories/GHSA-9r76-858f-v6jh), CVE-2026-45542 | NimBLE protocomm Security2 provisioning | **Not-current-path**: BT/NimBLE absent; no application protocomm/Wi-Fi provisioning API use found. SoftAP itself is not this provisioning service. |
| [GHSA-h7r3-gmg9-xjmg](https://github.com/espressif/esp-idf/security/advisories/GHSA-h7r3-gmg9-xjmg), CVE-2026-25507 | BLE provisioning teardown with `keep_ble_on=true` | **Not-current-path**: same disabled BLE/no provisioning service evidence, not a verified vendor UAF fix. |
| [GHSA-v6r2-f6p2-88cj](https://github.com/espressif/esp-idf/security/advisories/GHSA-v6r2-f6p2-88cj), CVE-2026-55687 | Hardware JPEG decoder DQT parsing | **Not-current-path**: ESP32-S3 configuration, no `esp_driver_jpeg` compilation input or application JPEG calls. No malformed-image testing. |
| [GHSA-w82j-7q63-7pqm](https://github.com/espressif/esp-idf/security/advisories/GHSA-w82j-7q63-7pqm), CVE-2026-45329; [GHSA-mmgp-73p4-92xp](https://github.com/espressif/esp-idf/security/advisories/GHSA-mmgp-73p4-92xp), CVE-2026-45328 | ESP-TEE REE/TEE secure-service wrappers | **Not-current-path**: target is Xtensa ESP32-S3, not the advisory's supported RISC-V TEE SoCs; no `esp_tee` compilation inputs or enabled TEE setting. This exclusion is distinct from choosing not to implement secure boot/encrypted NVS. |
Local snapshot evidence: generated `sdkconfig.h` selects `CONFIG_IDF_TARGET="esp32s3"` / `CONFIG_IDF_TARGET_ARCH_XTENSA=1`; no enabled `CONFIG_BT_ENABLED`, `CONFIG_BT_BLUEDROID_ENABLED`, `CONFIG_BT_NIMBLE_ENABLED` or ESP-TEE option. Filtered existing compilation database counts for `/bt/host/`, `/esp_tee/`, `/esp_driver_jpeg/`: **0 each**. `src/` searches for provisioning/protocomm/JPEG APIs found none. This is a feature screen, not inspection or certification of the disabled vendor implementations. Re-enabling any feature invalidates its disposition.
### Parent handoff and remaining limits
**No new current-path actionable source correction established among these six named findings.** Keep the existing DHCP/EMS/OID-allocation fixes. Optional defense-in-depth candidates are the exact ASN.1 one-line fix, ECDH curve-width bounds check and both basicConstraints source fixes; they must not be represented as already implemented. The basicConstraints test-only commit mismatch is actionable **backport guidance**, not evidence of a present authentication bypass. Preserve server ticket disablement and re-review before introducing certificate imports, driver-only ECC, arbitrary-curve ECDH callers or local isolation requirements.
Completed evidence work: official six-advisory fetches, focused upstream patch comparisons/history queries, original-source/config/caller inspection, read-only equality checks of six IDF generated overrides, and filtered configured-input inspection. Document-scoped `git diff --check` and the corrected document-presence/link-count check passed (the initial checker incorrectly expected twice the number of advisory URLs). Concurrent changes appeared in other agents' parser/override/release-notice files during the review; none were edited or reverted here, and source/configuration evidence above is the inspected snapshot, not certification of subsequent changes. No exploits, new host regression tests, build or device validation were run. The finite applicability questions above are dispositioned; full advisory coverage, runtime fault/timing behavior and whole-phase target acceptance remain unresolved. **Do not summarize this as “all CVEs safe.”**
## Implementation addendum — 2026-09-15
**Implemented, with host/build evidence; not target validation or a completed advisory review.** Source checked against `tools/security_overrides.py`, `cmake/security_overrides.cmake` and the existing generated copies:
- **CVE-2026-45160:** pinned DHCP backport handles PAD/END before length access, validates remaining payload length and minimum type/IP lengths, and advances by the validated length. Remaining-length comparisons deliberately avoid forming out-of-object pointers.
- **CVE-2026-50581:** TLS 1.2 EMS `calc_verify` failure now returns `ret` before derivation. This is the TLS 1.2 hunk only, not the upstream TLS 1.3 correction or a global mbedTLS update.
- **CVE-2026-34874:** X.509 OID allocation failure now returns `MBEDTLS_ERR_X509_ALLOC_FAILED` before `memcpy()`.
- The registry now has **seven** entries: the four historical entries below plus `dhcpserver` on `lwip`, `mbedtls_ssl_tls` on nested target `mbedtls`, and `mbedtls_x509_create` on nested target `mbedx509`. Nested-target selection validates the allowlist and owning SDK library directory, rejects imported/alias targets, and retains the exactly-one-source/property-preservation checks. All seven generated copies were read-only verified against rendered pinned inputs; each carries the project modification notice dated **2026-09-15**, retaining upstream notices.
- **Still unpatched:** CVE-2026-45541 WS negotiation and CVE-2025-48965 ASN.1 named-data state. Their baseline applicability qualifications below remain; the three backports do not fix them.
Supplied parent evidence: `pio run` **PASS**, **94,340 B linked RAM / 1,767,217 B flash** (unchanged RAM, **64,092 B flash** from the 9C 1,831,309 B baseline; includes the wolf crypto policy). Parent reports all four focused commands in [hardening validation](security_hardening.md#mitigation-hostbuild-evidence--2026-09-15) passed; independent reviewer reports the SDK-override and wolf-crypto-policy suites passed with no blocking implementation defects. These commands were not rerun for this documentation update. No target evidence, dependency upgrade, asset regeneration or device operation is claimed. Broader advisory review and whole-phase acceptance remain open.
## Historical pre-mitigation research baseline — 2026-09-15
**The remainder preserves the original investigation, hashes, applicability and proposed tests. Statements such as “not implemented,” “current,” four entries and original compilation inputs describe that earlier snapshot, not the implementation above.**
Review date: **2026-09-15**. Scope: the installed `/home/mscholz/.platformio/packages/framework-espidf`, current application source, and checked-in/generated security overrides. **Review and recommendations only; no fixes implemented.** No build, test compilation, upload, monitor, erase, or device operations were performed.
This is not a complete IDF/mbedTLS advisory inventory, certification, or statement that an old version is safe. Advisory release tables are not sufficient to identify downstream backports: the installed implementation and actual source registration were inspected.
## Decision summary
| Issue | Confirmed local finding | Application applicability | Recommended priority |
| --- | --- | --- | --- |
| CVE-2026-45160, DHCP option parsing | Original vulnerable parser compiled; no override | Exposed whenever the project SoftAP/DHCP server is active; adjacent associated client, no application login required | **First correction:** backport the release/v5.5 bounds fix |
| CVE-2026-45541, WS subprotocol parsing | Vulnerable SDK function compiled; no override | Faulty tokenization loop **not reached by current application upgrades**, which pass `NULL`; both routes are ordinary HTTP handlers | Defense-in-depth backport; preserve current admission-before-101 design |
| CVE-2026-50581, ignored EMS error | Missing early return in installed `ssl_compute_master()` | TLS 1.2/EMS path used by HTTPS; hash/allocation failure prerequisite. Cipher restriction and disabled renegotiation do not remove this path | Prompt fail-closed correction alongside DHCP/X.509 work |
| CVE-2025-48965, ASN.1 named-data state | Zero-length replacement clears pointer but leaves stale length | Current certificate names are trusted, single nonempty CNs; malicious repeated-OID/empty-value trigger not provided by current name generation | Lower-priority library correction/regression coverage |
| CVE-2026-34874, X.509 name allocation failure (3.6.6 fix) | Unchecked allocation immediately followed by `memcpy()` | **Used by local certificate creation**, even with the safe fixed CN; OOM can trigger it | Prompt correction; fixed input is not a mitigation |
**Important correction to issue classification:** CVE-2025-48965 is not the X.509 allocation-failure bug. Its official advisory describes a stale `val.len` after a zero-length replacement. CVE-2026-34874 is the separate unchecked allocation fixed in 3.6.6. Do not merge their applicability or mark either fixed by the project's HTTPD scratch allocator changes.
## Exact reviewed baseline and registration
Installed `components/esp_common/include/esp_idf_version.h` defines **5.5.0**. `components/mbedtls/mbedtls/include/mbedtls/build_info.h` defines **3.6.3**, `0x03060300`. The following SHA-256 values were calculated from installed bytes, not inferred from version labels. Paths are relative to the installed IDF root:
| Installed source | SHA-256 |
| --- | --- |
| `components/esp_common/include/esp_idf_version.h` | `30fdfbed6cc0055a89f3454f61b56d5e5643bbc46c0774aae63e41869cf2947a` |
| `components/lwip/apps/dhcpserver/dhcpserver.c` | `953f46189bc64680ea5fa761e75511fadb3aebf698a0d9dff251d77166d78b80` |
| `components/esp_http_server/src/httpd_ws.c` | `e514f603a696e3e775573bc8882a350691e31fcae96e435f9062248e7c91677c` |
| `components/mbedtls/mbedtls/library/ssl_tls.c` | `b726c0c55bc5f32255f129d55f9f2fface85ce83de90a2d16c9017b93b738bff` |
| `components/mbedtls/mbedtls/library/asn1write.c` | `6667aebb1e5f0500ef4a281fe2752fc7bc59610e7bfc01d2916d224e5bc5c3e3` |
| `components/mbedtls/mbedtls/library/x509_create.c` | `fd399239aee30384786a19b47bfe5dd22b979d5d89bb38f29f0c82a3d81daaf7` |
### Checked-in edits are part of the effective source
Root `CMakeLists.txt:1516` includes `cmake/security_overrides.cmake` after `project()`. That file invokes `tools/security_overrides.py`, loads its manifest, and replaces exactly one source on the resolved component target, preserving source properties and original quoted-include directory. Version/source/hash/edit ambiguity fails configuration.
The registry currently has exactly four entries:
| Entry | Component | Protected original SHA-256 |
| --- | --- | --- |
| `wolfssh_internal` | `wolfssl__wolfssh` | `81ff1f9166708abd5c2911e9fe57c0aee01c88b5d3f68c909ee8a856d37f36a9` |
| `https_server` | `esp_https_server` | `6481942b62e51125e2a43441fa0900cbda74bd2ea05c82f0c29eb4933c31946e` |
| `httpd_parse` | `esp_http_server` | `6bba77064aaa68a06f8d4c01432064a1b050c91ed22741c547785b0d8a6c07d8` |
| `esp_tls_mbedtls` | `esp-tls` | `09210c5a601647ca5775d127a2951bab2f3e509192b53487bbea8a93d8731b78` |
Read-only Python inspection called `verify_version()` and `render_entry()` in memory (not `generate()`), verified all four original pins, and compared rendered bytes with the existing generated files: **all four matched exactly**. This did not rewrite installed or generated files.
The existing `.pio/build/esp32-s3-devkitc-1-n16r8/security_overrides/manifest.cmake` and narrowly filtered `compile_commands.json` register those four generated sources, but register **original** `dhcpserver.c`, `httpd_ws.c`, `ssl_tls.c`, `asn1write.c`, and `x509_create.c`. Thus HTTPS cleanup, HTTPD scratch wiping/null handling, TLS policy, and wolfSSH fixes do **not** constitute fixes for these five findings.
This confirms existing configured compilation inputs, not freshness of the executable, successful rebuilding, or the firmware installed on a device.
### mbedTLS registration constraint
Installed `components/mbedtls/CMakeLists.txt` imports upstream nested targets. The existing compile database's object paths confirm:
- `ssl_tls.c` → target `mbedtls` (`.../CMakeFiles/mbedtls.dir/ssl_tls.c.obj`).
- `x509_create.c` → target `mbedx509`.
- `asn1write.c` → target `mbedcrypto`.
The current replacement helper resolves an **IDF component's** `COMPONENT_LIB`; it does not resolve these nested library targets. Simply adding `Entry(..., "mbedtls", ...)` would select the component wrapper, not the actual owning target, and should fail its exactly-one-source check. A future patch must minimally add an explicit, validated target-selection mechanism for these three nested targets while retaining current component resolution for existing entries. Do not weaken the match check or add duplicate source compilation to the wrapper.
## CVE-2026-45160 — DHCP server `parse_options()`
Official [GHSA-g764-gwc3-75m5](https://github.com/espressif/esp-idf/security/advisories/GHSA-g764-gwc3-75m5) and fetched [release/v5.5 patch](https://github.com/espressif/esp-idf/commit/d51b1076092487e533eadf8b48c9c8579d3a6712.patch).
**Exact upstream fix commit:** `d51b1076092487e533eadf8b48c9c8579d3a6712`.
Confirmed installed `dhcpserver.c:902952`:
- Loop only checks `optptr < end`.
- Message type reads `optptr[2]` without validating a length byte or payload.
- Requested IP compares four bytes without a declared/remaining-length check.
- Advancement reads `optptr[1]` without ensuring it exists.
- PAD is not treated as a one-byte option.
The GHSA lists later affected point releases and a planned 5.5.5 fix; that is **not evidence excluding 5.5.0**. The old implementation is directly present here.
### Reachability
`src/wifi_manager.c:create_default_wifi_netifs()` explicitly builds `ESP_NETIF_DEFAULT_WIFI_AP()` and installs default AP handlers. Installed `esp_netif_defaults.h:5961` sets `ESP_NETIF_DHCP_SERVER | ESP_NETIF_FLAG_AUTOUP`. Existing generated configuration has `CONFIG_LWIP_DHCPS=1`. `start_radio_and_policy()` selects AP/APSTA when policy requires it; `set_runtime_ap_enabled()` also permits STA→APSTA activation.
This is therefore an applicable exposure when SoftAP is active, not a hypothetical unused SDK feature. A station-only moment is not a permanent mitigation if fallback or administrative policy can enable AP later. The official impact is adjacent-network denial of service, not demonstrated heap disclosure: the advisory says overread bytes are not echoed. WPA association controls reduce access but do not fix the parser. No live attack or actual device AP state was tested.
### Minimal recommended edits (not implemented)
Add a pinned `idf` entry for `components/lwip/apps/dhcpserver/dhcpserver.c`, component `lwip`, using the exact original hash above. Backport the official patch's PAD definition and parser changes:
1. Skip PAD; terminate at END before reading a length.
2. Require a length byte and the entire declared payload to fit.
3. Require message-type payload length ≥1 and requested-IP length ≥4.
4. Advance using the already-validated `opt_len`; remove the obsolete end flag.
5. Retain notices and existing post-loop state behavior.
For a strict-C bounds implementation, consider remaining-length comparisons (`end - optptr >= 2`, then `opt_len <= remaining - 2`) rather than constructing a pointer beyond the object in the upstream `optptr + 2 + opt_len > end` check. If chosen, document this small deviation and test equivalence; this review did not apply or test either form.
Future tests: empty options, lone option code, missing length, oversized payload, PAD sequences, END at boundary, short type/IP fields, valid DISCOVER/REQUEST/RELEASE and option combinations. Verify actual generated `lwip` compilation input, no duplicate original, and no changes to AP policy, broker, UART0, or USB recovery.
## CVE-2026-45541 — WS subprotocol negotiation
Official [GHSA-3j8v-xgrq-5vg8](https://github.com/espressif/esp-idf/security/advisories/GHSA-3j8v-xgrq-5vg8) and fetched [release/v5.5 patch](https://github.com/espressif/esp-idf/commit/00a2f7fbbbd8fe6d04729022e1d5c9a49435bfe8.patch).
**Exact upstream fix commit:** `00a2f7fbbbd8fe6d04729022e1d5c9a49435bfe8`.
Installed `httpd_ws.c:7095` has `strtok_r()` followed by a `do` loop that dereferences its possibly NULL result. It also compares using `sizeof(subprotocol)`, the pointer size rather than protocol length. A nonempty delimiter-only header can yield no tokens.
### Current route registration avoids the defective loop
- Existing configuration has `CONFIG_HTTPD_WS_SUPPORT=1`; disabling WS at compile time is **not** the reason for non-reachability.
- `src/web_server.c:518539` defines serial and admin upgrade routes with `.is_websocket = false`; omitted `supported_subprotocol` members of these static initializers are NULL. `start_server()` actually registers the serial handler array and optional admin route.
- `src/web_serial_transport.c:745` and `src/web_admin_transport.c:570` use `web_httpd_upgrade()` after admission.
- `src/web_httpd_adapter.c:174` calls `httpd_ws_respond_server_handshake(request, NULL)`.
- Installed `httpd_ws_get_response_subprotocol()` returns at its `supported_subprotocol == NULL` check **before** tokenization. The optional registration adapter also rejects `is_websocket` or `supported_subprotocol`.
Conclusion: vulnerable library bytes are present, but **this CVE's NULL-token dereference is not reachable through the current application upgrade paths**. The official generic warning about pre-application-authentication crashes applies to automatic SDK WS negotiation with a non-NULL supported protocol; it should not be copied onto these manual-admission routes without this qualification. TLS alone is not a general mitigation.
### Minimal recommended edits (not implemented)
Add a separately pinned `httpd_ws.c` entry for component `esp_http_server`; do not conflate it with the existing `httpd_parse.c` entry. Backport the upstream `while (s != NULL)` loop, exact-length match and explicit next-token step, retaining notices. Do not enable automatic upgrades or add a subprotocol to justify the patch.
Future tests: empty/delimiter-only headers, NULL supported protocol, unsupported protocol, exact match and prefix mismatch, plus current cookie/Origin/ticket admission-before-101 behavior. Mark it as a defense-in-depth fix, not closure of a demonstrated unauthenticated application crash.
## Bounded mbedTLS 3.6.3 review
### CVE-2026-50581 — EMS calculation failure ignored
Official [advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-07-extended-master-secret-calculation-failure-ignored.md), published 2026-07-07. Affects through 3.6.6; first fixed 3.6.x release is **3.6.7**, not 3.6.6.
Fetched [basic fix](https://github.com/Mbed-TLS/mbedtls/commit/f595df4569c1a1650ad9d077e2f2e819e9f1dddb.patch): **`f595df4569c1a1650ad9d077e2f2e819e9f1dddb`**. Advisory gives test/documentation range `338572c1d805a31b875a448536bcb50d72f9bc40..27065ceb643a4266888ba1f200e4f20845e801cf`; that range was not reviewed here.
Confirmed installed `ssl_tls.c:70417085`: `session_hash[48]`, initial `seed_len=64`, and `handshake->calc_verify()` error only logged; execution continues. The override edits `esp-tls/esp_tls_mbedtls.c`, **not** this file. The server's two ECDHE-ECDSA AES-GCM suites use SHA-256/SHA-384 and TLS 1.2; EMS remains relevant even without renegotiation. Installed `esp_config.h:10941097` enables EMS when `CONFIG_MBEDTLS_TLS_ENABLED`, which is 1 in the existing generated header.
A calculation/allocation failure can leave an uninitialized hash and potentially retain length 64, causing a 16-byte buffer overread. Per upstream, this does not directly disclose stack contents or the master secret; a correctly functioning peer rejects the incorrect Finished message. Higher-level master-secret uniqueness attacks require additional conditions, including both peers affected and induced failures. **No direct HTTPS login bypass, practical remote fault trigger, or device exploit was established.** Low historical memory minima justify fault testing, not an assertion that this failure occurred.
**Minimal recommendation:** pinned `ssl_tls.c` replacement on actual target `mbedtls`, inserting `return ret;` immediately after the existing `MBEDTLS_SSL_DEBUG_RET(1, "calc_verify", ret)` inside the error branch. Preserve EMS; do not disable it as a shortcut. The fetched commit also changes `ssl_tls13_server.c` for a separate resumption-secret error: do not claim the one-line TLS 1.2 backport implements that second fix or globally updates mbedTLS. Current HTTPS policy is TLS 1.2 only.
Future tests should inject `calc_verify` failure for both SHA paths, ensure PRF/key derivation and successful handshake progression do not occur, preserve success behavior, and exercise cleanup. Exact driver/backend failure inducibility on the target remains unresolved; no preprocessing/cryptographic or fault-injection test was run.
### CVE-2025-48965 — ASN.1 named-data inconsistency, not OOM
Official [advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2025-06-6.md) and [3.6.4 release notes](https://github.com/Mbed-TLS/mbedtls/releases/tag/mbedtls-3.6.4). Affects through 3.6.3; fixed in 3.6.4.
Installed `asn1write.c:374435` checks allocation failures when creating a node/OID/value and preserves old data until replacement allocation succeeds. However, the `val_len == 0` branch frees `cur->val.p` and sets it NULL without resetting `cur->val.len`. Reusing the same OID or writing the inconsistent list can dereference NULL. Official examples include `DC=foo,DC=#0000` and `DC=foo,DC=#0000,DC=bar`.
`src/web_security.c:92111,128257` builds `CN=ESP32 SAK <six hex digits>` from the MAC, initializes a fresh writer, and sets subject and issuer separately. There is no repeated OID or empty value in either name. Thus the faulty primitive exists and is indirectly called, but **the official hostile-name trigger is not supplied by this certificate-generation path**. Do not say “not applicable because the project never creates certificates”; it does. Do not treat separate subject/issuer lists as repeated attributes in one list.
**Minimal recommendation:** ensure `cur->val.len = 0` when clearing the value, on actual target `mbedcrypto`, with a pin on the installed file. Retain the existing preserve-old-on-allocation-failure logic. The official advisory/release was fetched, but **an exact upstream CVE-2025-48965 fix commit was not resolved or patch-verified in this bounded review**; obtain and compare the specific 3.6.4 change before implementing/pinning a claimed official backport. Test nonempty→empty→same-length replacement, list serialization after empty replacement, repeated OIDs, and allocation failures independently.
### CVE-2026-34874 — `x509_string_to_names()` allocation failure
Official [advisory](https://raw.githubusercontent.com/Mbed-TLS/mbedtls-docs/main/security-advisories/mbedtls-security-advisory-2026-03-null-pointer-dereference-x509.md) and [3.6.6 release notes](https://github.com/Mbed-TLS/mbedtls/releases/tag/mbedtls-3.6.6). Affects 3.5.03.6.5; fixed in 3.6.6.
Fetched [basic fix](https://github.com/Mbed-TLS/mbedtls/commit/bfaf4a47fd33da860796feaba6235847acb71127.patch): **`bfaf4a47fd33da860796feaba6235847acb71127`**. The advisory identifies tests/documentation through `4704b6b4bd963f1331582374e881184addf8f523`; those additional changes were not reviewed here.
Installed `x509_create.c:306310` allocates the known attribute's OID and calls `memcpy(oid.p, ...)` without checking NULL. The project's CN takes exactly this recognized-attribute branch through both name setters. Trusted names avoid the previous CVE, **not this OOM defect**. Application return-code checks cannot catch a fault that happens inside the setter before it returns.
**Minimal recommendation:** pinned `x509_create.c` replacement on actual target `mbedx509`; directly after `oid.p = mbedtls_calloc(1, oid.len)`, add the official three-line NULL guard returning `MBEDTLS_ERR_X509_ALLOC_FAILED`. Preserve existing application cleanup and fail-closed identity publication. No new buffer or policy change is required.
The upstream advisory discusses arbitrary code execution on microcontrollers where address zero is writable. **That impact was not demonstrated for this ESP32-S3 memory map**; confirmed here is the unchecked write path and potential failure during certificate generation, not practical code execution. Test OID allocation failure at each setter, clean writer destruction, no persistence/publication of incomplete material, preservation of the old identity on failed rotation, and successful retry.
## Actionable next correction and remaining evidence
1. **Implement the pinned DHCP parser backport first.** It is the clearest currently reachable unauthenticated network-input defect in this scope. Do not merely change advisory wording or a version label.
2. In the same security correction effort, support explicit nested-target overrides and backport the EMS early return and X.509 allocation guard. Verify each protected source appears exactly once on its real owner target; retain all existing four corrections and their source properties.
3. Backport WS defensively and add registration/NULL-subprotocol regression coverage without changing application admission. Resolve the exact ASN.1 3.6.4 patch before adding that lower-priority correction.
4. Before acceptance, run focused parser/allocation/error-propagation tests against the generated compilation inputs, then a firmware build and target checks under separately authorized implementation/validation work. **None were performed for this review.** Ensure failures cannot compromise UART0 recovery, native USB independence, broker ownership, or bounded transport isolation.
5. A full IDF upgrade is an alternative maintenance strategy, but must rebase/re-audit all existing source pins, private HTTPD contracts, and TLS behavior. Updating only to mbedTLS 3.6.6 would leave CVE-2026-50581 unresolved. This document does not certify any upgrade candidate against the full advisory set.
Unresolved boundaries: exact ASN.1 fix commit; target-specific OOM/hash failure reproducibility and impact; actual running firmware/configuration; complete mbedTLS/IDF advisory coverage and downstream release integration. Existing source registration and generated-byte equality are confirmed; patch application, tests, linking, and device behavior are not.
Review mechanics: project code-map/current-state read first; targeted source, configuration and compilation-input inspection; official advisories and four exact fix patches fetched. No large release-history index was used. Some GitHub API requests timed out/returned no results and direct ReadTheDocs access via Python returned HTTP 403; official raw advisory sources and individual release pages supplied the evidence above. One read-only inspection command hit its 10-second timeout; a linear-time replacement completed the inspection. No source modifications were made, and this review owns only this document.
+29
View File
@@ -0,0 +1,29 @@
# Legacy credential removal and storage compatibility
Current storage/recovery contract. The user accepted cleanup on 2026-09-08, confirming the certificate fingerprint was unchanged and preexisting test users remained usable. [Overall acceptance and evidence limits](web_administration_acceptance.md) supersede the old per-slice handoff; no unreported provisioning, recovery, power-loss or all-key tests are implied.
## User database
- `user_database_init(load_result)` takes no legacy credential. Missing `user_db/database` storage is committed as an empty v1 database; no account/password is imported.
- Create the first administrator on physical UART0 with `user add <username> admin`, optionally `--generate`. Entered passwords use hidden confirmation; generated passwords are shown once. There is no reserved bootstrap account or public bootstrap state.
- `user recover --force` is UART0-only, calls `user_database_recover_empty()`, and destructively rebuilds only an unavailable database empty. It refuses a healthy initialized database, including an empty one. Follow with normal `user add`; unrelated configuration and TLS/SSH identities are untouched.
- Valid existing v1 database bytes load without rewriting or changing accounts, roles, IDs, authentication generations, verifiers or authorized keys. Previously migrated role-`user` accounts are not automatically promoted. The private `v1_admin_marker` preserves the old wire byte and is derived from administrator count during mutations; it is not a new role, public bootstrap field or schema change.
- No public bootstrap, legacy user migration or synchronization API remains. Final-admin protection, conditional mutations, copied principal currentness and target-only revocation remain the canonical account contracts.
## HTTPS identity storage
`web_security` owns only TLS material. At the unchanged `web_sec/material` key, a private byte-oriented reader validates the shipped **1,392-byte v1** layout and builds **1,340-byte TLS-only v2**. It retains the **exact private-key DER, certificate DER, SHA-256 fingerprint and material generation**: this migration is not certificate rotation.
The v2 candidate is validated and committed before live publication. Temporary credential-bearing v1 input is wiped. No public legacy credential reader/type, display, rotation or authentication path remains. Unknown/malformed material, read failures, invalid cryptographic identity and migration write/commit failures fail closed; they do not trigger fallback regeneration or overwrite of rejected material. Truly missing material may be generated and saved normally.
`web credentials show`, `web credentials rotate --force` and `user bootstrap` (including its generated form) are removed. `web certificate info` and `web certificate rotate --force` remain subject to existing frontend policy. `web reset --force` explicitly replaces TLS certificate/private key only; it does not reset passwords, import accounts or synchronize verifiers. TLS replacement/restart can close browser sessions and requires renewed certificate trust/login, without changing user credentials or revoking unrelated SSH sessions.
## Compatibility and physical-security limits
**Older v1-only firmware cannot read v2 HTTPS storage.** Do not assume a downgrade preserves usable HTTPS or restores removed credentials. Existing user database v1 compatibility is separate from this HTTPS downgrade incompatibility.
Replacing an NVS blob logically removes credential fields from the current record; it is **not secure flash wiping**. Append-oriented historical copies may retain plaintext legacy credentials, and current Wi-Fi secrets/TLS/SSH private keys remain unencrypted. PBKDF2 verifiers remain subject to offline guessing. No factory/partition erase is required or authorized by this cleanup.
## Regression references
Use `tests/web_security/run.py`, `tests/admin_console_boundary/accounts.py`, `tests/admin_ssh_policy/run.py` and [current legacy-removal procedures](user_administration_tests.md#current-legacy-removal-regression-procedure). Prior host tests used NVS fault doubles and a generated identity wrapped in the historical TLS layout, not an independently captured old-device fixture; they do not prove flash durability or power-loss behavior. Procedures are not claims of execution.
+185
View File
@@ -0,0 +1,185 @@
# Phase 9 bounded host validation
`tools/validate_phase9.py` is a thin, sequential orchestrator for existing test
runners, not a new security test implementation or a Phase 9 acceptance gate.
See [security hardening](security_hardening.md) for scope, historical evidence,
and the deferred whole-phase target checklist.
## Current candidate execution — 2026-09-18
Supplied final parent command, run from the repository root:
```sh
CCACHE_DISABLE=1 python3 -B tools/validate_phase9.py --build-dir .pio/idf-candidate-5.5.3/app-validated/.pio/build/esp32-s3-devkitc-1-n16r8 --idf-path .pio/idf-candidate-5.5.3/core/packages/framework-espidf --platformio-core-dir .pio/idf-candidate-5.5.3/core --interop --web-performance
```
**PASS 24/24.** This selects the actual fresh isolated build, SDK and toolchain core; it is not a default-root-build execution. The separate fresh `.pio/idf-candidate-5.5.3/app-validated` build **PASS** reports **95,552 B linked RAM / 1,749,493 B flash**, versus historical **94,340 / 1,768,901 B** (**+1,212 B RAM / 19,408 B flash**). The default parent `pio run` timed out after **200 seconds during installation, before compilation**; no normal root build PASS is claimed.
Pre/post source equality: **3,237 files**, SHA-256 **`3a1af78c15cfdd02da1055a8957b4086f9018862b7aa1c7c52fd2401a1a0a031`**. Actual generated-input registration covers **nine C sources plus one forced header**. WS receive tests exercise generated code: **982 cases / 10 mutation checks**, including the five signed `sizeof` corrections. The stale web-cookie fixture asserting IDF 5.5.0 was corrected, not bypassed. Historical stale-WS compilation/coverage failures in the [rebase review](idf_553_rebase_review.md) are resolved by this final snapshot, not hidden or retroactively called passes.
The [fix-bearing Wi-Fi bundle](wifi_security_update_plan.md) is integrated in the candidate, with unchanged PMF/WPA3; radio-hardware vulnerability closure and full target/resource/recovery gates remain pending. Nine notice catalog entries were semantically rebased, the other 66 unchanged (75 total); supplied notice evidence is **36 fixtures PASS**, two actual deterministic bundles each **77 files / 4,433,930 bytes**. Archive pins and source equality do not prove complete immutable root/ancillary/Python dependency closure, legal clearance or Phase 9 acceptance. This documentation update records supplied parent evidence; it did not rerun these builds, suites, bundles or hardware tests.
## Usage
From the repository root (the script itself also resolves the root independently
of the caller's working directory):
```sh
python3 -B tools/validate_phase9.py --dry-run
python3 -B tools/validate_phase9.py
python3 -B tools/validate_phase9.py --fail-fast
python3 -B tools/validate_phase9.py --timeout 300
```
Build and OpenSSH interoperability are **independent explicit opt-ins**:
```sh
python3 -B tools/validate_phase9.py --build --build-timeout 600
python3 -B tools/validate_phase9.py --interop --timeout 300
python3 -B tools/validate_phase9.py --build --interop --dry-run
```
These examples are usage, not execution claims. `--build` runs exactly `pio run`
first; it does not upload, erase, monitor, or select another PlatformIO environment.
PlatformIO itself may download dependencies or write its normal external caches.
The caller/parent must choose whether to build and arrange any required permission
separately. No installer, permission grant, network retry, or sandbox escalation
is implemented. A failed/timed-out build skips every dependent host command to
avoid testing stale artifacts as if that build succeeded.
`--interop` adds only `--interop` to `tests/wolfssh_order_contract/run.py` (its
default single matrix). That runner uses OpenSSH and local AF_UNIX sockets, not
an IP host or device. Socket permissions and installed OpenSSH tooling must
already be available; denial is a failure, not a reason to grant permissions.
Neither option is enabled by default. `--web-performance` independently adds the generated-WS performance runner (24 commands total). `--build-dir`, `--idf-path` and `--platformio-core-dir` select existing candidate artifacts/SDK/core; `--build` rejects a non-default build directory, which must be built separately. No target address, credentials, arbitrary
command, or device-operation argument is accepted.
## Coverage and prerequisites
The fixed default plan contains **23 commands**; `--dry-run` prints their exact
argv vectors and timeouts without launching anything or checking prerequisites.
There is no discovery-time execution of runners (some run at import/top level).
Paths and options were inspected in their actual `run.py` implementations.
| Scope | Existing runners / modes |
|---|---|
| 9A effective crash policy | `security_build_policy --sdkconfig-header .pio/build/esp32-s3-devkitc-1-n16r8/config/sdkconfig.h` |
| 9B admission / credentials | `ssh_auth_policy`, `ssh_auth_transport`, `hidden_input` |
| 9C allocator | `ssh_memory` |
| Current seven-suite baseline | `sdk_security_overrides --build-dir .pio/build/esp32-s3-devkitc-1-n16r8`, `wolfssh_auth_contract`, `ssh_protocol_policy`, `wolf_crypto_policy`, `wolfssh_parser_contract`, `wolfssh_order_contract`, `release_notices` |
| Focused SSH/admin and HTTPS lifecycle regressions | `ssh_management`, `admin_console_boundary`, `admin_ssh_policy`, `web_admin_transport`, `web_admin_tickets`, `web_httpd_idle` |
| Web early admission, credentials and administrative lifecycle | `web_cookie_auth` default plus separate `--admin`, `--accounts`, `--ssh`, `--lifecycle` commands |
Every runner path is `tests/<name>/run.py`. Auth contract, protocol policy, and
crypto policy receive explicit `--compile-commands
.pio/build/esp32-s3-devkitc-1-n16r8/compile_commands.json` arguments. No
`--host-only`, candidate injection, or silent fallback is used. Default operation
requires an existing configured build, installed pinned SDK/managed sources,
the production toolchain and host compiler/libraries needed by these runners
(including OpenSSL development support for relevant tests). It **does not run
PlatformIO** to satisfy those requirements. Missing explicit files/executables
are `PREREQ` failures; deeper source/toolchain prerequisites are checked by the
existing runners and surface as nonzero `FAIL` results. Existing artifacts are
not proof that the current checkout has been freshly built.
The current cookie-auth runner has no `--admission` branch: the default exercises
early admission/wiping, and each selected domain mode repeats that baseline.
Unrelated display/network/UI suites are intentionally excluded; web performance is an explicit opt-in.
`ssh_memory` retains its documented optional installed-IDF extent-source check
as skipped when no `--idf-path` is supplied; explicit candidate selection enables it. Its normal allocator contracts still run.
The ordering runner's candidate `--target-contracts`, separate `--pio-adapter`
regression, and repeated interop matrices are not added implicitly. Run those
separately when their particular evidence is needed. This is a focused full
Phase 9 host regression set, not every test in the repository.
## Bounds, output, and result semantics
- Each host command has a 180-second wall-clock timeout by default; the optional
build gets 600 seconds. Both timeout flags accept finite values in `(0, 3600]`.
The fixed sequential plan bounds total child execution by the sum of its
timeouts (default 4,140 seconds), plus launch/reporting/cleanup overhead.
- POSIX process groups are required. Timeout or Ctrl-C kills the active process
group and reaps the runner; successful/failed exit also retires any remaining
group descendants. This covers normal compiler/test children, not deliberately
detached processes. Group reaping has a five-second wait bound.
- Commands use argv lists, no shell evaluation or interpolation, with stdin
closed. The child environment is copied with `CCACHE_DISABLE=1`; explicit `--idf-path` and `--platformio-core-dir` also set resolved `IDF_PATH` and `PLATFORMIO_CORE_DIR` for children;
arbitrary compiler, SDK, proxy and other caller environment settings are not
overwritten. The parent's environment is not mutated.
- stdout/stderr are inherited live. The orchestrator creates no persistent log,
JSON capture, environment dump, or secret artifact. Existing runners retain
their own temporary fixture/build behavior; forced termination can bypass
their temporary-directory cleanup. Console output is **not a redaction
guarantee**: use synthetic fixtures, review before sharing, and do not redirect
output into routine secret-bearing persistent captures. Build outputs remain
normal PlatformIO artifacts only when explicitly requested.
- `PASS` means the entire runner exited zero, not that an earlier printed PASS
line appeared. The final summary records each command's exit, timeout or
missing prerequisite. Defaults collect failures and continue independent
commands; `--fail-fast` reports remaining commands as `SKIP`. Build failure
always stops dependent commands. No selected suite is silently dropped.
- Exit 0 means all selected commands passed, or a dry-run plan was printed.
Dry-run uses `PLAN`, never `PASS`, and is not validation. Failures, timeouts,
prerequisites and dependent skips return 1; invalid CLI arguments return 2;
Ctrl-C returns 130. Optional build/interop omissions are announced separately
and do not turn a successful host run into failure.
## Orchestrator fixture tests
```sh
python3 -B tests/phase9_validation/run.py
```
Offline unittest groups check the exact plan/paths/strict arguments, independent
opt-ins, timeout configuration and invalid values, dry-run nonexecution, default
build/interop omission, failure collection, fail-fast and failed-build skips,
missing file/executable handling, literal argv/environment preservation,
timeout/descendant termination, and inherited streams/closed stdin. They execute
only small Python fixtures, never PlatformIO, interop, devices, or network.
## Execution record — 2026-09-16
Initial orchestrator-agent execution, under the existing sandbox without elevation (historical first run):
- `python3 -B tests/phase9_validation/run.py`: **10 tests PASS**.
- `python3 -B tools/validate_phase9.py --dry-run`: exit 0; **plan only**, no
prerequisite or suite validation.
- `python3 -B tools/validate_phase9.py`: **exit 1, 22 PASS / 1 FAIL**, no timeouts;
about 57 seconds of summed command time. Build and interop explicitly skipped.
- Direct rerun `CCACHE_DISABLE=1 python3 -B tests/admin_console_boundary/run.py`:
reproduced exit 1 at line 40, `ValueError: substring not found` for
`ssh.index("static void *ssh_malloc(")`. Earlier subtest PASS lines do not make
the runner pass. The existing runner is outside this change's ownership and
was not edited.
Passed commands: `security_build_policy`, `ssh_auth_policy`, `ssh_auth_transport`,
`hidden_input`, `ssh_memory`, **all seven current baseline suites listed above**,
`ssh_management`, `admin_ssh_policy`, `web_admin_transport`, `web_admin_tickets`,
`web_httpd_idle`, and all five selected `web_cookie_auth` modes.
Only `admin_console_boundary` failed.
No firmware build, interop, device, runtime reserve, hardware panic/recovery,
release delivery, or whole-Phase-9 acceptance result is claimed for this task.
### Follow-up supplied evidence
The owning agent corrected the stale `admin_console_boundary` source anchor;
its subsequent default orchestrator run reports **23/23 PASS**. This supersedes
the initial 22/23 host result above, without turning its early PASS lines into
a successful initial run. Final supplied parent execution now confirms:
- `CCACHE_DISABLE=1 python3 -B tools/validate_phase9.py`: **PASS 23/23**.
- `tests/phase9_validation/run.py`: **PASS 10 tests**.
No build or interop ran this turn; both remain separate opt-ins, not default
execution. Firmware source is unchanged. These are actual parent results supplied
for this record, not another execution by this documentation integration.
The supplied notice agent also reports **36 fixture tests PASS** and two actual
75-input bundles, each **77 files / 4,433,930 bytes**, verified deterministic; see
[packaging evidence](release_packaging.md). These are agent measurements, not a
new build or bundle measurement by this documentation integration.
The [finite advisory search](dependency_advisory_coverage.md) is complete for its
declared snapshot, but the [PMF-capable SoftAP blocker](wifi_security_update_plan.md)
was **not fixed at that historical snapshot**. The current fix-bearing bundle is now integrated in the validated candidate; host success does not validate radio behavior, clear distribution obligations or complete Phase 9.
+249
View File
@@ -0,0 +1,249 @@
# Offline release notice packaging
This procedure produces a **bounded notice/provenance bundle**, not a firmware
release, corresponding-source archive, complete SBOM, or legal clearance.
The **radio-blob corresponding-source/System Library question remains open**.
See [the license inventory](dependency_licenses.md) for the original review and
[the retained scope/provenance statement](../third_party/release-notices/README.md)
for license choices, mixed notices, wolfSSH packaging discrepancy, TLSF text
assembly, icon limits, and remaining release gates.
## Run against the installed reviewed snapshot
Requirements: Python 3.9+ on Linux/POSIX with `O_NOFOLLOW`, directory descriptors
and `dir_fd` operations; already installed matching managed components,
ESP-IDF and Xtensa toolchain. Standard library only. The tool never fetches,
installs, builds, runs PlatformIO, accesses a device, or regenerates assets.
Run from the repository root. Supply **an explicit, not-yet-existing output
directory outside all three input roots**, with an existing parent. Example
for the reviewed installed 5.5.3 candidate (choose a fresh final directory name):
```sh
python3 tools/release_notices.py \
--sdk-root /home/mscholz/Repos/ESP32_serial_swiss_army_knife/.pio/idf-candidate-5.5.3/core/packages/framework-espidf \
--toolchain-root /home/mscholz/Repos/ESP32_serial_swiss_army_knife/.pio/idf-candidate-5.5.3/core/packages/toolchain-xtensa-esp-elf \
--output /tmp/esp32-release-notices-review-01
```
`--project-root` optionally selects a different checkout containing the exact
reviewed inputs; by default it is the script's repository. The trusted catalog
always comes from the script's repository, not from that alternate checkout.
Paths to SDK/toolchain packages are explicit; no installation is guessed.
There is no user catalog option, force/overwrite mode, automatic repinning,
recursive collection, archive command, or automatic release upload.
Every input in `third_party/release-notices/inputs.json` is mandatory and pinned
by **full-file SHA-256 and size**. Missing sources, altered bytes, bad excerpts,
empty files, directories, FIFOs, symlinks (even to identical files), parent
traversal, binary notice payloads and exhausted bounds fail closed. Symlinks in
input-root or output-parent ancestry are rejected too: pass real non-symlinked
paths, not a convenience symlink. All input preflight completes before creating
output. The limits are 128 inputs, 4 MiB per input/catalog and 32 MiB cumulative
source bytes. The current catalog has **75 inputs**, including the retained SVGs and pinned
[icon provenance evidence](icon_provenance.md). Overview documents edited in this
integration are not catalog inputs; `docs/icon_provenance.md` **is pinned**.
Coordinate any change to that record with the catalog owner; never silently repin.
An existing output file, directory (even empty) or dangling symlink is never
overwritten. Parent directories are not automatically created. Output uses
private directory/file modes (0700/0600, subject to umask). On a write failure,
the tool deliberately leaves any partial directory for inspection and never
recursively deletes it. A successful exit plus a valid manifest and matching
payload hashes is required; presence of a partial manifest is not success.
Use another fresh path for a retry. Do not put output into a tree that an
untrusted process can concurrently rename or modify; descriptor/no-follow
checks prevent symlink traversal but are not isolation from the same OS user.
## Bundle layout and reproducibility
- `README.txt`: limitations and entry point for recipients.
- `inputs/project/…`: project GPL text, resolved lock, managed licenses and
manifests, wolfSSL/wolfSSH README evidence, original wolfSSH header excerpts,
xterm MIT texts and recorded provenance, icon summary and official 7.4.47
SVG/license/metadata evidence, TLSF full rendering
and scope/provenance statement.
- `inputs/sdk/…`: complete scoped SDK license documents, mixed Newlib/argtable3
notices, radio license files, package/version identity and original source
notice excerpts. SDK `LICENSE` supplies full Apache-2.0 text; it does **not**
authenticate individual icons or cover all SDK files.
- `inputs/toolchain/…`: actual toolchain Newlib text, GPLv3, GCC Runtime Library
Exception 3.1 and package identity. No toolchain executable is copied.
- `manifest.json`: schema/snapshot, catalog SHA-256, logical root/path,
full-source size/hash, optional zero-based half-open byte range, purpose,
output path/size/hash, and the generated introduction's hash. Excerpts have
`.notice.txt` appended; null ranges retain whole original files unchanged.
Whole mixed documents are preserved, not converted into guessed SPDX labels.
The longer toolchain Newlib notice does not replace the distinct SDK text.
The wolfSSH package GPLv2-or-later text and GPLv3-or-later source headers remain
separate and unmodified; upstream packaging clarification is still needed.
Generated metadata contains no collection timestamps or absolute host paths;
original notices retain their own dates and text. For identical catalog and
inputs, file names and file contents are deterministic across
output locations, input-root locations and source mtimes. Directory/file
mtimes are **not** normalized, and no reproducible tar/zip archive is claimed.
The manifest hashes all payloads but not itself; retain its hash in your
separate release evidence if needed. The catalog is trusted reviewed policy,
not a cryptographic signature or proof of package-wide integrity/authorship.
Only explicit catalog paths are read. No application config, sdkconfig,
build tree, ELF/map/binary, key, credential backup, NVS/flash dump or whole
repository is collected. Hash-pinned source implementations are read only to
validate original header excerpts, not copied as implementations. The lock and
installed package/component manifests are dependency identity metadata, not
build configuration. A hash pin is not a general-purpose secret scanner:
review additions to this trusted list before accepting them.
## Validate and inspect
Temporary-fixture regression suite (does not need installed packages):
```sh
python3 tests/release_notices/run.py
```
The suite tests missing/changed sources (including changes outside a notice
excerpt), exact mixed-text retention, byte ranges, path traversal, source/root/
output symlinks, existing user data, nonregular files, bounds, output failures,
secret/config exclusion, determinism, and CLI behavior. No hardware tests are
implied.
For a real bundle, check the successful process exit, parse `manifest.json`,
recompute every payload hash/size, check no unlisted files are present, and
read the scope statement. Compare two independently created fresh outputs by
relative names and bytes (not mtimes). Inspect at least both Newlib files,
argtable3, wpa_supplicant COPYING/README, GCC exception, wolfSSH LICENSE/README
and header excerpts, TLSF text/provenance, both xterm notices and the icon
summary. These checks establish scoped assembly, **not release compliance**.
If a pinned input differs, stop and review the changed package/license/source.
There is deliberately no update-catalog command. Review versions, new/nested
NOTICEs, original source notice ranges and hashes, then deliberately update
catalog policy and test it. The runtime does not discover added notices or
packages outside its finite list; this limitation makes its reads bounded and
prevents opportunistic collection of user files.
## Supplied execution evidence — 2026-09-16
Agent results: **36 notice fixture tests PASS**, and **two actual 75-input
bundles verified deterministic**, each **77 files / 4,433,930 bytes**. These
replace the earlier 62-input / 64-file / 541,147-byte snapshot, not its historical
record. No parent rebuild or bundle reassembly was run in this documentation
turn; firmware source is unchanged. Assembly is not legal clearance or Phase 9
acceptance. The [unfixed Wi-Fi blocker](wifi_security_update_plan.md) also remains
a separate security gate; a future coherent vendor update requires catalog review.
## Installed candidate notice rebase — 2026-09-18
This addendum audits the existing 75-input catalog against **already installed**
PlatformIO 6.13.0 migration candidates, not merely downloaded archives. No
installation, build, production/config edit, or security-override rebase was
performed by this notice audit. The preceding 2026-09-16 evidence is historical.
Actual candidate package root:
`/home/mscholz/Repos/ESP32_serial_swiss_army_knife/.pio/idf-candidate-5.5.3/core/packages/`.
Its `framework-espidf/package.json` reports **3.50503.0**, and `version.txt`
reports **5.5.3**. Both `toolchain-xtensa-esp-elf/package.json` and
`toolchain-riscv32-esp/package.json` report **14.2.0+20251107**. RISC-V identity
was checked for context; it is not a new input root or a claim of RISC-V notice
coverage. The shared `/home/mscholz/.platformio/packages/` still contains
framework **3.50500.0 / IDF 5.5.0** and both toolchains **14.2.0+20241119**;
do not use those shared paths with this rebased catalog.
All 75 old catalog full-file hashes/sizes matched the old shared SDK/toolchain
and current project inputs before editing. Comparison against the installed
candidate found exactly **nine changed entries** (eight SDK, one Xtensa),
listed below. The other **66 entries remain unchanged**, including all **39
project/managed inputs**, the dependency-lock pin, icon evidence and managed
version map. No catalog paths, purposes unrelated to version identity, or
excerpt ranges were added/removed/relaxed. Snapshot identity/date and the three
identity-purpose strings were updated deliberately, not by automatic repinning.
Paths below are relative to the indicated catalog root. Hashes are full-source
SHA-256; old hashes remain in the preceding Git catalog revision.
| Root / path | Old → candidate bytes | Candidate SHA-256 |
| --- | ---: | --- |
| sdk / `components/esp-tls/esp_tls_mbedtls.c` | 50176 → 54323 | `edc39052244526cb91c93a16bc765194031060e5560fd432e75542f2f6c8db53` |
| sdk / `components/esp_http_server/src/httpd_parse.c` | 42937 → 42937 | `db7fbbb322bccb4a21bc1607208a6bb7d1f4c0d7ecc3299de10c9e60edaa943b` |
| sdk / `components/esp_https_server/src/https_server.c` | 15257 → 15459 | `a2a5ca0549fbe8d1ddd7f9647a48a31fdd6329b997e1550ab69d6a10efecff0d` |
| sdk / `components/freertos/FreeRTOS-Kernel/include/freertos/task.h` | 133072 → 133108 | `8b908b964d2c87377838762478253eec04312b985e6bb680bacd3f03ab253897` |
| sdk / `components/mbedtls/mbedtls/library/ssl_tls.c` | 329921 → 336963 | `0154e70f20b465213d3f97a9c2b75e686d79ee83592f90e1d7e7d995593ca7e1` |
| sdk / `components/mbedtls/mbedtls/library/x509_create.c` | 19803 → 19934 | `55edce5b8fcb039a404b84ea830f06d018128b155dfbf0d74d26b17247b546c6` |
| sdk / `package.json` | 536 → 536 | `230c52993499adf9f64d1d6477495ea46c3f14d63022bd52081858373098da68` |
| sdk / `version.txt` | 5 → 5 | `b473c8e2ed91b38d7e96e54d4ce094474ca6015c0641b7cdfc0ab94b1f8b4668` |
| toolchain / `package.json` | 472 → 472 | `bdd3b852d051d6513912e71d29851bd04b800e2d33d78aec48067af5d83da5c9` |
Semantic notice review: five changed implementation files retain byte-identical
complete opening notices at their existing ranges (ESP-TLS `[0,122)`, HTTPD
`[0,124)`, HTTPS `[0,123)`, Mbed TLS shared TLS `[0,223)` and X.509 `[0,169)`).
Their output hashes stay unchanged; full-source hashes must change even when
only implementation bytes change. This does **not** approve the implementation
changes or establish compatibility of the project's security overlays.
FreeRTOS `task.h` retains its complete MIT notice at `[0,1455)`; only
`SPDX-FileContributor: 2023-2024` becomes `2023-2025` within that excerpt.
Its output hash changes from
`8e3d9f79bbbdf6dfd6fbf132982a7ec3a45ff6dac92277034316efae4cccad84` to
`e53c9bcefd4327c713696e870a3568a27cedf8833467b9cd9536cb2e09ab7ad8`.
The remaining `task.h` changes correct stack-watermark documentation to bytes.
The two package JSON diffs change only versions; SDK `version.txt` changes only
`5.5.0` to `5.5.3`.
All 24 remaining SDK inputs and three Xtensa license inputs match the old pins,
including SDK/radio Apache texts, both Newlib documents, mixed argtable3,
wpa_supplicant and GCC exception/GPL texts. An auxiliary installed-tree filename
comparison found the same 45 SDK files whose basenames start with LICENSE,
COPYING or NOTICE (case-insensitive), with no additions/removals. All 85 files
under Xtensa `share/licenses/` have identical relative paths and hashes. This
finite discovery check is not an exhaustive attribution or linked-object audit.
Validation after the catalog edit: **36/36 notice fixture tests PASS** via
`python3 -B tests/release_notices/run.py`; two fresh temporary actual bundles
using the candidate roots above and the current project passed assembly,
per-payload manifest SHA-256/size checks, exact file-list checks, and identical
relative names/bytes across outputs. Each has **77 files / 4,433,930 bytes**
(the unchanged total size does not imply unchanged contents). Both manifest
SHA-256 values are
`1fd0a69b82dc2632bab4ab6dda33675e7229c8d341c7fafb7158c1e8f2456a68`.
Temporary bundles were removed after comparison. Project entries and managed
snapshot pins were also asserted equal to the pre-migration Git catalog.
These results are **notice assembly evidence only**, not legal clearance,
corresponding-source delivery, radio-blob exception approval, vulnerability
closure, firmware build validation or target acceptance. Existing pinned project
provenance retains historical baseline wording; this addendum distinguishes the
new SDK notice snapshot without silently rewriting/re-pinning that evidence.
All separate distribution gates below remain open.
## Separate work before distribution
1. Resolve or obtain qualified review of radio-blob corresponding-source or
exception basis for the actual linked firmware. Apache binary permissions
alone do not settle this question. No legal clearance is claimed.
2. Resolve the wolfSSH package/header discrepancy and remaining icon derivative
questions. [Exact retained SVG provenance](icon_provenance.md) is verified at
official 7.4.47, commit `9e04201d4557e729822fb57f62a316c3dea1d4a8`: Google
USB and Simran Wi-Fi. Full Apache text is retained; no NOTICE was found in
that pinned distribution. Manual firmware bitmap derivation and the distinct
mockup Wi-Fi path remain unresolved. No artwork was regenerated.
3. Audit the final application/bootloader/runtime object set and aggregation
boundaries. Full SDK/toolchain redistribution needs broader nested/tool/test
notice coverage; this is not an all-files license scanner.
4. Prepare and validate a separate, deliberately reviewed corresponding-source
delivery. Preserve exact required sources and safe build/install inputs,
asset preferred sources and scripts, original hash-matching overlay inputs,
`tools/security_overrides.py`, `cmake/security_overrides.cmake`, root CMake
integration, `cmake/wolf_crypto_policy.{cmake,h}`, and the complete
`tools/wolfssh_order/` inputs/provenance/archives. Preserve upstream notices
and generated dated change notices on eight C sources and one PUBLIC forced
header. A stock vendor tarball or this notice bundle is not sufficient.
Do not automatically archive the working repository or real configurations.
5. Assess GPLv3 source delivery/offer and User Product Installation Information.
Protect device passwords, Wi-Fi credentials, private keys, verifiers,
tickets, credential backups and flash/NVS images throughout that process.
6. Arrange and verify actual notice delivery with firmware, devices and browser
assets. This command does not add a license endpoint, change browser assets,
or prove that a recipient of a JS response or standalone device receives
notices. Keep these gates open until the real delivery path is validated.
+85 -146
View File
@@ -37,15 +37,15 @@ These constraints apply across all phases:
| 5A | Authenticated HTTPS administration foundation | **Complete** |
| 5B | Offline xterm.js WebSocket serial terminal | **Complete** |
| 6 | Authenticated SSH serial transport | **Complete** |
| 7 | Local display and button interface | **In progress (7E validation)** |
| 8 | Role-based users and administrative access | **In progress (8B validation)** |
| 9 | Security and production hardening | **Planned** |
| 7 | Local display and button interface | **Complete** |
| 8 | Role-based users and administrative access | **Complete (8D.22 accepted 2026-09-13)** |
| 9 | Security and production hardening | **In progress (9A9C implemented; combined phase validation deferred)** |
| 10 | Authenticated, rollback-capable OTA | **Planned** |
| 11 | BLE serial transport and provisioning evaluation | **Planned** |
| 12 | Advanced network integration | **Under evaluation** |
| 13 | Optional filesystem-backed features | **Under evaluation** |
## Completed foundation
## Completed phases
### Phase 0 — RS-232 hardware characterization
@@ -57,7 +57,7 @@ Implemented and hardware-validated:
- Hardware CTS transmit gating and RTS receive-backpressure tests.
- Exclusive RS-232 port ownership and fault-safe cleanup.
- RGB status indication for diagnostic state.
- Potentially disruptive tests isolated under the `debug` CLI submenu; top-level `status` retained.
- Phase 0 hardware diagnostics, including signal status, are isolated under the `debug` CLI submenu.
Detailed procedures are in [Electrical tests](electrical_tests.md) and [Hardware wiring](wiring.md).
@@ -93,7 +93,7 @@ Implemented and hardware-validated:
- Automatic broker connection when the host opens the port with DTR asserted.
- Opportunistic writer acquisition with observer fallback.
- Binary-transparent bidirectional serial data.
- Supported host line-coding application while USB owns the writer lease.
- Host line-coding visibility for diagnostics; UART1 remains under explicit serial configuration control.
- Disconnect cleanup, bounded buffering, counters, and UART0 lifecycle controls.
### Phase 4 — Wi-Fi foundation
@@ -109,6 +109,11 @@ Implemented and hardware-validated:
- Root and `wifi` aliases for `ping`, `nslookup`, and `traceroute`.
- Wi-Fi/lwIP payload allocation configured to prefer PSRAM with capacities pinned in `sdkconfig.defaults`.
Post-validation enhancements implemented; regression validation pending:
- Edits to disabled station profiles are staged without restarting the active radio; enable-state changes and edits affecting enabled radio policy apply asynchronously.
- Configurable STA-only `sak-<suffix>.local` mDNS hostname with an independent versioned NVS record, live hostname updates, automatic withdrawal/restoration across STA IPv4 transitions, and nonfatal failure isolation. The responder initializes at most once and keeps its task stack internal while general metadata prefers PSRAM.
A WPA3-required profile correctly rejects an AP that does not advertise the required Protected Management Frame capability; mixed mode is the compatible choice for such an AP.
### Phase 5A — Authenticated HTTPS foundation
@@ -116,7 +121,7 @@ A WPA3-required profile correctly rejects an AP that does not advertise the requ
Implemented and hardware-validated:
- HTTPS-only service on TCP port 443 using ESP-IDF mbedTLS.
- Persistent random shared `admin` credential.
- Persistent random shared `admin` credential, later retained only as migration/recovery material by Phase 8.
- Persistent device-specific ECDSA P-256 certificate and private key.
- Physical-console credential retrieval, rotation, certificate inspection, rotation, and recovery.
- Explicit failure behavior that preserves UART0, USB, serial, and Wi-Fi recovery paths.
@@ -136,160 +141,94 @@ Implemented and hardware-validated:
- Viewport-constrained terminal fitting without recursive page growth.
- Validation with multiple clients, ANSI colors, advanced escape sequences, and full-screen terminal software.
## Latest completed phase
Post-validation enhancement implemented; browser regression validation pending: the combined Connect/Disconnect control explicitly closes the terminal WebSocket and pauses automatic reconnect until Connect is selected.
### Phase 6 — Authenticated SSH serial transport
The SSH implementation is complete and hardware-validated. It provides:
Implemented and target-hardware validated:
- wolfSSH on TCP port 22 while HTTPS remains on mbedTLS.
- Password authentication using the shared `admin` credential.
- A separate persistent ECDSA P-256 SSH host key and OpenSSH-compatible fingerprint.
- Interactive shell/PTY channels only.
- No `exec`, subsystem, SFTP, SCP, agent forwarding, or TCP forwarding.
- Two fixed session/handshake slots.
- Three password attempts and a 15-second handshake deadline.
- No broker client before successful authentication and shell negotiation.
- Binary-transparent serial forwarding with no in-band writer-control protocol.
- Opportunistic writer acquisition and observer behavior through the common broker.
- Credential-rotation revocation and UART0 session/host-key administration.
- A single bounded wolfSSH owner task pinned to CPU 1.
- wolfSSL/wolfSSH allocations that prefer PSRAM with internal-memory fallback.
- A per-call wolfSSH receive budget to prevent pipelined input from monopolizing the owner task.
- Bounded broker and WebSocket work bursts that guarantee scheduler/idle progress during sustained serial traffic.
- Software AES for PSRAM-backed mbedTLS records plus software wolfCrypt AES/SHA, preventing mbedTLS and wolfSSL from independently reconfiguring shared ESP32 crypto hardware.
- Internal task stacks retained for safety during flash/NVS cache-disable windows.
- Heap and SSH stack telemetry through `memory` and `ssh status`.
SSH login, host-key verification, serial traffic, Web Serial coexistence, and USB CDC coexistence have been validated. During concurrency testing, the previously failing three-client arrangement used USB CDC and SSH as writer in turn while the remaining transports observed.
Early runs showed healthy heap values but CPU 0 idle-task watchdog timeouts, disproving the initial memory-pressure hypothesis. One trace exposed an unbounded broker scheduling path. A later, decisive trace repeatedly stopped inside mbedTLS's external-RAM hardware-AES DMA wait while HTTPD encrypted a WebSocket record. The broker and WebSocket producer now use bounded active bursts, mbedTLS software AES avoids the hanging PSRAM DMA path, and wolfSSL AES/SHA hardware acceleration is disabled because its private locks do not coordinate with ESP-IDF's crypto lock.
#### Phase 6 hardware validation
The final target-hardware retest covered:
1. USB CDC, one WebSocket terminal, and one SSH terminal connected concurrently.
2. SSH as writer with USB CDC and WebSocket observing.
3. USB CDC as writer with SSH and WebSocket observing.
4. Serial traffic with active readers and writer-token release/reassignment.
5. Continued HTTPS/WebSocket, SSH, USB CDC, serial-service, and UART0 responsiveness.
The software-crypto build no longer reproduces the HTTPD watchdog stall. This validates that the failure was a shared hardware-crypto/PSRAM DMA problem rather than heap exhaustion. Phase 6 is complete; these concurrent arrangements remain regression tests for future transport, TLS, memory-placement, and ESP-IDF changes.
## Current and planned phases
The order below is the current plan. Phase 7 and Phase 8A are complete, Phase 8B is implemented and awaiting target-hardware validation, and later work remains planned or under evaluation. Detailed requirements should be finalized at the start of each phase, and optional features must not weaken the completed serial and recovery paths.
- wolfSSH on TCP port 22 with a separate persistent ECDSA P-256 host key.
- Two bounded interactive shell/PTY sessions; no `exec`, file transfer, forwarding, or subsystems.
- Authenticated, binary-transparent broker forwarding with opportunistic writer acquisition and observer fallback.
- Bounded handshake attempts/deadlines, receive work, buffers, and a single wolfSSH owner task pinned to CPU 1.
- UART0 lifecycle, session, counter, and host-key administration.
- PSRAM-preferred allocations with internal fallback and internal task stacks.
- Bounded broker/WebSocket work, software mbedTLS AES, and software wolfCrypt AES/SHA to avoid the validated shared-hardware-crypto/PSRAM watchdog failure while retaining ESP-IDF SHA/MPI acceleration.
- Concurrent USB, WebSocket, and SSH operation validated with USB and SSH alternately holding the writer lease.
### Phase 7 — Local display and buttons
Add a standalone local status/control interface without making it a dependency of the serial core. The planning baseline uses a 128×64 dual-color monochrome I²C OLED sold with an SSD1315 controller. Phase 7A confirmed SSD1306-compatible operation, 7-bit I²C address `0x3c`, orientation, column mapping, contrast/inversion behavior, button inputs, and the physical color geometry on the selected hardware.
Implemented and target-hardware validated:
Phase 7A diagnostics and target-hardware electrical validation are complete. Phases 7B through 7E are complete and target-hardware validated.
- Optional 128×64 SSD1315-compatible I²C OLED on GPIO11/12 and active-low buttons on GPIO10/13/14; assignments remain centralized in `board_pins.h`.
- Display service with a static framebuffer, bounded dirty-page commits, and separate yellow status rows 015 plus blue content rows 1663.
- Low-priority status/control task built from copied public snapshots; no service lock is held across I²C and the UI never becomes a broker client.
- Overview, RS-232, broker, and network/service pages with no credential or key material.
- Confirmation-protected local controls for service lifecycle, Wi-Fi reconnect/profile rotation, writer release, display off, and reboot; the UI cannot assign a writer or edit secrets/configuration.
- Persistent dim/off settings, bounded boot animation, consumed wake presses, stuck-button quarantine, and one-shot confirmations.
- Missing, disconnected, or unresponsive display hardware remains nonfatal and can recover through one bounded reprobe.
- Concurrent serial, UART0, USB, WebSocket, SSH, and injected display/button fault behavior validated. See [Electrical tests](electrical_tests.md) and [Hardware wiring](wiring.md).
#### Hardware baseline
### Phase 8 — Role-based users and administrative access — Complete
- Wire OLED `VCC` to `3V3` and OLED `GND` to `GND`. The OLED must use 3.3 V because module-mounted I²C pull-ups may connect SDA and SCL to `VCC`.
- Wire OLED `SDA` to GPIO11 and OLED `SCL` to GPIO12. These pins are currently unused and sit in the available GPIO1014 block on the DevKit header.
- Wire three active-low buttons between their GPIO and `GND`, using the ESP32 internal pull-ups: GPIO10 for previous/back, GPIO13 for select/confirm, and GPIO14 for next.
- Use short left/right presses for page or item navigation, short select for entry, a long left press for back/home, and an explicit select hold for disruptive confirmation.
- Verify whether the module provides suitable SDA/SCL pull-ups and that every external pull-up is tied to 3.3 V, not 5 V; add external pull-ups to 3.3 V if the module does not provide them.
- Hardware verification established yellow rows 015 and blue rows 1663. A narrow physical black divider separates the two regions even though row 15 is the final yellow addressable row and row 16 the first blue addressable row.
- Keep assignments centralized in the board profile rather than scattering display or button GPIO assumptions through UI code.
Implemented and accepted: a bounded, persistent user system replaces the single shared network credential. Both roles can use the authenticated web serial/status interface. Over SSH, `user` routes to the broker-backed serial stream while `admin` routes exclusively to the administration shell and receives no broker client or writer lease. UART0 remains the physical recovery and bootstrap authority.
![Phase 7C icon status-page mockup](phase7c_icon_mockup.svg)
The persistent yellow strip uses fixed-position serial, Wi-Fi-strength, USB, WebSocket, SSH, broker-client, and alert icons. Active icons are solid with a compact value below; inactive icon slots remain blank and show no value. The blue 128×48 content panel begins at row 16 and rotates through overview, RS-232, broker-client, and network/service pages; the physical black divider remains visually clear. No password, Wi-Fi secret, private-key material, or routine credential data may appear on the display.
#### Implementation sequence
1. **Phase 7A — Electrical bring-up and diagnostics — Complete**
- Bounded low-level display and button diagnostics are available under the existing `debug` submenu.
- The selected module acknowledged at 7-bit `0x3c` (8-bit `0x78` write / `0x79` read). A guarded full scan is retained for the dedicated local-UI bus; an absent display remains nonfatal and does not make the serial core dependent on the OLED.
- Hardware validation passed for geometry, orientation, row/column addressing, contrast, inversion, button pull-ups/debounce/short-press/long-press/stuck behavior, and the color geometry: yellow rows 015, blue rows 1663, with a physical black separator between the regions.
2. **Phase 7B — Display driver — Complete**
- The `local_display` service owns the local I²C bus, SSD1315-compatible panel, and framebuffer. It uses a static 1 KiB 128×64 framebuffer, a compact 5×7 upper/lowercase, digit, and punctuation renderer, and an internal mutex; do not add LVGL for this fixed monochrome UI.
- Rendering treats the yellow 128×16 status panel (rows 015) and blue 128×48 content panel (rows 1663) as separate panels so the physical divider remains clear.
- Frame commits refresh only dirty 8-pixel pages. I²C runs at 100 kHz with bounded transactions.
- The display bus initializes at boot; a known display is automatically initialized and cleared. A missing or unresponsive display is nonfatal and does not make the serial core dependent on it.
- Target-hardware validation passed for initialization, all display diagnostic patterns, the rendered panel layout and physical divider, row 15/16 boundary, contrast, inversion, display-off/reinitialization, and button diagnostics. Observed contrast control has a useful brightness range of 1255.
3. **Phase 7C — Read-only status UI — Complete**
- The low-priority `local_status_ui` owner task builds display state from copied public serial, Wi-Fi, broker, USB, WebSocket, HTTPS, and SSH snapshots. It does not parse CLI output, reach into transport internals, or become a broker client.
- Previous/back and next short presses navigate overview, RS-232/modem, broker-client/writer, and network/service pages. Select has no state-changing action in this read-only phase.
- The task polls and debounces the existing active-low button inputs and refreshes at 4 Hz maximum. It collects service snapshots before beginning a display frame, so no service or broker lock is held across an I²C transaction.
- The yellow panel is page-independent and uses fixed icon slots. Wi-Fi strength is shown by segmented Wi-Fi bars; the USB glyph is derived from Pictogrammers Material Design Icons. Page text uses lowercase where appropriate, separates labels and values with colons, and shows the active station or AP SSID plus channel.
- To reduce OLED aging, inactivity dims contrast to `1` after five minutes and switches the panel off after ten minutes. The first debounced button press restores contrast `127` and wakes without navigating.
- A missing/unresponsive display is nonfatal; the task remains read-only and never acquires serial writer ownership.
- Target-hardware validation passed for the four pages, fixed active-only status icons, lowercase layout, diagnostics hold, dim/off/wake behavior, all available concurrent client interfaces, UART0 recovery, and serial traffic from 9600 through 230400 baud.
4. **Phase 7D — Local controls — Complete**
- A shallow local `Controls` menu directly invokes public serial-service, Wi-Fi, HTTPS, SSH, broker, display, and restart APIs; it never parses or injects CLI text.
- The menu provides serial start/stop, Wi-Fi start/stop/reconnect/next-profile, HTTPS start/stop, SSH start/stop, emergency current-writer revocation, display off, and reboot. `WiFi:next profile` queues a rotation to the enabled profile after the currently active one in priority order, wrapping safely; profile configuration and credentials remain unavailable to the UI. The menu deliberately excludes serial configuration editing, Wi-Fi profile/AP changes, host-key/certificate changes, I²C scans, and assignment of the writer to another client.
- A visible confirmation screen and one continuous two-second Select hold are required for service stops, Wi-Fi reconnect, Wi-Fi next-profile, writer revocation, and reboot. The confirmation times out after 30 seconds; previous/back cancels. A wake press is consumed and cannot navigate or confirm an action.
- Wi-Fi lifecycle results report a queued request rather than falsely claiming an asynchronous transition has completed. HTTPS/SSH start requests require a connected station or active AP. The current writer is only ever force-released to no writer; the UI is not a broker client and cannot acquire or assign a writer lease.
- Target-hardware validation passed for menu navigation and timeout behavior, controls and asynchronous results, two-second confirmations and cancellation, Wi-Fi next-profile progression/wrap, chord rejection, wake-press suppression, and preservation of UART0 plus transport recovery.
5. **Phase 7E — Reliability, persistence, and documentation — Complete**
- At startup, a bounded five-second OLED-only identity animation renders a compact monochrome, right-oriented derivative of the project logo in the blue panel: its upright `>_` terminal remains readable, while both USB and serial cable ends enter from the left. The full device name scrolls through the yellow panel. A missing or failing OLED skips the animation without delaying recovery services further.
- A versioned `local_ui` NVS configuration makes the dim and display-off inactivity delays independently configurable from 0 through 86400 seconds. Zero disables a transition; defaults remain 300/600 seconds. UART0 `display` commands provide status, RAM edits, save/load, defaults, and atomic reset behavior.
- A button held for ten seconds is quarantined until its debounced release, after which it rearms. Quarantined inputs no longer keep a chord latched or block the other controls. A confirmation hold can execute at most once.
- Dim/off wake and missing-display recovery now occur only on a new debounced press edge. A held or stuck input cannot continuously probe an absent OLED, flood logs, or indefinitely refresh the inactivity timer; the wake gesture remains consumed.
- Dirty framebuffer commits have a 500 ms scheduling budget in addition to each bounded 250 ms I²C transaction. A failed frame marks the panel unavailable, while serial, broker, network, USB, and UART0 services remain independent. Safely reconnecting the OLED and pressing a button requests one bounded reprobe.
- Wi-Fi manager queue drops now activate the persistent yellow alert slot and remain observable through Wi-Fi counters. Local action errors continue to be reported directly without blocking queue insertion.
- Target-hardware validation passed for configuration persistence and disable semantics, absent and reattached display behavior, I²C NACK/timeout handling, each stuck-button and rearm path, repeated actions/queue-error indication, and concurrent USB CDC, WebSocket, SSH, serial, and UART0 operation during faults.
Phase 7 completion required electrical validation on the selected module, correct operation with all current transports, bounded display/button failure behavior, safe action confirmation, no unexplained serial or broker loss, and documented UART0 recovery; these criteria are met.
### Phase 8 — Role-based users and administrative access
Replace the single shared network credential with a bounded, persistent user system. Accounts have one of two authorization roles: `user` receives the currently implemented authenticated serial/status experience, while `admin` additionally receives administrative command and user-management capabilities. UART0 remains the physical recovery and bootstrap authority.
Implementation sequence:
Completed implementation (8A8C target-hardware validated; 8D explicitly accepted at 8D.22 on 2026-09-13):
1. **Phase 8A — User database and UART0 administration — Complete**
- A versioned `user_db` NVS blob holds at most eight accounts with unique lowercase usernames, `user`/`admin` roles, random account IDs, per-account authentication generations, and fixed storage bounds. The final administrator cannot be deleted or demoted.
- Passwords use random 16-byte salts and PBKDF2-HMAC-SHA256 verifiers rather than recoverable plaintext. UART0 provides bounded no-echo entry, confirmation, and one-time 24-character generated passwords for bootstrap, create, and password-change operations. Valid authentication attempts perform one real or dummy PBKDF2 outside the database mutex and revalidate the account generation before returning a principal.
- Each account accepts up to three bounded OpenSSH public keys. Initial import supports Ed25519 and ECDSA P-256, validates key structure and P-256 points, rejects a key already assigned to any account, and exposes only key type plus SHA-256 fingerprint in snapshots and status output.
- On first boot after upgrade, the existing shared `admin` network credential is transactionally imported as a role-`user` account; it is never silently elevated. `user bootstrap` sets a new password and promotes that account to `admin`. Until bootstrap, legacy web credential rotation/reset synchronizes the imported verifier and boot reconciliation repairs an interrupted second NVS commit. After bootstrap, Phase 8A deliberately leaves the legacy HTTPS/SSH credential separate until Phase 8B switches network authentication to the common database.
- `user recover --force` remains registered even when a malformed or incompatible user blob prevents normal initialization. From physical UART0 it explicitly replaces only the user-database blob with a role-`user` account derived from the current legacy network credential; it never automatically erases shared NVS.
- NVS remains unencrypted. Verifiers improve password-at-rest handling, but offline guessing remains possible and append-oriented flash may retain historical plaintext legacy credentials until the partition or flash is physically erased.
- Target-hardware basics for migration, bootstrap, CRUD, persistence, and command behavior were validated before beginning Phase 8B. The full fault-injection matrix remains a regression suite for later hardening.
2. **Phase 8B — Role-aware HTTPS and SSH authentication — Implemented; validation pending**
- HTTPS Basic and SSH password authentication now use the common user database and retain a secret-free principal containing account ID, username, role, authentication method, and credential generation. Authentication fails closed when the database is unavailable; both `user` and `admin` roles retain the existing serial/status experience.
- SSH advertises password and public-key authentication only. The application authorizes stored Ed25519 or ECDSA P-256 username/key pairs, while wolfSSH verifies possession. Authorized unsigned probes produce only the protocol `PK_OK` response; a principal becomes authenticated only from wolfSSH's post-signature result callback and is checked again before broker admission.
- WebSocket tickets are one-time, principal-bound bearer values. Tickets are consumed before currentness validation, and active WebSocket/SSH sessions retain copied principals. Currentness is checked around broker admission, before WebSocket input, and periodically for idle/output sessions.
- Successful password, role, key, bootstrap, delete, and legacy pre-bootstrap synchronization mutations synchronously invalidate only the affected username's tickets and sessions. Per-account generations plus ongoing currentness checks provide fail-safe revocation for changed/deleted accounts while unrelated users remain connected.
- Secret-free UART0 session snapshots show account, role, and authentication method. Transport slot generations remain separate from account authentication generations to preserve ABA-safe task/work ownership.
- The legacy `web_sec` credential no longer authenticates HTTPS or SSH. It remains only for first migration and explicit physical recovery; rotating it after bootstrap does not disconnect or alter role-based users. TLS certificate/private-key handling remains in `web_security`.
- Pending target-hardware validation covers both roles and password lengths, both supported SSH key types and probe/signature behavior, ticket binding/reuse/expiry, targeted password/role/key/delete revocation, username recreation, concurrent users/transports, database-unavailable fail-closed behavior, and preservation of normal serial writer/observer operation.
3. **Phase 8C — SSH administrative shell — Planned**
- Route authenticated `admin` SSH shell sessions to the same registered administrative command set as UART0, without creating a broker client. Normal users continue to receive the existing broker-backed serial stream.
- Serialize command parsing safely because ESP-IDF console internals are process-global. Use bounded per-session input/output queues and a separate command worker; only the SSH owner task may call wolfSSH APIs.
- Versioned NVS database for up to eight `user`/`admin` accounts, random account IDs and authentication generations, final-admin protection, and three Ed25519/P-256 keys per account.
- Salted PBKDF2-HMAC-SHA256 password verifiers, bounded no-echo entry, one-time generated passwords, and secret-free account/key status.
- Historical migration/bootstrap supported the initial cutover. Current firmware instead commits missing storage empty, provisions the first admin with normal UART0 `user add`, and provides UART0-only unavailable-database recovery; legacy credential/bootstrap commands are removed.
- Migration, bootstrap, CRUD, persistence, and command basics target-hardware validated; the full fault-injection matrix remains regression coverage. NVS remains unencrypted and offline guessing remains possible.
2. **Phase 8B — Role-aware HTTPS and SSH authentication — Complete**
- HTTPS and SSH authenticate through the common database and copied secret-free principals; unavailable user storage fails closed. The initial HTTPS Basic path was replaced by cookie authentication in 8D.
- One-time principal-bound WebSocket tickets and ongoing principal-currentness checks prevent stale admission or input.
- Account mutations request targeted WebSocket/SSH revocation; authentication generations provide fail-safe invalidation while unrelated accounts remain connected.
- Password/key login, ticket behavior, targeted revocation, recovery, and concurrent transport operation are target-hardware validated. Legacy credentials were subsequently removed without changing established TLS identity or valid users.
3. **Phase 8C — SSH administrative shell — Complete**
- Authenticated `admin` SSH shell sessions route to a bounded administration worker and never create a broker client or acquire a serial writer lease. Normal `user` sessions retain the existing broker-backed serial stream.
- UART0 and admin SSH now submit complete lines to one fixed-length request queue. A single dispatcher task is the sole caller of ESP-IDF's non-reentrant `esp_console_run()` and therefore executes the same registered command handlers for both entry routes. The former separately implemented reduced SSH command dispatcher has been removed.
- The worker uses fixed per-session command/input and output buffers. Queue records contain copied secret-free principals and generation-tagged session tokens; late work is discarded after disconnect, slot reuse, role change, password/key mutation, or deletion. Task-local standard streams route canonical handler output into the applicable bounded SSH ring, and only the SSH owner task calls wolfSSH APIs.
- Transport-neutral bounded prompts now support interactive user passwords/keys and Wi-Fi secrets over admin SSH without exposing hidden input or allowing another command while a prompt is active. Ping callbacks enqueue typed bounded events and the dispatcher alone formats their output. Four-entry per-session history and whole-line Tab completion are RAM-only and wiped on disconnect.
- Authenticated administrators receive the operational registry, including HTTPS material rotation/reset, reboot, ping, and SSH lifecycle/session/host-key mutation. Self-terminating reboot and SSH actions are deferred until acknowledgement output drains, block further shell input, and execute through existing synchronous owner APIs from a separate bounded control task. First-admin provisioning and explicit `user recover --force` remain physical-UART0 operations (`user bootstrap` was later removed); admin SSH also rejects generating a replacement password for its own account.
- `ssh sessions` and `ssh counters` identify broker versus admin-console routes, worker command state, queued admin output, admission failures, and input backpressure. `exit` and Ctrl+D on an empty command line request bounded deferred self-disconnect after best-effort application-buffer draining. Admin sessions are checked for a current `admin` principal before command execution and during the active-session reconciliation.
- Keep SFTP, SCP, `exec`, forwarding, subsystems, and unauthenticated shells disabled.
4. **Phase 8D — Web user administration — Planned**
- Add an admin-only user-management interface and typed, bounded APIs for account CRUD, roles, password generation/change, SSH-key management, and revocation. Never expose a generic HTTP endpoint that executes arbitrary CLI text.
- Hide administrative navigation and controls for normal users, and enforce every authorization decision server-side so hidden UI is not treated as a security boundary.
- Preserve the existing normal terminal interface. Use strict origin/CSRF protections for mutations, secret-safe JSON encoding, one-time display of generated passwords, and no-store responses for administrative material.
- Target-hardware validation passed for route separation, history/Tab editing, interactive visible/hidden prompts, output/backpressure, generated and entered user/password/key management including the longest ECDSA P-256 import, ping event routing, deferred reboot/SSH lifecycle drain behavior, bootstrap/recovery rejection, targeted self/other-user revocation during queued work, UART0/SSH administration serialization, and concurrent USB/WebSocket/user-SSH/admin-SSH operation. Stress at 460800 baud with SSH and WebSocket clients caused substantial expected packet drops and slower display controls, but did not exhaust memory or require lowering the supported baud-rate range.
4. **Phase 8D — Integrated web administration — Complete**
- User explicitly signed off tested firmware at **8D.22 on 2026-09-13**, superseding earlier per-slice pending acceptance/review gates. Cookie login/logout replaces Basic; bounded digest-only sessions, same-origin/CSRF checks, principal currentness and targeted revocation protect serial and admin routes.
- Admin-only Serial/Admin selection and Settings preserve connected terminal observation and serial writer ownership. The browser shell shares the serialized UART0/admin-SSH dispatcher, with bounded output, explicit admission and retained frontend restrictions—not unrestricted shell parity.
- Typed Serial, Accounts/password/authorized-key, Network/Wi-Fi/mDNS, Display, Broker and SSH settings; confirmed HTTPS stop/restart/reboot and HTTPS/SSH identity rotation. Canonical owners compare reserved service/identity/target generations, preserve commit/failure semantics and expose no stored secrets. Admitted work is not cancelled by later logout/timeout; uncertain mutations are never automatically replayed.
- Accessible Serial/Wi-Fi/client/writer contextual controls reuse existing controllers. Writer transfer is explicit and generation-safe; one writer, isolated observers, binary transparency, UART0 administrative recovery and network-independent native USB UART1 remain invariants.
- Scope removed by user: **8D.15** dedicated typed network diagnostics (shell diagnostics retained) and the unimplemented **8D.19** ordinary browser-session/native-USB controls (SSH controls retained). Browser identity reset/recovery/export is excluded; canonical recovery remains available.
- Prior final build PASS: **100,556 B linked RAM / 1,828,573 B flash, CPU 160 MHz**. Earlier combined binary WebSocket-send fix was explicitly accepted at **160 MHz / 230400 baud with full client mix including browser admin**. Latest overall sign-off does not invent individual fault/soak/duration results or a latest exact zero-drop comparison.
- Latest loaded internal/DMA minima **2,052 / 460 B** remain a conservative transient-headroom follow-up, not a blocker reopening acceptance or an approved reserve. See [acceptance and telemetry](web_administration_acceptance.md), [current contracts](web_administration.md), [regression procedures](user_administration_tests.md#integrated-web-administration-regression-procedure) and [legacy compatibility](legacy_credential_removal.md).
Completion requires migration and power-loss recovery tests, final-admin protection, malformed credential/key rejection, password and key login for both roles, targeted session revocation, concurrent normal/admin SSH operation, hidden and server-rejected user-level web administration, and continued UART0 recovery.
## Current and planned phases
Phase 8 is complete for its accepted scope. Phase 9 has started at the user's request; later work remains planned or under evaluation. Optional features must not weaken completed serial and recovery paths. General release gates below remain guidance for future work, not claims that every listed fault, soak or reserve measurement was individually performed for 8D.
### Phase 9 — Security and production hardening
Harden stored credentials, boot integrity, update trust, failure diagnostics, and dependency maintenance. This phase must be staged carefully because some ESP32 eFuse operations are irreversible.
**In progress.** Harden network authentication, secret lifetimes, crash/debug exposure and operational maintenance. Secure boot and encrypted NVS are explicitly excluded by user preference. No eFuse, partition, at-rest encryption or dependency-version upgrades are part of 9A9C; 9C adds source-pinned build-tree dependency corrections; no future flash/PSRAM encryption commitment is implied. Physical extraction and firmware replacement remain outside the threat model after Phase 9, and software debug restrictions do not imply physical JTAG fuse restrictions.
Planned work:
Staged work:
- Define development, test, and production security profiles.
- Enable and validate NVS encryption for Wi-Fi, HTTPS, and SSH material.
- Evaluate flash encryption and PSRAM encryption for the target hardware and threat model.
- Enable secure boot with a documented signing-key and recovery process.
- Define secret-safe core-dump handling; do not expose credentials or session material in diagnostics.
- Audit key and session-material zeroization across application, mbedTLS, wolfSSL, and wolfSSH allocations.
- Add authentication throttling, lockout/backoff, and security-event counters where appropriate.
- Review TLS/SSH algorithms, certificate policy, password policy, and browser security headers.
- Review current wolfSSL/wolfSSH and ESP-IDF security releases instead of treating integration versions as permanent pins.
- Recheck all third-party licenses and preserve source/license notices.
- Document provisioning, key rotation, factory reset, backup, recovery, and device decommissioning.
1. **9A — Crash/debug build policy and operational profiles — In progress; hardware pending.** `src/security_build_policy.c` requires `CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y` and `CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT=y`; rejects core-dump enable/flash/UART, panic print/halt/GDBstub, runtime GDBstub and ESP/FreeRTOS debugger-aware options. `sdkconfig.defaults` makes the baseline explicit. Development/test/production use the same build baseline, not separate PlatformIO environments. Host matrix (`python3 tests/security_build_policy/run.py`) compiles the actual guard: 17 cases plus the generated-header check passed on 2026-09-15. `pio run` passed (94,196 B linked RAM / 1,828,565 B flash); target panic/recovery tests have not run. Production readiness remains pending.
2. **9B — SSH admission and credential handling — Implemented; combined target validation deferred.** Boot-lifetime, owner-only token buckets independently bound handshakes, password/signed-key requests and unsigned probes; reconnect/restart/counter clearing do not replenish them. Existing per-slot attempt limits/currentness remain. Explicit keyboard-interactive rejection, pending-signature result fencing, secret-free admission counters, consumed admin-buffer wipes and fail-closed hidden-prompt overflow/unsupported-byte handling are implemented. Four focused suites (including 35 pinned-vendor control-flow cases), 11 related regressions and `pio run` passed on 2026-09-15: 94,340 B linked RAM / 1,829,925 B flash. Global-budget starvation remains a documented tradeoff, not a solved availability problem.
3. **9C — Library cleanup and protocol policy — Implemented; combined target validation deferred.** Exact-hash build-tree overrides correct HTTPS cleanup/leaks, HTTPD scratch failure/wiping/first-read handling, bounded SSH password parsing/wiping and server-local TLS policy without modifying installed dependencies. Secure wolfSSL allocation hooks and explicit SSH policy fail closed; early web quota probing avoids receiving already-throttled bodies. TLS1.2 ECDHE-ECDSA AES-GCM and SSH GCM/modern-KEX allowlists intentionally exclude legacy-only clients; no identity migration. Bounded password/certificate/header/destructor review is documented, not exhaustive zeroization. Final build PASS 94,340 B linked RAM / 1,831,309 B flash; focused and related host/source-contract tests passed. [Review and maintenance contract](security_library_review.md).
4. **9D — Maintenance and lifecycle — In progress; unresolved security and distribution questions.** [Security operations](security_operations.md) documents provisioning, explicit saves, rotation, recovery, reconstruction (no implemented backup/export) and approved destructive reset/decommissioning. The [wolfSSL/wolfSSH implementation addendum](wolf_security_review.md) records the implemented Xtensa small X25519/Ed25519 mitigation (CVE-2025-12888), with consistent library/consumer flags and a resolved-settings guard; small X25519 is not combined with blinding. Bounded IGNORE/service/string parsing, channel-window overflow, ECC/Ed25519 labels and exact signature framing are now corrected in the existing generated override. [P-256 import and X25519 all-zero-result checks](ssh_key_validation_review.md) are enabled with effective PUBLIC flags confirmed; the [finite remaining SSH parser/caller review](ssh_parser_remaining_review.md) is complete, not exhaustive safety. Exact CHANNEL_FAILURE recipient, `ssh-userauth` service and all nine channel-name checks are implemented; unknown/trailing-payload behavior is retained. PR899 client skips remain unchanged behind server ordering, forwarding is disabled, and the inspected generic caller trace has no short-digest/OID trigger; generic APIs are not globally fixed. **Restricted existing-profile ordering correction (CVE-2025-14942) is implemented**, using audited PR793/819/840/855/921 subsets plus local gates, not a full upstream backport. X25519/P-256 only, independent SELF/PEER bits, expected-message/authentication gates and queued NEWKEYS continuation handle nonblocking writes. **EXT_INFO is intentionally disabled; no `server-sig-algs` is advertised.** Nine C overrides (including the new IDF 5.5.3 WS signed-size correction) plus one PUBLIC forced ABI header retain hash pins/notices; joined forced-header arguments fix PlatformIO sorting/deduplication. The review's misplaced EOF guard is corrected and verified with no scoped blocker. The [IDF implementation addendum](idf_security_review.md) records pinned DHCP (CVE-2026-45160), TLS 1.2 EMS (CVE-2026-50581) and X.509 allocation-failure (CVE-2026-34874) backports; historical research remains labeled and retained. The [finite IDF applicability completion](idf_security_review.md#finite-applicability-completion--2026-09-16) dispositions all six named findings: ECDH small-output, zero-length ECC PK parse, basicConstraints, server NewSessionTicket and stale ASN.1 length are not current paths/configurations for their documented reasons; optimized ECC reduction is active but its privileged-local/physical side-channel attacker model is excluded. No new current-path correction was established. That earlier review screened only the first advisory-index page. The subsequent [finite dependency coverage](dependency_advisory_coverage.md) accounts for all **22 IDF entries across three pages**, plus named managed-component and browser publication channels. The declared dated search is complete, not exhaustive advisory clearance; unpatched primitives, inaccessible full-release databases and fresh findings remain.
Security features must be validated first on expendable hardware before any irreversible production configuration is recommended.
**Historical IDF 5.5.0 integration evidence:** supplied parent build PASS: **94,340 B linked RAM / 1,768,901 B flash**, unchanged RAM / **+200 B flash** versus 1,768,701 B. Final parent **all seven suites PASS**: ordering `--interop` (8,028 checks, seven rejected mutations, 12 exact-256-KiB sessions with clean channel close/transport EOF), SDK overrides with actual `--build-dir` registration, auth (135), protocol, strict crypto, notices (30), and parser (3,258 × two modes plus channel profiles; 11 + 18 + 2 rejected mutations). Interop required unsandboxed approval only for local AF_UNIX sockets; no remote network/device operation. Agent ordering evidence: **8,028 checks / seven rejected mutations**. Initial interop failed a harness close race despite early PASS output; the corrected harness waits for peer close/transport EOF and independently reaps the server through an fd-passing proxy. Final agent repeated OpenSSH matrix: **36/36 sessions**, each exact **256 KiB**, **two or ten** completed key exchanges and clean client/server exits; see [evidence and limits](security_hardening.md#ordering-hostbuild-evidence--2026-09-16).
**Release status:** the [bounded license inventory](dependency_licenses.md) marks modification/date notices resolved for all nine generated C files plus one header (baseline 2026-09-15 and wolfSSH ordering 2026-09-16; upstream licenses retained), with archived patch hashes/commits and patch license context recorded, but radio-blob corresponding-source/exception, source/notice delivery and provenance questions remain open. [Offline notice assembly](release_packaging.md) is implemented by [tools/release_notices.py](../tools/release_notices.py): 75 mandatory hash/size-pinned inputs (nine IDF/toolchain notice entries semantically rebased for the candidate; the other 66 unchanged), deterministic bounded outputs, fail-closed preflight and no overwrite/fetch/build/device access. Supplied agent evidence: **36 notice fixture tests PASS; two actual bundles verified deterministic, each 77 files / 4,433,930 bytes**. This includes retained SVGs and [exact icon provenance](icon_provenance.md), not corresponding-source delivery or legal clearance. These are agent measurements, not a parent rebuild or reassembly in this documentation turn.
**Remaining maintenance/target gates:** official registry wolfSSH 1.5.0 / wolfSSL 5.9.2 queries returned 404 on 2026-09-15; upstream tags exist but managed compatibility is not established. The [remaining ordering gates and immutable provenance](wolf_security_review.md#restricted-ordering-correction-and-remaining-gates) retain target cleanup during rekey, intended-client compatibility without EXT_INFO and whole-phase resource/timing validation. Future upstream adoption still requires isolated packaging/compatibility evaluation. Upgrades/backports require coherent source/header review, override rebasing and contract tests, not blind repinning. The [declared finite dependency search](dependency_advisory_coverage.md) is complete; fresh findings and explicit coverage gaps remain. **The fix-bearing Wi-Fi vendor bundle is integrated in the validated IDF 5.5.3 candidate; radio-hardware closure remains pending.** Follow the [Wi-Fi security update plan](wifi_security_update_plan.md) for target acceptance; do not transplant one archive, edit only the callback signature or weaken PMF/WPA3. Root migration pins are edited; complete immutable dependency closure and a successful normal root build are not established. **Phase 9 is not complete or production-ready; scoped mitigations do not establish full advisory closure, device validation or license/distribution clearance.** OTA signing trust remains separate Phase 10 work.
**Current IDF 5.5.3 integration:** fresh isolated `app-validated` build PASS, **95,552 B linked RAM / 1,749,493 B flash** (**+1,212 / 19,408 B** versus historical 94,340 / 1,768,901 B). Root selects PlatformIO 6.13.0 / framework 3.50503.0 / both toolchains 14.2.0+20251107. Default root `pio run` timed out after 200 seconds during installation, before compilation. All nine C overrides plus the header have actual-build registration evidence; generated WS tests pass **982 cases / 10 mutation checks**. See [integration and remaining gates](idf_candidate_integration.md).
**Bounded host validation:** 23 commands by default; build, OpenSSH interop and web performance are explicit options. Historical default 23/23 and 10 orchestrator fixtures passed on the earlier snapshot. Current supplied parent validation selects the isolated IDF 5.5.3 build/core/SDK, with `--interop --web-performance`: **PASS 24/24**. See [exact command, source equality and evidence limits](phase9_validation.md#current-candidate-execution--2026-09-18). This does not claim a successful default root build or whole-phase acceptance.
At the user's request, hardware validation is deferred to **Phase 9 as a whole**, not required between implementation slices. [Security hardening](security_hardening.md) collects profiles, host evidence and the combined target checklist. Silent panic reboot removes useful crash diagnostics, not ordinary reset/boot/status information or every possible log disclosure. Raw flash/RAM/dumps remain secret-bearing, not routine diagnostic exports. Existing coredump bytes are not retroactively cleared; no secure erase is claimed. Isolated synthetic-secret debug builds require explicit reviewed source-policy changes, not a provided bypass flag.
### Phase 10 — Authenticated OTA and rollback
@@ -297,7 +236,7 @@ Use the existing dual 4 MiB application slots and `otadata` partition to add saf
Planned work:
- Accept only authenticated, integrity-checked firmware images compatible with the selected secure-boot policy.
- Accept only authenticated, integrity-checked firmware images under an independently defined OTA signing-trust policy without secure boot; define trusted-key provisioning, rotation, revocation and recovery. This cannot prevent physical firmware replacement.
- Support an update path that does not expose a plaintext management endpoint.
- Stream downloads with bounded RAM use and explicit progress/error reporting.
- Preserve serial, Wi-Fi, HTTPS, and SSH configuration across successful updates.
@@ -321,7 +260,7 @@ Planned work:
- Preserve binary transparency through explicit framing and MTU-aware partial transfers.
- Bound connections, queues, retries, and advertising behavior.
- Measure coexistence with 2.4 GHz Wi-Fi, HTTPS, WebSocket, SSH, USB CDC, and UART service.
- Store bond/provisioning data under the hardened secret-storage policy.
- Define bond/provisioning secret retention under the unencrypted-storage threat model; do not assume Phase 9 provides at-rest encryption.
- Provide UART0 controls and a physical recovery path for clearing BLE state.
BLE remains subordinate to stable Wi-Fi and serial operation; it should be omitted if coexistence or memory costs cannot be bounded acceptably.
@@ -330,7 +269,7 @@ BLE remains subordinate to stable Wi-Fi and serial operation; it should be omitt
These features are candidates, not current commitments:
- mDNS advertisement for the certificates device-specific `.local` name and selected services.
- Additional DNS-SD service advertisement and any certificate-name integration beyond the implemented configurable STA hostname.
- Enterprise Wi-Fi support, subject to credential-storage and certificate-validation design.
- IPv6 behavior and diagnostics beyond the current basic support.
- WireGuard feasibility evaluation, including RAM, CPU, licensing, key storage, routing, and recovery impact.
@@ -367,10 +306,10 @@ Every phase should satisfy the following before being marked complete:
The following are not implemented merely because flash partitions or library support exist:
- NVS, flash, or PSRAM encryption.
- Secure boot or production eFuse provisioning.
- Secure boot and encrypted NVS are excluded by explicit user preference, not scheduled future enablement.
- Flash/PSRAM encryption and production eFuse provisioning are outside the current scope, with no enablement commitment.
- OTA download, image confirmation, or rollback policy.
- Core-dump collection or secret-safe core-dump processing.
- Core-dump collection or export: the supported Phase 9A baseline disables new dumps; existing partition bytes are not cleared.
- Filesystem mounting.
- SFTP, SCP, SSH `exec`, forwarding, or subsystems.
+231
View File
@@ -0,0 +1,231 @@
# Security hardening — Phase 9
**Status: in progress.** Phase 8 is complete at the accepted 8D.22 scope. **9A crash/debug policy, 9B SSH admission/credential handling and 9C library cleanup/protocol policy** are implemented with host/build validation. At the user's request, hardware validation is deferred to **Phase 9 as a whole**, not an approval gate between implementation slices. **9D maintenance/lifecycle is in progress, with unresolved advisory and distribution/source/notice questions. Phase 9 is not complete or production-ready.** This document records policy and procedures, not unrun passes or production certification.
## Current migration evidence — 2026-09-18
Root `platformio.ini` now pins **PlatformIO espressif32 6.13.0 / framework-espidf 3.50503.0 (IDF 5.5.3)** and both Xtensa and RISC-V toolchains at **14.2.0+20251107**. These are exact version pins, not enforcement of archive hashes or a complete immutable build closure. The [candidate integration record](idf_candidate_integration.md) distinguishes the verified archive identities from the root configuration.
Supplied parent evidence: a **fresh isolated application build PASS** in `.pio/idf-candidate-5.5.3/app-validated`, with **95,552 B linked RAM / 1,749,493 B flash**, versus historical **94,340 / 1,768,901 B**: **+1,212 B RAM / 19,408 B flash**. The default root `pio run` timed out after **200 seconds during installation, before compilation**; it is **not a normal root build PASS**. Final explicit-candidate Phase 9 validation with interop and web performance **PASS 24/24**; see [command and snapshot evidence](phase9_validation.md#current-candidate-execution--2026-09-18). Source equality covered **3,237 files**, pre/post SHA-256 **`3a1af78c15cfdd02da1055a8957b4086f9018862b7aa1c7c52fd2401a1a0a031`**.
All **nine generated C sources plus one forced header** are validated as actual compilation inputs. The new WS correction makes five fixed-header `sizeof` comparisons signed; **982 behavioral cases / 10 mutation checks** cover generated WS receive behavior. The stale web-cookie IDF 5.5.0 fixture was corrected. [Rebase review](idf_553_rebase_review.md) retains old findings as history, not current blockers, and records all packaged Wi-Fi/PHY/coexistence/supplicant files matching the locked framework archive.
The fix-bearing vendor Wi-Fi bundle is integrated in the validated candidate, **not radio-hardware vulnerability closure**. PMF/WPA3 is unchanged. Whole-phase target/radio/resource/recovery acceptance, complete dependency closure and release/source/legal gates remain pending; **Phase 9 is not complete or production-ready**. These are supplied parent results, not builds or hardware tests rerun by this documentation update.
## Scope and threat model
Reduce network abuse, accidental diagnostic disclosure and unnecessary secret retention while preserving one UART1 broker writer, isolated observers and binary transparency. UART0 remains trusted physical administration/recovery; native USB remains network-independent UART1 access, not an admin console. Whole-device reboot interrupts every transport.
Secure boot and encrypted NVS are explicitly excluded by user preference. Physical flash/RAM extraction and firmware replacement remain outside the threat model even after Phase 9. There is no commitment to flash/PSRAM encryption, eFuse provisioning or physical JTAG restrictions. Software debugger-aware configuration checks do not disable physical debug access by fuse.
9A does not change partitions, at-rest encryption, dependencies or generated assets, and requires no upload or erase as part of host/build validation. The unused `nvs_key` and `coredump` partitions remain for layout compatibility. Disabling new dumps does not clear old coredump contents. Logical NVS replacement, reset and credential rotation are not secure erasure; historical plaintext copies can remain.
## 9A supported build baseline
`src/security_build_policy.c` enforces the following at compile time, with explicit settings in `sdkconfig.defaults`:
- Require `CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y` and `CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT=y`.
- Reject enabled core-dump support, flash or UART dump destinations.
- Reject panic print/reboot, print/halt and GDBstub modes, plus runtime GDBstub.
- Reject `CONFIG_ESP_DEBUG_OCDAWARE` and `CONFIG_FREERTOS_DEBUG_OCDAWARE` when enabled.
The host matrix in `tests/security_build_policy/run.py` compiles the actual guard against synthetic configurations; it is not merely a text check of defaults. Existing generated SDK configuration must also satisfy the guard: defaults alone are not evidence of the effective build configuration.
Silent panic reboot deliberately sacrifices panic text, register dumps and backtraces for reduced crash disclosure. Reset-reason/boot information and ordinary status/logging can remain; neither silence across the full boot sequence nor general log redaction is guaranteed. A monitor exception decoder cannot reconstruct a backtrace that was never emitted.
## 9B SSH admission and credential handling
### Boot-lifetime admission budgets
`src/ssh_auth_policy.{c,h}` owns three independent, fixed-size token buckets. Only the SSH owner task accesses the shared 72-byte policy; no allocation, per-peer/account map, timer task or sleep is added.
| Admission class | Initial/maximum burst | Refill |
|---|---:|---|
| New SSH handshake | 6 | One token per 10 seconds |
| Password or signed-key authentication request | 6 | One token per 10 seconds |
| Unsigned public-key probe | 12 | One token per 5 seconds |
These are **burst-plus-refill limits**, not six/twelve requests in every rolling minute. All peers/accounts and both slots share each class. Idle refill stops at capacity; denials do not extend the refill deadline. Reconnects, service stop/start, identity rotation and `ssh clear-counters` do not replenish the pools. Reboot starts a new policy lifetime. Timestamp regression fails closed. No persistent account lockout or NVS write is introduced.
- A handshake token is taken after finding capacity but before `wolfSSH_new()`/handshake work. Full-capacity rejection takes no token; later allocation/IO failure does not refund it.
- Password/signed-key admission precedes database verification/authorization and ordinary key signature work. Success, invalid credentials, backend errors and rejected password-change requests do not refund admission. Unsigned probes use their own pool and cannot authenticate.
- Exhaustion shuts down/rejects the new or authenticating connection without waiting inside the owner task. Already-authenticated streams do not pass through this admission gate. The existing three-counted-attempt failure closure, two-slot bound and 15-second handshake deadline remain.
- **Availability tradeoff:** a client can consume the handshake burst by opening/abandoning connections and race legitimate clients for each refill. Global verification/probe pools can also starve other users. This bounds admitted work, not fair access or immunity to denial of service. TCP accept/rejection work and library parsing still occur; target latency under abuse is not yet measured. Restrict network access, stop the offending traffic and allow natural refill rather than repeatedly reconnecting/restarting. UART0/USB remain independent of these pools; HTTPS keeps its separate policy.
### Callback and library contract
`src/ssh_transport.c` requires wolfSSH 1.4.20, certificates disabled and `none` authentication disabled at compile time. The reviewed parser calls ordinary-key authorization before signature verification; rejected authorizations and unsigned probes have no result callback. Password results are completed within the password callback. An explicit pending-result marker fences signed-key completion; duplicate/unexpected/closing-session results cannot promote a principal or count another completed attempt. Principal currentness is still checked at successful signature completion and route admission.
Advertising only password/publickey is not a dispatch filter in this wolfSSH version. An explicit rejecting keyboard-interactive prompt callback and per-slot context prevent its unregistered-callback path; it creates/sends no prompts and closes the connection. The advertised methods remain password/publickey. This does not certify every malformed-packet path in the library.
`tests/wolfssh_auth_contract/run.py` checks the reviewed `internal.c` SHA-256 and version, preprocesses the actual build's feature profile, and executes extracted vendor parser/send functions with narrow crypto/IO doubles. A same-version source change requires re-audit, not blindly replacing the hash. It does not replace real-client/cryptographic integration testing. The positive `SendChannelData()` return contract means the caller's accepted prefix has been copied, including its consumed-data WANT_WRITE case; it is not peer acknowledgement.
### Counters and secret lifetime
`ssh counters` adds aggregate-only diagnostics:
- `handshakes` / `handshake-throttled`: admitted handshake work / rate-denied connections, separate from capacity failures.
- `verifications` / `verification-throttled`: admitted password/signed-key requests / rate-denied requests. Admission does not imply the verifier ran or completed.
- `probes` / `probe-throttled`: admitted/denied unsigned-key lookups, not completed credential attempts.
- `attempt-limit-closes`, `backend-errors`, `method-rejects`: three-attempt closures, database auth/authorization/currentness errors, and rejected callback-level methods (including keyboard). These are not counts of every malformed SSH packet.
Existing `auth-attempts`/`auth-failures` remain completed counted outcomes; rejected password changes count, unsigned probes and rate-denied requests do not. Signed-key results finalize once after authorized work. These admission/auth counters saturate at `UINT64_MAX`, contain no submitted credentials/identities, and may be cleared independently of enforcement state.
The transport now wipes consumed admin RX bytes, positively accepted admin TX bytes, and the full retired slot while retaining its generation. Partial/retry paths preserve pending bytes. Serial-route hot-path behavior is unchanged. This shortens application plaintext lifetime; it is not a claim that wolfSSH/wolfSSL/mbedTLS, stack or PSRAM copies are all erased.
Hidden UART0 and shared remote-console prompts now reject overflow or unsupported bytes on submission with a wiped output buffer and `ESP_ERR_INVALID_SIZE`, rather than accepting a truncated/normalized prefix. The failure remains sticky after Backspace/Delete. Printable ASCII, CR/LF submission, Backspace/Delete and Ctrl-C retain their defined roles; visible command-line editing is unchanged. Existing callers prevent a rejected password or confirmation from reaching persistence. For pasted passwords, exceeding 64 characters or including unsupported bytes requires a fresh attempt; the password policy itself is unchanged.
## 9C library cleanup and protocol policy
[Library review and maintenance contract](security_library_review.md) records the scoped audit, corrected paths, existing cleanup and limits. This is not exhaustive library certification or a dependency security-release review.
### Reproducible source corrections
`tools/security_overrides.py` verifies full original-file SHA-256 values and ESP-IDF 5.5.3, applies exact-once edits, and generates nine corrected C sources plus one header under the build directory (the original four 9C sources, three IDF advisory sources, the additional wolfSSH `ssh.c`/`internal.h` ordering inputs, and the IDF 5.5.3 WS signed-receive correction). `cmake/security_overrides.cmake`, included after `project()`, replaces exactly the corresponding sources in existing IDF/component targets, retaining compilation properties. Installed SDK/managed sources and their notices remain unchanged. Missing, changed or ambiguous sources fail configuration; there is no unpatched fallback. Do not edit derived files or repin a hash merely to make an upgrade build.
- **HTTPS:** delete TLS on post-handshake transport-allocation failure; fully destroy retained TLS configuration on failed HTTPD start; wipe the copied raw private key before free. Failed stop still retains live ownership.
- **HTTPD parser:** allocate/copy/wipe/free scratch on resize, preserve the old pointer on allocation failure, wipe final scratch, and handle the null initial parser pointer without undefined subtraction. Pending/unread bytes retain their existing behavior.
- **wolfSSH password parser:** bound both password lengths against the actual packet before application callbacks, reject malformed change-password fields without calling authentication, and wipe the bounded method-specific payload suffix before failure responses. Username/service/method prefixes remain intact. The current project callbacks are synchronous; library `WS_AUTH_PENDING` retains the payload for retry and is not claimed wiped.
- **ESP-TLS server configuration:** enforce the static-lifetime TLS list below before handshake setup; client defaults and global cryptographic primitives remain unchanged. IDF dynamic TLS buffers are rejected because their cleanup bypasses the reviewed upstream record-buffer wipe.
The new `src/ssh_memory.{c,h}` wolfSSL/wolfCrypt allocation hooks wipe the full owned usable allocation before release, including library import-failure and dynamic packet-buffer copies. They require the reviewed unpoisoned IDF 5.5.3 heap configuration; poisoning modes fail compilation rather than risking canary writes. No allocation header is added. Shrink retains capacity and wipes the tail; growth allocates/copies before wiping/freeing the old block, preserving it on allocation failure. PSRAM preference/internal fallback is unchanged. **Growth and HTTPD scratch resizing temporarily need both blocks; lower linked size is not evidence of safe runtime headroom.** Live inline buffers, in-place compaction tails, stack spills and every crypto intermediate are not comprehensively covered.
### Explicit network protocol policy
| Setting | Allowed values, in preference order |
|---|---|
| HTTPS version | TLS 1.2 only; server renegotiation disabled |
| HTTPS suites | `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` |
| SSH KEX | `curve25519-sha256`, `ecdh-sha2-nistp256` |
| SSH host key | `ecdsa-sha2-nistp256` |
| SSH ciphers, both directions | `aes128-gcm@openssh.com`, `aes256-gcm@openssh.com` |
| SSH MAC advertisement | `hmac-sha2-256` (GCM supplies packet authentication) |
| SSH user-key policy | `ssh-ed25519`, `ecdsa-sha2-nistp256`; database authorization remains authoritative; no EXT_INFO/`server-sig-algs` advertisement |
`src/ssh_protocol_policy.c` uses permanent strings and checks every setter; any failure destroys the unpublished context without fallback. Tests verify the actual compiler's available algorithms and generated KEXINIT lists, not merely setter success. The server-only TLS correction avoids breaking future outbound HTTPS clients by globally removing RSA-certificate suites.
**Compatibility:** TLS CBC/CCM/ARIA-only and SSH CBC/CTR-only clients no longer connect; removed KEX-only clients also fail. Bounded OpenSSH host interoperability is recorded below; intended-client compatibility without EXT_INFO and rekey/cleanup on hardware remain target gates. RSA-SHA2 discovery is not claimed. Existing TLS/SSH identity and user-key storage need no rotation or migration. Password/KDF, certificate validity/trust and browser-header policy were reviewed and retained with documented limits; no blind KDF-cost increase or HSTS policy was introduced.
### Web admission and shorter plaintext lifetimes
A non-consuming quota/epoch check now runs after valid challenge consumption but before body receive. An already-exhausted verification budget returns 429/`Retry-After` without receiving/parsing credentials or calling the verifier; unread bodies still cause connection closure, not draining. The authoritative reservation remains after parsing. Raw JSON is wiped before verification, parsed credentials afterward, and both before error-response sending. Header strings remain live through synchronous serialization.
The existing global five-verifications/60-second fixed window is unchanged: malformed requests do not charge it, counter clear does not replenish it, and web service restart does. This differs deliberately from SSH's boot-lifetime buckets. The first boot-minute window remains anchored at uptime zero. Challenge monopolization, global-budget starvation and malformed-body work while budget is available are not solved by this early check.
## 9D maintenance and lifecycle — in progress
- [Security operations](security_operations.md) supplies source-checked provisioning, explicit-save, account/key/identity rotation, recovery, reconstruction and approved erase/decommissioning procedures. There is no implemented configuration backup/export or private-identity restore workflow. Commands and checklists are not device execution evidence; the user will validate Phase 9 as a whole.
- [wolfSSL/wolfSSH review and implementation addendum](wolf_security_review.md): the **CVE-2025-12888** Xtensa mitigation now selects `CURVE25519_SMALL` and `ED25519_SMALL` consistently for wolfSSL and consumers. The PUBLIC forced-include resolved-settings guard rejects missing small implementations, X25519 blinding (incompatible with small in this pinned version), and unreviewed Curve448/Ed448 enablement. The existing generated wolfSSH override now bounds IGNORE/service strings, rejects zero-capacity string output and channel-window overflow, corrects ECC/Ed25519 key/signature labels, and enforces exact signature framing (ECC nested r/s bounds plus inner/outer consumption; Ed25519 outer consumption). These are PR892/881/880 subsets plus local framing corrections, not full backports; password wiping/async retention remain unchanged. PUBLIC `WOLFSSL_VALIDATE_ECC_IMPORT` and `WOLFSSL_ECDHX_SHARED_NOT_ZERO` now enable P-256 import validation and X25519 all-zero-result rejection, with effective production flags confirmed and fail-closed backend guards. See [key-validation evidence](ssh_key_validation_review.md) and [parser scope/limits](../tests/wolfssh_parser_contract/README.md). The restricted existing-profile correction for **CVE-2025-14942** is implemented as described below. The [finite remaining SSH review](ssh_parser_remaining_review.md) is complete: bounded exact CHANNEL_FAILURE recipient parsing (fatal policy retained), exact `ssh-userauth` service validation, and exact length/byte dispatch for all nine channel-request names are implemented. Unknown-request/trailing-payload behavior is preserved. PR899 client key skips are unchanged and blocked by current server role/ordering; PR918/919 forwarding is disabled. The inspected generic signature caller trace found no attacker-selected short-digest/OID path; generic APIs remain unpatched. These are profile-specific dispositions, not exhaustive parser/library safety; revisit on caller, feature, KEX or source changes. No exploit or whole-library clearance is demonstrated; added validation CPU/allocation cost and target interoperability remain unmeasured.
- [Focused IDF review and implementation addendum](idf_security_review.md): pinned backports now implement DHCP option bounds (**CVE-2026-45160**), TLS 1.2 EMS failure return (**CVE-2026-50581**) and X.509 OID allocation-failure handling (**CVE-2026-34874**). Explicit nested-target validation places the mbedTLS edits on `mbedtls`/`mbedx509`, retaining source properties and exactly-one-source checks. WS negotiation **CVE-2026-45541** and ASN.1 named-data **CVE-2025-48965** remain unpatched with the review's qualified applicability, not blanket closure. The [finite IDF applicability completion](idf_security_review.md#finite-applicability-completion--2026-09-16) dispositions all six named findings: ECDH small-output, zero-length ECC PK parse, basicConstraints, server NewSessionTicket and stale ASN.1 length are not current paths/configurations for their documented reasons; optimized ECC reduction is active but its privileged-local/physical side-channel attacker model is excluded. No new current-path correction was established. That earlier review screened only the first advisory-index page. The subsequent [finite dependency coverage](dependency_advisory_coverage.md) accounts for all **22 IDF entries across three pages**, plus named managed-component and browser publication channels. The declared dated search is complete, not exhaustive advisory clearance; unpatched primitives, inaccessible full-release databases and fresh findings remain.
- [Dependency license inventory](dependency_licenses.md) is a bounded engineering inventory, not legal or distribution clearance. All **nine generated C sources plus one header** carry prominent modification notices: the baseline **2026-09-15** notice plus **2026-09-16** ordering/provenance notices on wolfSSH outputs, with upstream notices retained, including both mbedTLS dual-license headers. That narrow finding is resolved. Radio-blob corresponding-source/exception questions, actual firmware/device/browser notice delivery, preferred-source packaging, wolfSSH package-license discrepancy and manual bitmap derivation, the distinct mockup Wi-Fi path and recipient license delivery remain open; [exact retained SVG provenance](icon_provenance.md) is resolved. Notice assembly does not prove recipient delivery. [Offline notice assembly](release_packaging.md) is implemented by [tools/release_notices.py](../tools/release_notices.py): 75 mandatory hash/size-pinned inputs (nine IDF/toolchain notice entries semantically rebased for the candidate; the other 66 unchanged), deterministic bounded outputs, fail-closed preflight and no overwrite/fetch/build/device access. Supplied agent evidence: **36 notice fixture tests PASS; two actual bundles verified deterministic, each 77 files / 4,433,930 bytes**. This includes retained SVGs and [exact icon provenance](icon_provenance.md), not corresponding-source delivery or legal clearance. These are agent measurements, not a parent rebuild or reassembly in this documentation turn.
- **Restricted ordering correction implemented, not a full upstream backport or sign-off.** The [ordering review](wolf_security_review.md#restricted-ordering-correction-and-remaining-gates) and [provenance/prerequisite disposition](../tools/wolfssh_order/README.md) document the audited PR793/819/840/855/921 subsets plus local gates. Existing X25519/P-256 KEX only; independent SELF/PEER state, exact expected replies and authentication-phase checks cover both roles. Queued NEWKEYS survives WANT_WRITE without duplication. **EXT_INFO is deliberately disabled; no `server-sig-algs` is sent**, and `extInfoSent` stays zero. CMake applies the generated ABI header BEFORE PUBLIC and via a PUBLIC forced include; joined `-include/path` flags fix PlatformIO sorting/deduplication for ordering and crypto guards. Review's misplaced EOF guard is corrected before channel mutation; verification found no scoped blocker. Target cleanup during rekey and no-EXT_INFO client compatibility remain pending.
- No dependency versions were upgraded. Beyond the implemented backports above, proposed upgrades/backports remain candidates, not approved compatible versions. Re-audit coherent source/header changes, effective compile policy, exact-hash overrides and callback/parser contracts, then obtain host/build and whole-phase target evidence. 9A9C passes below are historical scoped evidence, not closure of these newly recorded findings.
Secure boot and encrypted NVS remain excluded. No runbook, advisory report or license inventory establishes production readiness or authorizes a destructive device operation.
## Operational profiles
These are handling and validation profiles of the **same supported build baseline**, not separate PlatformIO environments or selectable security overrides.
| Profile | Operational rules |
|---|---|
| Development | Keep the guard enabled; use synthetic credentials and controlled serial payloads for fault investigation. Keep UART0 recovery available. Review captures before sharing. |
| Test | Use an isolated, expendable target and synthetic secrets; record exact source/configuration, host/build results and device observations. Exercise crashes and recovery without exporting raw memory. |
| Production | Use the same guard, restrict physical/network access, verify device identity through trusted UART0, and apply reviewed provisioning/rotation/recovery procedures. Readiness remains pending Phase 9 review and target evidence. |
If richer crash debugging is essential, use an isolated synthetic-secret build outside this supported baseline. It requires explicit reviewed changes to the source policy and applicable configuration; no bypass flag is provided. Do not use real credentials or deploy that build as production firmware. Restore and revalidate the supported policy before release.
Raw flash, RAM and dumps can contain Wi-Fi passwords, private keys, password verifiers, session material and serial payloads. Treat them as secret-bearing and **do not export them as routine diagnostics**. Prefer bounded status/counter observations and reviewed synthetic-secret reproductions. Restrict any exceptional artifacts and define retention/deletion before collecting them; deletion is not a secure-erase guarantee.
## Validation gates
### Ordering host/build evidence — 2026-09-16
Supplied parent `pio run` **PASS**: **94,340 B linked RAM / 1,768,901 B flash**, unchanged RAM / **+200 B flash** versus 1,768,701 B. **Supplied final parent results: all seven suites PASS** — ordering `--interop` (8,028 checks, seven rejected mutations, 12 sessions with exact 256 KiB echo each and clean channel close plus transport EOF), SDK overrides `--build-dir .pio/build/esp32-s3-devkitc-1-n16r8`, auth (135 cases), protocol, strict crypto, notices (30), and parser (3,258 cases in each of two stack modes plus channel profiles; 11 + 18 + 2 rejected mutations). Interop required unsandboxed approval solely for local AF_UNIX sockets; no remote network or device operation occurred. This documentation update did not rerun firmware or host suites.
Supplied agent ordering tests passed **8,028 checks and seven rejected mutations**, including the corrected EOF guard and real shutdown/exit-status rekey fences. The installed PlatformIO/SCons adapter regression validates joined forced-header flags with a real Xtensa consumer and rejects a split-option mutation. The [test README and code](../tests/wolfssh_order_contract/README.md) describe full generated translation units, real wolfCrypt, message-ID matrices, fragmented writes and both roles/rekey directions.
Initial host interoperability failed a harness close race: early `INTEROP PASS` preceded OpenSSH `Broken pipe` and was not a pass. The harness now waits for peer channel close and transport EOF, passes a local socket descriptor to OpenSSH, independently owns/reaps the server, and checks both process exits. Final agent `python3 tests/wolfssh_order_contract/run.py --interop --interop-repeat 3` evidence: **36/36 sessions**, each exact **256 KiB** binary echo, **ten** key exchanges in client-rekey cases or **two** in fragmented server-rekey cases, clean exits and no EXT_INFO. Coverage uses OpenSSH 10.2p1, both KEX algorithms, Ed25519/P-256/password authentication and AES128-GCM. It is not general library shutdown, arbitrary-client or target evidence. Whole-phase gates remain pending.
The [source-authoritative parser report](ssh_parser_remaining_review.md#validation-and-remaining-handoff) and [test contract](../tests/wolfssh_parser_contract/README.md) split the channel matrix from the 3,258 base cases: **2,737 per stack mode** for TERM-only, TERM+SHELL and TERM+SHELL+AGENT; **2,735 per stack mode** for no-terminal and SHELL-only. All five profiles run both modes; alternate features are host fixtures, not firmware enablement. Mutations are **11 base + 18 name/length + 2 real application admission gates**. Parent ordering adds **12 OpenSSH sessions**, each exact **256 KiB**, rekey and clean client/server exit; SDK tests checked actual build registration. These integrated parent results supersede the parser report's earlier stale-build handoff, without changing its historical execution record. Independent review reported no actionable defects within the scoped parser/bundle review, not a Phase 9 approval.
### Mitigation host/build evidence — 2026-09-15
Supplied parent results (not rerun for this documentation update): `pio run` **PASS**, **94,340 B linked RAM / 1,768,949 B flash**. RAM is unchanged and flash is **1,732 B larger** than the preceding 1,767,217 B mitigation build. Linked size is not runtime headroom or timing evidence.
All five parent commands passed (crypto policy in strict mode, without candidate injection):
```sh
CCACHE_DISABLE=1 python3 tests/sdk_security_overrides/run.py --build-dir .pio/build/esp32-s3-devkitc-1-n16r8
CCACHE_DISABLE=1 python3 tests/wolf_crypto_policy/run.py
CCACHE_DISABLE=1 python3 tests/wolfssh_parser_contract/run.py
CCACHE_DISABLE=1 python3 tests/wolfssh_auth_contract/run.py
CCACHE_DISABLE=1 python3 tests/ssh_protocol_policy/run.py
```
Independent review found no blocker in the scoped changes. The parser suite passed **3,124 cases per stack mode (two modes)** with guard pages/UBSan trap instrumentation and **six rejected guard-removal mutations**; its crypto doubles establish parser gating, not signature arithmetic. The auth suite passed **135 cases**. Strict crypto tests run real vendor arithmetic/ASN vectors, independently compare seven audited source bodies with exact parser deltas, and check twelve production translation units plus negative policy cases. Effective ECC/X25519 flags were confirmed. SDK override validation includes actual seven-source build registration. This is scoped implementation/host/build evidence, not ordering closure, exhaustive parser/crypto review, license clearance or whole-phase acceptance. No target evidence, upgrade, asset regeneration or device operation is claimed.
### Host and build — historical passes 2026-09-15 (9A9C)
From the repository root:
```sh
python3 tests/security_build_policy/run.py
python3 tests/ssh_auth_policy/run.py
python3 tests/ssh_auth_transport/run.py
python3 tests/hidden_input/run.py
pio run
python3 tests/security_build_policy/run.py --sdkconfig-header .pio/build/esp32-s3-devkitc-1-n16r8/config/sdkconfig.h
python3 tests/wolfssh_auth_contract/run.py
python3 tests/sdk_security_overrides/run.py --build-dir .pio/build/esp32-s3-devkitc-1-n16r8
python3 tests/ssh_memory/run.py
python3 tests/ssh_protocol_policy/run.py
python3 tests/web_cookie_auth/run.py --admission
```
Historical final 9C `pio run` passed with **94,340 B linked RAM / 1,831,309 B flash**, unchanged linked RAM / +1,384 B flash against 9B. This is linked size, not measured runtime headroom. Five focused suites passed after final HTTPD first-read correction: pinned SDK cleanup/TLS/source registration, 135 generated wolfSSH parser/control-flow cases, secure allocator, SSH policy (including 15 actual context-integration cases), and web early admission/wiping. The allocator's optional installed-SDK extent contract was also run with the installed IDF path and passed; plain invocation reports that optional check skipped. Seventeen integrated regression commands passed before the final first-read addition, including SSH auth/management, HTTPD idle, HTTPS lifecycle, five cookie-auth modes and the 18-case crash-policy matrix. All ten existing cookie-auth domain modes also passed during implementation. Independent reviews found no blocking issues; the identified inherited first-read pointer issue was corrected and tested. Use `CCACHE_DISABLE=1` on host commands if the compiler wrapper's cache is read-only in a sandbox. No upload, erase, eFuse operation or target test was performed.
Record the revision, compiler/build outcome and effective configuration. Confirm that the matrix accepts the supported configuration, rejects each prohibited option independently, and rejects absent/disabled required settings. Confirm the normal firmware build compiles the guard. A rejected unsafe configuration is an expected negative-test result, not a firmware build pass. Neither these commands nor a successful build proves target panic behavior.
### Combined Phase 9 target validation — deferred, not run
Retain these checks for the user's final whole-phase test session; do not stop implementation for separate slice sign-off. Include the [9D operational rehearsal](security_operations.md#deferred-whole-phase-9-hardware-rehearsal) and targeted message-order/parser/key-validation/interoperability checks for the implemented restricted mitigations and any subsequent reviewed changes. None is recorded as passed here.
#### Crash and recovery
1. On an isolated synthetic-secret target, record the tested image/configuration and capture UART0 at 115200 baud. Verify normal boot, UART0 administration, native USB UART1 access, HTTPS and SSH before fault testing.
2. Through separately reviewed test-only fault injection, trigger a controlled panic with the supported build policy intact. Verify reboot rather than halt/debugger wait, no panic register/backtrace output and no UART core dump. Record any remaining boot/reset information; do not promise complete UART silence.
3. Verify no new flash core dump is written using a reviewed target-side pass/fail check that does not export partition contents. Distinguish old partition contents from a new write; do not erase the partition merely to claim this test passed.
4. After reboot, verify UART0 recovery and USB serial access, then authenticated HTTPS/SSH and broker writer/observer behavior. With network services unavailable, verify UART0 and native USB still work. Review routine status/log output using synthetic secrets; this is bounded evidence, not universal redaction proof.
5. Record outcomes and limitations in the combined Phase 9 acceptance. Device flashing/fault injection requires a separately authorized hardware session; no eFuse changes, partition migration or erase is required by this policy.
#### Authentication, input and loaded isolation
1. On a restricted test network using synthetic credentials, exercise password and Ed25519/P-256 key login for both roles, including a client offering multiple keys. Verify unsigned probes, wrong passwords/signatures, stale-principal rejection and normal shell admission. Explicit keyboard-interactive requests must close/reject without a crash or prompt.
2. Exhaust each admission class separately, respecting the independent budgets. For verification testing reuse admitted connections (up to the existing three-failure limit) so handshake exhaustion does not mask the verification gate. Verify counter deltas, reconnect resistance, natural refill and that successful logins also consume capacity. Unsigned probes must not increase completed `auth-attempts`.
3. From UART0, clear counters and stop/start SSH while exhausted; observe that neither grants fresh tokens. Account for time elapsed during these operations. Do not assume that a reconnect failure indicates bad credentials. A quiet 60-second period replenishes all pools; ongoing hostile traffic can keep them depleted.
4. Keep an established SSH serial stream and USB/browser clients active while generating bounded invalid-login/reconnect traffic. Record serial/broker drops, UART0 command latency, SSH stream responsiveness, internal/DMA minima and recovery. Do not use this admission policy to claim zero CPU impact; TCP/kernel work, KDF/signature work within budget and two-slot occupancy still matter.
5. Test hidden credentials at maximum length and one byte over, different suffixes past the limit, unsupported input bytes, overflow followed by editing, Ctrl-C, disconnect and confirmation failure on UART0 and remote administration. No rejected prefix may be persisted or echoed. Check both CR/LF behavior, including delayed UART0 LF delivery: the current UART0 reader relies on next-prompt input flushing, unlike the remote reader's explicit paired-LF handling; host fakes do not prove device timing.
6. Exercise generated-password delivery with slow/partial remote output and short subsequent commands, then disconnect/reconnect. Application-buffer wipe assertions are host evidence; do not export live RAM to establish a device pass.
#### Protocol compatibility and allocation-failure recovery
1. Verify both allowed TLS suites and both SSH GCM ciphers using compatible clients; force excluded CBC/CTR/other-only offers and confirm rejection. Exercise both SSH KEX choices and both user-key types, initial handshake and rekey, plus TLS renegotiation rejection. Verify intended clients work without EXT_INFO/`server-sig-algs`; do not assume RSA-SHA2 discovery. Exercise disconnect/cleanup during rekey and subsequent session recovery under load. Retain UART0 access; do not rotate identities to work around an algorithm mismatch.
2. With synthetic credentials, test truncated/oversized SSH password and change-password packets: no authentication callback for malformed fields, no crash, bounded disconnect/recovery. Include malformed IGNORE/service strings, window overflow, ECC/Ed25519 labels and nested/trailing signature bytes, invalid P-256 points and low-order X25519 inputs. Measure added import-validation latency/allocation/stack cost, host-key loading and handshake deadlines under repeated KEX/rekey and combined load. Host canary/vector assertions are not real encrypted-packet coverage.
3. Exercise HTTPS failed-start, post-handshake allocation failure, normal/failed-stop retry and split-header scratch allocation failure on a separately reviewed fault-injection image. Observe recovery/no accumulating allocation loss without exporting keys or RAM. Failed stop must not prematurely free live TLS state.
4. Repeatedly start/stop HTTPS and SSH and stress header parsing/authentication under the full transport mix. Capture internal/DMA/PSRAM free/minimum/largest-block and stack margins alongside serial/broker loss counters. Specifically measure old-plus-new allocation peaks and secure-free CPU cost; previous very low internal minima remain important.
5. Verify exhausted web login returns early without stalled-body work, clears the used pre-login challenge, and recovers after the documented window. Check malformed requests below quota and correct credentials for normal behavior; do not infer fairness from a rate-limit pass.
**Bounded host validation:** 23 commands by default; build, OpenSSH interop and web performance are explicit options. Historical default 23/23 and 10 orchestrator fixtures passed on the earlier snapshot. Current supplied parent validation selects the isolated IDF 5.5.3 build/core/SDK, with `--interop --web-performance`: **PASS 24/24**. See [exact command, source equality and evidence limits](phase9_validation.md#current-candidate-execution--2026-09-18). This does not claim a successful default root build or whole-phase acceptance.
## Staged next work
- **Implementation/maintenance gate:** the finite SSH and six-finding IDF reviews are complete for their stated profiles; do not re-list them as unimplemented. The [declared finite advisory search](dependency_advisory_coverage.md) is complete. The fix-bearing vendor bundle is integrated in the validated IDF 5.5.3 candidate; complete the [remaining Wi-Fi target gates](wifi_security_update_plan.md), retaining PMF/WPA3 and exact override guards. Integration is not radio-hardware closure. Residual direct-SDK AES-DMA applicability and publication-channel gaps remain; recheck the bounded snapshot before release. Optional ASN.1/ECDH/basicConstraints defense-in-depth backports are not implemented or required by a demonstrated current-path finding.
- **Release gate:** notice assembly is implemented; validate actual firmware/device/browser delivery, corresponding source and preferred asset sources, radio-blob legal basis, wolfSSH packaging clarification, remaining manual bitmap/mockup provenance, final runtime/bootloader attribution and any Installation Information. See [packaging gates](release_packaging.md#separate-work-before-distribution).
- **Target/acceptance gate:** rehearse operations and the combined target checklist above, including panic/recovery, abuse/isolation, cleanup during rekey, intended-client compatibility without EXT_INFO, loaded KEX/rekey and heap/stack/CPU timing. Obtain explicit whole-phase acceptance; no scoped reviewer or host PASS can substitute.
- **Continue 9D maintenance and lifecycle.** Execute the [remaining ordering gates and advisory work](wolf_security_review.md#restricted-ordering-correction-and-remaining-gates), target-validate the integrated coherent Wi-Fi correction identified by the completed finite dependency search, and revisit its explicit residual questions, and address the [release source/notice work](dependency_licenses.md#actionable-release-work-not-performed). Runbooks are documented, not rehearsed; remaining mitigations/reviews, distribution clearance and whole-phase acceptance remain outstanding.
- **Retained evidence limits:** 9C completes a bounded cleanup/protocol review, not every-library-copy zeroization. Live inline residue, compaction tails, hardware/stack intermediates, global admission starvation and resource/interop measurements remain documented limitations or combined target gates. Any additional hardening must preserve owner lifetimes and bounded recovery.
- **Phase 10: OTA trust.** Define independent image-signature verification, trust-anchor provisioning, rotation/revocation, rollback/downgrade and recovery policy without secure boot. Authenticated transport alone is not image-signing policy, and OTA signature checks cannot prevent physical firmware replacement.
See the [roadmap](roadmap.md#phase-9--security-and-production-hardening), [electrical procedures](electrical_tests.md) and [administration regressions](user_administration_tests.md) for wider gates. Production readiness remains pending; Phase 8 acceptance is not reopened by these follow-ups.
+143
View File
@@ -0,0 +1,143 @@
# Security library review — Phase 9C
## Scope and status
Bounded implementation/source audit, verified 2026-09-15; not library security certification.
Baseline: **ESP-IDF 5.5.0, mbedTLS 3.6.3, wolfSSH 1.4.20, wolfSSL 5.8.2~1**
(upstream wolfSSL version macro: 5.8.2). Original dependencies are not upgraded or hand-patched.
Versions were checked against installed headers and `src/idf_component.yml`; override hashes
were checked against installed originals. Source is authoritative over older integration notes.
The reported Phase 9C reviews have no remaining blocking finding; the HTTPD null-initial
read finding is fixed and covered by the passing host suite below.
Whole-Phase-9 target validation is deferred at the user's request; see [main policy](security_hardening.md).
The [main policy](security_hardening.md#validation-gates) records final firmware build/size evidence separately from this source review.
## Confirmed gaps fixed
| Boundary / source | Implemented correction |
|---|---|
| SDK `esp_https_server/src/https_server.c` | Delete TLS when post-handshake transport allocation fails; destroy the complete secure context on HTTPD start failure. Restore the original open callback and clear stale context/destructor pointers. Wipe `serverkey_bytes` before freeing the raw key copy. Failed stop retains live ownership. |
| SDK `esp_http_server/src/httpd_parse.c` | Replace scratch realloc with allocate/copy/wipe/free; preserve old pointer/content on allocation failure and wipe current scratch at final cleanup. Preserve pending/unread bytes. Initial reads avoid NULL subtraction and retain a NULL parser position until set; existing positions relocate correctly. |
| SDK `esp-tls/esp_tls_mbedtls.c` | Apply the server-local TLS profile below after defaults and before setup; static suite storage, TLS 1.2 minimum/maximum, no renegotiation. Client defaults/caller suites and global crypto features are unchanged. |
| wolfSSH `src/internal.c` | Use `GetSize()` bounds for password/new-password fields, reject invalid context/index, and guard authentication dispatch after new-password parse failure. Wipe the checked packet suffix before failure output, preserving the username/service/method prefix needed by the caller. Skip wiping on `WS_AUTH_PENDING` for retry; the project does not return pending. |
| `src/ssh_memory.c`, `src/ssh_transport.c` | Register secure wolfSSL/wolfSSH allocation hooks before library allocation; wipe retired heap extents and explicit shrink tails, including allocator rounding. |
| `src/ssh_protocol_policy.c`, `src/ssh_transport.c` | Apply all five explicit lists; any setter failure frees the unpublished candidate and returns failure, without default-policy fallback. |
| `src/web_cookie_auth.c` | Check exhausted verification budget before body receive/parse, reserve authoritatively after parsing, and shorten JSON/credential lifetime before backend/error output. |
The three SDK overrides and wolfSSH override are registered in `tools/security_overrides.py`.
Root `CMakeLists.txt` includes `cmake/security_overrides.cmake` **after `project()`**;
`src/CMakeLists.txt` includes both new SSH modules. No embedded web assets were regenerated.
## Heap and packet lifetime contract
`ssh_memory` compile-guards **unpoisoned IDF 5.5.0**: `heap_caps_get_allocated_size()`
must return the owned usable extent of a base allocation, not an interior-pointer extent.
Allocation remains PSRAM-first with internal fallback; no allocation headers, metadata tables,
extra locks or tasks are introduced. Free securely wipes the complete extent before release.
Shrink retains the pointer/capacity and wipes the discarded tail; it does not reclaim heap.
Growth allocates a replacement, copies the old usable extent, then wipes/frees the old allocation.
Failed growth leaves the old allocation and contents unchanged. Growth temporarily needs **old + new**
storage, including possible internal fallback. HTTPD resize similarly needs both bounded allocations,
but retains its ordinary shrink/grow behavior rather than a permanent maximum-sized scratch buffer.
These fixes cover specific retired copies, not every secret throughout its lifetime:
- Static and still-live library buffers can retain bytes; heap hooks do not intercept in-place compaction.
- Packet-suffix wiping is deliberately prefix-preserving and is not an asynchronous-auth wipe guarantee.
- Backend-specific spills, stack/register copies, crypto intermediates and accelerator state were not exhaustively audited.
- Browser memory, flash history and all allocator regions are not proven clean; do not export raw memory dumps as evidence.
## Existing cleanup verified, not presumed broken
Inspection of the installed original sources found existing wipes on the checked normal paths:
- wolfSSL `wolfcrypt/src/ecc.c:wc_ecc_free()` calls `mp_forcezero()` for the private scalar;
`integer.c` wipes used digits before release, while `tfm.c` delegates to `fp_forcezero()`.
- mbedTLS `library/pk_wrap.c:eckey_free_wrap()` delegates to `ecp.c:mbedtls_ecp_keypair_free()`;
the private MPI reaches `bignum.c:mbedtls_mpi_free()` and its zeroize-and-free path.
- mbedTLS `library/md.c:mbedtls_md_free()` zeroizes/frees HMAC pads and wipes the context.
- mbedTLS `library/ssl_tls.c:mbedtls_ssl_free()` zeroizes/frees input/output record buffers;
its inspected buffer-resize path also zeroizes retired storage.
Thus ordinary destructors are **not generally broken across both stacks**. The confirmed gaps above
are separate raw-copy, ownership, resize and packet-lifetime issues. IDF dynamic TLS buffers are
compile-rejected because their destruction bypasses the inspected upstream record-buffer path;
other configurations/backends need their own review, not extrapolation from these observations.
## Current protocol allowlists and compatibility
| Layer / setting | Exact current policy |
|---|---|
| HTTPS versions | TLS 1.2 only; renegotiation disabled or compiled out |
| HTTPS suites | `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384` |
| SSH `Kex` | `curve25519-sha256,ecdh-sha2-nistp256` |
| SSH `Key` (host identity) | `ecdsa-sha2-nistp256` |
| SSH `Cipher` (both directions) | `aes128-gcm@openssh.com,aes256-gcm@openssh.com` |
| SSH `Mac` (both advertised directions) | `hmac-sha2-256`; GCM provides the negotiated AEAD integrity |
| SSH `KeyAccepted` | `ssh-ed25519,ecdsa-sha2-nistp256` (`server-sig-algs` advertisement only) |
| SSH compression | `none` |
| SSH authentication | Password or enrolled Ed25519/ECDSA-P256 public key; keyboard-interactive rejected |
SSH list strings have static lifetime because contexts/sessions borrow their pointers. List setters
alone do not validate compiled support; the source/production-feature tests check names, IDs and
serialized initial/rekey lists. Enrollment/authorization remains in the user database, not `KeyAccepted`.
Legacy CBC/CTR-only SSH clients, excluded KEX/host-key clients, and CBC-only TLS clients cannot connect;
TLS clients need TLS 1.2 plus one listed ECDHE-ECDSA GCM suite (TLS-1.3-only also fails).
There is no automatic compatibility fallback. Modern-client compatibility is still a live-test gate,
not a claim that signature verification, real KEX/rekey or TLS/SSH handshakes were exercised here.
## Web admission and retained credential/browser policy
The early quota probe neither consumes attempts nor advances the window. The final post-parse
reservation preserves **five password verifications per 60 seconds globally**; malformed requests
are not charged. Exhausted requests avoid body receive/parser/KDF and close without draining unread
bodies. Challenges remain consumable before this probe: this does **not** establish challenge fairness
or prevent global starvation. HTTPS service stop/start resets this window/challenges, unlike SSH's
boot-lifetime admission buckets. Epoch/readiness checks fence stale work at both quota boundaries.
Raw JSON is wiped after parsing and before KDF; parsed credentials immediately after authentication;
denial paths wipe both before error responses. Ordinary final request/token cleanup remains in place.
`src/user_database.{c,h}` remains unchanged: **1264 printable ASCII bytes** (`0x20``0x7e`),
PBKDF2-HMAC-SHA256 with **50,000 iterations**, **16-byte random salt**, **32-byte verifier**.
Generated passwords select **24 symbols from 64**, giving **144 bits** with uniform secure randomness.
This is a reviewed retained baseline, not a claim that 50,000 iterations meets every current deployment
recommendation. Benchmark target verification latency and mixed-load headroom before choosing a new
cost; do not blindly increase it. No verifier storage format or key-rotation behavior changes here.
`src/web_security.c` generates a self-signed **P-256 / ECDSA-SHA256** certificate, non-CA,
digital-signature usage, server-auth EKU, device DNS and fixed AP IPv4 SANs, with fixed validity
**2025-01-01 through 2049-12-31**. Existing validation checks the key pair, expected fields/SANs and
self-signature; this inspection is not a new real-crypto signature-verification test.
Compare the certificate SHA-256 fingerprint through trusted UART0 (`web certificate info`) before
accepting browser trust; a warning bypass is not verification, nor is arbitrary STA-IP trust solved.
Existing persistence/rotation/recovery contracts remain unchanged; NVS is not newly encrypted.
`src/web_login_ui.c`, `src/web_ui.c` and `src/web_cookie_auth.c` retain CSP, document/auth
`Cache-Control: no-store`, and `Secure; HttpOnly; SameSite=Strict` cookies. Static assets retain their
separate caching policy. HSTS is deliberately not blindly forced for the self-signed hostname/IP
workflow: it is not a substitute for verified certificate trust and may obstruct recovery.
## Maintenance and evidence
1. Keep the original SDK/managed sources untouched. Maintain reviewed `Entry` hashes and exact-once
edits in `tools/security_overrides.py`; never repin a hash merely to make configuration succeed.
2. Re-audit changed source ownership, cleanup, allocator extents, algorithms and resolved features.
Full original SHA-256/version mismatch, missing/ambiguous edits or source registration fail closed.
3. CMake retains component targets and source properties/quoted-include context, replacing exactly one
original compilation per entry. Generator/version/original/derived changes trigger reconfiguration;
changed originals fail the hash check. Do not hand-patch SDK files or derived build-tree output.
4. Derived full files preserve original copyright/license notices; regenerate through configuration,
verify exact generated bytes and single-source registration, then rerun the relevant host contracts.
5. Future release/dependency review remains pending: external advisories and license obligations have
**not** been reviewed here. No CVE absence, vulnerability completeness or license-compliance claim.
Verified host commands passed during this documentation audit (prefix `CCACHE_DISABLE=1`):
- `python3 tests/sdk_security_overrides/run.py --build-dir .pio/build/esp32-s3-devkitc-1-n16r8`
- `python3 tests/ssh_memory/run.py --idf-path /home/mscholz/.platformio/packages/framework-espidf`
- `python3 tests/ssh_protocol_policy/run.py`
- `python3 tests/wolfssh_auth_contract/run.py`
- `python3 tests/web_cookie_auth/run.py`
These execute actual modules/extracted installed or patched functions with heap, crypto, IO and layout
mocks, plus pinned source/production-feature contracts and existing Ninja registration checks.
They cover cleanup failures, null-first-read behavior, policy serialization/publication and web quota/wipe
ordering; they are not complete parser fuzzing, real signature verification, live handshakes or target tests.
No firmware build, upload, erase, raw-dump export or hardware operation was performed for this document.
+117
View File
@@ -0,0 +1,117 @@
# Security operations — Phase 9D
Operator runbook for the current firmware; procedures below are **not execution records**.
Use the [command reference](command_reference.md) for complete syntax and the [browser contracts](web_administration.md) for frontend permissions and result handling.
No device operation is authorized merely by this document. Schedule disruptive work, retain trusted UART0 access, and obtain explicit approval for destructive recovery/erase.
The user will validate **whole Phase 9**, not provide per-segment sign-off. **9D is in progress; Phase 9 is not complete or production-ready.** The [partial wolfSSL/wolfSSH advisory review](wolf_security_review.md) leaves current-path security findings open; the [bounded license inventory](dependency_licenses.md) leaves distribution/corresponding-source/notice questions unresolved. This runbook neither resolves those findings nor claims device validation or license clearance.
## Safety and access
- Restrict physical access: UART0 is the trusted administrative recovery authority. Use the USB-to-UART bridge at 115200 baud, not native USB CDC.
- Native USB is network-independent, binary-transparent UART1 access through the one-writer/multiple-observer broker; it is not an admin console. Reboot interrupts every transport.
- Use a trusted workstation and restricted provisioning network. Disable terminal recording, screen sharing and clipboard history before secret entry/reveal; do not put secrets in command arguments, tickets, screenshots or routine logs.
- UART0 and authenticated role-`admin` SSH provide the operational commands below, except `user recover --force` is UART0-only. Role-`user` SSH is serial, not administration.
- Browser shell is narrower: other-account interactive add/password and forced role/delete only; no self/generated/key/recovery account commands. Wi-Fi/mDNS shell access is status-only. Typed Settings has separate account/network/identity workflows; do not infer shell parity.
- NVS is **unencrypted**: Wi-Fi PSKs and HTTPS/SSH private keys are plaintext at rest; password verifiers are also sensitive. Secure boot and NVS encryption are not provided by this phase. Physical flash extraction and firmware replacement remain outside the protection boundary.
## First provisioning — UART0 first
1. Start in a controlled RF environment with UART0 attached. Defaults enable Wi-Fi with a random-password fallback AP and no station profiles; networking can start before the console is ready. A new AP name is not an authentication secret.
2. Once the console is ready, use `wifi stop`, inspect `wifi status`, then `wifi save` if Wi-Fi must remain disabled after reboot. Stop is asynchronous: check actual state, not only the queue acknowledgement. Do not rely on this to prevent the initial boot's radio exposure.
3. Inspect `user status`. Missing user storage initializes empty; create the first administrator with `user add <username> admin` on UART0 and the hidden confirmation prompts. There is no bootstrap/shared default web credential. A healthy empty database needs **add**, not recovery.
4. Store the chosen password in the operator's protected vault. Usernames and password bounds are in the command reference (passwords: 1264 printable ASCII characters). Optionally use `--generate` only with private, reliable one-time capture. Create/test a separately controlled recovery administrator if policy requires one; the final administrator cannot be deleted or demoted.
5. Choose AP policy explicitly with `wifi ap policy off` or `wifi ap policy fallback` (use `always` only intentionally). For retained AP access, set `wifi ap secret` through the hidden 863-character prompt, or privately retrieve the generated password with `wifi ap show-secret`. Never include its output in routine captures.
6. Configure an unused/disabled station slot using `wifi profile set <slot> <priority> <mixed|wpa3> <ssid>`, then `wifi profile secret <slot>`, then `wifi profile enable <slot>`. Check peer compatibility before choosing WPA3. Profile set preserves the existing secret/enabled state; disable an existing slot before staging its replacement. Enabling or editing an enabled profile/AP can reconnect the radio.
7. Use `wifi start` when ready, inspect `wifi status` / `wifi profiles`, and `wifi save` to persist the intended working policy, profiles, secrets and boot-enabled state. Restrict upstream network access to intended operators; do not expose ports 443/22 to untrusted networks.
8. Read `web certificate info` and `ssh host-key info` through trusted UART0. Compare the certificate SHA-256 fingerprint in the HTTPS client and the OpenSSH `SHA256:` host-key fingerprint **before supplying account credentials or accepting changed trust**. A self-signed certificate or an unsolicited network fingerprint alone is not proof of device identity.
9. Establish narrowly scoped browser certificate trust and SSH known-host trust only after comparison. Investigate an unexpected mismatch rather than disabling verification or deleting all known-host entries. Test fresh HTTPS login and both intended SSH roles; an admin SSH login does not acquire a serial writer lease.
10. Set required serial framing, mDNS suffix and display policy with their documented commands and explicit saves. Record intended state privately; later rehearse a reboot and compare actual loaded settings/trust before production use.
**Fallback-default caution:** true first boot attempts to persist generated Wi-Fi defaults, but that save can fail. Incompatible stored configuration selects generated RAM defaults without overwriting the rejected blob. `wifi defaults` generates fresh RAM defaults; `wifi reset` generates and saves them. Both restore enabled/fallback policy and replace the AP password, not merely repair connectivity. Re-protect the AP and verify/save intended state rather than assuming an old password or disabled radio survived.
## Working configuration versus service lifecycle
| Operation/domain | Persistence and operational effect |
|---|---|
| Serial, Wi-Fi, mDNS, display edits | Working RAM until `serial save`, `wifi save`, `mdns save` or `display save`, respectively; `load` reads that domain's storage, not an external backup. `defaults` is RAM; `reset` applies/persists domain defaults. Check errors and actual state; these domains do not share one atomic transaction. |
| `wifi start` / `wifi stop` | Queue runtime action **and** set RAM `enabled-at-boot` true/false; only `wifi save` persists it. Local start/stop has the same semantics. |
| `web start` / `web stop`, `ssh start` / `ssh stop` | Runtime service controls, not persistent enable/disable configuration. No corresponding service `save` or durable boot-disable command. Stops disconnect that service's clients. |
| Boot network services | `main.c` attempts HTTPS/SSH startup independently when Wi-Fi initialization/start has no error and each service's security/runtime initialization succeeds. Wi-Fi configured off can still initialize successfully: listeners may be started without radio reachability. Wi-Fi-off is not a persistent HTTPS/SSH-disable flag. |
| Accounts and identities | Mutations commit their own NVS blob as part of the operation; no follow-up `save`. Commit acknowledgement is not a general power-loss/durability guarantee. |
| `reboot` | Loses unsaved RAM and all live sessions. A runtime service stop does not survive normal boot startup. |
## Routine account, password and authorized-key rotation
1. Keep UART0 or a separate current administrator available. Inspect `user show <username>` privately to confirm role and current key slots; do not operate from stale indices. The database allows eight accounts and three authorized keys per account.
2. Set a known replacement with `user password <username>` using hidden prompts. `user password <username> --generate` commits then displays a value once: protect it immediately. Lost generated output has no retrieval command; inspect account state, then deliberately set another known password via UART0/another admin rather than blindly replaying generation.
3. Admin SSH **rejects its own generated-password replacement**; its ordinary hidden self-password change is allowed but revokes the invoking principal. Browser shell denies all self account mutations. Typed Accounts supports self changes; its Generate action only returns a value, does not change the account, and has no retained retrieval. Securely save/acknowledge it before separately submitting the mutation.
4. For an authorized-key rotation, generate/protect the private key on the operator's host; import only the supported Ed25519 or ECDSA-P256 **public** key with `user key add <username>`. With capacity available, add first, test a fresh login using the new key, then remove the old key using its freshly inspected slot: `user key delete <username> <0..2> --force`. If full, use independent recovery access before removing a slot. `user key clear <username> --force` removes all that account's keys, not its password.
5. Password, role and key changes stale the affected principal; deletion removes the account. Committed changes trigger targeted web-ticket/session and SSH revocation, supplemented by authoritative currentness checks. Self changes can lose their result before it arrives; unrelated accounts should remain usable. Disconnect/timeout is not proof of rollback or cancellation of admitted work.
6. Reauthenticate to verify the new credential and rejection of the retired one; do not confuse admission throttling with a bad password. For account retirement use `user delete <username> --force`; for reduced privilege use `user role <username> user --force`. Preserve a usable administrator. A password change does **not** remove authorized keys, and key removal does **not** change the password: revoke both paths for a compromised account.
7. Update the protected operator record and revoke any reused credentials/keys on other systems separately. A key can authorize multiple device accounts; remove every affected authorization. Retire superseded host-side private-key copies according to storage policy.
## HTTPS and SSH server identity rotation
Plan a maintenance window and distribute newly verified public trust through a trusted channel. Server identity changes are separate from account passwords/authorized keys and do not replace them.
- **HTTPS:** `web certificate rotate --force` replaces certificate **and** private key. Owner ordering is reserve → generate/commit/publish → stop/restart if running. Precommit failure leaves the old identity/logins in place; after commit, lifecycle failure never rolls the identity back. Failed stop can leave the old certificate served while UART0 reports new stored material. Rotation while stopped stays stopped.
- **SSH:** `ssh host-key rotate --force` reserves ownership → stops sessions → generates/commits/publishes → restarts if previously running. Failed stop skips mutation/start. Persistence failure may follow client disconnection and attempts to restart with unchanged material; that restart can also fail. A committed new key is never rolled back after restart failure. Rotation while stopped stays stopped.
- UART0/admin SSH expose both rotations. Browser shell allows only exact `web certificate rotate --force`, not SSH host-key mutation; typed HTTPS/SSH Settings provides its own bounded rotation flow. Neither browser route provides identity reset/recovery/export.
- Remote scheduling/drain/HTTP acknowledgement is not peer receipt or operation completion. On timeout/lost result, use Check Result/Refresh where available, then inspect UART0 service status and fingerprints. **Do not automatically repeat rotation.**
- Resolve lifecycle failures with deliberate UART0 `web stop` / `web start` or `ssh stop` / `ssh start`, checking each outcome; do not start over failed cleanup or rotate again to repair it. If recovery needs reboot, account for unsaved state and all-transport interruption.
- After recovery, compare the actually served identity against trusted UART0, replace only the relevant client trust entry, and test a fresh connection. HTTPS restart requires fresh login; SSH rotation closes SSH sessions but does not inherently require HTTPS relogin. USB/UART0 remain independent of these network-service rotations, not of reboot.
## Configuration backup and reconstruction
There is **no implemented configuration export/import or full backup/restore workflow**, nor a supported private-identity export/restore command. `save` writes working state to the same device; it is not an off-device backup. Do not use raw NVS/flash dumps as routine backups or duplicate them onto replacement devices.
Maintain an access-controlled operator inventory outside the repository: reviewed firmware/build provenance, intended serial settings, station/AP policy and profile ordering, boot-enabled intent, mDNS/display settings, account roles, authorized-public-key provenance, verified public server fingerprints, and last successful save/rehearsal outcomes. Keep device/account/network identifiers in that protected record, not public issue logs. This runbook intentionally contains no populated inventory or identifier template.
Keep passwords, Wi-Fi PSKs and client private keys in a separately protected, backed-up vault with controlled recovery access and retention. Inventory entries should reference vault records rather than duplicate secrets. Ordinary status cannot reconstruct PSKs/passwords/private keys; public fingerprints cannot recreate an identity. Do not collect verifier material, session cookies or tickets for backup.
Reconstruction means first-admin provisioning, manually re-entering reviewed settings and secrets, re-importing authorized **public** keys, explicitly saving each configuration domain, and verifying new server trust. Replacement hardware/newly generated identities require client trust changes, not promises to restore the old identity. Test the reconstruction on an isolated spare with synthetic credentials. Exceptional forensic flash capture requires separate approval, restricted handling and retention; it remains secret-bearing, not a supported restore format.
## Recovery — smallest affected domain first
Use UART0 status/error observations to distinguish connectivity, authentication, storage and lifecycle faults. Avoid reset for ordinary login throttling or protocol mismatch; restrict hostile traffic and allow natural budget refill. Native USB preserves serial access during network failure, not administrative recovery.
| Fault | Deliberate recovery and scope |
|---|---|
| Wrong/lost password, healthy database | `user password <username>` through UART0 or another current admin; inspect/revoke authorized keys separately if compromised. Do not recover/erase the database. |
| User database unavailable after failed initialization | Only with explicit approval, UART0 `user recover --force` replaces **only the user blob** with an empty database, discarding all accounts/verifiers/authorized keys. Then `user add <username> admin`. Healthy databases, including healthy empty ones, are refused. Underlying NVS/RNG/allocation failure can still prevent recovery. Empty storage commits before dummy-verifier initialization; a later initialization error does not prove the old accounts survived. |
| HTTPS material unavailable/damaged | With approval, UART0 `web reset --force` replaces **only HTTPS certificate/private key**, not users or SSH/Wi-Fi configuration; it can also replace healthy material. Unlike stopped rotation, reset attempts to start a stopped service. Verify new trust and lifecycle state. |
| SSH material unavailable/damaged | With approval, UART0 `ssh reset --force` replaces **only SSH host identity**, not account keys/passwords or HTTPS material; it can also replace healthy material and attempts startup. Verify new trust and lifecycle state. |
| Ordinary configuration wrong/incompatible | Review the domain's `status`, then choose `load`, manual correction plus `save`, or explicitly approved domain `reset`. `serial reset`, `wifi reset`, `mdns reset`, `display reset` are not factory resets; Wi-Fi reset can reopen fallback access with a new password. |
| Service/network fault with healthy identity | Recover radio/profile or stop/start the affected service; preserve identities. If initialization remains unavailable, investigate the reported dependency/storage fault before an approved reboot or broader recovery. |
Identity resets are also available to authenticated admin SSH, but UART0 is preferred for recovery; browser reset is unavailable. None of these domain commands promises secure deletion of superseded flash bytes. A failed write or lost result calls for inspection, not assumptions about persisted state.
## Destructive factory-style reset — explicit approval only
There is **no on-device factory-reset command**. Full reset is the host-side erase/reflash procedure, not a collection of identity resets. It is not a routine upgrade, backup, password repair or prerequisite for this runbook.
1. Obtain explicit approval for this particular target and **all flash/NVS data loss**; confirm the physical device/port, maintenance window, protected reconstruction inventory and reviewed firmware. Disconnect sensitive serial equipment and isolate RF before erase/reflash.
2. Only in that separately authorized hardware session, from the repository root, run `pio run --target erase`; check success, then reflash with `pio run --target upload`. Use `pio device monitor -b 115200` on the USB-to-UART bridge for provisioning. Do not automate or run these operations as documentation validation.
3. Erase removes firmware and all NVS domains, including users, Wi-Fi secrets/configuration, TLS/SSH identities, serial, mDNS and display settings, plus other flash contents. Ordinary upload alone is **not** a reset. Reflash and follow UART0-first provisioning; expect newly generated identities/AP secret and no old accounts. Re-establish client trust only after verification.
4. Erase success is **not a forensic secure-erase guarantee**, proof that external copies disappeared, or a general persistence guarantee. Preserve custody/disposal controls below. See the [documented partition migration](../README.md#one-time-migration-from-the-default-partition-table) before changing layouts.
## Decommissioning
- Isolate/disconnect the device and attached serial equipment; revoke access **outside the device** before custody changes. Rotate upstream/shared Wi-Fi PSKs or revoke network admission as applicable; remove saved device-AP credentials on peers.
- Remove retired device certificate exceptions/pins and SSH known-host trust on operator systems. Revoke account/key authorizations and reused credentials on other devices/services separately; a local reset cannot revoke remote trust or a copied private key.
- If approved, perform the destructive erase above; do not reflash merely to retire hardware. Logical rotation/reset can leave historical plaintext NVS pages, older credentials and private keys in flash. Retired flash/RAM captures, backups, terminal records, vault versions and workstation copies require separate retention/disposal handling.
- Flash erase, file deletion and software RAM wiping do not prove all copies are unrecoverable. Maintain physical custody; use approved media destruction/device disposal when confidentiality requires it. Do not claim secure boot, encrypted NVS, extraction resistance or guaranteed erasure.
## Deferred whole-Phase-9 hardware rehearsal
Use a separately authorized, isolated expendable target and synthetic secrets. Record sanitized outcomes, exact tested build and limitations, not passwords, raw dumps or live identifiers. These checks are **planned, not passed**, and join the [combined Phase 9 gates](security_hardening.md#combined-phase-9-target-validation--deferred-not-run) and [administration regressions](user_administration_tests.md):
- [ ] First boot/healthy-empty provisioning; no remote first-admin path; fallback AP protection, saved radio-off/on behavior, and fresh trusted HTTPS/SSH login for both roles.
- [ ] Save/load/default/reset/reboot per configuration domain; failed first-default save and incompatible Wi-Fi storage; compare runtime radio/listener state with saved boot intent.
- [ ] Password/key/role/delete rotation: old credential rejection, self-revocation, unrelated-account isolation, final-admin protection, remote self-generated denial, typed generation-before-submit, lost/partial one-time output and stale results.
- [ ] Both identity rotations running/stopped; failed stop/commit/restart and lost ACK/result using reviewed fault injection; no blind replay, stored-versus-served trust comparison, reconnect/relogin and independent UART0/USB access.
- [ ] Each domain recovery preserves unrelated domains; unavailable-user recovery is UART0-only, healthy recovery refused. Reconstruct a spare from protected records without raw NVS restore.
- [ ] Separately approved destructive erase/reflash rehearsal: all domains reset, fresh identities/AP credential/accounts provisioning; rehearse external trust revocation and disposal checklist without claiming secure erasure.
- [ ] Complete existing whole-phase crash/no-dump, authentication/admission/refill, hidden-input, protocol/rekey, allocation-failure and full transport-mix/resource checks; verify one writer, isolated observers and recovery. Do not substitute this runbook review for those measurements.
Source basis: [startup](../src/main.c), [console policy](../src/admin_ssh_console.c), [users](../src/user_console.c) / [storage](../src/user_database.c), [Wi-Fi commands](../src/wifi_console.c) / [manager](../src/wifi_manager.c) / [storage](../src/wifi_config.c), [HTTPS owner](../src/web_server.c) / [material](../src/web_security.c), and [SSH owner](../src/ssh_transport.c) / [material](../src/ssh_security.c). Commit ordering is an implementation contract, not power-loss or hardware-validation evidence.
+112
View File
@@ -0,0 +1,112 @@
# SSH key-validation review — 2026-09-15
## Decision and scope
**The baseline P-256 ECDH and X25519 validation gaps are mitigated by project-owned compile policy. Parent firmware build and local strict crypto suite PASS; the broader SSH review and hardware gates remain open.** This supplements, rather than silently rewrites, the historical [wolf review](wolf_security_review.md).
- Enable upstream `WOLFSSL_VALIDATE_ECC_IMPORT` for wolfSSL 5.8.2. The SSH server imports an unauthenticated P-256 peer point and otherwise reaches scalar multiplication without an on-curve check.
- Enable existing upstream `WOLFSSL_ECDHX_SHARED_NOT_ZERO`. The SSH X25519 input precheck does not reject every low-order input; the result check was disabled.
- These are PUBLIC definitions in `cmake/wolf_crypto_policy.cmake`, with resolved-settings checks in `cmake/wolf_crypto_policy.h`. No root `CMakeLists.txt` edit is necessary: it already includes this module after `project()`. The existing small X25519/Ed25519 policy and RNG/acceleration controls are preserved.
- No dependency version, installed vendor source, generated override, application source, or device change was made by this task. Edits are restricted to the assigned policy files, `tests/wolf_crypto_policy/`, and this report.
- This is **not** a demonstrated long-term-key recovery, authentication bypass, remotely measured exploit, full upstream backport, or release approval. ECDH uses a freshly generated ephemeral key, separate from the long-term signing identity.
## Exact local evidence
Inspected installed wolfSSH 1.4.20 / wolfSSL 5.8.2~1 and the generated wolfSSH input located through `.pio/build/esp32-s3-devkitc-1-n16r8/compile_commands.json`. SHA-256 snapshot:
| Input | SHA-256 |
| --- | --- |
| `managed_components/wolfssl__wolfssh/src/internal.c` | `81ff1f9166708abd5c2911e9fe57c0aee01c88b5d3f68c909ee8a856d37f36a9` |
| `.pio/build/esp32-s3-devkitc-1-n16r8/security_overrides/wolfssh_internal/internal.c` | `9e5923d536cee049409a7df471d155a6dd2e804d55a1528f5c4abc8e34807dea` |
| `managed_components/wolfssl__wolfssl/wolfcrypt/src/ecc.c` | `909c57e2756a8002df9f1d214483c659cb20db4a5f51047eda62d64ac458db06` |
| `managed_components/wolfssl__wolfssl/wolfcrypt/src/curve25519.c` | `9a0f6f0205245a8d19500a936d9b02bb71c8656713648408d1cb408362694b76` |
| `managed_components/wolfssl__wolfssl/wolfcrypt/src/signature.c` | `62ab3db3dfd251b2a2c73b69ef05aab6085d2e0d673fd9159514b3ee261cea4f` |
The original and generated bodies of `HashForId`, `KeyAgreeEcdh_server`, `KeyAgreeCurve25519_server`, `SignHEcdsa`, and `DoUserAuthRequestPublicKey` remain byte-identical. `DoUserAuthRequestEcc` and `DoUserAuthRequestEd25519` now contain the reviewed label/framing corrections from `tools/security_overrides.py`. The crypto suite independently reconstructs only those exact deltas from the hash-pinned original, requires exact anchor counts, and compares all seven complete functions with the actual generated compilation input. It does not derive its expected bodies from the generator being checked, skip changed functions, normalize away changes or relax the original hashes. Any additional change requires re-review. This is not a whole-generator equivalence test.
Generated-source line references below retain the initial pre-parser-correction snapshot; use the named functions in the current generated source, whose hash is recorded above.
Before changing policy, actual Xtensa preprocessing of `ecc.c` confirmed `USE_FAST_MATH`, `ECC_TIMING_RESISTANT`, `WOLFSSL_SMALL_STACK`, `HAVE_ECC_CHECK_KEY`, and internal `HAVE_ECC_CHECK_PUBKEY_ORDER`; neither validation definition was present. `USE_ECC_B_PARAM` and SP math were absent. Initial candidate replay checked the proposed definitions. Following the parent build, **strict mode now passes without injecting policy flags**, checking the saved production compiler/includes/definitions and syntax for twelve library/SSH/application translation units, including `ecc.c` and `signature.c`. Parent-reported `pio run` PASS: **94,340 B linked RAM / 1,768,949 B flash**. This agent did not rerun PlatformIO or inspect a flashed image; compile-profile checks and the supplied link/build result are distinct evidence.
## P-256 import and ECDH
Generated `internal.c:1125111317`, `KeyAgreeEcdh_server`:
1. Derive `primeId` from negotiated KEX; project policy allows `ecdh-sha2-nistp256` and X25519.
2. Initialize public/private keys; attach the session RNG to the ephemeral private key.
3. `wc_ecc_import_x963_ex(handshake->e, eSz, pubKey, primeId)` imports the peer point.
4. Only after successful import, generate a fresh private key, export its public point, and call `wc_ecc_shared_secret`.
5. Errors propagate; both key objects are freed. The policy adds no task, queue, retry loop, protocol control sequence, or new entropy source.
Installed `ecc.c:1070911020` parses X9.63 coordinates and selects the curve. At `1099310996`, `wc_ecc_check_key` is called **only** with `WOLFSSL_VALIDATE_ECC_IMPORT`. Merely compiling `HAVE_ECC_CHECK_KEY` is not equivalent. The inferred-curve `wc_ecc_import_x963` wrapper uses the same implementation.
Without this flag, `wc_ecc_shared_secret` (`46694752`) checks pointers, private-key type, domain metadata and matching curve IDs, not whether the peer coordinates satisfy the curve equation. Its software path reaches `wc_ecc_shared_secret_ex` (`5102`), `wc_ecc_shared_secret_gen_sync` (`4759`), and `wc_ecc_mulmod_ex2` (`4942` vicinity), using curve A, prime and order. No equivalent point-validation call precedes the multiplication. **The absent import validation is applicable, not just an unproven macro concern.**
With the flag, `_ecc_validate_public_key` (`1049510703`) checks infinity, coordinate ranges, the curve equation and public-point order; private imports additionally check the private range and private/public consistency where applicable. It loads B from `key->dp->Bf` even when `USE_ECC_B_PARAM` is absent. There is no need to force B storage or reproduce the larger upstream source refactor. The guard rejects configurations that disable the software validator or route it to the known successful hardware stubs; it does not claim arbitrary future backends are validated.
The work is bounded by the selected curve and existing key/input limits, but **not free**: valid imports incur public validation, including order checking, and private/public consistency checks can add multiplication and allocations. Target latency, memory peaks, stack margins, repeated-handshake/rekey load and the existing deadlines must be measured. Existing admission limiting is not evidence that this cost is harmless.
## X25519 all-zero result
Generated `internal.c:1133511394`, `KeyAgreeCurve25519_server`, explicitly runs `wc_curve25519_check_public` before import, key generation and shared-secret calculation. Installed `curve25519.c:645710` rejects wrong lengths, zero/one, the high bit, and the upper-end range in the little-endian path. This is **not** a complete low-order rejection rule.
The real vendor small-math tests exercise two nontrivial low-order u-coordinates that pass that precheck:
- `e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`
- `5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157`
`wc_curve25519_shared_secret_ex` (`452536`) already contains a 32-byte OR reduction under `WOLFSSL_ECDHX_SHARED_NOT_ZERO`. It returns `ECC_OUT_OF_RANGE_E` for an all-zero result before copying it to the caller, then wipes its temporary. Neither the current SSH server helper nor subsequent successful-KEX processing adds an equivalent result test. Enabling this existing check is sufficient for the inspected software path. Tests verify rejection of both inputs, unchanged caller output on rejection, ordinary zero/one precheck rejection, and the valid RFC7748 shared secret. No custom blacklist or small-math/blinding combination is introduced.
## Raw signatures and CVE-2026-5194 applicability
**No attacker-selected short digest/OID-confusion trigger was found in the reviewed current raw SSH authentication/signing paths. The separate ECC/Ed25519 label and signature-framing defects have now been corrected by the parser owner, as reviewed below; that does not backport generic crypto API hardening.**
- `src/ssh_transport.c:489` calls `user_database_authorize_ssh_public_key` before wolfSSH signature verification. `src/user_database.c:185` vicinity checks exact embedded type, exact `nistp256`, 65-byte uncompressed point and end-of-blob; mbedTLS parses and checks the point. `user_database_authorize_ssh_public_key:810` repeats validation and requires exact stored key-type/blob matching for the named account. Thus the server user-key path already has an independent P-256 point-validation boundary, unlike unauthenticated KEX. The new wolfSSL import check is defense in depth here.
- Generated `DoUserAuthRequestPublicKey:7324` vicinity derives `hashId = HashForId(pkTypeId)`, obtains `digestSz` from `wc_HashGetDigestSize`, and hashes the session ID and authentication message locally. `HashForId` maps P256 to SHA256: the digest is 32 bytes, not a peer-supplied digest length. The untrusted signature type does not choose an alternate prehash independently of that authorized key type.
- Generated `DoUserAuthRequestEcc:6851` vicinity imports Q, converts raw r/s through `wc_ecc_rs_raw_to_sig`, and calls `wc_SignatureVerifyHash` with that locally computed digest and length. Installed `signature.c:131` only checks that the hash type exists, not equality of `hash_len` with its size; `ecc.c:9204` checks r/s ranges but predates the new minimum-digest check. These upstream API weaknesses remain in the dependency, but the reviewed caller supplies the correct size.
- `SignHEcdsa:11676` hashes exchange hash H using `HashForId(handshake->pubKeyId)` and signs the resulting full SHA256 digest for the allowed P256 host key. This is distinct from ECDH.
- Client host verification (`DoKexDhReply`, generated calls near `5651/5685`) uses `wc_SignatureVerify`, which computes the full digest before verification. Client `BuildUserAuthRequestEcc` derives its digest size from `HashForId(keySigId)`. These are not the intended application's server authentication role. Existing message-order concerns mean role alone must not substitute for validating dispatch reachability.
- Certificate variants (`DoUserAuthRequestEccCert`, `BuildUserAuthRequestEccCert`) are under disabled `WOLFSSH_CERTS`. Current Ed25519 auth takes its separate message/streaming-verification path, not an attacker-sized Ed25519ph digest. Ed448 and ML-DSA are not current SSH algorithms.
- Host private DER decoding goes through `wc_EccPrivateKeyDecode` in installed `asn.c:35833`; template parsing calls `wc_ecc_import_private_key_ex` near `36033`. Real host tests cover valid SEC1 P256 private/public import without a pre-attached RNG, plus rejection of a corrupted embedded public point. This is not an NVS lifecycle or identity-rotation test.
The compile-policy mitigation does **not** backport PR10131's global digest-length/OID enforcement. Reassess if new raw APIs, certificates, key types, callbacks or client roles are enabled.
## Parser-owner corrections reviewed and remaining work
The following formerly pending gaps are **fixed in the current generated input**, not by the crypto compile flags:
1. Both key/signature label checks in `DoUserAuthRequestEcc` and `DoUserAuthRequestEd25519` now use OR. Unequal lengths reject before `memcmp`; equal lengths compare the bounded expected span. This rejects equal-length wrong labels and avoids comparing an oversized label against the shorter expected label. Existing error normalization remains unchanged.
2. ECC `GetSize` first proves `sz <= signatureSz - i`; converting `sz` to the absolute end with `sz += i` therefore cannot wrap. Both `GetStringRef` calls use that end, not the outer field size. The subsequent `i != sz || sz != pk->signatureSz` rejection requires exact inner and outer consumption before conversion or verification.
3. Ed25519 requires `sz == pk->signatureSz - i` before starting streaming signature verification. Trailing bytes outside the declared signature string now reject.
Reviewed `tools/security_overrides.py` and `tests/wolfssh_parser_contract/{run.py,README.md,auth_framing.c}` against exact original/generated function diffs. These deltas leave ECC digest creation, raw-to-DER conversion and crypto calls, and Ed25519 streamed-message construction unchanged. Valid framing is retained; previously tolerated malformed labels/trailing bytes reject. No exploit or authentication-bypass demonstration is claimed.
The parser suite uses extracted generated functions, guard pages, instrumented nested reads, UBSan trap mode and **crypto doubles**. Its documented 3,124 cases per stack mode and six guard-removal mutations concern parser gating, not actual signature arithmetic. In contrast, this crypto suite executes real installed vendor arithmetic/ASN/wrappers and separately checks exact generated parser deltas and production compilation settings. Neither suite is an end-to-end SSH handshake test.
Parent build plus local strict crypto validation resolve the earlier build/profile handoff; no root edit is requested. Remaining work: broader ordering/state-machine and deferred parser/advisory review, standalone ECC curve-name/key-blob semantic validation if that dependency path is used without the application's existing checks, generic PR10131 API hardening as applicability requires, and whole-phase hardware/resource/latency tests. Later changes to audited functions still require explicit delta review, not silent repinning.
## Tests and limitations
Commands run for this task:
```sh
python3 tests/wolf_crypto_policy/run.py --host-only
python3 tests/wolf_crypto_policy/run.py --candidate
# Follow-up after parent firmware build:
python3 tests/wolf_crypto_policy/run.py
```
**Follow-up strict suite PASS**, including all host vectors and private ASN-decode cases, seven exact source-body checks with independently specified parser deltas, and production flags without candidate injection. Earlier host-only/candidate runs also passed. Parent build evidence is supplied, not rerun here; no device validation was performed. Details are in the companion [test README](../tests/wolf_crypto_policy/README.md). Coverage includes 20 guard cases; a host CMake fixture executing the real module over a library → SSH → app graph; real installed small-X25519/Ed25519 and TFM P256 crypto; explicit/inferred import rejection for off-curve, infinity, out-of-range, truncated and wrong-tag points; valid ECDH; raw/DER valid and invalid ECDSA verification; private-key ASN import; exact source checks; twelve strict production target macro/syntax checks; four real-settings missing-policy rejection cases.
Host settings use software TFM, ECC timing resistance and small-stack allocation, but host word size, allocator, OS entropy, compiler and absent ESP acceleration differ from firmware. The CMake fixture is not the full ESP-IDF graph. No exhaustive Wycheproof/fuzz campaign, allocator-failure injection, crypto-suite sanitizer execution, network handshake, real rekey, timing/side-channel measurement, stack/heap reserve measurement, agent-performed firmware link, flashing or hardware validation is claimed. The parent-reported firmware build/link and size figures above do not establish runtime reserves. Test development exposed host fixture omissions (POSIX declarations, wolfmath linkage, filesystem RNG and ASN settings); those were corrected without modifying vendor sources.
## External sources rechecked
Read-only retrieval on 2026-09-15:
- [wolfSSL PR10133 diff](https://github.com/wolfSSL/wolfssl/pull/10133.diff): removes conditional B/on-curve gating and treats `wc_ecc_import_x963_ex` input as untrusted by default in the later tree. This is not a directly applied patch to 5.8.2.
- [5.9.1 tagged ChangeLog](https://raw.githubusercontent.com/wolfSSL/wolfssl/v5.9.1-stable/ChangeLog.md), Bug Fixes: explicitly recommends `WOLFSSL_VALIDATE_ECC_IMPORT` for users of older versions. This is the basis for the bounded policy choice.
- [wolfSSL PR10374 diff](https://github.com/wolfSSL/wolfssl/pull/10374.diff): makes X25519/X448 all-zero checking opt-out. The existing 5.8.2 opt-in macro enables the inspected equivalent synchronous result check; later nonblocking/TLS changes are not imported.
- [wolfSSL PR10131 diff](https://github.com/wolfSSL/wolfssl/pull/10131.diff): certificate signature-OID/key-type consistency plus raw digest-size hardening; used to distinguish the current SSH caller contract from unpatched generic API behavior.
PR URLs are mutable and are not an archived commit-pinned upstream evidence bundle. Local original source hashes above and the source-contract tests bound the implementation inspected here.
+276
View File
@@ -0,0 +1,276 @@
# Remaining SSH parser review — 2026-09-16
## Completed scope and decision
**This finite review is complete for the current pinned server profile:** PR899
key skips and CHANNEL_FAILURE, PR902 service validation, PR918/919 forwarding
callback applicability, the remaining generic signature-API caller question, and
**exact `DoChannelRequest` name dispatch including application callback gates**.
Three bounded current-path corrections are implemented. This is not a complete
wolfSSH/wolfSSL audit, a full backport of these PRs, firmware validation, or Phase9
sign-off. It supplements the historical/deferred statements in
[wolf review](wolf_security_review.md), [key-validation review](ssh_key_validation_review.md)
and the [parser contract](../tests/wolfssh_parser_contract/README.md).
Only `tools/security_overrides.py`, `tests/wolfssh_parser_contract/*`, and this report
are owned by this slice. No ordering delta, crypto configuration, version, managed
component, application, production generated file, PlatformIO or device change.
Concurrent packaging/IDF-review work is unrelated and left untouched.
| Reviewed item | Current-profile disposition |
| --- | --- |
| PR899 RSA/ECC unchecked key skips | Confirmed in the pinned client parsers, not reachable through current server dispatch. No speculative client patch. |
| PR899 CHANNEL_FAILURE length predicate | Reachable after authentication. Corrected with a bounded exact recipient parser, not just the upstream predicate change. Existing fatal failure policy retained. |
| PR902 | **Service names**, not channel callbacks. Exact `ssh-userauth` required by current server handler. Client accept half unused/unmodified. |
| PR918/919 | Forwarding global/channel callback handling; compiled out with `WOLFSSH_FWD` absent. No forwarding patch. |
| `DoChannelRequest` prefix/NUL name aliases | Closed: all nine name predicates require exact length then exact bytes; branch bodies and unknown-request handling preserved. |
| Generic signature API / PR10131 remaining question | Weak generic API remains, but no attacker-selected short digest/OID path in the inspected current SSH caller set. No crypto/API patch justified for this profile. |
## Exact source and upstream provenance
The authoritative source is wolfSSH **1.4.20 original + existing ordering delta +
existing parser/password edits + the three corrections below**, not installed source
alone. `render_entry` verifies original SHA-256 and exact-once edit anchors. Tests
render into temporary files; production generated inputs are not overwritten.
| Input | SHA-256 |
| --- | --- |
| Original `managed_components/wolfssl__wolfssh/src/internal.c` | `81ff1f9166708abd5c2911e9fe57c0aee01c88b5d3f68c909ee8a856d37f36a9` |
| Reviewed prior original+ordering+parser generated `internal.c` | `4948f8c447670eb54153dd1f3db69e4fa3092f7d7f7ed58a18a8fa05fcd168ca` |
| Fresh generated `internal.c` after this review | `1fdd608d45c4f33da82b0765dc66e1ec2060e78c744bc539906ef1b8a0f783ae` |
| Unchanged `tools/wolfssh_order/delta.json` | `6a81376fe3ffc5f449cde105402963f52d2d78cc844153e869a7e1e0f734fb76` |
| wolfSSL 5.8.2 `wolfcrypt/src/signature.c` | `62ab3db3dfd251b2a2c73b69ef05aab6085d2e0d673fd9159514b3ee261cea4f` |
Fetched official PR patches and independently fetched their commit patches on
2026-09-16; each pair was **byte-identical**. Exact archives and URL/SHA-256 records
are in `tests/wolfssh_parser_contract/pr*.patch` and `provenance.json`. The runner
also pins those commits/hashes/URLs independently; no download occurs during tests
or configuration.
- [PR899 commit d2eeec5e263a4821c90805963eeb0666e99868a6](https://github.com/wolfSSL/wolfssh/commit/d2eeec5e263a4821c90805963eeb0666e99868a6): RSA algorithm skip, ECC curve skip, CHANNEL_FAILURE predicate; Windows file/terminal hunks unused on ESP.
- [PR902 commit ffa646a4b9d47d5d9d6127db140c433c58b1e276](https://github.com/wolfSSL/wolfssh/commit/ffa646a4b9d47d5d9d6127db140c433c58b1e276): service request/accept name checks.
- [PR918 commit fd82a4bcf55935f0801b14bca6be9c71e32ae914](https://github.com/wolfSSL/wolfssh/commit/fd82a4bcf55935f0801b14bca6be9c71e32ae914): global forwarding callback-before-reply, missing-callback rejection and cancel reply framing.
- [PR919 commit 0317c40fc131fab952d291d43c56c7b7ce5f4303](https://github.com/wolfSSL/wolfssh/commit/0317c40fc131fab952d291d43c56c7b7ce5f4303): reject direct-tcpip channel without forwarding callback.
`review.py` independently reverses only the new notice, the two initial handler
changes and nine exact channel-name predicates, then requires the complete prior
generated-source hash. The complete original `DoChannelRequest` is recovered by
reversing just those predicates. Any other source change, including ordering,
client parsing, request branch bodies, password wiping or crypto callers, fails
this fence. Original/version/anchor guards remain;
no silent repin or removal of existing strict build-source checks.
## PR899: distinguish client host keys from server authentication
`ParseRSAPubKey` reads an unchecked algorithm-name length then adds it to its index.
`ParseECCPubKey` does the same for the curve name. An oversized/wrapping length can
invalidate the intended cursor progression. PR899 replaces these skips with
`GetSkip`; it does not establish full curve-name/key-blob semantic validation.
These are real dependency defects, not evidence of current server exploitation.
Exact static call chain: `DoKexDhReply``ParsePubKey``ParseRSAPubKey` or
`ParseECCPubKey`. There is one call to `ParsePubKey`, in `DoKexDhReply`. The current
server user-key verifier instead uses `DoUserAuthRequestPublicKey`
`DoUserAuthRequestEcc`/`DoUserAuthRequestEd25519`; it does not call either PR899 key
parser. Application authorization additionally validates and exactly matches the
stored key blob before successful proof-of-possession verification.
This exclusion is **not just a server-role assertion**:
1. `src/ssh_transport.c` creates only `WOLFSSH_ENDPOINT_SERVER` contexts.
2. Generated `DoPacket` checks `IsMessageAllowed(..., WS_MSG_RECV)` before dispatch.
3. The current two KEX choices set the server expectation to `MSGID_KEXDH_INIT`
(30), then `MSGID_NEWKEYS` (21), never `MSGID_KEXDH_REPLY` (31) or GEX reply (33).
Both initial KEX and rekey use those restrictions. Before peer KEXINIT or with
no nonzero matching expectation, reply messages are rejected as well.
4. Both dispatch routes to `DoKexDhReply` (31 and 33) therefore fail the generated
expectation gate. Disabled DH/GEX must not be confused with the compiled case
labels. The full generated ordering suite was rerun, including wrong-message
rejection and both KEX exchanges/rekeys.
5. Production macro replay confirms `WOLFSSH_NO_RSA`, `WOLFSSH_NO_DH`, and disabled
certificates. Client code is not generally compile-disabled: ECC client parser
safety depends on the role/ordering contract, not on dead-code assumptions.
**Disposition:** retain both key parsers byte-identical, fence the call chain and
ordering source, and require this decision to be revisited before enabling client
use or widening KEX. No standalone client parsing safety claim.
### CHANNEL_FAILURE correction and behavior
The pinned `DoChannelFailure` did not read a recipient at all: `len != 0` returned
`WS_BAD_ARGUMENT`; an empty payload returned `WS_CHANOPEN_FAILED`. It did not have
the out-of-bounds read implied by blindly treating it as the newer parser. But
CHANNEL_FAILURE is a connection-protocol message allowed after authentication by
the current server gate, so its malformed-input contract is relevant even though
the application has no useful outstanding channel-request workflow needing it.
The local adaptation validates pointers, uses `GetUint32` on a local cursor,
requires exactly one remaining recipient field (`begin == len`), and verifies the
recipient through `ChannelFind(..., WS_CHANNEL_ID_SELF)`. Only then does it publish
the cursor and return the existing `WS_CHANOPEN_FAILED`. Truncation/wrapping offsets
and trailing data return `WS_BUFFER_E`; an unknown recipient returns
`WS_INVALID_CHANID`. Failure leaves the caller index unchanged; no channel/session
state is mutated. No new queue, allocation, retry or callback is introduced.
This **does not turn CHANNEL_FAILURE into a recoverable reply** or implement
request correlation. Both old nonempty rejection and new parsed failure remain
fatal to this application's worker path, which treats only its explicit
would-block/receive statuses as retryable. The correction establishes bounded
framing and the appropriate existing failure result, not an authentication-bypass
or memory-corruption exploit fix. It is a local adaptation, not a full PR899 patch.
## PR902 and present channel callback policy
The old bounded `DoServiceRequest` accepted any short service string and advanced
to `CLIENT_USERAUTH_REQUEST_DONE`. PR902 really is applicable before user
authentication: ordering permits SERVICE_REQUEST at `ACCEPT_KEYED` but does not
validate its name. The generated handler now requires length 12 and exact bytes
`ssh-userauth`; mismatch returns `WS_INVALID_STATE_E` before index/state publication.
Length comparison short-circuits before the fixed-span comparison. Existing bounds
and the strict name-capacity limit remain. Unlike upstream's later-tree patch,
this subset does not queue a best-effort disconnect: the owner already closes on
this error. Valid-service transition is unchanged. `DoServiceAccept` is unchanged;
the current server gate rejects SERVICE_ACCEPT before dispatch.
For the channel/forwarding question:
- Actual Xtensa replay confirms `WOLFSSH_FWD`, `WOLFSSH_AGENT`, `WOLFSSH_CERTS`,
`WOLFSSH_SFTP`, and `WOLFSSH_SCP` absent. PR918's `DoGlobalRequestFwd` call sites
and PR919's direct-tcpip handling are under `WOLFSSH_FWD`. Unsupported forwarding
channel types take the default unknown-type failure before channel allocation;
global forwarding requests fall through to failure if a reply is requested.
- `create_context` registers shell, exec and subsystem callbacks, not a channel-open
or global-request callback. Default session-channel acceptance is intentional:
the pinned handler limits it to one channel, and auth ordering precedes it.
- Shell callback marks `shell_requested`; exec/subsystem callbacks reject.
`process_handshake` additionally requires an authenticated/current principal,
that flag and `WOLFSSH_SESSION_SHELL` before broker/admin routing. Callback
rejection alone is not the whole policy: the library stores session type and
completion state even for rejected requests, while the application gate stops
exec/subsystem admission. The registered callbacks never execute commands.
- The pinned generic channel-open callback rejection path appends the channel even
after callback failure; no callback is installed here, so that dormant path is
not patched by this review. Revisit before adding one. Do not infer that PR919
repairs generic channel-open callbacks; its archived hunk is forwarding-only.
### Completed follow-up: exact channel-request names
The concrete prefix issue is **closed**, without refactoring the request parser.
All nine `WSTRNCMP(type, literal, typeSz) == 0` predicates are replaced by
`typeSz == sizeof(literal) - 1 && WMEMCMP(type, literal, sizeof(literal) - 1) == 0`.
The length check short-circuits before any comparison on a short name. `memcmp`
compares through embedded NULs instead of accepting a terminated prefix. Existing
bounded `GetString` copies at most 31 bytes; every recognized name is shorter, so
an oversized name truncated to 31 bytes cannot alias a recognized name. No new
allocation, helper, protocol response, state transition or feature setting.
The full handler and application gates were rechecked, not just the shell branch:
| Exact name | Existing branch / actual production gate |
| --- | --- |
| `env` | Parses two strings; no environment-setting callback. Always compiled. |
| `shell` | Sets shell session type, calls registered `accept_shell`, marks library completion. Application still requires the callback's `shell_requested` flag and shell session type. |
| `exec`, `subsystem` | Parse command, store their session type, call registered rejecting callbacks. Library completion is not application admission; no command is executed by these callbacks. |
| `pty-req` | Under `WOLFSSH_TERM`, **present** in production. Parses term/dimensions/modes; resize callback is optional and not installed by this application. Does not authorize a shell. |
| `window-change` | Requires both `WOLFSSH_TERM` and `WOLFSSH_SHELL`; **absent** because production has no `WOLFSSH_SHELL`. Remains on the unknown path in that profile. |
| `exit-status`, `exit-signal` | Under TERM or SHELL; **present** via TERM. Existing payload parsing preserved. |
| `auth-agent-req@openssh.com` | Under `WOLFSSH_AGENT`; **absent**. Optional enabled-branch comparison tested only in a host fixture, not enabled in firmware. |
Empty names, proper prefixes, same-prefix suffixes, same-length wrong bytes,
embedded NULs and overlong names no longer select any recognized branch. They take
the **unchanged unknown-request path**: no branch callback/session-type update,
consume the payload and return success (send channel success if requested).
This deliberately does not introduce unknown-request rejection or strict trailing
payload validation. Malformed header/name/boolean framing still fails before
lookup/callback. Existing exec/subsystem behavior of calling their rejecting
callbacks even after a command-payload parse error is also preserved; those real
callbacks cannot execute commands. A prior accepted shell does not authorize a
later exec/subsystem: the actual application session-type gate still rejects it,
with or without a requested reply. No unauthenticated route is introduced.
`channel_request.c` executes actual generated helpers and the complete handler.
`channel_request.py` separately hash-pins and extracts the real `accept_shell`,
`reject_channel_request` and complete `process_handshake` bodies, checks their
registration/context wiring, and executes them with platform/routing doubles.
Tests exercise both broker/admin shell admission and rejection for missing callback
context/flag, missing authentication/principal, stale principal, non-shell session
and unsupported role. This is not a live broker/admin or task-lifecycle test.
## Generic signature API: finite caller closure, not library closure
Rechecked exact pinned `signature.c` and generated SSH calls, supplementing the
[key-validation trace](ssh_key_validation_review.md#raw-signatures-and-cve-2026-5194-applicability):
- `wc_SignatureVerifyHash` and `wc_SignatureGenerateHash_ex` reject zero sizes and
invalid hash types but do **not** require the supplied hash length to equal the
algorithm's digest length. That generic weakness remains; no global PR10131
backport or crypto configuration change is made.
- Current server ECC authentication is the sole enabled SSH
`wc_SignatureVerifyHash` caller. `DoUserAuthRequestPublicKey` derives the digest
size from `HashForId(pkTypeId)` and `wc_HashGetDigestSize`, checks errors, hashes
locally, then passes it to `DoUserAuthRequestEcc`. Authorized P256 implies SHA256,
32 bytes. A peer signature field does not supply this digest length. The other
SSH VerifyHash call is certificate-gated and absent.
- `SignHEcdsa` hashes exchange H locally using the negotiated P256 host-key hash and
calls `wc_ecc_sign_hash` with the full 32-byte digest. Ed25519 authentication uses
streamed message verification, not generic prehash verification.
- Both `wc_SignatureVerify` call sites are in blocked client `DoKexDhReply`; that
wrapper also derives/hashes a full digest internally. Client ECC auth signing
and certificate signing are not current server paths; agent signing is disabled.
No application `src/` call to generic signature generation/verification APIs or
raw `wc_ecc_sign_hash`/`wc_ecc_verify_hash` was found outside these vendor paths.
- No wolfSSL TLS context/connect/accept use was found in application `src/`;
HTTPS uses mbedTLS. This is application reachability evidence, **not** a claim
that wolfSSL TLS or generic ASN/signature APIs are compiled out or fixed.
**Closed question:** no short-digest/OID-confusion trigger in this inspected current
SSH caller set. **Reopen on:** certificate/client/agent enablement, new raw API
callers, key/KEX widening or a changed authorization/hash construction. General
wolfSSL TLS/ASN/API auditing remains outside this finite scope.
## Validation and remaining handoff
Executed in this slice:
| Command (all prefixed `CCACHE_DISABLE=1`) | Result |
| --- | --- |
| `python3 tests/wolfssh_parser_contract/run.py` | PASS: existing 3,258 cases × two stack modes / 11 mutations, plus channel matrix below / 20 additional rejected mutations; independent full-source/provenance fences. |
| `python3 tests/wolfssh_parser_contract/review.py --profile` | PASS: actual saved Xtensa feature replay and fresh-source syntax. Explicitly reports production input is the reviewed **prior** baseline. |
| `python3 tests/wolfssh_auth_contract/run.py --host-only` | PASS: 135 password/control-flow/wipe cases. |
| `python3 tests/sdk_security_overrides/run.py` | PASS: generator and CMake fixtures, including existing SDK corrections. No actual build-registration option used. |
| `python3 tests/wolfssh_order_contract/run.py` | PASS: 8,028 full-generated-source/real-crypto checks and seven rejected mutations. No OpenSSH interop option used. |
| `python3 tests/wolf_crypto_policy/run.py --host-only` (initial review, not rerun for name-only follow-up) | PASS: 20 guards, PUBLIC CMake fixture, real vendor small-math/P256/ASN vectors. No strict production crypto rerun. |
| `python3 tests/ssh_protocol_policy/run.py` (initial review; not rerun while build remains stale) | **Blocked as expected:** `Generated wolfSSH source differs from render_entry; reconfigure the build`. Its strict guard was not changed or bypassed. |
Follow-up channel matrix: **2,737 cases per stack mode** for production TERM-only,
TERM+SHELL, and TERM+SHELL+AGENT profiles; **2,735 per stack mode** for no-terminal
and SHELL-only profiles. All five profiles run both stack modes with guard pages
and UBSan trap instrumentation. The alternative features are host-only coverage,
not production settings. Tests cover every proper prefix, valid names, appended
bytes/NUL suffixes, every embedded-NUL/same-length wrong-byte position, 3165-byte
names, every packet/payload truncation, oversized/wrapping declared lengths,
nonzero offsets, want-reply both ways, known/unknown channels, PTY callbacks and
real application admission. Instrumented comparison asserts that the compared
span equals the initialized name length. **18 name/length mutations and two real
application shell-admission gate mutations are rejected**, in addition to the
existing 11 parser mutations. Ordering/auth/SDK suites and Xtensa profile/syntax
were rerun successfully after the follow-up; `git diff --check` also passed.
The new parser tests use crypto/channel doubles; they establish dispatch/gating
and preserved state contracts, not cryptographic arithmetic or actual channel lifetime. The
ordering suite supplies separate full-library host evidence. No resource/timing,
firmware link, device, broad fuzzing, new network SSH or Phase9 acceptance claim.
Remaining handoff is bounded:
1. Parent-approved regeneration/build and strict production-source suites after
integrating concurrent work; production generated bytes are deliberately stale.
2. The requested channel-name dispatch and callback-gate review is **complete**.
Existing unknown/trailing-payload behavior is explicitly preserved, not certified
as a generally strict parser and not expanded into another parser inventory.
3. Existing whole-phase hardware/rekey cleanup, compatibility and heap/stack/CPU
gates remain as recorded in the ordering/key-validation reviews. No new target
cost measurement is claimed for these allocation-free checks.
4. Dormant client-key/forwarding/certificate/generic-API defects are documented
profile exclusions, not fixed dependency features. Re-audit only if those
capabilities or the pinned source/role/ordering contract change.
+123 -6
View File
@@ -1,8 +1,46 @@
# Role-based user database and UART0 administration
# User administration and authentication tests
## Phase 8A role-based user database and UART0 administration
Reusable procedures, **not execution evidence**. [Phase 8 is accepted](web_administration_acceptance.md); overall 8D.22 user sign-off does not assert that every checklist item below ran. Historical 8A/B sections describe their original baselines only; current cookie authentication, removed bootstrap/credentials and UART0-only recovery override them. Use current contracts and the integrated regression section for present behavior. Never log generated/entered passwords, cookies/tickets or private/verifier material.
Keep UART0 physically attached throughout these tests. Phase 8A deliberately does not change HTTPS or SSH authentication: existing network sessions still use the legacy shared credential, while the new database and public keys are prepared for the Phase 8B cutover. Do not include generated or entered passwords in test logs.
## Current Broker management regression procedure — 8D.16
The [Broker contract](web_administration.md#broker-and-contextual-controls) defines current API, generations, wrap safety and bounds. Retain these checks for future regressions; acceptance is recorded separately.
- Verify admin-only detailed client rows against non-consuming UART0 snapshots/counters; direct normal-user management GET/POST denied. Observe zero/one/full client mix without reading UART payloads as a probe.
- Opening, selecting, cancelling, refreshing and navigating must leave writer and both terminals unchanged. Explicit full-page Refresh clears selection; contextual refresh retains selected target/version and sticky stale/absence latches until deliberate reselection. Native confirmation must identify exact target and snapshot writer.
- Assign among USB/SSH/two browser serial clients with both admins connected. Disconnect/reuse target while confirmation is open; race writer release/reacquire, competing requests, shell force and local release. Stale confirmation must fail without changing the intervening lease; Refresh/reselect/confirm explicitly.
- Test separate-login result isolation, same-login tab replacement, pending capacity, lost ACK/result, bounded polling/manual recovery, logout/expiry/revocation and HTTPS stop/restart. Never infer cancellation from connection loss or replay automatically.
- At signed-off 160 MHz/230400 baud, check full-mix binary traffic/drop isolation, UART0/USB recovery and optional-route failure isolation. Capture exact revision/mix and internal/DMA/PSRAM plus HTTPD/dispatcher margins; host tests/build do not approve reserves or target throughput for an unmeasured workload.
## Current Network settings regression procedure — 8D.12/8D.13
The [Network contract](web_administration.md#network) defines the current byte codec, owner/persistence semantics and uncertainty. Retain these regression procedures without inferring individual execution from overall sign-off.
- Verify admin-only Settings/Network and direct-route normal-user denial, current cookie/principal, body/query/framing/Origin/CSRF checks, unavailable/contended snapshots and generation races against CLI/local controls.
- Round-trip UTF-8 and arbitrary SSID bytes through text/hex, including NUL/BOM/non-UTF-8 and 32-byte boundaries. No saved PSK or length may appear in responses, status/logs/completion/local display. Keep omits credentials; Replace never accepts blank; disabled-STA Clear (including disable+clear) works; enabled-STA/AP clear is denied even when AP policy is off. Check transient-input expiry and context/session clearing.
- Distinguish RAM Apply, explicit Save, stored-only Wi-Fi Load and reboot persistence. Missing/invalid/failing Wi-Fi storage must not install generated defaults or new AP secrets. Exercise stale generations, queue failure/drop accounting and NVS failures without secret logging. No Wi-Fi reset/default/export action exists.
- Prepare UART0 and USB before confirming disruptive actions. Test Start/Stop (including RAM boot policy), Reconnect/Next, AP policies and stopped no-ops. The selected profile is an edit target, not explicit connection selection; Next uses canonical priority/wrap. Cancel confirmations and exercise lost ACK/401/disconnect, manual Check Result/Refresh, another-tab result replacement and no automatic replay. `accepted` is not online; delivery before disconnection is not guaranteed. Reconnect via STA/AP; UART0 administers recovery, USB preserves independent UART1 access.
- Test mDNS generation/Set/Save/Load/Defaults, live/offline reannouncement, next STA IP, init/live failure isolation and `applied_not_queued`. Verify actual client DNS and changed-hostname browser trust/login, not merely `announced`. Confirm no unintentional Wi-Fi secret reset.
- With USB/two web serial/SSH serial and both admin routes, verify hidden output draining and writer/observer preservation through Settings navigation. Separate actual network-disruption losses from serial/broker regressions. Exercise optional Network route/timer failure and stop/restart without taking down unrelated routes. Browser-shell restrictions remain unchanged.
- Capture boot/full-mix internal/DMA/PSRAM free/minimum/largest blocks and memory floors during TLS/Network operations; timer heap/slot costs, repeated-operation cleanup/soak and **HTTPD/dispatcher stack margins** remain required. Record exact revision/client mix and nonsecret counters, including broker and manager queue drops. Host tests do not establish target reserve or hard scheduling/cancellation guarantees.
## Current legacy-removal regression procedure
The legacy bootstrap/credential/reconciliation instructions in the phase baselines below are **historical only**, superseded by [legacy credential removal](legacy_credential_removal.md) and the current [command reference](command_reference.md). Basic authentication is also historical; current HTTPS uses cookie login. The current overrides apply to later Phase 8C/browser procedures too: no `user bootstrap` or `web credentials` command remains, first-admin creation uses normal UART0 `user add`, and recovery rebuilds empty. Never treat the checklist below as evidence of execution.
1. On a disposable controlled NVS image with only `user_db/database` missing, boot and confirm an empty database is persisted with zero accounts/admins and no imported credential. Reboot and confirm it remains empty. Keep physical UART0 attached; do not factory-erase the device for this test.
2. Run `user add maint admin` on UART0, check hidden password confirmation and cancellation, then confirm account/password persistence after reboot. Separately exercise `user add operator user --generate` and secure one-time display. Final-administrator delete/demotion must still fail. Existing SSH own-password generation restrictions and typed browser generated-password support remain unchanged.
3. Load a valid existing v1 user image and verify accounts, roles, IDs, auth generations, verifiers and keys are unchanged, including a formerly migrated role-`user` account. No bootstrap status should appear and no account should be silently promoted. No web material change may synchronize a verifier.
4. On a disposable malformed user image, confirm authentication fails closed without automatically overwriting storage. On UART0 run `user recover --force`, confirm empty storage, then `user add maint admin`. Recovery must refuse healthy databases, including healthy empty storage, and be unavailable through SSH/browser. Verify serial/Wi-Fi configuration and TLS/SSH identities remain intact. Inject read/write/commit failures where available and check failure isolation and complete committed records, not partial live mutations.
5. Upgrade valid 1,392-byte v1 `web_sec/material`; verify persisted 1,340-byte TLS-only v2 and exact certificate/key DER, fingerprint and generation retention in a controlled fixture without logging private data. Reboot and confirm identity continuity. Malformed/unknown/cryptographically invalid records and migration read/write/commit failures must fail closed without fallback replacement. Do not interpret a failed commit as proof that no flash write occurred.
6. Confirm help/completion/status expose no legacy credential/bootstrap operation or secret. Removed commands must reject without mutation. Exercise retained user generation and `web certificate rotate --force` through supported frontends. `web reset --force` must change TLS only, require new certificate trust/login after HTTPS restart, leave user credentials/generations unchanged, and not revoke unrelated SSH sessions.
7. Recheck UART0/native USB availability and broker one-writer/isolated-observer behavior with network authentication unavailable. Record only nonsecret counters and telemetry. Older v1-only firmware cannot read HTTPS v2; logical NVS replacement is not secure flash erasure and no factory erase is required.
Acceptance and prior evidence limits are recorded in [legacy compatibility](legacy_credential_removal.md) and [overall acceptance](web_administration_acceptance.md); the preceding procedure is not an execution log.
## Historical Phase 8A baseline — role-based database and UART0 administration
Keep UART0 physically attached throughout these tests. At the Phase 8A baseline, HTTPS and SSH still used the legacy shared credential while the new database and public keys were prepared for the Phase 8B cutover.
### 1. First-boot migration and persistence
@@ -12,7 +50,7 @@ Upgrade a device that already has working HTTPS/SSH credentials and no `user_db`
2. Confirm exactly one `admin`-named account exists with role `user`, `bootstrapped=no`, no displayed password/salt/verifier, and no public keys.
3. Confirm the pre-upgrade credential still authenticates to HTTPS and SSH and that serial terminal behavior is unchanged.
4. Reboot and confirm `user status` reports the same account ID and authentication generation.
5. Confirm routine boot logs, `status`, `web status`, and `ssh status` contain no user password, verifier, salt, or raw public-key blob.
5. Confirm routine boot logs, `web status`, and `ssh status` contain no user password, verifier, salt, or raw public-key blob.
A transient failure reading the legacy web credential must not create or commit an empty user database. If a valid `user_db` blob already exists, it must still load without the legacy credential being readable.
@@ -85,9 +123,9 @@ Because NVS is not yet encrypted, this test validates logical verifier storage r
With the maximum supported mix of USB CDC, WebSocket, and SSH serial clients active, repeat user list/show and several UART0 mutations. Confirm password prompts remain physical-UART-only, no user operation acquires a broker client or writer lease, existing Phase 8A network authentication and revocation behavior remains functional, and serial/broker counters show no unexplained loss. Record `memory`, `web counters`, and `ssh counters` before and after the run.
## Phase 8B role-aware HTTPS and SSH authentication
## Historical Phase 8B baseline — role-aware HTTPS and SSH authentication
Complete the Phase 8A bootstrap first and retain two disposable accounts, one `user` and one `admin`. Phase 8B gives both roles the existing serial/status interface; the administrative SSH shell is not expected until Phase 8C.
These procedures preserve the Phase 8B regression baseline. Complete the Phase 8A bootstrap first and retain two disposable accounts, one `user` and one `admin`. At that baseline both roles received the serial/status interface; current Phase 8C firmware instead routes SSH administrators to the administration shell.
### 1. HTTPS passwords and fail-closed behavior
@@ -120,3 +158,82 @@ Run `web status`, `ssh sessions`, `web counters`, `ssh counters`, and `broker cl
### 5. Concurrency regression
With USB CDC, two role-based network users, one WebSocket terminal, one SSH terminal, and UART1 traffic active, alternate writer ownership and mutate one account. Confirm binary transparency, observer isolation, bounded authentication/handshake behavior, UART0 responsiveness, and no unexpected disconnect of the unaffected user. Record memory, broker, web, SSH, and serial counters before and after. Repeat after reboot to verify passwords, roles, keys, and authentication methods persist.
## Phase 8C SSH administrative shell
**Validation status: passed on target hardware.** The full matrix below passed, including concurrent USB/WebSocket/user-SSH/admin-SSH operation. At 460800 baud with SSH and WebSocket clients in parallel, substantial packet drops and slower display controls were observed under load, but memory exhaustion could not be provoked and no lower baud-rate cap is planned.
Use one disposable `admin` and one disposable `user`. Keep UART0 attached throughout. The SSH server still accepts only shell sessions: `exec`, subsystem/SFTP/SCP, forwarding, and unauthenticated connections must remain rejected.
### 1. Route separation and normal shells
1. Connect as the normal user and confirm the existing broker-backed UART1 serial stream, broker client, and writer/observer behavior are unchanged.
2. Connect as the administrator and confirm the `admin@serial-tool>` prompt appears. Run `help`, `memory`, `serial status`, `wifi status`, `web status`, `broker status`, and `broker clients`. Compare representative output with UART0 and confirm both routes execute the same registered command implementations.
3. From UART0 run `ssh sessions` and `broker clients`. The user session must show `route=broker`; the admin session must show `route=admin-console`, `broker=0`, `broker-role=n/a`, and no writer lease. The admin session must not start UART1 or alter broker client/writer counts merely by connecting.
### 2. Bounded command processing
Exercise printable input, backspace, Ctrl-C, CR/LF, an empty line, and a line longer than the documented limit. Confirm the command line is bounded, overflow is discarded through a clear diagnostic, and a new prompt remains usable. Run `help`, `user list`, and `broker clients` in a normal ANSI terminal and confirm every line starts in column zero: canonical LF output must be normalized to CRLF without doubling handlers that already emit CRLF.
Run at least five distinct commands, then use Up/Down to navigate the four-entry per-session history, return to a saved draft with Down, and confirm older entries are bounded out. Verify history does not survive reconnect and is not shared with a second administrator. Exercise Tab on root and nested prefixes such as `us`, `user l`, `wifi ap sh`, `wifi next`, and `ssh host-key i`; confirm the same hints are offered by UART0 and SSH. For an ambiguous prefix, confirm both routes print the same matching candidates and redraw the unchanged input line instead of cycling candidates; unique/common prefixes must redraw cleanly without inserting escape-sequence bytes into the command. Type a command, use Left/Right to insert and delete characters in its middle, then use Home/End and the terminal's Pos1/Ende keys; verify cursor placement, Backspace, and Delete change exactly the intended byte before submission.
Run an unsupported command and confirm it is rejected without affecting UART0 or the serial broker. Run the full root `help` output to exercise output-ring draining. With the SSH client temporarily unable to read output, confirm the worker applies input backpressure rather than accepting an unbounded command/output backlog; inspect `ssh counters` for admin-console admission and input-backpressure values.
### 3. Remote account administration
Run `user list`, `user show <name>`, `user add <name> user --generate`, `user password <name> --generate`, `user role <name> admin --force`, and the key delete/clear operations from the administrative shell. Confirm generated passwords appear once only on that authenticated channel, affected account sessions are revoked, and unrelated sessions remain connected.
Import both supported key types through the remote form:
```text
user key add <username> ssh-ed25519 <base64-blob>
user key add <username> ecdsa-sha2-nistp256 <base64-blob>
```
Confirm the full ECDSA P-256 command is accepted, fingerprints appear in `user show`, a duplicate on the same account is rejected, and the same key can be imported for a second account. Verify subsequent private-key SSH login uses the selected SSH username.
### 4. Interactive administration, lifecycle actions, and revocation
Confirm `user bootstrap` and `user recover --force` remain unavailable from SSH and continue to work through physical UART0. Also confirm that an administrator cannot run `user password <own-username> --generate` over its own SSH session; entered replacement passwords and generated passwords for other accounts remain available. From admin SSH, exercise manually entered user passwords and public keys, Wi-Fi station/AP secret entry, AP secret display, legacy web recovery credential display/rotation, HTTPS certificate rotation/reset, and both `ping` and `wifi ping`. Hidden characters must not echo or enter command history; visible key input must support Backspace and Ctrl-C; ping lines must remain ordered and correctly attributed to the invoking SSH session.
Exercise `ssh disconnect` for another session and the current session. For the other-session case, confirm the acknowledgement drains, the target closes, and the source shell returns. Separately test `reboot`, `ssh stop`, `ssh host-key rotate --force`, and `ssh reset --force`: each must acknowledge scheduling, stop accepting another command, drain output, and then close/reboot as appropriate. Reconnect after key replacement and verify the new fingerprint. Simulate an unread SSH output window and confirm the destructive action cancels after its bounded drain timeout rather than remaining pending forever.
While an administrative command is queued or running, use UART0 to change that admin's role/password/key or delete it. Confirm no second remote administrative command runs after the mutation, the SSH session is revoked promptly, and queued output is not delivered to a reused SSH slot. Repeat with a different account mutation and confirm the administrator remains connected.
Finally, issue commands concurrently from UART0 and admin SSH, including `user list`, long `help` output, and one UART0 interactive password or key prompt while an SSH command waits. Confirm the single dispatcher serializes all `esp_console_run()` calls, UART0 retains its line editing/history/completion, prompt input is consumed only from UART0, outputs are not mixed between transports, and there is no stack overflow, corrupted argument parsing, database damage, or broker disruption.
## Integrated web administration regression procedure
Current retained-scope checks for future changes. [8D.22 sign-off](web_administration_acceptance.md) closes the phase; these are **not additional acceptance conditions or claims of individual execution**. Record exact revision, workload/client mix, duration, counters and heap/stack evidence for any new run. Do not treat host doubles as target timing/power-loss proof or reserve approval. Prepare UART0 recovery/native USB before disruptive tests and do not erase persisted data without explicit approval.
### 1. Integrated login and authorization
Authenticate as both roles through the same-origin login page, explicitly log out, and switch accounts without clearing browser state or relying on an HTTP Basic credential cache. Verify bounded session capacity, expiry, login throttling, malformed cookies, CSRF rejection, Origin rejection, password/role/key invalidation, deletion/recreation, and unrelated-account isolation. A normal user must be unable to discover through navigation or invoke directly any admin ticket, admin WebSocket, typed mutation API, quick setting, detailed client list, or writer-transfer operation.
### 2. Serial/admin terminal switching and lease preservation
As an administrator, connect the browser serial terminal, acquire the writer lease, send and observe serial data, then switch repeatedly between **Serial terminal** and **Admin shell**. The visible terminal contents and input route must change, but `broker clients`, the displayed browser client ID, and active writer ID must remain unchanged. Request control/Release control and writer/observer state must stay visible in both modes. While Admin shell is selected, have a normal user request the writer lease and confirm the retained browser lease prevents unintended takeover. Only explicit Release control, confirmed writer transfer, Disconnect, logout, revocation, expiry, or connection failure may release it.
Verify the browser admin shell executes the canonical registry through the single dispatcher, preserves bounded history/completion/prompts and backpressure, and does not itself become a second broker client. First-admin provisioning remains UART0-only, remote recovery is rejected, and the removed bootstrap command is unavailable everywhere. Closing only the admin-console route must leave the browser serial client and its lease intact.
### 3. Quick settings and client popovers
For an administrator, open the **Serial** and **Wi-Fi** card popovers by hover, keyboard focus, and click/tap. Confirm each path exposes the same controls, opening alone performs no mutation, Escape/outside click closes cleanly, current values refresh safely, common edits have clear apply-versus-save behavior, and links reach the full Settings section. Saved Wi-Fi secrets must not appear by default or enter routine DOM text, logs, URLs, or status responses.
Open **Broker clients** and confirm its secret-free list matches authoritative broker snapshots: client ID, transport/name, writer/observer role, and bounded queue/drop state. Open **Active writer**, choose another currently connected eligible client, confirm the transfer explicitly, and verify exactly one writer remains. Disconnect or recycle the target before confirmation and confirm its stale generation/ID is rejected without releasing or reassigning the current writer. Hover/focus alone must never transfer ownership.
### 4. Typed settings and destructive operations
Exercise user/password/role/key management, serial settings and persistence, Wi-Fi profiles/AP policy/secrets, retained SSH service/session controls, display settings, HTTPS lifecycle/reboot and HTTPS/SSH rotation through typed bounded APIs. Dedicated typed network diagnostics and ordinary browser-session/native-USB management are excluded; exercise existing shell diagnostics only through permitted frontends. Compare resulting subsystem state with the equivalent canonical CLI behavior without routing API requests through command strings. Generated passwords appear once in no-store responses; destructive or self-terminating HTTPS/SSH/reboot/security actions require explicit confirmation and explain the expected connection loss.
### 5. Concurrency and failure isolation
Run USB, browser serial, browser admin shell, user SSH, admin SSH, UART0, and active UART1 traffic concurrently. Alternate explicit writer transfers while issuing administrative commands and opening/closing popovers. Verify one writer, isolated observers, bounded memory/queues, principal revocation, no mixed admin output, no hidden lease loss during terminal switching, and continued UART0/native-USB recovery if web-session or admin-console initialization fails.
### 6. Service identity, lost acknowledgement and recovery
Confirm public fingerprints and both service/identity versions before HTTPS/SSH rotation. Race canonical CLI changes with open confirmations; stale operations must reject before mutation. For HTTPS, exercise send-return/ID-callback admission, accepted-but-lost work and failed destruction without accumulating callbacks; restart must retain owner reservation while deliberately invalidating logins. For SSH, failed stop must skip mutation/start and retained context must survive until every slot retires. Inspect precommit/postcommit partial effects without assuming an error means no change; never replay automatically. Verify new trust via UART0, fresh HTTPS login after restart, stopped-rotate versus CLI-reset behavior, and continued unrelated-service recovery. Browser identity Reset/recovery/export is not part of the workflow.
### 7. Display, API bounds and optional failures
Exercise Display generation conflicts, explicit RAM/Save/Load/Defaults/Reset, absent panel with available UI task and concurrent button activity. Reset storage failure must leave RAM unchanged. Across all typed domains check body/receive/schema limits, optional registration failures, one-slot/login isolation, queue expiry versus admitted execution, saturation and stale IDs. Secret timers cancel/wipe only non-executing work; logout/deadline cannot recall admitted commits. Compare Serial service discards with preserved broker clients/lease/output, rather than claiming uninterrupted data through explicit reconfiguration.
+128
View File
@@ -0,0 +1,128 @@
# Web administration contracts
Current, accepted firmware behavior. Phase status and executed-evidence limits belong in the [roadmap](roadmap.md#phase-8--role-based-users-and-administrative-access--complete) and [acceptance record](web_administration_acceptance.md), not in implementation timelines. [Regression procedures](user_administration_tests.md#integrated-web-administration-regression-procedure) describe checks, not results. Source is authoritative; start with the [code map](agent/code-map.md).
## Authentication and admission
- HTTPS-only, same-origin login replaces Basic authentication entirely. Four digest-only opaque sessions have absolute one-hour expiry; four pre-login challenges last 120 seconds. Login is globally bounded to five credential attempts per 60 seconds. Live sessions/challenges/tickets are not evicted to admit another client.
- Raw tokens travel only in the host-only `__Host-` cookie with Secure, HttpOnly, SameSite=Strict, Path=/ and explicit lifetime; no Domain. Session records retain copied secret-free principals, CSRF state and nonzero, nonreused originating-session IDs. Passwords, raw cookies/tickets, verifiers and private keys never enter routine snapshots/logs/completion/display.
- Mutation admission requires current cookie/principal, strict Origin and CSRF validation; administration additionally requires current `admin`. Normal users retain serial/status but cannot invoke administration directly. Authentication POST fetches use CORS mode with fixed same-origin URLs and same-origin credentials: do not accept Origin `null` to compensate for browser no-referrer behavior.
- Session-store initialization is part of admitted HTTPS start; authentication failure gates HTTPS. Failed start/accepted stop disables and wipes session state. Logout invalidates only the originating session before socket cleanup; account mutation invalidates that account's sessions/tickets, including deletion/recreation, without revoking unrelated accounts. Currentness checks remain authoritative if best-effort notifications fail.
- Four serial tickets and two admin tickets are digest-only, single-use, 30-second, session/principal-bound records. Cookie/Origin/ticket/currentness and transport admission precede explicit WebSocket 101. Store RNG/SHA/database calls run outside short spinlocks; IDs/expiry/epochs fence stale publication without nested store/transport locks.
- HTTPD remains bounded to six sockets, two serial WebSockets, one admin WebSocket and 39 method/path handlers; LRU eviction is disabled. Sessions, sockets, tickets and the two shared remote-console slots are separate capacity limits. Optional settings/admin failures preserve unrelated routes where their initialization contract permits; UART0 and native USB remain independent of web readiness.
`web_httpd_adapter` alone accesses private IDF 5.5.0 HTTPD state. It rejects duplicate/ambiguous headers, postpones 101 until admission, and wipes consumed header scratch while preserving right-aligned unread bytes. Optional Settings registration stages descriptor/name allocations before publishing either, avoiding the pinned public registration failure path. Re-audit these private boundaries on SDK upgrades and same-version SDK patches: the version guard does not detect patches that retain the same version number. HTTPD response headers are pointer-backed, not copied; both `Set-Cookie` value buffers must remain valid and distinct through response send. Do not reuse or wipe those buffers before sending completes. Do not enable header/ticket debug logging. Auth documents, scripts and sensitive responses are no-store with CSP/no-referrer/frame-denial protections; authored loader changes require matching CSP hashes. Generated assets are not a normal documentation/build output.
## Terminal and console ownership
Switching Serial/Admin/Settings never creates a second serial client, requests/releases the writer lease or reconnects serial. Hidden connected terminals keep draining; only selected terminal input is sent. Both browser terminals have separate 5,000-line scrollback and 64 KiB callback-accounted pending-output bounds with visible browser-drop counts. Admin input is bounded to 4 KiB admission and 512-byte frames. Admin open/reopen is explicit; admin close is isolated. Disconnect pauses serial reconnect but retains login; logout/expiry/revocation closes affected sockets normally.
The document binds terminal state to its first validated username/role/session-stable CSRF tuple. A different identity requires a clean document before showing retained output. Pagehide fences sockets/work and hides scrollback until same-session revalidation; admin is not automatically reopened. Fit readiness caches only success and uses at most three generation-fenced animation-frame retries per external request.
`admin_ssh_console` is the sole `esp_console_run()` caller for UART0, admin SSH and browser admin. Two fixed remote-console slots are shared across SSH/browser, not two per transport. Queue records carry copied principals and transport-qualified generation tokens. Owner currentness is checked outside console locks before commands and during prompts (250 ms polling plus validation/scheduling latency), then identity is rechecked. This is operation admission, not cancellation or rollback of arbitrary executing handlers. Consumed output and retired prompt/history state are wiped.
HTTPD alone owns browser-admin socket IO and its 1,552-byte PSRAM-only payload. A 20 ms timer queues at most one owner poll, not a new task. Close uses current-owner shutdown, not queued reusable `sock_db *` pointers. Detach fences submitters; queued state retires only after successful HTTPD destruction. Failed destruction retains ownership and prevents unsafe restart/reuse.
### Browser-shell policy
Typed Settings permissions do not expand shell permissions. Parsed canonical arguments, not raw prefixes or completion suggestions, control admission:
- Browser `web` permits only `web status`, `web stop`, and exact `web certificate rotate --force`; certificate info/reset, diagnostics/performance and other web forms are denied.
- Browser `wifi`/`mdns` permit only status. Network mutation belongs to typed Settings or UART0/admin SSH.
- Browser `user` permits status/list/show and interactive add/password plus forced role/delete for **other accounts only**. Self changes, generated passwords, key commands and recovery are denied there; typed Accounts supports the separately bounded self/generated/key workflows.
- Browser SSH stop/disconnect/reset and host-key mutation are denied; typed SSH Settings has its own safe owner path. Do not claim full browser-shell parity.
- Browser `reboot` and owner-relative `exit` are supported. First-admin provisioning uses normal `user add` on UART0; unavailable-database recovery is UART0-only. The legacy `user bootstrap` and web credential commands no longer exist.
Self-affecting shell actions use the existing bounded drain/control path (up to ten seconds plus a short delay), not guaranteed peer delivery. Browser certificate rotation hands a typed action after drain/200 ms to the existing 12 KiB dispatcher, never crypto/NVS on the 4 KiB control stack. Pending input is discarded through execution, and an executing slot remains reserved across self-detach. UART0/admin SSH retain canonical recovery actions.
## Typed settings API and operation lifetime
All routes below are under `/api/settings/`. Each domain has bodyless GET snapshot plus GET/POST operation unless noted. Requests reject queries, malformed/oversized/duplicate/unknown fields and inappropriate bodies; mutation routes require bounded JSON with current admin/Origin/CSRF. GET allows absent Origin but rejects mismatch. Snapshot contention/unavailability is not an empty successful projection. HTTPD performs bounded admission/encoding only; canonical mutations run on the existing four-entry administration dispatcher using **IDs only**, not command strings, credentials, request pointers or socket handles.
| Domain and source | Snapshot / operation suffix | Request / snapshot / result buffer bounds (bytes) |
|---|---|---|
| `web_serial_settings`, serial service | `serial` / `serial-operation` | 256 / 256 / 96 |
| `web_account_settings`, user database | `accounts` / `account-operation` | 768 / 1024 (accounts), 512 (keys) / 96 |
| `web_network_settings`, Wi-Fi + mDNS | `network` / `network-operation` | 768 / 2048 / 128 |
| `web_display_settings`, local status UI | `display` / `display-operation` | 256 / 128 / 96 |
| `web_broker_settings`, session broker | `broker` / `broker-operation` | 256 / 2048 / 96 |
| `web_ssh_settings`, SSH owner/security | `ssh` / `ssh-operation` | 256 / 768 / 96 |
| `web_lifecycle_settings`, HTTPS owner/security | `lifecycle` / `lifecycle-operation` | 256 / 320 / 96 |
Mutation bodies use at most four receive attempts. Each domain retains one original-login-bound pending/result slot, nonreused operation IDs and an executing reservation. Results are replaceable, login-isolated observations, not durable history or idempotency keys. Another tab can replace a completed result. Dispatcher currentness and the 30-second dequeue deadline precede canonical owner admission. **Admitted work may finish after logout, revocation, timeout or navigation.** A failed response, 401 or disappearance of a result proves neither success nor cancellation; inspect current state before any deliberate retry.
Accounts and Network each use a one-second timer to cancel/wipe queued, non-executing secrets after 30 seconds plus scheduling latency. Shared input wipes on dequeue/rejection; executing locals wipe on return. This is not a hard wall-clock erasure/execution guarantee. Other domain deadlines are dequeue checks, not new cancellation timers. UI fences late/session-changed responses, bounds request/result checking to 15 seconds and never automatically replays/restores mutations. Serial/Accounts/Network/Display/Broker use bounded automatic checks where implemented (at most ten one-second GETs); SSH and HTTPS/Reboot require manual Check Result/Refresh.
### Serial and Display
Serial Apply/Defaults change RAM; Save persists working device state, not browser drafts. Load follows canonical defaults/fallback behavior. Reset uses canonical apply/persist/best-effort rollback. Reconfiguration/stop discards serial-service RX/TX and task-local pending data but preserves broker clients, lease and already-fanned output. USB with DTR may restart a stopped service. `/api/status` uses a zero-wait consistent serial snapshot (`running:null` if unavailable).
Display accepts dim/off timeouts 086400 seconds and an expected nonzero configuration generation. All writers, including CLI/legacy Apply, share a zero-wait owner reservation; NVS runs outside critical sections. Save stabilizes selected RAM; Load retains canonical fallback without rewriting NVS; Reset commits defaults **before** RAM publication, leaving RAM unchanged on failure. Buttons/diagnostic holds update activity, not configuration generation. Configuration needs an available UI task, not a physically present panel, and never takes over I2C.
### Accounts and authorized keys
The database owns eight accounts, final-admin protection and conditional target username/account-ID/auth-generation checks inside its mutation lock. Create/password/role/delete and key mutations share canonical commit/invariant logic. HTTPD uses zero-wait secret-free projections, not blocking CLI snapshots. Successful mutations request target-only web/SSH revocation; self mutation can revoke access before result retrieval.
Separate bodyless POST `accounts/generate-password` returns one 24-character value without mutation or retained retrieval. The browser uses a 60-second context-bound saved acknowledgement before separate submission; this is UX, not delivery proof, and JavaScript strings cannot be securely wiped. POST `accounts/keys` returns only slot/type/SHA-256 fingerprints for the selected identity. Key add/delete/clear share the operation slot; public-key import is at most 384 decoded text bytes in the 768-byte request and uses canonical Ed25519/P-256 validation. Three stable key indices may be sparse; never interpret response-array position as an index. No stored key blob, verifier or password is exported.
### Network
Wi-Fi config/runtime is one zero-wait consistent projection; mDNS is a separate projection, not cross-domain atomic authorization. Four stable profiles carry enabled/priority/security/SSID/password-configured metadata. `mixed` means WPA2-or-stronger, not open. `announced` is expected STA announcement, not verified DNS.
SSID wire values are reversible **bytes**, maximum 32: printable ASCII, standard single-character JSON escapes and `\u00HH`, with no raw non-ASCII, non-byte Unicode or surrogates. NUL/non-UTF-8 round-trip. UI text is UTF-8-encoded before byte serialization; exact reversible text or literal hex preserves existing bytes and BOM, with no silent replacement/truncation.
Flat operations select one domain/target:
- `wifi-patch` + Wi-Fi generation: optional boot policy, AP policy/channel/SSID/password/clear; `profile-patch` additionally selects stable profile 03 and optional enabled/priority/security.
- `wifi-save|wifi-load` require Wi-Fi generation. `start|stop|reconnect|next-profile` use canonical connection controls, not explicit selected-profile connection.
- `mdns-set` requires its generation and suffix; `mdns-save|mdns-load|mdns-defaults` require its generation. Suffix is 155 lowercase ASCII letters/digits/hyphens, no leading/trailing hyphen, producing `sak-<suffix>`.
Omitted fields preserve current bytes under the Wi-Fi mutex. Password Keep omits, Replace is 863 printable ASCII bytes, disabled-STA Clear is explicit; replacement and clear cannot coexist. AP clear is always denied, even while off. No saved PSK or length is returned. Wi-Fi compare/merge/whole-candidate validation and required queue admission precede RAM publication. Save stabilizes selected bytes; Load reads stored configuration only and cannot generate fallback secrets. No browser Wi-Fi reset/default-secret/export route exists.
Edits require explicit Save. Disabled-profile-only edits do not restart active radio; enabled-policy/AP changes follow canonical asynchronous restart. Start/Stop change RAM enabled-at-boot; Reconnect/Next are no-ops while stopped. Next follows enabled priority order with wrap; editor selection is not connection selection. mDNS independently owns generation/persistence; the Wi-Fi manager owns radio/reannouncement. mDNS RAM change followed by queue failure is reported without rollback; its Load may choose deterministic MAC-derived defaults.
Network result fields are `id/action/state/error`: `pending`, `accepted`, `ok`, `failed`, `cancelled`, `stale`, `invalid`, `loaded_defaults`, `applied_not_queued`, or login-isolated `idle`. `accepted` means RAM/owner-queue admission, **not** association/DHCP/DNS completion. `ok` denotes explicit Save. Loss can precede response; recover via STA/AP and inspect before retrying. UART0 administers recovery; native USB provides network-independent UART1, not an admin console.
### Broker and contextual controls
Broker management atomically copies eight compact client rows, writer and lease generation under one zero-wait mutex acquisition, without reading UART payloads or consuming events. Conditional assignment compares the selected nonzero target ID and lease generation under the same force-writer lock before any effects. Stale/absent targets conflict; same-current-target assignment is a no-op only after validation. Accepted serial TX is not recalled by transfer.
IDs have three slot bits and 29 generation bits; exhausted client slots retire until reboot rather than wrap. The separate 32-bit lease version saturates at UINT32_MAX, survives counter clear and advances on grant/release/revoke before advisory event delivery. Forced transfer can advance twice; it is not a count. Saturation blocks typed assignment but leaves ordinary request/release/disconnect and canonical recovery force available. Reboot invalidates old browser sessions.
Serial/Wi-Fi/Broker quick views reuse one nonmodal settings host and existing controllers/drafts, not parallel editors. Hover/focus/click/tap never mutate. Network quick mode excludes password controls. Full-page drafts are protected; promotion preserves controller/selection, departure fences reads/timers without cancelling admitted work. Dismissal restores the prior terminal without stealing unrelated focus; explicit Escape/Close returns focus to its trigger.
Broker contextual reads use one timer five seconds after successful completion and a five-second whole-read deadline, stopping on errors/uncertainty/departure. Explicit target/lease selection is not rebased by refresh. Sticky stale/absence latches require deliberate reselection even if later snapshots match again. Confirmation captures exact versions before session revalidation; guarded aria-disabled controls preserve focus during updates.
## Service lifecycle and identity rotation
Service generations are saturated, distinct from identity and session generations, and advance on admitted canonical lifecycle attempts including failures; counter clear/reinit cannot revive stale versions. Public zero-wait metadata authorizes nothing. Conditional controls compare under the canonical owner reservation; no snapshot-check/unconditional-mutate gap is allowed. Reboot invalidates originating logins and boot-local reservation IDs.
### HTTPS and reboot
GET `lifecycle` has seven fields: `generation`, `running`, `transitioning`, `controllable`, `identity_generation`, `fingerprint`, `rotatable`. Stored HTTPS fingerprint is 64 lowercase hex SHA-256 digits. Stop/restart/reboot require exactly action + service generation; rotate also requires identity generation. Unknown/duplicate/escaped/coerced fields and zero/saturated versions reject. Unavailable identity yields generation zero/empty fingerprint/not rotatable without removing ordinary service controls.
Self-cutting HTTP actions use **successful synchronous send return → one nonreused-ID HTTPD callback → existing dispatcher**. Send return is not browser receipt. The callback never waits or performs lifecycle work, and captures no request/fd/reusable operation pointer. A two-second ACK admission deadline and post-validation 30-second dequeue deadline are not execution bounds. Accepted-but-lost HTTPD work retains one reservation until callback arrival or successful HTTPD destruction; failed destruction cannot release it or accumulate more callbacks. The original login/current admin is revalidated before owner admission.
`web_server_stop_current()`/`web_server_restart_current()` compare and reserve under the server mutex. Restart retains transition ownership through stop/start; failed stop skips start, failed cleanup retains handles and canonical recovery, and reinit preserves the error. `web_server_reboot_current()` reserves the HTTPS generation then uses canonical `esp_restart()` outside locks, not an HTTPD stop wait or self-console cleanup.
`web_server_replace_identity(service_generation, identity_generation, reset, &committed)` reserves **service before identity**, before any crypto/storage. Both nonzero generations mean conditional healthy-running rotation; both zero retain CLI semantics; conditional Reset is invalid. Canonical CLI/browser-shell rotation and direct security rotate/reset share nonreused task-owner-bound identity reservation tokens. Only the owner can replace once/release; exhaustion fails closed until reboot. Crypto/NVS run outside service/security mutexes and spinlocks; commit precedes live publication and old-key wipe. Reservation remains held while reserved start copies the committed pair.
HTTPS ordering is **commit → stop → restart**. Precommit generation/RNG/storage failure leaves identity, HTTPD and logins unchanged (service version may advance after admission). Postcommit lifecycle failure never rolls back identity; failed stop can leave old served and new stored fingerprints different. Running replacement restarts HTTPS; canonical stopped rotation stays stopped, while CLI TLS-only reset can recover unavailable identity and starts a stopped service. Browser has no Reset/recovery/export action.
Save drafts; rotation/restart invalidates all web logins and closes both browser routes. Inspect `web certificate info` through trusted UART0, verify fingerprint before renewing trust, then reload/sign in freshly. Accepting a warning alone is not trusted verification. Use canonical UART0/admin SSH `web stop` / `web start` for retained-server recovery. Network/SSH/USB are not stopped by HTTPS-only operations; whole-device reboot interrupts all transports and loses unsaved RAM.
### SSH
GET `ssh` supplies service/session state plus identity generation, fixed P-256 algorithm, unpadded OpenSSH `SHA256:` base64 fingerprint and rotatable flag. Service actions use exactly `action`, `generation`, `target`; rotate adds `identity_generation` and requires target zero. Start/stop and exact-session disconnect use published state, saturated service generation and the command mutex; exhausted SSH session slots retire rather than wrap. Disconnect success is an owner close request, not completed teardown. HTTPD never calls wolfSSH or waits for the SSH task.
`ssh_transport_replace_identity()` compares/reserves **service then identity before stop or storage**, holding the existing command mutex across **stop → generate/commit/publish → conditional restart**. Canonical UART0/deferred admin-SSH rotation/reset and direct security mutations share the task-bound nonreused identity reservation. Crypto/NVS run outside security locks/spinlocks. Both nonzero versions select conditional rotation (also while stopped); both zero preserve canonical semantics, with no conditional Reset.
Failed stop/timeout skips mutation and never starts again; pending owner work is not cancelled. Persistence failure after successful stop may already have disconnected clients and attempts old-identity restart if previously running. Committed replacement remains committed if restart fails. Stopped rotation stays stopped; canonical reset can recover unavailable material/start stopped SSH. Only the SSH owner frees runtime context after all slots retire, before clearing cleanup admission; start rejects orphan handles. wolfSSH copies DER into its context; caller/candidate/superseded private bytes are wiped.
SSH changes leave invoking HTTPS available, so they use the ordinary ID-dispatcher/result path, not HTTPS's self-cutting ACK gate. UI confirms both versions and all-SSH/session scope, retains stale selection and manual 15-second/no-replay flow. A failed result may represent partial effects. Verify new trust through UART0 `ssh host-key info` before updating known_hosts; no HTTPS relogin is inherently required. Browser Reset/recovery/key export and user authorized-key changes are separate, excluded from host rotation.
## Diagnostics, recovery and scope boundaries
See [admission diagnostics](web_admission_diagnostics.md), [ordinary HTTPS idle cleanup](https_idle_cleanup.md), [throughput diagnostics](web_throughput_diagnostics.md) and [legacy storage compatibility](legacy_credential_removal.md). Broker read means transport handoff, not peer receipt; capture non-consuming counters before disconnect. TLS `-0x004C` is generic NET_RECV_FAILED, not evidence of OOM. Resource minima and counter observations require attribution, not inferred causes.
Phase 8D.15's dedicated typed network-diagnostics UI/API was removed: diagnostics remain shell-based, subject to frontend policy. The unimplemented 8D.19 ordinary browser-session/native-USB control expansion was removed; existing SSH controls remain. No full shell parity, browser identity recovery/reset/export, encryption, secure boot or OTA is implied by acceptance. UART0 is the administrative recovery authority; native USB is binary-transparent, network-independent UART1 access. Neither permits bypassing the broker's single writer or recalling already-admitted work.
+40
View File
@@ -0,0 +1,40 @@
# Web administration acceptance
## Phase 8D.22 sign-off — 2026-09-13
The user explicitly accepted the tested firmware: **“Yep, I tested the firmware thats a 8d.22 signoff.”** Phase 8D is complete for its retained scope. This supersedes earlier per-slice target-pending, parent-review and integration-acceptance gates; it does not require additional testing to establish the user's sign-off. Phase 8A/B/C were already recorded as complete and target-hardware validated in the roadmap, so [Phase 8 is complete](roadmap.md#phase-8--role-based-users-and-administrative-access--complete).
Accepted functionality comprises cookie authentication, isolated browser serial/admin terminals, typed Serial/Accounts/authorized-key/Network/Display/Broker/SSH/HTTPS settings, contextual controls, confirmed generation-safe writer/service/identity actions and retained UART0/native-USB recovery. [Current contracts](web_administration.md) define actual permissions, bounded failures and partial effects; acceptance is not a claim of unrestricted browser-shell parity.
Scope decisions remain effective: 8D.15 dedicated typed network diagnostics was removed (shell diagnostics retained); the unimplemented 8D.19 ordinary browser-session/native-USB control remainder was removed (SSH controls retained). Browser identity Reset/recovery/export was not added. Phase 9 security/production hardening is next only on a separate user request.
## Latest firmware evidence
The **prior final firmware build passed**, reporting **100,556 bytes linked RAM / 1,828,573 bytes flash**, at **160 MHz**. This is recorded prior build evidence, not a build run during documentation consolidation. Host regression suites and independent implementation reviews were previously reported passing; no new host/runtime test pass is asserted here.
Latest user telemetry, bytes:
| Sample / memory capability | Free | Minimum free | Largest block |
|---|---:|---:|---:|
| Boot internal 8-bit | 59,808 | 58,840 | 31,744 |
| Boot internal DMA | 52,052 | 51,084 | 31,744 |
| Boot PSRAM | 8,196,968 | 8,183,972 | 8,126,464 |
| Loaded after burst, internal 8-bit | 31,508 | 2,052 | 18,432 |
| Loaded after burst, internal DMA | 23,752 | 460 | 18,432 |
| Loaded after burst, PSRAM | 8,136,624 | 8,065,972 | 7,995,392 |
Loaded SSH minimum-free stack was **15,028 bytes**. The capture had two active SSH sessions across the serial/admin roles, two serial WebSockets and USB, with SSH holding the serial writer. Browser admin had been used and then closed; it was **not active in the captured loaded sample**. Web send/queue/protocol error counters were zero; SSH IO errors were zero, with one handshake failure and one session revocation retained without attributing a cause.
Latest broker/serial counters were not supplied, so these transport counters do **not** establish an exact latest zero-drop or byte-integrity result. No latest full-mix-with-browser-admin-active, individual fault-injection, exact duration, soak, cleanup-cycle or reserve-floor result is inferred. Generic SDK TLS `-0x004C` / NET_RECV_FAILED is not an OOM diagnosis. Two boot authentication failures could plausibly involve stale browser cookies, but that explanation is unconfirmed.
## Earlier acceptance retained without replaying the timeline
- M1 browser login/logout and M2 shared browser administration were explicitly accepted by the user; later Serial/account/Network presentation and legacy-credential cleanup also received scoped acceptance.
- The user explicitly accepted the combined binary WebSocket-send fix at **160 MHz, 230400 baud with the full client mix, including browser admin**. That prior acceptance stands independently of the latest capture's closed browser-admin socket. It does not imply an unreported latest exact counter comparison or soak duration. Keep the combined send and bounded failed-send isolation, not the earlier frequency-only experiment.
- Ordinary HTTPS idle cleanup was accepted as working; that is not a guarantee against all future admission failures or owner delays.
## Nonblocking follow-ups and evidence limits
The extremely low internal/DMA lifetime minima remain an unresolved transient-headroom follow-up, **not a blocker reopening 8D sign-off and not an approved reserve**. Capability pools overlap; summed per-region lifetime minima can be conservative/non-simultaneous and do not prove an allocation failure. Do not add internal and DMA numbers together or attribute an error to memory pressure without correlated evidence. HTTPD/dispatcher stack margins, peak correlation, allocation reserve policy and long-run cleanup/soak evidence remain distinct future measurements.
[Regression procedures](user_administration_tests.md#integrated-web-administration-regression-procedure) and focused test runners remain available for future changes; listing them is not evidence they all ran on hardware. Documentation-only consolidation changes no firmware, configuration, generated assets or test implementation and performs no build/upload/erase/commit. No new Phase 9 work is authorized by this acceptance.
+32
View File
@@ -0,0 +1,32 @@
# Web admission diagnostics
Current default-disabled instrumentation, not an admission fix or an allocation-failure detector. `src/web_diagnostics.{c,h}` observes public synchronous HTTPS create/close callbacks and the four serial/admin ticket/upgrade handlers. It adds no owner task, queued probe or socket-capacity change. See [ordinary idle cleanup](https_idle_cleanup.md) for the independent cleanup policy and [acceptance evidence](web_administration_acceptance.md) for user reports.
## Usage and interpretation
Use UART0 (preferred during network stalls) or authenticated admin SSH:
```text
web diagnostics clear
web diagnostics enable
web diagnostics show
```
Enable before reproducing the failed third connection. At failure, run `web diagnostics show` promptly, alongside existing `memory`/`web counters`/browser Network timing evidence; repeat the snapshot if admission remains stalled. Then `web diagnostics disable` freezes event retention (live occupancy continues updating); `web diagnostics show` prints retained history, and `web diagnostics clear` erases history/counters without changing live sockets or enable state. The setting is RAM-only and defaults off after boot. Existing browser-shell policy deliberately denies these commands, even though shared completion offers the fixed forms. There is no HTTP diagnostic endpoint.
- Six connection records are maintained from boot even with capture disabled, so enabling on an already loaded server does not mislabel existing sockets. Each successful TLS connection gets a monotonically increasing, non-wrapping, firmware-lifetime 64-bit `conn` sequence independent of fd, cookie, ticket, broker or user identity. Clear, disable and HTTPS restart do not reset it. Internal TLS object identity is used only during synchronous cleanup; no pointer is exported or dereferenced by the console.
- Snapshot output gives its boot-relative `snapshot_us`, post-TLS occupancy split ordinary/serial-WS/admin-WS and each live fd/connection sequence/open time/age. `kind=0/1/2` means ordinary/serial/admin. Ordinary includes every successful TLS socket not yet observed as upgraded, including idle keep-alives, assets/login/settings and sockets not yet used for HTTP. Classification is actual public `httpd_ws_get_fd_info()` state after upgrade-handler return, **not inferred from `ESP_OK`**. No URI string is inspected.
- The fixed 32-entry overwrite ring records successful TLS open, TLS transport-context close, and enter/result for serial/admin ticket and upgrade handlers. `t_us` is boot-relative observation time; result `dt_us` measures the underlying handler only (including its work/IO, excluding entry resource sampling); close `dt_us` is successful-TLS connection lifetime. Open/enter durations are zero. Open/result occupancy includes the connection; close occupancy excludes it. Event IDs survive clear; `overwritten` counts evicted retained records since clear. `unmatched` counts duplicate create/unmatched close; `lost` counts untrackable creates (getter failure, metadata/sequence exhaustion). Nonzero anomaly counters mean occupancy is not trustworthy as complete evidence. Counters saturate.
- `rc` is the exact handler return, **not HTTP status or ticket issuance outcome**: sending a 401/403/503 can return `ESP_OK`. Match browser HTTP status and existing rejection/issuance counters; there is no ticket-value correlation, request ID, authentication identity, header/body/query logging, or allocation-failure attribution. Upgrade success is visible in the occupancy classification. Ring overwrite or clear/toggle during an operation can leave unpaired enter/result records; do not invent a duration for a missing result.
- Each retained event samples free/largest bytes for internal 8-bit, internal DMA and PSRAM 8-bit, plus the current HTTPD task's minimum-free stack **in ESP-IDF bytes**. Capability scans run outside the diagnostic lock. Samples are sequential, not an atomic heap snapshot; overlapping internal/DMA pools must not be added. Stack watermark includes diagnostic call overhead and is not dispatcher margin. `show` does not query a live task handle: resources are historical event samples, not fresh heap values at show time. Use `memory` for current system heap.
- Console snapshots copy only local diagnostic metadata under a short portMUX, never inspect HTTPD session internals or wait for its owner. Printing occurs outside the lock. At most 32 ID-qualified rows and six live records are printed, even during churn; concurrent clear/overwrite is reported as “no longer retained”. Capture epochs reject samples crossing enable/disable/clear, and sequence checks prevent a stale upgrade result from reclassifying a reused fd. No queued diagnostic work exists, hence no outstanding probe or stale queue lifetime to retire on restart. Minimal connection bookkeeping and upgrade classification remain active while disabled; heap scans and event recording do not. Instrumentation still has CPU/static RAM cost, not zero perturbation.
## SDK audit and explicit blind spots
Audited installed PlatformIO ESP-IDF **5.5.0**, `components/esp_https_server/src/https_server.c` (`httpd_ssl_open`, `httpd_ssl_close`), `components/esp_http_server/src/httpd_sess.c` (`httpd_sess_delete`) and `httpd_main.c`. HTTPS performs synchronous TLS creation before the configured `open_fn` and `user_cb` create callback. It installs a transport-context destructor; that destructor invokes the public close callback before deleting TLS/freeing the context. HTTPD's default close closes the fd, then clears contexts, then frees its session slot. The diagnostic close therefore marks a cleanup observation, not a FIN timestamp or causal close reason. It uses the stored fd, not a getter on an already-closed socket. **Neither `open_fn` nor `close_fn` is replaced**, preserving all existing HTTPS cleanup ownership and failure behavior. Callbacks execute synchronously under the existing HTTPD lifecycle; successful stop finishes cleanup before restart, while failed/partial stop retains remaining live metadata. No asynchronous fd-only events are consumed, avoiding event-delay/fd-reuse ambiguity.
This deliberately bounded first slice does **not** measure TCP connect/accept/listen backlog, pending clients when IDF stops accepting at capacity, handshake begin/duration/failure, TLS allocation failure or aggregate lwIP socket pressure. The public configured open hook is post-TLS too; adding it would not fix these blind spots. No owner-queued client-list probe is added. Occupancy is an owner-published **successful-TLS lower bound**, not the complete HTTPD session table while a handshake is in progress. A clean **6/6** snapshot supports established-connection saturation at that instant (three WS + three ordinary is directly distinguishable); fewer than six does not exonerate admission/TLS/global socket pressure. Correlate time with browser evidence and existing secret-free TLS errors; do not call this pre-TLS tracing or claim the root cause is proven. Existing capacities, receive/send/handshake timeouts and accepted admission issue remain unchanged.
## Regression entry points and limits
`python3 tests/web_diagnostics/run.py` covers bounded metadata/ring behavior and SDK guards; `python3 tests/web_admin_transport/server_lifecycle.py` covers lifecycle composition. These are reusable host commands, not a new execution claim. Doubled TLS/scheduling and host tests cannot establish target admission latency, reserve floors or fault causes. Capture on UART0 alongside `memory`, `web counters`, browser timings and non-consuming broker/serial counters, without cookies/tickets/headers. Generic TLS NET_RECV_FAILED (`-0x004C`) and NET_CONN_RESET (`-0x0050`) are not OOM diagnoses.
+77
View File
@@ -0,0 +1,77 @@
# Web serial throughput diagnostics
## Current contract and accepted fix
Default-disabled instrumentation measures broker fan-out and binary WebSocket TX, not CPU usage, peer receipt or pure scheduler latency. The user separately accepted the combined binary header/payload-send fix at **160 MHz / 230400 baud with full mix including browser admin**. [Acceptance evidence](web_administration_acceptance.md) distinguishes that report from the latest capture and unmeasured reserves. The old frequency-only experiment is not the retained solution.
`web_httpd_ws_send_binary` is an IDF-5.5.0-pinned owner-only session-override send with a bounded 516-byte header/payload scratch copy and 512-byte payload. Generation validation and one outstanding item per slot remain. A non-full send installs a reject-only override before close/shutdown, preventing SDK automatic PONG/CLOSE from reentering TLS with different arguments after incomplete output, even if shutdown fails. No retry/replay; HTTPD owns TLS destruction. Text/control/admin retain the SDK sender. One API call does not promise one TLS record/packet or peer receipt. Keep CPU160, priorities, scheduling and 4096-byte broker/512-byte web payload bounds unless separately changing them with evidence.
## Broker accounting
`broker counters` retains global totals and adds one row per active client: generation-safe ID, type, pending bytes, output high-water mark (HWM), UART bytes considered for that client, queued bytes, read bytes and dropped bytes. `broker clients` helps map the IDs to active transports; `web performance show` supplies each web slot's broker ID.
- HWM is peak output occupancy, bounded by 4,096 bytes. `broker clear-counters` clears totals but seeds each active HWM with current pending occupancy, not zero. It does not drain queues or change ownership.
- `read` means handed to a transport, not received or rendered by a peer. Queued counts successful copies; UART counts bytes considered while the client was connected.
- Disconnected per-client rows disappear and slot/generation reuse resets them. Global counters retain disconnected traffic until cleared, including accepted-but-unread output discarded on disconnect. Thus global drops need not mean only overflow, and queued plus dropped need not equal UART fan-out after disconnect discards.
- Capture before disconnect. **Do not use `broker read` for observation:** it consumes data intended for that transport. Snapshot/counter commands do not consume serial data.
## Independent web performance capture
Use physical UART0 for the least intrusive capture. Commands are also available through the authenticated admin SSH registry. `web performance enable|disable|show|clear` is separate from admission tracing (`web diagnostics enable|disable|show|clear`) and from ordinary `web counters|clear-counters`.
Performance capture defaults disabled. Enable resumes aggregates; disable freezes aggregates; clear resets aggregates while preserving enable state. Each control operation advances a nonwrapping epoch and fences in-flight samples. Exhaustion fails closed. Slot generation and broker identity also fence reuse; this is not a disconnected-session archive.
Each active one of two fixed slots shows fd, generation, broker ID, pending/measured-pending/executing state and current-epoch `pending_age_us`. Age starts at reservation-path entry and includes an executing send. If `measured_pending=0`, zero age is unavailable, not evidence of immediate service. Disabling invalidates current-epoch pending age; capture a live `show` only if investigating a stuck queue, accepting its perturbation.
Only serial **binary TX** is measured. Text/control frames are not samples, though they can delay subsequent binary work. No payloads, passwords, keys, cookies, tickets, verifier material or other authentication secrets are retained or printed.
| Printed timing | Exact interpretation |
|---|---|
| `queue->callback-entry` | Reservation-path entry to HTTPD callback entry, timestamped before the callback takes the transport lock. Includes submission-path work, not just HTTPD queue residence; owned callbacks retired without sending can count. |
| `send-call` | Time around the actual synchronous HTTPD-owner send API call. Return is not peer acknowledgement, browser receipt or rendering. |
| `completion->first-drain-attempt-return` | Successful send-call completion to return of the first subsequent broker read attempt, including empty/error attempts. |
| `completion->next-nonempty-drain-return (includes idle)` | Completion to the next successful nonempty broker read return, possibly after empty attempts and source idle time. |
| `completion->first-attempt-nonempty-return` | Subset where the first subsequent read returns data. Excludes observed empty attempts, but does not prove backlog existed at send completion. |
Each timing reports count, sum in microseconds, integer estimated average (`sum/count`, zero for no samples) and maximum. Completion intervals are not scheduler-only: they include transport work, broker read/mutex time and intervening control-frame work, and may include idle time even in the first-attempt-nonempty subset. They do not isolate a particular task, TLS operation or network cause.
`queued_frames/bytes` counts transport reservations, including reported queue failures; `queue_errors` records those failures. `sent_frames/bytes` counts successful send-call returns. `send_errors` includes owner-context rejection, whereas send-call timings require an actual API call. `retired` records measured callbacks retired without sending. Saturating aggregates set `saturated=1`; totals and averages then cease to be reliable. Epoch fencing intentionally prevents old work contaminating a new capture, so do not demand equality across toggles or in-flight clears.
## Reproducible UART0 capture
1. Record firmware/build identity, baud/framing/flow control, source burst size, browser versions, client IDs/roles and full-mix topology. Establish all serial clients and both admin routes first. Quiet the UART source and allow queues and connection activity to settle. Do not reconnect/login during the trace.
2. Optionally stop independent admission tracing before the timed capture. Then reset in this order, while quiet:
```text
web diagnostics disable
web performance clear
web performance enable
broker clear-counters
serial clear-counters
web clear-counters
```
The first command is optional; record whether admission tracing was enabled. Resets are sequential, not an atomic cross-service snapshot.
3. Send the known burst once, stop the source and wait for transport queues to drain. Avoid repeated console/status printing during the burst. A quiet final broker pending count of zero alone does not prove browser receipt; retain peer byte counts too.
4. Stop performance capture first, then capture all counters **before disconnecting any client**:
```text
web performance disable
web performance show
broker counters
serial counters
web counters
broker clients
```
Disable already prints the performance snapshot; `show` is an explicit repeatable frozen-aggregate record. Keep connection counts and source/peer totals with the sample.
5. Only after saving evidence, change to one browser, keeping the other full-mix participants and serial settings equivalent. Quiet/settle and repeat the complete reset/burst/drain/stop/capture sequence. Do not compare a fresh capture to lifetime counters.
6. Separately compare equivalent performance-enabled and performance-disabled bursts with fresh ordinary counter resets. Keep performance disabled for the latter; do not treat retained performance aggregates as that run's measurements. Keep admission tracing state equal and record it.
At 230400 baud, 8N1, 4,096 bytes represents approximately **177.8 ms** of continuous input retention from an empty broker queue, ignoring flow-control pauses. Compare per-client drops/HWM with latency maxima against this scale, not as a hard deadline or proof of cause; occupancy, idle gaps and timings cover different boundaries. For future regressions, gather per-client attribution and controlled comparisons before changing buffers, priorities, scheduling or CPU.
## Resources and regression references
Two fixed diagnostic records plus nonwrapping epoch/timestamp/slot fences and broker HWM fields add bounded storage, no new instrumentation allocations/tasks/queues/payloads. Disabled is not zero overhead: gate branches remain and broker occupancy/HWM is always active. Enabled timing and short aggregate locks have runtime costs not established by host tests. The combined-send local scratch adds HTTPD stack use; actual reserve remains a target measurement.
`tests/session_broker_diagnostics/run.py` covers counters and generation-safe management; `tests/web_serial_performance/run.py` covers production send/drain paths, epochs, retirement, SDK wire compatibility and failed-send/control-reply isolation. `tests/admin_ssh_policy/run.py` covers SSH-allowed/browser-denied tracing commands. Prior focused/broad host validation and firmware builds passed; no tests were run during documentation consolidation. These harnesses do not prove real TLS/scheduler overhead, peer-byte integrity or long-soak behavior. Use the capture procedure above for future attribution, retaining explicit workload/duration/counter provenance.
+131
View File
@@ -0,0 +1,131 @@
# Wi-Fi management-frame security update plan
Initial review date: **2026-09-16**; integration status updated **2026-09-18**. The original review was a focused documentation-only follow-up to [dependency advisory coverage](dependency_advisory_coverage.md#new-release-note-finding-wi-fi-management-frame-corruption). **At that initial review, no correction was implemented, exploit reproduced, build run, device accessed, or upgrade approved.** The fix-bearing complete IDF 5.5.3 vendor bundle is now integrated in the validated candidate; this is not radio-hardware vulnerability closure or deployment approval. See [current integration evidence](idf_candidate_integration.md#final-integration-evidence--2026-09-18) and [semantic rebase review](idf_553_rebase_review.md).
## Decision
**Prefer a complete, immutable Espressif IDF 5.5 maintenance-release bundle, integrated through a compatible pinned PlatformIO package/toolchain, over transplanting Wi-Fi archives into IDF 5.5.0.** IDF **5.5.3 is the verified fix-bearing reference candidate/minimum demonstrated release here**, not a recommendation to deploy it in preference to all later maintenance releases. The earlier coverage records 5.5.4/5.5.5; selecting a newer deployment candidate requires the same immutable provenance and compatibility gates below, not a repeat broad advisory audit.
Do not change PMF/WPA3 policy as an automatic mitigation. Do not replace only `libnet80211.a`, edit only a callback declaration, relax source guards, or overwrite the installed SDK. The vendor correction is integrated in the fresh candidate build; deployed old firmware remains exposed, and target/radio validation remains pending. PMF/WPA3 has not been weakened.
## Current applicability and trigger limits
Rechecked authoritative source `src/wifi_manager.c:315363`:
- SoftAP uses `WIFI_AUTH_WPA2_WPA3_PSK`, four clients, `pmf_cfg.capable=true`, `required=false`, `WPA3_SAE_PWE_BOTH`. AP/APSTA are real supported paths, including live fallback transitions (`set_runtime_ap_enabled`). Optional PMF is **not PMF disabled**.
- Station uses PMF capability in both profiles; mixed has WPA2 minimum/optional PMF, WPA3 requires PMF. Do not downgrade station profiles to address a demonstrated SoftAP trigger.
- Existing generated `sdkconfig.h` identifies ESP32-S3 and enables SoftAP, WPA3 SAE, SoftAP SAE, SAE H2E and SAE-PK support. This is build metadata, not proof of a running device's current mode or negotiated association.
- Architecture: the permanent Wi-Fi manager owns driver operations and bounded events; application NVS is authoritative, driver storage is RAM-only, AP policy is off/fallback/always. Working edits require explicit save. Preserve manager ownership, secret wiping and secret-free status. UART0 recovery and native USB UART1 access must remain independent of network success. Broker single-writer/multiple-isolated-observer behavior is unchanged.
The official contained fix says that when the supplicant sends an **authentication response for an already-connected station, with keys installed after a successful four-way handshake**, management encryption was selected from `bss->pmf_enable` without checking whether the frame was robust. The encryption code assumed header space that had not been allocated, causing memory corruption. The fix checks robust-management-frame status before encryption.
This supports a current-feature exposure candidate when SoftAP is active with the relevant station/key/PMF state. Radio delivery of the relevant management exchange, rather than application HTTPS/SSH authentication, is the pertinent access path (inference from the described Wi-Fi operation). The public text does **not** establish whether an attacker must know the PSK, personally complete association, or can spoof an existing station's exchange. It supplies no packet-level proof, CVSS, reliable arbitrary-code-execution claim, or exhaustive affected-mode matrix. Do not characterize this as proven unauthenticated remote exploitation, nor assume application login protects it. STA-only exclusion is limited to the described AP-response path, not a blanket clean bill for the opaque bundle.
The same vendor change also fixes an RSN-IE length/allocation mismatch, deauthentication-reason parsing, and default SAE PWE values. The project's short configured IE set has not been shown to trigger the allocation issue; do not conflate that uncertainty with the established old ABI/bundle identity.
## Official immutable provenance
Official sources fetched in this review:
1. [5.5.3 release](https://github.com/espressif/esp-idf/releases/tag/v5.5.3), also [release API](https://api.github.com/repos/espressif/esp-idf/releases/tags/v5.5.3): explicitly names the management-frame memory-corruption correction under `a3927641`.
2. [Merge commit](https://github.com/espressif/esp-idf/commit/a3927641bfd0aedfaab3514cba3d7fb01378ce4d), checked through its official commit API: **`a3927641bfd0aedfaab3514cba3d7fb01378ce4d`**. Its title emphasizes SAE defaults; the title alone omits the security detail.
3. [Contained fix patch](https://github.com/espressif/esp-idf/commit/caf4cad3b422be5c2f93afeff4cd07796a262b46.patch): **`caf4cad3b422be5c2f93afeff4cd07796a262b46`**, “Backport some wifi fixes,” with the trigger explanation. This is the merge's second parent, not a conflicting identification.
4. [Annotated release tag object](https://api.github.com/repos/espressif/esp-idf/git/tags/b31fcc7a314a44ad992b58f589f7d1d8a4fadff6): tag object **`b31fcc7a314a44ad992b58f589f7d1d8a4fadff6`** resolves to IDF commit **`2c211b236707889e8400c4dc5644dd5c4ee071e0`**. [Immutable comparison](https://api.github.com/repos/espressif/esp-idf/compare/a3927641bfd0aedfaab3514cba3d7fb01378ce4d...2c211b236707889e8400c4dc5644dd5c4ee071e0) reports ahead 195 / behind 0, establishing inclusion of the merge.
### Exact published source/ABI delta
The fix changes four paths:
| Path relative to IDF | Published change |
| --- | --- |
| `components/wpa_supplicant/esp_supplicant/src/esp_wifi_driver.h` | `wpa_funcs.wpa_ap_get_wpa_ie`: `uint8_t *(*)(uint8_t *len)` becomes `uint8_t *(*)(size_t *len)` |
| `components/wpa_supplicant/esp_supplicant/src/esp_wpa_main.c` | Matching callback implementation takes `size_t *ie_len`; assignment from `hapd->wpa_auth->wpa_ie_len` remains |
| `components/esp_wifi/lib` | Submodule `d7373a90dc3f0be841b29911e33de5f99988dbff`**`a4e903fe43bf09a95022f9802db43d39740ccc0b`** |
| `components/esp_wifi/include/esp_wifi_types_generic.h` | Two SAE PWE documentation comments record default `WPA3_SAE_PWE_BOTH`; not structure-layout changes |
The historical shared IDF 5.5.0 header and callback take `uint8_t *`; `esp_wpa_main.c` registers the callback for SoftAP. The callback slot/pointer size need not change for this to be an ABI break: the width and interpretation of the pointed-to output change (one byte versus a `size_t`, four bytes on ESP32-S3). Mixed old/new caller and callee can corrupt storage or leave an incorrect length. Casting the callback does not fix the contract. Both sides, including the opaque caller, must agree.
The visible C edits are the length correction/interface marker. **The management-encryption fix is in the vendor binary update, not a public C hunk that can be copied into this application.**
### Bundle identity: baseline, fix point, release point are different
- Historical shared installed baseline matches Wi-Fi submodule **`8a1b7bbc00e895d040c5c9a6fb9d1db2bbfc7958`** from IDF v5.5, not the fix's immediate predecessor `d7373a90…`.
- The exact fix-point bundle is **`a4e903fe43bf09a95022f9802db43d39740ccc0b`**.
- The complete 5.5.3 release points to **`e0befaa593277b4e80726079fbd521b4681754c2`**, verified again at the immutable release commit. [Wi-Fi comparison](https://api.github.com/repos/espressif/esp32-wifi-lib/compare/a4e903fe43bf09a95022f9802db43d39740ccc0b...e0befaa593277b4e80726079fbd521b4681754c2) reports ahead 3 / behind 0. Do not call the fix-point bundle the final 5.5.3 bundle.
Calculated Git blob SHA-1 (`blob <length>\0` plus bytes) of **all seven installed S3 archives** and compared against official metadata for [baseline](https://api.github.com/repos/espressif/esp32-wifi-lib/contents/esp32s3?ref=8a1b7bbc00e895d040c5c9a6fb9d1db2bbfc7958), [fix point](https://api.github.com/repos/espressif/esp32-wifi-lib/contents/esp32s3?ref=a4e903fe43bf09a95022f9802db43d39740ccc0b), and [release point](https://api.github.com/repos/espressif/esp32-wifi-lib/contents/esp32s3?ref=e0befaa593277b4e80726079fbd521b4681754c2):
| Archive | Installed = baseline Git blob | Fix-point Git blob | 5.5.3-release Git blob |
| --- | --- | --- | --- |
| `libcore.a` | `ec2e76caad4c29ee92ec45432e0dc3bf946ea4c7` | `af63b0f8254bde084b2f474cdba1c1d63b4ae750` | `9f7b14a8bf6eec64973da8adc65d35b5ba9bee49` |
| `libespnow.a` | `d4925dc7f73173077e8ed58abbbe5a59b5bb7be5` | `da0537c3f754a9d638fbecd4f4d806bfa66316b4` | `132b4f67e339ca2081d2add91c14eefa39476ff9` |
| `libmesh.a` | `5cd43bf5a0a0388fb6f093a154401f00227d9570` | `6ae30c90ba59ab949e98db89b6b51daab434a5a0` | `2e9dc1c8c7afbf033337b4175032e9b1161e3262` |
| `libnet80211.a` | `6ee20bec142638dc0a442b9642de9fa62db6ddd0` | `8ce8a2a6a9a753e31508bd609bf0a0d1d44c332f` | `2800d447ec385d33869373696ba8191292647694` |
| `libpp.a` | `c9fc98fe529c9ff2891839fdb9a41b1189c03c49` | `536fd25e30a1be76ff122d93e7481f1da22e6892` | `8944bcad7371621045f376cf74c62fde6f368cbb` |
| `libsmartconfig.a` | `31518eb9336f07de14b4a71c0389217a54ed3ec7` | `19e8274e0961fdf88351a0dec6e0d696b8ee2b94` | `4dc759e25617aa00b9e12887fd092a1d5780a170` |
| `libwapi.a` | `0604ff76aa9134b475daf08496e03350d5ef8f09` | `e43863a22e93990b8a4deb7c4efc8e4c27566789` | `65655b6feab0572a6e8a1200946d53a21f3f4722` |
All historical shared-SDK archives matched baseline; all differ from both newer bundles. This is artifact identity, not proof that every archive is linked or contains the defect. Remote binaries were **not downloaded during the initial review**. Later candidate archive download/verification and complete Wi-Fi/PHY/coexistence/supplicant package comparisons are recorded in the integration/rebase reviews; the candidate uses the release-point column, not this old baseline. Git IDs are provenance identifiers, not independently measured remote SHA-256 digests or a vendor signature verification.
The release API advertises the submodule-inclusive `esp-idf-v5.5.3.zip`, asset ID **357881088**, SHA-256 **`d16e6b57b1df1a523aff6a1d0ef2f99cf058cb71e73f694429769eaaea171428`**. This is vendor-published metadata, not a locally verified download. The release is marked `immutable=false`; therefore pin the resolved commit/submodules and verify artifact hashes, not merely a tag URL. Espressif warns that GitHub's automatic source archives omit submodules; those are not complete SDK inputs.
## PMF/WPA3 mitigation assessment
Both the [v5.5 documentation source](https://raw.githubusercontent.com/espressif/esp-idf/v5.5/docs/en/api-guides/wifi-security.rst) and [immutable candidate documentation](https://raw.githubusercontent.com/espressif/esp-idf/2c211b236707889e8400c4dc5644dd5c4ee071e0/docs/en/api-guides/wifi-security.rst), plus the installed type header, establish:
- `pmf_cfg.capable` is deprecated, effectively true internally. Setting it false is **not a supported PMF-off mitigation**.
- `required=false` permits optional PMF; it does not disable it.
- `esp_wifi_disable_pmf_config()` is the documented optional-PMF disable API. Disabling PMF on WPA3 or WPA2/WPA3 mixed SoftAP returns an error.
- WPA3 mandates PMF. WPA2-only mode by itself still does not prove PMF is disabled.
**No issue-specific official workaround was found in the inspected release/fix text.** The API documentation explains general configuration, not an endorsement that disabling PMF safely mitigates all defects in this change. The trigger supplies a rationale that actually eliminating `bss->pmf_enable` could avoid the described encryption path; the opaque implementation and lifecycle have not been proved to honor that invariant across existing associations/restarts.
Consequently, a WPA2-only plus explicit PMF-disable implementation is at most an **unapproved conditional workaround candidate**. It would remove SAE benefits and management-frame protection, require explicit owner acceptance, documented threat trade-offs, correct manager-owned stop/reconfigure/start sequencing, checked API results, and target evidence that negotiated PMF cannot reappear across APSTA/fallback transitions. It would not repair the RSN-IE allocation defect. Do not implement it as a silent downgrade, global WPA3 Kconfig removal, or station-profile change.
If operational containment is urgently required before an update, the owner may explicitly choose existing AP-off policy (removes the described AP response path) or Wi-Fi-off (removes radio service), accepting lost network/fallback access. These are feature-withdrawal containment options, **not vendor-certified workarounds or a source fix**. Preserve and verify UART0/native USB access first; do not automatically persist policy changes. No containment action was taken here.
## What a coherent replacement entails
### Preferred: complete vendor maintenance release
Use all IDF source, private/public headers, Wi-Fi/PHY/coexistence libraries and other submodules from one resolved release, with its toolchain and Python/build requirements. Do not install final-release blobs alongside fix-point-only C edits or mix two release revisions. Preserve the application security policies separately through audited overrides.
Current integration disposition (supplied parent evidence, 2026-09-18):
| Input | Current state | Remaining boundary |
| --- | --- | --- |
| Root `platformio.ini` | Platform 6.13.0, framework 3.50503.0 / IDF 5.5.3, Xtensa and RISC-V 14.2.0+20251107 | Exact version pins, not complete immutable root dependency closure; default root build timed out during installation at 200 seconds before compilation |
| Isolated `app-validated` | Fresh build PASS; 95,552 B RAM / 1,749,493 B flash (+1,212 / 19,408 B versus historical 94,340 / 1,768,901 B) | Linked size is not runtime reserve |
| Protected corrections | Nine C sources plus forced header; per-entry semantic rebase, five new signed WS receive checks; 982 cases / 10 mutation checks | No original correction removed as superseded; retain exact fail-closed guards |
| Actual build/host validation | Explicit candidate SDK/core/build with interop and web performance PASS 24/24; source equality 3,237 files, identical pre/post hash recorded in [validation](phase9_validation.md#current-candidate-execution--2026-09-18) | Not radio-hardware vulnerability closure or full target acceptance |
| Radio delivery | All packaged Wi-Fi/PHY/coexistence/supplicant files match locked framework archive; candidate callback is `size_t *` | Not independent opaque-code correctness or recursive upstream submodule provenance |
| Notices | Nine entries semantically rebased, 66 unchanged, 75 total; 36 fixtures PASS; two actual bundles each 77 files / 4,433,930 bytes | Recipient/source/legal clearance pending |
The completed [semantic rebase review](idf_553_rebase_review.md#3-per-entry-semantic-disposition) covers candidate originals, not only Wi-Fi: HTTPS cleanup/private-key release, HTTPD scratch/null-read handling, server-local TLS policy, DHCP bounds, TLS EMS failure, X.509 allocation failure; retain/revalidate wolfSSH password/parser/ordering/ABI changes and wolfCrypt settings. Mark each correction **retained, rebased, or superseded with source/test evidence**. Upstream fixes do not automatically supersede local lifetime/policy additions in the same source. Also retain silent-panic/no-coredump and heap-wipe policy guards. The durable architecture's older four-correction summary is not the complete current inventory; the current generator and code map are authoritative.
### Contingency: vendor-supported backport onto 5.5.0
The smallest **published delta against the fix's own parent** is the four-path change above. The smallest **proven safe delta against this project's 5.5.0** is **not established**.
A candidate backport must at least pair both callback changes with one complete ESP32-S3 Wi-Fi archive set from the same vendor revision, retain the vendor patch/provenance, and establish compatibility with all private Wi-Fi headers, OS adapter tables, supplicant structures/callbacks, PHY/coexistence interfaces, configuration ABI and toolchain. All seven S3 archives form the conservative replacement set; do not mix old optional archives with new ones simply because current linking omits them. This minimum set is necessary for coherent provenance, **not sufficient proof** of cross-baseline compatibility.
Ask Espressif for a supported 5.5.0 backport bundle or an explicit compatibility statement with its required source/header/library/toolchain prerequisites, confirming both management-frame and IE-length corrections. The immediate-parent blob pointer differs from baseline; successful linking alone cannot establish binary layout/calling-contract compatibility. Without that evidence or a complete audited dependency closure, choose the full-release path rather than treating the two C signature edits plus blobs as approved.
## Implementation plan history and remaining acceptance
Steps 14 below preserve the original plan: package selection, isolated preparation, override rebase and fresh candidate build/host checks now have the evidence above. Complete immutable dependency closure is not claimed. Steps 56 remain acceptance/release gates; historical “no code change yet” language is not a new blocker.
1. **Compatibility/provenance gate first, no code change yet.** Resolve one deployment release and PlatformIO delivery combination. Record immutable SDK commit, recursive submodule pins, package/toolchain identities and SHA-256 manifests. Confirm vendor inclusion of the fix. Obtain missing packaging/ABI evidence; if unavailable, report the blocker instead of guessing a framework URL or transplanting archives.
2. **Prepare isolated inputs after approval.** Do not modify the user's shared installed SDK. Obtain complete vendor inputs in a dedicated location, verify provenance/hashes, and compare only relevant integration surfaces and protected-source entries. Keep existing managed components pinned where compatible; explicitly review any resolver-required changes. Review license/notice/source-delivery updates for new radio/SDK artifacts.
3. **Rebase security contracts.** Implement a reviewed per-entry disposition and exact new source pins, retain fail-closed guards, and verify every generated override/forced header reaches the actual targets. Add a bundle-consistency check for the selected SDK and archive identities so an old/new mixed bundle fails deterministically. Do not enable unrelated features, regenerate web assets, migrate credentials, or alter partitions.
4. **Build/host gates in the later implementation task only.** Clean candidate build with the selected toolchain; inspect linked archive paths/map, generated configuration and actual compilation inputs. Run SDK override, crypto, parser, ordering/interop, authentication/protocol, build-policy and notice validations as applicable to the resolved input changes. Record sizes and compare resource budgets; a host pass is not radio validation. Existing historical passes do not validate this candidate.
5. **Target gates under explicit device authorization.** Exercise WPA2 with/without negotiated PMF and WPA3 SoftAP; authenticate/reassociate after keys are installed; cover PMF optional/required behavior, four clients, disconnect/reconnect and AP/STA/APSTA/fallback transitions. Obtain vendor regression guidance or an authorized isolated-radio reproduction for the exact trigger; ordinary reconnect tests alone do not prove vulnerability closure. Stress concurrent HTTPS/WebSocket/SSH and verify bounded recovery, heap/stack reserve, queue behavior, no secret/crash-memory disclosure, and unchanged broker isolation. Verify UART0 recovery and native USB UART1 operation while Wi-Fi fails/stops/restarts. Include persisted-config reboot tests without erasure.
6. **Release gate.** Keep PMF/WPA3 security at least unchanged. Record exact artifacts and test evidence, retain a controlled recovery image and configuration backup procedure, and mark the old image as still exposed rather than calling rollback a security fix. No flash erase, upload, pin changes or deployment until separately authorized. Update durable project memory only when implemented contracts/ownership genuinely change.
## Open evidence and review boundary
- **Resolved:** official fix IDs/description; exact visible ABI delta; all seven installed S3 archives match baseline; distinct fix and final-release bundles; release/fix ancestry; current application configuration; PMF-disable restrictions; exact-IDF/hash guards; recommended versus installed toolchain mismatch.
- **Current resolved integration:** official PlatformIO 6.13.0 / IDF 5.5.3 delivery and exact toolchain selection, semantic override rebase, fresh candidate build and 24/24 host validation, whole packaged radio-component equality and notice rebase.
- **Still unresolved:** complete immutable ancillary/tool/Python/managed dependency closure; independent PHY/coexistence upstream submodule provenance; opaque binary implementation correctness; packet-level attacker requirements; target/runtime/resource evidence and deployment acceptance. A 5.5.0 transplant remains unproved and was not selected.
- A follow-up GitHub API request for candidate `components/esp_phy/lib` returned **HTTP 403 rate limit exceeded**. The sequential metadata query stopped there, so PHY/coexistence pins were not established; no inference was drawn from that failure. Already completed Wi-Fi/release/ancestry queries succeeded. Official raw documentation remained available. Do not treat this partial metadata boundary as a compatibility clearance.
- Historical initial-review validation only: read-only local source/package/config inspection; local seven-archive Git-blob hashing; official patch/release/tag/content/comparison/toolchain/documentation reads. No broad repeated dependency audit, binary download, PlatformIO invocation, build, test suite, device operation, configuration edit, or asset generation. Documentation links/provenance do not constitute signed-vendor attestation, exhaustive security certification, or Phase 9 sign-off.
+192
View File
@@ -0,0 +1,192 @@
# Phase 9D — wolfSSL / wolfSSH advisory review (partial)
## Implementation addendum — 2026-09-16
**Xtensa small-math mitigation implemented; the broader review and security sign-off remain open.** Root `CMakeLists.txt` defines `CURVE25519_SMALL` and `ED25519_SMALL` before component parsing. `cmake/wolf_crypto_policy.cmake` propagates a forced-include resolved-settings guard PUBLIC from wolfSSL to consumers, including wolfSSH/application code. `cmake/wolf_crypto_policy.h` requires both enabled small implementations, rejects `WOLFSSL_CURVE25519_BLINDING`, and rejects enabling Curve448/Ed448 without review. This follows PR 9275's small-math policy for the enabled Xtensa algorithms, with consistent library/consumer production flags and ABI-sensitive layouts. **Blinding is not enabled with small X25519**: wolfSSL 5.8.2 excludes/rejects this combination; do not force it back on or present the historical blinding observation below as current policy.
**Parser corrections implemented:** `tools/security_overrides.py` extends the existing hash-pinned wolfSSH generated source (now eight C source overrides plus one header overall). The PR892 subset bounds `DoIgnore`/`GetSkip` and service-string reads, accepts boundary-empty skips, rejects zero-capacity `GetString`, and preserves the old strict service-name length limit. The PR881 subset rejects channel-window addition overflow without changing the window. The PR880 subset changes both ECC/Ed25519 key/signature label comparisons to short-circuit OR. Local framing corrections bound ECC r/s reads to the declared sub-blob and require exact inner/outer consumption; Ed25519 also requires exact outer consumption. Valid framing and crypto/digest/message construction remain unchanged; formerly tolerated malformed labels/trailing bytes reject. Existing password bounds/wiping and async-pending retention remain intact. See the [parser contract and deferred scope](../tests/wolfssh_parser_contract/README.md); these are subsets, not complete PR backports. The [finite remaining SSH review](ssh_parser_remaining_review.md) is complete: bounded exact CHANNEL_FAILURE recipient parsing (fatal policy retained), exact `ssh-userauth` service validation, and exact length/byte dispatch for all nine channel-request names are implemented. Unknown-request/trailing-payload behavior is preserved. PR899 client key skips are unchanged and blocked by current server role/ordering; PR918/919 forwarding is disabled. The inspected generic signature caller trace found no attacker-selected short-digest/OID path; generic APIs remain unpatched. These are profile-specific dispositions, not exhaustive parser/library safety; revisit on caller, feature, KEX or source changes.
**Crypto validation implemented:** PUBLIC `WOLFSSL_VALIDATE_ECC_IMPORT` and `WOLFSSL_ECDHX_SHARED_NOT_ZERO` enable existing upstream P-256 import validation and X25519 all-zero-result rejection. The guard rejects missing checks and reviewed validator-disabling/hardware-stub configurations. Strict production checks confirm the effective flags without candidate injection. The [key-validation review](ssh_key_validation_review.md) traces the previously missing unauthenticated P-256 KEX point check and low-order X25519 inputs that pass the old precheck. Current raw SSH signature callers supply locally derived full digests; no current short-digest/OID-confusion trigger was found. This does not backport generic PR10131 API hardening or demonstrate an exploit. Import validation adds CPU/allocation cost requiring target measurement.
Supplied parent build evidence: `pio run` **PASS**, **94,340 B linked RAM / 1,768,901 B flash**, unchanged RAM / **+200 B flash** versus 1,768,701 B. Final parent results: **all seven suites PASS** — ordering `--interop` (8,028 checks, seven rejected mutations, 12 exact-256-KiB sessions with clean channel close/transport EOF), SDK overrides with actual `--build-dir` registration, auth (135 cases), protocol, strict crypto, notices (30), and parser (3,258 cases × two modes plus channel profiles; 11 + 18 + 2 rejected mutations). Interop's unsandboxed approval was solely for local AF_UNIX sockets; no remote network or device operation. See [dated evidence and limits](security_hardening.md#ordering-hostbuild-evidence--2026-09-16). These are supplied results, not build/test reruns by this documentation update or runtime-headroom evidence.
**Restricted ordering correction implemented for CVE-2025-14942; not a full upstream backport or advisory/phase sign-off.** The finite parser/client/generic-caller questions are dispositioned in the linked report; broader advisory coverage, whole-phase target validation and [release delivery/source/legal gates](release_packaging.md#separate-work-before-distribution) remain open. Offline notice assembly is implemented, not distribution clearance. No dependency upgrade or device operation was performed. Phase 9 is not complete or production-ready.
### Restricted ordering correction and remaining gates
The earlier temporary attempt is superseded by the [implemented restricted-profile correction and prerequisite disposition](../tools/wolfssh_order/README.md). wolfSSH remains pinned to **1.4.20** with the existing **Curve25519-SHA256 / ECDH-P256** KEX profile; DH/GEX/PQ widening is rejected. Independent SELF/PEER keying bits, exact nonzero expected-message tracking and service/authentication phase gates reject wrong-direction, premature and duplicate traffic. Receive expectations are separate from send-side rekey fences. Pre-peer-KEXINIT in-flight traffic remains legal when only SELF initiated rekey.
`SendNewKeys` queues one packet under the old sending keys and installs new sending keys; SUCCESS or WANT_WRITE clears SELF, retaining PEER and its expected NEWKEYS. Existing flush paths finish the same buffered packet without resending NEWKEYS. **EXT_INFO is intentionally disabled**, rather than adding a pending extension continuation: no `ext-info-c`, no outgoing EXT_INFO, incoming EXT_INFO rejected, `sendExtInfo`/`extInfoSent` remain zero. There is **no `server-sig-algs` advertisement** now; the KeyAccepted setter does not produce that wire extension. RSA-SHA2 discovery/RSA user-key interoperability is not claimed.
The executable consolidated edits are [delta.json](../tools/wolfssh_order/delta.json), not all hunks of PR793/819/840/855/921. [provenance.json](../tools/wolfssh_order/provenance.json) records exact archived patch byte hashes, source URLs and full embedded commit IDs; preserve those archives rather than relying on mutable PR responses. Original source/header hashes are pinned, upstream notices retained, and generated wolfSSH files carry the **2026-09-16** ordering modification/provenance notice. There are **eight C overrides plus one generated `wolfssh/internal.h`**. CMake propagates the ABI overlay BEFORE PUBLIC and as a PUBLIC forced include, with a stale-header guard and configure/compiler dependencies. Joined `-include/path` arguments preserve both ordering and crypto forced headers through PlatformIO sorting/deduplication; the adapter regression exercises a real Xtensa consumer and a failing split-option mutation.
Review found a misplaced EOF guard; it is now corrected in `SendChannelEof` before lookup/serialization/`eofTxd` mutation. The extra `SendChannelExit` guard remains intentional local hardening, not PR793's EOF hunk. Follow-up verification found no scoped blocker. Supplied ordering evidence: **8,028 checks and seven rejected mutations**, including actual EOF/shutdown/exit-status rekey fences.
The initial host interoperability run failed a close race despite printing `INTEROP PASS` early; that output was not successful completion. The corrected harness waits for peer channel close and transport EOF, uses a local fd-passing proxy, independently owns/reaps the server, and requires both process exits to be zero. Final agent evidence: **36/36 repeated OpenSSH 10.2p1 sessions**, each exact **256 KiB** binary echo, with **ten** completed exchanges for client-rekey cases or **two** for fragmented server-rekey cases, clean exits and no EXT_INFO. See the [test contract, harness diagnosis and limits](../tests/wolfssh_order_contract/README.md). This establishes bounded host interoperability, not general shutdown correctness or device behavior.
Official registry queries for wolfSSH **1.5.0** and wolfSSL **5.9.2** returned **404 on 2026-09-15**. Upstream tags exist at wolfSSH commit `8643d7be841184f766374e3b0ed68ced6391543c` and wolfSSL commit `ac01707f552c611fbd135cc723b2682b3e7f80f2`; tag existence is not managed-component availability or ESP compatibility. This is supplied query evidence, not a fresh network check by this documentation update.
Remaining gates: target cleanup/disconnect during rekey, no-EXT_INFO compatibility with intended clients, initial KEX/rekey under load, and stack/heap/timing measurements during whole-phase validation. Broader advisory coverage and release-specific source/legal/recipient delivery remain open; finite parser review and notice assembly are no longer pending implementation. Any future upstream upgrade still needs isolated packaging/compatibility evaluation, coherent source/header review and explicit rebasing of source overrides and version/callback contracts while preserving password/parser/crypto protections. The restricted correction is not a full wolfSSH 1.4.22/1.5.0 backport, dependency upgrade, or phase sign-off.
## Historical pre-mitigation research baseline — 2026-09-15
**The remainder retains the original pre-mitigation research evidence. “Current” macros, generated hashes, priorities and “not applied/tested” statements below describe that historical snapshot, not today's implementation. The addendum and linked key-validation review supersede the scoped small-math, parser, ECC/X25519 and ordering status claims. Restricted ordering is implemented; its target/compatibility gates remain open; the [finite remaining parser review](ssh_parser_remaining_review.md) supersedes historical deferred PR899/service/client/generic-caller questions, without certifying dormant dependency code.**
Review date: **2026-09-15**. Read-only external research and local applicability inspection; stopped at the user's requested handoff. **Not a completed security review or release clearance.** Only this new report was written. No dependencies, sources, generated inputs, or parent documents were changed; no build, hardware test, network exploit, or public PoC was executed.
## Release decision / current-path priorities
1. **Block security sign-off pending mitigation of CVE-2025-12888.** Current SSH advertises X25519 on Xtensa, and actual compiler preprocessing confirms the affected non-small implementation. Upstream recommends the small implementation; existing blinding is not evidence that this separate compiler/architecture issue is resolved. Exploitability on this precise GCC/optimization/device combination was not measured.
2. **Block sign-off pending a reviewed wolfSSH message-order correction.** CVE-2025-14942 is critical for clients; upstream explicitly recommends its fix for servers because the same defect exists, without identifying a specific server attack. The generated local server state machine lacks the fix. Do **not** report demonstrated server password disclosure or authentication bypass from this evidence.
3. **Close current-path parser gaps before sign-off.** Upstream wolfSSH PR 892 fixes unchecked SSH_IGNORE/service-string parsing still present in the generated source. These are security-relevant malformed-input handling defects, not assigned CVEs in the inspected release notes. Actual out-of-allocation access/exploit impact remains unproven: packet padding and enclosing receive-buffer invariants need auditing. Phase 9C's password fix does not fix these handlers.
4. **Keep ECC validation and other non-CVE hardening open.** Current ECC import lacks `WOLFSSL_VALIDATE_ECC_IMPORT`; 5.9.1 release notes explicitly recommend this flag for older versions. Whether the SSH ECDH path already performs equivalent validation before scalar multiplication was not resolved. Do not call this a confirmed invalid-curve vulnerability.
Smallest proposed mitigation for item 1: enable `CURVE25519_SMALL` consistently for library and consumers through project-owned compile policy; upstream PR 9275 also enables `ED25519_SMALL`, `CURVE448_SMALL`, and `ED448_SMALL` on Xtensa. For enabled algorithms, follow that upstream policy rather than assume X25519 blinding suffices. Check the effective blinding/small combination, ABI, compile guards, performance, and real SSH interoperability. This was **not applied or tested**.
Item 2 is **not a safe one-line patch**. PR 855 changes `internal.c`, handshake layout in `wolfssh/internal.h`, message ranges, expected-message tracking, and logging; 1.4.20 also predates intervening rekey changes. A backport needs the coherent library/header change set, audit of prerequisites, and later PR 921 follow-up noted in 1.5.0. Prefer evaluating **wolfSSH 1.5.0 + wolfSSL 5.9.2**, the newest stable releases returned by the queried APIs, rather than merely reaching the minimum fixed release. This is a candidate pair, **not verified ESP managed-component availability or compatibility**. Any upgrade requires rebasing exact-hash Phase 9C overrides, auth/version guards, callback changes (including keyboard auth), and contract tests; do not blindly repin.
For item 3 the smallest candidate backport is the bounded `GetSkip`/`GetString` handling from PR 892, including necessary helper semantics, plus regression cases for truncated/oversized/wrapping lengths. Preserve Phase 9C password framing and wiping. No backport has been proven safe by this report.
## Local evidence and effective policy
- `dependencies.lock`: `wolfssl/wolfssl` **5.8.2~1** (upstream **5.8.2**), component hash `4d619e882c19d967bbaa53302e3bd2bdb8c611b5efb13302171aace809fccfdf`; `wolfssl/wolfssh` **1.4.20**, component hash `24d623360c07374a90b1ade8d1218b24bb7b661fd51ace9135dccf510a338927`.
- Actual database: `.pio/build/esp32-s3-devkitc-1-n16r8/compile_commands.json`. Replayed four actual compiler commands with `-E -dM`, removing compilation/output/dependency-write flags, capturing stdout only: wolfCrypt `ecc.c`, `curve25519.c`, `random.c`, and generated wolfSSH `security_overrides/wolfssh_internal/internal.c`. All four preprocessing invocations returned 0. This is current compile-policy evidence, not proof the flashed binary matches it.
- Compiler: `xtensa-esp32s3-elf-gcc`, `__GNUC__=14`, `__GNUC_MINOR__=2`, `__XTENSA__=1`; representative wolfCrypt commands use **`-Og`**.
- Generated wolfSSH input SHA-256: `1c04d26d46f7bef61eefcf0b78c43742662001bf6054ad2383500c9063c62494`. `tools/security_overrides.py` pins original `internal.c` SHA-256 `81ff1f9166708abd5c2911e9fe57c0aee01c88b5d3f68c909ee8a856d37f36a9`; edits bound both password lengths with `GetSize`, prevent malformed new-password framing reaching the callback, and wipe the checked method suffix. No message-order or IGNORE/service parsing correction appears in those edits.
- `src/ssh_protocol_policy.c`: KEX `curve25519-sha256,ecdh-sha2-nistp256`; host key `ecdsa-sha2-nistp256`; ciphers AES-128/256-GCM; MAC advertisement HMAC-SHA256; user-key advertisement Ed25519/P256. Database authorization remains separate from advertisement.
- `src/ssh_transport.c`: creates `WOLFSSH_ENDPOINT_SERVER`; sets authentication callbacks, explicit keyboard rejection, shell acceptance, and exec/subsystem rejection. Project memory identifies wolfCrypt as SSH crypto, **not the HTTPS provider**. However, **`WOLFCRYPT_ONLY` and `NO_TLS` are absent** in the actual macros: “used only for crypto” must not be mislabeled “TLS compiled out.” No duplicate IDF/mbedTLS advisory assessment is made here.
| Area | Effective observations | Consequence |
| --- | --- | --- |
| Math | `USE_FAST_MATH` present; `WOLFSSL_SP_MATH`, `WOLFSSL_SP_MATH_ALL`, `WOLFSSL_HAVE_SP_ECC`, `WOLFSSL_HAVE_SP_DH`, `WOLFSSL_SP_NONBLOCK` absent | TFM, not SP. SP-specific release fixes are not automatically current-path findings. |
| DH | `NO_DH` present; generated SSH also has `WOLFSSH_NO_DH` | Finite-field DH and SSH DH-GEX fixes are not current negotiated features. ECDH is distinct and remains enabled. |
| ECC | `HAVE_ECC`, `ECC_TIMING_RESISTANT`, `HAVE_ECC_CHECK_KEY` present; `WOLFSSL_VALIDATE_ECC_IMPORT`, `USE_ECC_B_PARAM` absent; `HAVE_ECC_CHECK_PUBKEY_ORDER` appears in `ecc.c` after its internal includes | A compiled key-check implementation is not proof callers invoke it. `ecc.c:1099310996` gates import-time checking on the absent validation flag. |
| X25519 / Ed25519 | `HAVE_CURVE25519`, `HAVE_ED25519`, `WOLFSSL_CURVE25519_BLINDING` present; `CURVE25519_SMALL`, `ED25519_SMALL` absent | CVE-2025-12888 configuration matches; earlier blinding hardening is enabled. |
| RNG | `HAVE_HASHDRBG`, `WC_RNG_SEED_CB` present; custom generate-block/seed macros absent; `wc_SetSeed_Cb(ssh_seed)` registration observed | Project callback supplies wolfCrypt Hash-DRBG seeding. Do not confuse this with OpenSSL RAND-after-fork or claim entropy quality was tested. |
| AES / hardware | `HAVE_AESGCM` present; streaming GCM absent; ESP32 crypto port present, hardware AES/hash explicitly disabled; RSA hardware-disable macro absent | Current AES/hash software policy is intentional. Not an all-software-crypto claim. |
| Optional APIs | `HAVE_PKCS7`, `HAVE_ECCSI`, `HAVE_CHACHA`, `HAVE_XCHACHA`, `HAVE_POLY1305`, `OPENSSL_EXTRA` absent; ASN template present/original absent | Many crypto-only advisories still need feature/API filtering, not just TLS exclusion. |
| SSH features | `WOLFSSH_CERTS`, `WOLFSSH_SFTP`, `WOLFSSH_SCP`, `WOLFSSH_FWD`, `WOLFSSH_AGENT` absent; `NO_WOLFSSH_CLIENT` absent | No certificate/file-transfer/forwarding feature; client code not compile-disabled, but inspected application is server-only. |
## Priority advisory evidence table
Dates below are CVE record **publication dates (UTC)**, not reservation or release dates. Upstream severity does not by itself establish local exploitability. Source URLs are listed below.
| ID / upstream severity | Published | Affected / fixed upstream | Local applicability and evidence |
| --- | --- | --- | --- |
| **CVE-2025-12888 / Low** | 2025-11-21 | `<5.8.4`; fixed 5.8.4, wolfSSL PR 9275 | **Applicable configuration, immediate mitigation priority.** Xtensa + advertised X25519 + small implementation absent. Patch inspected. |
| **CVE-2025-14942 / Critical (client)** | 2026-01-06 | `<1.4.22`; fixed 1.4.22, wolfSSH PR 855 | **Potential server impact / upstream recommends server fix.** Generated `internal.c:587623` has old accept-state filtering, no expected-message tracking. Critical client credential-leak scenario is not this application's role. |
| CVE-2025-11625 / Critical | 2025-10-21 | `<=1.4.20` client; fixed 1.4.21, PR 840 | **Not current role.** Host-verification bypass/credential leak concerns wolfSSH clients. CNA version string is malformed (`1.4.20;0`); range taken from official release notes. |
| CVE-2025-11624 / Medium | 2025-10-21 | 1.3.01.4.20 inclusive; fixed 1.4.21, PR 834 | **Not current feature.** SFTP file-handle stack overflow; SFTP absent. |
| CVE-2025-15382 / Medium | 2026-01-06 | Release notes: 1.4.121.4.21 inclusive; fixed 1.4.22, PR 859 | **Not current feature.** SCP clean-path overread. CNA incorrectly/differently says `<1.4.21`; use conservative release-note range and retain discrepancy. |
| CVE-2026-0930 / Low | 2026-04-20 | 1.4.15`<1.5.0`; fixed 1.5.0 | **Not current platform/application.** Windows wolfSSHd terminal resize. Release notes name PR 864; CNA references PR 846 instead. Discrepancy not resolved. |
| CVE-2026-5194 / Critical | 2026-04-09 | 3.12.0`<5.9.1`; fixed 5.9.1, wolfSSL PR 10131 | **Not demonstrated on current SSH flow.** Certificate OID/type confusion absent without SSH certificates. Patch also hardens low-level ECC digest lengths, so crypto-only use is not a blanket exclusion. Inspected SSH paths derive digest sizes from hash IDs; finish tracing every current raw-signature call before closure. |
| CVE-2026-5187 / Low | 2026-04-09 | `<=5.9.0`; fixed 5.9.1, PR 10025 | **No current trigger established.** `DecodeObjectId`/unknown ASN.1 extension handling; raw SSH keys are not X.509 extensions. ASN is compiled for keys/signatures, so retain API reachability check rather than claim all ASN parsing absent. |
| CVE-2025-13912 / Low | 2025-12-11 | `<5.8.4`; fixed 5.8.4, PR 9148 | **Not reported compiler/architecture combination.** Advisory describes Clang on AArch64/RISC-V/x86_64; current GCC14.2 Xtensa. Separate from CVE-2025-12888. |
| CVE-2025-7396 / Low | 2025-07-18 | Blinding introduced 5.8.0, enabled by default in applicable 5.8.2 builds | **Existing mitigation present:** actual `WOLFSSL_CURVE25519_BLINDING`. CNA affected string `5.8.0; 0` is not a usable precise range. Not a resolution of the Xtensa advisory. |
## Post-pin release review, including changes without CVEs
| Product / version | Release-note date / GitHub publication UTC date | Scope checked |
| --- | --- | --- |
| wolfSSL 5.8.4 | 2025-11-20 / 2025-11-21 | Xtensa small implementations, Clang hardening, TLS advisories, ESP SHA changes. |
| wolfSSL 5.9.0 | 2026-03-18 / 2026-03-19 | TLS/PKCS/CRL advisories; RISC-V SP timing, KCAPI ECC import, RNG/port changes. |
| wolfSSL 5.9.1 | 2026-04-08 / 2026-04-08 | Certificate/digest checks; ECC import validation; SP and hardware-port hardening. |
| wolfSSL 5.9.2 | 2026-06-23 / 2026-06-25 | Latest stable returned; additional crypto validation, zeroization, SP/DH, PKCS, TLS and platform fixes. Unreleased master material is not a release candidate. |
| wolfSSH 1.4.21 | 2025-10-20 / 2025-10-22 | Client/SFTP CVEs; rekey PR 793, auth rejection fixes, keyboard callback changes. |
| wolfSSH 1.4.22 | 2026-01-05 / 2026-01-06 | State-machine/SCP CVEs; PRs 854 auth initialization, 857 string parsing, 856 worker/backpressure. |
| wolfSSH 1.5.0 | 2026-04-17 / 2026-04-20 | Latest stable returned; parser/bounds, callback defaults, key cleanup, KEX ordering, Windows CVE. |
Non-CVE findings are not automatically less important:
- **wolfSSH PR 892 (fixed in 1.5.0):** actual generated `DoIgnore` at line 5912 reads its length with unchecked `ato32`, ignores `len`, and advances by an unchecked peer length. `DoServiceRequest` at line 6124 also reads before checking; later service-name check does not establish four readable input bytes. Patch replaces these with bounded helpers. Password portion is already locally corrected, but the entire PR is not present.
- **wolfSSH PR 881 (1.5.0):** patch adds overflow check before `peerWindowSz += bytesToAdd`. Patch inspected; exact local function comparison was not completed. Potential availability/correctness issue, not a confirmed buffer overflow.
- **wolfSSH PR 899 (1.5.0):** patch bounds skips in `ParseRSAPubKey`/`ParseECCPubKey` and corrects `DoChannelFailure` length validation. Current role/reachability not finished; do not conflate client host-key parsing with server user-key authentication.
- **wolfSSH PR 880 (1.5.0):** release notes describe public-key type validation logical-operator correction. Actual generated `DoUserAuthRequestEcc` contains length mismatch **AND** `memcmp` mismatch checks for both key and signature type. This needs focused review with database key matching and attacker signature framing; exploit impact not established. Terminal-mode, agent, TPM, daemon changes in that PR need separate feature filtering.
- **wolfSSH PRs 918/919/902 (1.5.0):** forwarding/channel callback and payload hardening. FWD is absent; shell/exec/subsystem callbacks are registered, but default channel-open handling is not fully audited. No forwarding bypass claim.
- **wolfSSL PR 10133 (5.9.1):** ECC validation hardening. Actual `wc_ecc_import_x963_ex` calls `wc_ecc_check_key` only under absent `WOLFSSL_VALIDATE_ECC_IMPORT`. `HAVE_ECC_CHECK_PUBKEY_ORDER` is present inside `ecc.c`; its validation implementation can load curve B even without `USE_ECC_B_PARAM`. Do not infer “no point check anywhere” merely from absent B macro. Smallest candidate hardening is the upstream-recommended validation flag, pending full ECDH call trace and cost tests.
- **wolfSSL 5.9.2:** SP integer fixes, P521 SP ECDH 65/66-byte output check (PR 10702), DH subgroup hardening (PR 10560) are not current TFM/P256/no-DH features. Curve25519 all-zero-secret default checking (PR 10374), private-key clamp check (PR 10363), and broader ECC/EdDSA zeroization/validation fixes warrant follow-up. ESP port fixes in 5.9.1 PRs 10003/10080 need per-backend review; AES/hash hardware is disabled but that does not eliminate every ESP port path.
## Remaining wolfSSL CVE inventory collected
All identifiers in this section have the prefix **CVE-**. Ranges are CNA metadata, not proof of local reachability; `0` means the record supplied no meaningful historical lower bound. Every listed record was successfully queried at `https://cveawg.mitre.org/api/cve/<full-ID>`. Fixed versions and trigger descriptions came from the official security page and ChangeLog. This is a compact screening inventory, **not completed per-patch validation**.
| IDs | Published | Affected range / fixed | Current-feature screening |
| --- | --- | --- | --- |
| 2025-11931 | 2025-11-21 | `<5.8.4` / 5.8.4 | XChaCha API absent. |
| 2025-11932, 2025-12889 | 2025-11-21 | `<5.8.4` / 5.8.4 | wolfSSL TLS PSK/digest policy not used. |
| 2025-11933, 2025-11934, 2025-11935, 2025-11936 | 2025-11-21 | `[3.12.0,5.8.4)` / 5.8.4 | wolfSSL TLS1.3 not used. |
| 2026-0819 | 2026-03-19 | `[5.5.0,5.9.0)` / 5.9.0 | PKCS7 absent. |
| 2026-1005, 2026-2646 | 2026-03-19 | `<=5.8.4` / 5.9.0 | No wolfSSL sniffer/session restore use. |
| 2026-2645 | 2026-03-19 | `<5.8.4` / 5.8.4; further 5.9.0 hardening | wolfSSL TLS1.2 server not used; table headline 5.9.0 must not obscure earlier effective fix. |
| 2026-3229, 2026-3230, 2026-3547, 2026-3548, 2026-3549 | 2026-03-19 | `<5.9.0` / 5.9.0 | Compatibility certificate APIs/TLS/CRL not current SSH features. |
| 2026-3503 | 2026-03-19 | `[5.8.2,5.9.0)` / 5.9.0 | ARM Cortex-M PQ fault attack; wrong platform/features. |
| 2026-3579, 2026-3580 | 2026-03-19 | `<5.9.0` / 5.9.0 | RISC-V RV32I SP timing; wrong platform/math. |
| 2026-3849 | 2026-03-19 | 5.6.05.8.4 inclusive / 5.9.0 | HPKE/ECH TLS client not used. |
| 2026-4159, 2026-4395 | 2026-03-19 | `<5.9.0`; `<=5.8.4`, respectively / 5.9.0 | PKCS7 / Linux KCAPI ECC not current features. |
| 2026-5188 | 2026-04-10 | `<=5.9.0` / 5.9.1 | Original ASN SAN parser; current template parser, no SSH certificates. |
| 2026-5263, 2026-5264, 2026-5295, 2026-5392, 2026-5393, 2026-5447, 2026-5448, 2026-5460 | 2026-04-09 | `<5.9.1` / 5.9.1 | Certificate constraints, DTLS, PKCS7, experimental dual certs, compatibility APIs or TLS PQ paths not used. |
| 2026-5446 | 2026-04-09 | `[5.2.1,5.9.1)` / 5.9.1 | ARIA TLS not used. |
| 2026-5466, 2026-5479 | 2026-04-10 | `<5.9.1` / 5.9.1 | ECCSI / EVP ChaCha absent. |
| 2026-5477, 2026-5500, 2026-5501 | 2026-04-10 | `<=5.9.0` / 5.9.1 | EAX/CMAC >4GiB, PKCS7, compatibility X509 not used. |
| 2026-5503, 2026-5504, 2026-5507, 2026-5772, 2026-5778 | 2026-04-09 | `<=5.9.0` / 5.9.1 | ECH, PKCS7, session restore, hostname matcher, sniffer not used. |
| 2026-10097 | 2026-06-25 | `[5.7.0,5.9.1]` / 5.9.2 | AVX2 ML-KEM; wrong platform/feature. |
| 2026-10098 | 2026-06-25 | `[4.6.0,5.9.1]` / 5.9.2 | OCSP not used. |
| 2026-10512 | 2026-06-25 | `[5.6.4,5.9.1]` / 5.9.2 | X25519 x86_64 assembly; wrong implementation. |
| 2026-10592, 2026-6731, 2026-6412 | 2026-06-25 | `[3.9.10,5.9.1]` / 5.9.2 | Certificate name constraints/digest policy not current feature. |
| 2026-11310 | 2026-06-25 | `[5.8.4,5.9.1]` / 5.9.2 | Pin predates introduction; compatibility X509 absent. |
| 2026-11703 | 2026-06-25 | `[3.15.0,5.9.1]` / 5.9.2 | TLS SNI/ALPN resumption not used. |
| 2026-11999, 2026-6091, 2026-55964 | 2026-06-25 | `[5.7.4,5.9.1]` / 5.9.2 | Certificate path verification not current feature. |
| 2026-12340, 2026-55960 | 2026-06-25 | `[5.6.4,5.9.1]` / 5.9.2 | SM2 certificate/RPK TLS not used. |
| 2026-55958 | 2026-06-25 | `[5.4.0,5.9.1]` / 5.9.2 | Renesas TSIP TLS; wrong platform. |
| 2026-55961 | 2026-06-25 | `[3.15.7,5.9.1]` / 5.9.2 | Compatibility PKCS7 absent. |
| 2026-55962 | 2026-06-25 | `[5.5.4,5.9.1]` / 5.9.2 | TLS post-handshake authentication not used. |
| 2026-55967 | 2026-06-25 | `[4.8.0,5.9.1]` / 5.9.2 | GCM streaming >64GiB per message; streaming absent, not cumulative SSH session traffic. |
| 2026-6092 | 2026-06-25 | `[5.2.0,5.9.1]` / 5.9.2 | TLS Encrypt-then-MAC not used. |
| 2026-6094, 2026-7531 | 2026-06-25 | `[5.8.0,5.9.1]` / 5.9.2 | PKCS7 / TLS PQ hybrid not used. |
| 2026-6291 | 2026-06-25 | `[3.9.10,5.9.1]` / 5.9.2 | PKCS7 RSA padding oracle, not SSH raw key authentication. |
| 2026-6325 | 2026-06-25 | `[4.8.0,5.9.1]` / 5.9.2 | TLS signature-list setup not used. |
| 2026-6329 | 2026-06-25 | `[3.10.0,5.9.1]` / 5.9.2 | PKCS12 MAC verification not a current SSH workflow. |
| 2026-6330 | 2026-06-25 | `[5.7.4,5.9.1]` / 5.9.2 | ARM64 ML-KEM; wrong platform/feature. |
| 2026-6331, 2026-6678, 2026-7511 | 2026-06-25 | `[3.15.5,5.9.1]` / 5.9.2 | EVP HMAC / PKCS7 APIs not used. |
| 2026-6450 | 2026-06-25 | `[4.3.0,5.9.1]` / 5.9.2 | CRL not used. |
| 2026-6679 | 2026-06-25 | `[5.4.0,5.9.0]` / 5.9.1 | DTLS not used. Listed under 5.9.2 but narrative says already fixed 5.9.1. |
| 2026-6681 | 2026-06-25 | `[3.10.0,5.9.0]` / 5.9.1 | PKCS7 absent; same release-table/narrative discrepancy. |
| 2026-7532 | 2026-06-25 | `<=5.9.1` / 5.9.2 | X509 IP constraints not used. Related advisory ID TALOS-2026-2409 appears in upstream ChangeLog; Talos page not queried. |
| 2026-8720 | 2026-06-25 | `[5.9.0,5.9.1]` / 5.9.2 | HMAC-BLAKE2 APIs introduced after pin. |
## Queried sources and caveats
All following requests occurred during this **2026-09-15** review. Network requests succeeded; no blocked-network limitation applies to collected external evidence. The last attempted local read/status command failed with `authorization channel closed`; no final repository status/diff validation was obtained.
Official index and release sources fetched:
- https://www.wolfssl.com/docs/security-vulnerabilities/
- https://github.com/wolfSSL/wolfssh/releases
- https://raw.githubusercontent.com/wolfSSL/wolfssh/master/ChangeLog.md
- https://raw.githubusercontent.com/wolfSSL/wolfssl/master/ChangeLog.md
- https://api.github.com/repos/wolfSSL/wolfssl/releases?per_page=6
- https://api.github.com/repos/wolfSSL/wolfssh/releases?per_page=6
Patch URLs actually queried (read only; no patch applied):
- https://github.com/wolfSSL/wolfssl/pull/9275.diff
- https://github.com/wolfSSL/wolfssl/pull/10131.diff
- https://github.com/wolfSSL/wolfssl/pull/10133.diff
- https://github.com/wolfSSL/wolfssl/pull/10025.diff
- https://github.com/wolfSSL/wolfssh/pull/855.diff
- https://github.com/wolfSSL/wolfssh/pull/892.diff
- https://github.com/wolfSSL/wolfssh/pull/881.diff
- https://github.com/wolfSSL/wolfssh/pull/899.diff
CVE metadata: exact URL construction is `https://cveawg.mitre.org/api/cve/` followed by each full CVE identifier in the priority table and inventory above. Every such ID was queried; some twice. These are vendor CNA records served by the CVE API. Full paths are mechanically recoverable without search, e.g. https://cveawg.mitre.org/api/cve/CVE-2025-12888 and https://cveawg.mitre.org/api/cve/CVE-2025-14942 . No NVD or GitHub advisory API query was made.
Additional upstream patch links **identified in release notes, not fetched**: wolfSSH [840](https://github.com/wolfSSL/wolfssh/pull/840), [834](https://github.com/wolfSSL/wolfssh/pull/834), [859](https://github.com/wolfSSL/wolfssh/pull/859), [864](https://github.com/wolfSSL/wolfssh/pull/864), [793](https://github.com/wolfSSL/wolfssh/pull/793), [854](https://github.com/wolfSSL/wolfssh/pull/854), [856](https://github.com/wolfSSL/wolfssh/pull/856), [857](https://github.com/wolfSSL/wolfssh/pull/857), [880](https://github.com/wolfSSL/wolfssh/pull/880), [902](https://github.com/wolfSSL/wolfssh/pull/902), [918](https://github.com/wolfSSL/wolfssh/pull/918), [919](https://github.com/wolfSSL/wolfssh/pull/919), [921](https://github.com/wolfSSL/wolfssh/pull/921); wolfSSL [9148](https://github.com/wolfSSL/wolfssl/pull/9148), [10003](https://github.com/wolfSSL/wolfssl/pull/10003), [10080](https://github.com/wolfSSL/wolfssl/pull/10080), [10363](https://github.com/wolfSSL/wolfssl/pull/10363), [10374](https://github.com/wolfSSL/wolfssl/pull/10374), [10560](https://github.com/wolfSSL/wolfssl/pull/10560), [10702](https://github.com/wolfSSL/wolfssl/pull/10702).
Evidence limitations:
- The consolidated official page omitted the four wolfSSH CVEs published with 1.4.21/1.4.22 despite listing older and newer entries. **Neither that omission nor the user's earlier empty GitHub advisory tabs proves absence of vulnerabilities.** GitHub advisory tabs were not re-queried here.
- Release-note dates differ from GitHub publication dates. CNA metadata has malformed ranges and conflicting references as noted. No date was inferred from a CVE year.
- Master ChangeLogs and PR diffs are mutable. Release tags/timestamps were queried, but upstream full commit hashes and archived evidence snapshots were not captured. Some long patch responses were output-limited; do not interpret a successful fetch as a complete hunk-by-hunk audit.
- Macro evidence is stronger than default Kconfig assumptions but not disassembly/timing evidence. Whole-library API reachability/linker elimination, every math/port fix, low-order X25519 behavior, RNG error paths, and ECC validation call chains remain unfinished.
- Older entries such as wolfSSH CVE-2024-2873 (fixed 1.4.17) were visible in the index; this report is focused on post-pin maintenance and does not certify every historical advisory.
- Parent follow-up: resolve the current-path priorities, choose a coherent upgrade/backport strategy, add negative message-order/parser/key-validation tests against actual generated sources, and run firmware plus whole-Phase-9 hardware gates. No hardware evidence is implied here.
+3
View File
@@ -0,0 +1,3 @@
Import("env")
env.Replace(COMPILATIONDB_INCLUDE_TOOLCHAIN=True)
+7 -1
View File
@@ -2,7 +2,11 @@
default_envs = esp32-s3-devkitc-1-n16r8
[env:esp32-s3-devkitc-1-n16r8]
platform = platformio/espressif32@6.12.0
platform = platformio/espressif32@6.13.0
platform_packages =
platformio/framework-espidf@3.50503.0
platformio/toolchain-xtensa-esp-elf@14.2.0+20251107
platformio/toolchain-riscv32-esp@14.2.0+20251107
board = esp32-s3-devkitc-1-n16r8
framework = espidf
@@ -13,3 +17,5 @@ board_build.partitions = partitions.csv
monitor_speed = 115200
monitor_filters = esp32_exception_decoder
extra_scripts = pre:extra_script.py
+37 -1
View File
@@ -1,4 +1,6 @@
# ESP32-S3-WROOM-1-N16R8 hardware configuration
# Single-variable web throughput experiment; target validation pending.
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y
CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y
CONFIG_SPIRAM=y
CONFIG_SPIRAM_MODE_OCT=y
@@ -14,7 +16,8 @@ CONFIG_ESP_WIFI_RX_BA_WIN=6
CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4
# Keep concurrent HTTPS handshakes from exhausting scarce internal DRAM.
# Active TLS material remains unencrypted in PSRAM until the hardening phase.
# Active TLS material remains unencrypted in PSRAM; physical extraction is outside
# the supported threat model (docs/security_hardening.md).
CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC=y
# CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC is not set
# Hardware AES can hang in the PSRAM DMA path and cannot be shared safely with
@@ -49,6 +52,20 @@ CONFIG_ESP_ENABLE_WOLFSSH=y
# The managed component emits a generic RSA stack warning although this target disables RSA.
CONFIG_ESP_WOLFSSL_NO_STACK_SIZE_BUILD_WARNING=y
# Keep configurable hostname discovery STA-only and bounded. The responder task
# remains internal; general mDNS metadata prefers PSRAM to protect internal heap.
CONFIG_MDNS_MAX_INTERFACES=1
CONFIG_MDNS_MAX_SERVICES=1
CONFIG_MDNS_PREDEF_NETIF_STA=y
# CONFIG_MDNS_PREDEF_NETIF_AP is not set
# CONFIG_MDNS_PREDEF_NETIF_ETH is not set
# CONFIG_MDNS_ENABLE_CONSOLE_CLI is not set
# CONFIG_MDNS_ENABLE_BROWSE is not set
# CONFIG_MDNS_MULTIPLE_INSTANCE is not set
CONFIG_MDNS_TASK_CREATE_FROM_INTERNAL=y
CONFIG_MDNS_MEMORY_ALLOC_SPIRAM=y
# CONFIG_MDNS_MEMORY_ALLOC_INTERNAL is not set
# Support WPA3-SAE for station profiles and the WPA2/WPA3 fallback AP.
CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y
CONFIG_ESP_WIFI_ENABLE_SAE_H2E=y
@@ -56,3 +73,22 @@ CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y
# Keep diagnostic and interactive-console logging concise but useful.
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# Crash memory/registers can contain credentials and serial payloads. Keep the
# reserved coredump partition unused; enforce resolved settings at compile time.
CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y
# CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set
# CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set
CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT=y
# CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set
# CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT is not set
# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set
# CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set
# CONFIG_ESP_DEBUG_OCDAWARE is not set
# CONFIG_FREERTOS_DEBUG_OCDAWARE is not set
# Audited allocation extents and TLS record retirement used by Phase 9C.
CONFIG_HEAP_POISONING_DISABLED=y
# CONFIG_HEAP_POISONING_LIGHT is not set
# CONFIG_HEAP_POISONING_COMPREHENSIVE is not set
# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set
+36
View File
@@ -6,6 +6,7 @@ idf_component_register(
"network_console.c"
"system_console.c"
"secure_random.c"
"security_build_policy.c"
"status_led.c"
"local_display.c"
"local_boot_animation.c"
@@ -21,7 +22,12 @@ idf_component_register(
"session_broker.c"
"session_console.c"
"ssh_security.c"
"admin_command_gate.c"
"admin_ssh_console.c"
"ssh_transport.c"
"ssh_auth_policy.c"
"ssh_memory.c"
"ssh_protocol_policy.c"
"ssh_console.c"
"usb_cdc_transport.c"
"usb_console.c"
@@ -29,13 +35,32 @@ idf_component_register(
"user_console.c"
"web_security.c"
"web_serial_transport.c"
"web_serial_settings.c"
"web_account_settings.c"
"web_network_settings.c"
"web_display_settings.c"
"web_broker_settings.c"
"web_ssh_settings.c"
"web_lifecycle_settings.c"
"web_admin_tickets.c"
"web_admin_transport.c"
"web_assets_data.c"
"web_ui.c"
"web_server.c"
"web_diagnostics.c"
"web_session_store.c"
"web_auth_parse.c"
"web_httpd_adapter.c"
"web_httpd_idle.c"
"web_cookie_auth.c"
"web_login_ui.c"
"web_console.c"
"wifi_config.c"
"wifi_manager.c"
"wifi_console.c"
"mdns_config.c"
"mdns_service.c"
"mdns_console.c"
INCLUDE_DIRS "."
REQUIRES
bootloader_support
@@ -56,11 +81,22 @@ idf_component_register(
led_strip
lwip
mbedtls
mdns
nvs_flash
wolfssl__wolfssh
wolfssl__wolfssl
)
# Only web_httpd_adapter.c uses this private, version-checked boundary.
target_include_directories(${COMPONENT_LIB} PRIVATE
"$ENV{IDF_PATH}/components/esp_http_server/src"
"$ENV{IDF_PATH}/components/esp_http_server/src/port/esp32")
# HTTPD debug logs include header values; URI warnings include ticket queries.
# Compile those out, independently of runtime log-level changes.
idf_component_get_property(httpd_lib esp_http_server COMPONENT_LIB)
target_compile_definitions(${httpd_lib} PRIVATE LOG_LOCAL_LEVEL=ESP_LOG_ERROR)
# Public wolfSSH headers include wolfCrypt configuration from user_settings.h.
target_compile_definitions(${COMPONENT_LIB} PRIVATE
WOLFSSL_USER_SETTINGS
+44
View File
@@ -0,0 +1,44 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Shared recursive gate for administrative command execution origins. */
#include "admin_command_gate.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static SemaphoreHandle_t s_gate;
esp_err_t admin_command_gate_take(void)
{
taskENTER_CRITICAL(&s_lock);
SemaphoreHandle_t gate = s_gate;
taskEXIT_CRITICAL(&s_lock);
if (gate == NULL) {
SemaphoreHandle_t candidate = xSemaphoreCreateRecursiveMutex();
if (candidate == NULL) {
return ESP_ERR_NO_MEM;
}
taskENTER_CRITICAL(&s_lock);
if (s_gate == NULL) {
s_gate = candidate;
candidate = NULL;
}
gate = s_gate;
taskEXIT_CRITICAL(&s_lock);
if (candidate != NULL) {
vSemaphoreDelete(candidate);
}
}
return xSemaphoreTakeRecursive(gate, portMAX_DELAY) == pdTRUE ? ESP_OK : ESP_FAIL;
}
void admin_command_gate_give(void)
{
taskENTER_CRITICAL(&s_lock);
SemaphoreHandle_t gate = s_gate;
taskEXIT_CRITICAL(&s_lock);
if (gate != NULL) {
(void)xSemaphoreGiveRecursive(gate);
}
}
+17
View File
@@ -0,0 +1,17 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Serializes trusted UART0 and authenticated SSH administrative mutations. */
#pragma once
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
esp_err_t admin_command_gate_take(void);
void admin_command_gate_give(void);
#ifdef __cplusplus
}
#endif
File diff suppressed because it is too large Load Diff
+163
View File
@@ -0,0 +1,163 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Bounded administrative dispatcher with a small remote-owner boundary. */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
#include "user_database.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Nonblocking typed settings admission to the canonical dispatcher. */
esp_err_t admin_ssh_console_submit_serial_settings(uint32_t id);
esp_err_t admin_ssh_console_submit_account_settings(uint32_t id);
esp_err_t admin_ssh_console_submit_network_settings(uint32_t id);
esp_err_t admin_ssh_console_submit_display_settings(uint32_t id);
esp_err_t admin_ssh_console_submit_broker_settings(uint32_t id);
esp_err_t admin_ssh_console_submit_ssh_settings(uint32_t id);
esp_err_t admin_ssh_console_submit_lifecycle_settings(uint32_t id);
/* Fits the longest supported ECDSA P-256 OpenSSH key import command. */
#define ADMIN_SSH_CONSOLE_COMMAND_LINE_CAPACITY 256U
#define ADMIN_CONSOLE_TRANSPORT_SSH 0U
#define ADMIN_CONSOLE_TRANSPORT_WEB 1U
typedef struct {
uint8_t slot_index;
uint32_t session_id;
uint32_t slot_generation;
uint8_t transport; /* Zero is SSH, including legacy designated initializers. */
} admin_ssh_console_token_t;
typedef enum {
ADMIN_SSH_DEFER_NONE = 0,
ADMIN_SSH_DEFER_REBOOT,
ADMIN_SSH_DEFER_STOP,
ADMIN_SSH_DEFER_DISCONNECT,
ADMIN_SSH_DEFER_HOST_KEY_ROTATE,
ADMIN_SSH_DEFER_HOST_KEY_RESET,
ADMIN_CONSOLE_DEFER_SELF_CLOSE,
ADMIN_CONSOLE_DEFER_WEB_STOP,
ADMIN_CONSOLE_DEFER_WEB_CERTIFICATE_ROTATE,
} admin_ssh_deferred_action_type_t;
/* Small owner boundary; module/API names are retained for existing SSH callers.
* Exactly two shared console slots, not two per transport. slot_index addresses
* this pool; open_available atomically selects a free slot. Owners must not reuse an identity while
* old work can exist. transport is a firmware-assigned namespace (0 = SSH).
* An occupied or still-executing slot cannot be replaced by open_owned().
*
* The immutable adapter lives for firmware lifetime. Callbacks run on the
* control task OUTSIDE console locks for drained/perform, except perform actions
* selected by dispatcher_actions run serialized on the existing 12KiB dispatcher
* after drain/delay and queued identity/principal revalidation (no command replay).
* Zero dispatcher_actions preserves legacy control-task execution. Required is_current
* runs on the dispatcher outside console locks; it must be bounded and validate
* full transport identity, originating-session liveness and principal binding,
* without calling socket libraries or handlers. Core separately checks accounts.
* drained must be nonblocking, validate the full identity and include pending
* owner output. perform must revalidate identity and marshal lifecycle work to
* its owner, never call socket libraries here. Neither callback may call console
* handlers. supported_actions is a bitmask (1U << action); reject unsupported
* actions before side effects. Legacy STOP/DISCONNECT/key actions mean SSH;
* SELF_CLOSE means this frontend; WEB_STOP means HTTPS, not SSH.
* WEB_CERTIFICATE_ROTATE replaces the HTTPS identity and restarts HTTPS.
* These WEB actions and SELF_CLOSE ignore argument.
*
* One owner serializes feed calls per session; different owners may feed in
* parallel. Shared completion scratch is nonblocking/serialized by the core.
* The owner alone consumes output, maintains authentication/session liveness,
* and calls close on disconnect/revocation. Core copies/rechecks principals at
* admission and dispatch. Dispatch and prompts also check owner currentness;
* blocked prompts recheck every 250ms (plus check/scheduling latency). This does
* not cancel or roll back arbitrary executing handlers. Admission remains the
* owner's responsibility; is_current need not accept unpublished admission.
* Close wakes prompts; executing state is retained until the handler returns.
* Output remains bounded (5s write backpressure); deferred work waits at most
* 10s for application drain plus 200ms, NOT peer-delivery confirmation.
* Dispatcher actions then wait behind queued commands/prompts, with input gated
* until completion or cancellation; the drain bound is not an execution deadline.
* No new tasks, queues, slots, or browser endpoint are provided by this API.
*/
typedef struct {
uint32_t supported_actions;
uint32_t dispatcher_actions; /* Subset of supported_actions; immutable. */
bool (*is_current)(const admin_ssh_console_token_t *token,
const user_principal_t *principal);
bool (*drained)(const admin_ssh_console_token_t *token);
esp_err_t (*perform)(const admin_ssh_console_token_t *token,
admin_ssh_deferred_action_type_t action, uint32_t argument);
} admin_console_owner_t;
/* Selects any inactive, nonexecuting slot from the shared two-slot pool.
* Input slot_index is ignored; only slot_index changes, and only on success.
* Caller supplies transport/session_id/slot_generation and must retain the
* returned token. Full pool returns ESP_ERR_INVALID_STATE, like open_owned.
*/
esp_err_t admin_ssh_console_open_available(admin_ssh_console_token_t *token,
const user_principal_t *principal,
const admin_console_owner_t *owner);
esp_err_t admin_ssh_console_open_owned(const admin_ssh_console_token_t *token,
const user_principal_t *principal,
const admin_console_owner_t *owner);
typedef struct {
bool active;
bool command_pending;
bool input_pending;
bool output_pending;
bool deferred_action_pending;
size_t input_length;
size_t output_length;
} admin_ssh_console_session_snapshot_t;
/* Starts the single command worker. It is the sole esp_console_run() caller. */
esp_err_t admin_ssh_console_init(void);
/* Register administration-shell-only root commands after esp_console initialization. */
esp_err_t admin_ssh_console_register_commands(void);
/* Called after all ESP-IDF commands are registered; starts the UART0 frontend. */
esp_err_t admin_ssh_console_start_uart_frontend(void);
/* Valid only while a registered command callback runs on the dispatcher task. */
bool admin_ssh_console_dispatch_is_remote(void);
bool admin_ssh_console_dispatch_is_web(void);
const user_principal_t *admin_ssh_console_dispatch_principal(void);
/* Revalidate account, originating owner/session and token before side effects.
* False outside the dispatcher; UART0 dispatch remains physically trusted. */
bool admin_ssh_console_dispatch_is_current(void);
/* Shared parsed browser account policy: dispatcher admission + handler defense. */
bool admin_ssh_console_web_user_command_allowed(
size_t argc, char **argv, const user_principal_t *principal);
esp_err_t admin_ssh_console_dispatch_read_input(
const char *prompt, uint8_t *output, size_t capacity,
bool hidden, size_t *output_length);
esp_err_t admin_ssh_console_dispatch_defer(
admin_ssh_deferred_action_type_t action, uint32_t argument);
void admin_ssh_console_close(const admin_ssh_console_token_t *token);
/* Called by the session owner. Returns false when input must be backpressured. */
bool admin_ssh_console_accepts_input(const admin_ssh_console_token_t *token);
bool admin_ssh_console_feed_input(const admin_ssh_console_token_t *token,
const uint8_t *data, size_t length,
size_t *consumed);
/* Called by the session owner; copies already-produced output without blocking. */
esp_err_t admin_ssh_console_read_output(const admin_ssh_console_token_t *token,
uint8_t *data, size_t capacity,
size_t *received);
esp_err_t admin_ssh_console_get_session_snapshot(
const admin_ssh_console_token_t *token,
admin_ssh_console_session_snapshot_t *snapshot);
#ifdef __cplusplus
}
#endif
+155 -22
View File
@@ -4,15 +4,21 @@
#include "console_completion.h"
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "esp_console.h"
#include "linenoise/linenoise.h"
static const char *const s_root_candidates[] = {
"help", "exit", "debug", "display", "serial", "broker", "usb", "user",
"wifi", "mdns", "web", "ssh", "ping", "nslookup", "traceroute", "reboot", "memory",
};
/* Keep full-line candidate strings grouped by their registered root command. */
static const char *const s_completion_candidates[] = {
/* Hardware debug commands and safe fixed arguments. */
"debug status",
"debug transceiver",
"debug transceiver enable",
"debug transceiver disable",
@@ -120,8 +126,6 @@ static const char *const s_completion_candidates[] = {
"user status",
"user list",
"user show",
"user bootstrap",
"user bootstrap --generate",
"user recover --force",
"user add",
"user delete",
@@ -139,6 +143,7 @@ static const char *const s_completion_candidates[] = {
"wifi start",
"wifi stop",
"wifi reconnect",
"wifi next-profile",
"wifi save",
"wifi load",
"wifi defaults",
@@ -162,6 +167,14 @@ static const char *const s_completion_candidates[] = {
"wifi nslookup",
"wifi traceroute",
/* Station mDNS hostname configuration. */
"mdns status",
"mdns suffix",
"mdns save",
"mdns load",
"mdns defaults",
"mdns reset",
/* Authenticated HTTPS lifecycle and physical-admin recovery operations. */
"web help",
"web status",
@@ -169,10 +182,14 @@ static const char *const s_completion_candidates[] = {
"web stop",
"web counters",
"web clear-counters",
"web credentials",
"web credentials show",
"web credentials rotate",
"web credentials rotate --force",
"web diagnostics enable",
"web diagnostics disable",
"web diagnostics show",
"web diagnostics clear",
"web performance enable",
"web performance disable",
"web performance show",
"web performance clear",
"web certificate",
"web certificate info",
"web certificate rotate",
@@ -197,6 +214,115 @@ static const char *const s_completion_candidates[] = {
"ssh reset --force",
};
void console_completion_visit(const char *line,
console_completion_visitor_t visitor,
void *context)
{
if (line == NULL || visitor == NULL) {
return;
}
size_t line_length = strlen(line);
const char *const *candidates = strchr(line, ' ') == NULL
? s_root_candidates
: s_completion_candidates;
size_t candidate_count = strchr(line, ' ') == NULL
? sizeof(s_root_candidates) / sizeof(s_root_candidates[0])
: sizeof(s_completion_candidates) /
sizeof(s_completion_candidates[0]);
for (size_t index = 0U; index < candidate_count; ++index) {
const char *candidate = candidates[index];
if (strlen(candidate) > line_length &&
strncmp(candidate, line, line_length) == 0 &&
!visitor(candidate, context)) {
return;
}
}
}
typedef struct {
const char *line;
const char *first;
size_t common_length;
} completion_expand_context_t;
static bool collect_common_prefix(const char *candidate, void *context)
{
completion_expand_context_t *result = context;
if (result->first == NULL) {
result->first = candidate;
result->common_length = strlen(candidate);
return true;
}
size_t candidate_length = strlen(candidate);
if (result->common_length > candidate_length) {
result->common_length = candidate_length;
}
size_t offset = strlen(result->line);
while (offset < result->common_length && result->first[offset] == candidate[offset]) {
++offset;
}
result->common_length = offset;
return true;
}
bool console_completion_expand(const char *line, char *completed, size_t capacity)
{
if (line == NULL || completed == NULL || capacity == 0U) {
return false;
}
completion_expand_context_t result = {.line = line};
console_completion_visit(line, collect_common_prefix, &result);
size_t line_length = strlen(line);
if (result.first == NULL || result.common_length <= line_length ||
result.common_length >= capacity) {
return false;
}
memcpy(completed, result.first, result.common_length);
completed[result.common_length] = '\0';
return true;
}
typedef struct {
char *output;
size_t capacity;
size_t length;
bool complete;
} completion_format_context_t;
static bool format_completion_candidate(const char *candidate, void *context)
{
completion_format_context_t *result = context;
size_t candidate_length = strlen(candidate);
if (candidate_length + 2U > result->capacity - result->length) {
result->complete = false;
return false;
}
memcpy(result->output + result->length, candidate, candidate_length);
result->length += candidate_length;
result->output[result->length++] = '\r';
result->output[result->length++] = '\n';
return true;
}
bool console_completion_format_matches(const char *line, char *output, size_t capacity,
size_t *output_length)
{
if (line == NULL || output == NULL || output_length == NULL || capacity == 0U) {
return false;
}
completion_format_context_t result = {
.output = output,
.capacity = capacity,
.complete = true,
};
console_completion_visit(line, format_completion_candidate, &result);
if (!result.complete) {
return false;
}
*output_length = result.length;
return true;
}
static ssize_t console_read_with_late_terminal_upgrade(int file_descriptor,
void *buffer,
size_t size)
@@ -213,27 +339,34 @@ static ssize_t console_read_with_late_terminal_upgrade(int file_descriptor,
return received;
}
/* The UART frontend is the sole caller of linenoise's completion callback. */
static char s_uart_completion_output[CONSOLE_COMPLETION_OUTPUT_CAPACITY];
static void console_completion_callback(const char *buffer, linenoiseCompletions *completions)
{
/* Preserve ESP-IDF completion for registered root command names. */
if (strchr(buffer, ' ') == NULL) {
esp_console_get_completion(buffer, completions);
char completed[257U] = {0};
if (console_completion_expand(buffer, completed, sizeof(completed))) {
linenoiseAddCompletion(completions, completed);
return;
}
const size_t buffer_length = strlen(buffer);
for (size_t index = 0;
index < sizeof(s_completion_candidates) / sizeof(s_completion_candidates[0]);
++index) {
const char *const candidate = s_completion_candidates[index];
const size_t candidate_length = strlen(candidate);
/* linenoise expects the complete replacement line, not only its suffix. */
if (candidate_length > buffer_length &&
strncmp(candidate, buffer, buffer_length) == 0) {
linenoiseAddCompletion(completions, candidate);
}
size_t output_length = 0U;
if (!console_completion_format_matches(buffer, s_uart_completion_output,
sizeof(s_uart_completion_output),
&output_length) ||
output_length == 0U) {
return;
}
/*
* Linenoise cycles every completion it receives. Print the shared list
* ourselves, then return the unchanged line as its one completion so its
* normal refresh restores the prompt without selecting a candidate.
*/
fputs("\r\n", stdout);
(void)fwrite(s_uart_completion_output, 1U, output_length, stdout);
fflush(stdout);
linenoiseAddCompletion(completions, buffer);
}
void console_completion_install(void)
+25
View File
@@ -2,13 +2,38 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Current longest formatted match list is below this; overflow fails closed. */
#define CONSOLE_COMPLETION_OUTPUT_CAPACITY 1024U
/* Install late-terminal upgrade handling and project-specific completion. */
void console_completion_install(void);
typedef bool (*console_completion_visitor_t)(const char *candidate, void *context);
/* Visit the same matching hint candidates used by both UART0 and admin SSH. */
void console_completion_visit(const char *line,
console_completion_visitor_t visitor,
void *context);
/* Bounded longest-prefix completion shared by the UART and admin SSH frontends. */
bool console_completion_expand(const char *line, char *completed, size_t capacity);
/*
* Format the matching candidates as CRLF-terminated lines for a frontend that
* cannot use linenoise's native completion display. A successful empty result
* means no candidate matched; false means the supplied output buffer was too
* small or an argument was invalid.
*/
bool console_completion_format_matches(const char *line, char *output, size_t capacity,
size_t *output_length);
#ifdef __cplusplus
}
#endif
+16
View File
@@ -6,6 +6,7 @@
#include <stdio.h>
#include <string.h>
#include "admin_ssh_console.h"
#include "driver/uart.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
@@ -31,6 +32,10 @@ static esp_err_t read_input(const char *prompt, uint8_t *output, size_t capacity
if (prompt == NULL || output == NULL || output_length == NULL || capacity == 0U) {
return ESP_ERR_INVALID_ARG;
}
if (admin_ssh_console_dispatch_is_remote()) {
return admin_ssh_console_dispatch_read_input(
prompt, output, capacity, hidden, output_length);
}
*output_length = 0U;
memset(output, 0, capacity);
esp_err_t error = prepare_prompt(prompt);
@@ -38,6 +43,7 @@ static esp_err_t read_input(const char *prompt, uint8_t *output, size_t capacity
return error;
}
bool rejected = false;
for (;;) {
uint8_t byte = 0U;
if (uart_read_bytes(CONSOLE_INPUT_UART, &byte, 1U, portMAX_DELAY) != 1) {
@@ -66,6 +72,11 @@ static esp_err_t read_input(const char *prompt, uint8_t *output, size_t capacity
continue;
}
if (byte < 0x20U || byte > 0x7eU || *output_length >= capacity - 1U) {
/* Hidden credentials must never accept a truncated/normalized prefix. */
if (hidden) {
rejected = true;
continue;
}
putchar('\a');
fflush(stdout);
continue;
@@ -77,6 +88,11 @@ static esp_err_t read_input(const char *prompt, uint8_t *output, size_t capacity
}
}
putchar('\n');
if (rejected) {
secure_wipe(output, capacity);
*output_length = 0U;
return ESP_ERR_INVALID_SIZE;
}
return ESP_OK;
}
+4
View File
@@ -8,6 +8,10 @@
#include "esp_err.h"
/* Hidden input accepts printable ASCII with CR/LF submit, BS/DEL editing and
* Ctrl-C cancellation. Overflow or any other byte rejects the entire prompt on
* submit (ESP_ERR_INVALID_SIZE), even after editing; rejected input is wiped.
* capacity includes the trailing NUL. Visible line editing is unchanged. */
esp_err_t console_input_read_hidden(const char *prompt,
uint8_t *output, size_t capacity,
size_t minimum_length, size_t maximum_length,
+1
View File
@@ -4,6 +4,7 @@ dependencies:
idf: ">=5.3.0"
espressif/led_strip: "^3.0.3"
espressif/esp_tinyusb: "^2.2.1"
espressif/mdns: "^1.8.2"
# Exact official registry versions form the reviewed Phase 6 integration baseline.
wolfssl/wolfssl: "5.8.2~1"
wolfssl/wolfssh: "1.4.20"
+61 -13
View File
@@ -203,6 +203,8 @@ static TickType_t s_diagnostic_hold_started;
static uint32_t s_external_activity_sequence;
static local_ui_config_t s_config;
static bool s_config_available;
static bool s_config_busy;
static uint32_t s_config_generation;
static const gpio_num_t s_button_gpios[LOCAL_STATUS_BUTTON_COUNT] = {
LOCAL_UI_BUTTON_PREVIOUS_GPIO,
@@ -1368,21 +1370,62 @@ esp_err_t local_status_ui_get_config(local_ui_config_t *config)
return available ? ESP_OK : ESP_ERR_INVALID_STATE;
}
esp_err_t local_status_ui_get_settings(local_ui_config_t *config, uint32_t *generation)
{
if (config == NULL || generation == NULL) return ESP_ERR_INVALID_ARG;
portENTER_CRITICAL(&s_timing_mux);
esp_err_t error = !s_config_available ? ESP_ERR_INVALID_STATE :
s_config_busy ? ESP_ERR_TIMEOUT : ESP_OK;
if (error == ESP_OK) {
*config = s_config;
*generation = s_config_generation;
}
portEXIT_CRITICAL(&s_timing_mux);
return error;
}
esp_err_t local_status_ui_update_settings(local_ui_settings_action_t action,
uint32_t expected_generation, const local_ui_config_t *config, bool *loaded_defaults)
{
if (loaded_defaults != NULL) *loaded_defaults = false;
if (action < LOCAL_UI_SETTINGS_APPLY || action > LOCAL_UI_SETTINGS_RESET ||
(action == LOCAL_UI_SETTINGS_APPLY && local_ui_config_validate(config) != ESP_OK))
return ESP_ERR_INVALID_ARG;
local_ui_config_t candidate;
portENTER_CRITICAL(&s_timing_mux);
esp_err_t error = !s_config_available ||
(expected_generation && expected_generation != s_config_generation) ||
s_config_generation == UINT32_MAX ? ESP_ERR_INVALID_STATE :
s_config_busy ? ESP_ERR_TIMEOUT : ESP_OK;
if (error == ESP_OK) {
candidate = action == LOCAL_UI_SETTINGS_APPLY ? *config : s_config;
s_config_busy = true;
}
portEXIT_CRITICAL(&s_timing_mux);
if (error != ESP_OK) return error;
bool stored = true;
if (action == LOCAL_UI_SETTINGS_LOAD) error = local_ui_config_load(&candidate, &stored);
if (action == LOCAL_UI_SETTINGS_DEFAULTS || action == LOCAL_UI_SETTINGS_RESET)
local_ui_config_defaults(&candidate);
if (action == LOCAL_UI_SETTINGS_SAVE || action == LOCAL_UI_SETTINGS_RESET)
error = local_ui_config_save(&candidate);
portENTER_CRITICAL(&s_timing_mux);
if (error == ESP_OK && action != LOCAL_UI_SETTINGS_SAVE) {
s_config = candidate;
++s_config_generation;
++s_external_activity_sequence;
}
s_config_busy = false;
portEXIT_CRITICAL(&s_timing_mux);
if (error == ESP_OK && loaded_defaults != NULL) *loaded_defaults = !stored;
return error;
}
esp_err_t local_status_ui_apply_config(const local_ui_config_t *config)
{
esp_err_t error = local_ui_config_validate(config);
if (error != ESP_OK) {
return error;
}
portENTER_CRITICAL(&s_timing_mux);
if (!s_config_available) {
portEXIT_CRITICAL(&s_timing_mux);
return ESP_ERR_INVALID_STATE;
}
s_config = *config;
++s_external_activity_sequence;
portEXIT_CRITICAL(&s_timing_mux);
return ESP_OK;
return local_status_ui_update_settings(LOCAL_UI_SETTINGS_APPLY, 0, config, NULL);
}
esp_err_t local_status_ui_start(const local_ui_config_t *config)
@@ -1397,6 +1440,11 @@ esp_err_t local_status_ui_start(const local_ui_config_t *config)
portENTER_CRITICAL(&s_timing_mux);
s_config = *config;
if (s_config_generation == UINT32_MAX) {
portEXIT_CRITICAL(&s_timing_mux);
return ESP_ERR_INVALID_STATE;
}
++s_config_generation;
s_config_available = true;
portEXIT_CRITICAL(&s_timing_mux);
+16
View File
@@ -21,6 +21,22 @@ esp_err_t local_status_ui_start(const local_ui_config_t *config);
esp_err_t local_status_ui_get_config(local_ui_config_t *config);
esp_err_t local_status_ui_apply_config(const local_ui_config_t *config);
typedef enum {
LOCAL_UI_SETTINGS_APPLY, LOCAL_UI_SETTINGS_SAVE, LOCAL_UI_SETTINGS_LOAD,
LOCAL_UI_SETTINGS_DEFAULTS, LOCAL_UI_SETTINGS_RESET
} local_ui_settings_action_t;
/* Zero-wait RAM projection. Generation is nonzero and never wraps. */
esp_err_t local_status_ui_get_settings(local_ui_config_t *config, uint32_t *generation);
/* Reserve configuration across storage IO, without holding a critical section.
* Zero expected_generation is for canonical unconditional CLI operations only.
* Nonzero stale generations return ESP_ERR_INVALID_STATE; contention returns
* ESP_ERR_TIMEOUT. Load retains the canonical default fallback. Reset commits
* defaults before publishing RAM, so a storage failure needs no RAM rollback.
* No display IO occurs here; successful RAM changes signal renderer activity. */
esp_err_t local_status_ui_update_settings(local_ui_settings_action_t action,
uint32_t expected_generation, const local_ui_config_t *config, bool *loaded_defaults);
/* Preserve a manually selected display diagnostic for a bounded interval. */
void local_status_ui_hold_for_diagnostics(void);
+9 -24
View File
@@ -87,7 +87,8 @@ static int apply_parameter(const char *parameter, const char *text)
}
local_ui_config_t config;
esp_err_t error = local_status_ui_get_config(&config);
uint32_t generation;
esp_err_t error = local_status_ui_get_settings(&config, &generation);
if (error != ESP_OK) {
printf("Could not read local UI configuration: %s\n", esp_err_to_name(error));
return 1;
@@ -102,7 +103,7 @@ static int apply_parameter(const char *parameter, const char *text)
return 1;
}
error = local_status_ui_apply_config(&config);
error = local_status_ui_update_settings(LOCAL_UI_SETTINGS_APPLY, generation, &config, NULL);
if (error != ESP_OK) {
printf("Invalid display configuration: %s. When both timeouts are enabled, off must be later than dim.\n",
esp_err_to_name(error));
@@ -122,11 +123,7 @@ static int command_display(int argc, char **argv)
return apply_parameter(argv[2], argv[3]);
}
if (argc == 2 && strcmp(argv[1], "save") == 0) {
local_ui_config_t config;
esp_err_t error = local_status_ui_get_config(&config);
if (error == ESP_OK) {
error = local_ui_config_save(&config);
}
esp_err_t error = local_status_ui_update_settings(LOCAL_UI_SETTINGS_SAVE, 0, NULL, NULL);
if (error != ESP_OK) {
printf("Could not save display configuration: %s\n", esp_err_to_name(error));
return 1;
@@ -136,17 +133,15 @@ static int command_display(int argc, char **argv)
}
if (argc == 2 && strcmp(argv[1], "load") == 0) {
local_ui_config_t config;
bool used_stored_config;
esp_err_t error = local_ui_config_load(&config, &used_stored_config);
if (error == ESP_OK) {
error = local_status_ui_apply_config(&config);
}
bool loaded_defaults = false;
esp_err_t error = local_status_ui_update_settings(LOCAL_UI_SETTINGS_LOAD, 0, NULL, &loaded_defaults);
if (error == ESP_OK) error = local_status_ui_get_config(&config);
if (error != ESP_OK) {
printf("Could not load display configuration: %s\n", esp_err_to_name(error));
return 1;
}
printf("Loaded %s display configuration.\n",
used_stored_config ? "stored" : "default");
loaded_defaults ? "default" : "stored");
print_config(&config);
return 0;
}
@@ -163,19 +158,9 @@ static int command_display(int argc, char **argv)
return 0;
}
if (argc == 2 && strcmp(argv[1], "reset") == 0) {
local_ui_config_t previous;
local_ui_config_t defaults;
local_ui_config_defaults(&defaults);
esp_err_t error = local_status_ui_get_config(&previous);
if (error == ESP_OK) {
error = local_status_ui_apply_config(&defaults);
}
if (error == ESP_OK) {
error = local_ui_config_reset_storage();
if (error != ESP_OK) {
(void)local_status_ui_apply_config(&previous);
}
}
esp_err_t error = local_status_ui_update_settings(LOCAL_UI_SETTINGS_RESET, 0, NULL, NULL);
if (error != ESP_OK) {
printf("Could not reset display configuration: %s\n", esp_err_to_name(error));
return 1;
+43 -32
View File
@@ -1,6 +1,5 @@
#include <string.h>
#include "driver/uart.h"
#include "admin_ssh_console.h"
#include "console_completion.h"
#include "esp_console.h"
#include "esp_err.h"
@@ -13,6 +12,9 @@
#include "local_ui_config.h"
#include "local_ui_console.h"
#include "local_ui_hw_test.h"
#include "mdns_config.h"
#include "mdns_console.h"
#include "mdns_service.h"
#include "rs232_hw_test.h"
#include "rs232_port_owner.h"
#include "secure_random.h"
@@ -45,7 +47,6 @@ static const char *TAG = "firmware";
void app_main(void)
{
ESP_LOGI(TAG, "ESP32-S3 Serial Swiss Army Knife Phase 7E local UI reliability started");
if (esp_psram_is_initialized()) {
ESP_LOGI(TAG, "PSRAM initialized: %u bytes", (unsigned int)esp_psram_get_size());
@@ -64,6 +65,8 @@ void app_main(void)
ESP_ERROR_CHECK(status_led_init());
ESP_ERROR_CHECK(rs232_port_owner_init());
ESP_ERROR_CHECK(rs232_hw_test_init());
/* Reserve the shared UART0 dispatcher before optional SSH/network services. */
ESP_ERROR_CHECK(admin_ssh_console_init());
/* The optional display can fail without affecting UART0 or serial transports. */
esp_err_t local_display_error = local_display_init();
@@ -127,29 +130,16 @@ void app_main(void)
"HTTPS security material unavailable (%s); use UART0 'web reset --force' to replace it",
esp_err_to_name(web_security_error));
} else {
ESP_LOGI(TAG, "Using %s HTTPS identity and legacy recovery credential",
web_security_source == WEB_SECURITY_LOAD_STORED ? "stored" : "newly generated");
ESP_LOGI(TAG, "Using %s HTTPS identity",
web_security_source == WEB_SECURITY_LOAD_STORED
? "stored"
: (web_security_source == WEB_SECURITY_LOAD_MIGRATED_V1
? "migrated v1"
: "newly generated"));
}
user_database_load_result_t user_database_source = USER_DATABASE_LOAD_EMPTY;
web_security_credentials_t legacy_credentials;
memset(&legacy_credentials, 0, sizeof(legacy_credentials));
user_database_legacy_credentials_t legacy = {0};
const user_database_legacy_credentials_t *legacy_pointer = NULL;
if (web_security_error == ESP_OK &&
web_security_show_credentials(&legacy_credentials) == ESP_OK) {
legacy = (user_database_legacy_credentials_t){
.username = (const uint8_t *)legacy_credentials.username,
.username_length = legacy_credentials.username_length,
.password = (const uint8_t *)legacy_credentials.password,
.password_length = legacy_credentials.password_length,
};
legacy_pointer = &legacy;
}
esp_err_t user_database_error =
user_database_init(legacy_pointer, &user_database_source);
secure_wipe(&legacy_credentials, sizeof(legacy_credentials));
secure_wipe(&legacy, sizeof(legacy));
esp_err_t user_database_error = user_database_init(&user_database_source);
if (user_database_error != ESP_OK) {
ESP_LOGE(TAG, "User database unavailable: %s; HTTPS and SSH authentication will fail closed; use UART0 'user recover --force'",
esp_err_to_name(user_database_error));
@@ -157,9 +147,7 @@ void app_main(void)
ESP_LOGI(TAG, "Using %s user database",
user_database_source == USER_DATABASE_LOAD_STORED
? "stored"
: (user_database_source == USER_DATABASE_LOAD_MIGRATED_LEGACY
? "newly migrated user-level"
: "new empty"));
: "new empty");
}
esp_err_t web_runtime_error = web_server_init();
@@ -213,6 +201,23 @@ void app_main(void)
"Stored Wi-Fi configuration is incompatible; using RAM defaults without overwriting it");
}
mdns_config_t mdns_config;
bool used_stored_mdns_config = false;
esp_err_t mdns_config_error = mdns_config_load(&mdns_config, &used_stored_mdns_config);
if (mdns_config_error != ESP_OK) {
mdns_config_defaults(&mdns_config);
ESP_LOGW(TAG, "NVS mDNS configuration unavailable (%s); using RAM defaults",
esp_err_to_name(mdns_config_error));
}
esp_err_t mdns_service_error = mdns_service_init(&mdns_config);
if (mdns_service_error != ESP_OK) {
ESP_LOGW(TAG, "mDNS configuration service unavailable: %s; Wi-Fi will continue",
esp_err_to_name(mdns_service_error));
} else {
ESP_LOGI(TAG, "Using %s mDNS suffix sak-%s.local",
used_stored_mdns_config ? "stored" : "default", mdns_config.suffix);
}
esp_err_t wifi_error = wifi_config_error;
if (wifi_config_error == ESP_OK) {
wifi_error = wifi_manager_init(&wifi_config);
@@ -245,8 +250,8 @@ void app_main(void)
ESP_LOGI(TAG, "Authenticated HTTPS listening on TCP port 443");
}
}
if (wifi_error == ESP_OK && web_security_error == ESP_OK &&
ssh_security_error == ESP_OK && ssh_runtime_error == ESP_OK) {
if (wifi_error == ESP_OK && ssh_security_error == ESP_OK &&
ssh_runtime_error == ESP_OK) {
esp_err_t start_error = ssh_transport_start();
if (start_error != ESP_OK) {
ESP_LOGE(TAG, "SSH startup failed: %s; UART0 recovery remains available",
@@ -274,8 +279,9 @@ void app_main(void)
esp_console_repl_config_t repl_config = ESP_CONSOLE_REPL_CONFIG_DEFAULT();
repl_config.prompt = "serial-tool> ";
repl_config.max_cmdline_length = 160;
repl_config.task_stack_size = 8192;
repl_config.max_cmdline_length = ADMIN_SSH_CONSOLE_COMMAND_LINE_CAPACITY;
/* The stock REPL task remains dormant; our shared frontend owns line dispatch. */
repl_config.task_stack_size = 2048;
/*
* UART0 remains dedicated to development and diagnostics. The external
@@ -298,14 +304,19 @@ void app_main(void)
ESP_ERROR_CHECK(usb_console_register_commands());
ESP_ERROR_CHECK(user_console_register_commands());
ESP_ERROR_CHECK(wifi_console_register_commands());
if (mdns_service_error == ESP_OK) {
ESP_ERROR_CHECK(mdns_console_register_commands());
}
ESP_ERROR_CHECK(web_console_register_commands());
ESP_ERROR_CHECK(ssh_console_register_commands());
ESP_ERROR_CHECK(network_console_register_root_commands());
ESP_ERROR_CHECK(system_console_register_commands());
ESP_ERROR_CHECK(admin_ssh_console_register_commands());
/* Upgrade late UART terminals safely and add nested completion. */
console_completion_install();
ESP_ERROR_CHECK(esp_console_start_repl(repl));
ESP_ERROR_CHECK(admin_ssh_console_start_uart_frontend());
ESP_LOGI(TAG, "Interactive test console ready at %d baud", CONSOLE_BAUD_RATE);
ESP_LOGI(TAG, "Shared UART0/SSH administration console ready at %d baud",
CONSOLE_BAUD_RATE);
ESP_LOGI(TAG, "Type 'help' for commands; native USB starts UART1 only when its host port opens");
}
+145
View File
@@ -0,0 +1,145 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Versioned persistent configuration for the station mDNS hostname. */
#include "mdns_config.h"
#include <stddef.h>
#include <string.h>
#include "esp_mac.h"
#include "nvs.h"
#include "nvs_flash.h"
_Static_assert(sizeof(mdns_config_t) == MDNS_CONFIG_BLOB_SIZE,
"mDNS config schema size changed");
static bool suffix_character_is_valid(char character)
{
return (character >= 'a' && character <= 'z') ||
(character >= '0' && character <= '9') || character == '-';
}
void mdns_config_defaults(mdns_config_t *config)
{
static const char hex[] = "0123456789abcdef";
uint8_t mac[6] = {0};
if (config == NULL) {
return;
}
memset(config, 0, sizeof(*config));
config->schema_version = MDNS_CONFIG_SCHEMA_VERSION;
config->blob_size = MDNS_CONFIG_BLOB_SIZE;
if (esp_read_mac(mac, ESP_MAC_WIFI_STA) != ESP_OK) {
return;
}
for (size_t index = 0U; index < sizeof(mac); ++index) {
config->suffix[index * 2U] = hex[mac[index] >> 4U];
config->suffix[index * 2U + 1U] = hex[mac[index] & 0x0fU];
}
config->suffix_len = sizeof(mac) * 2U;
}
esp_err_t mdns_config_validate(const mdns_config_t *config)
{
if (config == NULL || config->schema_version != MDNS_CONFIG_SCHEMA_VERSION ||
config->blob_size != MDNS_CONFIG_BLOB_SIZE || config->suffix_len == 0U ||
config->suffix_len > MDNS_CONFIG_SUFFIX_MAX_LEN || config->reserved != 0U ||
config->suffix[config->suffix_len] != '\0') {
return ESP_ERR_INVALID_ARG;
}
if (config->suffix[0] == '-' || config->suffix[config->suffix_len - 1U] == '-') {
return ESP_ERR_INVALID_ARG;
}
for (size_t index = 0U; index < MDNS_CONFIG_SUFFIX_MAX_LEN; ++index) {
if (index < config->suffix_len) {
if (!suffix_character_is_valid(config->suffix[index])) {
return ESP_ERR_INVALID_ARG;
}
} else if (config->suffix[index] != '\0') {
return ESP_ERR_INVALID_ARG;
}
}
return ESP_OK;
}
esp_err_t mdns_config_load(mdns_config_t *config, bool *used_stored_config)
{
if (config == NULL || used_stored_config == NULL) {
return ESP_ERR_INVALID_ARG;
}
mdns_config_defaults(config);
*used_stored_config = false;
if (mdns_config_validate(config) != ESP_OK) {
return ESP_FAIL;
}
esp_err_t error = nvs_flash_init();
if (error != ESP_OK) {
return error;
}
nvs_handle_t handle;
error = nvs_open(MDNS_CONFIG_NVS_NAMESPACE, NVS_READONLY, &handle);
if (error == ESP_ERR_NVS_NOT_FOUND) {
return ESP_OK;
}
if (error != ESP_OK) {
return error;
}
size_t size = 0U;
error = nvs_get_blob(handle, MDNS_CONFIG_NVS_BLOB_KEY, NULL, &size);
if (error == ESP_ERR_NVS_NOT_FOUND || error == ESP_ERR_NVS_TYPE_MISMATCH ||
(error == ESP_OK && size != sizeof(*config))) {
nvs_close(handle);
return ESP_OK;
}
if (error != ESP_OK) {
nvs_close(handle);
return error;
}
mdns_config_t stored = {0};
error = nvs_get_blob(handle, MDNS_CONFIG_NVS_BLOB_KEY, &stored, &size);
nvs_close(handle);
if (error == ESP_ERR_NVS_INVALID_LENGTH) {
return ESP_OK;
}
if (error != ESP_OK) {
return error;
}
if (size == sizeof(stored) && mdns_config_validate(&stored) == ESP_OK) {
*config = stored;
*used_stored_config = true;
}
return ESP_OK;
}
esp_err_t mdns_config_save(const mdns_config_t *config)
{
esp_err_t error = mdns_config_validate(config);
if (error != ESP_OK) {
return error;
}
error = nvs_flash_init();
if (error != ESP_OK) {
return error;
}
nvs_handle_t handle;
error = nvs_open(MDNS_CONFIG_NVS_NAMESPACE, NVS_READWRITE, &handle);
if (error != ESP_OK) {
return error;
}
error = nvs_set_blob(handle, MDNS_CONFIG_NVS_BLOB_KEY, config, sizeof(*config));
if (error == ESP_OK) {
error = nvs_commit(handle);
}
nvs_close(handle);
return error;
}
esp_err_t mdns_config_reset_storage(void)
{
mdns_config_t config;
mdns_config_defaults(&config);
return mdns_config_save(&config);
}
+29
View File
@@ -0,0 +1,29 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Versioned persistent configuration for the station mDNS hostname. */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "esp_err.h"
#define MDNS_CONFIG_SCHEMA_VERSION 1U
#define MDNS_CONFIG_BLOB_SIZE 64U
#define MDNS_CONFIG_SUFFIX_MAX_LEN 55U
#define MDNS_CONFIG_NVS_NAMESPACE "mdns_cfg"
#define MDNS_CONFIG_NVS_BLOB_KEY "config"
typedef struct {
uint32_t schema_version;
uint16_t blob_size;
uint8_t suffix_len;
uint8_t reserved;
char suffix[MDNS_CONFIG_SUFFIX_MAX_LEN + 1U];
} mdns_config_t;
void mdns_config_defaults(mdns_config_t *config);
esp_err_t mdns_config_validate(const mdns_config_t *config);
esp_err_t mdns_config_load(mdns_config_t *config, bool *used_stored_config);
esp_err_t mdns_config_save(const mdns_config_t *config);
esp_err_t mdns_config_reset_storage(void);
+149
View File
@@ -0,0 +1,149 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Administration console for the station mDNS hostname. */
#include "mdns_console.h"
#include <stdio.h>
#include <string.h>
#include "esp_console.h"
#include "mdns_config.h"
#include "mdns_service.h"
#include "wifi_manager.h"
static void print_usage(void)
{
printf("Usage: mdns status|suffix <lowercase-suffix>|save|load|defaults|reset\n");
}
static int request_reannounce(void)
{
esp_err_t error = wifi_manager_mdns_reannounce();
if (error != ESP_OK) {
printf("mDNS configuration updated; it will be used when Wi-Fi STA receives an IP (%s).\n",
esp_err_to_name(error));
}
return 0;
}
static int show_status(void)
{
mdns_service_snapshot_t snapshot;
esp_err_t error = mdns_service_get_snapshot(&snapshot);
if (error != ESP_OK) {
printf("mDNS unavailable: %s\n", esp_err_to_name(error));
return 1;
}
printf("mDNS: initialized=%s announced=%s hostname=%s.local suffix=%s last-error=%s\n",
snapshot.initialized ? "yes" : "no", snapshot.announced ? "yes" : "no",
snapshot.hostname, snapshot.suffix, esp_err_to_name(snapshot.last_error));
return 0;
}
static int set_suffix(const char *suffix)
{
size_t length = strlen(suffix);
mdns_config_t config;
esp_err_t error = mdns_service_get_config(&config);
if (error == ESP_OK) {
memset(config.suffix, 0, sizeof(config.suffix));
if (length <= MDNS_CONFIG_SUFFIX_MAX_LEN) {
memcpy(config.suffix, suffix, length);
config.suffix_len = (uint8_t)length;
error = mdns_service_set_config(&config);
} else {
error = ESP_ERR_INVALID_ARG;
}
}
if (error != ESP_OK) {
printf("Suffix must be 1..%u lowercase letters, digits, or hyphens, and cannot begin or end with a hyphen.\n",
MDNS_CONFIG_SUFFIX_MAX_LEN);
return 1;
}
printf("mDNS suffix updated in RAM; hostname is sak-%s.local; use 'mdns save' to persist it.\n",
suffix);
return request_reannounce();
}
static int save_config(void)
{
mdns_config_t config;
esp_err_t error = mdns_service_get_config(&config);
if (error == ESP_OK) {
error = mdns_config_save(&config);
}
if (error != ESP_OK) {
printf("Could not save mDNS configuration: %s\n", esp_err_to_name(error));
return 1;
}
printf("mDNS configuration saved to NVS.\n");
return 0;
}
static int load_config(void)
{
mdns_config_t config;
bool stored = false;
esp_err_t error = mdns_config_load(&config, &stored);
if (error == ESP_OK) {
error = mdns_service_set_config(&config);
}
if (error != ESP_OK) {
printf("Could not load mDNS configuration: %s\n", esp_err_to_name(error));
return 1;
}
printf("Loaded %s mDNS configuration into RAM.\n", stored ? "stored" : "default");
return request_reannounce();
}
static int apply_defaults(bool persist)
{
mdns_config_t config;
mdns_config_defaults(&config);
esp_err_t error = mdns_service_set_config(&config);
if (error == ESP_OK && persist) {
error = mdns_config_save(&config);
}
if (error != ESP_OK) {
printf("Could not apply mDNS defaults: %s\n", esp_err_to_name(error));
return 1;
}
printf("MAC-derived mDNS defaults applied%s.\n", persist ? " and saved" : " in RAM");
return request_reannounce();
}
static int command_mdns(int argc, char **argv)
{
if (argc == 1 || (argc == 2 && strcmp(argv[1], "status") == 0)) {
return show_status();
}
if (argc == 3 && strcmp(argv[1], "suffix") == 0) {
return set_suffix(argv[2]);
}
if (argc == 2 && strcmp(argv[1], "save") == 0) {
return save_config();
}
if (argc == 2 && strcmp(argv[1], "load") == 0) {
return load_config();
}
if (argc == 2 && strcmp(argv[1], "defaults") == 0) {
return apply_defaults(false);
}
if (argc == 2 && strcmp(argv[1], "reset") == 0) {
return apply_defaults(true);
}
print_usage();
return 1;
}
esp_err_t mdns_console_register_commands(void)
{
const esp_console_cmd_t command = {
.command = "mdns",
.help = "Configure the STA mDNS hostname; use 'mdns' for status",
.hint = NULL,
.func = &command_mdns,
.argtable = NULL,
};
return esp_console_cmd_register(&command);
}
+6
View File
@@ -0,0 +1,6 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include "esp_err.h"
esp_err_t mdns_console_register_commands(void);
+208
View File
@@ -0,0 +1,208 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* mDNS runtime service; its lifecycle is owned by wifi_manager. */
#include "mdns_service.h"
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "mdns.h"
static SemaphoreHandle_t s_mutex;
static mdns_config_t s_config;
static uint32_t s_config_generation;
static bool s_component_initialized;
static bool s_initialization_failed;
static bool s_announced;
static esp_err_t s_last_error;
static void lock_service(void)
{
(void)xSemaphoreTake(s_mutex, portMAX_DELAY);
}
static void unlock_service(void)
{
(void)xSemaphoreGive(s_mutex);
}
static void make_hostname(const mdns_config_t *config, char *hostname, size_t size)
{
(void)snprintf(hostname, size, "sak-%s", config->suffix);
}
esp_err_t mdns_service_init(const mdns_config_t *config)
{
if (mdns_config_validate(config) != ESP_OK) {
return ESP_ERR_INVALID_ARG;
}
if (s_mutex != NULL) {
return ESP_ERR_INVALID_STATE;
}
s_mutex = xSemaphoreCreateMutex();
if (s_mutex == NULL) {
return ESP_ERR_NO_MEM;
}
s_config = *config;
s_config_generation = 1;
s_last_error = ESP_OK;
return ESP_OK;
}
esp_err_t mdns_service_get_config(mdns_config_t *config)
{
if (config == NULL || s_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
lock_service();
*config = s_config;
unlock_service();
return ESP_OK;
}
esp_err_t mdns_service_set_config(const mdns_config_t *config)
{
if (s_mutex == NULL || mdns_config_validate(config) != ESP_OK) {
return ESP_ERR_INVALID_ARG;
}
lock_service();
if (s_config_generation == UINT32_MAX) { unlock_service(); return ESP_ERR_INVALID_STATE; }
s_config = *config;
++s_config_generation;
unlock_service();
return ESP_OK;
}
static void snapshot_locked(mdns_service_snapshot_t *snapshot)
{
memset(snapshot, 0, sizeof(*snapshot));
snapshot->config_generation = s_config_generation;
snapshot->initialized = true;
snapshot->announced = s_announced;
memcpy(snapshot->suffix, s_config.suffix, s_config.suffix_len);
make_hostname(&s_config, snapshot->hostname, sizeof(snapshot->hostname));
snapshot->last_error = s_last_error;
}
esp_err_t mdns_service_get_snapshot(mdns_service_snapshot_t *snapshot)
{
if (!snapshot || !s_mutex) return ESP_ERR_INVALID_STATE;
lock_service();
snapshot_locked(snapshot);
unlock_service();
return ESP_OK;
}
esp_err_t mdns_service_get_settings(mdns_service_snapshot_t *snapshot)
{
if (!snapshot) return ESP_ERR_INVALID_ARG;
memset(snapshot, 0, sizeof(*snapshot));
if (!s_mutex) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_mutex, 0) != pdTRUE) return ESP_ERR_TIMEOUT;
snapshot_locked(snapshot);
unlock_service();
return ESP_OK;
}
esp_err_t mdns_service_update_current(uint32_t generation, mdns_settings_action_t action,
const mdns_config_t *config, bool *stored)
{
if (!stored || action > MDNS_SETTINGS_DEFAULTS || action < MDNS_SETTINGS_SET ||
(action == MDNS_SETTINGS_SET && mdns_config_validate(config) != ESP_OK)) return ESP_ERR_INVALID_ARG;
*stored = true;
if (!s_mutex) return ESP_ERR_INVALID_STATE;
lock_service();
if (!generation || generation != s_config_generation) { unlock_service(); return ESP_ERR_NOT_FOUND; }
esp_err_t error = ESP_OK;
mdns_config_t candidate = s_config;
if (action == MDNS_SETTINGS_SAVE) error = mdns_config_save(&s_config);
else if (s_config_generation == UINT32_MAX) error = ESP_ERR_INVALID_STATE;
else {
if (action == MDNS_SETTINGS_SET) candidate = *config;
else if (action == MDNS_SETTINGS_LOAD) error = mdns_config_load(&candidate, stored);
else mdns_config_defaults(&candidate);
if (error == ESP_OK) error = mdns_config_validate(&candidate);
if (error == ESP_OK) { s_config = candidate; ++s_config_generation; }
}
unlock_service();
return error;
}
esp_err_t mdns_service_start(void)
{
if (s_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
lock_service();
if (s_component_initialized) {
s_announced = true;
unlock_service();
/* A suffix staged while offline must reach the already-created responder
* when the next STA IP arrives, even if its reannounce command ran offline. */
return mdns_service_reannounce();
}
if (s_initialization_failed) {
esp_err_t error = s_last_error;
unlock_service();
return error;
}
mdns_config_t config = s_config;
unlock_service();
esp_err_t error = mdns_init();
if (error == ESP_OK) {
char hostname[MDNS_CONFIG_SUFFIX_MAX_LEN + 5U] = {0};
make_hostname(&config, hostname, sizeof(hostname));
error = mdns_hostname_set(hostname);
if (error == ESP_OK) {
error = mdns_instance_name_set("ESP32 Serial Swiss Army Knife");
}
if (error != ESP_OK) {
mdns_free();
}
}
lock_service();
s_component_initialized = error == ESP_OK;
s_initialization_failed = error != ESP_OK;
s_announced = error == ESP_OK;
s_last_error = error;
unlock_service();
return error;
}
void mdns_service_stop(void)
{
if (s_mutex == NULL) {
return;
}
lock_service();
s_announced = false;
unlock_service();
}
esp_err_t mdns_service_reannounce(void)
{
if (s_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
lock_service();
if (!s_component_initialized) {
esp_err_t error = s_initialization_failed ? s_last_error : ESP_ERR_INVALID_STATE;
unlock_service();
return error;
}
mdns_config_t config = s_config;
unlock_service();
char hostname[MDNS_CONFIG_SUFFIX_MAX_LEN + 5U] = {0};
make_hostname(&config, hostname, sizeof(hostname));
esp_err_t error = mdns_hostname_set(hostname);
lock_service();
s_last_error = error;
unlock_service();
return error;
}
+38
View File
@@ -0,0 +1,38 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* mDNS runtime service; its lifecycle is owned by wifi_manager. */
#pragma once
#include <stdbool.h>
#include "esp_err.h"
#include "mdns_config.h"
typedef struct {
uint32_t config_generation;
bool initialized;
bool announced;
char suffix[MDNS_CONFIG_SUFFIX_MAX_LEN + 1U];
char hostname[MDNS_CONFIG_SUFFIX_MAX_LEN + 5U];
esp_err_t last_error;
} mdns_service_snapshot_t;
esp_err_t mdns_service_init(const mdns_config_t *config);
esp_err_t mdns_service_get_config(mdns_config_t *config);
esp_err_t mdns_service_set_config(const mdns_config_t *config);
esp_err_t mdns_service_get_snapshot(mdns_service_snapshot_t *snapshot);
/* Zero-wait secret-free projection for HTTPD; ESP_ERR_TIMEOUT on contention. */
esp_err_t mdns_service_get_settings(mdns_service_snapshot_t *snapshot);
typedef enum { MDNS_SETTINGS_SET, MDNS_SETTINGS_SAVE, MDNS_SETTINGS_LOAD,
MDNS_SETTINGS_DEFAULTS } mdns_settings_action_t;
/* Dispatcher-only. Check generation and mutate/persist under the service mutex.
* ESP_ERR_NOT_FOUND is stale. LOAD may select deterministic MAC defaults (stored
* reports that distinction). Caller separately queues manager reannouncement. */
esp_err_t mdns_service_update_current(uint32_t generation, mdns_settings_action_t action,
const mdns_config_t *config, bool *stored);
/* Only wifi_manager may call these lifecycle operations. */
esp_err_t mdns_service_start(void);
void mdns_service_stop(void);
esp_err_t mdns_service_reannounce(void);
+120 -87
View File
@@ -12,8 +12,10 @@
#include "esp_console.h"
#include "esp_err.h"
#include "esp_heap_caps.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "lwip/inet.h"
#include "lwip/inet_chksum.h"
@@ -163,109 +165,111 @@ static int resolve_ping_target(const char *host, ip_addr_t *target,
return 0;
}
typedef enum {
PING_EVENT_LINE = 0,
PING_EVENT_END,
} ping_event_kind_t;
typedef struct {
TaskHandle_t waiting_task;
ping_event_kind_t kind;
char line[128];
char address[NUMERIC_ADDRESS_CAPACITY];
uint32_t transmitted;
uint32_t received;
uint32_t duration_ms;
esp_err_t profile_error;
esp_err_t delete_error;
bool received_reply;
bool summary_valid;
} ping_event_t;
typedef struct {
QueueHandle_t queue;
} ping_wait_context_t;
#define PING_EVENT_QUEUE_LENGTH (PING_MAX_COUNT + 1U)
static StaticQueue_t s_ping_queue_storage;
/* Dispatcher-owned lazy payload; retain for firmware lifetime so callback queue
* storage cannot dangle. Queue control stays internal. No internal-RAM fallback. */
static uint8_t *s_ping_queue_bytes;
static QueueHandle_t s_ping_queue;
static void ping_on_success(esp_ping_handle_t handle, void *arguments)
{
(void)arguments;
ping_wait_context_t *context = arguments;
ping_event_t event = {.kind = PING_EVENT_LINE};
uint16_t sequence = 0U;
uint8_t ttl = 0U;
uint32_t reply_size = 0U;
uint32_t elapsed_ms = 0U;
ip_addr_t reply_address;
char numeric[NUMERIC_ADDRESS_CAPACITY];
if (esp_ping_get_profile(handle, ESP_PING_PROF_SEQNO,
&sequence, sizeof(sequence)) != ESP_OK ||
esp_ping_get_profile(handle, ESP_PING_PROF_SIZE,
&reply_size, sizeof(reply_size)) != ESP_OK ||
esp_ping_get_profile(handle, ESP_PING_PROF_TIMEGAP,
&elapsed_ms, sizeof(elapsed_ms)) != ESP_OK ||
esp_ping_get_profile(handle, ESP_PING_PROF_IPADDR,
&reply_address, sizeof(reply_address)) != ESP_OK ||
ipaddr_ntoa_r(&reply_address, numeric, (int)sizeof(numeric)) == NULL) {
printf("ping: received a reply but could not read its profile\n");
return;
}
if (IP_IS_V4(&reply_address) &&
esp_ping_get_profile(handle, ESP_PING_PROF_TTL,
&ttl, sizeof(ttl)) == ESP_OK) {
printf("%" PRIu32 " bytes from %s: icmp_seq=%" PRIu16
" ttl=%u time=%" PRIu32 " ms\n",
reply_size, numeric, sequence, (unsigned int)ttl, elapsed_ms);
char numeric[NUMERIC_ADDRESS_CAPACITY] = "?";
bool valid = esp_ping_get_profile(handle, ESP_PING_PROF_SEQNO,
&sequence, sizeof(sequence)) == ESP_OK &&
esp_ping_get_profile(handle, ESP_PING_PROF_SIZE,
&reply_size, sizeof(reply_size)) == ESP_OK &&
esp_ping_get_profile(handle, ESP_PING_PROF_TIMEGAP,
&elapsed_ms, sizeof(elapsed_ms)) == ESP_OK &&
esp_ping_get_profile(handle, ESP_PING_PROF_IPADDR,
&reply_address, sizeof(reply_address)) == ESP_OK &&
ipaddr_ntoa_r(&reply_address, numeric, (int)sizeof(numeric)) != NULL;
if (!valid) {
strlcpy(event.line, "ping: received a reply but could not read its profile",
sizeof(event.line));
} else if (IP_IS_V4(&reply_address) &&
esp_ping_get_profile(handle, ESP_PING_PROF_TTL,
&ttl, sizeof(ttl)) == ESP_OK) {
snprintf(event.line, sizeof(event.line),
"%" PRIu32 " bytes from %s: icmp_seq=%" PRIu16
" ttl=%u time=%" PRIu32 " ms",
reply_size, numeric, sequence, (unsigned int)ttl, elapsed_ms);
} else {
printf("%" PRIu32 " bytes from %s: icmp_seq=%" PRIu16
" time=%" PRIu32 " ms\n",
reply_size, numeric, sequence, elapsed_ms);
snprintf(event.line, sizeof(event.line),
"%" PRIu32 " bytes from %s: icmp_seq=%" PRIu16
" time=%" PRIu32 " ms",
reply_size, numeric, sequence, elapsed_ms);
}
(void)xQueueSend(context->queue, &event, 0U);
}
static void ping_on_timeout(esp_ping_handle_t handle, void *arguments)
{
(void)arguments;
ping_wait_context_t *context = arguments;
ping_event_t event = {.kind = PING_EVENT_LINE};
uint16_t sequence = 0U;
ip_addr_t target_address;
char numeric[NUMERIC_ADDRESS_CAPACITY] = "?";
if (esp_ping_get_profile(handle, ESP_PING_PROF_SEQNO,
&sequence, sizeof(sequence)) == ESP_OK &&
esp_ping_get_profile(handle, ESP_PING_PROF_IPADDR,
&target_address, sizeof(target_address)) == ESP_OK) {
(void)ipaddr_ntoa_r(&target_address, numeric, (int)sizeof(numeric));
}
printf("From %s: icmp_seq=%" PRIu16 " timeout\n", numeric, sequence);
snprintf(event.line, sizeof(event.line), "From %s: icmp_seq=%" PRIu16 " timeout",
numeric, sequence);
(void)xQueueSend(context->queue, &event, 0U);
}
static void ping_on_end(esp_ping_handle_t handle, void *arguments)
{
ping_wait_context_t *context = (ping_wait_context_t *)arguments;
uint32_t transmitted = 0U;
uint32_t received = 0U;
uint32_t duration_ms = 0U;
ping_wait_context_t *context = arguments;
ping_event_t event = {.kind = PING_EVENT_END, .profile_error = ESP_OK};
ip_addr_t target_address;
char numeric[NUMERIC_ADDRESS_CAPACITY] = "?";
esp_err_t profile_error = esp_ping_get_profile(
handle, ESP_PING_PROF_REQUEST, &transmitted, sizeof(transmitted));
if (profile_error == ESP_OK) {
profile_error = esp_ping_get_profile(
handle, ESP_PING_PROF_REPLY, &received, sizeof(received));
strlcpy(event.address, "?", sizeof(event.address));
event.profile_error = esp_ping_get_profile(
handle, ESP_PING_PROF_REQUEST, &event.transmitted, sizeof(event.transmitted));
if (event.profile_error == ESP_OK) {
event.profile_error = esp_ping_get_profile(
handle, ESP_PING_PROF_REPLY, &event.received, sizeof(event.received));
}
if (profile_error == ESP_OK) {
profile_error = esp_ping_get_profile(
handle, ESP_PING_PROF_DURATION, &duration_ms, sizeof(duration_ms));
if (event.profile_error == ESP_OK) {
event.profile_error = esp_ping_get_profile(
handle, ESP_PING_PROF_DURATION, &event.duration_ms, sizeof(event.duration_ms));
}
if (esp_ping_get_profile(handle, ESP_PING_PROF_IPADDR,
&target_address, sizeof(target_address)) == ESP_OK) {
(void)ipaddr_ntoa_r(&target_address, numeric, (int)sizeof(numeric));
(void)ipaddr_ntoa_r(&target_address, event.address, (int)sizeof(event.address));
}
if (profile_error == ESP_OK) {
context->received_reply = received > 0U;
context->summary_valid = true;
uint32_t loss_percent = transmitted == 0U
? 0U
: ((transmitted - received) * 100U) / transmitted;
printf("\n--- %s ping statistics ---\n", numeric);
printf("%" PRIu32 " packets transmitted, %" PRIu32
" received, %" PRIu32 "%% packet loss, time %" PRIu32 " ms\n",
transmitted, received, loss_percent, duration_ms);
} else {
printf("ping: session ended, but summary profile retrieval failed: %s\n",
esp_err_to_name(profile_error));
}
/* Stop ping_sock's task before waking the higher-priority console caller. */
context->delete_error = esp_ping_delete_session(handle);
xTaskNotifyGive(context->waiting_task);
event.delete_error = esp_ping_delete_session(handle);
(void)xQueueSend(context->queue, &event, 0U);
}
static int execute_ping(int argc, char **argv)
@@ -288,12 +292,26 @@ static int execute_ping(int argc, char **argv)
return 1;
}
ping_wait_context_t context = {
.waiting_task = xTaskGetCurrentTaskHandle(),
.delete_error = ESP_FAIL,
};
/* Remove any unrelated notification before this command begins waiting. */
(void)ulTaskNotifyTake(pdTRUE, 0U);
if (s_ping_queue_bytes == NULL) {
s_ping_queue_bytes = heap_caps_malloc(
PING_EVENT_QUEUE_LENGTH * sizeof(ping_event_t),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (s_ping_queue_bytes == NULL) {
printf("ping: PSRAM event storage unavailable\n");
return 1;
}
}
if (s_ping_queue == NULL) {
s_ping_queue = xQueueCreateStatic(PING_EVENT_QUEUE_LENGTH, sizeof(ping_event_t),
s_ping_queue_bytes, &s_ping_queue_storage);
} else {
(void)xQueueReset(s_ping_queue);
}
if (s_ping_queue == NULL) {
printf("ping: could not allocate event queue\n");
return 1;
}
ping_wait_context_t context = {.queue = s_ping_queue};
esp_ping_config_t config = ESP_PING_DEFAULT_CONFIG();
config.count = count;
@@ -321,21 +339,36 @@ static int execute_ping(int argc, char **argv)
return 1;
}
/* Finite count guarantees on_ping_end; blocking keeps console output ordered. */
if (ulTaskNotifyTake(pdTRUE, portMAX_DELAY) == 0U) {
printf("ping: wait for session completion failed\n");
(void)esp_ping_stop(session);
(void)esp_ping_delete_session(session);
return 1;
for (;;) {
ping_event_t event;
if (xQueueReceive(s_ping_queue, &event, portMAX_DELAY) != pdTRUE) {
printf("ping: wait for session completion failed\n");
return 1;
}
if (event.kind == PING_EVENT_LINE) {
printf("%s\n", event.line);
continue;
}
if (event.profile_error != ESP_OK) {
printf("ping: session ended, but summary profile retrieval failed: %s\n",
esp_err_to_name(event.profile_error));
return 1;
}
uint32_t loss_percent = event.transmitted == 0U
? 0U
: ((event.transmitted - event.received) * 100U) /
event.transmitted;
printf("\n--- %s ping statistics ---\n", event.address);
printf("%" PRIu32 " packets transmitted, %" PRIu32
" received, %" PRIu32 "%% packet loss, time %" PRIu32 " ms\n",
event.transmitted, event.received, loss_percent, event.duration_ms);
if (event.delete_error != ESP_OK) {
printf("ping: could not delete session: %s\n",
esp_err_to_name(event.delete_error));
return 1;
}
return event.received > 0U ? 0 : 1;
}
bool command_succeeded = context.summary_valid && context.received_reply;
if (context.delete_error != ESP_OK) {
printf("ping: could not delete session: %s\n",
esp_err_to_name(context.delete_error));
return 1;
}
return command_succeeded ? 0 : 1;
}
static bool socket_addresses_equal(const struct addrinfo *left,
+4 -7
View File
@@ -1579,6 +1579,7 @@ DEFINE_OWNED_COMMAND(rts_flow_test)
static void print_debug_usage(void)
{
printf("Usage:\n");
printf(" debug status\n");
printf(" debug transceiver <enable|disable>\n");
printf(" debug drivers <TX 0|1> <DTR 0|1> <RTS 0|1>\n");
printf(" debug loopback-a|loopback-b|valid-test\n");
@@ -1595,6 +1596,9 @@ static int command_debug(int argc, char **argv)
}
/* Existing handlers expect their own command name in argv[0]. */
if (strcmp(argv[1], "status") == 0) {
return command_status(argc - 1, argv + 1);
}
if (strcmp(argv[1], "transceiver") == 0) {
return command_transceiver(argc - 1, argv + 1);
}
@@ -1647,13 +1651,6 @@ esp_err_t rs232_hw_test_register_console_commands(void)
}
const esp_console_cmd_t commands[] = {
{
.command = "status",
.help = "Show MAX3243 driver, receiver, VLD, and shutdown states",
.hint = NULL,
.func = &command_status,
.argtable = NULL,
},
{
.command = "debug",
.help = "Low-level RS-232 and local-UI hardware diagnostics; run 'debug' for subcommands",
+30
View File
@@ -0,0 +1,30 @@
#include "sdkconfig.h"
/* Check resolved configuration, not just defaults: existing sdkconfig files
* survive default changes. Crash memory may contain credentials and UART data.
* See docs/security_hardening.md before changing this supported-build policy. */
#if !defined(CONFIG_ESP_COREDUMP_ENABLE_TO_NONE) || !CONFIG_ESP_COREDUMP_ENABLE_TO_NONE
#error "Security policy: select CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y"
#endif
#if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH || CONFIG_ESP_COREDUMP_ENABLE_TO_UART || CONFIG_ESP_COREDUMP_ENABLE
#error "Security policy: flash and UART core dumps must be disabled"
#endif
#if !defined(CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT) || !CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT
#error "Security policy: select CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT=y"
#endif
#if CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT || CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT || CONFIG_ESP_SYSTEM_PANIC_GDBSTUB
#error "Security policy: panic register output and panic GDB stub must be disabled"
#endif
#if CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME
#error "Security policy: runtime GDB stub must be disabled"
#endif
/* Prevent a connected debugger from replacing panic recovery with a halt.
* This is not a physical JTAG access restriction and does not change eFuses. */
#if CONFIG_ESP_DEBUG_OCDAWARE || CONFIG_FREERTOS_DEBUG_OCDAWARE
#error "Security policy: JTAG/OCD-aware panic handling must be disabled"
#endif
+43 -4
View File
@@ -7,6 +7,7 @@
#include "driver/gpio.h"
#include "driver/uart.h"
#include "esp_check.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
@@ -17,8 +18,10 @@
#define SERIAL_UART_RX_RING_SIZE 8192
#define SERIAL_UART_EVENT_QUEUE_SIZE 64
#define SERIAL_RX_STREAM_SIZE 16384
#define SERIAL_TX_STREAM_SIZE 8192
#define SERIAL_RX_STREAM_SIZE 16384U
#define SERIAL_TX_STREAM_SIZE 8192U
#define SERIAL_RX_STREAM_STORAGE_SIZE (SERIAL_RX_STREAM_SIZE + 1U)
#define SERIAL_TX_STREAM_STORAGE_SIZE (SERIAL_TX_STREAM_SIZE + 1U)
#define SERIAL_IO_CHUNK_SIZE 256
#define SERIAL_TASK_STACK_SIZE 4096
#define SERIAL_TASK_PRIORITY 10
@@ -32,6 +35,10 @@ static SemaphoreHandle_t s_state_mutex;
static SemaphoreHandle_t s_task_stopped;
static StreamBufferHandle_t s_rx_stream;
static StreamBufferHandle_t s_tx_stream;
static StaticStreamBuffer_t s_rx_stream_control;
static StaticStreamBuffer_t s_tx_stream_control;
static uint8_t *s_rx_stream_storage;
static uint8_t *s_tx_stream_storage;
static QueueHandle_t s_uart_event_queue;
static TaskHandle_t s_event_task;
static portMUX_TYPE s_counter_lock = portMUX_INITIALIZER_UNLOCKED;
@@ -472,8 +479,24 @@ esp_err_t serial_service_init(const serial_config_t *initial_config)
s_state_mutex = xSemaphoreCreateMutex();
s_task_stopped = xSemaphoreCreateBinary();
s_rx_stream = xStreamBufferCreate(SERIAL_RX_STREAM_SIZE, 1);
s_tx_stream = xStreamBufferCreate(SERIAL_TX_STREAM_SIZE, 1);
s_rx_stream_storage = heap_caps_calloc_prefer(
1U, SERIAL_RX_STREAM_STORAGE_SIZE, 2,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
s_tx_stream_storage = heap_caps_calloc_prefer(
1U, SERIAL_TX_STREAM_STORAGE_SIZE, 2,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
if (s_rx_stream_storage != NULL) {
s_rx_stream = xStreamBufferCreateStatic(
SERIAL_RX_STREAM_STORAGE_SIZE, 1U, s_rx_stream_storage,
&s_rx_stream_control);
}
if (s_tx_stream_storage != NULL) {
s_tx_stream = xStreamBufferCreateStatic(
SERIAL_TX_STREAM_STORAGE_SIZE, 1U, s_tx_stream_storage,
&s_tx_stream_control);
}
if (s_state_mutex == NULL || s_task_stopped == NULL ||
s_rx_stream == NULL || s_tx_stream == NULL) {
if (s_state_mutex != NULL) {
@@ -488,10 +511,14 @@ esp_err_t serial_service_init(const serial_config_t *initial_config)
if (s_tx_stream != NULL) {
vStreamBufferDelete(s_tx_stream);
}
heap_caps_free(s_rx_stream_storage);
heap_caps_free(s_tx_stream_storage);
s_state_mutex = NULL;
s_task_stopped = NULL;
s_rx_stream = NULL;
s_tx_stream = NULL;
s_rx_stream_storage = NULL;
s_tx_stream_storage = NULL;
return ESP_ERR_NO_MEM;
}
@@ -619,6 +646,18 @@ esp_err_t serial_service_get_config(serial_config_t *config)
return ESP_OK;
}
esp_err_t serial_service_get_snapshot(serial_service_snapshot_t *snapshot)
{
if (snapshot == NULL) return ESP_ERR_INVALID_ARG;
memset(snapshot, 0, sizeof(*snapshot));
if (!s_initialized) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_state_mutex, 0) != pdTRUE) return ESP_ERR_TIMEOUT;
snapshot->config = s_config;
snapshot->running = atomic_load(&s_running);
xSemaphoreGive(s_state_mutex);
return ESP_OK;
}
size_t serial_service_read(uint8_t *data, size_t size)
{
if (!s_initialized || data == NULL || size == 0) {
+8
View File
@@ -48,6 +48,14 @@ bool serial_service_is_running(void);
esp_err_t serial_service_apply_config(const serial_config_t *config);
esp_err_t serial_service_get_config(serial_config_t *config);
typedef struct {
serial_config_t config;
bool running;
} serial_service_snapshot_t;
/* Nonblocking, consistent working configuration/state; no hardware or NVS IO. */
esp_err_t serial_service_get_snapshot(serial_service_snapshot_t *snapshot);
/*
* Access is intentionally nonblocking. The session broker is the sole
* logical RX consumer and TX producer; calls are serialized internally to
+58 -5
View File
@@ -47,6 +47,8 @@ static session_broker_slot_t s_slots[SESSION_BROKER_MAX_CLIENTS];
static session_broker_client_id_t s_writer_id;
static uint32_t s_connected_clients;
static uint64_t s_event_sequence;
/* Saturation disables management confirmations, never ordinary recovery. */
static uint32_t s_writer_generation = 1U;
static session_broker_global_counters_t s_counters;
static bool s_initialized;
@@ -102,6 +104,10 @@ static void broadcast_event_locked(session_broker_event_type_t type,
session_broker_client_id_t client_id,
session_broker_client_id_t writer_id)
{
if ((type == SESSION_BROKER_EVENT_WRITER_GRANTED ||
type == SESSION_BROKER_EVENT_WRITER_RELEASED ||
type == SESSION_BROKER_EVENT_WRITER_REVOKED) && s_writer_generation != UINT32_MAX)
++s_writer_generation;
session_broker_event_t event = {
.sequence = ++s_event_sequence,
.type = type,
@@ -149,6 +155,10 @@ static void fan_out_rx_locked(const uint8_t *data, size_t size)
slot->counters.uart_rx_bytes += size;
size_t queued = xStreamBufferSend(slot->output, data, size, 0);
size_t pending = xStreamBufferBytesAvailable(slot->output);
if (pending > slot->counters.output_high_water_bytes) {
slot->counters.output_high_water_bytes = pending;
}
size_t dropped = size - queued;
slot->counters.output_queued_bytes += queued;
slot->counters.output_dropped_bytes += dropped;
@@ -295,7 +305,8 @@ esp_err_t session_broker_connect(session_broker_client_type_t type,
session_broker_slot_t *slot = NULL;
size_t slot_index = 0U;
for (; slot_index < SESSION_BROKER_MAX_CLIENTS; ++slot_index) {
if (!s_slots[slot_index].connected) {
if (!s_slots[slot_index].connected &&
s_slots[slot_index].generation < SESSION_BROKER_MAX_GENERATION) {
slot = &s_slots[slot_index];
break;
}
@@ -315,9 +326,7 @@ esp_err_t session_broker_connect(session_broker_client_type_t type,
}
uint32_t generation = slot->generation + 1U;
if (generation == 0U || generation > SESSION_BROKER_MAX_GENERATION) {
generation = 1U;
}
/* Exhausted slots are retired until reboot: no 29-bit ID reuse. */
xStreamBufferReset(slot->output);
xQueueReset(slot->events);
@@ -466,13 +475,19 @@ esp_err_t session_broker_release_writer(session_broker_client_id_t client_id)
return ESP_OK;
}
esp_err_t session_broker_force_writer(session_broker_client_id_t client_id)
static esp_err_t broker_force_writer(session_broker_client_id_t client_id,
uint32_t expected_generation)
{
if (!s_initialized) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
if (expected_generation && (expected_generation == UINT32_MAX ||
expected_generation != s_writer_generation)) {
xSemaphoreGive(s_mutex);
return ESP_ERR_INVALID_STATE;
}
session_broker_slot_t *new_writer = NULL;
if (client_id != SESSION_BROKER_NO_CLIENT) {
new_writer = find_slot_locked(client_id);
@@ -518,6 +533,41 @@ esp_err_t session_broker_force_writer(session_broker_client_id_t client_id)
return ESP_OK;
}
esp_err_t session_broker_force_writer(session_broker_client_id_t client_id)
{
return broker_force_writer(client_id, 0);
}
esp_err_t session_broker_assign_writer_current(session_broker_client_id_t client_id,
uint32_t generation)
{
if (!client_id || !generation) return ESP_ERR_INVALID_ARG;
return broker_force_writer(client_id, generation);
}
esp_err_t session_broker_get_management_snapshot(session_broker_management_snapshot_t *snapshot)
{
if (!snapshot) return ESP_ERR_INVALID_ARG;
if (!s_initialized) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_mutex, 0) != pdTRUE) return ESP_ERR_TIMEOUT;
memset(snapshot, 0, sizeof(*snapshot));
snapshot->generation = s_writer_generation;
snapshot->writer_id = s_writer_id;
for (size_t i = 0; i < SESSION_BROKER_MAX_CLIENTS; ++i) {
const session_broker_slot_t *slot = &s_slots[i];
if (!slot->connected) continue;
session_broker_management_client_t *client = &snapshot->clients[snapshot->count++];
client->id = slot->id;
client->type = slot->type;
memcpy(client->name, slot->name, sizeof(client->name));
client->pending = xStreamBufferBytesAvailable(slot->output);
client->high_water = slot->counters.output_high_water_bytes;
client->dropped = slot->counters.output_dropped_bytes;
}
xSemaphoreGive(s_mutex);
return ESP_OK;
}
esp_err_t session_broker_force_release_writer(
session_broker_client_id_t expected_writer_id)
{
@@ -740,6 +790,8 @@ esp_err_t session_broker_clear_counters(void)
memset(&s_counters, 0, sizeof(s_counters));
for (size_t i = 0; i < SESSION_BROKER_MAX_CLIENTS; ++i) {
memset(&s_slots[i].counters, 0, sizeof(s_slots[i].counters));
s_slots[i].counters.output_high_water_bytes =
xStreamBufferBytesAvailable(s_slots[i].output);
}
xSemaphoreGive(s_mutex);
return ESP_OK;
@@ -758,6 +810,7 @@ esp_err_t session_broker_clear_client_counters(session_broker_client_id_t client
return ESP_ERR_NOT_FOUND;
}
memset(&slot->counters, 0, sizeof(slot->counters));
slot->counters.output_high_water_bytes = xStreamBufferBytesAvailable(slot->output);
xSemaphoreGive(s_mutex);
return ESP_OK;
}
+39 -2
View File
@@ -49,6 +49,11 @@ typedef struct {
session_broker_client_id_t writer_id;
} session_broker_event_t;
/*
* Active-client counters cover this connection (or the last counter clear).
* They become unavailable on disconnect and reset on slot/generation reuse;
* global totals retain disconnected clients' traffic until explicitly cleared.
*/
typedef struct {
/* UART bytes considered for delivery while this client was connected. */
uint64_t uart_rx_bytes;
@@ -67,13 +72,18 @@ typedef struct {
uint64_t events_queued;
uint64_t events_popped;
uint64_t event_drops;
/* Peak output occupancy, <= SESSION_BROKER_OUTPUT_SIZE; clear seeds pending. */
size_t output_high_water_bytes;
} session_broker_client_counters_t;
typedef struct {
uint64_t uart_rx_bytes;
/* UART RX drained when there were no connected observers. */
uint64_t unobserved_rx_bytes;
/* Queue/read/drop totals count one copy per client observer. */
/* Queue/read/drop totals count one copy per client observer.
* Drops include full-buffer losses and unread output discarded on disconnect.
* Read means handed to a transport, not confirmed delivery to its peer.
*/
uint64_t output_queued_bytes;
uint64_t output_read_bytes;
uint64_t output_dropped_bytes;
@@ -110,6 +120,31 @@ typedef struct {
session_broker_global_counters_t counters;
} session_broker_global_snapshot_t;
/* Compact, atomic, non-consuming management projection. No transport pointers. */
typedef struct {
session_broker_client_id_t id;
session_broker_client_type_t type;
char name[SESSION_BROKER_CLIENT_NAME_MAX + 1U];
size_t pending, high_water;
uint64_t dropped;
} session_broker_management_client_t;
typedef struct {
uint32_t generation;
session_broker_client_id_t writer_id;
size_t count;
session_broker_management_client_t clients[SESSION_BROKER_MAX_CLIENTS];
} session_broker_management_snapshot_t;
/* Zero-wait atomic snapshot. Generation survives counter clears; UINT32_MAX
* means confirmations exhausted until reboot. Every lease transition advances
* it, including release/reacquire ABA. Client IDs never wrap within a boot. */
esp_err_t session_broker_get_management_snapshot(session_broker_management_snapshot_t *snapshot);
/* Nonzero target and generation required; compare + target validation + transfer
* share the broker lock. Stale/exhausted generation or absent target has no effects.
* Existing unconditional force remains available to recovery/console callers. */
esp_err_t session_broker_assign_writer_current(session_broker_client_id_t client_id,
uint32_t generation);
/*
* Allocates all eight output streams and event queues, then starts the
* permanent broker task. The serial service must already be initialized
@@ -158,7 +193,9 @@ esp_err_t session_broker_get_global_snapshot(session_broker_global_snapshot_t *s
size_t session_broker_list_clients(session_broker_client_snapshot_t *clients,
size_t capacity);
/* Counter clearing does not reset client IDs, queued data, or event sequence. */
/* Counter clearing does not reset client IDs, queued data, or event sequence.
* Client output high-water marks restart at current queued occupancy, not zero.
*/
esp_err_t session_broker_clear_counters(void);
esp_err_t session_broker_clear_client_counters(session_broker_client_id_t client_id);
+20
View File
@@ -182,6 +182,26 @@ static int show_counters(void)
counter->events_queued,
counter->events_popped,
counter->event_drops);
session_broker_client_snapshot_t clients[SESSION_BROKER_MAX_CLIENTS];
size_t count = session_broker_list_clients(clients, SESSION_BROKER_MAX_CLIENTS);
printf("Active clients (since connect/clear; lost on disconnect; global totals retained):\n");
printf("Output bytes: HWM <= %u; clear seeds pending; read = handed to transport.\n",
(unsigned int)SESSION_BROKER_OUTPUT_SIZE);
printf("Global dropped also includes unread output discarded on disconnect.\n");
printf("ID type pending HWM UART queued read dropped\n");
for (size_t index = 0; index < count; ++index) {
const session_broker_client_snapshot_t *client = &clients[index];
printf("%-10lu %-9s %-7u %-7u %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
(unsigned long)client->id,
client_type_name(client->type),
(unsigned int)client->output_bytes_pending,
(unsigned int)client->counters.output_high_water_bytes,
client->counters.uart_rx_bytes,
client->counters.output_queued_bytes,
client->counters.output_read_bytes,
client->counters.output_dropped_bytes);
}
return 0;
}
+50
View File
@@ -0,0 +1,50 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "ssh_auth_policy.h"
#include <stddef.h>
bool ssh_auth_policy_admit(ssh_auth_policy_t *policy,
ssh_auth_policy_kind_t kind, int64_t now_us)
{
if (policy == NULL || (unsigned)kind >= SSH_AUTH_POLICY_KIND_COUNT || now_us < 0) {
return false;
}
for (unsigned i = 0; i < SSH_AUTH_POLICY_KIND_COUNT; ++i) {
if (policy->buckets[i].initialized && now_us < policy->buckets[i].last_seen_us) {
return false;
}
}
const unsigned capacity = kind == SSH_AUTH_POLICY_PROBE
? SSH_AUTH_POLICY_PROBE_CAPACITY
: kind == SSH_AUTH_POLICY_HANDSHAKE
? SSH_AUTH_POLICY_HANDSHAKE_CAPACITY : SSH_AUTH_POLICY_VERIFICATION_CAPACITY;
const int64_t interval = kind == SSH_AUTH_POLICY_PROBE
? SSH_AUTH_POLICY_PROBE_REFILL_US
: kind == SSH_AUTH_POLICY_HANDSHAKE
? SSH_AUTH_POLICY_HANDSHAKE_REFILL_US : SSH_AUTH_POLICY_VERIFICATION_REFILL_US;
ssh_auth_policy_bucket_t *bucket = &policy->buckets[kind];
if (!bucket->initialized) {
bucket->tokens = (uint8_t)capacity;
bucket->refill_us = now_us;
bucket->initialized = true;
} else {
/* Both timestamps are nonnegative and ordered. Divide before adding
* to avoid overflow even for a jump from zero to INT64_MAX. */
const int64_t elapsed = now_us - bucket->refill_us;
const int64_t earned = elapsed / interval;
if (earned >= (int64_t)(capacity - bucket->tokens)) {
bucket->tokens = (uint8_t)capacity;
bucket->refill_us = now_us;
} else {
bucket->tokens += (uint8_t)earned;
bucket->refill_us = now_us - elapsed % interval;
}
}
bucket->last_seen_us = now_us;
if (bucket->tokens == 0) {
return false;
}
--bucket->tokens;
return true;
}
+44
View File
@@ -0,0 +1,44 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#define SSH_AUTH_POLICY_HANDSHAKE_CAPACITY 6U
#define SSH_AUTH_POLICY_HANDSHAKE_REFILL_US INT64_C(10000000)
#define SSH_AUTH_POLICY_VERIFICATION_CAPACITY 6U
#define SSH_AUTH_POLICY_VERIFICATION_REFILL_US INT64_C(10000000)
#define SSH_AUTH_POLICY_PROBE_CAPACITY 12U
#define SSH_AUTH_POLICY_PROBE_REFILL_US INT64_C(5000000)
typedef enum {
SSH_AUTH_POLICY_HANDSHAKE,
SSH_AUTH_POLICY_VERIFICATION,
SSH_AUTH_POLICY_PROBE,
SSH_AUTH_POLICY_KIND_COUNT
} ssh_auth_policy_kind_t;
typedef struct {
int64_t refill_us;
int64_t last_seen_us;
uint8_t tokens;
bool initialized;
} ssh_auth_policy_bucket_t;
typedef struct {
ssh_auth_policy_bucket_t buckets[SSH_AUTH_POLICY_KIND_COUNT];
} ssh_auth_policy_t;
/* Single-owner only: no allocation, locks, clock reads, timers or sleeps.
* Start zero-initialized; each class lazily starts at capacity. The owner must
* retain one shared instance across sessions, stop/start and counter clears;
* only reboot resets it. Do not modify fields directly or refund admissions.
* Each true result consumes one token, regardless of subsequent auth outcome.
* Refill adds one token per class-specific interval, preserving partial credit
* below capacity and discarding all surplus (including fractions) at capacity.
* now_us must be nonnegative and nondecreasing across ALL classes (equal is OK).
* NULL, invalid kind, negative time and regression reject without mutation.
* An empty-bucket denial records time but never postpones the refill deadline.
*/
bool ssh_auth_policy_admit(ssh_auth_policy_t *policy,
ssh_auth_policy_kind_t kind, int64_t now_us);
+83 -13
View File
@@ -9,6 +9,7 @@
#include <stdlib.h>
#include <string.h>
#include "admin_ssh_console.h"
#include "esp_console.h"
#include "mbedtls/base64.h"
#include "secure_random.h"
@@ -50,6 +51,15 @@ static const char *auth_method_name(user_auth_method_t method)
: method == USER_AUTH_METHOD_SSH_PUBLIC_KEY ? "public-key" : "unknown";
}
static const char *route_name(ssh_transport_session_route_t route)
{
return route == SSH_TRANSPORT_ROUTE_BROKER
? "broker"
: route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE
? "admin-console"
: "none";
}
static int print_sessions(const ssh_transport_snapshot_t *snapshot)
{
printf("SSH sessions: active=%" PRIu32 "/%u\n",
@@ -60,21 +70,22 @@ static int print_sessions(const ssh_transport_snapshot_t *snapshot)
continue;
}
printf(" id=%" PRIu32 " slot=%u peer=%s state=%s auth=%s account=%s"
" user-role=%s method=%s broker=%" PRIu32
" broker-role=%s rx-pending=%s tx-pending=%s closing=%s\n",
" user-role=%s method=%s route=%s broker=%" PRIu32
" broker-role=%s admin-command=%s admin-output=%" PRIu32
" rx-pending=%s tx-pending=%s closing=%s\n",
session->session_id, (unsigned int)index, session->peer,
state_name(session->state), session->authenticated ? "yes" : "no",
session->principal_valid ? session->username : "-",
session->principal_valid
? user_role_to_string(session->user_role)
: "-",
session->principal_valid
? auth_method_name(session->auth_method)
: "-",
session->broker_client_id,
session->broker_client_id == SESSION_BROKER_NO_CLIENT
? "unattached"
: (session->writer ? "writer" : "observer"),
session->principal_valid ? user_role_to_string(session->user_role) : "-",
session->principal_valid ? auth_method_name(session->auth_method) : "-",
route_name(session->route), session->broker_client_id,
session->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE
? "n/a"
: (session->broker_client_id == SESSION_BROKER_NO_CLIENT
? "unattached"
: (session->writer ? "writer" : "observer")),
session->admin_command_pending ? "running" : "idle",
session->admin_output_pending,
session->rx_pending ? "yes" : "no",
session->tx_pending ? "yes" : "no",
session->close_requested ? "yes" : "no");
@@ -127,6 +138,16 @@ static int show_counters(void)
counter->handshake_successes, counter->handshake_failures,
counter->handshake_timeouts, counter->authentication_attempts,
counter->authentication_failures, counter->request_rejections);
printf("Auth admission: handshakes=%" PRIu64 " handshake-throttled=%" PRIu64
" verifications=%" PRIu64 " verification-throttled=%" PRIu64 "\n",
counter->handshake_admissions, counter->handshake_throttle_rejections,
counter->authentication_admissions, counter->authentication_throttle_rejections);
printf("Auth policy: probes=%" PRIu64 " probe-throttled=%" PRIu64
" attempt-limit-closes=%" PRIu64 " backend-errors=%" PRIu64
" method-rejects=%" PRIu64 "\n",
counter->authentication_probe_admissions, counter->authentication_probe_rejections,
counter->authentication_limit_disconnects, counter->authentication_backend_errors,
counter->authentication_method_rejections);
printf("Broker: connect=%" PRIu64 " failures=%" PRIu64
" disconnect=%" PRIu64 " writer-requests=%" PRIu64
" grants=%" PRIu64 " denials=%" PRIu64
@@ -135,6 +156,10 @@ static int show_counters(void)
counter->disconnections, counter->writer_requests,
counter->writer_grants, counter->writer_denials,
counter->writer_revocations);
printf("Admin console: admissions=%" PRIu64 " admission-failures=%" PRIu64
" input-backpressure=%" PRIu64 "\n",
counter->admin_console_admissions, counter->admin_console_admission_failures,
counter->admin_console_input_rejections);
printf("Stream: rx=%" PRIu64 " accepted=%" PRIu64
" rejected=%" PRIu64 " tx=%" PRIu64
" io-failures=%" PRIu64 " session-revocations=%" PRIu64 "\n",
@@ -193,6 +218,18 @@ static bool parse_session_id(const char *text, uint32_t *session_id)
static int replace_host_key(bool reset)
{
if (admin_ssh_console_dispatch_is_remote()) {
esp_err_t deferred = admin_ssh_console_dispatch_defer(
reset ? ADMIN_SSH_DEFER_HOST_KEY_RESET : ADMIN_SSH_DEFER_HOST_KEY_ROTATE, 0U);
if (deferred != ESP_OK) {
printf("Could not schedule SSH host-key replacement: %s\n",
esp_err_to_name(deferred));
return 1;
}
printf("SSH host-key %s scheduled after output drains; all SSH sessions will close.\n",
reset ? "reset" : "rotation");
return 0;
}
ssh_security_metadata_t before = {0};
bool had_before = ssh_security_get_metadata(&before) == ESP_OK;
esp_err_t error = ssh_transport_replace_host_key(reset);
@@ -242,6 +279,16 @@ static int command_ssh(int argc, char **argv)
return 0;
}
if (argc == 2 && strcmp(argv[1], "stop") == 0) {
if (admin_ssh_console_dispatch_is_remote()) {
esp_err_t deferred = admin_ssh_console_dispatch_defer(
ADMIN_SSH_DEFER_STOP, 0U);
if (deferred != ESP_OK) {
printf("Could not schedule SSH stop: %s\n", esp_err_to_name(deferred));
return 1;
}
printf("SSH stop scheduled after output drains; all SSH sessions will close.\n");
return 0;
}
esp_err_t error = ssh_transport_stop();
if (error != ESP_OK) {
printf("Could not stop SSH: %s\n", esp_err_to_name(error));
@@ -268,7 +315,30 @@ static int command_ssh(int argc, char **argv)
printf("Session ID must be a nonzero decimal integer.\n");
return 1;
}
esp_err_t error = ssh_transport_disconnect(session_id);
esp_err_t error;
if (admin_ssh_console_dispatch_is_remote()) {
ssh_transport_snapshot_t snapshot;
error = ssh_transport_get_snapshot(&snapshot);
bool found = false;
if (error == ESP_OK) {
for (size_t index = 0U; index < SSH_TRANSPORT_MAX_SESSIONS; ++index) {
if (snapshot.sessions[index].active &&
snapshot.sessions[index].session_id == session_id) {
found = true;
break;
}
}
if (!found) {
error = ESP_ERR_NOT_FOUND;
}
}
if (error == ESP_OK) {
error = admin_ssh_console_dispatch_defer(
ADMIN_SSH_DEFER_DISCONNECT, session_id);
}
} else {
error = ssh_transport_disconnect(session_id);
}
if (error != ESP_OK) {
printf("Could not disconnect SSH session: %s\n", esp_err_to_name(error));
return 1;
+62
View File
@@ -0,0 +1,62 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "ssh_memory.h"
#include <string.h>
#include "sdkconfig.h"
#include "esp_heap_caps.h"
#include "esp_idf_version.h"
#include "secure_random.h"
#if !defined(CONFIG_HEAP_POISONING_DISABLED) || !CONFIG_HEAP_POISONING_DISABLED || \
(defined(CONFIG_HEAP_POISONING_LIGHT) && CONFIG_HEAP_POISONING_LIGHT) || \
(defined(CONFIG_HEAP_POISONING_COMPREHENSIVE) && CONFIG_HEAP_POISONING_COMPREHENSIVE)
#error "SSH memory requires heap poisoning disabled"
#endif
#if ESP_IDF_VERSION != ESP_IDF_VERSION_VAL(5, 5, 3)
#error "Reaudit SSH memory usable extent contract for this IDF"
#endif
void *ssh_memory_malloc(size_t size)
{
return heap_caps_malloc_prefer(size, 2,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
}
void ssh_memory_free(void *pointer)
{
if (pointer == NULL) {
return;
}
secure_wipe(pointer, heap_caps_get_allocated_size(pointer));
heap_caps_free(pointer);
}
void *ssh_memory_realloc(void *pointer, size_t size)
{
if (pointer == NULL) {
return ssh_memory_malloc(size);
}
if (size == 0U) {
ssh_memory_free(pointer);
return NULL;
}
/* Audited unpoisoned IDF 5.5.3 reports the owned usable extent, including
* rounding. Do not substitute an interior-pointer/block-containing query. */
size_t capacity = heap_caps_get_allocated_size(pointer);
if (size <= capacity) {
secure_wipe((unsigned char *)pointer + size, capacity - size);
return pointer;
}
void *replacement = ssh_memory_malloc(size);
if (replacement == NULL) {
return NULL;
}
memcpy(replacement, pointer, capacity);
ssh_memory_free(pointer);
return replacement;
}
+31
View File
@@ -0,0 +1,31 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Install these hooks before wolfSSH/wolfSSL allocations begin. No module state,
* locks or allocation headers. Free/realloc accept only live allocation BASE
* pointers from this allocator (or NULL), never interior pointers.
*
* PSRAM is preferred, with internal 8-bit heap fallback. malloc(0) follows the
* SDK allocator. free wipes the full owned usable extent. realloc(NULL, size)
* delegates to malloc; realloc(non-NULL, 0) securely frees and returns NULL.
*
* Realloc within the usable extent retains the pointer AND capacity: it wipes
* [size, capacity), but does not reclaim memory. Growth copies the entire old
* usable extent, not merely the original requested size. Both allocations are
* live until copying finishes; failure leaves the old allocation unchanged.
* This is heap-retirement cleanup, not a guarantee about live library buffers
* or stack secrets. Only the guarded, audited unpoisoned IDF build is supported.
*/
void *ssh_memory_malloc(size_t size);
void ssh_memory_free(void *pointer);
void *ssh_memory_realloc(void *pointer, size_t size);
#ifdef __cplusplus
}
#endif
+37
View File
@@ -0,0 +1,37 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "ssh_protocol_policy.h"
#include <stddef.h>
#include <wolfssh/error.h>
#include <wolfssh/version.h>
#if LIBWOLFSSH_VERSION_HEX != 0x01004020
#error "Re-audit SSH protocol policy and algorithm-list contracts for this wolfSSH version"
#endif
/* wolfSSH borrows these pointers in both contexts and sessions. */
static const char s_kex[] = "curve25519-sha256,ecdh-sha2-nistp256";
static const char s_host_key[] = "ecdsa-sha2-nistp256";
static const char s_cipher[] = "aes128-gcm@openssh.com,aes256-gcm@openssh.com";
static const char s_mac[] = "hmac-sha2-256";
/* server-sig-algs advertisement only; the user database enforces enrollment. */
static const char s_key_accepted[] = "ssh-ed25519,ecdsa-sha2-nistp256";
int ssh_protocol_policy_apply(WOLFSSH_CTX *context)
{
if (context == NULL) {
return WS_SSH_CTX_NULL_E;
}
int result = wolfSSH_CTX_SetAlgoListKex(context, s_kex);
if (result != WS_SUCCESS) return result;
result = wolfSSH_CTX_SetAlgoListKey(context, s_host_key);
if (result != WS_SUCCESS) return result;
result = wolfSSH_CTX_SetAlgoListCipher(context, s_cipher);
if (result != WS_SUCCESS) return result;
result = wolfSSH_CTX_SetAlgoListMac(context, s_mac);
if (result != WS_SUCCESS) return result;
result = wolfSSH_CTX_SetAlgoListKeyAccepted(context, s_key_accepted);
if (result != WS_SUCCESS) return result;
return WS_SUCCESS;
}
+10
View File
@@ -0,0 +1,10 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include <wolfssh/ssh.h>
/* Apply before publishing the context or creating sessions. Returns WS_SUCCESS
* or the first setter error (WS_SSH_CTX_NULL_E for NULL). Failure may leave a
* partially configured context: the caller must discard it, never fall back to
* defaults. Does not allocate, free, or publish the context. */
int ssh_protocol_policy_apply(WOLFSSH_CTX *context);
+83 -45
View File
@@ -48,6 +48,9 @@ static bool s_mutex_creating;
static ssh_security_blob_t s_material;
static bool s_material_ready;
static ssh_security_load_result_t s_load_result;
static uint32_t s_identity_token, s_next_identity_token;
static TaskHandle_t s_identity_owner;
static bool s_identity_used;
static bool bytes_are_zero(const uint8_t *data, size_t size)
{
@@ -338,6 +341,10 @@ esp_err_t ssh_security_init(ssh_security_load_result_t *load_result)
return ESP_OK;
}
if (s_identity_token) {
xSemaphoreGive(s_security_mutex);
return ESP_ERR_INVALID_STATE;
}
ssh_security_blob_t candidate;
bool missing = false;
error = load_blob(&candidate, &missing);
@@ -411,60 +418,91 @@ esp_err_t ssh_security_get_metadata(ssh_security_metadata_t *metadata)
return error;
}
esp_err_t ssh_security_rotate(void)
esp_err_t ssh_security_get_identity_snapshot(ssh_security_identity_snapshot_t *snapshot)
{
if (s_security_mutex == NULL) {
if (!snapshot) return ESP_ERR_INVALID_ARG;
memset(snapshot, 0, sizeof(*snapshot));
if (!s_security_mutex) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_security_mutex, 0U) != pdTRUE) return ESP_ERR_TIMEOUT;
esp_err_t error = s_material_ready ? ESP_OK : ESP_ERR_INVALID_STATE;
if (error == ESP_OK) {
snapshot->metadata.generation = s_material.generation;
memcpy(snapshot->metadata.sha256_fingerprint, s_material.sha256_fingerprint,
sizeof(snapshot->metadata.sha256_fingerprint));
snapshot->busy = s_identity_token != 0 || s_next_identity_token == UINT32_MAX;
}
xSemaphoreGive(s_security_mutex);
return error;
}
esp_err_t ssh_security_reserve_identity(uint32_t generation, bool reset, uint32_t *token)
{
if (!token || (reset && generation)) return ESP_ERR_INVALID_ARG;
*token = 0;
if (reset) {
esp_err_t error = secure_random_init();
if (error == ESP_OK) error = ensure_mutex();
if (error != ESP_OK) return error;
}
if (!s_security_mutex) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_security_mutex, 0U) != pdTRUE) return ESP_ERR_TIMEOUT;
if (s_identity_token || s_next_identity_token == UINT32_MAX ||
(!s_material_ready && !reset) ||
(s_material_ready && s_material.generation == UINT32_MAX) ||
(generation && generation != s_material.generation)) {
xSemaphoreGive(s_security_mutex);
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_security_mutex, portMAX_DELAY);
esp_err_t error = ESP_ERR_INVALID_STATE;
ssh_security_blob_t candidate;
memset(&candidate, 0, sizeof(candidate));
if (s_material_ready && s_material.generation != UINT32_MAX) {
error = generate_blob(&candidate, s_material.generation + 1U);
if (error == ESP_OK) {
error = save_blob(&candidate);
}
if (error == ESP_OK) {
install_blob(&candidate);
}
}
secure_wipe(&candidate, sizeof(candidate));
*token = s_identity_token = ++s_next_identity_token;
s_identity_owner = xTaskGetCurrentTaskHandle();
s_identity_used = false;
xSemaphoreGive(s_security_mutex);
return error;
return ESP_OK;
}
esp_err_t ssh_security_reset(void)
esp_err_t ssh_security_replace_reserved(uint32_t token)
{
esp_err_t error = secure_random_init();
if (error != ESP_OK) {
return error;
}
error = ensure_mutex();
if (error != ESP_OK) {
return error;
}
if (!s_security_mutex || !token) return ESP_ERR_INVALID_STATE;
xSemaphoreTake(s_security_mutex, portMAX_DELAY);
uint32_t generation = 1U;
if (s_material_ready) {
if (s_material.generation == UINT32_MAX) {
xSemaphoreGive(s_security_mutex);
return ESP_ERR_INVALID_STATE;
}
generation = s_material.generation + 1U;
if (s_identity_token != token || s_identity_used ||
s_identity_owner != xTaskGetCurrentTaskHandle()) {
xSemaphoreGive(s_security_mutex);
return ESP_ERR_INVALID_STATE;
}
ssh_security_blob_t candidate;
error = generate_blob(&candidate, generation);
if (error == ESP_OK) {
error = save_blob(&candidate);
}
if (error == ESP_OK) {
install_blob(&candidate);
}
secure_wipe(&candidate, sizeof(candidate));
s_identity_used = true;
uint32_t generation = s_material_ready ? s_material.generation + 1U : 1U;
xSemaphoreGive(s_security_mutex);
/* Reservation excludes writers while crypto and flash run outside locks. */
ssh_security_blob_t candidate = {0};
esp_err_t error = generate_blob(&candidate, generation);
if (error == ESP_OK) error = save_blob(&candidate);
xSemaphoreTake(s_security_mutex, portMAX_DELAY);
if (error == ESP_OK) install_blob(&candidate);
xSemaphoreGive(s_security_mutex);
secure_wipe(&candidate, sizeof(candidate));
return error;
}
void ssh_security_release_identity(uint32_t token)
{
if (!s_security_mutex || !token) return;
xSemaphoreTake(s_security_mutex, portMAX_DELAY);
if (s_identity_token == token && s_identity_owner == xTaskGetCurrentTaskHandle()) {
s_identity_token = 0;
s_identity_owner = NULL;
}
xSemaphoreGive(s_security_mutex);
}
static esp_err_t replace_identity(bool reset)
{
uint32_t token = 0;
esp_err_t error = ssh_security_reserve_identity(0, reset, &token);
if (error == ESP_OK) error = ssh_security_replace_reserved(token);
ssh_security_release_identity(token);
return error;
}
esp_err_t ssh_security_rotate(void) { return replace_identity(false); }
esp_err_t ssh_security_reset(void) { return replace_identity(true); }
+17 -1
View File
@@ -3,6 +3,7 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
@@ -38,7 +39,22 @@ esp_err_t ssh_security_copy_private_key(uint8_t *output, size_t capacity,
size_t *output_length);
esp_err_t ssh_security_get_metadata(ssh_security_metadata_t *metadata);
/* Caller must stop SSH first. Rotation requires valid live material; reset replaces any stored state. */
typedef struct {
ssh_security_metadata_t metadata;
bool busy;
} ssh_security_identity_snapshot_t;
/* Zero-wait atomic public projection; no private material. */
esp_err_t ssh_security_get_identity_snapshot(ssh_security_identity_snapshot_t *snapshot);
/* Owner transaction: nonreused token, reserve before side effects and retain through
* restart. Only the reserving task may replace once and release. Zero generation
* selects canonical semantics; reset additionally permits unavailable material. */
esp_err_t ssh_security_reserve_identity(uint32_t generation, bool reset, uint32_t *token);
esp_err_t ssh_security_replace_reserved(uint32_t token);
void ssh_security_release_identity(uint32_t token);
/* Rotation requires valid live material; reset replaces any stored state.
* Direct callers share the reservation but do not restart the transport. */
esp_err_t ssh_security_rotate(void);
esp_err_t ssh_security_reset(void);
+526 -87
View File
@@ -9,8 +9,10 @@
#include <stdio.h>
#include <string.h>
#include "esp_heap_caps.h"
#include "admin_ssh_console.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
@@ -22,10 +24,23 @@
#include "secure_random.h"
#include "serial_service.h"
#include "ssh_security.h"
#include "ssh_auth_policy.h"
#include "ssh_memory.h"
#include "ssh_protocol_policy.h"
#include "user_database.h"
#include <wolfssl/wolfcrypt/memory.h>
#include <wolfssl/wolfcrypt/random.h>
#include <wolfssh/ssh.h>
#include <wolfssh/version.h>
/* Admission precedes signature work; result callbacks only follow authorized
* signed keys. Re-audit the parser/callback contract when upgrading wolfSSH. */
#if LIBWOLFSSH_VERSION_HEX != 0x01004020
#error "Re-audit SSH authentication callback ordering for this wolfSSH version"
#endif
#if defined(WOLFSSH_CERTS) || defined(WOLFSSH_ALLOW_USERAUTH_NONE)
#error "SSH admission policy requires certificate and none authentication disabled"
#endif
#if defined(CONFIG_MBEDTLS_HARDWARE_AES) && CONFIG_MBEDTLS_HARDWARE_AES
#error "Concurrent mbedTLS/wolfSSH operation requires mbedTLS software AES"
@@ -57,12 +72,15 @@ typedef struct {
int socket_fd;
WOLFSSH *ssh;
session_broker_client_id_t broker_client_id;
ssh_transport_session_route_t route;
user_principal_t principal;
user_principal_t pending_principal;
bool principal_valid;
bool pending_principal_valid;
bool awaiting_auth_result;
bool authenticated;
bool shell_requested;
uint8_t console_slot_index;
uint8_t authentication_attempts;
word32 io_read_budget;
bool writer;
@@ -84,14 +102,20 @@ static ssh_slot_t s_slots[SSH_TRANSPORT_MAX_SESSIONS];
static ssh_transport_session_snapshot_t
s_session_snapshots[SSH_TRANSPORT_MAX_SESSIONS];
static uint32_t s_external_close_id[SSH_TRANSPORT_MAX_SESSIONS];
/* Published with snapshots; dispatcher never reads owner-task slot storage. */
static user_principal_t s_console_principals[SSH_TRANSPORT_MAX_SESSIONS];
static uint8_t s_console_slot_indices[SSH_TRANSPORT_MAX_SESSIONS];
static ssh_transport_counters_t s_counters;
static SemaphoreHandle_t s_command_mutex;
static bool s_initializing;
static bool s_init_faulted;
static bool s_initialized;
static bool s_running;
static bool s_transitioning;
static bool s_desired_running;
static bool s_cleanup_pending;
/* Saturates independently of the internal completion sequence; never reset by counters. */
static uint32_t s_management_generation = 1U;
static uint32_t s_requested_sequence;
static uint32_t s_completed_sequence;
static esp_err_t s_command_result = ESP_ERR_INVALID_STATE;
@@ -100,11 +124,14 @@ static esp_err_t s_last_error = ESP_ERR_INVALID_STATE;
/* Owned exclusively by the transport task. */
static WOLFSSH_CTX *s_context;
static int s_listen_fd = -1;
/* Boot-lifetime admission state: neither service restart nor counter clear
* replenishes it. Only the SSH owner accesses this fixed-size policy. */
static ssh_auth_policy_t s_auth_policy;
static void add_counter(uint64_t *counter, uint64_t value)
{
taskENTER_CRITICAL(&s_lock);
*counter += value;
*counter = value > UINT64_MAX - *counter ? UINT64_MAX : *counter + value;
taskEXIT_CRITICAL(&s_lock);
}
@@ -125,6 +152,17 @@ static void notify_task(void)
}
}
static admin_ssh_console_token_t admin_console_token(const ssh_slot_t *slot,
size_t slot_index)
{
(void)slot_index; /* Physical SSH index is not the shared console index. */
return (admin_ssh_console_token_t){
.slot_index = slot->console_slot_index,
.session_id = slot->session_id,
.slot_generation = slot->generation,
};
}
static void publish_slot(const ssh_slot_t *slot, size_t slot_index)
{
ssh_transport_session_snapshot_t snapshot = {
@@ -140,11 +178,21 @@ static void publish_slot(const ssh_slot_t *slot, size_t slot_index)
.socket_fd = slot->socket_fd,
.broker_client_id = slot->broker_client_id,
.state = slot->state,
.route = slot->route,
.user_role = slot->principal_valid ? slot->principal.role : USER_ROLE_USER,
.auth_method = slot->principal_valid
? slot->principal.method
: USER_AUTH_METHOD_PASSWORD,
};
if (slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE) {
admin_ssh_console_session_snapshot_t admin_snapshot;
admin_ssh_console_token_t token = admin_console_token(slot, slot_index);
if (admin_ssh_console_get_session_snapshot(&token, &admin_snapshot) == ESP_OK) {
snapshot.admin_command_pending = admin_snapshot.command_pending;
snapshot.admin_output_pending = (uint32_t)admin_snapshot.output_length;
snapshot.tx_pending = snapshot.tx_pending || admin_snapshot.output_pending;
}
}
if (slot->principal_valid) {
memcpy(snapshot.username, slot->principal.username,
slot->principal.username_length);
@@ -153,14 +201,123 @@ static void publish_slot(const ssh_slot_t *slot, size_t slot_index)
taskENTER_CRITICAL(&s_lock);
s_session_snapshots[slot_index] = snapshot;
s_console_slot_indices[slot_index] =
snapshot.active && slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE
? slot->console_slot_index : UINT8_MAX;
if (slot->principal_valid) {
s_console_principals[slot_index] = slot->principal;
} else {
secure_wipe(&s_console_principals[slot_index], sizeof(user_principal_t));
}
taskEXIT_CRITICAL(&s_lock);
}
/* Caller holds s_lock. Match session identity first, then the assigned console
* binding; callbacks must never index physical SSH storage by console slot.
*/
static size_t admin_console_snapshot_index_locked(const admin_ssh_console_token_t *token)
{
if (token == NULL || token->transport != ADMIN_CONSOLE_TRANSPORT_SSH ||
token->session_id == 0U || token->slot_generation == 0U) {
return SSH_TRANSPORT_MAX_SESSIONS;
}
for (size_t i = 0U; i < SSH_TRANSPORT_MAX_SESSIONS; ++i) {
const ssh_transport_session_snapshot_t *slot = &s_session_snapshots[i];
if (slot->active && slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE &&
slot->session_id == token->session_id &&
slot->generation == token->slot_generation &&
s_console_slot_indices[i] != UINT8_MAX &&
s_console_slot_indices[i] == token->slot_index) {
return i;
}
}
return SSH_TRANSPORT_MAX_SESSIONS;
}
/* Dispatcher/control adapters: published state only, no runtime wolfSSH calls. */
static bool admin_console_is_current(const admin_ssh_console_token_t *token,
const user_principal_t *principal)
{
if (principal == NULL) {
return false;
}
taskENTER_CRITICAL(&s_lock);
size_t index = admin_console_snapshot_index_locked(token);
if (index == SSH_TRANSPORT_MAX_SESSIONS) {
taskEXIT_CRITICAL(&s_lock);
return false;
}
const ssh_transport_session_snapshot_t *slot = &s_session_snapshots[index];
const user_principal_t *bound = &s_console_principals[index];
bool current = slot->active && slot->authenticated && slot->principal_valid &&
slot->state == SSH_TRANSPORT_SESSION_ACTIVE &&
slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE && !slot->close_requested &&
s_external_close_id[index] != token->session_id &&
slot->session_id == token->session_id && slot->generation == token->slot_generation &&
bound->user_id == principal->user_id && bound->auth_generation == principal->auth_generation &&
bound->role == USER_ROLE_ADMIN && bound->role == principal->role &&
bound->method == principal->method && bound->username_length == principal->username_length &&
bound->username_length <= USER_DATABASE_USERNAME_CAPACITY &&
memcmp(bound->username, principal->username, bound->username_length) == 0;
taskEXIT_CRITICAL(&s_lock);
return current;
}
static bool admin_console_drained(const admin_ssh_console_token_t *token)
{
taskENTER_CRITICAL(&s_lock);
size_t index = admin_console_snapshot_index_locked(token);
bool drained = index < SSH_TRANSPORT_MAX_SESSIONS &&
!s_session_snapshots[index].tx_pending;
taskEXIT_CRITICAL(&s_lock);
return drained;
}
static esp_err_t admin_console_perform(const admin_ssh_console_token_t *token,
admin_ssh_deferred_action_type_t action,
uint32_t argument)
{
if (!admin_console_drained(token)) {
return ESP_ERR_NOT_FOUND;
}
switch (action) {
case ADMIN_SSH_DEFER_REBOOT:
esp_restart();
return ESP_OK;
case ADMIN_SSH_DEFER_STOP:
return ssh_transport_stop();
case ADMIN_CONSOLE_DEFER_SELF_CLOSE:
return ssh_transport_disconnect(token->session_id);
case ADMIN_SSH_DEFER_DISCONNECT:
return ssh_transport_disconnect(argument);
case ADMIN_SSH_DEFER_HOST_KEY_ROTATE:
return ssh_transport_replace_host_key(false);
case ADMIN_SSH_DEFER_HOST_KEY_RESET:
return ssh_transport_replace_host_key(true);
default:
return ESP_ERR_NOT_SUPPORTED;
}
}
static const admin_console_owner_t s_admin_console_owner = {
.supported_actions = (1U << ADMIN_SSH_DEFER_REBOOT) |
(1U << ADMIN_SSH_DEFER_STOP) | (1U << ADMIN_SSH_DEFER_DISCONNECT) |
(1U << ADMIN_SSH_DEFER_HOST_KEY_ROTATE) |
(1U << ADMIN_SSH_DEFER_HOST_KEY_RESET) | (1U << ADMIN_CONSOLE_DEFER_SELF_CLOSE),
.drained = admin_console_drained,
.is_current = admin_console_is_current,
.perform = admin_console_perform,
};
static bool consume_external_close(const ssh_slot_t *slot, size_t slot_index)
{
taskENTER_CRITICAL(&s_lock);
bool requested = s_external_close_id[slot_index] != 0U &&
s_external_close_id[slot_index] == slot->session_id;
if (requested) {
/* Keep close intent visible while the owner begins cleanup. */
s_session_snapshots[slot_index].close_requested = true;
}
if (requested || slot->state == SSH_TRANSPORT_SESSION_FREE) {
s_external_close_id[slot_index] = 0U;
}
@@ -168,24 +325,6 @@ static bool consume_external_close(const ssh_slot_t *slot, size_t slot_index)
return requested;
}
static void *ssh_malloc(size_t size)
{
return heap_caps_malloc_prefer(size, 2,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
}
static void ssh_free(void *pointer)
{
heap_caps_free(pointer);
}
static void *ssh_realloc(void *pointer, size_t size)
{
return heap_caps_realloc_prefer(pointer, size, 2,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
}
static int ssh_seed(OS_Seed *seed, byte *output, word32 size)
{
@@ -244,9 +383,52 @@ static void clear_pending_principal(ssh_slot_t *slot)
if (slot != NULL) {
secure_wipe(&slot->pending_principal, sizeof(slot->pending_principal));
slot->pending_principal_valid = false;
slot->awaiting_auth_result = false;
}
}
static void close_authentication(ssh_slot_t *slot)
{
if (slot != NULL && !slot->close_requested) {
slot->close_requested = true;
if (slot->socket_fd >= 0) {
(void)shutdown(slot->socket_fd, SHUT_RDWR);
}
}
}
static bool admit_authentication(ssh_slot_t *slot, bool probe)
{
ssh_auth_policy_kind_t kind = probe ? SSH_AUTH_POLICY_PROBE
: SSH_AUTH_POLICY_VERIFICATION;
if (!ssh_auth_policy_admit(&s_auth_policy, kind, esp_timer_get_time())) {
add_counter(probe ? &s_counters.authentication_probe_rejections
: &s_counters.authentication_throttle_rejections, 1U);
clear_pending_principal(slot);
close_authentication(slot);
return false;
}
add_counter(probe ? &s_counters.authentication_probe_admissions
: &s_counters.authentication_admissions, 1U);
return true;
}
/* Advertisement is not a dispatch filter in wolfSSH 1.4.20. Supply a rejecting
* callback so a direct keyboard-interactive request cannot call through NULL. */
static int reject_keyboard_auth(WS_UserAuthData_Keyboard *keyboard, void *context)
{
if (keyboard != NULL) {
secure_wipe(keyboard, sizeof(*keyboard));
}
ssh_slot_t *slot = (ssh_slot_t *)context;
if (slot != NULL && !slot->close_requested) {
add_counter(&s_counters.authentication_method_rejections, 1U);
}
clear_pending_principal(slot);
close_authentication(slot);
return WS_ERROR;
}
static bool complete_authentication_attempt(ssh_slot_t *slot, bool failed)
{
add_counter(&s_counters.authentication_attempts, 1U);
@@ -261,10 +443,8 @@ static bool complete_authentication_attempt(ssh_slot_t *slot, bool failed)
return true;
}
slot->close_requested = true;
if (slot->socket_fd >= 0) {
(void)shutdown(slot->socket_fd, SHUT_RDWR);
}
add_counter(&s_counters.authentication_limit_disconnects, 1U);
close_authentication(slot);
return false;
}
@@ -290,10 +470,14 @@ static int authenticate_password(ssh_slot_t *slot,
slot->principal = principal;
slot->principal_valid = true;
slot->authenticated = true;
secure_wipe(&principal, sizeof(principal));
return WOLFSSH_USERAUTH_SUCCESS;
}
secure_wipe(&principal, sizeof(principal));
if (error != ESP_OK) {
add_counter(&s_counters.authentication_backend_errors, 1U);
}
bool retry = complete_authentication_attempt(slot, true);
if (!retry) {
return WOLFSSH_USERAUTH_REJECTED;
@@ -323,6 +507,9 @@ static int authenticate_public_key(ssh_slot_t *slot,
if (error != ESP_OK || !authorized) {
secure_wipe(&principal, sizeof(principal));
if (error != ESP_OK) {
add_counter(&s_counters.authentication_backend_errors, 1U);
}
if (public_key->hasSignature == 0U) {
return error == ESP_OK ? WOLFSSH_USERAUTH_INVALID_PUBLICKEY
: WOLFSSH_USERAUTH_FAILURE;
@@ -338,6 +525,7 @@ static int authenticate_public_key(ssh_slot_t *slot,
if (public_key->hasSignature != 0U) {
slot->pending_principal = principal;
slot->pending_principal_valid = true;
slot->awaiting_auth_result = true;
}
secure_wipe(&principal, sizeof(principal));
return WOLFSSH_USERAUTH_SUCCESS;
@@ -348,20 +536,29 @@ static int authenticate_user(byte authentication_type,
void *context)
{
ssh_slot_t *slot = (ssh_slot_t *)context;
if (slot == NULL || authentication == NULL ||
authentication_type != authentication->type) {
if (slot == NULL || slot->state != SSH_TRANSPORT_SESSION_HANDSHAKE ||
slot->close_requested || slot->authenticated || slot->awaiting_auth_result) {
clear_pending_principal(slot);
return WOLFSSH_USERAUTH_INVALID_AUTHTYPE;
close_authentication(slot);
return WOLFSSH_USERAUTH_REJECTED;
}
if (authentication_type == WOLFSSH_USERAUTH_PASSWORD) {
return authenticate_password(slot, authentication);
}
if (authentication_type == WOLFSSH_USERAUTH_PUBLICKEY) {
return authenticate_public_key(slot, authentication);
if (authentication == NULL || authentication_type != authentication->type ||
(authentication_type != WOLFSSH_USERAUTH_PASSWORD &&
authentication_type != WOLFSSH_USERAUTH_PUBLICKEY)) {
add_counter(&s_counters.authentication_method_rejections, 1U);
clear_pending_principal(slot);
close_authentication(slot);
return WOLFSSH_USERAUTH_REJECTED;
}
clear_pending_principal(slot);
return WOLFSSH_USERAUTH_INVALID_AUTHTYPE;
bool probe = authentication_type == WOLFSSH_USERAUTH_PUBLICKEY &&
authentication->sf.publicKey.hasSignature == 0U;
if (!admit_authentication(slot, probe)) {
return WOLFSSH_USERAUTH_REJECTED;
}
return authentication_type == WOLFSSH_USERAUTH_PASSWORD
? authenticate_password(slot, authentication)
: authenticate_public_key(slot, authentication);
}
static int authentication_result(byte result, WS_UserAuthData *authentication,
@@ -370,10 +567,17 @@ static int authentication_result(byte result, WS_UserAuthData *authentication,
ssh_slot_t *slot = (ssh_slot_t *)context;
if (slot == NULL || authentication == NULL ||
authentication->type != WOLFSSH_USERAUTH_PUBLICKEY ||
authentication->sf.publicKey.hasSignature == 0U) {
authentication->sf.publicKey.hasSignature == 0U ||
slot->state != SSH_TRANSPORT_SESSION_HANDSHAKE ||
slot->close_requested || slot->authenticated ||
!slot->awaiting_auth_result || !slot->pending_principal_valid) {
clear_pending_principal(slot);
close_authentication(slot);
return WS_ERROR;
}
/* The authorization callback already consumed the verification token.
* Take the completion marker before any result/currentness processing. */
slot->awaiting_auth_result = false;
if (result != WOLFSSH_USERAUTH_SUCCESS) {
(void)complete_authentication_attempt(slot, true);
@@ -387,6 +591,9 @@ static int authentication_result(byte result, WS_UserAuthData *authentication,
&slot->pending_principal, &current)
: ESP_ERR_INVALID_STATE;
if (error != ESP_OK || !current) {
if (error != ESP_OK) {
add_counter(&s_counters.authentication_backend_errors, 1U);
}
(void)complete_authentication_attempt(slot, true);
clear_pending_principal(slot);
return WS_ERROR;
@@ -442,6 +649,11 @@ static void close_socket(int *socket_fd)
static bool cleanup_slot(ssh_slot_t *slot)
{
if (slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE) {
size_t slot_index = (size_t)(slot - s_slots);
admin_ssh_console_token_t token = admin_console_token(slot, slot_index);
admin_ssh_console_close(&token);
}
if (slot->ssh != NULL) {
(void)wolfSSH_shutdown(slot->ssh);
wolfSSH_free(slot->ssh);
@@ -461,7 +673,7 @@ static bool cleanup_slot(ssh_slot_t *slot)
}
uint32_t generation = slot->generation;
memset(slot, 0, sizeof(*slot));
secure_wipe(slot, sizeof(*slot));
slot->state = SSH_TRANSPORT_SESSION_FREE;
slot->generation = generation;
slot->socket_fd = -1;
@@ -513,15 +725,21 @@ static esp_err_t create_context(void)
return ESP_FAIL;
}
result = ssh_protocol_policy_apply(context);
if (result != WS_SUCCESS) {
wolfSSH_CTX_free(context);
return ESP_FAIL;
}
wolfSSH_SetIORecv(context, bounded_ssh_receive);
wolfSSH_SetUserAuth(context, authenticate_user);
wolfSSH_SetUserAuthTypes(context, allowed_auth_types);
wolfSSH_SetUserAuthResult(context, authentication_result);
wolfSSH_SetKeyboardAuthPrompts(context, reject_keyboard_auth);
(void)wolfSSH_CTX_SetChannelReqShellCb(context, accept_shell);
(void)wolfSSH_CTX_SetChannelReqExecCb(context, reject_channel_request);
(void)wolfSSH_CTX_SetChannelReqSubsysCb(context, reject_channel_request);
(void)wolfSSH_CTX_SetBanner(
context, "ESP32 Serial Swiss Army Knife - authenticated serial transport\r\n");
s_context = context;
return ESP_OK;
}
@@ -554,6 +772,11 @@ static esp_err_t create_listener(void)
static esp_err_t start_runtime(void)
{
/* Never overwrite an orphaned context/listener or sessions after failed stop. */
if (s_context != NULL || s_listen_fd >= 0) return ESP_ERR_INVALID_STATE;
for (size_t index = 0U; index < SSH_TRANSPORT_MAX_SESSIONS; ++index) {
if (s_slots[index].state != SSH_TRANSPORT_SESSION_FREE) return ESP_ERR_INVALID_STATE;
}
esp_err_t error = create_context();
if (error == ESP_OK) {
error = create_listener();
@@ -599,7 +822,7 @@ static esp_err_t stop_runtime(void)
break;
}
}
if (s_context != NULL) {
if (all_free && s_context != NULL) {
wolfSSH_CTX_free(s_context);
s_context = NULL;
}
@@ -686,7 +909,8 @@ static ssh_slot_t *find_free_slot(size_t *slot_index)
}
for (size_t index = 0U; index < SSH_TRANSPORT_MAX_SESSIONS; ++index) {
if (s_slots[index].state == SSH_TRANSPORT_SESSION_FREE) {
if (s_slots[index].state == SSH_TRANSPORT_SESSION_FREE &&
s_slots[index].generation < SSH_TRANSPORT_GENERATION_MAX) {
*slot_index = index;
return &s_slots[index];
}
@@ -747,6 +971,13 @@ static void accept_connections(void)
close(socket_fd);
continue;
}
if (!ssh_auth_policy_admit(&s_auth_policy, SSH_AUTH_POLICY_HANDSHAKE,
esp_timer_get_time())) {
add_counter(&s_counters.handshake_throttle_rejections, 1U);
close(socket_fd);
continue;
}
add_counter(&s_counters.handshake_admissions, 1U);
if (set_nonblocking(socket_fd) != ESP_OK) {
add_counter(&s_counters.io_failures, 1U);
close(socket_fd);
@@ -756,7 +987,8 @@ static void accept_connections(void)
(void)setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY,
&enabled, sizeof(enabled));
uint32_t generation = next_generation(slot->generation);
/* Exhausted slots are retired by find_free_slot(), never reused after wrap. */
uint32_t generation = slot->generation + 1U;
memset(slot, 0, sizeof(*slot));
slot->state = SSH_TRANSPORT_SESSION_HANDSHAKE;
slot->generation = generation;
@@ -776,6 +1008,7 @@ static void accept_connections(void)
wolfSSH_SetIOReadCtx(slot->ssh, slot);
wolfSSH_SetUserAuthCtx(slot->ssh, slot);
wolfSSH_SetUserAuthResultCtx(slot->ssh, slot);
wolfSSH_SetKeyboardAuthCtx(slot->ssh, slot);
wolfSSH_SetChannelReqCtx(slot->ssh, slot);
publish_slot(slot, slot_index);
}
@@ -886,14 +1119,35 @@ static void process_handshake(ssh_slot_t *slot, size_t slot_index)
return;
}
esp_err_t error = connect_broker(slot, slot_index);
if (error != ESP_OK) {
add_counter(&s_counters.broker_failures, 1U);
request_slot_close(slot, false);
esp_err_t error;
if (slot->principal.role == USER_ROLE_USER) {
error = connect_broker(slot, slot_index);
if (error != ESP_OK) {
add_counter(&s_counters.broker_failures, 1U);
request_slot_close(slot, false);
return;
}
slot->route = SSH_TRANSPORT_ROUTE_BROKER;
} else if (slot->principal.role == USER_ROLE_ADMIN) {
admin_ssh_console_token_t token = admin_console_token(slot, slot_index);
error = admin_ssh_console_open_available(&token, &slot->principal,
&s_admin_console_owner);
if (error != ESP_OK) {
add_counter(&s_counters.admin_console_admission_failures, 1U);
request_slot_close(slot, false);
return;
}
slot->console_slot_index = token.slot_index;
slot->route = SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE;
add_counter(&s_counters.admin_console_admissions, 1U);
} else {
request_slot_close(slot, true);
return;
}
if (!slot_principal_is_current(slot)) {
disconnect_failed_admission(slot);
if (slot->route == SSH_TRANSPORT_ROUTE_BROKER) {
disconnect_failed_admission(slot);
}
request_slot_close(slot, true);
return;
}
@@ -1052,6 +1306,11 @@ static bool flush_client_output(ssh_slot_t *slot)
slot->ssh, slot->tx_buffer + slot->tx_offset,
(word32)(slot->tx_length - slot->tx_offset));
if (result > 0) {
/* Positive stream_send means copied/consumed by wolfSSH, not peer
* receipt. Preserve pending bytes on retry and the binary serial path. */
if (slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE) {
secure_wipe(slot->tx_buffer + slot->tx_offset, (size_t)result);
}
slot->tx_offset += (size_t)result;
add_counter(&s_counters.tx_bytes, (uint64_t)result);
if (slot->tx_offset >= slot->tx_length) {
@@ -1086,12 +1345,99 @@ static bool read_broker_output(ssh_slot_t *slot)
return received == 0U ? true : flush_client_output(slot);
}
static void process_active(ssh_slot_t *slot)
static bool reconcile_admin_principal(ssh_slot_t *slot)
{
bool healthy = service_wolfssh_io(slot) &&
drain_broker_events(slot) && reconcile_writer(slot) &&
flush_client_output(slot) && read_broker_output(slot) &&
flush_client_input(slot) && receive_client_input(slot);
int64_t now = esp_timer_get_time();
if (now - slot->last_reconcile_us < SSH_TRANSPORT_RECONCILE_INTERVAL_US) {
return true;
}
slot->last_reconcile_us = now;
if (!slot_principal_is_current(slot) || slot->principal.role != USER_ROLE_ADMIN) {
request_slot_close(slot, true);
return false;
}
return true;
}
static bool flush_admin_input(ssh_slot_t *slot, size_t slot_index)
{
if (slot->rx_offset >= slot->rx_length) {
slot->rx_offset = 0U;
slot->rx_length = 0U;
return true;
}
admin_ssh_console_token_t token = admin_console_token(slot, slot_index);
size_t consumed = 0U;
bool accepted = admin_ssh_console_feed_input(
&token, slot->rx_buffer + slot->rx_offset,
slot->rx_length - slot->rx_offset, &consumed);
if (consumed > 0U) {
secure_wipe(slot->rx_buffer + slot->rx_offset, consumed);
slot->rx_offset += consumed;
add_counter(&s_counters.rx_accepted_bytes, consumed);
}
if (slot->rx_offset >= slot->rx_length) {
slot->rx_offset = 0U;
slot->rx_length = 0U;
}
if (!accepted && consumed == 0U) {
add_counter(&s_counters.admin_console_input_rejections, 1U);
}
return true;
}
static bool receive_admin_input(ssh_slot_t *slot, size_t slot_index)
{
if (slot->rx_length != 0U) {
return flush_admin_input(slot, slot_index);
}
admin_ssh_console_token_t token = admin_console_token(slot, slot_index);
if (!admin_ssh_console_accepts_input(&token)) {
return true;
}
slot->io_read_budget = SSH_TRANSPORT_WOLFSSH_READ_BUDGET;
int result = wolfSSH_stream_read(slot->ssh, slot->rx_buffer,
sizeof(slot->rx_buffer));
if (result > 0) {
slot->rx_offset = 0U;
slot->rx_length = (size_t)result;
add_counter(&s_counters.rx_bytes, (uint64_t)result);
return flush_admin_input(slot, slot_index);
}
return result == 0 || wolfssh_would_block(slot->ssh, result);
}
static bool read_admin_output(ssh_slot_t *slot, size_t slot_index)
{
if (slot->tx_length != 0U) {
return true;
}
admin_ssh_console_token_t token = admin_console_token(slot, slot_index);
size_t received = 0U;
esp_err_t error = admin_ssh_console_read_output(&token, slot->tx_buffer,
sizeof(slot->tx_buffer), &received);
if (error != ESP_OK && error != ESP_ERR_NOT_FOUND) {
return false;
}
slot->tx_offset = 0U;
slot->tx_length = received;
return error == ESP_OK;
}
static void process_active(ssh_slot_t *slot, size_t slot_index)
{
bool healthy = service_wolfssh_io(slot);
if (healthy && slot->route == SSH_TRANSPORT_ROUTE_BROKER) {
healthy = drain_broker_events(slot) && reconcile_writer(slot) &&
flush_client_output(slot) && read_broker_output(slot) &&
flush_client_input(slot) && receive_client_input(slot);
} else if (healthy && slot->route == SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE) {
healthy = reconcile_admin_principal(slot) && flush_client_output(slot) &&
read_admin_output(slot, slot_index) && flush_client_output(slot) &&
receive_admin_input(slot, slot_index);
} else if (healthy) {
healthy = false;
}
if (!healthy) {
add_counter(&s_counters.io_failures, 1U);
request_slot_close(slot, false);
@@ -1117,7 +1463,7 @@ static void process_slots(void)
if (slot->state == SSH_TRANSPORT_SESSION_HANDSHAKE) {
process_handshake(slot, index);
} else if (slot->state == SSH_TRANSPORT_SESSION_ACTIVE) {
process_active(slot);
process_active(slot, index);
}
publish_slot(slot, index);
}
@@ -1131,10 +1477,18 @@ static void process_slots(void)
}
if (all_free) {
taskENTER_CRITICAL(&s_lock);
if (!s_running) {
s_cleanup_pending = false;
}
bool stopped = !s_running;
taskEXIT_CRITICAL(&s_lock);
/* The owner alone retires the retained context, before reopening admission. */
if (stopped) {
if (s_context != NULL) {
wolfSSH_CTX_free(s_context);
s_context = NULL;
}
taskENTER_CRITICAL(&s_lock);
s_cleanup_pending = false;
taskEXIT_CRITICAL(&s_lock);
}
}
}
@@ -1163,20 +1517,29 @@ esp_err_t ssh_transport_init(void)
taskEXIT_CRITICAL(&s_lock);
return ESP_OK;
}
if (s_initializing) {
if (s_initializing || s_init_faulted) {
taskEXIT_CRITICAL(&s_lock);
return ESP_ERR_INVALID_STATE;
}
s_initializing = true;
taskEXIT_CRITICAL(&s_lock);
bool wolfssh_initialized = false;
esp_err_t error = secure_random_init();
if (error != ESP_OK) {
error = ESP_ERR_INVALID_STATE;
goto fail;
}
if (wolfSSL_SetAllocators(ssh_malloc, ssh_free, ssh_realloc) != 0 ||
wolfSSH_Init() != WS_SUCCESS || wc_SetSeed_Cb(ssh_seed) != 0) {
if (wolfSSL_SetAllocators(ssh_memory_malloc, ssh_memory_free, ssh_memory_realloc) != 0) {
error = ESP_FAIL;
goto fail;
}
if (wolfSSH_Init() != WS_SUCCESS) {
error = ESP_FAIL;
goto fail;
}
wolfssh_initialized = true;
if (wc_SetSeed_Cb(ssh_seed) != 0) {
error = ESP_FAIL;
goto fail;
}
@@ -1186,6 +1549,11 @@ esp_err_t ssh_transport_init(void)
error = ESP_ERR_NO_MEM;
goto fail;
}
error = admin_ssh_console_init();
if (error != ESP_OK) {
vSemaphoreDelete(command_mutex);
goto fail;
}
for (size_t index = 0U; index < SSH_TRANSPORT_MAX_SESSIONS; ++index) {
s_slots[index].state = SSH_TRANSPORT_SESSION_FREE;
s_slots[index].socket_fd = -1;
@@ -1211,7 +1579,9 @@ esp_err_t ssh_transport_init(void)
return ESP_OK;
fail:
bool cleanup_failed = wolfssh_initialized && wolfSSH_Cleanup() != WS_SUCCESS;
taskENTER_CRITICAL(&s_lock);
s_init_faulted = cleanup_failed;
s_initializing = false;
taskEXIT_CRITICAL(&s_lock);
return error;
@@ -1238,6 +1608,7 @@ static esp_err_t request_running_locked(bool desired)
return ESP_OK;
}
s_desired_running = desired;
if (s_management_generation != UINT32_MAX) ++s_management_generation;
s_transitioning = true;
s_requested_sequence = next_generation(s_requested_sequence);
sequence = s_requested_sequence;
@@ -1284,46 +1655,54 @@ esp_err_t ssh_transport_stop(void)
return request_running(false);
}
esp_err_t ssh_transport_replace_host_key(bool reset)
esp_err_t ssh_transport_replace_identity(uint32_t service_generation,
uint32_t identity_generation,
bool reset, bool *committed)
{
if (s_command_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_command_mutex, portMAX_DELAY);
if (!committed || (!!service_generation != !!identity_generation) ||
(reset && service_generation) || service_generation == UINT32_MAX ||
identity_generation == UINT32_MAX) return ESP_ERR_INVALID_ARG;
*committed = false;
if (!s_command_mutex) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_command_mutex, 0U) != pdTRUE) return ESP_ERR_TIMEOUT;
bool was_running;
bool cleanup_pending;
taskENTER_CRITICAL(&s_lock);
if (!s_initialized || s_transitioning) {
taskEXIT_CRITICAL(&s_lock);
xSemaphoreGive(s_command_mutex);
return ESP_ERR_INVALID_STATE;
}
was_running = s_running;
cleanup_pending = s_cleanup_pending;
bool valid = s_initialized && !s_transitioning &&
(!service_generation || (!s_cleanup_pending && service_generation == s_management_generation));
bool was_running = s_running, cleanup_pending = s_cleanup_pending;
taskEXIT_CRITICAL(&s_lock);
esp_err_t error = ESP_OK;
if (was_running || cleanup_pending) {
error = request_running_locked(false);
}
uint32_t token = 0;
esp_err_t error = valid ? ssh_security_reserve_identity(identity_generation, reset, &token)
: ESP_ERR_INVALID_STATE;
if (error == ESP_OK) {
error = reset ? ssh_security_reset() : ssh_security_rotate();
}
if (error != ESP_OK) {
if (was_running) {
(void)request_running_locked(true);
taskENTER_CRITICAL(&s_lock);
if (s_management_generation != UINT32_MAX) ++s_management_generation;
taskEXIT_CRITICAL(&s_lock);
/* Keep the service mutex and identity reservation through stop/replace/start.
* Failed stop must never mutate identity or attempt another start. */
if (was_running || cleanup_pending) error = request_running_locked(false);
if (error == ESP_OK) {
error = ssh_security_replace_reserved(token);
*committed = error == ESP_OK;
if (error != ESP_OK && was_running) {
/* Stop succeeded: restore service using unchanged committed material. */
(void)request_running_locked(true);
} else if (error == ESP_OK && (was_running || reset)) {
error = request_running_locked(true);
}
}
xSemaphoreGive(s_command_mutex);
return error;
}
if (was_running || reset) {
error = request_running_locked(true);
}
ssh_security_release_identity(token);
xSemaphoreGive(s_command_mutex);
return error;
}
esp_err_t ssh_transport_replace_host_key(bool reset)
{
bool committed;
return ssh_transport_replace_identity(0, 0, reset, &committed);
}
esp_err_t ssh_transport_get_snapshot(ssh_transport_snapshot_t *snapshot)
{
if (snapshot == NULL) {
@@ -1359,6 +1738,66 @@ esp_err_t ssh_transport_get_snapshot(ssh_transport_snapshot_t *snapshot)
return ESP_OK;
}
esp_err_t ssh_transport_get_management_snapshot(ssh_transport_management_snapshot_t *snapshot)
{
if (snapshot == NULL) return ESP_ERR_INVALID_ARG;
taskENTER_CRITICAL(&s_lock);
if (!s_initialized) {
taskEXIT_CRITICAL(&s_lock);
return ESP_ERR_INVALID_STATE;
}
memset(snapshot, 0, sizeof(*snapshot));
snapshot->generation = s_management_generation;
snapshot->running = s_running;
snapshot->transitioning = s_transitioning || s_cleanup_pending;
for (size_t i = 0; i < SSH_TRANSPORT_MAX_SESSIONS; ++i) {
snapshot->sessions[i] = s_session_snapshots[i];
snapshot->sessions[i].close_requested |=
snapshot->sessions[i].active && s_external_close_id[i] == snapshot->sessions[i].session_id;
}
taskEXIT_CRITICAL(&s_lock);
return ESP_OK;
}
esp_err_t ssh_transport_manage_current(ssh_transport_management_action_t action,
uint32_t target, uint32_t generation)
{
if (!generation || generation == UINT32_MAX ||
action < SSH_TRANSPORT_MANAGE_START || action > SSH_TRANSPORT_MANAGE_DISCONNECT ||
((action == SSH_TRANSPORT_MANAGE_DISCONNECT) != (target != 0U))) return ESP_ERR_INVALID_ARG;
if (s_command_mutex == NULL) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_command_mutex, 0U) != pdTRUE) return ESP_ERR_TIMEOUT;
esp_err_t error = ESP_ERR_INVALID_STATE;
taskENTER_CRITICAL(&s_lock);
if (s_initialized && !s_transitioning && !s_cleanup_pending &&
generation == s_management_generation) {
if (action == SSH_TRANSPORT_MANAGE_DISCONNECT) {
error = ESP_ERR_NOT_FOUND;
for (size_t i = 0; i < SSH_TRANSPORT_MAX_SESSIONS; ++i) {
const ssh_transport_session_snapshot_t *session = &s_session_snapshots[i];
if (session->active && session->session_id == target &&
!session->close_requested && session->state != SSH_TRANSPORT_SESSION_CLOSING &&
s_external_close_id[i] != target) {
s_external_close_id[i] = target;
error = ESP_OK;
break;
}
}
} else if (s_running != (action == SSH_TRANSPORT_MANAGE_START)) {
error = ESP_OK;
}
}
taskEXIT_CRITICAL(&s_lock);
/* The command mutex spans comparison and canonical lifecycle admission.
* No HTTPD work/lock is involved; only the SSH owner touches sockets/wolfSSH. */
if (error == ESP_OK) {
if (action == SSH_TRANSPORT_MANAGE_DISCONNECT) notify_task();
else error = request_running_locked(action == SSH_TRANSPORT_MANAGE_START);
}
xSemaphoreGive(s_command_mutex);
return error;
}
esp_err_t ssh_transport_clear_counters(void)
{
taskENTER_CRITICAL(&s_lock);
+51
View File
@@ -27,6 +27,12 @@ typedef enum {
SSH_TRANSPORT_SESSION_CLOSING,
} ssh_transport_session_state_t;
typedef enum {
SSH_TRANSPORT_ROUTE_NONE = 0,
SSH_TRANSPORT_ROUTE_BROKER,
SSH_TRANSPORT_ROUTE_ADMIN_CONSOLE,
} ssh_transport_session_route_t;
typedef struct {
uint64_t starts;
uint64_t start_failures;
@@ -38,6 +44,17 @@ typedef struct {
uint64_t handshake_timeouts;
uint64_t authentication_attempts;
uint64_t authentication_failures;
/* Admission is before work; completion above excludes denied requests and
* unsigned probes. All values are counts, never submitted identity data. */
uint64_t handshake_admissions;
uint64_t handshake_throttle_rejections;
uint64_t authentication_admissions;
uint64_t authentication_throttle_rejections;
uint64_t authentication_probe_admissions;
uint64_t authentication_probe_rejections;
uint64_t authentication_limit_disconnects;
uint64_t authentication_backend_errors;
uint64_t authentication_method_rejections;
uint64_t request_rejections;
uint64_t broker_connections;
uint64_t broker_failures;
@@ -52,6 +69,9 @@ typedef struct {
uint64_t tx_bytes;
uint64_t io_failures;
uint64_t session_revocations;
uint64_t admin_console_admissions;
uint64_t admin_console_admission_failures;
uint64_t admin_console_input_rejections;
} ssh_transport_counters_t;
typedef struct {
@@ -62,11 +82,14 @@ typedef struct {
bool close_requested;
bool rx_pending;
bool tx_pending;
bool admin_command_pending;
uint32_t admin_output_pending;
uint32_t session_id;
uint32_t generation;
int socket_fd;
session_broker_client_id_t broker_client_id;
ssh_transport_session_state_t state;
ssh_transport_session_route_t route;
user_role_t user_role;
user_auth_method_t auth_method;
char username[USER_DATABASE_USERNAME_CAPACITY + 1U];
@@ -87,11 +110,39 @@ typedef struct {
ssh_transport_counters_t counters;
} ssh_transport_snapshot_t;
typedef enum {
SSH_TRANSPORT_MANAGE_START = 0,
SSH_TRANSPORT_MANAGE_STOP,
SSH_TRANSPORT_MANAGE_DISCONNECT,
} ssh_transport_management_action_t;
typedef struct {
uint32_t generation;
bool running;
bool transitioning;
ssh_transport_session_snapshot_t sessions[SSH_TRANSPORT_MAX_SESSIONS];
} ssh_transport_management_snapshot_t;
/* Compact published state only; no wolfSSH calls or task-stack scan. */
esp_err_t ssh_transport_get_management_snapshot(ssh_transport_management_snapshot_t *snapshot);
/* Dispatcher-only conditional admission; success on disconnect means owner notified,
* not peer receipt/cleanup. Lifecycle timeout does not cancel admitted work. */
esp_err_t ssh_transport_manage_current(ssh_transport_management_action_t action,
uint32_t target, uint32_t generation);
/* Installs wolfCrypt RNG/PSRAM hooks and starts the sole wolfSSH owner task. */
esp_err_t ssh_transport_init(void);
esp_err_t ssh_transport_start(void);
esp_err_t ssh_transport_stop(void);
/* Conditional off-HTTPD rotation: both generations checked/reserved before stop.
* Zero generations retain canonical rotate/reset semantics. A failed stop skips
* mutation/start; persistence failure may already have disconnected all SSH.
* committed reports irreversible publication even if restart subsequently fails. */
esp_err_t ssh_transport_replace_identity(uint32_t service_generation,
uint32_t identity_generation,
bool reset, bool *committed);
/* Serialize stop, persistent host-key replacement, and conditional restart. */
esp_err_t ssh_transport_replace_host_key(bool reset);
+10
View File
@@ -6,6 +6,7 @@
#include <stdint.h>
#include <stdio.h>
#include "admin_ssh_console.h"
#include "esp_console.h"
#include "esp_heap_caps.h"
#include "esp_system.h"
@@ -47,6 +48,15 @@ static int command_reboot(int argc, char **argv)
return 1;
}
if (admin_ssh_console_dispatch_is_remote()) {
esp_err_t error = admin_ssh_console_dispatch_defer(ADMIN_SSH_DEFER_REBOOT, 0U);
if (error != ESP_OK) {
printf("Could not schedule reboot: %s\n", esp_err_to_name(error));
return 1;
}
printf("Reboot scheduled after console output drains; unsaved changes will be lost.\n");
return 0;
}
printf("Rebooting now; unsaved RAM-only configuration changes will be lost.\n");
fflush(stdout);
/* Give the UART driver time to transmit the acknowledgement before reset. */
+33 -155
View File
@@ -9,7 +9,6 @@
#include "freertos/queue.h"
#include "freertos/stream_buffer.h"
#include "freertos/task.h"
#include "serial_config.h"
#include "serial_service.h"
#include "tinyusb.h"
#include "tinyusb_cdc_acm.h"
@@ -47,14 +46,15 @@ static portMUX_TYPE s_state_lock = portMUX_INITIALIZER_UNLOCKED;
static atomic_bool s_initialized;
static atomic_bool s_initializing;
static atomic_bool s_init_faulted;
static atomic_uint s_usb_state;
/* Changes on every effective CDC open/close boundary, even during one task poll. */
static atomic_uint s_connection_generation;
static session_broker_client_id_t s_broker_client_id;
static bool s_writer;
/* Host-provided CDC line coding is diagnostic information only. */
static usb_cdc_transport_line_coding_t s_line_coding;
static bool s_line_coding_pending;
static usb_cdc_transport_counters_t s_counters;
static const char s_language_descriptor[] = {0x09, 0x04};
@@ -133,14 +133,11 @@ static void device_event_callback(tinyusb_event_t *event, void *arg)
notify_transport_task();
break;
case TINYUSB_EVENT_DETACHED: {
/* A new attachment must receive fresh control state and line coding. */
/* A new attachment must receive fresh control state. */
unsigned int old_state = atomic_exchange(&s_usb_state, 0U);
if (usb_state_is_open(old_state)) {
atomic_fetch_add(&s_connection_generation, 1U);
}
taskENTER_CRITICAL(&s_state_lock);
s_line_coding_pending = false;
taskEXIT_CRITICAL(&s_state_lock);
notify_transport_task();
break;
}
@@ -225,13 +222,6 @@ static void cdc_line_state_callback(int itf, cdcacm_event_t *event)
}
}
if (!event->line_state_changed_data.dtr) {
/* Do not apply a closed host session's deferred line coding after reopen. */
taskENTER_CRITICAL(&s_state_lock);
s_line_coding_pending = false;
taskEXIT_CRITICAL(&s_state_lock);
}
notify_transport_task();
}
@@ -251,137 +241,15 @@ static void cdc_line_coding_callback(int itf, cdcacm_event_t *event)
sizeof(coding));
taskENTER_CRITICAL(&s_state_lock);
if (s_line_coding_pending) {
/* Preserve the latest complete setting and account for the superseded one. */
++s_counters.callback_drops;
}
s_line_coding = (usb_cdc_transport_line_coding_t) {
.baud_rate = coding.bit_rate,
.stop_bits = coding.stop_bits,
.parity = coding.parity,
.data_bits = coding.data_bits,
};
s_line_coding_pending = true;
taskEXIT_CRITICAL(&s_state_lock);
notify_transport_task();
}
static bool take_pending_line_coding(usb_cdc_transport_line_coding_t *coding)
{
bool pending;
taskENTER_CRITICAL(&s_state_lock);
pending = s_line_coding_pending;
if (pending) {
*coding = s_line_coding;
s_line_coding_pending = false;
}
taskEXIT_CRITICAL(&s_state_lock);
return pending;
}
static bool serial_configs_equal(const serial_config_t *left,
const serial_config_t *right)
{
return left->version == right->version &&
left->baud_rate == right->baud_rate &&
left->data_bits == right->data_bits &&
left->parity == right->parity &&
left->stop_bits == right->stop_bits &&
left->flow_control == right->flow_control &&
left->dtr_behavior == right->dtr_behavior &&
left->rts_threshold == right->rts_threshold;
}
static bool map_line_coding(const usb_cdc_transport_line_coding_t *coding,
serial_config_t *config)
{
if (coding->baud_rate < SERIAL_CONFIG_MIN_BAUD_RATE ||
coding->baud_rate > SERIAL_CONFIG_MAX_BAUD_RATE) {
return false;
}
config->baud_rate = coding->baud_rate;
switch (coding->data_bits) {
case 7U:
config->data_bits = SERIAL_CONFIG_DATA_BITS_7;
break;
case 8U:
config->data_bits = SERIAL_CONFIG_DATA_BITS_8;
break;
default:
return false;
}
switch (coding->parity) {
case CDC_LINE_CODING_PARITY_NONE:
config->parity = SERIAL_CONFIG_PARITY_NONE;
break;
case CDC_LINE_CODING_PARITY_ODD:
config->parity = SERIAL_CONFIG_PARITY_ODD;
break;
case CDC_LINE_CODING_PARITY_EVEN:
config->parity = SERIAL_CONFIG_PARITY_EVEN;
break;
default:
/* Mark and space parity are intentionally not representable by UART policy. */
return false;
}
switch (coding->stop_bits) {
case CDC_LINE_CODING_STOP_BITS_1:
config->stop_bits = SERIAL_CONFIG_STOP_BITS_1;
break;
case CDC_LINE_CODING_STOP_BITS_2:
config->stop_bits = SERIAL_CONFIG_STOP_BITS_2;
break;
default:
/* This also rejects USB's 1.5-stop-bit encoding. */
return false;
}
return true;
}
static void apply_pending_line_coding(bool writer)
{
if (!writer || !serial_service_is_running()) {
return;
}
/* Restarting UART1 discards queued TX, so defer framing changes until idle. */
if (serial_service_tx_pending() > 0U) {
return;
}
usb_cdc_transport_line_coding_t coding;
if (!take_pending_line_coding(&coding)) {
return;
}
serial_config_t current;
if (serial_service_get_config(&current) != ESP_OK) {
add_counter(&s_counters.line_coding_failed, 1U);
return;
}
serial_config_t desired = current;
if (!map_line_coding(&coding, &desired)) {
add_counter(&s_counters.line_coding_rejected, 1U);
return;
}
/* Flow control, DTR policy, and RTS threshold remain from current RAM state. */
if (serial_configs_equal(&current, &desired)) {
return;
}
if (serial_service_apply_config(&desired) == ESP_OK) {
add_counter(&s_counters.line_coding_applied, 1U);
} else {
add_counter(&s_counters.line_coding_failed, 1U);
}
/* CDC line coding must not reconfigure the independently configured UART1. */
}
static bool writer_event_type(session_broker_event_type_t type)
@@ -761,8 +629,6 @@ static void transport_task(void *context)
continue;
}
apply_pending_line_coding(writer);
if (atomic_load(&s_connection_generation) != observed_generation) {
continue;
}
@@ -811,18 +677,23 @@ static void reset_uninitialized_state(void)
.parity = USB_CDC_TRANSPORT_PARITY_NONE,
.data_bits = 8U,
};
s_line_coding_pending = false;
memset(&s_counters, 0, sizeof(s_counters));
taskEXIT_CRITICAL(&s_state_lock);
}
static void cleanup_init_allocations(bool cdc_initialized, bool driver_installed)
static esp_err_t cleanup_init_allocations(bool cdc_initialized, bool driver_installed)
{
if (cdc_initialized) {
(void)tinyusb_cdcacm_deinit(TINYUSB_CDC_ACM_0);
esp_err_t error = tinyusb_cdcacm_deinit(TINYUSB_CDC_ACM_0);
if (error != ESP_OK) {
return error;
}
}
if (driver_installed) {
(void)tinyusb_driver_uninstall();
esp_err_t error = tinyusb_driver_uninstall();
if (error != ESP_OK) {
return error;
}
}
if (s_control_queue != NULL) {
vQueueDelete(s_control_queue);
@@ -833,12 +704,27 @@ static void cleanup_init_allocations(bool cdc_initialized, bool driver_installed
s_host_rx_stream = NULL;
}
reset_uninitialized_state();
return ESP_OK;
}
static esp_err_t fail_initialization(esp_err_t original_error,
bool cdc_initialized,
bool driver_installed)
{
esp_err_t cleanup_error = cleanup_init_allocations(cdc_initialized, driver_installed);
if (cleanup_error != ESP_OK) {
/* Retain callback-facing storage and reject retries after incomplete teardown. */
atomic_store(&s_init_faulted, true);
original_error = cleanup_error;
}
atomic_store(&s_initializing, false);
return original_error;
}
esp_err_t usb_cdc_transport_init(void)
{
bool expected = false;
if (atomic_load(&s_initialized) ||
if (atomic_load(&s_initialized) || atomic_load(&s_init_faulted) ||
!atomic_compare_exchange_strong(&s_initializing, &expected, true)) {
return ESP_ERR_INVALID_STATE;
}
@@ -870,9 +756,7 @@ esp_err_t usb_cdc_transport_init(void)
s_control_queue = xQueueCreate(USB_CDC_CONTROL_QUEUE_LENGTH,
sizeof(usb_cdc_control_t));
if (s_control_queue == NULL) {
cleanup_init_allocations(false, false);
atomic_store(&s_initializing, false);
return ESP_ERR_NO_MEM;
return fail_initialization(ESP_ERR_NO_MEM, false, false);
}
/* ESP32-S3's default full-speed internal PHY is fixed to GPIO19/20. */
@@ -884,9 +768,7 @@ esp_err_t usb_cdc_transport_init(void)
result = tinyusb_driver_install(&usb_config);
if (result != ESP_OK) {
cleanup_init_allocations(false, false);
atomic_store(&s_initializing, false);
return result;
return fail_initialization(result, false, false);
}
const tinyusb_config_cdcacm_t cdc_config = {
@@ -898,9 +780,7 @@ esp_err_t usb_cdc_transport_init(void)
};
result = tinyusb_cdcacm_init(&cdc_config);
if (result != ESP_OK) {
cleanup_init_allocations(false, true);
atomic_store(&s_initializing, false);
return result;
return fail_initialization(result, false, true);
}
TaskHandle_t task = NULL;
@@ -910,9 +790,7 @@ esp_err_t usb_cdc_transport_init(void)
NULL,
USB_CDC_TASK_PRIORITY,
&task) != pdPASS) {
cleanup_init_allocations(true, true);
atomic_store(&s_initializing, false);
return ESP_ERR_NO_MEM;
return fail_initialization(ESP_ERR_NO_MEM, true, true);
}
atomic_store(&s_transport_task, (uintptr_t)task);
-3
View File
@@ -44,9 +44,6 @@ typedef struct {
uint64_t writer_revocations;
uint64_t writer_events;
uint64_t service_start_failures;
uint64_t line_coding_applied;
uint64_t line_coding_rejected;
uint64_t line_coding_failed;
uint64_t callback_drops;
uint64_t control_drops;
} usb_cdc_transport_counters_t;
+2 -6
View File
@@ -76,7 +76,7 @@ static int show_status(void)
(unsigned int)snapshot.line_coding.data_bits,
parity_name(snapshot.line_coding.parity),
stop_bits_name(snapshot.line_coding.stop_bits));
printf("USB line coding changes RAM only; use 'serial save' to persist it.\n");
printf("Host line coding is reported only; UART1 uses the serial configuration.\n");
return 0;
}
@@ -110,11 +110,7 @@ static int show_counters(void)
counter->writer_denials,
counter->writer_revocations,
counter->writer_events);
printf("Line coding: applied=%" PRIu64 " rejected=%" PRIu64
" failed=%" PRIu64 " service-start-failures=%" PRIu64 "\n",
counter->line_coding_applied,
counter->line_coding_rejected,
counter->line_coding_failed,
printf("Service start failures=%" PRIu64 "\n",
counter->service_start_failures);
printf("Control/callback drops: control=%" PRIu64 " callback=%" PRIu64 "\n",
counter->control_drops,
+121 -93
View File
@@ -7,29 +7,35 @@
#include <stdlib.h>
#include <string.h>
#include "admin_command_gate.h"
#include "admin_ssh_console.h"
#include "console_input.h"
#include "esp_console.h"
#include "esp_heap_caps.h"
#include "mbedtls/base64.h"
#include "secure_random.h"
#include "ssh_transport.h"
#include "user_database.h"
#include "web_security.h"
#include "web_serial_transport.h"
#define USER_CONSOLE_KEY_LINE_CAPACITY 256U
/* Gate-owned public projection (no verifiers). Lazily retained for firmware
* lifetime; allocation failure must not disable mutations or UART0 recovery. */
static user_database_snapshot_t *s_user_snapshot;
static void print_usage(void)
{
printf("Usage:\n");
printf(" user status|list\n");
printf(" user show <username>\n");
printf(" user bootstrap [--generate]\n");
printf(" user recover --force\n");
printf(" user add <username> <user|admin> [--generate]\n");
printf(" user delete <username> --force\n");
printf(" user role <username> <user|admin> --force\n");
printf(" user password <username> [--generate]\n");
printf(" user key add <username>\n");
printf(" user key add <username> <type> <base64>\n");
printf(" user key delete <username> <0..2> --force\n");
printf(" user key clear <username> --force\n");
}
@@ -88,23 +94,30 @@ static void print_user(const user_database_user_snapshot_t *user)
static int show_users(const char *selected)
{
user_database_snapshot_t snapshot;
esp_err_t error = user_database_get_snapshot(&snapshot);
if (s_user_snapshot == NULL) {
s_user_snapshot = heap_caps_malloc(sizeof(*s_user_snapshot),
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (s_user_snapshot == NULL) {
printf("User status unavailable: PSRAM snapshot storage unavailable\n");
return 1;
}
}
esp_err_t error = user_database_get_snapshot(s_user_snapshot);
if (error != ESP_OK) {
printf("User database unavailable: %s\n", esp_err_to_name(error));
secure_wipe(s_user_snapshot, sizeof(*s_user_snapshot));
return 1;
}
if (selected == NULL) {
printf("User database: generation=%lu users=%u/%u admins=%u bootstrapped=%s\n",
(unsigned long)snapshot.generation,
(unsigned int)snapshot.user_count,
printf("User database: generation=%lu users=%u/%u admins=%u\n",
(unsigned long)s_user_snapshot->generation,
(unsigned int)s_user_snapshot->user_count,
USER_DATABASE_MAX_USERS,
(unsigned int)snapshot.admin_count,
snapshot.admin_bootstrapped ? "yes" : "no");
(unsigned int)s_user_snapshot->admin_count);
}
bool found = false;
for (size_t index = 0U; index < USER_DATABASE_MAX_USERS; ++index) {
const user_database_user_snapshot_t *user = &snapshot.users[index];
const user_database_user_snapshot_t *user = &s_user_snapshot->users[index];
if (!user->active ||
(selected != NULL &&
(strlen(selected) != user->username_length ||
@@ -116,11 +129,13 @@ static int show_users(const char *selected)
}
if (selected != NULL && !found) {
printf("User '%s' not found.\n", selected);
secure_wipe(s_user_snapshot, sizeof(*s_user_snapshot));
return 1;
}
if (!snapshot.admin_bootstrapped) {
printf("Administrative network access is not bootstrapped; use 'user bootstrap'.\n");
if (s_user_snapshot->admin_count == 0U) {
printf("No administrators; use 'user add <username> admin' on UART0.\n");
}
secure_wipe(s_user_snapshot, sizeof(*s_user_snapshot));
return 0;
}
@@ -165,53 +180,23 @@ static void show_generated_password(const char *username,
static int recover_database(void)
{
web_security_credentials_t credentials;
memset(&credentials, 0, sizeof(credentials));
esp_err_t error = web_security_show_credentials(&credentials);
if (error == ESP_OK) {
const user_database_legacy_credentials_t legacy = {
.username = (const uint8_t *)credentials.username,
.username_length = credentials.username_length,
.password = (const uint8_t *)credentials.password,
.password_length = credentials.password_length,
};
error = user_database_recover_from_legacy(&legacy);
}
secure_wipe(&credentials, sizeof(credentials));
esp_err_t error = user_database_recover_empty();
if (error != ESP_OK) {
printf("Could not recover user database: %s\n", esp_err_to_name(error));
return 1;
}
printf("User database replaced from the current legacy network credential.\n");
printf("The imported account has role user; run 'user bootstrap' to establish an administrator.\n");
printf("User database rebuilt empty; no credentials imported.\n");
printf("Use 'user add <username> admin' on UART0 to create an administrator.\n");
return 0;
}
static int bootstrap(bool generated)
static esp_err_t mutation_currentness(void)
{
esp_err_t error;
if (generated) {
user_database_generated_password_t password;
error = user_database_bootstrap_admin_generated(&password);
if (error == ESP_OK) {
show_generated_password("admin", &password);
}
} else {
uint8_t password[USER_DATABASE_PASSWORD_CAPACITY + 1U] = {0};
size_t password_length = 0U;
error = read_password(password, &password_length);
if (error == ESP_OK) {
error = user_database_bootstrap_admin(password, password_length);
}
secure_wipe(password, sizeof(password));
if (admin_ssh_console_dispatch_is_remote() &&
!admin_ssh_console_dispatch_is_current()) {
return ESP_ERR_NOT_ALLOWED;
}
if (error != ESP_OK) {
printf("Could not bootstrap administrator: %s\n", esp_err_to_name(error));
return 1;
}
revoke_user_network_sessions("admin");
printf("Administrator account bootstrapped. Role-aware HTTPS and SSH authentication is active.\n");
return 0;
return ESP_OK;
}
static int add_user(const char *username, const char *role_text, bool generated)
@@ -234,6 +219,7 @@ static int add_user(const char *username, const char *role_text, bool generated)
uint8_t password[USER_DATABASE_PASSWORD_CAPACITY + 1U] = {0};
size_t password_length = 0U;
error = read_password(password, &password_length);
if (error == ESP_OK) error = mutation_currentness();
if (error == ESP_OK) {
error = user_database_create((const uint8_t *)username, strlen(username),
role, password, password_length);
@@ -263,6 +249,7 @@ static int change_password(const char *username, bool generated)
uint8_t password[USER_DATABASE_PASSWORD_CAPACITY + 1U] = {0};
size_t password_length = 0U;
error = read_password(password, &password_length);
if (error == ESP_OK) error = mutation_currentness();
if (error == ESP_OK) {
error = user_database_set_password((const uint8_t *)username,
strlen(username),
@@ -297,6 +284,42 @@ static bool key_delimiter(uint8_t value)
return value == ' ' || value == '\t';
}
static int add_key_parts(const char *username,
const uint8_t *type, size_t type_length,
const uint8_t *encoded, size_t encoded_length)
{
uint8_t blob[USER_DATABASE_SSH_KEY_BLOB_CAPACITY] = {0};
size_t blob_length = 0U;
int decoded = mbedtls_base64_decode(blob, sizeof(blob), &blob_length,
encoded, encoded_length);
if (decoded != 0 || !user_database_key_valid(type, type_length, blob, blob_length)) {
printf("Unsupported or malformed key; use ssh-ed25519 or ecdsa-sha2-nistp256.\n");
secure_wipe(blob, sizeof(blob));
return 1;
}
uint8_t key_index = 0U;
esp_err_t error = user_database_add_ssh_key(
(const uint8_t *)username, strlen(username), type, type_length,
blob, blob_length, &key_index);
secure_wipe(blob, sizeof(blob));
if (error != ESP_OK) {
if (error == USER_DATABASE_ERR_DUPLICATE_SSH_KEY) {
printf("Could not add SSH key: that public key is already assigned to this account.\n");
} else if (error == ESP_ERR_NO_MEM) {
printf("Could not add SSH key: the account already has %u keys.\n",
USER_DATABASE_MAX_SSH_KEYS_PER_USER);
} else {
printf("Could not add SSH key: %s\n", esp_err_to_name(error));
}
return 1;
}
revoke_user_network_sessions(username);
printf("SSH public key added at index %u. Public-key login is active.\n",
(unsigned int)key_index);
return 0;
}
static int add_key(const char *username)
{
uint8_t line[USER_CONSOLE_KEY_LINE_CAPACITY] = {0};
@@ -338,42 +361,23 @@ static int add_key(const char *username)
size_t encoded_length = encoded_end == NULL
? remaining
: (size_t)(encoded_end - encoded);
uint8_t blob[USER_DATABASE_SSH_KEY_BLOB_CAPACITY] = {0};
size_t blob_length = 0U;
int decoded = mbedtls_base64_decode(blob, sizeof(blob), &blob_length,
encoded, encoded_length);
if (decoded != 0 ||
!user_database_key_valid(line, type_length, blob, blob_length)) {
printf("Unsupported or malformed key; use ssh-ed25519 or ecdsa-sha2-nistp256.\n");
secure_wipe(blob, sizeof(blob));
secure_wipe(line, sizeof(line));
return 1;
}
uint8_t key_index = 0U;
error = user_database_add_ssh_key((const uint8_t *)username, strlen(username),
line, type_length, blob, blob_length, &key_index);
secure_wipe(blob, sizeof(blob));
int result = add_key_parts(username, line, type_length, encoded, encoded_length);
secure_wipe(line, sizeof(line));
if (error != ESP_OK) {
if (error == USER_DATABASE_ERR_DUPLICATE_SSH_KEY) {
printf("Could not add SSH key: that public key is already assigned to this account.\n");
} else if (error == ESP_ERR_NO_MEM) {
printf("Could not add SSH key: the account already has %u keys.\n",
USER_DATABASE_MAX_SSH_KEYS_PER_USER);
} else {
printf("Could not add SSH key: %s\n", esp_err_to_name(error));
}
return 1;
}
revoke_user_network_sessions(username);
printf("SSH public key added at index %u. Public-key login is active.\n",
(unsigned int)key_index);
return 0;
return result;
}
static int command_user(int argc, char **argv)
static int command_user_inner(int argc, char **argv)
{
bool remote = admin_ssh_console_dispatch_is_remote();
const user_principal_t *principal = admin_ssh_console_dispatch_principal();
/* Repeat admission on canonical parsed arguments: direct handler calls must
* not bypass self-target, generated-secret or UART0-only restrictions. */
if (admin_ssh_console_dispatch_is_web() &&
(!admin_ssh_console_web_user_command_allowed((size_t)argc, argv, principal) ||
!admin_ssh_console_dispatch_is_current())) {
printf("Browser account command restricted or session no longer current.\n");
return 1;
}
if (argc == 1 || (argc == 2 && strcmp(argv[1], "status") == 0) ||
(argc == 2 && strcmp(argv[1], "list") == 0)) {
return show_users(NULL);
@@ -383,15 +387,11 @@ static int command_user(int argc, char **argv)
}
if (argc == 3 && strcmp(argv[1], "recover") == 0 &&
strcmp(argv[2], "--force") == 0) {
return recover_database();
}
if ((argc == 2 || argc == 3) && strcmp(argv[1], "bootstrap") == 0) {
bool generated = argc == 3 && strcmp(argv[2], "--generate") == 0;
if (argc == 3 && !generated) {
print_usage();
if (remote) {
printf("User database recovery is restricted to physical UART0.\n");
return 1;
}
return bootstrap(generated);
return recover_database();
}
if ((argc == 4 || argc == 5) && strcmp(argv[1], "add") == 0) {
bool generated = argc == 5 && strcmp(argv[4], "--generate") == 0;
@@ -403,9 +403,12 @@ static int command_user(int argc, char **argv)
}
if (argc == 4 && strcmp(argv[1], "delete") == 0 &&
strcmp(argv[3], "--force") == 0) {
esp_err_t error = user_database_delete((const uint8_t *)argv[2], strlen(argv[2]));
esp_err_t error = mutation_currentness();
if (error == ESP_OK) {
error = user_database_delete((const uint8_t *)argv[2], strlen(argv[2]));
}
if (error != ESP_OK) {
printf("Could not delete user (the migrated or final admin is protected): %s\n",
printf("Could not delete user (the final admin is protected): %s\n",
esp_err_to_name(error));
return 1;
}
@@ -421,8 +424,10 @@ static int command_user(int argc, char **argv)
printf("Role must be user or admin.\n");
return 1;
}
esp_err_t error = user_database_set_role((const uint8_t *)argv[2],
strlen(argv[2]), role);
esp_err_t error = mutation_currentness();
if (error == ESP_OK) {
error = user_database_set_role((const uint8_t *)argv[2], strlen(argv[2]), role);
}
if (error != ESP_OK) {
printf("Could not change role (the final admin is protected): %s\n",
esp_err_to_name(error));
@@ -438,12 +443,23 @@ static int command_user(int argc, char **argv)
print_usage();
return 1;
}
if (remote && generated && principal != NULL &&
strlen(argv[2]) == principal->username_length &&
memcmp(argv[2], principal->username, principal->username_length) == 0) {
printf("Remote generated-password changes for the current admin are disabled; use UART0.\n");
return 1;
}
return change_password(argv[2], generated);
}
if (argc == 4 && strcmp(argv[1], "key") == 0 &&
strcmp(argv[2], "add") == 0) {
return add_key(argv[3]);
}
if (argc == 6 && strcmp(argv[1], "key") == 0 &&
strcmp(argv[2], "add") == 0) {
return add_key_parts(argv[3], (const uint8_t *)argv[4], strlen(argv[4]),
(const uint8_t *)argv[5], strlen(argv[5]));
}
if (argc == 6 && strcmp(argv[1], "key") == 0 &&
strcmp(argv[2], "delete") == 0 && strcmp(argv[5], "--force") == 0) {
uint8_t index;
@@ -477,6 +493,18 @@ static int command_user(int argc, char **argv)
return 1;
}
static int command_user(int argc, char **argv)
{
esp_err_t error = admin_command_gate_take();
if (error != ESP_OK) {
printf("Administrative command gate unavailable: %s\n", esp_err_to_name(error));
return 1;
}
int result = command_user_inner(argc, argv);
admin_command_gate_give();
return result;
}
esp_err_t user_console_register_commands(void)
{
const esp_console_cmd_t command = {
+252 -207
View File
@@ -6,6 +6,7 @@
#include <stddef.h>
#include <string.h>
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "mbedtls/ecp.h"
@@ -24,7 +25,6 @@
static const uint8_t s_generated_alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static const uint8_t s_admin_username[] = "admin";
static const uint8_t s_ed25519_type[] = "ssh-ed25519";
static const uint8_t s_ecdsa_type[] = "ecdsa-sha2-nistp256";
static const uint8_t s_ecdsa_curve[] = "nistp256";
@@ -57,7 +57,8 @@ typedef struct {
uint32_t version;
uint32_t size;
uint32_t generation;
uint8_t admin_bootstrapped;
/* Retain the v1 wire byte/layout; derived by recount, never policy state. */
uint8_t v1_admin_marker;
uint8_t user_count;
uint8_t admin_count;
uint8_t reserved;
@@ -66,7 +67,7 @@ typedef struct {
static SemaphoreHandle_t s_mutex;
static stored_database_t s_database;
static stored_database_t s_candidate;
static stored_database_t *s_candidate;
static bool s_initialized;
static uint8_t s_dummy_salt[USER_DATABASE_PASSWORD_SALT_LENGTH];
static uint8_t s_dummy_hash[USER_DATABASE_PASSWORD_HASH_LENGTH];
@@ -80,9 +81,30 @@ static esp_err_t initialize_dummy_verifier(void)
return error;
}
static esp_err_t allocate_candidate(void)
{
if (s_candidate != NULL) {
return ESP_ERR_INVALID_STATE;
}
s_candidate = heap_caps_calloc_prefer(
1U, sizeof(*s_candidate), 2,
MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT,
MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
return s_candidate != NULL ? ESP_OK : ESP_ERR_NO_MEM;
}
static void discard_candidate(void)
{
secure_wipe(&s_candidate, sizeof(s_candidate));
if (s_candidate != NULL) {
secure_wipe(s_candidate, sizeof(*s_candidate));
}
}
static void release_candidate(void)
{
discard_candidate();
heap_caps_free(s_candidate);
s_candidate = NULL;
}
static bool constant_time_equal(const uint8_t *left, const uint8_t *right, size_t length)
@@ -273,7 +295,7 @@ static esp_err_t set_record_password(stored_user_t *user,
return error;
}
static esp_err_t generate_password(user_database_generated_password_t *generated)
esp_err_t user_database_generate_password_value(user_database_generated_password_t *generated)
{
if (generated == NULL) {
return ESP_ERR_INVALID_ARG;
@@ -329,7 +351,7 @@ static esp_err_t validate_database(const stored_database_t *database)
{
if (database->version != USER_DATABASE_SCHEMA_VERSION ||
database->size != sizeof(*database) || database->generation == 0U ||
database->admin_bootstrapped > 1U || database->reserved != 0U) {
database->v1_admin_marker > 1U || database->reserved != 0U) {
return ESP_ERR_INVALID_VERSION;
}
uint8_t users = 0U;
@@ -406,7 +428,7 @@ static esp_err_t validate_database(const stored_database_t *database)
}
}
if (users != database->user_count || admins != database->admin_count ||
(database->admin_bootstrapped != 0U) != (admins > 0U)) {
(database->v1_admin_marker != 0U) != (admins > 0U)) {
return ESP_ERR_INVALID_RESPONSE;
}
return ESP_OK;
@@ -424,6 +446,7 @@ static void recount(stored_database_t *database)
}
}
}
database->v1_admin_marker = database->admin_count > 0U ? 1U : 0U;
}
static esp_err_t next_generation(uint32_t *generation)
@@ -437,10 +460,10 @@ static esp_err_t next_generation(uint32_t *generation)
static esp_err_t commit_candidate_locked(void)
{
recount(&s_candidate);
esp_err_t error = next_generation(&s_candidate.generation);
recount(s_candidate);
esp_err_t error = next_generation(&s_candidate->generation);
if (error == ESP_OK) {
error = validate_database(&s_candidate);
error = validate_database(s_candidate);
}
if (error != ESP_OK) {
discard_candidate();
@@ -451,7 +474,7 @@ static esp_err_t commit_candidate_locked(void)
error = nvs_open(USER_DATABASE_NVS_NAMESPACE, NVS_READWRITE, &handle);
if (error == ESP_OK) {
error = nvs_set_blob(handle, USER_DATABASE_NVS_BLOB_KEY,
&s_candidate, sizeof(s_candidate));
s_candidate, sizeof(*s_candidate));
if (error == ESP_OK) {
error = nvs_commit(handle);
}
@@ -459,7 +482,7 @@ static esp_err_t commit_candidate_locked(void)
}
if (error == ESP_OK) {
secure_wipe(&s_database, sizeof(s_database));
s_database = s_candidate;
s_database = *s_candidate;
}
discard_candidate();
return error;
@@ -496,58 +519,7 @@ static esp_err_t initialize_user(stored_user_t *user,
return error;
}
static bool legacy_credentials_valid(const user_database_legacy_credentials_t *legacy)
{
return legacy != NULL && legacy->username != NULL && legacy->password != NULL &&
user_database_username_valid(legacy->username, legacy->username_length) &&
user_database_password_valid(legacy->password, legacy->password_length);
}
static esp_err_t synchronize_legacy_locked(
const user_database_legacy_credentials_t *legacy, bool *synchronized)
{
*synchronized = false;
if (s_database.admin_bootstrapped != 0U) {
return ESP_OK;
}
int index = find_user(&s_database, legacy->username, legacy->username_length);
if (index < 0) {
return ESP_OK;
}
const stored_user_t *stored = &s_database.users[index];
uint8_t derived[USER_DATABASE_PASSWORD_HASH_LENGTH] = {0};
esp_err_t error = derive_password(legacy->password, legacy->password_length,
stored->password_salt,
stored->password_iterations, derived);
bool already_current = error == ESP_OK &&
constant_time_equal(derived, stored->password_hash,
sizeof(derived));
secure_wipe(derived, sizeof(derived));
if (error != ESP_OK || already_current) {
*synchronized = already_current;
return error;
}
s_candidate = s_database;
stored_user_t *candidate_user = &s_candidate.users[index];
error = set_record_password(candidate_user, legacy->password,
legacy->password_length);
if (error == ESP_OK) {
error = next_generation(&candidate_user->auth_generation);
}
if (error == ESP_OK) {
error = commit_candidate_locked();
} else {
discard_candidate();
}
*synchronized = error == ESP_OK;
return error;
}
esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
user_database_load_result_t *load_result)
esp_err_t user_database_init(user_database_load_result_t *load_result)
{
if (load_result == NULL || s_mutex != NULL) {
return ESP_ERR_INVALID_ARG;
@@ -557,12 +529,16 @@ esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
if (s_mutex == NULL) {
return ESP_ERR_NO_MEM;
}
esp_err_t error = nvs_flash_init();
esp_err_t error = allocate_candidate();
if (error != ESP_OK) {
vSemaphoreDelete(s_mutex);
s_mutex = NULL;
return error;
}
error = nvs_flash_init();
if (error != ESP_OK) {
goto init_failed;
}
bool storage_missing = false;
nvs_handle_t handle;
@@ -583,10 +559,6 @@ esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
if (error == ESP_OK && !storage_missing) {
error = validate_database(&s_database);
}
if (error == ESP_OK && !storage_missing && legacy_credentials_valid(legacy)) {
bool synchronized = false;
error = synchronize_legacy_locked(legacy, &synchronized);
}
if (error == ESP_OK && !storage_missing) {
error = initialize_dummy_verifier();
if (error == ESP_OK) {
@@ -604,7 +576,7 @@ esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
goto init_failed;
}
if (!storage_missing || !legacy_credentials_valid(legacy)) {
if (!storage_missing) {
error = ESP_ERR_INVALID_STATE;
goto init_failed;
}
@@ -613,15 +585,8 @@ esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
s_database.version = USER_DATABASE_SCHEMA_VERSION;
s_database.size = sizeof(s_database);
s_database.generation = 1U;
error = initialize_user(&s_database.users[0], legacy->username,
legacy->username_length, USER_ROLE_USER,
legacy->password, legacy->password_length);
if (error != ESP_OK) {
goto init_failed;
}
*load_result = USER_DATABASE_LOAD_MIGRATED_LEGACY;
recount(&s_database);
s_candidate = s_database;
*s_candidate = s_database;
error = commit_candidate_locked();
if (error != ESP_OK) {
goto init_failed;
@@ -635,7 +600,7 @@ esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
init_failed:
secure_wipe(&s_database, sizeof(s_database));
discard_candidate();
release_candidate();
secure_wipe(s_dummy_salt, sizeof(s_dummy_salt));
secure_wipe(s_dummy_hash, sizeof(s_dummy_hash));
vSemaphoreDelete(s_mutex);
@@ -643,28 +608,8 @@ init_failed:
return error;
}
esp_err_t user_database_sync_legacy_credentials(
const user_database_legacy_credentials_t *legacy, bool *synchronized)
esp_err_t user_database_recover_empty(void)
{
if (synchronized == NULL || !legacy_credentials_valid(legacy)) {
return ESP_ERR_INVALID_ARG;
}
*synchronized = false;
if (!s_initialized || s_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
esp_err_t error = synchronize_legacy_locked(legacy, synchronized);
xSemaphoreGive(s_mutex);
return error;
}
esp_err_t user_database_recover_from_legacy(
const user_database_legacy_credentials_t *legacy)
{
if (!legacy_credentials_valid(legacy)) {
return ESP_ERR_INVALID_ARG;
}
if (s_initialized || s_mutex != NULL) {
return ESP_ERR_INVALID_STATE;
}
@@ -673,24 +618,23 @@ esp_err_t user_database_recover_from_legacy(
if (s_mutex == NULL) {
return ESP_ERR_NO_MEM;
}
esp_err_t error = nvs_flash_init();
esp_err_t error = allocate_candidate();
if (error != ESP_OK) {
vSemaphoreDelete(s_mutex);
s_mutex = NULL;
return error;
}
error = nvs_flash_init();
if (error != ESP_OK) {
goto recovery_failed;
}
memset(&s_database, 0, sizeof(s_database));
memset(&s_candidate, 0, sizeof(s_candidate));
s_candidate.version = USER_DATABASE_SCHEMA_VERSION;
s_candidate.size = sizeof(s_candidate);
s_candidate.generation = 1U;
error = initialize_user(&s_candidate.users[0], legacy->username,
legacy->username_length, USER_ROLE_USER,
legacy->password, legacy->password_length);
if (error == ESP_OK) {
error = commit_candidate_locked();
} else {
discard_candidate();
}
memset(s_candidate, 0, sizeof(*s_candidate));
s_candidate->version = USER_DATABASE_SCHEMA_VERSION;
s_candidate->size = sizeof(*s_candidate);
s_candidate->generation = 1U;
error = commit_candidate_locked();
if (error == ESP_OK) {
error = initialize_dummy_verifier();
}
@@ -701,7 +645,7 @@ esp_err_t user_database_recover_from_legacy(
recovery_failed:
secure_wipe(&s_database, sizeof(s_database));
discard_candidate();
release_candidate();
secure_wipe(s_dummy_salt, sizeof(s_dummy_salt));
secure_wipe(s_dummy_hash, sizeof(s_dummy_hash));
vSemaphoreDelete(s_mutex);
@@ -720,7 +664,6 @@ esp_err_t user_database_get_snapshot(user_database_snapshot_t *snapshot)
memset(snapshot, 0, sizeof(*snapshot));
xSemaphoreTake(s_mutex, portMAX_DELAY);
snapshot->initialized = true;
snapshot->admin_bootstrapped = s_database.admin_bootstrapped != 0U;
snapshot->generation = s_database.generation;
snapshot->user_count = s_database.user_count;
snapshot->admin_count = s_database.admin_count;
@@ -756,6 +699,25 @@ esp_err_t user_database_get_snapshot(user_database_snapshot_t *snapshot)
return ESP_OK;
}
esp_err_t user_database_get_accounts(user_database_accounts_t *accounts)
{
if (accounts == NULL) return ESP_ERR_INVALID_ARG;
memset(accounts, 0, sizeof(*accounts));
if (!s_initialized || s_mutex == NULL) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_mutex, 0U) != pdTRUE) return ESP_ERR_TIMEOUT;
for (size_t i = 0; i < USER_DATABASE_MAX_USERS; ++i) {
const stored_user_t *user = &s_database.users[i];
if (!user->active) continue;
user_database_account_t *out = &accounts->users[accounts->count++];
out->user_id = user->user_id;
out->auth_generation = user->auth_generation;
out->role = (user_role_t)user->role;
memcpy(out->username, user->username, user->username_length);
}
xSemaphoreGive(s_mutex);
return ESP_OK;
}
static void fill_principal(const stored_user_t *user, user_auth_method_t method,
user_principal_t *principal)
{
@@ -918,12 +880,9 @@ static esp_err_t create_locked(const uint8_t *username, size_t username_length,
if (free_index < 0) {
return ESP_ERR_NO_MEM;
}
s_candidate = s_database;
esp_err_t error = initialize_user(&s_candidate.users[free_index], username,
*s_candidate = s_database;
esp_err_t error = initialize_user(&s_candidate->users[free_index], username,
username_length, role, password, password_length);
if (error == ESP_OK && role == USER_ROLE_ADMIN) {
s_candidate.admin_bootstrapped = 1U;
}
if (error == ESP_OK) {
return commit_candidate_locked();
}
@@ -954,7 +913,7 @@ esp_err_t user_database_create_generated(
const uint8_t *username, size_t username_length, user_role_t role,
user_database_generated_password_t *generated_password)
{
esp_err_t error = generate_password(generated_password);
esp_err_t error = user_database_generate_password_value(generated_password);
if (error == ESP_OK) {
error = user_database_create(username, username_length, role,
generated_password->password,
@@ -966,56 +925,6 @@ esp_err_t user_database_create_generated(
return error;
}
esp_err_t user_database_bootstrap_admin(const uint8_t *password,
size_t password_length)
{
if (!s_initialized || s_mutex == NULL ||
!user_database_password_valid(password, password_length)) {
return ESP_ERR_INVALID_ARG;
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
if (s_database.admin_bootstrapped != 0U) {
xSemaphoreGive(s_mutex);
return ESP_ERR_INVALID_STATE;
}
int index = find_user(&s_database, s_admin_username, sizeof(s_admin_username) - 1U);
esp_err_t error;
if (index < 0) {
error = create_locked(s_admin_username, sizeof(s_admin_username) - 1U,
USER_ROLE_ADMIN, password, password_length);
} else {
s_candidate = s_database;
stored_user_t *user = &s_candidate.users[index];
error = set_record_password(user, password, password_length);
if (error == ESP_OK) {
user->role = USER_ROLE_ADMIN;
error = next_generation(&user->auth_generation);
}
if (error == ESP_OK) {
s_candidate.admin_bootstrapped = 1U;
error = commit_candidate_locked();
} else {
discard_candidate();
}
}
xSemaphoreGive(s_mutex);
return error;
}
esp_err_t user_database_bootstrap_admin_generated(
user_database_generated_password_t *generated_password)
{
esp_err_t error = generate_password(generated_password);
if (error == ESP_OK) {
error = user_database_bootstrap_admin(generated_password->password,
generated_password->password_length);
}
if (error != ESP_OK && generated_password != NULL) {
secure_wipe(generated_password, sizeof(*generated_password));
}
return error;
}
static esp_err_t mutate_user_begin(const uint8_t *username, size_t username_length,
int *index)
{
@@ -1026,31 +935,75 @@ static esp_err_t mutate_user_begin(const uint8_t *username, size_t username_leng
if (*index < 0) {
return ESP_ERR_NOT_FOUND;
}
s_candidate = s_database;
*s_candidate = s_database;
return ESP_OK;
}
esp_err_t user_database_delete(const uint8_t *username, size_t username_length)
static bool target_matches_locked(const uint8_t *username, size_t length,
const user_database_account_t *expected)
{
if (!expected) return true;
int index = find_user(&s_database, username, length);
return index >= 0 && expected->user_id != 0 && expected->auth_generation != 0 &&
s_database.users[index].user_id == expected->user_id &&
s_database.users[index].auth_generation == expected->auth_generation;
}
esp_err_t user_database_get_account_keys(const user_database_account_t *expected,
user_database_user_snapshot_t *snapshot)
{
if (!snapshot) return ESP_ERR_INVALID_ARG;
memset(snapshot, 0, sizeof(*snapshot));
if (!expected) return ESP_ERR_INVALID_ARG;
size_t length = strnlen(expected->username, sizeof(expected->username));
if (!user_database_username_valid((const uint8_t *)expected->username, length))
return ESP_ERR_INVALID_ARG;
if (!s_initialized || !s_mutex) return ESP_ERR_INVALID_STATE;
if (xSemaphoreTake(s_mutex, 0U) != pdTRUE) return ESP_ERR_TIMEOUT;
esp_err_t error = ESP_ERR_NOT_FOUND;
if (target_matches_locked((const uint8_t *)expected->username, length, expected)) {
const stored_user_t *user = &s_database.users[find_user(&s_database,
(const uint8_t *)expected->username, length)];
snapshot->active = true;
snapshot->user_id = user->user_id;
snapshot->auth_generation = user->auth_generation;
snapshot->role = (user_role_t)user->role;
snapshot->username_length = length;
memcpy(snapshot->username, user->username, length);
snapshot->public_key_count = user->key_count;
for (size_t i = 0; i < USER_DATABASE_MAX_SSH_KEYS_PER_USER; ++i) {
const stored_key_t *key = &user->keys[i];
if (!key->active) continue;
user_database_key_snapshot_t *out = &snapshot->public_keys[i];
out->active = true;
out->index = (uint8_t)i;
out->key_type_length = key->type_length;
memcpy(out->key_type, key->type, key->type_length);
memcpy(out->sha256_fingerprint, key->fingerprint, sizeof(out->sha256_fingerprint));
}
error = ESP_OK;
}
xSemaphoreGive(s_mutex);
return error;
}
static esp_err_t delete_user(const uint8_t *username, size_t username_length,
const user_database_account_t *expected)
{
if (!s_initialized || s_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
int index;
esp_err_t error = mutate_user_begin(username, username_length, &index);
esp_err_t error = target_matches_locked(username, username_length, expected)
? mutate_user_begin(username, username_length, &index) : ESP_ERR_NOT_FOUND;
if (error == ESP_OK) {
const stored_user_t *user = &s_database.users[index];
bool protected_migrated_admin =
s_database.admin_bootstrapped == 0U &&
user->username_length == sizeof(s_admin_username) - 1U &&
memcmp(user->username, s_admin_username,
sizeof(s_admin_username) - 1U) == 0;
if (protected_migrated_admin ||
(user->role == USER_ROLE_ADMIN && s_database.admin_count <= 1U)) {
if (user->role == USER_ROLE_ADMIN && s_database.admin_count <= 1U) {
error = ESP_ERR_INVALID_STATE;
discard_candidate();
} else {
secure_wipe(&s_candidate.users[index], sizeof(s_candidate.users[index]));
secure_wipe(&s_candidate->users[index], sizeof(s_candidate->users[index]));
error = commit_candidate_locked();
}
}
@@ -1058,8 +1011,8 @@ esp_err_t user_database_delete(const uint8_t *username, size_t username_length)
return error;
}
esp_err_t user_database_set_role(const uint8_t *username, size_t username_length,
user_role_t role)
static esp_err_t set_role(const uint8_t *username, size_t username_length,
user_role_t role, const user_database_account_t *expected)
{
if (!s_initialized || s_mutex == NULL ||
(role != USER_ROLE_USER && role != USER_ROLE_ADMIN)) {
@@ -1067,9 +1020,10 @@ esp_err_t user_database_set_role(const uint8_t *username, size_t username_length
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
int index;
esp_err_t error = mutate_user_begin(username, username_length, &index);
esp_err_t error = target_matches_locked(username, username_length, expected)
? mutate_user_begin(username, username_length, &index) : ESP_ERR_NOT_FOUND;
if (error == ESP_OK) {
stored_user_t *user = &s_candidate.users[index];
stored_user_t *user = &s_candidate->users[index];
if (user->role == role) {
error = ESP_OK;
discard_candidate();
@@ -1079,9 +1033,6 @@ esp_err_t user_database_set_role(const uint8_t *username, size_t username_length
} else {
user->role = (uint8_t)role;
error = next_generation(&user->auth_generation);
if (error == ESP_OK && role == USER_ROLE_ADMIN) {
s_candidate.admin_bootstrapped = 1U;
}
if (error == ESP_OK) {
error = commit_candidate_locked();
} else {
@@ -1093,8 +1044,37 @@ esp_err_t user_database_set_role(const uint8_t *username, size_t username_length
return error;
}
esp_err_t user_database_set_password(const uint8_t *username, size_t username_length,
const uint8_t *password, size_t password_length)
esp_err_t user_database_delete(const uint8_t *username, size_t length)
{
return delete_user(username, length, NULL);
}
esp_err_t user_database_set_role(const uint8_t *username, size_t length, user_role_t role)
{
return set_role(username, length, role, NULL);
}
esp_err_t user_database_delete_current(const user_database_account_t *expected)
{
if (!expected) return ESP_ERR_INVALID_ARG;
size_t length = strnlen(expected->username, sizeof(expected->username));
if (!user_database_username_valid((const uint8_t *)expected->username, length))
return ESP_ERR_INVALID_ARG;
return delete_user((const uint8_t *)expected->username, length, expected);
}
esp_err_t user_database_set_role_current(const user_database_account_t *expected, user_role_t role)
{
if (!expected) return ESP_ERR_INVALID_ARG;
size_t length = strnlen(expected->username, sizeof(expected->username));
if (!user_database_username_valid((const uint8_t *)expected->username, length))
return ESP_ERR_INVALID_ARG;
return set_role((const uint8_t *)expected->username, length, role, expected);
}
static esp_err_t set_password(const uint8_t *username, size_t username_length,
const uint8_t *password, size_t password_length,
const user_database_account_t *expected)
{
if (!s_initialized || s_mutex == NULL ||
!user_database_password_valid(password, password_length)) {
@@ -1102,9 +1082,10 @@ esp_err_t user_database_set_password(const uint8_t *username, size_t username_le
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
int index;
esp_err_t error = mutate_user_begin(username, username_length, &index);
esp_err_t error = target_matches_locked(username, username_length, expected)
? mutate_user_begin(username, username_length, &index) : ESP_ERR_NOT_FOUND;
if (error == ESP_OK) {
stored_user_t *user = &s_candidate.users[index];
stored_user_t *user = &s_candidate->users[index];
error = set_record_password(user, password, password_length);
if (error == ESP_OK) {
error = next_generation(&user->auth_generation);
@@ -1119,11 +1100,27 @@ esp_err_t user_database_set_password(const uint8_t *username, size_t username_le
return error;
}
esp_err_t user_database_set_password(const uint8_t *username, size_t username_length,
const uint8_t *password, size_t password_length)
{
return set_password(username, username_length, password, password_length, NULL);
}
esp_err_t user_database_set_password_current(const user_database_account_t *expected,
const uint8_t *password, size_t password_length)
{
if (!expected) return ESP_ERR_INVALID_ARG;
size_t length = strnlen(expected->username, sizeof(expected->username));
if (!user_database_username_valid((const uint8_t *)expected->username, length))
return ESP_ERR_INVALID_ARG;
return set_password((const uint8_t *)expected->username, length, password, password_length, expected);
}
esp_err_t user_database_generate_password(
const uint8_t *username, size_t username_length,
user_database_generated_password_t *generated_password)
{
esp_err_t error = generate_password(generated_password);
esp_err_t error = user_database_generate_password_value(generated_password);
if (error == ESP_OK) {
error = user_database_set_password(username, username_length,
generated_password->password,
@@ -1135,11 +1132,11 @@ esp_err_t user_database_generate_password(
return error;
}
esp_err_t user_database_add_ssh_key(
static esp_err_t add_ssh_key(
const uint8_t *username, size_t username_length,
const uint8_t *key_type, size_t key_type_length,
const uint8_t *key_blob, size_t key_blob_length,
uint8_t *key_index)
uint8_t *key_index, const user_database_account_t *expected)
{
if (!s_initialized || s_mutex == NULL || key_index == NULL ||
!user_database_key_valid(key_type, key_type_length, key_blob, key_blob_length)) {
@@ -1147,9 +1144,10 @@ esp_err_t user_database_add_ssh_key(
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
int user_index;
esp_err_t error = mutate_user_begin(username, username_length, &user_index);
esp_err_t error = target_matches_locked(username, username_length, expected)
? mutate_user_begin(username, username_length, &user_index) : ESP_ERR_NOT_FOUND;
if (error == ESP_OK) {
stored_user_t *user = &s_candidate.users[user_index];
stored_user_t *user = &s_candidate->users[user_index];
int free_index = -1;
for (size_t index = 0U;
index < USER_DATABASE_MAX_SSH_KEYS_PER_USER; ++index) {
@@ -1198,9 +1196,9 @@ esp_err_t user_database_add_ssh_key(
return error;
}
esp_err_t user_database_remove_ssh_key(const uint8_t *username,
size_t username_length,
uint8_t key_index)
static esp_err_t remove_ssh_key(const uint8_t *username,
size_t username_length, uint8_t key_index,
const user_database_account_t *expected)
{
if (!s_initialized || s_mutex == NULL ||
key_index >= USER_DATABASE_MAX_SSH_KEYS_PER_USER) {
@@ -1208,9 +1206,10 @@ esp_err_t user_database_remove_ssh_key(const uint8_t *username,
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
int user_index;
esp_err_t error = mutate_user_begin(username, username_length, &user_index);
esp_err_t error = target_matches_locked(username, username_length, expected)
? mutate_user_begin(username, username_length, &user_index) : ESP_ERR_NOT_FOUND;
if (error == ESP_OK) {
stored_user_t *user = &s_candidate.users[user_index];
stored_user_t *user = &s_candidate->users[user_index];
if (user->keys[key_index].active == 0U) {
error = ESP_ERR_NOT_FOUND;
discard_candidate();
@@ -1229,17 +1228,19 @@ esp_err_t user_database_remove_ssh_key(const uint8_t *username,
return error;
}
esp_err_t user_database_clear_ssh_keys(const uint8_t *username,
size_t username_length)
static esp_err_t clear_ssh_keys(const uint8_t *username,
size_t username_length,
const user_database_account_t *expected)
{
if (!s_initialized || s_mutex == NULL) {
return ESP_ERR_INVALID_STATE;
}
xSemaphoreTake(s_mutex, portMAX_DELAY);
int user_index;
esp_err_t error = mutate_user_begin(username, username_length, &user_index);
esp_err_t error = target_matches_locked(username, username_length, expected)
? mutate_user_begin(username, username_length, &user_index) : ESP_ERR_NOT_FOUND;
if (error == ESP_OK) {
stored_user_t *user = &s_candidate.users[user_index];
stored_user_t *user = &s_candidate->users[user_index];
if (user->key_count == 0U) {
error = ESP_OK;
discard_candidate();
@@ -1257,3 +1258,47 @@ esp_err_t user_database_clear_ssh_keys(const uint8_t *username,
xSemaphoreGive(s_mutex);
return error;
}
esp_err_t user_database_add_ssh_key(const uint8_t *username, size_t length,
const uint8_t *type, size_t type_length, const uint8_t *blob, size_t blob_length,
uint8_t *index)
{
return add_ssh_key(username, length, type, type_length, blob, blob_length, index, NULL);
}
esp_err_t user_database_remove_ssh_key(const uint8_t *username, size_t length, uint8_t index)
{
return remove_ssh_key(username, length, index, NULL);
}
esp_err_t user_database_clear_ssh_keys(const uint8_t *username, size_t length)
{
return clear_ssh_keys(username, length, NULL);
}
static bool key_target_valid(const user_database_account_t *expected)
{
return expected && user_database_username_valid((const uint8_t *)expected->username,
strnlen(expected->username, sizeof(expected->username)));
}
esp_err_t user_database_add_ssh_key_current(const user_database_account_t *expected,
const uint8_t *type, size_t type_length, const uint8_t *blob, size_t blob_length,
uint8_t *index)
{
if (!key_target_valid(expected)) return ESP_ERR_INVALID_ARG;
return add_ssh_key((const uint8_t *)expected->username, strlen(expected->username),
type, type_length, blob, blob_length, index, expected);
}
esp_err_t user_database_remove_ssh_key_current(const user_database_account_t *expected, uint8_t index)
{
if (!key_target_valid(expected)) return ESP_ERR_INVALID_ARG;
return remove_ssh_key((const uint8_t *)expected->username, strlen(expected->username), index, expected);
}
esp_err_t user_database_clear_ssh_keys_current(const user_database_account_t *expected)
{
if (!key_target_valid(expected)) return ESP_ERR_INVALID_ARG;
return clear_ssh_keys((const uint8_t *)expected->username, strlen(expected->username), expected);
}
+39 -25
View File
@@ -38,17 +38,9 @@ typedef enum {
typedef enum {
USER_DATABASE_LOAD_STORED = 0,
USER_DATABASE_LOAD_MIGRATED_LEGACY,
USER_DATABASE_LOAD_EMPTY,
} user_database_load_result_t;
typedef struct {
const uint8_t *username;
size_t username_length;
const uint8_t *password;
size_t password_length;
} user_database_legacy_credentials_t;
typedef struct {
uint32_t user_id;
uint32_t auth_generation;
@@ -84,27 +76,52 @@ typedef struct {
typedef struct {
bool initialized;
bool admin_bootstrapped;
uint32_t generation;
uint8_t user_count;
uint8_t admin_count;
user_database_user_snapshot_t users[USER_DATABASE_MAX_USERS];
} user_database_snapshot_t;
esp_err_t user_database_init(const user_database_legacy_credentials_t *legacy,
user_database_load_result_t *load_result);
/*
* Before the first administrator is established, keep the migrated account in
* sync with the legacy recovery credential. Once bootstrapped, that credential
* remains independent and no longer authenticates Phase 8B network services.
*/
esp_err_t user_database_sync_legacy_credentials(
const user_database_legacy_credentials_t *legacy, bool *synchronized);
/* Explicit UART0 recovery: replace unavailable user storage with one legacy user. */
esp_err_t user_database_recover_from_legacy(
const user_database_legacy_credentials_t *legacy);
/* Missing storage is persisted empty; valid v1 records load unchanged.
* Corrupt/unsupported storage fails closed and is never automatically replaced. */
esp_err_t user_database_init(user_database_load_result_t *load_result);
/* Explicit UART0 recovery only; refuses an initialized database. No credentials
* are imported or created. Caller enforces physical-console authorization. */
esp_err_t user_database_recover_empty(void);
esp_err_t user_database_get_snapshot(user_database_snapshot_t *snapshot);
/* Compact secret-free list, zero-wait mutex acquisition; no key material. */
typedef struct {
uint32_t user_id, auth_generation;
user_role_t role;
char username[USER_DATABASE_USERNAME_CAPACITY + 1U];
} user_database_account_t;
typedef struct {
size_t count;
user_database_account_t users[USER_DATABASE_MAX_USERS];
} user_database_accounts_t;
esp_err_t user_database_get_accounts(user_database_accounts_t *accounts);
/* Zero-wait, identity-conditional projection; fingerprints only, no key blobs.
* Output is cleared on failure; absent/stale identity returns NOT_FOUND. */
esp_err_t user_database_get_account_keys(const user_database_account_t *expected,
user_database_user_snapshot_t *snapshot);
esp_err_t user_database_add_ssh_key_current(const user_database_account_t *expected,
const uint8_t *key_type, size_t key_type_length,
const uint8_t *key_blob, size_t key_blob_length, uint8_t *key_index);
esp_err_t user_database_remove_ssh_key_current(const user_database_account_t *expected,
uint8_t key_index);
esp_err_t user_database_clear_ssh_keys_current(const user_database_account_t *expected);
/* Compare target identity under the mutation lock, before candidate/commit.
* ESP_ERR_NOT_FOUND means absent or stale; existing account invariants apply. */
esp_err_t user_database_delete_current(const user_database_account_t *expected);
esp_err_t user_database_set_role_current(const user_database_account_t *expected,
user_role_t role);
esp_err_t user_database_set_password_current(const user_database_account_t *expected,
const uint8_t *password, size_t password_length);
/* RNG only: no database initialization, account mutation or persistence. Caller
* owns/wipes successful output; failures clear it. Same generator as CLI. */
esp_err_t user_database_generate_password_value(user_database_generated_password_t *generated);
esp_err_t user_database_authenticate_password(
const uint8_t *username, size_t username_length,
const uint8_t *password, size_t password_length,
@@ -117,10 +134,6 @@ esp_err_t user_database_authorize_ssh_public_key(
esp_err_t user_database_principal_is_current(const user_principal_t *principal,
bool *current);
esp_err_t user_database_bootstrap_admin(const uint8_t *password,
size_t password_length);
esp_err_t user_database_bootstrap_admin_generated(
user_database_generated_password_t *generated_password);
esp_err_t user_database_create(const uint8_t *username, size_t username_length,
user_role_t role,
const uint8_t *password, size_t password_length);
@@ -146,6 +159,7 @@ esp_err_t user_database_remove_ssh_key(const uint8_t *username,
esp_err_t user_database_clear_ssh_keys(const uint8_t *username,
size_t username_length);
bool user_database_username_valid(const uint8_t *username, size_t length);
bool user_database_password_valid(const uint8_t *password, size_t length);
bool user_database_key_valid(const uint8_t *key_type, size_t key_type_length,
+484
View File
@@ -0,0 +1,484 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "web_account_settings.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "admin_ssh_console.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "secure_random.h"
#include "mbedtls/base64.h"
#include "ssh_transport.h"
#include "web_cookie_auth.h"
#include "web_auth_parse.h"
#include "web_httpd_adapter.h"
#include "web_serial_transport.h"
enum { IDLE, PENDING, OK, FAILED, CANCELLED, STALE, PROTECTED, DUPLICATE, FULL };
static const char *const s_states[] = {"idle", "pending", "ok", "failed", "cancelled", "stale", "protected", "duplicate", "full"};
typedef enum { ACTION_ROLE, ACTION_DELETE, ACTION_CREATE, ACTION_PASSWORD,
ACTION_KEY_ADD, ACTION_KEY_DELETE, ACTION_KEY_CLEAR } account_action_t;
static const char *const s_actions[] = {"role", "delete", "create", "password", "key-add", "key-delete", "key-clear"};
typedef struct {
uint32_t id;
web_session_id_t session;
user_principal_t principal;
user_database_account_t target;
int64_t deadline;
user_role_t role;
unsigned state;
account_action_t action;
bool executing;
uint8_t password[USER_DATABASE_PASSWORD_CAPACITY + 1U];
size_t password_length;
char key_type[USER_DATABASE_SSH_KEY_TYPE_CAPACITY + 1U];
uint8_t key_blob[USER_DATABASE_SSH_KEY_BLOB_CAPACITY];
size_t key_blob_length;
uint8_t key_index;
} account_operation_t;
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static account_operation_t s_operation;
static uint32_t s_next_id;
static esp_timer_handle_t s_secret_timer;
static bool s_secret_timer_started;
static bool credential_action(account_action_t action)
{
return action == ACTION_CREATE || action == ACTION_PASSWORD;
}
static void wipe_input(account_operation_t *operation)
{
secure_wipe(&operation->principal, sizeof(operation->principal));
secure_wipe(&operation->target, sizeof(operation->target));
secure_wipe(operation->password, sizeof(operation->password));
operation->password_length = 0;
secure_wipe(operation->key_type, sizeof(operation->key_type));
secure_wipe(operation->key_blob, sizeof(operation->key_blob));
operation->key_blob_length = 0;
operation->key_index = 0;
}
static void expire_secret(void *unused)
{
(void)unused;
taskENTER_CRITICAL(&s_lock);
/* Inspect only the current ID/deadline, never a captured/rearmed job. A late
* tick cannot cancel a replacement before its own deadline or executing work. */
if (s_operation.id && s_operation.state == PENDING && !s_operation.executing &&
credential_action(s_operation.action) && esp_timer_get_time() >= s_operation.deadline) {
s_operation.state = CANCELLED;
wipe_input(&s_operation);
}
taskEXIT_CRITICAL(&s_lock);
}
static bool ensure_secret_timer(void)
{
/* HTTPD is the sole admission owner. Once started, this one firmware-lifetime
* timer is never stopped/rearmed/deleted. Expiry is best-effort scheduling,
* not hard realtime; no network/database work runs in its callback. */
if (!s_secret_timer) {
const esp_timer_create_args_t args = {.callback = expire_secret, .name = "account-secret"};
if (esp_timer_create(&args, &s_secret_timer) != ESP_OK) return false;
}
if (!s_secret_timer_started) {
if (esp_timer_start_periodic(s_secret_timer, 1000000ULL) != ESP_OK) return false;
s_secret_timer_started = true;
}
return true;
}
/* OpenSSH text envelope only. The canonical database parser validates the SSH
* blob (including the P256 point) on the dispatcher, not the HTTPD stack. */
static bool parse_public_key(const char *text, size_t length, account_operation_t *operation)
{
size_t type_length = 0;
while (type_length < length && text[type_length] != ' ' && text[type_length] != '\t') ++type_length;
if (!((type_length == 11 && !memcmp(text, "ssh-ed25519", 11)) ||
(type_length == 19 && !memcmp(text, "ecdsa-sha2-nistp256", 19)))) return false;
size_t start = type_length;
while (start < length && (text[start] == ' ' || text[start] == '\t')) ++start;
size_t end = start;
while (end < length && text[end] != ' ' && text[end] != '\t') ++end;
size_t encoded_length = end - start;
if (!encoded_length || encoded_length > 172 || encoded_length % 4) return false;
for (size_t i = start; i < end; ++i) {
unsigned char c = (unsigned char)text[i];
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '+' || c == '/' ||
(c == '=' && i >= end - 2))) return false;
}
for (size_t i = end; i < length; ++i)
if ((text[i] < ' ' || text[i] > '~') && text[i] != '\t') return false;
if (mbedtls_base64_decode(operation->key_blob, sizeof(operation->key_blob),
&operation->key_blob_length, (const uint8_t *)text + start, encoded_length) != 0) return false;
/* Round-trip rejects noncanonical padding and unused base64 bits. */
unsigned char encoded[173];
size_t written = 0;
if (mbedtls_base64_encode(encoded, sizeof(encoded), &written, operation->key_blob,
operation->key_blob_length) != 0 || written != encoded_length ||
memcmp(encoded, text + start, written)) return false;
memcpy(operation->key_type, text, type_length);
return true;
}
/* Exact flat schemas. Password/public_key accept JSON escapes; canonical database
* policy validates the decoded bytes. No coercion/unknown/duplicate fields. */
static bool parse_request(const char *body, size_t length, account_operation_t *operation, bool keys_only)
{
const char *keys[] = {"action", "username", "user_id", "auth_generation", "role", "password", "public_key", "key_index"};
unsigned seen = 0;
size_t pos = 0;
#define SPACE() while (pos < length && (body[pos] == ' ' || body[pos] == '\t' || body[pos] == '\r' || body[pos] == '\n')) ++pos
#define TAKE(c) do { SPACE(); if (pos == length || body[pos++] != (c)) return false; } while (0)
TAKE('{');
for (unsigned field = 0; field < 8; ++field) {
if (field) { TAKE(','); }
TAKE('"');
size_t start = pos;
while (pos < length && body[pos] != '"') ++pos;
if (pos == length) return false;
unsigned key = 0;
for (; key < 8; ++key)
if (strlen(keys[key]) == pos - start && !memcmp(body + start, keys[key], pos - start)) break;
if (key == 8 || (seen & (1U << key))) return false;
++pos; TAKE(':'); SPACE();
uint32_t number = 0;
char value[USER_DATABASE_USERNAME_CAPACITY + 1] = {0};
if (key == 2 || key == 3 || key == 7) {
start = pos;
while (pos < length && body[pos] >= '0' && body[pos] <= '9') {
unsigned digit = (unsigned)(body[pos++] - '0');
if (number > (UINT32_MAX - digit) / 10U) return false;
number = number * 10U + digit;
}
if ((!number && key != 7) || pos == start || (pos - start > 1 && body[start] == '0')) return false;
if (key == 7 && number >= USER_DATABASE_MAX_SSH_KEYS_PER_USER) return false;
} else if (key == 6) {
char text[385] = {0};
size_t text_length = 0;
if (!web_auth_parse_json_string(body, length, &pos, (uint8_t *)text,
sizeof(text), &text_length) || !parse_public_key(text, text_length, operation)) return false;
} else if (key == 5) {
if (!web_auth_parse_json_string(body, length, &pos, operation->password,
sizeof(operation->password), &operation->password_length) ||
!user_database_password_valid(operation->password, operation->password_length)) return false;
} else {
TAKE('"'); start = pos;
while (pos < length && body[pos] != '"') {
if (body[pos] < ' ' || body[pos] > '~' || body[pos] == '\\' || pos - start >= sizeof(value) - 1) return false;
++pos;
}
if (pos == length) return false;
memcpy(value, body + start, pos - start); ++pos;
}
switch (key) {
case 0:
{
unsigned action = 0;
for (; action < sizeof(s_actions) / sizeof(*s_actions); ++action)
if (!strcmp(value, s_actions[action])) break;
if (action == sizeof(s_actions) / sizeof(*s_actions)) return false;
operation->action = (account_action_t)action;
}
break;
case 1:
if (!user_database_username_valid((const uint8_t *)value, strlen(value))) return false;
memcpy(operation->target.username, value, sizeof(value)); break;
case 2: operation->target.user_id = number; break;
case 3: operation->target.auth_generation = number; break;
case 4: if (!user_role_parse(value, &operation->role)) return false; break;
case 7: operation->key_index = (uint8_t)number; break;
}
seen |= 1U << key;
SPACE();
if (pos < length && body[pos] == '}') break;
}
TAKE('}'); SPACE();
#undef TAKE
#undef SPACE
const unsigned schemas[] = {31U, 15U, 51U, 47U, 79U, 143U, 15U};
return pos == length && seen == (keys_only ? 14U : schemas[operation->action]);
}
static bool parse(const char *body, size_t length, account_operation_t *operation)
{
return parse_request(body, length, operation, false);
}
void web_account_settings_execute(uint32_t id)
{
account_operation_t operation = {0};
taskENTER_CRITICAL(&s_lock);
bool admitted = id && s_operation.id == id && s_operation.state == PENDING && !s_operation.executing;
if (admitted) {
s_operation.executing = true;
operation = s_operation;
wipe_input(&s_operation);
}
taskEXIT_CRITICAL(&s_lock);
if (!admitted) return;
bool current = false;
esp_err_t error = web_session_store_check_principal(operation.session, &operation.principal, &current);
unsigned state = CANCELLED;
if (error == ESP_OK && current && operation.principal.role == USER_ROLE_ADMIN &&
esp_timer_get_time() < operation.deadline) {
/* CLI and typed mutations share this dispatcher. Target identity is also
* compared under the database mutation lock, not just at HTTP admission. */
switch (operation.action) {
case ACTION_ROLE: error = user_database_set_role_current(&operation.target, operation.role); break;
case ACTION_DELETE: error = user_database_delete_current(&operation.target); break;
case ACTION_CREATE:
error = user_database_create((const uint8_t *)operation.target.username,
strlen(operation.target.username), operation.role, operation.password, operation.password_length);
break;
case ACTION_KEY_ADD:
error = user_database_add_ssh_key_current(&operation.target,
(const uint8_t *)operation.key_type, strlen(operation.key_type),
operation.key_blob, operation.key_blob_length, &operation.key_index);
break;
case ACTION_KEY_DELETE:
error = user_database_remove_ssh_key_current(&operation.target, operation.key_index);
break;
case ACTION_KEY_CLEAR:
error = user_database_clear_ssh_keys_current(&operation.target);
break;
case ACTION_PASSWORD:
error = user_database_set_password_current(&operation.target, operation.password, operation.password_length);
break;
}
secure_wipe(operation.password, sizeof(operation.password));
operation.password_length = 0;
state = error == ESP_OK ? OK : error == ESP_ERR_NOT_FOUND ? STALE :
error == ESP_ERR_INVALID_STATE ? (operation.action == ACTION_CREATE ? DUPLICATE :
operation.action <= ACTION_PASSWORD ? PROTECTED : FAILED) :
error == USER_DATABASE_ERR_DUPLICATE_SSH_KEY && operation.action == ACTION_KEY_ADD ? DUPLICATE :
error == ESP_ERR_NO_MEM && (operation.action == ACTION_CREATE || operation.action == ACTION_KEY_ADD) ? FULL : FAILED;
if (error == ESP_OK && operation.action != ACTION_CREATE) {
size_t length = strlen(operation.target.username);
(void)web_serial_transport_revoke_user((const uint8_t *)operation.target.username, length);
(void)ssh_transport_revoke_user((const uint8_t *)operation.target.username, length);
}
}
secure_wipe(operation.password, sizeof(operation.password));
operation.password_length = 0;
taskENTER_CRITICAL(&s_lock);
if (s_operation.id == id && s_operation.state == PENDING && s_operation.executing) {
s_operation.state = state;
s_operation.executing = false;
wipe_input(&s_operation);
}
taskEXIT_CRITICAL(&s_lock);
secure_wipe(&operation, sizeof(operation));
}
static esp_err_t respond(httpd_req_t *request, const char *status, const char *body)
{
esp_err_t error = httpd_resp_set_status(request, status);
if (error == ESP_OK) error = httpd_resp_set_type(request, "application/json; charset=utf-8");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "Cache-Control", "no-store");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "X-Content-Type-Options", "nosniff");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "Referrer-Policy", "no-referrer");
if (error == ESP_OK) error = httpd_resp_sendstr(request, body);
return web_httpd_unread_body(request) ? ESP_FAIL : error;
}
static esp_err_t list_accounts(httpd_req_t *request)
{
user_database_accounts_t accounts;
if (user_database_get_accounts(&accounts) != ESP_OK)
return respond(request, "503 Service Unavailable", "{\"error\":\"accounts_unavailable\"}");
char body[1024];
size_t used = (size_t)snprintf(body, sizeof(body), "{\"users\":[");
for (size_t i = 0; i < accounts.count; ++i) {
const user_database_account_t *user = &accounts.users[i];
/* Database username policy makes these ASCII strings JSON-safe. */
int written = snprintf(body + used, sizeof(body) - used,
"%s{\"username\":\"%s\",\"user_id\":%" PRIu32 ",\"auth_generation\":%" PRIu32 ",\"role\":\"%s\"}",
i ? "," : "", user->username, user->user_id, user->auth_generation, user_role_to_string(user->role));
if (written < 0 || (size_t)written >= sizeof(body) - used) return ESP_FAIL;
used += (size_t)written;
}
if (used + 3 > sizeof(body)) return ESP_FAIL;
memcpy(body + used, "]}", 3);
return respond(request, "200 OK", body);
}
static bool read_request(httpd_req_t *request, account_operation_t *operation, bool keys_only)
{
char type[40] = {0}, body[768];
size_t received = 0;
bool valid = request->content_len && request->content_len <= sizeof(body) &&
httpd_req_get_hdr_value_str(request, "Content-Type", type, sizeof(type)) == ESP_OK &&
(!strcmp(type, "application/json") || !strcmp(type, "application/json; charset=utf-8"));
for (unsigned reads = 0; valid && received < request->content_len && reads < 4; ++reads) {
int count = httpd_req_recv(request, body + received, request->content_len - received);
if (count <= 0 || (size_t)count > request->content_len - received) valid = false;
else received += (size_t)count;
}
valid = valid && received == request->content_len &&
(keys_only ? parse_request(body, received, operation, true) : parse(body, received, operation));
secure_wipe(body, sizeof(body));
return valid;
}
esp_err_t web_account_keys_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
account_operation_t operation = {0};
user_database_user_snapshot_t snapshot = {0};
bool allowed = false;
esp_err_t error = web_cookie_auth_require_json(request, 768, &view, &allowed);
if (error != ESP_OK || !allowed) goto done;
if (view.principal.role != USER_ROLE_ADMIN) {
error = respond(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto done;
}
if (strcmp(request->uri, "/api/settings/accounts/keys") || !read_request(request, &operation, true)) {
error = respond(request, "400 Bad Request", "{\"error\":\"invalid_account_request\"}");
goto done;
}
error = user_database_get_account_keys(&operation.target, &snapshot);
if (error != ESP_OK) {
error = error == ESP_ERR_NOT_FOUND ? respond(request, "409 Conflict", "{\"error\":\"stale\"}") :
respond(request, "503 Service Unavailable", "{\"error\":\"accounts_unavailable\"}");
goto done;
}
char body[512];
int written = snprintf(body, sizeof(body),
"{\"username\":\"%s\",\"user_id\":%" PRIu32 ",\"auth_generation\":%" PRIu32 ",\"keys\":[",
snapshot.username, snapshot.user_id, snapshot.auth_generation);
if (written < 0 || (size_t)written >= sizeof(body)) { error = ESP_FAIL; goto done; }
size_t used = (size_t)written;
bool comma = false;
for (size_t i = 0; i < USER_DATABASE_MAX_SSH_KEYS_PER_USER; ++i) {
const user_database_key_snapshot_t *key = &snapshot.public_keys[i];
if (!key->active) continue;
unsigned char fingerprint[45];
size_t length = 0;
if (mbedtls_base64_encode(fingerprint, sizeof(fingerprint), &length,
key->sha256_fingerprint, sizeof(key->sha256_fingerprint)) != 0 || length != 44) {
error = ESP_FAIL; goto done;
}
fingerprint[43] = 0; /* OpenSSH SHA256 fingerprints omit base64 padding. */
written = snprintf(body + used, sizeof(body) - used,
"%s{\"index\":%u,\"type\":\"%s\",\"fingerprint\":\"SHA256:%s\"}",
comma ? "," : "", key->index, key->key_type, (const char *)fingerprint);
if (written < 0 || (size_t)written >= sizeof(body) - used) { error = ESP_FAIL; goto done; }
used += (size_t)written;
comma = true;
}
if (used + 3 > sizeof(body)) { error = ESP_FAIL; goto done; }
memcpy(body + used, "]}", 3);
error = respond(request, "200 OK", body);
done:
secure_wipe(&operation, sizeof(operation));
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
esp_err_t web_account_generate_password_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
user_database_generated_password_t generated = {0};
char response[96] = {0};
bool allowed = false;
esp_err_t error = web_cookie_auth_require(request, true, false, &view, &allowed);
if (error != ESP_OK || !allowed) goto done;
if (view.principal.role != USER_ROLE_ADMIN) {
error = respond(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto done;
}
error = user_database_generate_password_value(&generated);
if (error != ESP_OK) {
secure_wipe(&generated, sizeof(generated));
error = respond(request, "503 Service Unavailable", "{\"error\":\"unavailable\"}");
goto done;
}
bool current = false;
error = web_session_store_check_principal(view.id, &view.principal, &current);
if (error != ESP_OK || !current) {
secure_wipe(&generated, sizeof(generated));
error = respond(request, "401 Unauthorized", "{\"error\":\"authentication_required\"}");
goto done;
}
int written = snprintf(response, sizeof(response), "{\"password\":\"%s\"}", (const char *)generated.password);
secure_wipe(&generated, sizeof(generated));
error = written < 0 || (size_t)written >= sizeof(response) ? ESP_FAIL : respond(request, "200 OK", response);
done:
secure_wipe(&generated, sizeof(generated));
secure_wipe(response, sizeof(response));
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
esp_err_t web_account_settings_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
account_operation_t operation = {0};
bool allowed = false, mutation = request->method == HTTP_POST;
esp_err_t error = mutation ? web_cookie_auth_require_json(request, 768, &view, &allowed) :
web_cookie_auth_require(request, false, false, &view, &allowed);
if (error != ESP_OK || !allowed) goto done;
if (view.principal.role != USER_ROLE_ADMIN) {
error = respond(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto done;
}
if (!strcmp(request->uri, "/api/settings/accounts")) {
error = mutation ? respond(request, "400 Bad Request", "{\"error\":\"invalid_request\"}") : list_accounts(request);
goto done;
}
if (mutation) {
if (!read_request(request, &operation, false)) {
wipe_input(&operation);
error = respond(request, "400 Bad Request", "{\"error\":\"invalid_account_request\"}");
goto done;
}
if (credential_action(operation.action) && !ensure_secret_timer()) {
wipe_input(&operation);
error = respond(request, "503 Service Unavailable", "{\"error\":\"unavailable\"}");
goto done;
}
operation.session = view.id;
operation.principal = view.principal;
operation.deadline = esp_timer_get_time() + 30000000LL;
operation.state = PENDING;
taskENTER_CRITICAL(&s_lock);
bool busy = s_operation.state == PENDING || s_next_id == UINT32_MAX;
if (!busy) { operation.id = ++s_next_id; s_operation = operation; }
taskEXIT_CRITICAL(&s_lock);
if (busy || admin_ssh_console_submit_account_settings(operation.id) != ESP_OK) {
taskENTER_CRITICAL(&s_lock);
if (!busy && s_operation.id == operation.id && !s_operation.executing)
secure_wipe(&s_operation, sizeof(s_operation));
taskEXIT_CRITICAL(&s_lock);
wipe_input(&operation);
error = httpd_resp_set_hdr(request, "Retry-After", "1");
if (error == ESP_OK) error = respond(request, "503 Service Unavailable", "{\"error\":\"busy\"}");
goto done;
}
} else {
taskENTER_CRITICAL(&s_lock);
if (s_operation.session == view.id) {
operation.id = s_operation.id;
operation.action = s_operation.action;
operation.state = s_operation.state;
}
taskEXIT_CRITICAL(&s_lock);
}
wipe_input(&operation);
char response[96];
int written = snprintf(response, sizeof(response), "{\"id\":%" PRIu32 ",\"action\":\"%s\",\"state\":\"%s\"}",
operation.id, operation.id ? s_actions[operation.action] : "none", s_states[operation.state]);
error = written < 0 || (size_t)written >= sizeof(response) ? ESP_FAIL :
respond(request, mutation ? "202 Accepted" : "200 OK", response);
done:
secure_wipe(&operation, sizeof(operation));
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
+27
View File
@@ -0,0 +1,27 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include <stdint.h>
#include "esp_http_server.h"
/* One session-bound pending/result slot. Dispatcher execution only; completed
* results are replaceable, not durable history or an idempotent retry API. */
esp_err_t web_account_settings_handler(httpd_req_t *request);
void web_account_settings_execute(uint32_t id);
/* POST /api/settings/accounts/keys: admin cookie + Origin/CSRF, JSON exactly
* {username,user_id,auth_generation}. Read-only zero-wait snapshot, 512-byte
* response bound: {username,user_id,auth_generation,keys:[{index,type,fingerprint}]}.
* Fingerprints are OpenSSH SHA256: base64 without padding, never key blobs.
* Stale/absent target: 409 {error:"stale"}; busy DB: 503 accounts_unavailable.
* Register independently as an optional POST route.
*
* Existing account-operation POST adds key-add (+public_key, OpenSSH text <=384
* decoded bytes), key-delete (+key_index integer 0..2), key-clear. All require
* username/user_id/auth_generation. Exact schemas, <=768 body bytes/4 receives.
* Text/base64 errors: 400; canonical SSH blob/curve validation runs on dispatcher
* (failed result). Duplicate/full/stale use existing named result states.
* Success target-revokes immediately, including self; lost response/401 remains
* uncertain, never proof of cancellation. No automatic mutation retries. */
esp_err_t web_account_keys_handler(httpd_req_t *request);
/* POST /api/settings/accounts/generate-password; bodyless admin cookie +
* Origin/CSRF. RNG only, no queued/account/persistent state or retrieval. */
esp_err_t web_account_generate_password_handler(httpd_req_t *request);
+300
View File
@@ -0,0 +1,300 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "web_admin_tickets.h"
#include <limits.h>
#include <string.h>
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "mbedtls/sha256.h"
#include "secure_random.h"
typedef struct {
uint64_t generation;
web_session_id_t id;
int64_t expires_at_us;
user_principal_t principal;
uint8_t digest[32];
} ticket_t;
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static struct {
ticket_t tickets[WEB_ADMIN_TICKET_CAPACITY];
uint64_t epoch;
uint64_t generation;
uint32_t issued, consumed, rejected, capacity_rejections;
bool ready;
} s_state;
static void increment(uint32_t *counter)
{
if (*counter != UINT32_MAX) ++*counter;
}
static bool equal_digest(const uint8_t *a, const uint8_t *b)
{
volatile uint8_t difference = 0;
for (size_t i = 0; i < 32; ++i) difference |= a[i] ^ b[i];
return difference == 0;
}
static bool admin(const user_principal_t *p)
{
return p != NULL && p->role == USER_ROLE_ADMIN &&
p->method == USER_AUTH_METHOD_PASSWORD && p->user_id != 0 &&
p->auth_generation != 0 && p->username_length != 0 &&
p->username_length <= USER_DATABASE_USERNAME_CAPACITY;
}
static bool same_principal(const user_principal_t *a, const user_principal_t *b)
{
return admin(b) && a->user_id == b->user_id &&
a->auth_generation == b->auth_generation && a->role == b->role &&
a->method == b->method && a->username_length == b->username_length &&
memcmp(a->username, b->username, a->username_length) == 0;
}
static bool current(web_session_id_t id, const user_principal_t *p)
{
bool valid = false;
return id != 0 && admin(p) &&
web_session_store_check_principal(id, p, &valid) == ESP_OK && valid;
}
static void expire_locked(int64_t now)
{
for (size_t i = 0; i < WEB_ADMIN_TICKET_CAPACITY; ++i) {
ticket_t *t = &s_state.tickets[i];
if (t->generation && t->expires_at_us <= now) secure_wipe(t, sizeof(*t));
}
}
/* Fixed two-slot walk. Generation prevents an external check from deleting a
* replacement, including when RNG returns the same bytes on a later issue. */
static void prune(void)
{
for (size_t i = 0; i < WEB_ADMIN_TICKET_CAPACITY; ++i) {
ticket_t copy = {0};
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
expire_locked(now);
copy = s_state.tickets[i];
taskEXIT_CRITICAL(&s_lock);
if (copy.generation && !current(copy.id, &copy.principal)) {
taskENTER_CRITICAL(&s_lock);
if (s_state.tickets[i].generation == copy.generation)
secure_wipe(&s_state.tickets[i], sizeof(ticket_t));
taskEXIT_CRITICAL(&s_lock);
}
secure_wipe(&copy, sizeof(copy));
}
}
static void advance_epoch_locked(void)
{
if (s_state.epoch != UINT64_MAX) ++s_state.epoch;
if (s_state.epoch == UINT64_MAX) {
s_state.ready = false;
secure_wipe(s_state.tickets, sizeof(s_state.tickets));
}
}
void web_admin_tickets_start(void)
{
taskENTER_CRITICAL(&s_lock);
if (!s_state.ready && s_state.epoch != UINT64_MAX &&
s_state.generation != UINT64_MAX) {
advance_epoch_locked();
s_state.ready = s_state.epoch != UINT64_MAX;
}
taskEXIT_CRITICAL(&s_lock);
}
void web_admin_tickets_stop(void)
{
taskENTER_CRITICAL(&s_lock);
advance_epoch_locked();
s_state.ready = false;
secure_wipe(s_state.tickets, sizeof(s_state.tickets));
taskEXIT_CRITICAL(&s_lock);
}
static bool capture_epoch(uint64_t *epoch)
{
taskENTER_CRITICAL(&s_lock);
*epoch = s_state.epoch;
bool ready = s_state.ready;
taskEXIT_CRITICAL(&s_lock);
return ready;
}
static esp_err_t result(esp_err_t error)
{
if (error != ESP_OK) {
taskENTER_CRITICAL(&s_lock);
increment(&s_state.rejected);
taskEXIT_CRITICAL(&s_lock);
}
return error;
}
esp_err_t web_admin_tickets_issue(web_session_id_t id,
const user_principal_t *principal, char token[WEB_ADMIN_TICKET_LENGTH + 1U])
{
ticket_t candidate = {0};
uint8_t random[32] = {0};
uint64_t epoch = 0;
esp_err_t error = ESP_ERR_INVALID_ARG;
if (token == NULL) return result(error);
secure_wipe(token, WEB_ADMIN_TICKET_LENGTH + 1U);
if (id == 0 || principal == NULL) goto done;
error = ESP_ERR_INVALID_STATE;
if (!capture_epoch(&epoch) || !current(id, principal)) goto done;
candidate.id = id;
candidate.principal = *principal;
prune();
if (!current(id, &candidate.principal)) goto done;
error = secure_random_fill(random, sizeof(random));
/* Recheck even when crypto fails; never use an old authorization result. */
bool valid = current(id, &candidate.principal);
if (error != ESP_OK) goto done;
error = ESP_ERR_INVALID_STATE;
if (!valid) goto done;
static const char hex[] = "0123456789abcdef";
for (size_t i = 0; i < sizeof(random); ++i) {
token[2 * i] = hex[random[i] >> 4];
token[2 * i + 1] = hex[random[i] & 15];
}
int crypto = mbedtls_sha256(random, sizeof(random), candidate.digest, 0);
valid = current(id, &candidate.principal);
error = crypto == 0 ? ESP_ERR_INVALID_STATE : ESP_FAIL;
if (crypto != 0 || !valid) goto done;
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
expire_locked(now);
if (s_state.ready && epoch == s_state.epoch && now >= 0 &&
now <= INT64_MAX - WEB_ADMIN_TICKET_LIFETIME_US &&
s_state.generation != UINT64_MAX) {
ticket_t *free_slot = NULL;
bool duplicate = false;
for (size_t i = 0; i < WEB_ADMIN_TICKET_CAPACITY; ++i) {
ticket_t *t = &s_state.tickets[i];
if (!t->generation) free_slot = t;
else if (equal_digest(t->digest, candidate.digest)) duplicate = true;
}
if (duplicate) error = ESP_FAIL;
else if (free_slot == NULL) {
increment(&s_state.capacity_rejections);
error = ESP_ERR_NO_MEM;
} else {
candidate.generation = ++s_state.generation;
candidate.expires_at_us = now + WEB_ADMIN_TICKET_LIFETIME_US;
*free_slot = candidate;
increment(&s_state.issued);
error = ESP_OK;
}
}
taskEXIT_CRITICAL(&s_lock);
done:
secure_wipe(random, sizeof(random));
secure_wipe(&candidate, sizeof(candidate));
if (error != ESP_OK) secure_wipe(token, WEB_ADMIN_TICKET_LENGTH + 1U);
return result(error);
}
static int unhex(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
esp_err_t web_admin_tickets_consume(const char *token, web_session_id_t id,
const user_principal_t *principal)
{
uint8_t bytes[32] = {0}, digest[32] = {0};
ticket_t found = {0};
uint64_t epoch = 0;
esp_err_t error = ESP_ERR_INVALID_ARG;
if (token == NULL) goto done;
for (size_t i = 0; i < WEB_ADMIN_TICKET_LENGTH; ++i) {
int n = unhex(token[i]);
if (n < 0) goto done;
bytes[i / 2] |= (uint8_t)(n << ((i % 2 == 0) ? 4 : 0));
}
if (token[WEB_ADMIN_TICKET_LENGTH] != '\0') goto done;
error = ESP_ERR_INVALID_STATE;
if (!capture_epoch(&epoch)) goto done;
bool before = current(id, principal);
if (mbedtls_sha256(bytes, sizeof(bytes), digest, 0) != 0) {
(void)current(id, principal);
error = ESP_FAIL;
goto done;
}
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
expire_locked(now);
if (s_state.ready && epoch == s_state.epoch) {
error = ESP_ERR_NOT_FOUND;
for (size_t i = 0; i < WEB_ADMIN_TICKET_CAPACITY; ++i) {
ticket_t *t = &s_state.tickets[i];
if (t->generation && equal_digest(t->digest, digest)) {
found = *t;
secure_wipe(t, sizeof(*t));
increment(&s_state.consumed);
break;
}
}
}
taskEXIT_CRITICAL(&s_lock);
/* Burn precedes acting on either currentness result or identity binding. */
bool after = current(id, principal);
if (found.generation) {
now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
error = before && after && found.id == id &&
same_principal(&found.principal, principal) && s_state.ready &&
epoch == s_state.epoch && now < found.expires_at_us ?
ESP_OK : ESP_ERR_INVALID_STATE;
taskEXIT_CRITICAL(&s_lock);
}
done:
secure_wipe(bytes, sizeof(bytes));
secure_wipe(digest, sizeof(digest));
secure_wipe(&found, sizeof(found));
return result(error);
}
void web_admin_tickets_revoke(web_session_id_t id, const uint8_t *username,
size_t length)
{
taskENTER_CRITICAL(&s_lock);
advance_epoch_locked();
for (size_t i = 0; i < WEB_ADMIN_TICKET_CAPACITY; ++i) {
ticket_t *t = &s_state.tickets[i];
bool match = id != 0 ? t->id == id : username == NULL ||
(length == t->principal.username_length &&
length <= USER_DATABASE_USERNAME_CAPACITY &&
memcmp(username, t->principal.username, length) == 0);
if (match) secure_wipe(t, sizeof(*t));
}
taskEXIT_CRITICAL(&s_lock);
}
void web_admin_tickets_get_snapshot(web_admin_tickets_snapshot_t *snapshot)
{
if (snapshot == NULL) return;
prune();
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
expire_locked(now);
*snapshot = (web_admin_tickets_snapshot_t) {
.issued = s_state.issued, .consumed = s_state.consumed,
.rejected = s_state.rejected,
.capacity_rejections = s_state.capacity_rejections,
.storage_bytes = sizeof(s_state) + sizeof(s_lock), .ready = s_state.ready,
};
for (size_t i = 0; i < WEB_ADMIN_TICKET_CAPACITY; ++i)
if (s_state.tickets[i].generation) ++snapshot->active;
taskEXIT_CRITICAL(&s_lock);
}
+44
View File
@@ -0,0 +1,44 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include "web_session_store.h"
#define WEB_ADMIN_TICKET_LENGTH 64U
#define WEB_ADMIN_TICKET_CAPACITY 2U
#define WEB_ADMIN_TICKET_LIFETIME_US 30000000LL
typedef struct {
uint32_t issued;
uint32_t consumed;
uint32_t rejected;
uint32_t capacity_rejections;
uint32_t active;
size_t storage_bytes;
bool ready;
} web_admin_tickets_snapshot_t;
/* Trusted internal API, not HTTP authorization. Start is idempotent while ready;
* stop wipes records. Neither lifecycle operation resets epochs or counters.
* RNG must already be initialized. Exhausted generations fail closed. */
void web_admin_tickets_start(void);
void web_admin_tickets_stop(void);
/* Only current password-authenticated administrators. No live eviction.
* Output must not alias inputs; all 65 bytes are wiped on failure.
* NO_MEM: capacity; INVALID_ARG: malformed input; INVALID_STATE: stopped,
* stale, unauthorized or raced; FAIL: SHA failure; RNG errors propagate. */
esp_err_t web_admin_tickets_issue(web_session_id_t id,
const user_principal_t *principal, char token[WEB_ADMIN_TICKET_LENGTH + 1U]);
/* Exact hex string (either case). Matching tickets are burned even for wrong
* session/principal or failed currentness. NOT_FOUND means no live match.
* Crypto failure cannot identify/burn a ticket. Success is not a session lease. */
esp_err_t web_admin_tickets_consume(const char *token, web_session_id_t id,
const user_principal_t *principal);
/* Caller invalidates sessions FIRST. Nonzero ID takes precedence; otherwise
* non-NULL username matches exact bytes/length; otherwise revoke all.
* Every call cancels in-flight work, even when no record matches. */
void web_admin_tickets_revoke(web_session_id_t id, const uint8_t *username,
size_t length);
/* Saturating lifetime counters; consumed counts burned matches, not admissions.
* rejected counts failed issue/consume (including capacity). Snapshot prunes
* expired/stale records; storage_bytes includes state and lock, no secrets. */
void web_admin_tickets_get_snapshot(web_admin_tickets_snapshot_t *snapshot);
+606
View File
@@ -0,0 +1,606 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* One optional admin socket. HTTPD owns IO; the canonical dispatcher owns commands. */
#include "web_admin_transport.h"
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include "admin_ssh_console.h"
#include "esp_heap_caps.h"
#include "esp_timer.h"
#include "esp_system.h"
#include "web_server.h"
#include "web_security.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "secure_random.h"
#include "web_admin_tickets.h"
#include "web_cookie_auth.h"
#include "web_httpd_adapter.h"
#define ADMIN_POLL_US 20000ULL
#define ADMIN_INPUT_TIMEOUT_US 5000000LL
#define ADMIN_DETACH_TIMEOUT_US 2000000LL
typedef struct {
uint8_t rx[WEB_ADMIN_RX_CAPACITY];
uint8_t tx[WEB_ADMIN_TX_CAPACITY];
size_t rx_length, rx_offset;
int64_t input_deadline;
} admin_payload_t;
typedef struct {
bool occupied, active, console_open, close_requested, close_triggered, sending;
int fd;
web_session_id_t session;
user_principal_t principal;
admin_ssh_console_token_t token;
} admin_slot_t;
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static admin_slot_t s_slot;
static admin_payload_t *s_payload; /* PSRAM; touched only by HTTPD while attached. */
static esp_timer_handle_t s_timer;
static httpd_handle_t s_server;
static bool s_initialized, s_accepting, s_queued;
static unsigned s_submitting;
static uint32_t s_generation; /* Never wrap/reuse within a boot. */
static web_admin_transport_snapshot_t s_counts;
static void count(uint32_t *value, uint32_t amount)
{
taskENTER_CRITICAL(&s_lock);
*value = UINT32_MAX - *value < amount ? UINT32_MAX : *value + amount;
taskEXIT_CRITICAL(&s_lock);
}
static bool token_matches(const admin_ssh_console_token_t *token)
{
return token && s_slot.occupied && s_slot.console_open &&
token->transport == ADMIN_CONSOLE_TRANSPORT_WEB &&
token->session_id == s_slot.token.session_id &&
token->slot_generation == s_slot.token.slot_generation &&
token->slot_index == s_slot.token.slot_index;
}
static bool owner_current(const admin_ssh_console_token_t *token,
const user_principal_t *principal)
{
taskENTER_CRITICAL(&s_lock);
bool valid = token_matches(token) && s_accepting && s_slot.active && !s_slot.close_requested;
web_session_id_t id = valid ? s_slot.session : 0;
taskEXIT_CRITICAL(&s_lock);
bool current = false;
if (!valid || !principal || principal->role != USER_ROLE_ADMIN ||
web_session_store_check_principal(id, principal, &current) != ESP_OK || !current)
return false;
taskENTER_CRITICAL(&s_lock);
valid = token_matches(token) && s_accepting && s_slot.active &&
!s_slot.close_requested && s_slot.session == id;
taskEXIT_CRITICAL(&s_lock);
return valid;
}
static bool owner_drained(const admin_ssh_console_token_t *token)
{
taskENTER_CRITICAL(&s_lock);
bool drained = token_matches(token) && s_slot.active &&
!s_slot.close_requested && !s_slot.sending;
taskEXIT_CRITICAL(&s_lock);
return drained;
}
static esp_err_t owner_perform(const admin_ssh_console_token_t *token,
admin_ssh_deferred_action_type_t action, uint32_t argument)
{
(void)argument;
if (action != ADMIN_CONSOLE_DEFER_SELF_CLOSE && action != ADMIN_SSH_DEFER_REBOOT &&
action != ADMIN_CONSOLE_DEFER_WEB_STOP &&
action != ADMIN_CONSOLE_DEFER_WEB_CERTIFICATE_ROTATE) return ESP_ERR_NOT_SUPPORTED;
/* Drain is only a delivery heuristic, not an authorization lease. The
* execution task must recheck cookie/account binding after delay/queueing. */
taskENTER_CRITICAL(&s_lock);
user_principal_t principal = s_slot.principal;
taskEXIT_CRITICAL(&s_lock);
bool current = owner_current(token, &principal);
secure_wipe(&principal, sizeof(principal));
if (!current) return ESP_ERR_NOT_FOUND;
if (action == ADMIN_CONSOLE_DEFER_WEB_CERTIFICATE_ROTATE) {
/* The owner mask routes this crypto/NVS path to the 12KiB dispatcher.
* Commit before restart; a failed stop retains HTTPD ownership and must
* not be followed by start. No socket IO or console handler calls here. */
bool committed = false;
return web_server_replace_identity(0, 0, false, &committed);
}
if (action == ADMIN_CONSOLE_DEFER_WEB_STOP) return web_server_stop();
if (action == ADMIN_SSH_DEFER_REBOOT) {
esp_restart();
return ESP_OK;
}
taskENTER_CRITICAL(&s_lock);
bool valid = token_matches(token) && s_slot.active && s_accepting && !s_slot.close_requested;
if (valid) s_slot.close_requested = true;
taskEXIT_CRITICAL(&s_lock);
if (valid) admin_ssh_console_close(token);
return valid ? ESP_OK : ESP_ERR_NOT_FOUND;
}
static const admin_console_owner_t s_owner = {
.supported_actions = (1U << ADMIN_CONSOLE_DEFER_SELF_CLOSE) |
(1U << ADMIN_SSH_DEFER_REBOOT) | (1U << ADMIN_CONSOLE_DEFER_WEB_STOP) |
(1U << ADMIN_CONSOLE_DEFER_WEB_CERTIFICATE_ROTATE),
.dispatcher_actions = 1U << ADMIN_CONSOLE_DEFER_WEB_CERTIFICATE_ROTATE,
.is_current = owner_current, .drained = owner_drained, .perform = owner_perform,
};
/* No IO and no payload mutation: safe on console/revocation/lifecycle callers. */
static void request_close(void)
{
taskENTER_CRITICAL(&s_lock);
bool opened = s_slot.console_open;
admin_ssh_console_token_t token = s_slot.token;
if (s_slot.occupied) s_slot.close_requested = true;
taskEXIT_CRITICAL(&s_lock);
if (opened) admin_ssh_console_close(&token);
}
/* HTTPD callback, or lifecycle caller ONLY after HTTPD has successfully stopped. */
static void session_free(void *context)
{
if (context != &s_slot) return;
taskENTER_CRITICAL(&s_lock);
bool occupied = s_slot.occupied;
bool opened = s_slot.console_open;
bool active = s_slot.active;
admin_ssh_console_token_t token = s_slot.token;
secure_wipe(&s_slot, sizeof(s_slot));
taskEXIT_CRITICAL(&s_lock);
if (opened) admin_ssh_console_close(&token);
if (occupied && s_payload) secure_wipe(s_payload, sizeof(*s_payload));
if (active) count(&s_counts.disconnections, 1);
}
static bool capture(admin_ssh_console_token_t *token, user_principal_t *principal, int *fd)
{
taskENTER_CRITICAL(&s_lock);
bool active = s_slot.active;
*token = s_slot.token;
*principal = s_slot.principal;
*fd = s_slot.fd;
taskEXIT_CRITICAL(&s_lock);
return active;
}
static bool input_current(const admin_ssh_console_token_t *token,
const user_principal_t *principal)
{
if (owner_current(token, principal)) return true;
count(&s_counts.authorization_rejections, 1);
request_close();
return false;
}
static void discard_pending_input(void)
{
secure_wipe(s_payload->rx, sizeof(s_payload->rx));
s_payload->rx_offset = s_payload->rx_length = 0;
s_payload->input_deadline = 0;
count(&s_counts.input_backpressure, 1);
}
static bool feed_pending(const admin_ssh_console_token_t *token,
const user_principal_t *principal)
{
if (s_payload->rx_offset == s_payload->rx_length) return true;
if (!input_current(token, principal)) return false;
admin_ssh_console_session_snapshot_t console;
if (admin_ssh_console_get_session_snapshot(token, &console) != ESP_OK || !console.active) {
request_close();
return false;
}
if (console.deferred_action_pending) {
/* Never replay buffered keystrokes if a deferred action fails/cancels. */
discard_pending_input();
return true;
}
if (esp_timer_get_time() >= s_payload->input_deadline) {
count(&s_counts.input_backpressure, 1);
request_close();
return false;
}
size_t consumed = 0;
(void)admin_ssh_console_feed_input(token, s_payload->rx + s_payload->rx_offset,
s_payload->rx_length - s_payload->rx_offset, &consumed);
secure_wipe(s_payload->rx + s_payload->rx_offset, consumed);
s_payload->rx_offset += consumed;
if (s_payload->rx_offset == s_payload->rx_length) {
s_payload->rx_offset = s_payload->rx_length = 0;
s_payload->input_deadline = 0;
}
return true;
}
/* Only this HTTPD work callback sends console output or requests idle closure. */
static void poll_work(void *argument)
{
httpd_handle_t server = argument;
admin_ssh_console_token_t token;
user_principal_t principal;
int fd;
bool active = capture(&token, &principal, &fd);
taskENTER_CRITICAL(&s_lock);
bool attached = s_accepting && server == s_server;
taskEXIT_CRITICAL(&s_lock);
if (!active || !attached) goto done;
if (!input_current(&token, &principal)) goto closing;
if (httpd_sess_get_ctx(server, fd) != &s_slot ||
httpd_ws_get_fd_info(server, fd) != HTTPD_WS_CLIENT_WEBSOCKET) {
request_close();
goto closing;
}
admin_ssh_console_session_snapshot_t console;
if (admin_ssh_console_get_session_snapshot(&token, &console) != ESP_OK || !console.active) {
request_close();
goto closing;
}
if (!feed_pending(&token, &principal)) goto closing;
taskENTER_CRITICAL(&s_lock);
s_slot.sending = true; /* Covers the gap between ring consumption and socket send. */
taskEXIT_CRITICAL(&s_lock);
size_t length = 0;
esp_err_t error = admin_ssh_console_read_output(&token, s_payload->tx,
sizeof(s_payload->tx), &length);
if (error == ESP_OK && length && input_current(&token, &principal)) {
httpd_ws_frame_t frame = {.final = true, .type = HTTPD_WS_TYPE_BINARY,
.payload = s_payload->tx, .len = length};
error = httpd_ws_send_frame_async(server, fd, &frame);
if (error == ESP_OK) count(&s_counts.tx_bytes, (uint32_t)length);
}
secure_wipe(s_payload->tx, sizeof(s_payload->tx));
taskENTER_CRITICAL(&s_lock);
s_slot.sending = false;
taskEXIT_CRITICAL(&s_lock);
if (error != ESP_OK) {
count(&s_counts.send_failures, 1);
request_close();
}
closing:
taskENTER_CRITICAL(&s_lock);
bool close = s_slot.active && s_slot.close_requested && !s_slot.close_triggered;
taskEXIT_CRITICAL(&s_lock);
if (close && httpd_sess_get_ctx(server, fd) == &s_slot) {
/* IDF's queued close retains a reusable sock_db pointer. Shutdown on
* HTTPD instead: its next read owns deletion, with no late close that
* could evict a replacement (including a serial client). */
if (shutdown(fd, SHUT_RDWR) == 0) {
taskENTER_CRITICAL(&s_lock);
s_slot.close_triggered = true;
taskEXIT_CRITICAL(&s_lock);
} else count(&s_counts.send_failures, 1); /* Retry on the next bounded poll. */
}
done:
secure_wipe(&principal, sizeof(principal));
taskENTER_CRITICAL(&s_lock);
s_queued = false;
taskEXIT_CRITICAL(&s_lock);
}
/* ESP timer task: no database/console/socket calls, no waits, one queue entry max.
* Detach prevents new submissions and fences any submission already outside lock. */
static void poll_timer(void *argument)
{
(void)argument;
taskENTER_CRITICAL(&s_lock);
httpd_handle_t server = NULL;
uint32_t generation = 0;
if (s_accepting && s_slot.active && !s_queued) {
server = s_server;
generation = s_slot.token.slot_generation;
s_queued = true;
++s_submitting;
}
taskEXIT_CRITICAL(&s_lock);
if (!server) return;
esp_err_t error = httpd_queue_work(server, poll_work, server);
taskENTER_CRITICAL(&s_lock);
--s_submitting;
if (error != ESP_OK) {
s_queued = false;
if (s_slot.active && s_slot.token.slot_generation == generation)
s_slot.close_requested = true;
}
taskEXIT_CRITICAL(&s_lock);
if (error != ESP_OK) count(&s_counts.queue_failures, 1);
}
esp_err_t web_admin_transport_init(void)
{
#if defined(CONFIG_HTTPD_QUEUE_WORK_BLOCKING) && CONFIG_HTTPD_QUEUE_WORK_BLOCKING
return ESP_ERR_NOT_SUPPORTED;
#else
if (s_initialized) return ESP_OK; /* Lifecycle caller serializes initialization. */
admin_payload_t *payload = heap_caps_calloc(1, sizeof(*payload), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
esp_err_t error = payload ? ESP_OK : ESP_ERR_NO_MEM;
esp_timer_handle_t timer = NULL;
const esp_timer_create_args_t args = {
.callback = poll_timer, .name = "web_admin", .skip_unhandled_events = true,
};
if (error == ESP_OK) error = esp_timer_create(&args, &timer);
if (error == ESP_OK) error = esp_timer_start_periodic(timer, ADMIN_POLL_US);
if (error != ESP_OK) {
if (timer) (void)esp_timer_delete(timer);
if (payload) heap_caps_free(payload);
}
taskENTER_CRITICAL(&s_lock);
if (error == ESP_OK) {
s_payload = payload;
s_timer = timer;
s_initialized = true;
}
s_counts.last_error = error;
taskEXIT_CRITICAL(&s_lock);
return error;
#endif
}
esp_err_t web_admin_transport_attach(httpd_handle_t server)
{
if (!server) return ESP_ERR_INVALID_ARG;
taskENTER_CRITICAL(&s_lock);
bool allowed = s_initialized && !s_server && !s_queued && !s_submitting && !s_slot.occupied;
taskEXIT_CRITICAL(&s_lock);
if (!allowed) return ESP_ERR_INVALID_STATE;
web_admin_tickets_start();
taskENTER_CRITICAL(&s_lock);
s_server = server;
s_accepting = true;
taskEXIT_CRITICAL(&s_lock);
return ESP_OK;
}
esp_err_t web_admin_transport_detach(httpd_handle_t server)
{
taskENTER_CRITICAL(&s_lock);
bool owned = server && server == s_server;
if (owned) s_accepting = false;
taskEXIT_CRITICAL(&s_lock);
if (!owned) return ESP_ERR_INVALID_STATE;
web_admin_tickets_stop();
request_close();
int64_t deadline = esp_timer_get_time() + ADMIN_DETACH_TIMEOUT_US;
for (;;) {
taskENTER_CRITICAL(&s_lock);
bool submitting = s_submitting != 0;
taskEXIT_CRITICAL(&s_lock);
if (!submitting) return ESP_OK;
if (esp_timer_get_time() >= deadline) return ESP_ERR_TIMEOUT;
vTaskDelay(1);
}
}
void web_admin_transport_stopped(httpd_handle_t server)
{
taskENTER_CRITICAL(&s_lock);
bool owned = server && s_server == server && !s_accepting && !s_submitting;
taskEXIT_CRITICAL(&s_lock);
if (!owned) return;
session_free(&s_slot);
taskENTER_CRITICAL(&s_lock);
s_server = NULL;
s_queued = false; /* HTTPD is gone; its queued callbacks can no longer execute. */
taskEXIT_CRITICAL(&s_lock);
}
void web_admin_transport_revoke(web_session_id_t id, const uint8_t *username, size_t length)
{
web_admin_tickets_revoke(id, username, length);
taskENTER_CRITICAL(&s_lock);
bool match = s_slot.occupied && (id ? s_slot.session == id :
!username || (length == s_slot.principal.username_length &&
length <= USER_DATABASE_USERNAME_CAPACITY &&
memcmp(username, s_slot.principal.username, length) == 0));
admin_ssh_console_token_t token = s_slot.token;
bool opened = match && s_slot.console_open;
if (match) s_slot.close_requested = true;
taskEXIT_CRITICAL(&s_lock);
if (opened) admin_ssh_console_close(&token);
}
static esp_err_t response(httpd_req_t *request, const char *status, const char *body)
{
esp_err_t error = httpd_resp_set_status(request, status);
if (error == ESP_OK) error = httpd_resp_set_type(request, "application/json");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "Cache-Control", "no-store");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "Referrer-Policy", "no-referrer");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "X-Content-Type-Options", "nosniff");
if (error == ESP_OK) error = httpd_resp_sendstr(request, body);
return error;
}
static esp_err_t deny(httpd_req_t *request, const char *status, const char *body)
{
if (!strcmp(status, "503 Service Unavailable") &&
httpd_resp_set_hdr(request, "Retry-After", "5") != ESP_OK) return ESP_FAIL;
(void)response(request, status, body);
return ESP_FAIL; /* Close after rejection, never leave unread frames/body alive. */
}
esp_err_t web_admin_transport_ticket_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
char ticket[WEB_ADMIN_TICKET_LENGTH + 1U] = {0}, body[128] = {0};
bool allowed = false;
esp_err_t error = web_cookie_auth_require(request, true, false, &view, &allowed);
if (error != ESP_OK || !allowed) goto cleanup;
if (view.principal.role != USER_ROLE_ADMIN) {
count(&s_counts.authorization_rejections, 1);
error = deny(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto cleanup;
}
taskENTER_CRITICAL(&s_lock);
bool attached = s_accepting && s_server == request->handle;
taskEXIT_CRITICAL(&s_lock);
error = attached ? web_admin_tickets_issue(view.id, &view.principal, ticket) : ESP_ERR_INVALID_STATE;
if (error != ESP_OK) {
if (error == ESP_ERR_NO_MEM) count(&s_counts.capacity_rejections, 1);
error = deny(request, "503 Service Unavailable", "{\"error\":\"admin_unavailable_or_capacity\"}");
goto cleanup;
}
int n = snprintf(body, sizeof(body), "{\"ticket\":\"%s\",\"expires_in\":30}", ticket);
error = n > 0 && (size_t)n < sizeof(body) ? response(request, "200 OK", body) : ESP_FAIL;
cleanup:
secure_wipe(ticket, sizeof(ticket));
secure_wipe(body, sizeof(body));
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
static esp_err_t frame_handler(httpd_req_t *request)
{
admin_ssh_console_token_t token;
user_principal_t principal;
int fd;
bool active = capture(&token, &principal, &fd);
bool valid = active && request->sess_ctx == &s_slot &&
fd == httpd_req_to_sockfd(request) && input_current(&token, &principal);
if (!valid) goto failure;
httpd_ws_frame_t frame = {0};
if (httpd_ws_recv_frame(request, &frame, 0) != ESP_OK || !frame.final ||
frame.type != HTTPD_WS_TYPE_BINARY || frame.len > WEB_ADMIN_RX_CAPACITY) {
count(&s_counts.protocol_errors, 1);
goto failure;
}
admin_ssh_console_session_snapshot_t console;
if (admin_ssh_console_get_session_snapshot(&token, &console) != ESP_OK || !console.active)
goto failure;
/* Latch before the potentially blocking receive: cancellation during receive
* must not turn input observed during deferral into a new command. */
bool discard_frame = console.deferred_action_pending;
if (s_payload->rx_length != s_payload->rx_offset) {
if (!discard_frame) {
count(&s_counts.input_backpressure, 1);
goto failure;
}
/* Deferral may start before the next poll discards buffered trailing input. */
discard_pending_input();
}
frame.payload = s_payload->rx;
/* IDF treats len==0 as another header probe, not an empty payload read. */
if (frame.len && httpd_ws_recv_frame(request, &frame, sizeof(s_payload->rx)) != ESP_OK)
goto failure;
s_payload->rx_length = frame.len;
s_payload->rx_offset = 0;
s_payload->input_deadline = esp_timer_get_time() + ADMIN_INPUT_TIMEOUT_US;
if (discard_frame) discard_pending_input();
else if (!feed_pending(&token, &principal)) goto failure;
count(&s_counts.rx_bytes, (uint32_t)frame.len);
secure_wipe(&principal, sizeof(principal));
return ESP_OK;
failure:
secure_wipe(&principal, sizeof(principal));
request_close();
return ESP_FAIL;
}
esp_err_t web_admin_transport_upgrade_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
char ticket[WEB_ADMIN_TICKET_LENGTH + 1U] = {0};
admin_ssh_console_token_t token = {0};
bool allowed = false, reserved = false, opened = false;
esp_err_t error = web_cookie_auth_require(request, false, true, &view, &allowed);
if (error != ESP_OK || !allowed) goto cleanup;
if (view.principal.role != USER_ROLE_ADMIN) {
count(&s_counts.authorization_rejections, 1);
error = deny(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto cleanup;
}
static const char prefix[] = WEB_ADMIN_WS_URI "?ticket=";
if (!web_httpd_upgrade_requested(request) ||
strncmp(request->uri, prefix, sizeof(prefix) - 1U) ||
strlen(request->uri) != sizeof(prefix) - 1U + WEB_ADMIN_TICKET_LENGTH) {
error = deny(request, "400 Bad Request", "{\"error\":\"invalid_upgrade\"}");
goto cleanup;
}
memcpy(ticket, request->uri + sizeof(prefix) - 1U, WEB_ADMIN_TICKET_LENGTH);
if (web_admin_tickets_consume(ticket, view.id, &view.principal) != ESP_OK) {
count(&s_counts.authorization_rejections, 1);
error = deny(request, "403 Forbidden", "{\"error\":\"invalid_ticket\"}");
goto cleanup;
}
int socket_fd = httpd_req_to_sockfd(request);
taskENTER_CRITICAL(&s_lock);
if (socket_fd >= 0 && s_accepting && s_server == request->handle &&
!s_slot.occupied && s_generation != UINT32_MAX) {
++s_generation;
token = (admin_ssh_console_token_t){.transport = ADMIN_CONSOLE_TRANSPORT_WEB,
.session_id = s_generation, .slot_generation = s_generation};
s_slot.occupied = true;
s_slot.session = view.id;
s_slot.principal = view.principal;
s_slot.fd = socket_fd;
s_slot.token = token;
reserved = true;
}
taskEXIT_CRITICAL(&s_lock);
if (!reserved) {
count(&s_counts.capacity_rejections, 1);
error = deny(request, "503 Service Unavailable", "{\"error\":\"admin_capacity\"}");
goto cleanup;
}
error = admin_ssh_console_open_available(&token, &view.principal, &s_owner);
if (error != ESP_OK) {
count(&s_counts.capacity_rejections, 1);
error = deny(request, "503 Service Unavailable", "{\"error\":\"console_capacity_or_unavailable\"}");
goto cleanup;
}
opened = true;
bool current = false;
error = web_session_store_check_principal(view.id, &view.principal, &current);
taskENTER_CRITICAL(&s_lock);
s_slot.token = token;
s_slot.console_open = true;
bool admitted = error == ESP_OK && current && s_accepting && !s_slot.close_requested;
taskEXIT_CRITICAL(&s_lock);
if (!admitted) {
error = deny(request, "403 Forbidden", "{\"error\":\"session_revoked\"}");
goto cleanup;
}
error = web_httpd_upgrade(request, frame_handler);
if (error != ESP_OK) goto cleanup;
taskENTER_CRITICAL(&s_lock);
admitted = s_accepting && !s_slot.close_requested;
if (admitted) s_slot.active = true;
taskEXIT_CRITICAL(&s_lock);
if (!admitted) { error = ESP_FAIL; goto cleanup; }
request->sess_ctx = &s_slot;
request->free_ctx = session_free;
count(&s_counts.connections, 1);
reserved = false; /* HTTPD context now owns cleanup. */
cleanup:
if (reserved) {
if (opened) admin_ssh_console_close(&token);
session_free(&s_slot);
}
secure_wipe(ticket, sizeof(ticket));
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
void web_admin_transport_get_snapshot(web_admin_transport_snapshot_t *snapshot)
{
if (!snapshot) return;
taskENTER_CRITICAL(&s_lock);
*snapshot = s_counts;
snapshot->initialized = s_initialized;
snapshot->attached = s_accepting;
snapshot->active = s_slot.active;
snapshot->closing = s_slot.close_requested;
snapshot->payload_bytes = s_payload ? sizeof(*s_payload) : 0;
snapshot->static_bytes = sizeof(s_lock) + sizeof(s_slot) + sizeof(s_payload) +
sizeof(s_timer) + sizeof(s_server) + sizeof(s_initialized) + sizeof(s_accepting) +
sizeof(s_queued) + sizeof(s_submitting) + sizeof(s_generation) + sizeof(s_counts);
taskEXIT_CRITICAL(&s_lock);
}
+42
View File
@@ -0,0 +1,42 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include "esp_http_server.h"
#include "web_session_store.h"
#define WEB_ADMIN_TICKET_URI "/api/admin/ws-ticket"
#define WEB_ADMIN_WS_URI "/ws/admin"
#define WEB_ADMIN_MAX_SESSIONS 1U
#define WEB_ADMIN_RX_CAPACITY 512U
#define WEB_ADMIN_TX_CAPACITY 1024U
typedef struct {
bool initialized, attached, active, closing;
uint32_t connections, disconnections, capacity_rejections, authorization_rejections;
uint32_t protocol_errors, input_backpressure, send_failures, queue_failures;
uint32_t rx_bytes, tx_bytes;
size_t static_bytes, payload_bytes;
esp_err_t last_error;
} web_admin_transport_snapshot_t;
/* Lifecycle caller serializes init/attach/detach/stopped. Optional PSRAM-only
* payload allocation; no internal fallback, new task, broker client or dispatcher.
* Timer only queues at most one poll; HTTPD owns all payload/IO/session cleanup. */
esp_err_t web_admin_transport_init(void);
esp_err_t web_admin_transport_attach(httpd_handle_t server);
/* Disable admission and console access, then wait a bounded time for timer
* submissions to finish. On timeout do NOT stop/free HTTPD; retry detach first. */
esp_err_t web_admin_transport_detach(httpd_handle_t server);
/* Call ONLY after successful httpd_ssl_stop, including partial startup cleanup.
* Retires any unexecuted queued poll before allowing reuse of its static storage. */
void web_admin_transport_stopped(httpd_handle_t server);
/* Ordinary HTTP routes, never register is_websocket=true: admission before 101.
* These handlers enforce cookie/Origin/CSRF/role themselves. Binary frames carry
* console bytes, final/unfragmented, at most RX_CAPACITY; no serial controls. */
esp_err_t web_admin_transport_ticket_handler(httpd_req_t *request);
esp_err_t web_admin_transport_upgrade_handler(httpd_req_t *request);
/* Notification after authoritative store invalidation. id wins; else exact
* username; else all. Safe before init. No socket calls from notifier context. */
void web_admin_transport_revoke(web_session_id_t id, const uint8_t *username, size_t length);
void web_admin_transport_get_snapshot(web_admin_transport_snapshot_t *snapshot);
+261
View File
@@ -0,0 +1,261 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "web_auth_parse.h"
#include <string.h>
static void wipe(void *buffer, size_t length)
{
volatile uint8_t *p = buffer;
while (length--) *p++ = 0;
}
static bool alnum_ascii(unsigned char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
}
static bool authority(const char *text, size_t length, char *out)
{
if (!text || !length || length > WEB_AUTH_ORIGIN_CAPACITY - 5U) return false;
if (length >= 4U && memcmp(text + length - 4U, ":443", 4U) == 0) length -= 4U;
if (!length || length > WEB_AUTH_ORIGIN_CAPACITY - 9U) return false;
size_t label = 0;
for (size_t i = 0; i < length; ++i) {
unsigned char c = (unsigned char)text[i];
if (c == '.') {
if (!label || text[i - 1U] == '-') return false;
label = 0;
} else {
if (!alnum_ascii(c) && c != '-') return false;
if ((!label && c == '-') || ++label > 63U) return false;
}
out[i] = c >= 'A' && c <= 'Z' ? (char)(c + ('a' - 'A')) : (char)c;
}
if (!label || text[length - 1U] == '-') return false;
out[length] = 0;
return true;
}
bool web_auth_parse_origin(const char *host, size_t host_length,
const char *origin, size_t origin_length,
char canonical[WEB_AUTH_ORIGIN_CAPACITY])
{
if (!canonical) return false;
memset(canonical, 0, WEB_AUTH_ORIGIN_CAPACITY);
char other[WEB_AUTH_ORIGIN_CAPACITY] = {0};
if (!origin || origin_length < 9U || origin_length > WEB_AUTH_ORIGIN_CAPACITY + 3U ||
memcmp(origin, "https://", 8U) != 0 ||
!authority(host, host_length, canonical + 8U) ||
!authority(origin + 8U, origin_length - 8U, other) ||
strcmp(canonical + 8U, other) != 0) {
memset(canonical, 0, WEB_AUTH_ORIGIN_CAPACITY);
return false;
}
memcpy(canonical, "https://", 8U);
return true;
}
static bool cookie_name_char(unsigned char c)
{
return alnum_ascii(c) || (c && strchr("!#$%&'*+-.^_`|~", c));
}
bool web_auth_parse_optional_cookie(const char *header, size_t length, const char *name,
char token[WEB_AUTH_TOKEN_LENGTH + 1U], bool *present)
{
if (!present) return false;
*present = false;
if (!token) return false;
memset(token, 0, WEB_AUTH_TOKEN_LENGTH + 1U);
if (!header || !name || !*name || !length || length > WEB_AUTH_COOKIE_HEADER_MAX)
return false;
size_t pos = 0, selected = 0, name_length = strlen(name);
bool found = false;
while (pos < length) {
while (pos < length && header[pos] == ' ') ++pos;
size_t start = pos;
while (pos < length && cookie_name_char((unsigned char)header[pos])) ++pos;
size_t key_length = pos - start;
if (!key_length || pos == length || header[pos++] != '=') return false;
size_t value = pos;
while (pos < length && header[pos] != ';') {
unsigned char c = (unsigned char)header[pos++];
if (c < 0x21 || c > 0x7e || c == '"' || c == ',' || c == '\\') return false;
}
if (key_length == name_length && memcmp(header + start, name, key_length) == 0) {
if (found || pos - value != WEB_AUTH_TOKEN_LENGTH) return false;
for (size_t i = value; i < pos; ++i)
if (!((header[i] >= '0' && header[i] <= '9') ||
(header[i] >= 'a' && header[i] <= 'f'))) return false;
found = true;
selected = value;
}
if (pos < length && ++pos == length) return false;
}
if (found) memcpy(token, header + selected, WEB_AUTH_TOKEN_LENGTH);
*present = found;
return true;
}
bool web_auth_parse_cookie(const char *header, size_t length, const char *name,
char token[WEB_AUTH_TOKEN_LENGTH + 1U])
{
bool present = false;
return web_auth_parse_optional_cookie(header, length, name, token, &present) && present;
}
typedef struct { const uint8_t *data; size_t length; size_t pos; } json_cursor_t;
static void whitespace(json_cursor_t *c)
{
while (c->pos < c->length) {
uint8_t b = c->data[c->pos];
if (b != ' ' && b != '\t' && b != '\r' && b != '\n') break;
++c->pos;
}
}
static bool take(json_cursor_t *c, uint8_t byte)
{
whitespace(c);
if (c->pos == c->length || c->data[c->pos] != byte) return false;
++c->pos;
return true;
}
static bool hex4(json_cursor_t *c, uint32_t *value)
{
*value = 0;
for (unsigned i = 0; i < 4; ++i) {
if (c->pos == c->length) return false;
uint8_t b = c->data[c->pos++];
unsigned digit;
if (b >= '0' && b <= '9') digit = b - '0';
else if (b >= 'a' && b <= 'f') digit = b - 'a' + 10U;
else if (b >= 'A' && b <= 'F') digit = b - 'A' + 10U;
else return false;
*value = (*value << 4) | digit;
}
return true;
}
static bool codepoint(json_cursor_t *c, uint32_t *value)
{
if (c->pos == c->length) return false;
uint8_t b = c->data[c->pos++];
if (b == '\\') {
if (c->pos == c->length) return false;
b = c->data[c->pos++];
switch (b) {
case '"': case '\\': case '/': *value = b; return true;
case 'b': *value = 8; return true;
case 'f': *value = 12; return true;
case 'n': *value = 10; return true;
case 'r': *value = 13; return true;
case 't': *value = 9; return true;
case 'u': break;
default: return false;
}
if (!hex4(c, value)) return false;
if (*value >= 0xd800 && *value <= 0xdbff) {
uint32_t low;
if (c->length - c->pos < 2U || c->data[c->pos++] != '\\' ||
c->data[c->pos++] != 'u' || !hex4(c, &low) ||
low < 0xdc00 || low > 0xdfff) return false;
*value = 0x10000 + ((*value - 0xd800) << 10) + low - 0xdc00;
}
return *value && !(*value >= 0xd800 && *value <= 0xdfff);
}
if (b < 0x20) return false;
if (b < 0x80) { *value = b; return true; }
unsigned extra;
uint32_t minimum;
if (b >= 0xc2 && b <= 0xdf) { extra = 1; minimum = 0x80; *value = b & 0x1f; }
else if (b >= 0xe0 && b <= 0xef) { extra = 2; minimum = 0x800; *value = b & 0x0f; }
else if (b >= 0xf0 && b <= 0xf4) { extra = 3; minimum = 0x10000; *value = b & 7; }
else return false;
while (extra--) {
if (c->pos == c->length) return false;
b = c->data[c->pos++];
if ((b & 0xc0) != 0x80) return false;
*value = (*value << 6) | (b & 0x3f);
}
return *value >= minimum && *value <= 0x10ffff &&
!(*value >= 0xd800 && *value <= 0xdfff);
}
static bool string(json_cursor_t *c, uint8_t *out, size_t capacity, size_t *length)
{
*length = 0;
if (!take(c, '"')) return false;
while (c->pos < c->length && c->data[c->pos] != '"') {
uint32_t cp;
if (!codepoint(c, &cp)) return false;
size_t bytes = cp < 0x80 ? 1U : cp < 0x800 ? 2U : cp < 0x10000 ? 3U : 4U;
if (bytes > capacity - *length) return false;
if (bytes == 1U) out[(*length)++] = (uint8_t)cp;
else {
out[(*length)++] = (uint8_t)((bytes == 2U ? 0xc0 : bytes == 3U ? 0xe0 : 0xf0) |
(cp >> (6U * (bytes - 1U))));
for (size_t i = bytes - 1U; i > 0; --i)
out[(*length)++] = (uint8_t)(0x80 | ((cp >> (6U * (i - 1U))) & 0x3f));
}
}
if (c->pos == c->length) return false;
++c->pos;
out[*length] = 0;
return true;
}
bool web_auth_parse_json_string(const char *body, size_t length, size_t *position,
uint8_t *output, size_t capacity, size_t *decoded_length)
{
if (output && capacity) wipe(output, capacity);
if (decoded_length) *decoded_length = 0;
if (!body || !position || *position > length || !output || !capacity || !decoded_length)
return false;
json_cursor_t c = { (const uint8_t *)body, length, *position };
if (!string(&c, output, capacity - 1U, decoded_length)) {
wipe(output, capacity);
*decoded_length = 0;
return false;
}
*position = c.pos;
return true;
}
bool web_auth_parse_login(const char *body, size_t length,
web_auth_credentials_t *credentials)
{
if (!credentials) return false;
wipe(credentials, sizeof(*credentials));
if (!body || !length || length > WEB_AUTH_LOGIN_BODY_MAX) return false;
json_cursor_t c = { (const uint8_t *)body, length, 0 };
unsigned seen = 0;
if (!take(&c, '{')) return false;
for (unsigned field = 0; field < 2; ++field) {
uint8_t key[9] = {0};
size_t key_length;
if ((field && !take(&c, ',')) || !string(&c, key, 8U, &key_length) ||
!take(&c, ':')) goto invalid;
unsigned bit;
uint8_t *output;
size_t *output_length, capacity;
if (key_length == 8U && memcmp(key, "username", 8U) == 0) {
bit = 1; output = credentials->username;
output_length = &credentials->username_length; capacity = WEB_AUTH_USERNAME_MAX;
} else if (key_length == 8U && memcmp(key, "password", 8U) == 0) {
bit = 2; output = credentials->password;
output_length = &credentials->password_length; capacity = WEB_AUTH_PASSWORD_MAX;
} else goto invalid;
if ((seen & bit) || !string(&c, output, capacity, output_length)) goto invalid;
seen |= bit;
}
if (!take(&c, '}')) goto invalid;
whitespace(&c);
if (c.pos == c.length && seen == 3U) return true;
invalid:
wipe(credentials, sizeof(*credentials));
return false;
}
+53
View File
@@ -0,0 +1,53 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* Private, allocation-free parsing only: these helpers do not authorize requests. */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define WEB_AUTH_ORIGIN_CAPACITY 129U
#define WEB_AUTH_COOKIE_HEADER_MAX 1024U
#define WEB_AUTH_TOKEN_LENGTH 64U
#define WEB_AUTH_LOGIN_BODY_MAX 512U
#define WEB_AUTH_USERNAME_MAX 16U
#define WEB_AUTH_PASSWORD_MAX 64U
typedef struct {
size_t username_length;
size_t password_length;
uint8_t username[WEB_AUTH_USERNAME_MAX + 1U];
uint8_t password[WEB_AUTH_PASSWORD_MAX + 1U];
} web_auth_credentials_t;
/* Exact byte spans, not necessarily NUL-terminated. Inputs and output must not
* alias. Failures clear output. Host supports ASCII DNS/IPv4 authorities only;
* IPv6 literals are deliberately rejected until the device supports that route.
* Only optional :443 is accepted. Origin is mandatory and must match Host.
* HTTP callers must separately reject duplicate header lines, enforce methods,
* body/content-type limits, Fetch Metadata and CSRF/session policy. */
bool web_auth_parse_origin(const char *host, size_t host_length,
const char *origin, size_t origin_length,
char canonical[WEB_AUTH_ORIGIN_CAPACITY]);
/* Extract exactly one named lowercase-hex token; malformed/duplicate or missing
* selected cookie fails. Other cookies are syntax-checked but not retained.
* This deliberately accepts only unquoted cookie values, including unrelated
* cookies; quoted values fail closed. No whitespace inside a cookie pair.
* name is a trusted, nonempty C string. Output is sensitive: wipe after use. */
bool web_auth_parse_cookie(const char *header, size_t length, const char *name,
char token[WEB_AUTH_TOKEN_LENGTH + 1U]);
/* As above, but a missing selected cookie is valid with present=false. This
* lets HTTP policy distinguish absence from malformed/ambiguous cookies. */
bool web_auth_parse_optional_cookie(const char *header, size_t length, const char *name,
char token[WEB_AUTH_TOKEN_LENGTH + 1U], bool *present);
/* Decode one string at *position (including optional JSON whitespace). Capacity
* includes the terminator. Failure wipes output and leaves position unchanged.
* Success output is sensitive; caller must wipe it. Same strict decoder as login. */
bool web_auth_parse_json_string(const char *body, size_t length, size_t *position,
uint8_t *output, size_t capacity, size_t *decoded_length);
/* Exactly username/password string fields, either order. JSON escapes and valid
* UTF-8 accepted; unknown/duplicate fields, NUL and malformed Unicode rejected.
* Database credential policy remains authoritative. Caller must wipe BOTH the
* original request body and successful credentials using secure_wipe(). */
bool web_auth_parse_login(const char *body, size_t length,
web_auth_credentials_t *credentials);
+234
View File
@@ -0,0 +1,234 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "web_broker_settings.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "admin_ssh_console.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "secure_random.h"
#include "session_broker.h"
#include "web_cookie_auth.h"
#include "web_httpd_adapter.h"
enum { IDLE, PENDING, OK, FAILED, CANCELLED, CONFLICT };
static const char *const s_states[] = {"idle", "pending", "ok", "failed", "cancelled", "conflict"};
typedef struct {
uint32_t id;
web_session_id_t session;
user_principal_t principal;
int64_t deadline;
uint32_t generation, target;
unsigned state;
} broker_operation_t;
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static broker_operation_t s_operation;
static uint32_t s_next_id;
/* Narrow flat JSON: exact action plus two unsigned decimal integers, no
* escapes, duplicates, unknown fields, nesting, fractions or exponents. */
static bool parse(const char *body, size_t length, broker_operation_t *operation)
{
const char *keys[] = {"action", "generation", "target"};
unsigned seen = 0;
size_t pos = 0;
#define SPACE() while (pos < length && (body[pos] == ' ' || body[pos] == '\t' || body[pos] == '\r' || body[pos] == '\n')) ++pos
#define TAKE(c) do { SPACE(); if (pos == length || body[pos++] != (c)) return false; } while (0)
TAKE('{');
for (unsigned field = 0; field < 3; ++field) {
if (field) { TAKE(','); }
TAKE('"');
size_t start = pos;
while (pos < length && body[pos] != '"') ++pos;
if (pos == length) return false;
unsigned key = 0;
for (; key < 3; ++key)
if (strlen(keys[key]) == pos - start && !memcmp(body + start, keys[key], pos - start)) break;
if (key == 3 || (seen & (1U << key))) return false;
++pos; TAKE(':'); SPACE();
if (key == 0) {
const char action[] = "\"assign\"";
if (length - pos < sizeof(action) - 1 || memcmp(body + pos, action, sizeof(action) - 1)) return false;
pos += sizeof(action) - 1;
} else {
uint32_t number = 0;
start = pos;
while (pos < length && body[pos] >= '0' && body[pos] <= '9') {
unsigned digit = (unsigned)(body[pos++] - '0');
if (number > (UINT32_MAX - digit) / 10U) return false;
number = number * 10U + digit;
}
if (pos == start || (pos - start > 1 && body[start] == '0')) return false;
if (key == 1) operation->generation = number;
else operation->target = number;
}
seen |= 1U << key;
}
TAKE('}'); SPACE();
#undef TAKE
#undef SPACE
return pos == length && seen == 7 && operation->target &&
operation->generation && operation->generation != UINT32_MAX;
}
void web_broker_settings_execute(uint32_t id)
{
broker_operation_t operation;
taskENTER_CRITICAL(&s_lock);
operation = s_operation;
taskEXIT_CRITICAL(&s_lock);
if (!id || operation.id != id || operation.state != PENDING) {
secure_wipe(&operation, sizeof(operation));
return;
}
bool current = false;
esp_err_t error = web_session_store_check_principal(operation.session, &operation.principal, &current);
unsigned state = CANCELLED;
if (error == ESP_OK && current && operation.principal.role == USER_ROLE_ADMIN &&
esp_timer_get_time() < operation.deadline) {
error = session_broker_assign_writer_current(operation.target, operation.generation);
state = error == ESP_OK ? OK :
(error == ESP_ERR_INVALID_STATE || error == ESP_ERR_NOT_FOUND) ? CONFLICT : FAILED;
}
taskENTER_CRITICAL(&s_lock);
if (s_operation.id == id && s_operation.state == PENDING) {
s_operation.state = state;
secure_wipe(&s_operation.principal, sizeof(s_operation.principal));
}
taskEXIT_CRITICAL(&s_lock);
secure_wipe(&operation, sizeof(operation));
}
static esp_err_t respond(httpd_req_t *request, const char *status, const char *body)
{
esp_err_t error = httpd_resp_set_status(request, status);
if (error == ESP_OK) error = httpd_resp_set_type(request, "application/json; charset=utf-8");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "Cache-Control", "no-store");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "X-Content-Type-Options", "nosniff");
if (error == ESP_OK) error = httpd_resp_set_hdr(request, "Referrer-Policy", "no-referrer");
if (error == ESP_OK) error = httpd_resp_sendstr(request, body);
return web_httpd_unread_body(request) ? ESP_FAIL : error;
}
esp_err_t web_broker_operation_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
bool allowed = false;
bool mutation = request->method == HTTP_POST;
esp_err_t error = mutation
? web_cookie_auth_require_json(request, 256, &view, &allowed)
: web_cookie_auth_require(request, false, false, &view, &allowed);
if (error != ESP_OK || !allowed) goto done;
if (view.principal.role != USER_ROLE_ADMIN) {
error = respond(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto done;
}
broker_operation_t operation = {0};
if (mutation) {
char type[40] = {0}, body[256];
size_t received = 0;
bool valid = request->content_len && request->content_len <= sizeof(body) &&
httpd_req_get_hdr_value_str(request, "Content-Type", type, sizeof(type)) == ESP_OK &&
(!strcmp(type, "application/json") || !strcmp(type, "application/json; charset=utf-8"));
for (unsigned reads = 0; valid && received < request->content_len && reads < 4; ++reads) {
int count = httpd_req_recv(request, body + received, request->content_len - received);
if (count <= 0 || (size_t)count > request->content_len - received) valid = false;
else received += (size_t)count;
}
valid = valid && received == request->content_len && parse(body, received, &operation);
secure_wipe(body, sizeof(body));
if (!valid) {
error = respond(request, "400 Bad Request", "{\"error\":\"invalid_broker_request\"}");
goto done;
}
operation.session = view.id;
operation.principal = view.principal;
operation.deadline = esp_timer_get_time() + 30000000LL;
operation.state = PENDING;
taskENTER_CRITICAL(&s_lock);
bool busy = s_operation.state == PENDING || s_next_id == UINT32_MAX;
if (!busy) {
operation.id = ++s_next_id;
s_operation = operation;
}
taskEXIT_CRITICAL(&s_lock);
if (busy || admin_ssh_console_submit_broker_settings(operation.id) != ESP_OK) {
taskENTER_CRITICAL(&s_lock);
if (!busy && s_operation.id == operation.id) secure_wipe(&s_operation, sizeof(s_operation));
taskEXIT_CRITICAL(&s_lock);
error = httpd_resp_set_hdr(request, "Retry-After", "1");
if (error == ESP_OK) error = respond(request, "503 Service Unavailable", "{\"error\":\"busy\"}");
secure_wipe(&operation, sizeof(operation));
goto done;
}
} else {
taskENTER_CRITICAL(&s_lock);
if (s_operation.session == view.id) {
operation.id = s_operation.id;
operation.state = s_operation.state;
}
taskEXIT_CRITICAL(&s_lock);
}
char response[96];
int written = snprintf(response, sizeof(response), "{\"id\":%" PRIu32 ",\"action\":\"%s\",\"state\":\"%s\"}",
operation.id, operation.id ? "assign" : "none", s_states[operation.state]);
error = written < 0 || (size_t)written >= sizeof(response) ? ESP_FAIL :
respond(request, mutation ? "202 Accepted" : "200 OK", response);
secure_wipe(&operation, sizeof(operation));
done:
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
esp_err_t web_broker_settings_handler(httpd_req_t *request)
{
web_session_view_t view = {0};
bool allowed = false;
esp_err_t error = web_cookie_auth_require(request, false, false, &view, &allowed);
if (error != ESP_OK || !allowed) goto done;
if (view.principal.role != USER_ROLE_ADMIN) {
error = respond(request, "403 Forbidden", "{\"error\":\"admin_required\"}");
goto done;
}
session_broker_management_snapshot_t snapshot;
error = session_broker_get_management_snapshot(&snapshot);
if (error != ESP_OK) {
error = respond(request, "503 Service Unavailable", "{\"error\":\"broker_unavailable\"}");
goto done;
}
/* Eight rows; names are exact bounded bytes as hex, never unescaped JSON.
* Decimal-string drop counters retain all 64 bits in the browser. */
char response[2048];
int written = snprintf(response, sizeof(response),
"{\"generation\":%" PRIu32 ",\"writer\":%" PRIu32 ",\"clients\":[",
snapshot.generation, snapshot.writer_id);
size_t used = 0;
if (written < 0 || (size_t)written >= sizeof(response)) { error = ESP_FAIL; goto done; }
used = (size_t)written;
for (size_t i = 0; i < snapshot.count; ++i) {
const session_broker_management_client_t *client = &snapshot.clients[i];
char name[SESSION_BROKER_CLIENT_NAME_MAX * 2 + 1];
static const char hex[] = "0123456789abcdef";
size_t n = 0;
for (; n < SESSION_BROKER_CLIENT_NAME_MAX && client->name[n]; ++n) {
unsigned byte = (unsigned char)client->name[n];
name[n * 2] = hex[byte >> 4]; name[n * 2 + 1] = hex[byte & 15];
}
name[n * 2] = 0;
written = snprintf(response + used, sizeof(response) - used,
"%s{\"id\":%" PRIu32 ",\"type\":%u,\"name_hex\":\"%s\",\"pending\":%u,\"high_water\":%u,\"dropped\":\"%" PRIu64 "\"}",
i ? "," : "", client->id, (unsigned)client->type, name,
(unsigned)client->pending, (unsigned)client->high_water, client->dropped);
if (written < 0 || (size_t)written >= sizeof(response) - used) { error = ESP_FAIL; goto done; }
used += (size_t)written;
}
written = snprintf(response + used, sizeof(response) - used, "]}");
error = written < 0 || (size_t)written >= sizeof(response) - used ? ESP_FAIL :
respond(request, "200 OK", response);
done:
secure_wipe(&view, sizeof(view));
web_httpd_wipe_request(request, web_httpd_unread_body(request));
return error;
}
+9
View File
@@ -0,0 +1,9 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include <stdint.h>
#include "esp_http_server.h"
/* Optional admin-only snapshot and login-isolated typed assignment/results. */
esp_err_t web_broker_settings_handler(httpd_req_t *request);
esp_err_t web_broker_operation_handler(httpd_req_t *request);
void web_broker_settings_execute(uint32_t id);
+124 -145
View File
@@ -1,30 +1,33 @@
/* SPDX-License-Identifier: GPL-3.0-only */
/* UART0 HTTPS lifecycle, legacy recovery credential, and certificate commands. */
/* HTTPS lifecycle and TLS certificate commands. */
#include "web_console.h"
#include "admin_ssh_console.h"
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include "esp_console.h"
#include "secure_random.h"
#include "ssh_transport.h"
#include "user_database.h"
#include "web_security.h"
#include "web_serial_transport.h"
#include "web_server.h"
#include "web_cookie_auth.h"
#include "web_admin_transport.h"
#include "web_admin_tickets.h"
#include "web_diagnostics.h"
static void print_usage(void)
{
printf("Usage:\n");
printf(" web status|start|stop\n");
printf(" web counters|clear-counters\n");
printf(" web credentials show\n");
printf(" web credentials rotate --force\n");
printf(" web diagnostics enable|disable|show|clear\n");
printf(" web performance enable|disable|show|clear\n");
printf(" web certificate info\n");
printf(" web certificate rotate --force\n");
printf(" web reset --force\n");
printf(" web reset --force (TLS certificate and private key only)\n");
}
static void print_fingerprint(const uint8_t fingerprint[WEB_SECURITY_SHA256_LENGTH])
@@ -34,6 +37,30 @@ static void print_fingerprint(const uint8_t fingerprint[WEB_SECURITY_SHA256_LENG
}
}
static void show_admin_transport(void)
{
web_admin_transport_snapshot_t admin;
web_admin_tickets_snapshot_t tickets;
web_admin_transport_get_snapshot(&admin);
web_admin_tickets_get_snapshot(&tickets);
printf("WebSocket admin: initialized=%s attached=%s active=%s/1 closing=%s init-error=%s\n",
admin.initialized ? "yes" : "no", admin.attached ? "yes" : "no",
admin.active ? "yes" : "no", admin.closing ? "yes" : "no", esp_err_to_name(admin.last_error));
printf(" tickets=%" PRIu32 "/%u issued=%" PRIu32 " consumed=%" PRIu32
" rejected=%" PRIu32 " capacity=%" PRIu32 "\n",
tickets.active, WEB_ADMIN_TICKET_CAPACITY, tickets.issued, tickets.consumed,
tickets.rejected, tickets.capacity_rejections);
printf(" connected=%" PRIu32 " disconnected=%" PRIu32 " capacity=%" PRIu32
" authorization=%" PRIu32 " protocol=%" PRIu32 " input-backpressure=%" PRIu32 "\n",
admin.connections, admin.disconnections, admin.capacity_rejections,
admin.authorization_rejections, admin.protocol_errors, admin.input_backpressure);
printf(" rx-bytes=%" PRIu32 " tx-bytes=%" PRIu32 " send-failures=%" PRIu32
" queue-failures=%" PRIu32 " static=%u ticket-storage=%u PSRAM-payload=%u bytes\n",
admin.rx_bytes, admin.tx_bytes, admin.send_failures, admin.queue_failures,
(unsigned)admin.static_bytes, (unsigned)tickets.storage_bytes, (unsigned)admin.payload_bytes);
printf(" Admin counters are saturating lifetime counts (not reset by web clear-counters).\n");
}
static int show_status(void)
{
web_server_snapshot_t snapshot;
@@ -52,13 +79,26 @@ static int show_status(void)
(unsigned int)snapshot.port,
esp_err_to_name(snapshot.last_error));
if (users_error == ESP_OK) {
printf("Authentication: HTTP Basic over TLS via user database, users=%u admins=%u\n",
printf("Authentication: HTTPS cookie sessions via user database, users=%u admins=%u\n",
(unsigned int)users.user_count, (unsigned int)users.admin_count);
} else {
printf("Authentication database unavailable: %s; use 'user recover --force'.\n",
esp_err_to_name(users_error));
}
printf("Endpoints: GET /, GET /api/status, POST /api/ws-ticket, WSS /ws/serial\n");
printf("Authentication routes: GET /login, GET /api/login-challenge, POST /api/login, GET /api/session, POST /api/logout\n");
printf("Admin-only backend: POST /api/admin/ws-ticket, WSS /ws/admin (no normal UI entry)\n");
show_admin_transport();
web_cookie_auth_snapshot_t auth;
web_cookie_auth_get_snapshot(&auth);
web_session_store_snapshot_t sessions;
if (web_session_store_get_snapshot(&sessions) == ESP_OK)
printf("Cookie authentication: ready=%s sessions=%" PRIu32 "/4 challenges=%" PRIu32 "/4\n",
auth.ready ? "yes" : "no", sessions.active, auth.active_challenges);
printf("Login attempts=%" PRIu32 " invalid-credentials=%" PRIu32 " throttled=%" PRIu32
" auth-capacity-rejections=%" PRIu32 " CSRF/origin-rejections=%" PRIu32 " logouts=%" PRIu32 "\n",
auth.login_attempts, auth.login_failures, auth.throttled, auth.capacity_rejections,
auth.security_rejections, auth.logouts);
web_serial_transport_snapshot_t transport;
esp_err_t transport_error = web_serial_transport_get_snapshot(&transport);
@@ -110,6 +150,7 @@ static int show_counters(void)
return 1;
}
show_admin_transport();
const web_server_counters_t *counter = &snapshot.counters;
printf("Lifecycle: starts=%" PRIu64 " start-failures=%" PRIu64
" stops=%" PRIu64 "\n",
@@ -163,25 +204,6 @@ static int show_counters(void)
return 0;
}
static int show_credentials(void)
{
web_security_credentials_t credentials;
esp_err_t error = web_security_show_credentials(&credentials);
if (error != ESP_OK) {
printf("Could not read web credentials: %s\n", esp_err_to_name(error));
return 1;
}
printf("Username: %.*s\n", (int)credentials.username_length,
credentials.username);
printf("Password: %.*s\n", (int)credentials.password_length,
credentials.password);
printf("Phase 8B uses the user database for HTTPS and SSH authentication.\n");
printf("This legacy credential is retained only for migration and physical recovery.\n");
secure_wipe(&credentials, sizeof(credentials));
return 0;
}
static int show_certificate(void)
{
web_security_certificate_metadata_t metadata;
@@ -212,125 +234,65 @@ static bool force_is_present(int argc, char **argv, int expected_argc)
return argc == expected_argc && strcmp(argv[expected_argc - 1], "--force") == 0;
}
static int restart_if_running(bool was_running)
static int replace_material(bool reset)
{
if (!was_running) {
return 0;
}
esp_err_t error = web_server_stop();
bool committed = false;
esp_err_t error = web_server_replace_identity(0, 0, reset, &committed);
if (error != ESP_OK) {
printf("Material changed, but the old TLS server could not stop: %s\n",
esp_err_to_name(error));
return 1;
}
error = web_server_start();
if (error != ESP_OK) {
printf("Material changed, but HTTPS could not restart: %s\n",
esp_err_to_name(error));
printf("%s: %s\n", committed
? "New HTTPS identity persisted, but stop/start failed; no rollback. Inspect via UART0 before retrying"
: "HTTPS identity replacement rejected or failed before publication",
esp_err_to_name(error));
return 1;
}
printf("HTTPS certificate and private key replaced and persisted; user accounts unchanged.\n");
printf("Verify the new fingerprint via trusted UART0, renew browser trust, and sign in again.\n");
return 0;
}
static void synchronize_migrated_user(
const web_security_credentials_t *credentials)
{
const user_database_legacy_credentials_t legacy = {
.username = (const uint8_t *)credentials->username,
.username_length = credentials->username_length,
.password = (const uint8_t *)credentials->password,
.password_length = credentials->password_length,
};
bool synchronized = false;
esp_err_t error = user_database_sync_legacy_credentials(&legacy, &synchronized);
if (error != ESP_OK) {
printf("Warning: migrated user synchronization failed: %s. Boot will retry a valid stored database; otherwise use 'user recover --force'.\n",
esp_err_to_name(error));
return;
}
if (synchronized) {
(void)web_serial_transport_revoke_user(
(const uint8_t *)credentials->username,
credentials->username_length);
(void)ssh_transport_revoke_user(
(const uint8_t *)credentials->username,
credentials->username_length);
printf("The pre-bootstrap migrated user credential was synchronized.\n");
return;
}
static int rotate_certificate(void) { return replace_material(false); }
static int reset_material(void) { return replace_material(true); }
user_database_snapshot_t snapshot;
if (user_database_get_snapshot(&snapshot) == ESP_OK &&
snapshot.admin_bootstrapped) {
printf("This legacy recovery credential is separate from role-based user passwords.\n");
} else {
printf("Warning: no matching pre-bootstrap migrated user was synchronized; establish an administrator with 'user bootstrap'.\n");
}
static void print_performance_time(const char *name, const web_serial_performance_timing_t *t)
{
printf(" %s: count=%" PRIu64 " sum_us=%" PRIu64 " avg_us_est=%" PRIu64 " max_us=%" PRIu64 "\n",
name, t->count, t->sum_us, t->count ? t->sum_us / t->count : 0, t->max_us);
}
static int rotate_credentials(void)
static int performance_command(const char *action)
{
web_security_credentials_t credentials;
esp_err_t error = web_security_rotate_credentials(&credentials);
if (error != ESP_OK) {
printf("Could not rotate web credentials: %s\n", esp_err_to_name(error));
esp_err_t result = ESP_OK;
if (!strcmp(action, "enable")) result = web_serial_performance_enable(true);
else if (!strcmp(action, "disable")) result = web_serial_performance_enable(false);
else if (!strcmp(action, "clear")) result = web_serial_performance_clear();
else if (strcmp(action, "show")) return 1;
if (result != ESP_OK) {
printf("Web performance: %s\n", esp_err_to_name(result));
return 1;
}
synchronize_migrated_user(&credentials);
printf("Legacy migration/recovery credential rotated and persisted.\n");
printf("Username: %.*s\nPassword: %.*s\n",
(int)credentials.username_length, credentials.username,
(int)credentials.password_length, credentials.password);
secure_wipe(&credentials, sizeof(credentials));
return 0;
}
static int rotate_certificate(void)
{
web_server_snapshot_t snapshot;
esp_err_t error = web_server_get_snapshot(&snapshot);
if (error != ESP_OK) {
printf("Could not inspect HTTPS runtime: %s\n", esp_err_to_name(error));
return 1;
web_serial_performance_snapshot_t s;
web_serial_performance_snapshot(&s);
printf("Web performance: enabled=%u epoch=%" PRIu32 " epoch_exhausted=%u; binary TX only\n",
s.enabled, s.epoch, s.epoch_exhausted);
printf("Send-call return is synchronous HTTPD-owner bytes send, not peer receipt. Timings are instrumented estimates; saturated=1 invalidates averages/count totals.\n");
printf("Completion->nonempty includes idle gaps; first-nonempty excludes observed empty attempts, not proof of backlog.\n");
for (unsigned i = 0; i < WEB_SERIAL_TRANSPORT_MAX_SESSIONS; ++i) {
const web_serial_performance_session_t *r = &s.sessions[i];
if (!r->active) continue;
printf("slot=%u fd=%d generation=%" PRIu32 " broker=%" PRIu32
" pending=%u measured_pending=%u executing=%u pending_age_us=%" PRIu64 " saturated=%u\n",
i, r->socket_fd, r->generation, (uint32_t)r->broker_client_id,
r->pending, r->measured_pending, r->executing, r->pending_age_us, r->saturated);
printf(" queued_frames=%" PRIu64 " queued_bytes=%" PRIu64 " queue_errors=%" PRIu64
" sent_frames=%" PRIu64 " sent_bytes=%" PRIu64 " send_errors=%" PRIu64 " retired=%" PRIu64 "\n",
r->queued_frames, r->queued_bytes, r->queue_errors, r->sent_frames,
r->sent_bytes, r->send_errors, r->retired);
print_performance_time("queue->callback-entry", &r->queue_wait);
print_performance_time("send-call", &r->send_call);
print_performance_time("completion->first-drain-attempt-return", &r->completion_attempt);
print_performance_time("completion->next-nonempty-drain-return (includes idle)", &r->completion_nonempty);
print_performance_time("completion->first-attempt-nonempty-return", &r->completion_first_nonempty);
}
error = web_security_rotate_certificate();
if (error != ESP_OK) {
printf("Could not rotate web certificate: %s\n", esp_err_to_name(error));
return 1;
}
printf("Web certificate and private key rotated and persisted.\n");
return restart_if_running(snapshot.running);
}
static int reset_material(void)
{
web_server_snapshot_t snapshot;
bool was_running = web_server_get_snapshot(&snapshot) == ESP_OK && snapshot.running;
web_security_credentials_t credentials;
esp_err_t error = web_security_reset_all(&credentials);
if (error != ESP_OK) {
printf("Could not reset web security material: %s\n", esp_err_to_name(error));
return 1;
}
synchronize_migrated_user(&credentials);
printf("Legacy recovery credential, HTTPS certificate, and HTTPS private key replaced and persisted.\n");
printf("Username: %.*s\nPassword: %.*s\n",
(int)credentials.username_length, credentials.username,
(int)credentials.password_length, credentials.password);
secure_wipe(&credentials, sizeof(credentials));
if (was_running) {
return restart_if_running(true);
}
error = web_server_start();
if (error != ESP_OK) {
printf("Security material recovered, but HTTPS could not start: %s\n",
esp_err_to_name(error));
return 1;
}
printf("HTTPS started with the recovered security material.\n");
return 0;
}
@@ -340,6 +302,16 @@ static int command_web(int argc, char **argv)
print_usage();
return 0;
}
if (argc == 3 && strcmp(argv[1], "performance") == 0) {
if (performance_command(argv[2]) == 0) return 0;
print_usage();
return 1;
}
if (argc == 3 && strcmp(argv[1], "diagnostics") == 0) {
if (web_diagnostics_command(argv[2]) == 0) return 0;
print_usage();
return 1;
}
if (argc == 2 && strcmp(argv[1], "status") == 0) {
return show_status();
}
@@ -353,6 +325,15 @@ static int command_web(int argc, char **argv)
return 0;
}
if (argc == 2 && strcmp(argv[1], "stop") == 0) {
if (admin_ssh_console_dispatch_is_web()) {
esp_err_t error = admin_ssh_console_dispatch_defer(ADMIN_CONSOLE_DEFER_WEB_STOP, 0U);
if (error != ESP_OK) {
printf("Could not schedule HTTPS stop: %s\n", esp_err_to_name(error));
return 1;
}
printf("HTTPS stop scheduled after console output drains; both browser connections will close.\n");
return 0;
}
esp_err_t error = web_server_stop();
if (error != ESP_OK) {
printf("Could not stop HTTPS: %s\n", esp_err_to_name(error));
@@ -376,18 +357,6 @@ static int command_web(int argc, char **argv)
printf("HTTPS and WebSocket counters cleared.\n");
return 0;
}
if (argc == 3 && strcmp(argv[1], "credentials") == 0 &&
strcmp(argv[2], "show") == 0) {
return show_credentials();
}
if (strcmp(argv[1], "credentials") == 0 && argc >= 3 &&
strcmp(argv[2], "rotate") == 0) {
if (!force_is_present(argc, argv, 4)) {
printf("Credential rotation requires: web credentials rotate --force\n");
return 1;
}
return rotate_credentials();
}
if (argc == 3 && strcmp(argv[1], "certificate") == 0 &&
strcmp(argv[2], "info") == 0) {
return show_certificate();
@@ -398,11 +367,21 @@ static int command_web(int argc, char **argv)
printf("Certificate rotation requires: web certificate rotate --force\n");
return 1;
}
if (admin_ssh_console_dispatch_is_web()) {
esp_err_t error = admin_ssh_console_dispatch_defer(
ADMIN_CONSOLE_DEFER_WEB_CERTIFICATE_ROTATE, 0U);
if (error != ESP_OK) {
printf("Could not schedule HTTPS certificate rotation: %s\n", esp_err_to_name(error));
return 1;
}
printf("HTTPS identity rotation scheduled after console output drains; all web logins and browser terminals will close. A new identity may persist even if stop/start fails; no rollback. Verify the new fingerprint via trusted UART0 web certificate info before renewing browser trust, then reload and sign in. SSH and USB UART1 access remain independent.\n");
return 0;
}
return rotate_certificate();
}
if (strcmp(argv[1], "reset") == 0) {
if (!force_is_present(argc, argv, 3)) {
printf("Full material replacement requires: web reset --force\n");
printf("TLS-only certificate/private-key replacement requires: web reset --force\n");
return 1;
}
return reset_material();
@@ -416,7 +395,7 @@ esp_err_t web_console_register_commands(void)
{
const esp_console_cmd_t command = {
.command = "web",
.help = "Manage authenticated HTTPS and recover web credentials/certificate",
.help = "Manage authenticated HTTPS and recover TLS certificate/private key",
.hint = NULL,
.func = &command_web,
.argtable = NULL,
+446
View File
@@ -0,0 +1,446 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#include "web_cookie_auth.h"
#include <stdio.h>
#include <string.h>
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "mbedtls/sha256.h"
#include "secure_random.h"
#include "web_auth_parse.h"
#include "web_httpd_adapter.h"
#include "web_login_ui.h"
#include "web_serial_transport.h"
#define SESSION_COOKIE "__Host-sak-session"
#define PRELOGIN_COOKIE "__Host-sak-prelogin"
#define COOKIE_FLAGS "; Secure; HttpOnly; SameSite=Strict; Path=/; Max-Age="
#define CHALLENGE_US 120000000LL
#define WINDOW_US 60000000LL
typedef struct {
int64_t expiry;
uint8_t token_digest[32];
uint8_t origin_digest[32];
char csrf[65];
} challenge_t;
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static challenge_t s_challenges[4];
static bool s_ready;
static uint64_t s_epoch;
static int64_t s_window;
static unsigned s_attempts;
static web_cookie_auth_snapshot_t s_counts;
static bool equal(const void *a, const void *b, size_t size)
{
const uint8_t *x = a, *y = b;
unsigned difference = 0;
for (size_t i = 0; i < size; ++i) difference |= x[i] ^ y[i];
return difference == 0;
}
static bool header(httpd_req_t *r, const char *name, char *out, size_t size)
{
size_t length = httpd_req_get_hdr_value_len(r, name);
out[0] = 0;
return length < size && httpd_req_get_hdr_value_str(r, name, out, size) == ESP_OK;
}
static bool origin(httpd_req_t *r, bool required, char canonical[129])
{
char host[129] = {0}, supplied[137] = {0}, site[16] = {0};
if (!header(r, "Host", host, sizeof(host))) return false;
if (header(r, "Sec-Fetch-Site", site, sizeof(site))) {
if (strcmp(site, "same-origin") && strcmp(site, "none")) return false;
} else if (httpd_req_get_hdr_value_len(r, "Sec-Fetch-Site")) return false;
if (!header(r, "Origin", supplied, sizeof(supplied))) {
if (required || httpd_req_get_hdr_value_len(r, "Origin")) return false;
int length = snprintf(supplied, sizeof(supplied), "https://%s", host);
if (length < 0 || (size_t)length >= sizeof(supplied)) return false;
}
return web_auth_parse_origin(host, strlen(host), supplied, strlen(supplied), canonical);
}
static bool cookie(httpd_req_t *r, const char *name, char token[65])
{
char cookies[1025] = {0};
bool valid = header(r, "Cookie", cookies, sizeof(cookies)) &&
web_auth_parse_cookie(cookies, strlen(cookies), name, token);
secure_wipe(cookies, sizeof(cookies));
return valid;
}
static bool cookies_valid(httpd_req_t *r)
{
char cookies[1025] = {0}, token[65] = {0};
bool present;
esp_err_t error = httpd_req_get_hdr_value_str(r, "Cookie", cookies, sizeof(cookies));
bool valid = error == ESP_ERR_NOT_FOUND ||
(error == ESP_OK && httpd_req_get_hdr_value_len(r, "Cookie") < sizeof(cookies) &&
web_auth_parse_optional_cookie(cookies, strlen(cookies), SESSION_COOKIE, token, &present) &&
web_auth_parse_optional_cookie(cookies, strlen(cookies), PRELOGIN_COOKIE, token, &present));
secure_wipe(cookies, sizeof(cookies));
secure_wipe(token, sizeof(token));
return valid;
}
static esp_err_t response(httpd_req_t *r, const char *status, const char *body)
{
esp_err_t error = httpd_resp_set_status(r, status);
if (error == ESP_OK) error = httpd_resp_set_type(r, "application/json; charset=utf-8");
if (error == ESP_OK) error = httpd_resp_set_hdr(r, "Cache-Control", "no-store");
if (error == ESP_OK) error = httpd_resp_set_hdr(r, "X-Content-Type-Options", "nosniff");
if (error == ESP_OK) error = httpd_resp_set_hdr(r, "Referrer-Policy", "no-referrer");
if (error == ESP_OK) error = httpd_resp_set_hdr(r, "X-Frame-Options", "DENY");
if (error == ESP_OK) error = httpd_resp_sendstr(r, body);
/* Never let HTTPD drain an attacker-controlled rejected request body. */
return web_httpd_unread_body(r) ? ESP_FAIL : error;
}
static esp_err_t failure(httpd_req_t *r, const char *status, const char *code)
{
bool security = !strcmp(status, "403 Forbidden");
bool credentials = !strcmp(code, "invalid_credentials");
bool throttled = !strcmp(code, "throttled");
bool full = !strcmp(code, "capacity");
taskENTER_CRITICAL(&s_lock);
s_counts.security_rejections += security;
s_counts.login_failures += credentials;
s_counts.throttled += throttled;
s_counts.capacity_rejections += full;
taskEXIT_CRITICAL(&s_lock);
char body[80];
snprintf(body, sizeof(body), "{\"error\":\"%s\"}", code);
return response(r, status, body);
}
/* An early probe never charges or advances the verification window. Only the
* post-parse reservation commits it; retry == 0 means budget is available. */
static bool verification_budget(uint64_t epoch, bool reserve, int64_t *retry)
{
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
bool ready = s_ready && epoch == s_epoch;
int64_t window = s_window;
unsigned attempts = s_attempts;
if (now - window >= WINDOW_US) { window = now; attempts = 0; }
*retry = attempts < 5 ? 0 : (window + WINDOW_US - now + 999999LL) / 1000000LL;
if (ready && reserve && attempts < 5) {
s_window = window;
s_attempts = attempts + 1;
++s_counts.login_attempts;
}
taskEXIT_CRITICAL(&s_lock);
return ready;
}
static esp_err_t capacity(httpd_req_t *r)
{
if (httpd_resp_set_hdr(r, "Retry-After", "5") != ESP_OK) return ESP_FAIL;
return failure(r, "503 Service Unavailable", "capacity");
}
esp_err_t web_cookie_auth_start(void)
{
esp_err_t error = web_session_store_init();
taskENTER_CRITICAL(&s_lock);
if (error == ESP_OK && s_epoch != UINT64_MAX) {
++s_epoch;
secure_wipe(s_challenges, sizeof(s_challenges));
s_window = 0;
s_attempts = 0;
s_ready = true;
} else {
s_ready = false;
error = ESP_ERR_INVALID_STATE;
}
taskEXIT_CRITICAL(&s_lock);
return error;
}
void web_cookie_auth_stop(void)
{
taskENTER_CRITICAL(&s_lock);
s_ready = false;
if (s_epoch != UINT64_MAX) ++s_epoch;
secure_wipe(s_challenges, sizeof(s_challenges));
s_window = 0;
s_attempts = 0;
taskEXIT_CRITICAL(&s_lock);
web_session_store_stop();
}
void web_cookie_auth_get_snapshot(web_cookie_auth_snapshot_t *snapshot)
{
if (!snapshot) return;
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
*snapshot = s_counts;
snapshot->ready = s_ready;
snapshot->active_challenges = 0;
for (unsigned i = 0; i < 4; ++i) {
if (s_challenges[i].expiry <= now) secure_wipe(&s_challenges[i], sizeof(s_challenges[i]));
else ++snapshot->active_challenges;
}
taskEXIT_CRITICAL(&s_lock);
}
void web_cookie_auth_clear_counters(void)
{
taskENTER_CRITICAL(&s_lock);
memset(&s_counts, 0, sizeof(s_counts));
taskEXIT_CRITICAL(&s_lock);
}
static esp_err_t require(httpd_req_t *r, bool mutation, bool upgrade, size_t body_limit,
web_session_view_t *view, bool *allowed)
{
char canonical[129] = {0}, token[65] = {0}, csrf[65] = {0};
*allowed = false;
memset(view, 0, sizeof(*view));
if (!web_httpd_headers_valid(r) || !cookies_valid(r) || (!upgrade && strchr(r->uri, '?')) ||
r->content_len > body_limit || r->method != (mutation ? HTTP_POST : HTTP_GET))
return failure(r, "400 Bad Request", "invalid_request");
if (!origin(r, mutation || upgrade, canonical))
return failure(r, "403 Forbidden", "origin");
taskENTER_CRITICAL(&s_lock);
bool ready = s_ready;
taskEXIT_CRITICAL(&s_lock);
if (!ready) return failure(r, "503 Service Unavailable", "unavailable");
esp_err_t error = ESP_ERR_NOT_FOUND;
if (cookie(r, SESSION_COOKIE, token))
error = web_session_store_lookup(token, strlen(token), canonical, strlen(canonical), view);
secure_wipe(token, sizeof(token));
if (error != ESP_OK) {
if (error != ESP_ERR_NOT_FOUND)
return failure(r, "503 Service Unavailable", "unavailable");
if (!strcmp(r->uri, "/")) {
if (httpd_resp_set_hdr(r, "Location", "/login") != ESP_OK) return ESP_FAIL;
return response(r, "303 See Other", "");
}
return failure(r, "401 Unauthorized", "authentication_required");
}
if (mutation && (!header(r, "X-CSRF-Token", csrf, sizeof(csrf)) ||
strlen(csrf) != 64U || !equal(csrf, view->csrf, 64U))) {
secure_wipe(csrf, sizeof(csrf));
secure_wipe(view, sizeof(*view));
return failure(r, "403 Forbidden", "csrf");
}
secure_wipe(csrf, sizeof(csrf));
*allowed = true;
return ESP_OK;
}
esp_err_t web_cookie_auth_require(httpd_req_t *r, bool mutation, bool upgrade,
web_session_view_t *view, bool *allowed)
{
return require(r, mutation, upgrade, 0, view, allowed);
}
esp_err_t web_cookie_auth_require_json(httpd_req_t *r, size_t body_limit,
web_session_view_t *view, bool *allowed)
{
return require(r, true, false, body_limit, view, allowed);
}
static bool secret(char out[65])
{
uint8_t bytes[32];
bool ok = secure_random_fill(bytes, sizeof(bytes)) == ESP_OK;
if (ok) {
static const char hex[] = "0123456789abcdef";
for (size_t i = 0; i < sizeof(bytes); ++i) {
out[2*i] = hex[bytes[i] >> 4];
out[2*i+1] = hex[bytes[i] & 15];
}
out[64] = 0;
}
secure_wipe(bytes, sizeof(bytes));
return ok;
}
esp_err_t web_cookie_auth_handler(httpd_req_t *r)
{
bool login = !strcmp(r->uri, "/api/login");
bool bootstrap = !strcmp(r->uri, "/api/login-challenge");
bool logout = !strcmp(r->uri, "/api/logout");
bool document = !strcmp(r->uri, "/login");
web_session_view_t view = {0};
char canonical[129] = {0}, token[65] = {0}, csrf[65] = {0};
char set_cookie[180] = {0}, body[513] = {0}, retry_after[16] = {0};
int64_t retry = 0;
web_auth_credentials_t credentials = {0};
challenge_t candidate = {0};
uint8_t digest[32] = {0}, origin_digest[32] = {0};
esp_err_t result = ESP_FAIL;
const char *status = "400 Bad Request", *code = "invalid_request";
bool consumed = false, allowed = false;
bool challenge_published = false;
uint64_t epoch;
int selected = -1;
int64_t now = esp_timer_get_time();
taskENTER_CRITICAL(&s_lock);
bool ready = s_ready;
epoch = s_epoch;
taskEXIT_CRITICAL(&s_lock);
if (!ready) { status = "503 Service Unavailable"; code = "unavailable"; goto deny; }
if (!web_httpd_headers_valid(r) || !cookies_valid(r) || strchr(r->uri, '?') ||
r->method != ((login || logout) ? HTTP_POST : HTTP_GET) ||
(!login && r->content_len)) goto deny;
if (document) { result = web_login_ui_send_response(r); goto cleanup; }
if (!login && !bootstrap) {
result = web_cookie_auth_require(r, logout, false, &view, &allowed);
if (!allowed) goto cleanup;
if (logout) {
web_serial_transport_revoke_web_session(view.id);
taskENTER_CRITICAL(&s_lock);
++s_counts.logouts;
taskEXIT_CRITICAL(&s_lock);
result = httpd_resp_set_hdr(r, "Set-Cookie", SESSION_COOKIE "=" COOKIE_FLAGS "0");
if (result != ESP_OK) goto cleanup;
result = response(r, "204 No Content", "");
} else {
/* Database usernames are restricted ASCII; encode nevertheless. */
char username[97] = {0};
size_t used = 0;
for (size_t i = 0; i < view.principal.username_length && i < 16; ++i)
used += (size_t)snprintf(username + used, sizeof(username) - used,
"\\u%04x", (unsigned char)view.principal.username[i]);
int64_t remaining = (view.expires_at_us - esp_timer_get_time()) / 1000000LL;
snprintf(body, sizeof(body), "{\"username\":\"%s\",\"role\":\"%s\",\"csrf\":\"%s\",\"expires_in\":%lld}",
username, view.principal.role == USER_ROLE_ADMIN ? "admin" : "user", view.csrf,
(long long)(remaining > 0 ? remaining : 0));
result = response(r, "200 OK", body);
}
goto cleanup;
}
if (!origin(r, login, canonical)) { status = "403 Forbidden"; code = "origin"; goto deny; }
if (mbedtls_sha256((const uint8_t *)canonical, strlen(canonical), origin_digest, 0)) goto deny;
if (bootstrap) {
char flag[2];
if (!header(r, "X-Login-Bootstrap", flag, sizeof(flag)) || strcmp(flag, "1")) {
status = "403 Forbidden"; code = "csrf"; goto deny;
}
} else {
char type[40];
if (!header(r, "Content-Type", type, sizeof(type)) ||
(strcmp(type, "application/json") && strcmp(type, "application/json; charset=utf-8"))) {
status = "415 Unsupported Media Type"; code = "content_type"; goto deny;
}
if (!r->content_len || r->content_len > 512U) {
status = "413 Payload Too Large"; code = "body_size"; goto deny;
}
if (cookie(r, SESSION_COOKIE, token) &&
web_session_store_lookup(token, 64, canonical, strlen(canonical), &view) == ESP_OK) {
status = "409 Conflict"; code = "already_authenticated"; goto deny;
}
if (!header(r, "X-CSRF-Token", csrf, sizeof(csrf)) || strlen(csrf) != 64) {
status = "403 Forbidden"; code = "csrf"; goto deny;
}
}
bool has_cookie = cookie(r, PRELOGIN_COOKIE, token);
if (has_cookie && mbedtls_sha256((const uint8_t *)token, 64, digest, 0)) goto deny;
taskENTER_CRITICAL(&s_lock);
for (int i = 0; i < 4; ++i) {
challenge_t *entry = &s_challenges[i];
if (entry->expiry <= now) secure_wipe(entry, sizeof(*entry));
if (s_ready && epoch == s_epoch && entry->expiry && has_cookie &&
equal(entry->token_digest, digest, 32) && equal(entry->origin_digest, origin_digest, 32)) {
if (bootstrap || equal(entry->csrf, csrf, 64)) {
candidate = *entry;
selected = i;
if (login) { secure_wipe(entry, sizeof(*entry)); consumed = true; }
}
}
}
taskEXIT_CRITICAL(&s_lock);
if (bootstrap) {
bool fresh = selected < 0;
if (fresh) {
if (!secret(token) || !secret(candidate.csrf) ||
mbedtls_sha256((const uint8_t *)token, 64, candidate.token_digest, 0)) {
status = "503 Service Unavailable"; code = "unavailable"; goto deny;
}
memcpy(candidate.origin_digest, origin_digest, 32);
candidate.expiry = now + CHALLENGE_US;
taskENTER_CRITICAL(&s_lock);
if (s_ready && epoch == s_epoch) for (int i = 0; i < 4; ++i) {
if (!s_challenges[i].expiry) {
s_challenges[i] = candidate; selected = i; challenge_published = true; break;
}
}
taskEXIT_CRITICAL(&s_lock);
if (selected < 0) { result = capacity(r); goto cleanup; }
snprintf(set_cookie, sizeof(set_cookie), PRELOGIN_COOKIE "=%s" COOKIE_FLAGS "120", token);
if (httpd_resp_set_hdr(r, "Set-Cookie", set_cookie) != ESP_OK) goto cleanup;
}
snprintf(body, sizeof(body), "{\"csrf\":\"%s\",\"expires_in\":%lld}", candidate.csrf,
(long long)((candidate.expiry - now) / 1000000LL));
result = response(r, "200 OK", body);
goto cleanup;
}
if (!consumed) { status = "403 Forbidden"; code = "challenge_expired"; goto deny; }
if (httpd_resp_set_hdr(r, "Set-Cookie", PRELOGIN_COOKIE "=" COOKIE_FLAGS "0") != ESP_OK) goto cleanup;
if (!verification_budget(epoch, false, &retry)) {
status = "503 Service Unavailable"; code = "unavailable"; goto deny;
}
if (retry) goto throttled;
size_t received = 0;
int64_t deadline = now + 3000000LL;
while (received < r->content_len && esp_timer_get_time() < deadline) {
int count = httpd_req_recv(r, body + received, r->content_len - received);
if (count <= 0) goto deny;
received += (size_t)count;
}
if (received != r->content_len || !web_auth_parse_login(body, received, &credentials)) goto deny;
secure_wipe(body, sizeof(body));
if (!verification_budget(epoch, true, &retry)) {
status = "503 Service Unavailable"; code = "unavailable"; goto deny;
}
if (retry) goto throttled;
bool authenticated = false;
user_principal_t principal = {0};
esp_err_t error = user_database_authenticate_password(credentials.username, credentials.username_length,
credentials.password, credentials.password_length, &principal, &authenticated);
secure_wipe(&credentials, sizeof(credentials));
if (error == ESP_OK && authenticated)
error = web_session_store_issue(&principal, canonical, strlen(canonical), token, &view);
secure_wipe(&principal, sizeof(principal));
if (error == ESP_ERR_NO_MEM) { result = capacity(r); goto cleanup; }
if (error != ESP_OK) { status = "503 Service Unavailable"; code = "unavailable"; goto deny; }
if (!authenticated) { status = "401 Unauthorized"; code = "invalid_credentials"; goto deny; }
snprintf(set_cookie, sizeof(set_cookie), SESSION_COOKIE "=%s" COOKIE_FLAGS "3600", token);
if (httpd_resp_set_hdr(r, "Set-Cookie", set_cookie) != ESP_OK) {
web_session_store_invalidate(view.id); goto cleanup;
}
result = response(r, "200 OK", "{\"authenticated\":true}");
if (result != ESP_OK) web_session_store_invalidate(view.id);
goto cleanup;
throttled:
status = "429 Too Many Requests"; code = "throttled";
snprintf(retry_after, sizeof(retry_after), "%lld", (long long)retry);
if (httpd_resp_set_hdr(r, "Retry-After", retry_after) != ESP_OK) goto cleanup;
deny:
secure_wipe(body, sizeof(body));
secure_wipe(&credentials, sizeof(credentials));
result = failure(r, status, code);
cleanup:
if (challenge_published && result != ESP_OK) {
taskENTER_CRITICAL(&s_lock);
if (epoch == s_epoch && selected >= 0 &&
equal(s_challenges[selected].token_digest, candidate.token_digest, 32))
secure_wipe(&s_challenges[selected], sizeof(s_challenges[selected]));
taskEXIT_CRITICAL(&s_lock);
}
web_httpd_wipe_request(r, web_httpd_unread_body(r));
secure_wipe(&view, sizeof(view));
secure_wipe(token, sizeof(token));
secure_wipe(csrf, sizeof(csrf));
secure_wipe(set_cookie, sizeof(set_cookie));
secure_wipe(body, sizeof(body));
secure_wipe(&credentials, sizeof(credentials));
secure_wipe(&candidate, sizeof(candidate));
secure_wipe(digest, sizeof(digest));
return result;
}
+22
View File
@@ -0,0 +1,22 @@
/* SPDX-License-Identifier: GPL-3.0-only */
#pragma once
#include "esp_http_server.h"
#include "web_session_store.h"
esp_err_t web_cookie_auth_start(void);
void web_cookie_auth_stop(void);
typedef struct {
uint32_t login_attempts, login_failures, throttled, capacity_rejections;
uint32_t security_rejections, logouts, active_challenges;
bool ready;
} web_cookie_auth_snapshot_t;
void web_cookie_auth_get_snapshot(web_cookie_auth_snapshot_t *snapshot);
void web_cookie_auth_clear_counters(void);
/* Sends an error on denial, with allowed=false. View is caller-wiped. */
esp_err_t web_cookie_auth_require(httpd_req_t *request, bool mutation,
bool upgrade, web_session_view_t *view,
bool *allowed);
esp_err_t web_cookie_auth_handler(httpd_req_t *request);
/* Same mutation policy, allowing a bounded body; caller validates JSON/content type. */
esp_err_t web_cookie_auth_require_json(httpd_req_t *request, size_t body_limit,
web_session_view_t *view, bool *allowed);

Some files were not shown because too many files have changed in this diff Show More