Files
apex-twin/src/tools_esp.c
T
lotherk 260fe8cac6 apex-twin 1.23.0: ESP image verify, CRLF injection, audit rules
Hardware:
- esp_image_verify: walks the segment table (load/length), XORs the segment
  data against the stored checksum, aligns to 16 bytes and, when
  hash_appended is set, compares the appended SHA-256 with the computed digest
  up to the padding. Reports segments, entry, checksums and a valid flag; the
  offset supports OTA partitions.

Red:
- crlf_probe: injects an encoded CRLF + X-Apex-Injected: yes through one
  parameter (GET/POST) and checks whether the response carries the header;
  the response is evidence on a hit.

Blue:
- audit_rules: parses /etc/audit/audit.rules and rules.d/*.rules (root
  prefix): rule count, -e 2, an execve rule and watches on /etc/passwd,
  /etc/shadow, /etc/sudoers and /etc/group; reports missing watches, missing
  execve and unlocked rules.

Tests: generated valid/corrupted ESP images, CRLF-reflecting and filtering
endpoints, full and sparse audit rule sets. 728 checks, ASan suite green,
analyze clean, release-check green including distcheck 1.23.0.

Fixture lesson: the ESP image header is exactly 24 bytes; three extra filler
bytes shift every segment.
2026-11-21 17:36:58 +00:00

1130 lines
30 KiB
C

/*
* tools_esp.c - ESP32 family support beyond the Marauder CLI.
*
* esp_info identify the attached chip (esptool chip_id) and the USB
* 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.
* All three are read-only; flashing a firmware image is deliberately not part
* of this build.
*/
#include <errno.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
static const char *esptool_name(void)
{
if (apex_have("esptool.py"))
return "esptool.py";
if (apex_have("esptool"))
return "esptool";
return NULL;
}
static int read_small(const char *path, char *buf, size_t cap)
{
FILE *f;
size_t n;
if (cap == 0)
return -1;
f = fopen(path, "rb");
if (f == NULL)
return -1;
n = fread(buf, 1, cap - 1, f);
fclose(f);
buf[n] = '\0';
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r' ||
buf[n - 1] == ' '))
buf[--n] = '\0';
return (int)n;
}
/* /sys/class/tty/ttyACM0/device/../../idVendor, when sysfs exposes it */
static int usb_id(const char *serial, char *vid, size_t vn, char *pid, size_t pn)
{
const char *slash = strrchr(serial, '/');
char path[512];
int up;
if (slash == NULL || strlen(slash + 1) >= 64)
return -1;
for (up = 0; up <= 3; up++) {
size_t n;
int i;
snprintf(path, sizeof(path), "/sys/class/tty/%s/device", slash + 1);
for (i = 0; i < up; i++) {
n = strlen(path);
if (n + 4 >= sizeof(path))
return -1;
memcpy(path + n, "/..", 4);
}
n = strlen(path);
snprintf(path + n, sizeof(path) - n, "/idVendor");
if (read_small(path, vid, vn) > 0) {
snprintf(path + n, sizeof(path) - n, "/idProduct");
if (read_small(path, pid, pn) > 0)
return 0;
return 0;
}
}
return -1;
}
static void t_esp_info(mcp_conn *c, const mcp_json *args, void *user)
{
const char *serial = mcp_arg_string(args, "serial");
const char *tool = esptool_name();
mcp_buf b;
(void)user;
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"serial\":");
apex_json_str(&b, serial);
{
char vid[16];
char pid[16];
if (usb_id(serial, vid, sizeof(vid), pid, sizeof(pid)) == 0) {
mcp_buf_puts(&b, ",\"usb\":{\"vid\":");
apex_json_str(&b, vid);
mcp_buf_puts(&b, ",\"pid\":");
apex_json_str(&b, pid);
mcp_buf_puts(&b, "}");
}
}
mcp_buf_puts(&b, ",\"esptool\":");
if (tool == NULL) {
mcp_buf_puts(&b, "false,\"output\":\"esptool is not installed "
"(pip install esptool); the serial device is still "
"usable by the marauder tools\"}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_buf_puts(&b, "true");
{
char *argv[8];
int i = 0;
apex_proc p;
int rc;
argv[i++] = (char *)tool;
argv[i++] = "--port";
argv[i++] = (char *)serial;
argv[i++] = "chip_id";
argv[i] = NULL;
rc = apex_run(argv, 20000, 65536, &p);
if (rc != 0) {
mcp_buf_puts(&b, ",\"exit\":-1,\"output\":\"cannot run "
"esptool\"}");
} else {
mcp_buf_printf(&b, ",\"exit\":%d,\"output\":", p.exit_code);
apex_json_str(&b, p.out != NULL ? p.out : "");
apex_proc_free(&p);
}
}
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_esp_monitor(mcp_conn *c, const mcp_json *args, void *user)
{
const char *serial = mcp_arg_string(args, "serial");
int seconds = mcp_arg_int(args, "seconds", 5);
int baud = mcp_arg_int(args, "baud", g_cfg.baud);
int fd;
time_t deadline;
mcp_buf b;
size_t total = 0;
(void)user;
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
if (seconds <= 0 || seconds > 30)
seconds = 5;
fd = apex_serial_open(serial, baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s", serial, strerror(errno));
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_buf_init(&b);
deadline = time(NULL) + seconds;
while (time(NULL) < deadline && total < (1u << 20)) {
struct pollfd p;
int pr;
char buf[4096];
ssize_t n;
p.fd = fd;
p.events = POLLIN;
p.revents = 0;
pr = poll(&p, 1, 200);
if (pr <= 0)
continue;
n = read(fd, buf, sizeof(buf));
if (n <= 0)
continue;
mcp_buf_add(&b, buf, (size_t)n);
total += (size_t)n;
}
close(fd);
{
mcp_buf out;
mcp_buf_init(&out);
mcp_buf_puts(&out, "{\"serial\":");
apex_json_str(&out, serial);
mcp_buf_printf(&out, ",\"seconds\":%d,\"bytes\":%lu,\"data\":",
seconds, (unsigned long)total);
apex_json_str(&out, b.p != NULL ? b.p : "");
mcp_buf_puts(&out, "}");
mcp_reply_json(c, out.p);
mcp_buf_free(&out);
}
mcp_buf_free(&b);
}
static void t_esp_read_flash(mcp_conn *c, const mcp_json *args, void *user)
{
const char *serial = mcp_arg_string(args, "serial");
const char *tool = esptool_name();
int offset = mcp_arg_int(args, "offset", 0);
int size = mcp_arg_int(args, "size", 1048576);
char path[APEX_PATH_FULL];
char name[96];
char offs[32];
char sizes[32];
mcp_buf b;
(void)user;
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
if (tool == NULL) {
mcp_reply_error(c, "esptool is not installed (pip install esptool)");
return;
}
if (offset < 0 || offset > (16 << 20)) {
mcp_reply_error(c, "offset out of range (0..16777216)");
return;
}
if (size <= 0 || size > (4 << 20)) {
mcp_reply_error(c, "size out of range (1..4194304)");
return;
}
snprintf(name, sizeof(name), "%ld-esp-flash-%d.bin", (long)time(NULL),
(int)getpid());
if (apex_path_join(path, sizeof(path), g_cfg.evidence_dir, name) != 0) {
mcp_reply_error(c, "cannot build the evidence path");
return;
}
snprintf(offs, sizeof(offs), "0x%x", (unsigned)offset);
snprintf(sizes, sizeof(sizes), "0x%x", (unsigned)size);
{
char *argv[10];
int i = 0;
apex_proc p;
int rc;
argv[i++] = (char *)tool;
argv[i++] = "--port";
argv[i++] = (char *)serial;
argv[i++] = "read_flash";
argv[i++] = offs;
argv[i++] = sizes;
argv[i++] = path;
argv[i] = NULL;
rc = apex_run(argv, 180000, 65536, &p);
if (rc != 0) {
mcp_reply_error(c, "cannot run esptool");
return;
}
mcp_buf_init(&b);
if (p.exit_code == 0) {
struct stat st;
if (stat(path, &st) == 0) {
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"bytes\":%ld,\"offset\":%d,"
"\"exit\":0}", (long)st.st_size, offset);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
apex_proc_free(&p);
return;
}
}
mcp_buf_printf(&b, "esptool exited %d: ", p.exit_code);
if (p.out != NULL)
mcp_buf_add(&b, p.out, p.out_len);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
apex_proc_free(&p);
}
}
static void t_esp_flash(mcp_conn *c, const mcp_json *args, void *user)
{
const char *image = mcp_arg_string(args, "image");
const char *serial = mcp_arg_string(args, "serial");
int offset = mcp_arg_int(args, "offset", 0);
int confirm = mcp_arg_bool(args, "confirm", 0);
const char *tool = esptool_name();
struct stat st;
char offs[32];
mcp_buf b;
(void)user;
if (!confirm) {
mcp_reply_error(c, "refusing to flash without confirm=true");
return;
}
if (image == NULL || *image == '\0') {
mcp_reply_error(c, "image is required");
return;
}
if (image[0] != '/') {
mcp_reply_error(c, "image must be an absolute path");
return;
}
if (stat(image, &st) != 0 || !S_ISREG(st.st_mode)) {
mcp_reply_error(c, "image is not a regular file");
return;
}
if (st.st_size <= 0 || st.st_size > (16L << 20)) {
mcp_reply_error(c, "image size out of range (1..16 MiB)");
return;
}
if (offset < 0 || offset > (16 << 20)) {
mcp_reply_error(c, "offset out of range (0..16777216)");
return;
}
if (tool == NULL) {
mcp_reply_error(c, "esptool is not installed (pip install esptool)");
return;
}
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
snprintf(offs, sizeof(offs), "0x%x", (unsigned)offset);
{
char *argv[12];
int i = 0;
apex_proc p;
int rc;
argv[i++] = (char *)tool;
argv[i++] = "--port";
argv[i++] = (char *)serial;
argv[i++] = "--baud";
argv[i++] = "460800";
argv[i++] = "write_flash";
argv[i++] = offs;
argv[i++] = (char *)image;
argv[i] = NULL;
rc = apex_run(argv, 300000, 65536, &p);
if (rc != 0) {
mcp_reply_error(c, "cannot run esptool");
return;
}
apex_audit("esp_flash", image, offset, p.exit_code == 0,
p.exit_code == 0 ? "firmware written" : "flash failed",
serial);
mcp_buf_init(&b);
if (p.exit_code == 0) {
mcp_buf_puts(&b, "{\"image\":");
apex_json_str(&b, image);
mcp_buf_printf(&b, ",\"offset\":%d,\"bytes\":%ld,\"exit\":0,"
"\"output\":", offset, (long)st.st_size);
apex_json_str(&b, p.out != NULL ? p.out : "");
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
} else {
mcp_buf_printf(&b, "esptool exited %d: ", p.exit_code);
if (p.out != NULL)
mcp_buf_add(&b, p.out, p.out_len);
mcp_reply_error(c, b.p);
}
mcp_buf_free(&b);
apex_proc_free(&p);
}
}
/* ------------------------------------------------------- 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);
}
/* --------------------------------------------------------------- esp_app_info */
static void t_esp_app_info(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
int offset = mcp_arg_int(args, "offset", 0);
unsigned char *buf = NULL;
size_t len = 0;
const unsigned char *d;
char version[33];
char project[33];
char build_time[17];
char build_date[17];
char idf[33];
char sha[65];
int desc_ok = 0;
int i;
mcp_buf b;
(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 image (max 32 MiB)");
return;
}
if ((size_t)offset + 8 > len || buf[offset] != 0xe9) {
free(buf);
mcp_reply_error(c, "no ESP app header at the offset");
return;
}
version[0] = project[0] = build_time[0] = build_date[0] = idf[0] = '\0';
sha[0] = '\0';
if ((size_t)offset + 0x20 + 176 <= len) {
d = buf + offset + 0x20;
if (esp_le32(d) == 0xabcd5432u) {
desc_ok = 1;
snprintf(version, sizeof(version), "%.32s",
(const char *)(d + 16));
snprintf(project, sizeof(project), "%.32s",
(const char *)(d + 48));
snprintf(build_time, sizeof(build_time), "%.16s",
(const char *)(d + 80));
snprintf(build_date, sizeof(build_date), "%.16s",
(const char *)(d + 96));
snprintf(idf, sizeof(idf), "%.32s", (const char *)(d + 112));
for (i = 0; i < 32; i++)
snprintf(sha + i * 2, 3, "%02x", d[144 + i]);
sha[64] = '\0';
}
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"offset\":%d,\"esp_app\":true,\"segments\":%d,"
"\"entry\":\"0x%08lx\",\"descriptor\":",
offset, buf[offset + 1],
(unsigned long)esp_le32(buf + offset + 4));
if (desc_ok) {
mcp_buf_puts(&b, "{\"version\":");
apex_json_str(&b, version);
mcp_buf_puts(&b, ",\"project_name\":");
apex_json_str(&b, project);
mcp_buf_puts(&b, ",\"build_time\":");
apex_json_str(&b, build_time);
mcp_buf_puts(&b, ",\"build_date\":");
apex_json_str(&b, build_date);
mcp_buf_puts(&b, ",\"idf_version\":");
apex_json_str(&b, idf);
mcp_buf_puts(&b, ",\"elf_sha256\":");
apex_json_str(&b, sha);
mcp_buf_puts(&b, "}");
} else {
mcp_buf_puts(&b, "null");
}
mcp_buf_puts(&b, "}");
free(buf);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ----------------------------------------------------------- esp_image_verify */
static void t_esp_image_verify(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
int offset = mcp_arg_int(args, "offset", 0);
unsigned char *buf = NULL;
size_t len = 0;
size_t pos;
unsigned int segs;
unsigned int checksum = 0xef;
unsigned int computed;
unsigned int stored;
size_t aligned;
int checksum_ok;
int sha_present;
int sha_ok = 0;
unsigned int loads[16];
unsigned int sizes[16];
int i;
mcp_buf b;
(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 image (max 32 MiB)");
return;
}
if ((size_t)offset + 24 > len || buf[offset] != 0xe9) {
free(buf);
mcp_reply_error(c, "no ESP app header at the offset");
return;
}
segs = buf[offset + 1];
if (segs == 0 || segs > 16) {
free(buf);
mcp_reply_error(c, "segment count out of range");
return;
}
sha_present = buf[offset + 23] == 1;
pos = (size_t)offset + 24;
for (i = 0; i < (int)segs; i++) {
unsigned int load;
unsigned int seg_len;
size_t k;
if (pos + 8 > len) {
free(buf);
mcp_reply_error(c, "truncated segment header");
return;
}
load = esp_le32(buf + pos);
seg_len = esp_le32(buf + pos + 4);
pos += 8;
if (seg_len > len - pos) {
free(buf);
mcp_reply_error(c, "truncated segment data");
return;
}
for (k = 0; k < seg_len; k++)
checksum ^= buf[pos + k];
loads[i] = load;
sizes[i] = seg_len;
pos += seg_len;
}
if (pos >= len) {
free(buf);
mcp_reply_error(c, "no checksum byte");
return;
}
stored = buf[pos];
computed = checksum & 0xff;
checksum_ok = stored == computed;
aligned = (size_t)offset + (((pos + 1 - (size_t)offset) + 15) & ~15UL);
if (sha_present && aligned + 32 <= len) {
char hex[65];
char actual[65];
int k;
apex_sha256(buf + offset, aligned - (size_t)offset, hex);
for (k = 0; k < 32; k++)
snprintf(actual + k * 2, 3, "%02x", buf[aligned + k]);
actual[64] = '\0';
sha_ok = strcmp(hex, actual) == 0;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"offset\":%d,\"segments\":[", offset);
for (i = 0; i < (int)segs; i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_printf(&b, "{\"load\":\"0x%08lx\",\"size\":%u}",
(unsigned long)loads[i], sizes[i]);
}
mcp_buf_printf(&b, "],\"segment_count\":%u,\"entry\":\"0x%08lx\","
"\"checksum_stored\":%u,\"checksum_computed\":%u,"
"\"checksum_ok\":%s,\"sha256_present\":%s,\"sha256_ok\":%s,"
"\"valid\":%s}",
segs, (unsigned long)esp_le32(buf + offset + 4), stored,
computed, checksum_ok ? "true" : "false",
sha_present ? "true" : "false", sha_ok ? "true" : "false",
(checksum_ok && (!sha_present || sha_ok)) ? "true"
: "false");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(buf);
}
const mcp_tool TOOLS_ESP[] = {
{ "esp_info",
"Identify the attached ESP32 family board: run esptool chip_id on the "
"serial port and report the chip output, or say that esptool is missing. "
"Read-only; no firmware is written.",
"{\"type\":\"object\",\"properties\":{"
"\"serial\":{\"type\":\"string\",\"description\":\"default APEX_SERIAL\"}}}",
t_esp_info },
{ "esp_monitor",
"Read the ESP32 serial console for N seconds and return what it printed. "
"Sends nothing: no reset, no command, no flash. Use it to see boot "
"messages or a firmware prompt.",
"{\"type\":\"object\",\"properties\":{"
"\"serial\":{\"type\":\"string\",\"description\":\"default APEX_SERIAL\"},"
"\"seconds\":{\"type\":\"integer\",\"description\":\"1..30, default 5\"},"
"\"baud\":{\"type\":\"integer\",\"description\":\"default APEX_BAUD\"}}}",
t_esp_monitor },
{ "esp_read_flash",
"Dump ESP32 flash into the evidence directory with esptool read_flash. "
"Offset 0..16 MiB, size up to 4 MiB, 0600 file, path returned. Read-only "
"on the device; flashing a firmware image is not part of this build.",
"{\"type\":\"object\",\"properties\":{"
"\"serial\":{\"type\":\"string\",\"description\":\"default APEX_SERIAL\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"default 0\"},"
"\"size\":{\"type\":\"integer\",\"description\":\"default 1 MiB, max "
"4 MiB\"}}}",
t_esp_read_flash },
{ "esp_flash",
"Write a firmware image to the ESP32 with esptool write_flash. Requires "
"confirm=true and an absolute image path (1 byte..16 MiB); offset 0..16 "
"MiB. Every flash is audited. Use this to provision your own board, not "
"a device you do not own.",
"{\"type\":\"object\",\"properties\":{"
"\"image\":{\"type\":\"string\",\"description\":\"absolute path to "
"the .bin\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"default 0\"},"
"\"serial\":{\"type\":\"string\",\"description\":\"default "
"APEX_SERIAL\"},"
"\"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 },
{ "esp_app_info",
"Read an ESP app image offline: header magic 0xE9, segment count and "
"entry address, then the esp_app_desc_t at 0x20 (magic 0xABCD5432) with "
"version, project name, build time/date, IDF version and the ELF "
"SHA-256. The offset can point at an OTA partition inside a full dump. "
"Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"image or flash dump\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"default 0\"}},"
"\"required\":[\"path\"]}",
t_esp_app_info },
{ "esp_image_verify",
"Verify an ESP app image offline: walk the segment headers (load address "
"and length), XOR the segment data against the stored checksum and, when "
"the header says a digest is appended, compare the SHA-256 of the image "
"up to the 16-byte padding. Reports segments, entry, checksums and a "
"valid flag. The offset can point at an OTA partition. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"image or flash dump\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"default 0\"}},"
"\"required\":[\"path\"]}",
t_esp_image_verify },
};
const size_t TOOLS_ESP_N = sizeof(TOOLS_ESP) / sizeof(TOOLS_ESP[0]);