diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a2cbc3..40dd231 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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.2.0 — 2026-11-21 — this change
+## 1.3.0 — 2026-11-21 — this change
+
+- **Red:** `ssrf_probe` injects one parameter with a URL that points at a
+ loopback listener this process opens (or at a `callback_base` collector) and
+ reports a callback only when a request actually arrives, with the request line
+ saved as evidence. Three host variants (127.0.0.1, localhost, 127.1) and
+ unique tokens; GET query or POST form. It never targets metadata endpoints.
+- **Blue:** `detect_rules` writes one Sigma, one Suricata and one YARA skeleton
+ per finding under `$APEX_HOME/detections/`, carrying id, title, target and
+ severity, and says outright that the rules need tuning. `integrity_baseline`
+ creates and verifies a SHA-256 manifest (new `sha256.c`) and reports changed,
+ missing and added files without external tools.
+- **Hardware:** `esp_flash` runs `esptool write_flash` only with
+ `confirm=true`, an absolute image path (1 byte..16 MiB) and offset range
+ checks, and audits every attempt.
+- Tests: a fetch-performing target for SSRF (and one that ignores the URL), two
+ findings turned into six rule files with content checks, a baseline that sees
+ one changed, one missing and one added file plus the SHA-256 "abc" vector, and
+ the three esp_flash refusal paths. 476 checks. Coverage 79.4%.
+
+## 1.2.0 — 2026-11-21 — 2935b75
- **Red:** `vhost_discovery` fuzzes the Host header against one in-scope IP
(built-in list or `names=`), diffs status, byte count and `
` against a
diff --git a/README.md b/README.md
index 1e0a629..81c1517 100644
--- a/README.md
+++ b/README.md
@@ -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.
-**57 tools · 456 end-to-end checks · 340 fuzz cases · 79.6% line coverage · ~292 KiB**
+**61 tools · 476 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~313 KiB**
```
$ ./apex-twin --check
-{"version":"1.2.0","tools":57,...,"scope":{"loaded":true,...}}
+{"version":"1.3.0","tools":61,...,"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 (57)
+## Tools (61)
### Scope and bookkeeping
@@ -251,6 +251,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `cred_test` | HTTP Basic default credentials, max 20 attempts, 200 ms apart, stops on 429, refuses an endpoint that answers without auth |
| `vhost_discovery` | Host-header fuzzing against one in-scope IP; reports names whose status, byte count or title differs from the baseline, with evidence |
| `http_brute` | Built-in, comma or file wordlist for hidden paths; 200/201/204/3xx/401/403 are hits, 100 ms apart, evidence for the first five 200s |
+| `ssrf_probe` | Injects a URL parameter pointing at its own loopback listener (or your `callback_base`) and confirms a real fetch; never targets metadata endpoints |
### Blue team
@@ -260,6 +261,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `log_audit` | Auth-log summary: failures per IP (flagged at 5+), invalid users, accepted logins; paths limited to `/var/log/` and the state dir |
| `ioc_scan` | Walk a directory for `/dev/tcp` shells, `bash -i`, `base64|sh`, `curl|sh`, `nc -e`, `socat EXEC:`, setuid chmod, systemd units under `/tmp` |
| `web_log_audit` | nginx/apache access log: status split, top IPs, scanner UAs, SQLi/traversal/XSS patterns (URL-decoded), 4xx/5xx bursts |
+| `detect_rules` | Sigma, Suricata and YARA skeletons per finding under `$APEX_HOME/detections/`; templates that need tuning |
+| `integrity_baseline` | SHA-256 manifest of a tree (`create`) and a changed/missing/added report (`verify`), no external tools |
### ESP32
@@ -268,6 +271,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `esp_info` | `esptool chip_id` on the serial port, plus USB VID/PID when sysfs exposes it |
| `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 |
### Method
@@ -440,6 +444,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| IOC scan | 20 000 files maximum, 100 findings, 1 MiB per file |
| Path brute force | 200 paths per call, 100 ms apart |
| vhost discovery | 100 names per call, 100 ms apart |
+| Integrity baseline | 1000 files per call (max 5000), 1 MiB per file |
+| SSRF probe | 3 loopback variants, 1.2 s callback wait |
---
@@ -450,7 +456,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
-make test # version check + gate audit + 456 end-to-end checks
+make test # version check + gate audit + 476 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
@@ -554,7 +560,8 @@ src/tools_report.c report renderers (Markdown, CSV, JSON)
src/tools_traffic.c traffic_list / traffic_read
src/tools_red.c vuln_check, subdomain_enum, cred_test
src/tools_blue.c hardening_audit, log_audit, ioc_scan
-src/tools_esp.c esp_info, esp_monitor, esp_read_flash
+src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash
+src/sha256.c SHA-256 for integrity_baseline
src/tools_guard.c guard_check
src/apex-twin.c MCP stdio + HTTP face, --check, --version
vendor/libmcp/ header-only MCP transport (JSON-RPC, tools, HTTP body)
@@ -583,7 +590,7 @@ examples/ scope.json
## Status
-1.2.0. Built and run: 57 tools, 456 checks, 340 fuzz cases and 79.6% line
+1.3.0. Built and run: 61 tools, 476 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
@@ -603,8 +610,9 @@ keeps the gaps visible.
1.x is the first stable line: the gate invariant and the on-disk JSON formats
(fields may be added, old files stay readable) are the compatibility promise.
1.1 added the red, blue and ESP32 tool groups; 1.2 added vhost discovery,
-wordlist path brute-forcing and access-log analysis, again without changing an
-existing tool or file format.
+wordlist path brute-forcing and access-log analysis; 1.3 added SSRF
+verification, detection-rule export, integrity baselines and firmware writing
+(confirm-gated), again without changing an existing tool or file format.
Not yet wired into a fleet router, and there is no TLS interception.
diff --git a/SECURITY.md b/SECURITY.md
index bab30c1..c91617f 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -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.2.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
+is **1.3.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.
@@ -60,6 +60,12 @@ only narrow what the proxy does (the scope gate still runs first).
against an in-scope HTTP Basic endpoint, at most 20 of them, with a 200 ms
pause, stopping on 429, and it refuses a path that needs no authentication
(nothing to test). Keep the scope and the rules of engagement explicit.
+- **SSRF probing only calls your collector.** `ssrf_probe` injects URLs that
+ point at its own loopback listener (or `callback_base` you supply). It never
+ injects cloud metadata addresses and never reads what the target fetches.
+- **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.
- **Local reads.** `hardening_audit` and `ioc_scan` read files the operator can
already read; `log_audit` only accepts paths under `/var/log/` or the state
directory. None of them change anything.
diff --git a/docs/apex-twin.1 b/docs/apex-twin.1
index 956b9da..a9a4da3 100644
--- a/docs/apex-twin.1
+++ b/docs/apex-twin.1
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
-.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.2.0" "User Commands"
+.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.3.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -36,8 +36,10 @@ and the radio is the ESP32 Marauder serial CLI.
It is not an exploit framework: there is no shell, no exploit payload, no
post\-exploitation, no C2 and no persistence. Besides reconnaissance and web
testing it carries offensive verification (vuln_check, subdomain_enum,
-cred_test), defensive audits (hardening_audit, log_audit, ioc_scan) and ESP32
-board tools (esp_info, esp_monitor, esp_read_flash).
+cred_test, vhost_discovery, http_brute, ssrf_probe), defensive audits
+(hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules,
+integrity_baseline) and ESP32 board tools (esp_info, esp_monitor,
+esp_read_flash, esp_flash).
.SH MODES
.TP
.B apex-twin
diff --git a/src/apex.h b/src/apex.h
index d143799..9a73cba 100644
--- a/src/apex.h
+++ b/src/apex.h
@@ -15,7 +15,7 @@
#include "mcp.h"
-#define APEX_VERSION "1.2.0"
+#define APEX_VERSION "1.3.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
@@ -115,6 +115,9 @@ int apex_have(const char *prog);
char *apex_join_argv(char *const argv[]);
char *apex_strdup(const char *s);
+/* SHA-256 in lowercase hex (64 characters plus NUL). */
+void apex_sha256(const void *data, size_t len, char hex[65]);
+
/* ----------------------------------------------------------------- store */
/* One finding as it sits on disk. Long fields are truncated, never overflowed;
diff --git a/src/sha256.c b/src/sha256.c
new file mode 100644
index 0000000..5347bc2
--- /dev/null
+++ b/src/sha256.c
@@ -0,0 +1,102 @@
+/*
+ * sha256.c - SHA-256, because a baseline without a hash is a file list.
+ *
+ * Plain C99, no library. Used by integrity_baseline; a hash of a file is only
+ * useful if the same code computes it both times, which is exactly what this
+ * is for.
+ */
+#include
+#include
+#include
+
+#include "apex.h"
+
+static const uint32_t K[64] = {
+ 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u,
+ 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u,
+ 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u,
+ 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u,
+ 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu,
+ 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau,
+ 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u,
+ 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u,
+ 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u,
+ 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u,
+ 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u,
+ 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u,
+ 0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u,
+ 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u,
+ 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u,
+ 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u
+};
+
+static uint32_t rotr(uint32_t x, int n)
+{
+ return (x >> n) | (x << (32 - n));
+}
+
+static void block(uint32_t h[8], const unsigned char *p)
+{
+ uint32_t w[64];
+ uint32_t a, b, c, d, e, f, g, hh;
+ int i;
+
+ for (i = 0; i < 16; i++)
+ w[i] = ((uint32_t)p[i * 4] << 24) |
+ ((uint32_t)p[i * 4 + 1] << 16) |
+ ((uint32_t)p[i * 4 + 2] << 8) |
+ (uint32_t)p[i * 4 + 3];
+ for (i = 16; i < 64; i++) {
+ uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^
+ (w[i - 15] >> 3);
+ uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^
+ (w[i - 2] >> 10);
+
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
+ }
+ a = h[0]; b = h[1]; c = h[2]; d = h[3];
+ e = h[4]; f = h[5]; g = h[6]; hh = h[7];
+ for (i = 0; i < 64; i++) {
+ uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
+ uint32_t ch = (e & f) ^ ((~e) & g);
+ uint32_t t1 = hh + S1 + ch + K[i] + w[i];
+ uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
+ uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
+ uint32_t t2 = S0 + mj;
+
+ hh = g; g = f; f = e; e = d + t1;
+ d = c; c = b; b = a; a = t1 + t2;
+ }
+ h[0] += a; h[1] += b; h[2] += c; h[3] += d;
+ h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
+}
+
+void apex_sha256(const void *data, size_t len, char hex[65])
+{
+ uint32_t h[8] = { 0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au,
+ 0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u };
+ const unsigned char *p = data;
+ size_t left = len;
+ unsigned char tail[128];
+ size_t tail_len;
+ uint64_t bits = (uint64_t)len * 8;
+ int i;
+
+ while (left >= 64) {
+ block(h, p);
+ p += 64;
+ left -= 64;
+ }
+ memset(tail, 0, sizeof(tail));
+ memcpy(tail, p, left);
+ tail[left] = 0x80;
+ tail_len = left + 1 + 8 <= 64 ? 64 : 128;
+ for (i = 0; i < 8; i++)
+ tail[tail_len - 1 - i] = (unsigned char)(bits >> (8 * i));
+ block(h, tail);
+ if (tail_len == 128)
+ block(h, tail + 64);
+ for (i = 0; i < 8; i++)
+ snprintf(hex + i * 8, 9, "%08x", h[i]);
+ hex[64] = '\0';
+}
diff --git a/src/tools_blue.c b/src/tools_blue.c
index ccdc1eb..e01f9f8 100644
--- a/src/tools_blue.c
+++ b/src/tools_blue.c
@@ -21,6 +21,7 @@
#include
#include
#include
+#include
#include
#include
@@ -1004,6 +1005,450 @@ static void t_web_log_audit(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
}
+/* ------------------------------------------------------------- detect_rules */
+
+static const char *sigma_level(const char *sev)
+{
+ if (strcasecmp(sev, "critical") == 0)
+ return "critical";
+ if (strcasecmp(sev, "high") == 0)
+ return "high";
+ if (strcasecmp(sev, "medium") == 0)
+ return "medium";
+ if (strcasecmp(sev, "low") == 0)
+ return "low";
+ return "informational";
+}
+
+/* One printable line: no quotes, no backslashes, no control characters. */
+static void clean_text(char *dst, size_t n, const char *src)
+{
+ size_t w = 0;
+
+ if (src == NULL)
+ src = "";
+ for (; *src != '\0' && w + 1 < n; src++) {
+ unsigned char c = (unsigned char)*src;
+
+ if (c < 0x20)
+ c = ' ';
+ if (c == '"' || c == '\\' || c == ';')
+ c = '\'';
+ dst[w++] = (char)c;
+ }
+ dst[w] = '\0';
+}
+
+static void t_detect_rules(mcp_conn *c, const mcp_json *args, void *user)
+{
+ const char *target = mcp_arg_string(args, "target");
+ int limit = mcp_arg_int(args, "limit", 100);
+ apex_finding *rows;
+ int n;
+ int i;
+ int generated = 0;
+ char dir[APEX_PATH_FULL];
+ mcp_buf files;
+ mcp_buf b;
+
+ (void)user;
+ if (limit <= 0 || limit > 500)
+ limit = 100;
+ rows = calloc(1024, sizeof(*rows));
+ if (rows == NULL) {
+ mcp_reply_error(c, "out of memory");
+ return;
+ }
+ n = apex_finding_scan(rows, 1024);
+ snprintf(dir, sizeof(dir), "%s/detections", g_cfg.home);
+ apex_mkdir_p(dir, 0700);
+ mcp_buf_init(&files);
+ for (i = 0; i < n && generated < limit; i++) {
+ const apex_finding *f = &rows[i];
+ char title[256];
+ char host[256];
+ char path[APEX_PATH_FULL];
+ char name[64];
+ mcp_buf rule;
+
+ if (target != NULL && *target != '\0' &&
+ strcmp(f->target, target) != 0)
+ continue;
+ clean_text(title, sizeof(title), f->title);
+ clean_text(host, sizeof(host), f->target);
+
+ /* Sigma */
+ snprintf(name, sizeof(name), "sigma-%s.yml", f->id);
+ if (apex_path_join(path, sizeof(path), dir, name) == 0) {
+ mcp_buf_init(&rule);
+ mcp_buf_printf(&rule,
+ "title: \"APEX %s: %s\"\nid: apex-%s\n"
+ "status: experimental\n"
+ "description: \"%s on %s (%s) - template, tune the "
+ "selection to your log schema\"\n"
+ "author: APEX TWIN\nlogsource:\n category: web\n"
+ "detection:\n selection:\n url|contains: \"%s\"\n"
+ " condition: selection\nfalsepositives:\n"
+ " - \"template\"\nlevel: %s\n",
+ f->id, title, f->id, title, host, f->severity, host,
+ sigma_level(f->severity));
+ if (apex_write_file(path, rule.p, rule.len, 0600) == 0) {
+ generated++;
+ if (files.len > 0)
+ mcp_buf_puts(&files, ",");
+ mcp_buf_puts(&files, "\"");
+ mcp_buf_puts(&files, name);
+ mcp_buf_puts(&files, "\"");
+ }
+ mcp_buf_free(&rule);
+ }
+
+ /* Suricata */
+ snprintf(name, sizeof(name), "suricata-%s.rules", f->id);
+ if (apex_path_join(path, sizeof(path), dir, name) == 0) {
+ int sid = 9000000 + atoi(f->id[0] == 'f' ? f->id + 1 : f->id);
+
+ mcp_buf_init(&rule);
+ mcp_buf_printf(&rule,
+ "alert http any any -> any any (msg:\"APEX %s %s "
+ "(%s)\"; flow:to_server,established; "
+ "content:\"%s\"; http_host; sid:%d; rev:1;)\n",
+ f->id, title, host, host, sid);
+ if (apex_write_file(path, rule.p, rule.len, 0600) == 0) {
+ generated++;
+ if (files.len > 0)
+ mcp_buf_puts(&files, ",");
+ mcp_buf_puts(&files, "\"");
+ mcp_buf_puts(&files, name);
+ mcp_buf_puts(&files, "\"");
+ }
+ mcp_buf_free(&rule);
+ }
+
+ /* YARA */
+ snprintf(name, sizeof(name), "yara-%s.yar", f->id);
+ if (apex_path_join(path, sizeof(path), dir, name) == 0) {
+ mcp_buf_init(&rule);
+ mcp_buf_printf(&rule,
+ "rule APEX_%s\n{\n meta:\n"
+ " description = \"%s on %s\"\n"
+ " severity = \"%s\"\n"
+ " source = \"apex-twin\"\n"
+ " strings:\n $target = \"%s\" ascii wide "
+ "nocase\n condition:\n $target\n}\n",
+ f->id, title, host, sigma_level(f->severity), host);
+ if (apex_write_file(path, rule.p, rule.len, 0600) == 0) {
+ generated++;
+ if (files.len > 0)
+ mcp_buf_puts(&files, ",");
+ mcp_buf_puts(&files, "\"");
+ mcp_buf_puts(&files, name);
+ mcp_buf_puts(&files, "\"");
+ }
+ mcp_buf_free(&rule);
+ }
+ }
+ free(rows);
+ mcp_buf_init(&b);
+ mcp_buf_puts(&b, "{\"dir\":");
+ apex_json_str(&b, dir);
+ mcp_buf_printf(&b, ",\"generated\":%d,\"files\":[", generated);
+ if (files.p != NULL)
+ mcp_buf_add(&b, files.p, files.len);
+ mcp_buf_puts(&b, "],\"note\":\"these are skeletons: set the real "
+ "selection/flow and test them before deployment\"}");
+ mcp_reply_json(c, b.p);
+ mcp_buf_free(&b);
+ mcp_buf_free(&files);
+}
+
+/* --------------------------------------------------------- integrity_baseline */
+
+#define BASE_MAX 5000
+
+typedef struct {
+ char path[512];
+ long size;
+ char hex[65];
+ int seen;
+} base_entry;
+
+typedef struct {
+ int create;
+ base_entry *entries;
+ int n;
+ int max;
+ mcp_buf *lines;
+ int changed;
+ int added;
+ int missing;
+ int checked;
+ mcp_buf *detail;
+} integ_ctx;
+
+static int hash_file(const char *path, char hex[65], long *size)
+{
+ struct stat st;
+ FILE *f;
+ char *buf;
+
+ if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
+ return -1;
+ if (st.st_size < 0 || st.st_size > (1L << 20))
+ return -1;
+ f = fopen(path, "rb");
+ if (f == NULL)
+ return -1;
+ buf = malloc((size_t)st.st_size + 1);
+ if (buf == NULL) {
+ fclose(f);
+ return -1;
+ }
+ if (st.st_size > 0 &&
+ fread(buf, 1, (size_t)st.st_size, f) != (size_t)st.st_size) {
+ free(buf);
+ fclose(f);
+ return -1;
+ }
+ fclose(f);
+ apex_sha256(buf, (size_t)st.st_size, hex);
+ free(buf);
+ *size = (long)st.st_size;
+ return 0;
+}
+
+static void detail_add(integ_ctx *ctx, const char *path, const char *what)
+{
+ if (ctx->detail->len > 0)
+ mcp_buf_puts(ctx->detail, ",");
+ mcp_buf_puts(ctx->detail, "{\"path\":");
+ apex_json_str(ctx->detail, path);
+ mcp_buf_puts(ctx->detail, ",\"what\":");
+ apex_json_str(ctx->detail, what);
+ mcp_buf_puts(ctx->detail, "}");
+}
+
+static void integ_file(integ_ctx *ctx, const char *path)
+{
+ char hex[65];
+ long size;
+
+ if (ctx->checked >= ctx->max)
+ return;
+ if (hash_file(path, hex, &size) != 0)
+ return;
+ ctx->checked++;
+ if (ctx->create) {
+ mcp_buf_puts(ctx->lines, "{\"path\":");
+ apex_json_str(ctx->lines, path);
+ mcp_buf_printf(ctx->lines, ",\"size\":%ld,\"sha256\":\"%s\"}\n",
+ size, hex);
+ return;
+ }
+ {
+ int i;
+
+ for (i = 0; i < ctx->n; i++) {
+ base_entry *e = &ctx->entries[i];
+
+ if (strcmp(e->path, path) != 0)
+ continue;
+ e->seen = 1;
+ if (e->size != size || strcmp(e->hex, hex) != 0) {
+ ctx->changed++;
+ if (ctx->changed <= 20)
+ detail_add(ctx, path, "changed");
+ }
+ return;
+ }
+ ctx->added++;
+ if (ctx->added <= 20)
+ detail_add(ctx, path, "added");
+ }
+}
+
+static void integ_walk(integ_ctx *ctx, const char *dir, int depth)
+{
+ DIR *d;
+ struct dirent *ent;
+
+ if (depth > 8 || ctx->checked >= ctx->max)
+ return;
+ d = opendir(dir);
+ if (d == NULL)
+ return;
+ while ((ent = readdir(d)) != NULL) {
+ char path[1024];
+ struct stat st;
+ size_t dl = strlen(dir);
+ size_t nl = strlen(ent->d_name);
+
+ if (ctx->checked >= ctx->max)
+ break;
+ if (ent->d_name[0] == '.' &&
+ (ent->d_name[1] == '\0' ||
+ (ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
+ continue;
+ if (dl + nl + 2 > sizeof(path))
+ continue;
+ memcpy(path, dir, dl);
+ path[dl] = '/';
+ memcpy(path + dl + 1, ent->d_name, nl + 1);
+ if (lstat(path, &st) != 0)
+ continue;
+ if (S_ISLNK(st.st_mode))
+ continue;
+ if (S_ISDIR(st.st_mode))
+ integ_walk(ctx, path, depth + 1);
+ else if (S_ISREG(st.st_mode))
+ integ_file(ctx, path);
+ }
+ closedir(d);
+}
+
+static int json_str_field(const char *json, const char *key, char *out, size_t n)
+{
+ char pattern[64];
+ const char *p;
+ size_t i = 0;
+
+ snprintf(pattern, sizeof(pattern), "\"%s\":\"", key);
+ p = strstr(json, pattern);
+ if (p == NULL) {
+ out[0] = '\0';
+ return 0;
+ }
+ p += strlen(pattern);
+ while (*p != '\0' && *p != '"' && i + 1 < n)
+ out[i++] = *p++;
+ out[i] = '\0';
+ return 1;
+}
+
+static long json_num_field(const char *json, const char *key)
+{
+ char pattern[64];
+ const char *p;
+
+ snprintf(pattern, sizeof(pattern), "\"%s\":", key);
+ p = strstr(json, pattern);
+ if (p == NULL)
+ return 0;
+ return atol(p + strlen(pattern));
+}
+
+static void t_integrity_baseline(mcp_conn *c, const mcp_json *args, void *user)
+{
+ const char *action = mcp_arg_string(args, "action");
+ const char *path = mcp_arg_string(args, "path");
+ const char *baseline = mcp_arg_string(args, "baseline");
+ int limit = mcp_arg_int(args, "limit", 1000);
+ char base_path[APEX_PATH_FULL];
+ integ_ctx ctx;
+ mcp_buf lines;
+ mcp_buf detail;
+ mcp_buf b;
+ int create;
+
+ (void)user;
+ if (path == NULL || *path == '\0')
+ path = "/etc";
+ if (action == NULL || *action == '\0')
+ action = "verify";
+ create = strcmp(action, "create") == 0;
+ if (!create && strcmp(action, "verify") != 0) {
+ mcp_reply_error(c, "action must be create or verify");
+ return;
+ }
+ if (limit <= 0 || limit > BASE_MAX)
+ limit = 1000;
+ if (baseline != NULL && *baseline != '\0')
+ snprintf(base_path, sizeof(base_path), "%s", baseline);
+ else
+ snprintf(base_path, sizeof(base_path), "%s/baseline.jsonl",
+ g_cfg.home);
+ memset(&ctx, 0, sizeof(ctx));
+ ctx.create = create;
+ ctx.max = limit;
+ mcp_buf_init(&lines);
+ mcp_buf_init(&detail);
+ if (create) {
+ ctx.lines = &lines;
+ integ_walk(&ctx, path, 0);
+ if (apex_write_file(base_path, lines.p != NULL ? lines.p : "",
+ lines.len, 0600) != 0) {
+ mcp_reply_error(c, "cannot write the baseline");
+ mcp_buf_free(&lines);
+ mcp_buf_free(&detail);
+ return;
+ }
+ } else {
+ FILE *f = fopen(base_path, "rb");
+ char *line = NULL;
+ size_t cap = 0;
+
+ if (f == NULL) {
+ mcp_reply_error(c, "no baseline; run action=create first");
+ mcp_buf_free(&lines);
+ mcp_buf_free(&detail);
+ return;
+ }
+ ctx.entries = calloc(BASE_MAX, sizeof(*ctx.entries));
+ if (ctx.entries == NULL) {
+ fclose(f);
+ mcp_reply_error(c, "out of memory");
+ mcp_buf_free(&lines);
+ mcp_buf_free(&detail);
+ return;
+ }
+ while (ctx.n < BASE_MAX && getline(&line, &cap, f) >= 0) {
+ base_entry *e = &ctx.entries[ctx.n];
+
+ if (!json_str_field(line, "path", e->path, sizeof(e->path)))
+ continue;
+ e->size = json_num_field(line, "size");
+ if (!json_str_field(line, "sha256", e->hex, sizeof(e->hex)))
+ continue;
+ e->seen = 0;
+ ctx.n++;
+ }
+ free(line);
+ fclose(f);
+ ctx.detail = &detail;
+ integ_walk(&ctx, path, 0);
+ {
+ int i;
+
+ for (i = 0; i < ctx.n; i++)
+ if (!ctx.entries[i].seen) {
+ ctx.missing++;
+ if (ctx.missing <= 20)
+ detail_add(&ctx, ctx.entries[i].path,
+ "missing");
+ }
+ }
+ free(ctx.entries);
+ }
+ mcp_buf_init(&b);
+ mcp_buf_puts(&b, "{\"action\":");
+ apex_json_str(&b, create ? "create" : "verify");
+ mcp_buf_puts(&b, ",\"path\":");
+ apex_json_str(&b, path);
+ mcp_buf_puts(&b, ",\"baseline\":");
+ apex_json_str(&b, base_path);
+ if (create)
+ mcp_buf_printf(&b, ",\"files\":%d}", ctx.checked);
+ else
+ mcp_buf_printf(&b, ",\"checked\":%d,\"changed\":%d,\"missing\":%d,"
+ "\"added\":%d,\"details\":[%s]}", ctx.checked,
+ ctx.changed, ctx.missing, ctx.added,
+ detail.p != NULL ? detail.p : "");
+ mcp_reply_json(c, b.p);
+ mcp_buf_free(&b);
+ mcp_buf_free(&lines);
+ mcp_buf_free(&detail);
+}
+
const mcp_tool TOOLS_BLUE[] = {
{ "hardening_audit",
"Read-only posture audit of the local host: sshd_config (root login, "
@@ -1048,6 +1493,34 @@ const mcp_tool TOOLS_BLUE[] = {
"\"limit\":{\"type\":\"integer\",\"description\":\"lines to read, "
"default 5000, max 50000\"}}}",
t_web_log_audit },
+ { "detect_rules",
+ "Turn recorded findings into detection skeletons: one Sigma rule, one "
+ "Suricata rule and one YARA rule per finding under "
+ "$APEX_HOME/detections/. The rules carry the finding id, title, target "
+ "and severity; they are templates and must be tuned and tested before "
+ "deployment. Nothing is loaded into a sensor.",
+ "{\"type\":\"object\",\"properties\":{"
+ "\"target\":{\"type\":\"string\",\"description\":\"only findings for "
+ "this target\"},"
+ "\"limit\":{\"type\":\"integer\",\"description\":\"default 100, max "
+ "500\"}}}",
+ t_detect_rules },
+ { "integrity_baseline",
+ "Create or verify a SHA-256 baseline of a directory tree "
+ "($APEX_HOME/baseline.jsonl by default). create hashes every regular "
+ "file up to 1 MiB (1000 files default); verify re-hashes them and "
+ "reports changed, missing and added files. No external tools and no "
+ "database.",
+ "{\"type\":\"object\",\"properties\":{"
+ "\"action\":{\"type\":\"string\",\"enum\":[\"create\",\"verify\"],"
+ "\"description\":\"default verify\"},"
+ "\"path\":{\"type\":\"string\",\"description\":\"directory, default "
+ "/etc\"},"
+ "\"baseline\":{\"type\":\"string\",\"description\":\"default "
+ "$APEX_HOME/baseline.jsonl\"},"
+ "\"limit\":{\"type\":\"integer\",\"description\":\"max files, "
+ "default 1000\"}}}",
+ t_integrity_baseline },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
diff --git a/src/tools_esp.c b/src/tools_esp.c
index 186205e..6e7dde9 100644
--- a/src/tools_esp.c
+++ b/src/tools_esp.c
@@ -281,6 +281,92 @@ static void t_esp_read_flash(mcp_conn *c, const mcp_json *args, void *user)
}
}
+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);
+ }
+}
+
const mcp_tool TOOLS_ESP[] = {
{ "esp_info",
"Identify the attached ESP32 family board: run esptool chip_id on the "
@@ -308,6 +394,20 @@ const mcp_tool TOOLS_ESP[] = {
"\"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 },
};
const size_t TOOLS_ESP_N = sizeof(TOOLS_ESP) / sizeof(TOOLS_ESP[0]);
diff --git a/src/tools_red.c b/src/tools_red.c
index 7b0612d..ee0ed70 100644
--- a/src/tools_red.c
+++ b/src/tools_red.c
@@ -19,6 +19,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -979,6 +980,214 @@ static void t_http_brute(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
}
+/* ---------------------------------------------------------------- ssrf_probe */
+
+static void url_enc(mcp_buf *b, const char *s)
+{
+ static const char hex[] = "0123456789ABCDEF";
+ size_t i;
+
+ for (i = 0; s[i] != '\0'; i++) {
+ unsigned char c = (unsigned char)s[i];
+
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+ (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' ||
+ c == '~') {
+ mcp_buf_add(b, (const char *)&c, 1);
+ } else {
+ char out[3] = { '%', hex[c >> 4], hex[c & 15] };
+
+ mcp_buf_add(b, out, 3);
+ }
+ }
+}
+
+static int cb_open(int *port)
+{
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in sa;
+ socklen_t sl = sizeof(sa);
+ int one = 1;
+
+ if (fd < 0)
+ return -1;
+ setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+ memset(&sa, 0, sizeof(sa));
+ sa.sin_family = AF_INET;
+ sa.sin_port = 0;
+ sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0 ||
+ listen(fd, 8) != 0 ||
+ getsockname(fd, (struct sockaddr *)&sa, &sl) != 0) {
+ close(fd);
+ return -1;
+ }
+ *port = ntohs(sa.sin_port);
+ return fd;
+}
+
+static int cb_wait(int ls, int wait_ms, char *req, size_t n)
+{
+ struct pollfd p;
+ int c;
+ ssize_t r;
+
+ p.fd = ls;
+ p.events = POLLIN;
+ p.revents = 0;
+ if (poll(&p, 1, wait_ms) <= 0)
+ return 0;
+ c = accept(ls, NULL, NULL);
+ if (c < 0)
+ return 0;
+ r = read(c, req, n - 1);
+ close(c);
+ if (r <= 0)
+ return 0;
+ req[r] = '\0';
+ return 1;
+}
+
+static void t_ssrf_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");
+ const char *callback = mcp_arg_string(args, "callback_base");
+ int port = mcp_arg_int(args, "port", 80);
+ int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
+ int wait_ms = mcp_arg_int(args, "wait_ms", 1200);
+ int cbport = 0;
+ int ls = -1;
+ int is_post;
+ char token[64];
+ mcp_buf b;
+ int first = 1;
+ int confirmed = 0;
+ int verified;
+ const char *hosts[3] = { "127.0.0.1", "localhost", "127.1" };
+ int v;
+
+ (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 (wait_ms < 200 || wait_ms > 5000)
+ wait_ms = 1200;
+ if (!gated(c, "ssrf_probe", target, port))
+ return;
+
+ verified = callback == NULL || *callback == '\0';
+ if (verified) {
+ ls = cb_open(&cbport);
+ if (ls < 0) {
+ mcp_reply_error(c, "cannot open the callback listener");
+ return;
+ }
+ }
+ snprintf(token, sizeof(token), "apex%ld", (long)getpid());
+
+ mcp_buf_init(&b);
+ mcp_buf_puts(&b, "{\"target\":");
+ apex_json_str(&b, target);
+ mcp_buf_printf(&b, ",\"port\":%d,\"param\":", port);
+ apex_json_str(&b, param);
+ mcp_buf_printf(&b, ",\"method\":\"%s\",\"verified\":%s",
+ is_post ? "POST" : "GET", verified ? "true" : "false");
+ if (verified)
+ mcp_buf_printf(&b, ",\"callback_port\":%d", cbport);
+ mcp_buf_puts(&b, ",\"callbacks\":[");
+ for (v = 0; v < 3 && (verified ? 1 : v < 1); v++) {
+ char url[600];
+ char inj[900];
+ char status[256];
+ char *resp = NULL;
+ size_t len = 0;
+ const char *base = callback;
+ char hostpart[300];
+ char tok[96];
+
+ snprintf(tok, sizeof(tok), "%s-%d-%d", token, (int)getpid(), v);
+ if (verified) {
+ snprintf(hostpart, sizeof(hostpart), "http://%s:%d", hosts[v],
+ cbport);
+ base = hostpart;
+ }
+ snprintf(url, sizeof(url), "%s/%s", base, tok);
+ {
+ mcp_buf enc;
+ mcp_buf target_buf;
+
+ mcp_buf_init(&enc);
+ url_enc(&enc, url);
+ mcp_buf_init(&target_buf);
+ if (is_post) {
+ mcp_buf_printf(&target_buf, "%s=%s", param,
+ enc.p != NULL ? enc.p : "");
+ snprintf(inj, sizeof(inj), "%s", target_buf.p);
+ } else {
+ const char *sep = strchr(path, '?') != NULL ? "&" : "?";
+
+ snprintf(inj, sizeof(inj), "%s%s%s=%s", path, sep, param,
+ enc.p != NULL ? enc.p : "");
+ }
+ mcp_buf_free(&enc);
+ mcp_buf_free(&target_buf);
+ }
+ status[0] = '\0';
+ (void)apex_http_once(target, port, tls, is_post ? "POST" : "GET",
+ is_post ? path : inj,
+ is_post ? inj : NULL, NULL, 10000, &resp, &len,
+ status, sizeof(status));
+ free(resp);
+ if (verified) {
+ char req[1024];
+
+ if (cb_wait(ls, wait_ms, req, sizeof(req))) {
+ if (strstr(req, tok) != NULL) {
+ char *ev = apex_evidence_save("ssrf-callback", req,
+ strlen(req));
+ size_t k;
+ size_t n = strlen(req);
+
+ for (k = 0; k < n; k++)
+ if (req[k] == '\r' || req[k] == '\n')
+ req[k] = ' ';
+ if (!first)
+ mcp_buf_puts(&b, ",");
+ first = 0;
+ confirmed = 1;
+ mcp_buf_puts(&b, "{\"url\":");
+ apex_json_str(&b, url);
+ mcp_buf_puts(&b, ",\"request\":");
+ apex_json_str(&b, req);
+ mcp_buf_puts(&b, ",\"evidence\":");
+ if (ev != NULL)
+ apex_json_str(&b, ev);
+ else
+ mcp_buf_puts(&b, "null");
+ mcp_buf_puts(&b, "}");
+ free(ev);
+ }
+ }
+ }
+ }
+ mcp_buf_printf(&b, "],\"confirmed\":%s}", confirmed ? "true" : "false");
+ mcp_reply_json(c, b.p);
+ mcp_buf_free(&b);
+ if (ls >= 0)
+ close(ls);
+}
+
const mcp_tool TOOLS_RED[] = {
{ "vuln_check",
"Non-destructive verification of exposed artifacts on one web target: "
@@ -1069,6 +1278,29 @@ const mcp_tool TOOLS_RED[] = {
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_http_brute },
+ { "ssrf_probe",
+ "Inject one parameter with a URL that points at a callback: by default "
+ "a loopback listener this process opens (verified: a request arriving "
+ "there proves the target fetched it), or callback_base when the target "
+ "must reach an external collector (then only 'sent' is reported). Tries "
+ "127.0.0.1, localhost and 127.1 with unique tokens. GET query or POST "
+ "form. Only fetches to your own collector, never to metadata endpoints.",
+ "{\"type\":\"object\",\"properties\":{"
+ "\"target\":{\"type\":\"string\"},"
+ "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
+ "\"path\":{\"type\":\"string\",\"description\":\"endpoint, default "
+ "/\"},"
+ "\"param\":{\"type\":\"string\",\"description\":\"parameter that "
+ "takes a URL\"},"
+ "\"method\":{\"type\":\"string\",\"enum\":[\"GET\",\"POST\"],"
+ "\"description\":\"default GET\"},"
+ "\"callback_base\":{\"type\":\"string\",\"description\":\"external "
+ "collector base URL; omit for the loopback listener\"},"
+ "\"wait_ms\":{\"type\":\"integer\",\"description\":\"callback wait, "
+ "default 1200\"},"
+ "\"tls\":{\"type\":\"boolean\"}},"
+ "\"required\":[\"target\",\"param\"]}",
+ t_ssrf_probe },
};
const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[0]);
diff --git a/tests/gate_audit.py b/tests/gate_audit.py
index 83bcc88..def508b 100755
--- a/tests/gate_audit.py
+++ b/tests/gate_audit.py
@@ -21,15 +21,15 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-EXPECTED_TOOLS = 57
+EXPECTED_TOOLS = 61
GATE = ("gated(", "gated_cmd(", "apex_scope_check(")
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown",
- "traffic_list"}
+ "traffic_list", "detect_rules"}
# Tools that spawn a local program for hardware, not a network target. They take
# no target and cannot reach one through the argv they build.
-LOCAL_EXEC = {"esp_info", "esp_read_flash"}
+LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash"}
TABLE_RE = re.compile(r"const mcp_tool (TOOLS_[A-Z_]+)\[\] = \{(.*?)\n\};",
re.S)
diff --git a/tests/run.py b/tests/run.py
index b719a5b..391868a 100755
--- a/tests/run.py
+++ b/tests/run.py
@@ -130,7 +130,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("57 tools registered", len(tools) == 57, len(tools))
+check("61 tools registered", len(tools) == 61, 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",
@@ -1556,7 +1556,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"]) == 57)
+ check("http tools/list", len(listing["result"]["tools"]) == 61)
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
@@ -2700,6 +2700,71 @@ vhost_srv.server_close()
brute_srv.shutdown()
brute_srv.server_close()
shutil.rmtree(vb_home, ignore_errors=True)
+
+print("\n== ssrf probe ==")
+
+
+class _SsrfHandler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ parts = urllib.parse.urlsplit(self.path)
+ target_url = urllib.parse.parse_qs(parts.query).get("url", [""])[0]
+ if target_url:
+ try:
+ urllib.request.urlopen(target_url, timeout=3).read()
+ except Exception:
+ pass
+ body = b"fetched"
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+class _NoFetchHandler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ body = b"ignored"
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+
+ssrf_srv = http.server.HTTPServer(("127.0.0.1", 0), _SsrfHandler)
+ssrfp = ssrf_srv.server_address[1]
+threading.Thread(target=ssrf_srv.serve_forever, daemon=True).start()
+nofetch_srv = http.server.HTTPServer(("127.0.0.1", 0), _NoFetchHandler)
+nofetchp = nofetch_srv.server_address[1]
+threading.Thread(target=nofetch_srv.serve_forever, daemon=True).start()
+ssrf_home = tempfile.mkdtemp(prefix="apex-ssrf-")
+write_scope(ssrf_home, {"label": "ssrf", "expires": "2099-12-31T23:59:59Z",
+ "allow_private": True, "allow_ip": ["127.0.0.1"],
+ "allow_port": [str(ssrfp), str(nofetchp)]})
+res, _ = run([
+ call(1, "ssrf_probe", target="127.0.0.1", port=ssrfp, path="/fetch",
+ param="url", wait_ms=600, tls=False),
+ call(2, "ssrf_probe", target="127.0.0.1", port=nofetchp, path="/fetch",
+ param="url", wait_ms=300, tls=False),
+], home=ssrf_home)
+by_id = {r.get("id"): r for r in res}
+ssrf = json.loads(text(by_id[1]))
+check("ssrf_probe sees its own callback", ssrf["confirmed"] is True and
+ len(ssrf["callbacks"]) >= 1, ssrf)
+check("ssrf_probe keeps the callback request as evidence",
+ all(c.get("evidence") and os.path.isfile(c["evidence"])
+ for c in ssrf["callbacks"]), ssrf["callbacks"][:1])
+check("ssrf_probe does not invent a callback when the server ignores the URL",
+ json.loads(text(by_id[2]))["confirmed"] is False, text(by_id[2]))
+ssrf_srv.shutdown()
+ssrf_srv.server_close()
+nofetch_srv.shutdown()
+nofetch_srv.server_close()
+shutil.rmtree(ssrf_home, ignore_errors=True)
red_srv.shutdown()
red_srv.server_close()
clean_srv.shutdown()
@@ -2811,7 +2876,80 @@ check("web_log_audit flags the 4xx burst source",
wl["burst_ips"])
check("web_log_audit refuses a path outside the allowed roots", err(by_id[2]),
text(by_id[2]))
-shutil.rmtree(blue_home, ignore_errors=True)
+print("\n== detections and integrity ==")
+det_home = tempfile.mkdtemp(prefix="apex-det-")
+write_scope(det_home, {"label": "det", "expires": "2099-12-31T23:59:59Z",
+ "allow_private": True, "allow_ip": ["10.10.0.0/24"],
+ "allow_port": ["80"]})
+res, _ = run([
+ call(1, "finding_add", target="10.10.0.5", title="Exposed git",
+ severity="high", confidence="certain"),
+ call(2, "finding_add", target="10.10.0.5", title="Missing HSTS",
+ severity="critical", confidence="firm"),
+ call(3, "detect_rules", limit=10),
+ call(4, "detect_rules", target="none.example"),
+], home=det_home)
+by_id = {r.get("id"): r for r in res}
+rules = json.loads(text(by_id[3]))
+check("detect_rules writes three rules per finding",
+ rules["generated"] == 6 and len(rules["files"]) == 6, rules)
+det_dir = os.path.join(det_home, "detections")
+sigma = os.path.join(det_dir, "sigma-f0001.yml")
+suricata = os.path.join(det_dir, "suricata-f0001.rules")
+yara = os.path.join(det_dir, "yara-f0001.yar")
+check("detect_rules writes Sigma, Suricata and YARA files",
+ os.path.isfile(sigma) and os.path.isfile(suricata) and
+ os.path.isfile(yara), os.listdir(det_dir))
+with open(sigma) as f:
+ sy = f.read()
+with open(suricata) as f:
+ su = f.read()
+with open(yara) as f:
+ ya = f.read()
+check("the Sigma rule names the finding", "Exposed git" in sy and
+ "level: high" in sy, sy[:200])
+check("the Suricata rule carries the host and a sid",
+ "http_host" in su and "sid:9000001" in su, su)
+check("the YARA rule has a rule name and the target",
+ "rule APEX_f0001" in ya and "10.10.0.5" in ya, ya[:200])
+check("detect_rules filters by target", json.loads(text(by_id[4]))["generated"] == 0,
+ text(by_id[4]))
+
+tree = os.path.join(det_home, "tree")
+os.makedirs(tree)
+for name, data in (("a.txt", b"alpha"), ("b.txt", b"beta"),
+ ("abc.txt", b"abc")):
+ with open(os.path.join(tree, name), "wb") as f:
+ f.write(data)
+res, _ = run([call(1, "integrity_baseline", action="create", path=tree)],
+ home=det_home)
+made = json.loads(text(res[0]))
+check("integrity_baseline hashes the tree", made["files"] == 3, made)
+baseline = os.path.join(det_home, "baseline.jsonl")
+check("integrity_baseline wrote the manifest", os.path.isfile(baseline),
+ os.listdir(det_home))
+with open(baseline) as f:
+ lines = [line for line in f if line.strip()]
+check("the manifest has one line per file", len(lines) == 3, lines)
+abc = [line for line in lines if "abc.txt" in line][0]
+check("the hash of 'abc' is the SHA-256 test vector",
+ "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" in abc,
+ abc)
+with open(os.path.join(tree, "a.txt"), "wb") as f:
+ f.write(b"alpha-modified")
+os.unlink(os.path.join(tree, "b.txt"))
+with open(os.path.join(tree, "c.txt"), "wb") as f:
+ f.write(b"gamma")
+res, _ = run([call(1, "integrity_baseline", action="verify", path=tree)],
+ home=det_home)
+ver = json.loads(text(res[0]))
+check("integrity_baseline sees the modified file", ver["changed"] == 1, ver)
+check("integrity_baseline sees the deleted file", ver["missing"] == 1, ver)
+check("integrity_baseline sees the new file", ver["added"] == 1, ver)
+check("integrity_baseline reports what changed",
+ {d["what"] for d in ver["details"]} == {"changed", "missing", "added"},
+ ver["details"])
+shutil.rmtree(det_home, ignore_errors=True)
print("\n== esp32 tools ==")
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
@@ -2836,6 +2974,10 @@ res, _ = run([
call(1, "esp_monitor", serial=esp_path, seconds=1),
call(2, "esp_info", serial="/nonexistent/ttyESP0"),
call(3, "esp_read_flash", serial="/nonexistent/ttyESP0", size=99999999),
+ call(4, "esp_flash", image=os.path.join(esp_home, "fw.bin")),
+ call(5, "esp_flash", image="/nonexistent/fw.bin", confirm=True),
+ call(6, "esp_flash", image=os.path.join(esp_home, "fw.bin"),
+ confirm=False),
], home=esp_home)
esp_stop.set()
writer.join(timeout=2)
@@ -2850,6 +2992,12 @@ check("esp_info reports the serial and esptool state",
info["serial"] == "/nonexistent/ttyESP0" and
isinstance(info["esptool"], bool), info)
check("esp_read_flash validates the size", err(by_id[3]), text(by_id[3]))
+with open(os.path.join(esp_home, "fw.bin"), "wb") as f:
+ f.write(b"\x00" * 64)
+check("esp_flash refuses to run without confirm=true",
+ err(by_id[4]) and "confirm=true" in text(by_id[4]), text(by_id[4]))
+check("esp_flash refuses a missing image", err(by_id[5]), text(by_id[5]))
+check("esp_flash refuses a false confirm", err(by_id[6]), text(by_id[6]))
shutil.rmtree(esp_home, ignore_errors=True)
print("\n== store limits ==")