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.
This commit is contained in:
1 parent
6c618bf372
commit
260fe8cac6
10 files changed
+597
-15
No files matched your search
+21
-1
@@ -8,7 +8,27 @@ 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.22.0 — 2026-11-21 — this change
|
||||
## 1.23.0 — 2026-11-21 — this change
|
||||
|
||||
- **ESP image** (`esp_image_verify`): walks the segment table (load address,
|
||||
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 of the image up to the padding. Reports segments, entry,
|
||||
checksums and a valid flag; offset supports OTA partitions.
|
||||
- **CRLF** (`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` immutability, an execve rule and watches on
|
||||
/etc/passwd, /etc/shadow, /etc/sudoers and /etc/group; reports missing
|
||||
watches, a missing execve rule and unlocked rules.
|
||||
- Tests with a generated ESP image (valid and corrupted), CRLF-reflecting and
|
||||
filtering endpoints, and full/sparse audit rule sets. 728 checks. Coverage
|
||||
80.5%.
|
||||
- Fixture lesson: the ESP image header is exactly 24 bytes; three extra filler
|
||||
bytes shifted every segment and made the first verify look broken.
|
||||
|
||||
## 1.22.0 — 2026-11-21 — 6c618bf
|
||||
|
||||
- **SMTP relay** (`smtp_open_relay`): EHLO, MAIL FROM an .invalid sender, RCPT
|
||||
TO an external recipient; 250/251/252 means the server relays without
|
||||
|
||||
@@ -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.
|
||||
|
||||
**134 tools · 717 end-to-end checks · 340 fuzz cases · 80.4% line coverage · ~573 KiB**
|
||||
**137 tools · 728 end-to-end checks · 340 fuzz cases · 80.5% line coverage · ~581 KiB**
|
||||
|
||||
```
|
||||
$ ./apex-twin --check
|
||||
{"version":"1.22.0","tools":134,...,"scope":{"loaded":true,...}}
|
||||
{"version":"1.23.0","tools":137,...,"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 (134)
|
||||
## Tools (137)
|
||||
|
||||
### Scope and bookkeeping
|
||||
|
||||
@@ -284,6 +284,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
|
||||
| `email_security_audit` | SPF, DMARC, DKIM and MX via gated dig; policy and gaps |
|
||||
| `smtp_open_relay` | EHLO/MAIL/RCPT for an external recipient; open relay detection, no DATA |
|
||||
| `dns_open_resolver` | One recursive query against an in-scope resolver; answer means open |
|
||||
| `crlf_probe` | Encoded CRLF in one parameter; detects an injected response header |
|
||||
| `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN |
|
||||
| `pop3_probe` | Banner, CAPA list, STLS flag; no USER/PASS |
|
||||
| `sip_probe` | One UDP OPTIONS: status line, Server header, Allow methods |
|
||||
@@ -332,6 +333,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
|
||||
| `www_audit` | Web roots: world-writable content, .env/config/keys, backups, .git, missing index |
|
||||
| `apparmor_audit` | Profile list: enforce/complain counts, complain profiles named |
|
||||
| `selinux_audit` | enforce, SELINUX=/SELINUXTYPE=, boolean count; disabled/permissive findings |
|
||||
| `audit_rules` | audit.rules/rules.d: rule count, -e 2, execve, watches on passwd/shadow/sudoers/group |
|
||||
|
||||
### ESP32
|
||||
|
||||
@@ -345,6 +347,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
|
||||
| `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 |
|
||||
| `esp_app_info` | App header and esp_app_desc_t: version, project, build date, IDF version, ELF hash |
|
||||
| `esp_image_verify` | Segment table, XOR checksum and appended SHA-256; valid flag, OTA offset |
|
||||
|
||||
### Method
|
||||
|
||||
@@ -561,6 +564,9 @@ The full threat model, trust boundaries and a hardening checklist are in
|
||||
| SMTP relay | one MAIL and one RCPT, never DATA |
|
||||
| DNS resolver | one recursive dig query |
|
||||
| MAC audits | read /sys and /etc state only |
|
||||
| ESP verify | local image only, 32 MiB cap |
|
||||
| CRLF probe | one request, marker header only |
|
||||
| Audit rules | 100 files, read-only |
|
||||
|
||||
---
|
||||
|
||||
@@ -571,7 +577,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
|
||||
|
||||
```sh
|
||||
make # apex-twin
|
||||
make test # version check + gate audit + 717 end-to-end checks
|
||||
make test # version check + gate audit + 728 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
|
||||
@@ -683,7 +689,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery,
|
||||
snmp_walk, ldap_search, openapi_discovery, csrf_audit,
|
||||
rpc_probe, ntp_probe, api_auth_audit, cache_audit,
|
||||
tls_cipher_matrix, smb_null_session, smb_shares,
|
||||
email_security_audit, smtp_open_relay, dns_open_resolver
|
||||
email_security_audit, smtp_open_relay, dns_open_resolver,
|
||||
crlf_probe
|
||||
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,
|
||||
@@ -692,7 +699,7 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit,
|
||||
systemd_audit
|
||||
src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash,
|
||||
esp_partition_table, esp_nvs_parse, firmware_scan,
|
||||
esp_app_info
|
||||
esp_app_info, esp_image_verify
|
||||
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,
|
||||
@@ -726,7 +733,7 @@ examples/ scope.json
|
||||
|
||||
## Status
|
||||
|
||||
1.22.0. Built and run: 134 tools, 717 checks, 340 fuzz cases and 80.4% line
|
||||
1.23.0. Built and run: 137 tools, 728 checks, 340 fuzz cases and 80.5% 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
|
||||
@@ -766,7 +773,8 @@ audits; 1.19 added ESP app parsing, API auth and cache audits plus a log
|
||||
timeline; 1.20 added a TLS cipher matrix, SMB null-session check and Docker
|
||||
audit; 1.21 added SMB share probing, e-mail security checks and a web-root
|
||||
audit; 1.22 added SMTP relay and DNS resolver checks plus AppArmor/SELinux
|
||||
audits, again without changing an existing file format.
|
||||
audits; 1.23 added ESP image verification, CRLF injection and audit-rule
|
||||
checks, again without changing an existing file format.
|
||||
|
||||
Not yet wired into a fleet router, and there is no TLS interception.
|
||||
|
||||
|
||||
+4
-1
@@ -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.22.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
|
||||
is **1.23.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,9 @@ 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.
|
||||
- **Header-injection probes do not persist anything.** `crlf_probe` sends one
|
||||
encoded CRLF in a parameter and reads the response; `esp_image_verify` and
|
||||
`audit_rules` are offline file reads.
|
||||
- **Relay checks never send mail.** `smtp_open_relay` stops after RCPT and
|
||||
never issues DATA; `dns_open_resolver` sends one recursive query;
|
||||
`apparmor_audit` and `selinux_audit` read kernel/config state only.
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
.\" apex-twin.1 - manual page for APEX TWIN
|
||||
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.22.0" "User Commands"
|
||||
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.23.0" "User Commands"
|
||||
.SH NAME
|
||||
apex-twin \- scope\-gated offensive\-security MCP server
|
||||
.SH SYNOPSIS
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "1.22.0"
|
||||
#define APEX_VERSION "1.23.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
|
||||
@@ -5362,6 +5362,176 @@ static void t_selinux_audit(mcp_conn *c, const mcp_json *args, void *user)
|
||||
mcp_buf_free(&findings);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- audit_rules */
|
||||
|
||||
typedef struct {
|
||||
char watches[32][128];
|
||||
int nwatches;
|
||||
int rules;
|
||||
int files;
|
||||
int immutable;
|
||||
int execve;
|
||||
} ar_ctx;
|
||||
|
||||
static void ar_read_file(ar_ctx *ctx, const char *path)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
char *line = NULL;
|
||||
size_t cap = 0;
|
||||
|
||||
if (f == NULL)
|
||||
return;
|
||||
ctx->files++;
|
||||
while (getline(&line, &cap, f) >= 0) {
|
||||
char *t = line;
|
||||
size_t n;
|
||||
|
||||
while (*t == ' ' || *t == '\t')
|
||||
t++;
|
||||
n = strlen(t);
|
||||
while (n > 0 && (t[n - 1] == '\n' || t[n - 1] == '\r'))
|
||||
t[--n] = '\0';
|
||||
if (*t == '\0' || *t == '#')
|
||||
continue;
|
||||
ctx->rules++;
|
||||
if (strstr(t, "-e 2") != NULL)
|
||||
ctx->immutable = 1;
|
||||
if (strstr(t, "execve") != NULL)
|
||||
ctx->execve = 1;
|
||||
if (strncmp(t, "-w ", 3) == 0) {
|
||||
char p[128];
|
||||
int w = 0;
|
||||
|
||||
t += 3;
|
||||
while (*t == ' ' || *t == '\t')
|
||||
t++;
|
||||
while (*t != '\0' && *t != ' ' && *t != '\t' &&
|
||||
w + 1 < (int)sizeof(p))
|
||||
p[w++] = *t++;
|
||||
p[w] = '\0';
|
||||
if (w > 0 && ctx->nwatches < 32)
|
||||
snprintf(ctx->watches[ctx->nwatches++],
|
||||
sizeof(ctx->watches[0]), "%s", p);
|
||||
}
|
||||
}
|
||||
free(line);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
static void t_audit_rules(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *root = mcp_arg_string(args, "root");
|
||||
static const char *critical[] = {
|
||||
"/etc/passwd", "/etc/shadow", "/etc/sudoers", "/etc/group", NULL
|
||||
};
|
||||
char base[512];
|
||||
char path[1024];
|
||||
size_t bl;
|
||||
mcp_buf b;
|
||||
mcp_buf findings;
|
||||
int first = 1;
|
||||
int count = 0;
|
||||
ar_ctx ctx;
|
||||
int i;
|
||||
|
||||
(void)user;
|
||||
if (root == NULL)
|
||||
root = "";
|
||||
if (strlen(root) >= sizeof(base) - 2) {
|
||||
mcp_reply_error(c, "root path too long");
|
||||
return;
|
||||
}
|
||||
snprintf(base, sizeof(base), "%s", root);
|
||||
bl = strlen(base);
|
||||
while (bl > 0 && base[bl - 1] == '/')
|
||||
base[--bl] = '\0';
|
||||
memset(&ctx, 0, sizeof(ctx));
|
||||
snprintf(path, sizeof(path), "%s/etc/audit/audit.rules", base);
|
||||
ar_read_file(&ctx, path);
|
||||
snprintf(path, sizeof(path), "%s/etc/audit/rules.d", base);
|
||||
{
|
||||
DIR *d = opendir(path);
|
||||
struct dirent *ent;
|
||||
|
||||
if (d != NULL) {
|
||||
while ((ent = readdir(d)) != NULL) {
|
||||
char full[1024];
|
||||
size_t nl = strlen(ent->d_name);
|
||||
|
||||
if (ent->d_name[0] == '.')
|
||||
continue;
|
||||
if (nl < 7 ||
|
||||
strcmp(ent->d_name + nl - 6, ".rules") != 0)
|
||||
continue;
|
||||
snprintf(full, sizeof(full), "%.800s/%.160s", path,
|
||||
ent->d_name);
|
||||
ar_read_file(&ctx, full);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
}
|
||||
mcp_buf_init(&findings);
|
||||
for (i = 0; critical[i] != NULL; i++) {
|
||||
int j;
|
||||
int seen = 0;
|
||||
|
||||
for (j = 0; j < ctx.nwatches; j++)
|
||||
if (strcmp(ctx.watches[j], critical[i]) == 0)
|
||||
seen = 1;
|
||||
if (seen)
|
||||
continue;
|
||||
if (!first)
|
||||
mcp_buf_puts(&findings, ",");
|
||||
first = 0;
|
||||
count++;
|
||||
mcp_buf_puts(&findings, "{\"id\":\"missing-watch\",\"severity\":"
|
||||
"\"medium\",\"detail\":");
|
||||
{
|
||||
char detail[160];
|
||||
|
||||
snprintf(detail, sizeof(detail),
|
||||
"no audit watch on %s", critical[i]);
|
||||
apex_json_str(&findings, detail);
|
||||
}
|
||||
mcp_buf_puts(&findings, "}");
|
||||
}
|
||||
if (!ctx.immutable) {
|
||||
if (!first)
|
||||
mcp_buf_puts(&findings, ",");
|
||||
first = 0;
|
||||
count++;
|
||||
mcp_buf_puts(&findings, "{\"id\":\"not-immutable\",\"severity\":"
|
||||
"\"low\",\"detail\":\"rules are not locked with -e 2\"}");
|
||||
}
|
||||
if (!ctx.execve) {
|
||||
if (!first)
|
||||
mcp_buf_puts(&findings, ",");
|
||||
first = 0;
|
||||
count++;
|
||||
mcp_buf_puts(&findings, "{\"id\":\"no-execve\",\"severity\":"
|
||||
"\"medium\",\"detail\":\"no execve rule\"}");
|
||||
}
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"root\":");
|
||||
apex_json_str(&b, base);
|
||||
mcp_buf_printf(&b, ",\"files\":%d,\"rules\":%d,\"immutable\":%s,"
|
||||
"\"execve\":%s,\"watches\":[", ctx.files, ctx.rules,
|
||||
ctx.immutable ? "true" : "false",
|
||||
ctx.execve ? "true" : "false");
|
||||
for (i = 0; i < ctx.nwatches; i++) {
|
||||
if (i > 0)
|
||||
mcp_buf_puts(&b, ",");
|
||||
apex_json_str(&b, ctx.watches[i]);
|
||||
}
|
||||
mcp_buf_printf(&b, "],\"findings_count\":%d,\"findings\":[", count);
|
||||
if (findings.p != NULL)
|
||||
mcp_buf_add(&b, findings.p, findings.len);
|
||||
mcp_buf_puts(&b, "]}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
mcp_buf_free(&findings);
|
||||
}
|
||||
|
||||
const mcp_tool TOOLS_BLUE[] = {
|
||||
{ "hardening_audit",
|
||||
"Read-only posture audit of the local host: sshd_config (root login, "
|
||||
@@ -5678,6 +5848,14 @@ const mcp_tool TOOLS_BLUE[] = {
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
|
||||
t_selinux_audit },
|
||||
{ "audit_rules",
|
||||
"Parse /etc/audit/audit.rules and /etc/audit/rules.d/*.rules (root prefix "
|
||||
"supported): rule count, -e 2 immutability, an execve rule and watches on "
|
||||
"/etc/passwd, /etc/shadow, /etc/sudoers and /etc/group. Reports missing "
|
||||
"watches, a missing execve rule and unlocked rules. Read-only.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
|
||||
t_audit_rules },
|
||||
};
|
||||
|
||||
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
|
||||
+128
@@ -914,6 +914,123 @@ static void t_esp_app_info(mcp_conn *c, const mcp_json *args, void *user)
|
||||
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 "
|
||||
@@ -996,6 +1113,17 @@ const mcp_tool TOOLS_ESP[] = {
|
||||
"\"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]);
|
||||
+116
@@ -3967,6 +3967,107 @@ static void t_dns_open_resolver(mcp_conn *c, const mcp_json *args, void *user)
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- crlf_probe */
|
||||
|
||||
static void t_crlf_probe(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
const char *path = mcp_arg_string(args, "path");
|
||||
const char *param = mcp_arg_string(args, "param");
|
||||
const char *method = mcp_arg_string(args, "method");
|
||||
int port = mcp_arg_int(args, "port", 80);
|
||||
int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
|
||||
char value[256];
|
||||
char req[1400];
|
||||
char status[256];
|
||||
char header_val[128];
|
||||
char *resp = NULL;
|
||||
size_t len = 0;
|
||||
int code;
|
||||
int is_post;
|
||||
int injected = 0;
|
||||
int reflected = 0;
|
||||
char *evidence = NULL;
|
||||
mcp_buf enc;
|
||||
mcp_buf body;
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0' || param == NULL || *param == '\0') {
|
||||
mcp_reply_error(c, "target and param are required");
|
||||
return;
|
||||
}
|
||||
if (path == NULL || *path == '\0')
|
||||
path = "/";
|
||||
if (path[0] != '/') {
|
||||
mcp_reply_error(c, "path must start with /");
|
||||
return;
|
||||
}
|
||||
is_post = method != NULL && strcasecmp(method, "POST") == 0;
|
||||
if (!gated(c, "crlf_probe", target, port))
|
||||
return;
|
||||
snprintf(value, sizeof(value), "test\r\nX-Apex-Injected: yes");
|
||||
mcp_buf_init(&enc);
|
||||
url_enc(&enc, value);
|
||||
mcp_buf_init(&body);
|
||||
if (is_post) {
|
||||
mcp_buf_printf(&body, "%s=%s", param, enc.p != NULL ? enc.p : "");
|
||||
snprintf(req, sizeof(req), "%s", path);
|
||||
} else {
|
||||
const char *sep = strchr(path, '?') != NULL ? "&" : "?";
|
||||
|
||||
snprintf(req, sizeof(req), "%s%s%s=%s", path, sep, param,
|
||||
enc.p != NULL ? enc.p : "");
|
||||
}
|
||||
status[0] = '\0';
|
||||
if (apex_http_once(target, port, tls, is_post ? "POST" : "GET", req,
|
||||
is_post ? body.p : NULL,
|
||||
is_post ? "Content-Type: application/"
|
||||
"x-www-form-urlencoded\r\n" : NULL,
|
||||
8000, &resp, &len, status, sizeof(status)) != 0) {
|
||||
mcp_buf_free(&enc);
|
||||
mcp_buf_free(&body);
|
||||
mcp_reply_error(c, "cannot reach the endpoint");
|
||||
return;
|
||||
}
|
||||
code = apex_status_code(status);
|
||||
header_val[0] = '\0';
|
||||
response_header(resp, len, "X-Apex-Injected", header_val,
|
||||
sizeof(header_val));
|
||||
if (strcasestr(header_val, "yes") != NULL)
|
||||
injected = 1;
|
||||
if (find_bytes(resp, len, "X-Apex-Injected: yes"))
|
||||
reflected = 1;
|
||||
if (injected)
|
||||
evidence = apex_evidence_save("crlf", resp, len);
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port);
|
||||
apex_json_str(&b, path);
|
||||
mcp_buf_puts(&b, ",\"param\":");
|
||||
apex_json_str(&b, param);
|
||||
mcp_buf_printf(&b, ",\"status\":%d,\"injected\":%s,\"reflected\":%s,"
|
||||
"\"header_value\":", code, injected ? "true" : "false",
|
||||
reflected ? "true" : "false");
|
||||
apex_json_str(&b, header_val);
|
||||
mcp_buf_puts(&b, ",\"evidence\":");
|
||||
if (evidence != NULL)
|
||||
apex_json_str(&b, evidence);
|
||||
else
|
||||
mcp_buf_puts(&b, "null");
|
||||
mcp_buf_puts(&b, "}");
|
||||
apex_audit("crlf_probe", target, port, !injected,
|
||||
injected ? "CRLF injected a header" : "input is filtered",
|
||||
path);
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
mcp_buf_free(&enc);
|
||||
mcp_buf_free(&body);
|
||||
free(evidence);
|
||||
free(resp);
|
||||
}
|
||||
|
||||
const mcp_tool TOOLS_RED[] = {
|
||||
{ "vuln_check",
|
||||
"Non-destructive verification of exposed artifacts on one web target: "
|
||||
@@ -4318,6 +4419,21 @@ const mcp_tool TOOLS_RED[] = {
|
||||
"\"type\":{\"type\":\"string\",\"description\":\"default A\"}},"
|
||||
"\"required\":[\"server\"]}",
|
||||
t_dns_open_resolver },
|
||||
{ "crlf_probe",
|
||||
"Inject an encoded CRLF sequence into one parameter (GET query or POST "
|
||||
"form) with a marker header, then check whether the response carries "
|
||||
"X-Apex-Injected: yes, which means CRLF/header injection. The response is "
|
||||
"saved as evidence on a hit. Gate: the target must be in scope.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
|
||||
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
|
||||
"\"param\":{\"type\":\"string\"},"
|
||||
"\"method\":{\"type\":\"string\",\"enum\":[\"GET\",\"POST\"],"
|
||||
"\"description\":\"default GET\"},"
|
||||
"\"tls\":{\"type\":\"boolean\"}},"
|
||||
"\"required\":[\"target\",\"param\"]}",
|
||||
t_crlf_probe },
|
||||
};
|
||||
|
||||
const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[0]);
|
||||
+1
-1
@@ -21,7 +21,7 @@ import re
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
EXPECTED_TOOLS = 134
|
||||
EXPECTED_TOOLS = 137
|
||||
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.
|
||||
|
||||
+131
-2
@@ -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("134 tools registered", len(tools) == 134, len(tools))
|
||||
check("137 tools registered", len(tools) == 137, 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"]) == 134)
|
||||
check("http tools/list", len(listing["result"]["tools"]) == 137)
|
||||
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
|
||||
@@ -6108,6 +6108,135 @@ shutil.rmtree(se_root, ignore_errors=True)
|
||||
shutil.rmtree(se_perm, ignore_errors=True)
|
||||
shutil.rmtree(sec_home3, ignore_errors=True)
|
||||
|
||||
print("\n== ESP image verify, CRLF injection and audit rules ==")
|
||||
|
||||
|
||||
def build_esp_image(corrupt=False):
|
||||
body = bytearray()
|
||||
body += b"\xe9" + bytes([2]) + b"\x00\x00"
|
||||
body += struct.pack("<I", 0x40080000)
|
||||
body += b"\x00" * 16
|
||||
body[23] = 1
|
||||
data1 = b"ABCDEFGH"
|
||||
data2 = b"WXYZ"
|
||||
body += struct.pack("<II", 0x3F400000, len(data1)) + data1
|
||||
body += struct.pack("<II", 0x40080000, len(data2)) + data2
|
||||
checksum = 0xEF
|
||||
for b in data1 + data2:
|
||||
checksum ^= b
|
||||
body.append(checksum)
|
||||
while len(body) % 16 != 0:
|
||||
body.append(0)
|
||||
digest = hashlib.sha256(bytes(body)).digest()
|
||||
body += digest
|
||||
if corrupt:
|
||||
body[24 + 8] ^= 0xFF
|
||||
return bytes(body)
|
||||
|
||||
|
||||
esp_dir = tempfile.mkdtemp(prefix="apex-espimg-")
|
||||
esp_ok = os.path.join(esp_dir, "ok.bin")
|
||||
esp_bad = os.path.join(esp_dir, "bad.bin")
|
||||
with open(esp_ok, "wb") as f:
|
||||
f.write(build_esp_image(False))
|
||||
with open(esp_bad, "wb") as f:
|
||||
f.write(build_esp_image(True))
|
||||
|
||||
|
||||
class _CrlfHandler(http.server.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
parts = urllib.parse.urlsplit(self.path)
|
||||
value = urllib.parse.parse_qs(parts.query).get("q", [""])[0]
|
||||
body = b"ok"
|
||||
self.send_response(200)
|
||||
if parts.path == "/crlf" and "\r\n" in value:
|
||||
self.send_header("X-Apex-Injected", "yes")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
crlf_srv = http.server.HTTPServer(("127.0.0.1", 0), _CrlfHandler)
|
||||
crlf_port = crlf_srv.server_address[1]
|
||||
threading.Thread(target=crlf_srv.serve_forever, daemon=True).start()
|
||||
|
||||
ar_root = tempfile.mkdtemp(prefix="apex-ar-")
|
||||
os.makedirs(os.path.join(ar_root, "etc", "audit"))
|
||||
with open(os.path.join(ar_root, "etc", "audit", "audit.rules"), "w") as f:
|
||||
f.write("-w /etc/passwd -p wa -k passwd\n")
|
||||
f.write("-w /etc/shadow -p wa -k shadow\n")
|
||||
f.write("-w /etc/sudoers -p wa -k sudoers\n")
|
||||
f.write("-w /etc/group -p wa -k group\n")
|
||||
f.write("-a always,exit -F arch=b64 -S execve -k exec\n")
|
||||
f.write("-e 2\n")
|
||||
ar_sparse = tempfile.mkdtemp(prefix="apex-ars-")
|
||||
os.makedirs(os.path.join(ar_sparse, "etc", "audit", "rules.d"))
|
||||
with open(os.path.join(ar_sparse, "etc", "audit", "rules.d",
|
||||
"10-base.rules"), "w") as f:
|
||||
f.write("-w /etc/passwd -p wa -k passwd\n")
|
||||
|
||||
esp_home = tempfile.mkdtemp(prefix="apex-esp-home-")
|
||||
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z",
|
||||
"allow_private": True, "allow_ip": ["127.0.0.1"],
|
||||
"allow_port": [str(crlf_port)]})
|
||||
res, _ = run([
|
||||
call(1, "esp_image_verify", path=esp_ok),
|
||||
call(2, "esp_image_verify", path=esp_bad),
|
||||
call(3, "crlf_probe", target="127.0.0.1", port=crlf_port,
|
||||
path="/crlf", param="q", tls=False),
|
||||
call(4, "crlf_probe", target="127.0.0.1", port=crlf_port,
|
||||
path="/safe", param="q", tls=False),
|
||||
call(5, "audit_rules", root=ar_root),
|
||||
call(6, "audit_rules", root=ar_sparse),
|
||||
call(7, "crlf_probe", target="198.51.100.9", port=80, path="/crlf",
|
||||
param="q"),
|
||||
call(8, "esp_image_verify", path="/nonexistent-esp.bin"),
|
||||
], home=esp_home)
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
img = json.loads(text(by_id[1]))
|
||||
check("esp_image_verify accepts the intact image",
|
||||
img["segment_count"] == 2 and img["checksum_ok"] is True and
|
||||
img["sha256_present"] is True and img["sha256_ok"] is True and
|
||||
img["valid"] is True, img)
|
||||
check("esp_image_verify reports the segments and entry",
|
||||
img["segments"][0]["load"] == "0x3f400000" and
|
||||
img["segments"][1]["size"] == 4 and img["entry"] == "0x40080000", img)
|
||||
img_bad = json.loads(text(by_id[2]))
|
||||
check("esp_image_verify rejects the corrupted image",
|
||||
img_bad["checksum_ok"] is False and img_bad["valid"] is False, img_bad)
|
||||
crlf = json.loads(text(by_id[3]))
|
||||
check("crlf_probe detects the injected header",
|
||||
crlf["injected"] is True and crlf["header_value"] == "yes", crlf)
|
||||
check("crlf_probe keeps the response as evidence",
|
||||
crlf["evidence"] and os.path.isfile(crlf["evidence"]), crlf)
|
||||
crlf_safe = json.loads(text(by_id[4]))
|
||||
check("crlf_probe stays quiet on a filtering endpoint",
|
||||
crlf_safe["injected"] is False, crlf_safe)
|
||||
ar = json.loads(text(by_id[5]))
|
||||
check("audit_rules reads the full rule set",
|
||||
ar["files"] == 1 and ar["rules"] == 6 and ar["immutable"] is True and
|
||||
ar["execve"] is True and len(ar["watches"]) == 4, ar)
|
||||
check("audit_rules finds no gaps in the full set",
|
||||
ar["findings_count"] == 0, ar)
|
||||
ar_s = json.loads(text(by_id[6]))
|
||||
ar_ids = [f["id"] for f in ar_s["findings"]]
|
||||
check("audit_rules flags the missing watches and rules",
|
||||
ar_ids.count("missing-watch") == 3 and "not-immutable" in ar_ids and
|
||||
"no-execve" in ar_ids, ar_ids)
|
||||
check("crlf_probe refuses an out-of-scope target", err(by_id[7]),
|
||||
text(by_id[7]))
|
||||
check("esp_image_verify rejects a missing file", err(by_id[8]),
|
||||
text(by_id[8]))
|
||||
crlf_srv.shutdown()
|
||||
crlf_srv.server_close()
|
||||
shutil.rmtree(esp_dir, ignore_errors=True)
|
||||
shutil.rmtree(ar_root, ignore_errors=True)
|
||||
shutil.rmtree(ar_sparse, ignore_errors=True)
|
||||
shutil.rmtree(esp_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"})
|
||||
|
||||
Reference in new issue
Block a user