apex-twin 1.14.0: ESP32 flash analysis and mount audit

ESP32 offline (tools_esp.c):
- esp_partition_table: parse the 32-byte entries at 0x8000 (magic 0xAA50),
  type/subtype names, offset, size, flags and the MD5 entry.
- esp_nvs_parse: NVS pages (version byte 0xFE), namespace records (type 0x01,
  nsIndex 0) and key records with namespace, type and span.
- firmware_scan: signatures (ESP app header 0xE9, partition table, NVS page,
  littlefs/spiffs/FAT32, PEM), 4 KiB block entropy with integer-only log2 and
  printable strings with samples. All read local dumps with size caps.

Blue:
- mount_audit: parses a mount table and flags /tmp, /var/tmp and /dev/shm
  without nosuid/nodev/noexec and /home, /run/user, /media, /mnt without
  nosuid/nodev, with the missing option list and severity.

Tests with locally built binary fixtures: a partition dump with two entries and
an MD5 record, an NVS page with one namespace and two keys, a firmware image
with all four signatures plus a random high-entropy block, and a mount table
with hardened and unhardened entries. 627 checks, ASan suite green, analyze
clean, release-check green including distcheck 1.14.0.
This commit is contained in:
lotherk committed 2026-11-21 14:38:18 +00:00
1 parent 4962002e13
commit d829955d88
9 files changed
+783 -18

No files matched your search

+19 -1
View File
@@ -8,7 +8,25 @@ fields, and state from an older version is read by a newer one.
There are no git tags. The hash next to a version is the commit that introduced
it; the current entry is the commit that adds this section.
## 1.13.0 — 2026-11-21 — this change
## 1.14.0 — 2026-11-21 — this change
- **ESP32 offline analysis** (`tools_esp.c`): `esp_partition_table` parses the
32-byte partition entries at 0x8000 (magic 0xAA50) with type/subtype names,
offset, size, flags and the MD5 entry. `esp_nvs_parse` reads NVS pages
(version byte 0xFE) and reports namespaces (type 0x01, nsIndex 0) plus every
key with its namespace, type and span. `firmware_scan` reports signatures
(ESP app header 0xE9, partition table, NVS page, littlefs/spiffs/FAT32,
PEM certificates), 4 KiB block entropy (integer-only log2) and printable
strings. All read a local dump with size caps; no device is touched.
- **Blue** (`mount_audit`): parses a mount table and flags /tmp, /var/tmp and
/dev/shm without nosuid/nodev/noexec and /home, /run/user, /media, /mnt
without nosuid/nodev, with the missing option list and a severity.
- Tests with locally built binary fixtures: a partition dump with two entries
and an MD5 record, an NVS page with one namespace and two keys, a firmware
image with all four signatures plus a random high-entropy block, and a mount
table with hardened and unhardened entries. 627 checks. Coverage 79.4%.
## 1.13.0 — 2026-11-21 — 4962002
- **POP3** (`pop3_probe`): banner, CAPA capability list (STLS flagged), then
QUIT. No USER/PASS and no login.
+16 -9
View File
@@ -5,11 +5,11 @@ no Python in the serving path. It gives an agent real reconnaissance and real we
testing behind a scope gate that refuses everything until a rules-of-engagement
file says otherwise.
**100 tools · 615 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~461 KiB**
**104 tools · 627 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~473 KiB**
```
$ ./apex-twin --check
{"version":"1.13.0","tools":100,...,"scope":{"loaded":true,...}}
{"version":"1.14.0","tools":104,...,"scope":{"loaded":true,...}}
```
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
@@ -149,7 +149,7 @@ closes a request whose head or body does not arrive within
---
## Tools (100)
## Tools (104)
### Scope and bookkeeping
@@ -302,6 +302,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `cap_baseline` | File capability xattr manifest (`create`/`verify`); reports new, gone and changed capability sets |
| `module_audit` | Loaded modules and taint letters, kernel taint bits decoded (proprietary, out-of-tree, unsigned, ...) |
| `package_integrity` | `dpkg -V` / `rpm -V` changed files, optionally one package or a saved verify output |
| `mount_audit` | Mount table hardening: temp/shm mounts missing nosuid/nodev/noexec, home/media/mnt missing nosuid/nodev |
### ESP32
@@ -311,6 +312,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `esp_monitor` | Read the console for N seconds; sends nothing |
| `esp_read_flash` | Dump up to 4 MiB of flash into `evidence/` with `esptool read_flash` |
| `esp_flash` | `esptool write_flash` with mandatory `confirm=true`, absolute image, audited |
| `esp_partition_table` | Parse a flash dump's partition table at 0x8000 (0xAA50 entries, MD5 entry) |
| `esp_nvs_parse` | Parse an NVS partition dump: namespaces, keys, types, spans |
| `firmware_scan` | Signatures (ESP app, partition table, NVS, filesystems, PEM), 4 KiB entropy, strings |
### Method
@@ -503,6 +507,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| Module audit | 500 modules; /proc and /sys reads only |
| POP3/SIP/Telnet | one connection or datagram each; no login |
| Package verify | 300 s cap; one package when requested |
| Flash analysis | reads a local dump, 8/16/32 MiB caps |
| Mount audit | 500 mounts; reads a table, not the filesystem |
---
@@ -513,7 +519,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 615 end-to-end checks
make test # version check + gate audit + 627 end-to-end checks
make version-check # the five places that carry a version must agree
make gate-audit # static: every target-taking tool calls the gate
make asan # apex-twin-asan with ASan + UBSan
@@ -626,8 +632,9 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit,
detect_rules, integrity_baseline, mitre_map,
process_snapshot, persistence_audit, net_baseline,
ssh_key_audit, suid_baseline, cap_baseline, module_audit,
package_integrity
src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash
package_integrity, mount_audit
src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash,
esp_partition_table, esp_nvs_parse, firmware_scan
src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit,
redis_probe, snmp_probe, dns_zone_transfer
src/tools_db.c mysql_probe, postgres_probe, mongo_probe,
@@ -661,7 +668,7 @@ examples/ scope.json
## Status
1.13.0. Built and run: 100 tools, 615 checks, 340 fuzz cases and 79.4% line
1.14.0. Built and run: 104 tools, 627 checks, 340 fuzz cases and 79.4% line
coverage. The loop closes: a probe captures the exchange as a pair, a finding
points at it, `finding_update` gives it a state, an asset records the host it
came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
@@ -692,8 +699,8 @@ and LDAP probes plus an SSH key audit; 1.10 added RDP and SMB negotiation checks
and a SUID baseline; 1.11 added VNC, MQTT and GraphQL checks plus a file
capability baseline; 1.12 added Docker, Elasticsearch and IMAP checks plus a
kernel module/taint audit; 1.13 added POP3, SIP and Telnet checks plus package
integrity verification, again without changing an existing tool or file
format.
integrity verification; 1.14 added offline ESP32 flash analysis and a mount
audit, again without changing an existing tool or file format.
Not yet wired into a fleet router, and there is no TLS interception.
+5 -1
View File
@@ -9,7 +9,7 @@ problem.
The supported line is the one printed by `apex-twin --version` for the tree you
built; this document ships with that same tree. At the time of writing the line
is **1.13.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.14.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
line. The 1.0 line promises that the on-disk JSON formats for findings, assets
and traffic only gain fields, so state stays readable; older builds are still
rebuilt rather than patched in place.
@@ -66,6 +66,10 @@ only narrow what the proxy does (the scope gate still runs first).
- **Firmware writing needs an explicit confirmation.** `esp_flash` refuses
without `confirm=true`, validates an absolute image path and audits the
attempt; it exists to provision the operator's own board.
- **Firmware analysis reads local files only.** `esp_partition_table`,
`esp_nvs_parse` and `firmware_scan` open a dump the operator supplies, cap it
at 8/16/32 MiB and never touch a device. `mount_audit` reads a mount table
(the live one or a saved copy).
- **Mail and telephony probes stop at the greeting.** `pop3_probe` reads the
banner and CAPA and quits; `sip_probe` sends one OPTIONS and reads the answer;
`telnet_probe` sends nothing at all. `package_integrity` verifies installed
+4 -3
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.13.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.14.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -45,8 +45,9 @@ graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe,
sip_probe, telnet_probe), defensive audits (hardening_audit, log_audit,
ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map,
process_snapshot, persistence_audit, net_baseline, ssh_key_audit,
suid_baseline, cap_baseline, module_audit, package_integrity) and ESP32 board
tools (esp_info, esp_monitor, esp_read_flash, esp_flash).
suid_baseline, cap_baseline, module_audit, package_integrity, mount_audit) and
ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash,
esp_partition_table, esp_nvs_parse, firmware_scan).
.SH MODES
.TP
.B apex-twin
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.13.0"
#define APEX_VERSION "1.14.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+128
View File
@@ -3408,6 +3408,122 @@ static void t_package_integrity(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&files);
}
/* ---------------------------------------------------------------- mount_audit */
static int mount_has_opt(const char *opts, const char *want)
{
const char *p = opts;
size_t wl = strlen(want);
while (p != NULL && *p != '\0') {
const char *comma = strchr(p, ',');
size_t len = comma != NULL ? (size_t)(comma - p) : strlen(p);
if (len == wl && strncmp(p, want, wl) == 0)
return 1;
p = comma != NULL ? comma + 1 : NULL;
}
return 0;
}
static int mount_needs(const char *mount, const char **opts, int extra_exec)
{
if (strcmp(mount, "/tmp") == 0 || strncmp(mount, "/tmp/", 5) == 0 ||
strcmp(mount, "/var/tmp") == 0 ||
strncmp(mount, "/var/tmp/", 9) == 0 ||
strcmp(mount, "/dev/shm") == 0 ||
strncmp(mount, "/dev/shm/", 9) == 0) {
opts[0] = "nosuid";
opts[1] = "nodev";
opts[2] = extra_exec ? "noexec" : NULL;
return 1;
}
if (strcmp(mount, "/home") == 0 || strncmp(mount, "/home/", 6) == 0 ||
strncmp(mount, "/run/user", 9) == 0 ||
strcmp(mount, "/media") == 0 || strncmp(mount, "/media/", 7) == 0 ||
strcmp(mount, "/mnt") == 0 || strncmp(mount, "/mnt/", 5) == 0) {
opts[0] = "nosuid";
opts[1] = "nodev";
opts[2] = NULL;
return 1;
}
return 0;
}
static void t_mount_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
int limit = mcp_arg_int(args, "limit", 500);
FILE *f;
char *line = NULL;
size_t cap = 0;
mcp_buf b;
int first = 1;
int mounts = 0;
int findings = 0;
(void)user;
if (path == NULL || *path == '\0')
path = "/proc/mounts";
if (limit <= 0 || limit > 5000)
limit = 500;
f = fopen(path, "rb");
if (f == NULL) {
mcp_reply_error(c, "cannot read the mount table");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_puts(&b, ",\"findings\":[");
while (mounts < limit && getline(&line, &cap, f) >= 0) {
char dev[256];
char mount[512];
char fstype[64];
char opts[1024];
const char *needed[3];
const char *missing[3];
int nmissing = 0;
int extra_exec;
int k;
if (sscanf(line, "%255s %511s %63s %1023s", dev, mount, fstype,
opts) != 4)
continue;
mounts++;
extra_exec = 1;
if (!mount_needs(mount, needed, extra_exec))
continue;
for (k = 0; k < 3 && needed[k] != NULL; k++)
if (!mount_has_opt(opts, needed[k]))
missing[nmissing++] = needed[k];
if (nmissing == 0)
continue;
findings++;
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"mount\":");
apex_json_str(&b, mount);
mcp_buf_puts(&b, ",\"fstype\":");
apex_json_str(&b, fstype);
mcp_buf_puts(&b, ",\"missing\":[");
for (k = 0; k < nmissing; k++) {
if (k > 0)
mcp_buf_puts(&b, ",");
apex_json_str(&b, missing[k]);
}
mcp_buf_printf(&b, "],\"severity\":\"%s\"}",
nmissing >= 2 ? "medium" : "low");
}
free(line);
fclose(f);
mcp_buf_printf(&b, "],\"mounts\":%d,\"findings_count\":%d}", mounts,
findings);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_BLUE[] = {
{ "hardening_audit",
"Read-only posture audit of the local host: sshd_config (root login, "
@@ -3600,6 +3716,18 @@ const mcp_tool TOOLS_BLUE[] = {
"\"limit\":{\"type\":\"integer\",\"description\":\"files to return, "
"default 200\"}}}",
t_package_integrity },
{ "mount_audit",
"Parse a mount table (/proc/mounts by default, or a saved copy from a "
"mounted image) and flag filesystems that should be hardened: /tmp, "
"/var/tmp and /dev/shm without nosuid, nodev or noexec; /home, /run/user, "
"/media and /mnt without nosuid or nodev. Reports each mount with its "
"missing options and a severity. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"default "
"/proc/mounts\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"mounts to read, "
"default 500\"}}}",
t_mount_audit },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+489
View File
@@ -5,6 +5,10 @@
* VID/PID when sysfs exposes it
* esp_monitor read the serial console for N seconds (no commands sent)
* esp_read_flash dump the flash to an evidence file with esptool
* esp_flash write a firmware image (confirm=true required)
* esp_partition_table parse a flash dump's partition table at 0x8000
* esp_nvs_parse parse an NVS partition dump: namespaces and keys
* firmware_scan signatures, entropy and strings of a firmware dump
*
* The Marauder bridge in tools_radio.c covers the radio firmware; these tools
* cover the board itself: what is it, what does it print, and what is on it.
@@ -13,6 +17,7 @@
*/
#include <errno.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -367,6 +372,460 @@ static void t_esp_flash(mcp_conn *c, const mcp_json *args, void *user)
}
}
/* ------------------------------------------------------- offline flash tools */
static uint16_t esp_le16(const unsigned char *p)
{
return (uint16_t)(p[0] | (p[1] << 8));
}
static uint32_t esp_le32(const unsigned char *p)
{
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}
static unsigned char *esp_read_all(const char *path, size_t cap, size_t *len)
{
FILE *f;
struct stat st;
unsigned char *buf;
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 ||
(unsigned long)st.st_size > cap)
return NULL;
f = fopen(path, "rb");
if (f == NULL)
return NULL;
buf = malloc((size_t)st.st_size);
if (buf == NULL) {
fclose(f);
return NULL;
}
if (fread(buf, 1, (size_t)st.st_size, f) != (size_t)st.st_size) {
free(buf);
fclose(f);
return NULL;
}
fclose(f);
*len = (size_t)st.st_size;
return buf;
}
static const char *esp_part_type(unsigned int type, unsigned int subtype)
{
static char buf[32];
if (type == 0) {
if (subtype == 0)
return "factory";
if (subtype >= 0x10 && subtype <= 0x1f) {
snprintf(buf, sizeof(buf), "ota_%u", subtype - 0x10);
return buf;
}
if (subtype == 0x20)
return "test";
return "app";
}
if (type == 1) {
switch (subtype) {
case 0:
return "ota";
case 1:
return "phy";
case 2:
return "nvs";
case 3:
return "coredump";
case 4:
return "nvs_keys";
case 5:
return "efuse";
case 0x80:
return "esphttpd";
case 0x81:
return "fat";
case 0x82:
return "spiffs";
case 0x83:
return "littlefs";
default:
return "data";
}
}
return "unknown";
}
static void t_esp_partition_table(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
int offset = mcp_arg_int(args, "offset", 0x8000);
unsigned char *buf = NULL;
size_t len = 0;
size_t need;
mcp_buf b;
int first = 1;
int i;
int count = 0;
char md5[33];
(void)user;
if (path == NULL || *path == '\0') {
mcp_reply_error(c, "path is required");
return;
}
if (offset < 0 || offset > (16 << 20)) {
mcp_reply_error(c, "offset out of range (0..16777216)");
return;
}
buf = esp_read_all(path, 32UL << 20, &len);
if (buf == NULL) {
mcp_reply_error(c, "cannot read the dump (max 32 MiB)");
return;
}
if ((size_t)offset >= len) {
free(buf);
mcp_reply_error(c, "offset is past the end of the file");
return;
}
need = 32 * 33;
if (len - (size_t)offset < need)
need = len - (size_t)offset;
md5[0] = '\0';
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"offset\":%d,\"partitions\":[", offset);
for (i = 0; (size_t)(i * 32 + 32) <= need; i++) {
const unsigned char *e = buf + offset + i * 32;
uint16_t magic = esp_le16(e);
char label[17];
size_t w = 0;
if (magic == 0xebeb) {
int k;
for (k = 0; k < 16; k++)
snprintf(md5 + k * 2, 3, "%02x", e[16 + k]);
md5[32] = '\0';
break;
}
if (magic != 0xaa50)
break;
while (w < 16 && e[12 + w] != 0 && e[12 + w] != 0xff)
w++;
memcpy(label, e + 12, w);
label[w] = '\0';
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
count++;
mcp_buf_puts(&b, "{\"label\":");
apex_json_str(&b, label);
mcp_buf_printf(&b, ",\"type\":%u,\"subtype\":%u,\"kind\":",
e[2], e[3]);
apex_json_str(&b, esp_part_type(e[2], e[3]));
mcp_buf_printf(&b, ",\"offset\":%lu,\"size\":%lu,\"flags\":%lu}",
(unsigned long)esp_le32(e + 4),
(unsigned long)esp_le32(e + 8),
(unsigned long)esp_le32(e + 24));
}
free(buf);
mcp_buf_printf(&b, "],\"count\":%d,\"md5\":", count);
if (md5[0] != '\0')
apex_json_str(&b, md5);
else
mcp_buf_puts(&b, "null");
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static const char *nvs_type_name(unsigned int t)
{
switch (t) {
case 0x01:
return "u8";
case 0x02:
return "u16";
case 0x04:
return "u32";
case 0x08:
return "u64";
case 0x11:
return "i8";
case 0x12:
return "i16";
case 0x14:
return "i32";
case 0x18:
return "i64";
case 0x21:
return "string";
case 0x41:
return "blob";
case 0x42:
return "blob-data";
case 0x48:
return "blob-index";
default:
return "unknown";
}
}
static void t_esp_nvs_parse(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
unsigned char *buf = NULL;
size_t len = 0;
size_t pages;
size_t pg;
char names[32][17];
int nnames = 0;
mcp_buf keys;
mcp_buf b;
int key_count = 0;
int first = 1;
(void)user;
if (path == NULL || *path == '\0') {
mcp_reply_error(c, "path is required");
return;
}
buf = esp_read_all(path, 8UL << 20, &len);
if (buf == NULL) {
mcp_reply_error(c, "cannot read the NVS dump (max 8 MiB)");
return;
}
pages = len / 4096;
mcp_buf_init(&keys);
for (pg = 0; pg < pages; pg++) {
const unsigned char *p = buf + pg * 4096;
int j;
if (p[8] != 0xfe)
continue;
for (j = 0; j < 126; j++) {
const unsigned char *e = p + 32 + j * 32;
unsigned int ns = e[0];
unsigned int type = e[1];
char key[17];
size_t w = 0;
if (e[0] == 0xff && e[1] == 0xff)
break;
if (type == 0)
continue;
while (w < 16 && e[8 + w] != 0 && e[8 + w] != 0xff)
w++;
memcpy(key, e + 8, w);
key[w] = '\0';
if (w == 0)
continue;
if (type == 0x01 && ns == 0) {
int k;
int known = 0;
for (k = 0; k < nnames; k++)
if (strcmp(names[k], key) == 0)
known = 1;
if (!known && nnames < 32)
snprintf(names[nnames++], sizeof(names[0]),
"%s", key);
continue;
}
if (!first)
mcp_buf_puts(&keys, ",");
first = 0;
key_count++;
mcp_buf_puts(&keys, "{\"namespace\":");
apex_json_str(&keys,
(int)ns > 0 && (int)ns <= nnames
? names[ns - 1] : "");
mcp_buf_puts(&keys, ",\"key\":");
apex_json_str(&keys, key);
mcp_buf_puts(&keys, ",\"type\":");
apex_json_str(&keys, nvs_type_name(type));
mcp_buf_printf(&keys, ",\"span\":%u,\"ns_index\":%u}", e[2],
ns);
}
}
free(buf);
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"pages\":%lu,\"namespaces\":[",
(unsigned long)pages);
{
int i;
for (i = 0; i < nnames; i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
apex_json_str(&b, names[i]);
}
}
mcp_buf_printf(&b, "],\"key_count\":%d,\"keys\":[", key_count);
if (keys.p != NULL)
mcp_buf_add(&b, keys.p, keys.len);
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
mcp_buf_free(&keys);
}
/* integer-only log2 in Q8, enough for an entropy threshold */
static unsigned long esp_log2_q8(unsigned long n)
{
unsigned long base = 0;
unsigned long pow = 1;
if (n == 0)
return 0;
while (pow * 2 <= n) {
pow *= 2;
base++;
}
return (base << 8) + (((n - pow) << 8) / pow);
}
static void t_firmware_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
unsigned char *buf = NULL;
size_t len = 0;
mcp_buf b;
int first = 1;
int blocks = 0;
int high = 0;
unsigned long max_h = 0;
unsigned long sum_h = 0;
int strings = 0;
char samples[20][72];
int nsamples = 0;
size_t i;
int sig_count = 0;
(void)user;
if (path == NULL || *path == '\0') {
mcp_reply_error(c, "path is required");
return;
}
buf = esp_read_all(path, 16UL << 20, &len);
if (buf == NULL) {
mcp_reply_error(c, "cannot read the image (max 16 MiB)");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"size\":%lu,\"signatures\":[",
(unsigned long)len);
#define SIG_ADD(off, name) do { \
if (!first) mcp_buf_puts(&b, ","); \
first = 0; \
sig_count++; \
mcp_buf_printf(&b, "{\"offset\":%lu,\"name\":\"%s\"}", \
(unsigned long)(off), name); \
} while (0)
if (len >= 8 && buf[0] == 0xe9)
SIG_ADD(0, "esp-app");
if (len > 0x8000 + 32 && esp_le16(buf + 0x8000) == 0xaa50)
SIG_ADD(0x8000, "partition-table");
for (i = 0; i + 32 < len; i += 4096) {
if (buf[i + 8] == 0xfe) {
SIG_ADD(i, "nvs");
break;
}
}
{
static const struct {
const char *needle;
const char *name;
} marks[] = {
{ "littlefs", "littlefs" },
{ "spiffs", "spiffs" },
{ "FAT32", "fat32" },
{ "BEGIN CERTIFICATE", "pem-certificate" },
{ NULL, NULL }
};
int m;
for (m = 0; marks[m].needle != NULL; m++) {
const char *hit = memmem(buf, len, marks[m].needle,
strlen(marks[m].needle));
if (hit != NULL)
SIG_ADD((size_t)(hit - (const char *)buf), marks[m].name);
}
}
#undef SIG_ADD
mcp_buf_printf(&b, "],\"signature_count\":%d,\"entropy\":{\"block\":4096,"
"\"blocks\":", sig_count);
for (i = 0; i + 4096 <= len; i += 4096) {
unsigned long counts[256];
unsigned long sq = 0;
unsigned long h;
int k;
memset(counts, 0, sizeof(counts));
for (k = 0; k < 4096; k++)
counts[buf[i + k]]++;
for (k = 0; k < 256; k++)
if (counts[k] > 0)
sq += counts[k] * esp_log2_q8(counts[k]);
h = (12UL << 8) - (sq >> 12);
blocks++;
sum_h += h;
if (h > max_h)
max_h = h;
if (h > (7UL << 8) + 128)
high++;
}
{
unsigned long avg = blocks > 0 ? sum_h / (unsigned long)blocks : 0;
mcp_buf_printf(&b, "%d,\"average_x100\":%lu,\"max_x100\":%lu,"
"\"high_blocks\":%d},", blocks, avg * 100 / 256,
max_h * 100 / 256, high);
}
/* printable runs of 8 or more bytes */
for (i = 0; i < len;) {
size_t start = i;
size_t run;
while (i < len && buf[i] >= 0x20 && buf[i] < 0x7f)
i++;
run = i - start;
if (run >= 8) {
strings++;
if (nsamples < 20) {
size_t n = run < 64 ? run : 64;
memcpy(samples[nsamples], buf + start, n);
samples[nsamples][n] = '\0';
nsamples++;
}
} else if (i == start) {
i++;
}
}
mcp_buf_printf(&b, "\"strings\":{\"count\":%d,\"samples\":[", strings);
{
int k;
for (k = 0; k < nsamples; k++) {
if (k > 0)
mcp_buf_puts(&b, ",");
apex_json_str(&b, samples[k]);
}
}
mcp_buf_puts(&b, "]}}");
free(buf);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_ESP[] = {
{ "esp_info",
"Identify the attached ESP32 family board: run esptool chip_id on the "
@@ -408,6 +867,36 @@ const mcp_tool TOOLS_ESP[] = {
"\"confirm\":{\"type\":\"boolean\",\"description\":\"must be true\"}},"
"\"required\":[\"image\",\"confirm\"]}",
t_esp_flash },
{ "esp_partition_table",
"Parse an ESP32 flash dump offline: read the partition table at 0x8000 "
"(32-byte entries, magic 0xAA50) and report each label, type/subtype, "
"offset, size and flags, plus the MD5 entry when present. The offset is "
"adjustable for an already extracted table. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"flash dump file\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"default 32768 "
"(0x8000)\"}},"
"\"required\":[\"path\"]}",
t_esp_partition_table },
{ "esp_nvs_parse",
"Parse an NVS partition dump offline: page version 0xFE, 32-byte entries, "
"namespace records (type 0x01, nsIndex 0) and key records with their "
"namespace, type and span. Keys and namespace names are reported, values "
"are not decoded. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"NVS partition "
"dump\"}},"
"\"required\":[\"path\"]}",
t_esp_nvs_parse },
{ "firmware_scan",
"Scan a firmware image offline: signatures (ESP app header at 0xE9, "
"partition table at 0x8000, NVS page, littlefs/spiffs/FAT32 strings, PEM "
"certificates), 4 KiB block entropy (average, max, high blocks) and "
"printable strings with samples. Read-only; the file is capped at 16 MiB.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"firmware dump\"}},"
"\"required\":[\"path\"]}",
t_firmware_scan },
};
const size_t TOOLS_ESP_N = sizeof(TOOLS_ESP) / sizeof(TOOLS_ESP[0]);
+1 -1
View File
@@ -21,7 +21,7 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 100
EXPECTED_TOOLS = 104
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
+120 -2
View File
@@ -134,7 +134,7 @@ res, _ = run([
], home=empty)
check("tools/list answers", any(r.get("id") == 1 for r in res))
tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"]
check("100 tools registered", len(tools) == 100, len(tools))
check("104 tools registered", len(tools) == 104, len(tools))
names = {t["name"] for t in tools}
for need in ("portscan", "nmap", "http_request", "marauder_scan",
"method_playbook", "finding_add", "finding_update", "scope_check",
@@ -1560,7 +1560,7 @@ try:
check("http initialize", init["result"]["serverInfo"]["name"] == "apex-twin",
init)
listing = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
check("http tools/list", len(listing["result"]["tools"]) == 100)
check("http tools/list", len(listing["result"]["tools"]) == 104)
shown = post(call(3, "scope_show"))
check("http scope_show", '"loaded":true' in shown["result"]["content"][0]["text"])
# the id must be the request's id, not one found inside the arguments
@@ -4679,6 +4679,124 @@ sip_stop.set()
sip_sock.close()
shutil.rmtree(pkg_home, ignore_errors=True)
print("\n== ESP flash analysis and mount audit ==")
def esp_part_entry(label, ptype, subtype, offset, size, flags):
raw = struct.pack("<HBBII", 0xAA50, ptype, subtype, offset, size)
raw += label.encode().ljust(16, b"\x00")
raw += struct.pack("<I", flags)
return raw
flash_dump = bytearray(0x8000)
flash_dump += esp_part_entry("nvs", 1, 2, 0x9000, 0x6000, 0)
flash_dump += esp_part_entry("ota_0", 0, 0x10, 0x10000, 0x100000, 0)
flash_dump += (struct.pack("<H", 0xEBEB) + b"\xff" * 14 +
bytes(range(16)))
flash_path = os.path.join(tempfile.mkdtemp(prefix="apex-flash-"), "dump.bin")
with open(flash_path, "wb") as f:
f.write(flash_dump)
def nvs_entry(ns, typ, span, key):
raw = bytearray(32)
raw[0] = ns
raw[1] = typ
raw[2] = span
raw[3] = 0
raw[8:8 + len(key)] = key.encode()
return bytes(raw)
nvs_page = bytearray(4096)
struct.pack_into("<I", nvs_page, 0, 0xFFFFFFFE)
struct.pack_into("<I", nvs_page, 4, 1)
nvs_page[8] = 0xFE
nvs_page[32:64] = nvs_entry(0, 0x01, 1, "wifi")
nvs_page[64:96] = nvs_entry(1, 0x42, 1, "ssid")
nvs_page[96:128] = nvs_entry(1, 0x42, 1, "password")
nvs_path = os.path.join(os.path.dirname(flash_path), "nvs.bin")
with open(nvs_path, "wb") as f:
f.write(nvs_page)
firmware = bytearray(0x12000)
firmware[0] = 0xE9
firmware[1] = 2
struct.pack_into("<I", firmware, 4, 0x40080000)
firmware[0x8000:0x8000 + 32] = esp_part_entry("factory", 0, 0, 0x10000,
0x100000, 0)
struct.pack_into("<I", firmware, 0x9000, 0xFFFFFFFE)
firmware[0x9008] = 0xFE
firmware[0x10000:0x11000] = os.urandom(4096)
firmware[0x11000:0x11008] = b"littlefs"
fw_path = os.path.join(os.path.dirname(flash_path), "firmware.bin")
with open(fw_path, "wb") as f:
f.write(firmware)
mounts_path = os.path.join(os.path.dirname(flash_path), "mounts")
with open(mounts_path, "w") as f:
f.write("/dev/sda1 / ext4 rw,relatime 0 0\n")
f.write("tmpfs /tmp tmpfs rw,nosuid,nodev 0 0\n")
f.write("tmpfs /dev/shm tmpfs rw,nosuid,nodev,noexec 0 0\n")
f.write("tmpfs /var/tmp tmpfs rw 0 0\n")
f.write("/dev/sdb1 /home ext4 rw,nosuid,nodev 0 0\n")
flash_home = tempfile.mkdtemp(prefix="apex-flash-home-")
write_scope(flash_home, {"label": "flash", "expires": "2099-12-31T23:59:59Z"})
res, _ = run([
call(1, "esp_partition_table", path=flash_path),
call(2, "esp_nvs_parse", path=nvs_path),
call(3, "firmware_scan", path=fw_path),
call(4, "mount_audit", path=mounts_path),
call(5, "esp_partition_table", path="/nonexistent/dump.bin"),
], home=flash_home)
by_id = {r.get("id"): r for r in res}
parts = json.loads(text(by_id[1]))
plabels = {e["label"]: e for e in parts["partitions"]}
check("esp_partition_table reads both entries",
parts["count"] == 2 and set(plabels) == {"nvs", "ota_0"}, parts)
check("esp_partition_table decodes the fields",
plabels["nvs"]["kind"] == "nvs" and
plabels["nvs"]["offset"] == 0x9000 and
plabels["ota_0"]["kind"] == "ota_0" and
plabels["ota_0"]["size"] == 0x100000, plabels)
check("esp_partition_table reports the MD5 entry",
parts["md5"] == "000102030405060708090a0b0c0d0e0f", parts)
nvs = json.loads(text(by_id[2]))
keys = {k["key"]: k for k in nvs["keys"]}
check("esp_nvs_parse finds the namespace", nvs["namespaces"] == ["wifi"], nvs)
check("esp_nvs_parse lists the keys with namespace and type",
nvs["key_count"] == 2 and
keys["ssid"]["namespace"] == "wifi" and
keys["ssid"]["type"] == "blob-data" and
keys["password"]["span"] == 1, nvs)
fw = json.loads(text(by_id[3]))
sigs = {sig["name"] for sig in fw["signatures"]}
check("firmware_scan finds the image signatures",
{"esp-app", "partition-table", "nvs", "littlefs"} <= sigs, fw)
check("firmware_scan measures the random block as high entropy",
fw["entropy"]["high_blocks"] >= 1 and
fw["entropy"]["max_x100"] >= 750, fw["entropy"])
check("firmware_scan collects printable strings",
fw["strings"]["count"] >= 1 and
any("littlefs" in sample for sample in fw["strings"]["samples"]), fw)
mounts = json.loads(text(by_id[4]))
by_mount = {m["mount"]: m for m in mounts["findings"]}
check("mount_audit flags the unhardened temp mounts",
mounts["findings_count"] == 2 and "/tmp" in by_mount and
"/var/tmp" in by_mount, mounts)
check("mount_audit names the missing options",
by_mount["/tmp"]["missing"] == ["noexec"] and
set(by_mount["/var/tmp"]["missing"]) == {"nosuid", "nodev", "noexec"},
mounts)
check("mount_audit leaves hardened mounts alone",
"/dev/shm" not in by_mount and "/home" not in by_mount, mounts)
check("esp_partition_table rejects a missing file", err(by_id[5]),
text(by_id[5]))
shutil.rmtree(os.path.dirname(flash_path), ignore_errors=True)
shutil.rmtree(flash_home, ignore_errors=True)
print("\n== esp32 tools ==")
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})