diff --git a/CHANGELOG.md b/CHANGELOG.md index c986133..193efce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,26 @@ 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.7.0 — 2026-11-21 — this change +## 1.8.0 — 2026-11-21 — this change + +- **Red, web input** (`tools_red.c`): `param_fuzz` sends three benign probes per + parameter (unique marker, single quote, `{{1337*7}}`) through GET query or + POST form and reports marker reflection, SQL error strings, stack traces, + template errors and template evaluation (9359); 10 parameters, 100 ms apart, + first hits saved as evidence. `open_redirect` sends an external marker URL + and a protocol-relative variant through one parameter and checks Location + or a meta refresh. `host_header_injection` sends a `.invalid` canary as Host + (plain HTTP) and X-Forwarded-Host and reports body/Location reflection with + the baseline status and size. +- **Blue:** `net_baseline` builds and verifies a baseline of listening TCP + ports with the process that owns each socket (`/proc/net/tcp{,6}` plus + `/proc//fd`), reporting new ports, vanished ports and process changes. +- Tests with a local web fixture (reflecting endpoint, SQL error on quote, + template evaluation, redirect, Host echo, static pages), plus a real + socket-open/socket-close pair around the port baseline. 553 checks. + Coverage 79.9%. + +## 1.7.0 — 2026-11-21 — 276283d - **MySQL** (`mysql_probe`, new `tools_db.c`): parses the initial handshake — protocol version, server version, thread id, auth plugin and the capability diff --git a/README.md b/README.md index 5f7b0a0..d9c1d8c 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. -**77 tools · 537 end-to-end checks · 340 fuzz cases · 79.6% line coverage · ~375 KiB** +**81 tools · 553 end-to-end checks · 340 fuzz cases · 79.9% line coverage · ~391 KiB** ``` $ ./apex-twin --check -{"version":"1.7.0","tools":77,...,"scope":{"loaded":true,...}} +{"version":"1.8.0","tools":81,...,"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 (77) +## Tools (81) ### Scope and bookkeeping @@ -254,6 +254,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | | `jwt_audit` | Offline JWT audit: alg/typ/kid, iss/aud/sub/exp/iat/nbf, alg=none, expired, missing exp, path-like kid; HS256 signature verified with `secret=` | | `hash_id` | Identify a hash shape: MD5/NTLM, SHA-1/256/512, bcrypt, Argon2, crypt(3) formats, JWT | +| `param_fuzz` | Marker, quote and `{{1337*7}}` per parameter; reports reflection, SQL/stack/template errors and template evaluation | +| `open_redirect` | Sends an external marker URL and a protocol-relative variant; reports Location/meta-refresh redirects with evidence | +| `host_header_injection` | Canary as Host and X-Forwarded-Host; reports reflection in body or Location, with baseline size | | `ftp_probe` | One FTP connection: banner, FEAT list, and whether the literal anonymous pair is accepted (audited) | | `smtp_probe` | One SMTP connection: banner, EHLO extensions, VRFY of up to 8 users classified exists/unknown/cannot-verify | | `ssh_audit` | Banner plus KEXINIT lists (kex, host key, ciphers, MACs) and deprecated algorithms flagged | @@ -279,6 +282,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `mitre_map` | Map findings to ATT&CK techniques by title/tool/tags/CWE, with finding ids per technique | | `process_snapshot` | Read `/proc`: exe/fd count per process, flags /tmp or deleted executables, reverse-shell command lines, >256 fds | | `persistence_audit` | Cron, systemd units/timers and at jobs: flags /tmp paths, curl/wget piped to a shell, base64-to-shell, nc -e/socat, bash -i, setuid chmod | +| `net_baseline` | Listening TCP ports with owning process names (`create`/`verify`); reports new, gone and process-changed ports | ### ESP32 @@ -468,6 +472,8 @@ The full threat model, trust boundaries and a hardening checklist are in | SNMP | 4 communities, 2 attempts each, 1.8 s wait | | Zone transfer | one server, one in-scope zone, 30 s | | Database probes | one or two connections each; no password attempts | +| Param fuzz | 10 parameters × 3 probes per call, 100 ms apart | +| Net baseline | 500 ports; process lookup capped by /proc walk | --- @@ -478,7 +484,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 537 end-to-end checks +make test # version check + gate audit + 553 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 @@ -580,8 +586,12 @@ src/tools_kb.c technique and tool notes (data, not code) src/tools_asset.c inventory tools 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_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, + http_brute, ssrf_probe, jwt_audit, hash_id, param_fuzz, + open_redirect, host_header_injection +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 src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe, dns_zone_transfer @@ -616,7 +626,7 @@ examples/ scope.json ## Status -1.7.0. Built and run: 77 tools, 537 checks, 340 fuzz cases and 79.6% line +1.8.0. Built and run: 81 tools, 553 checks, 340 fuzz cases and 79.9% 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 @@ -641,8 +651,9 @@ verification, detection-rule export, integrity baselines and firmware writing (confirm-gated); 1.4 added offline JWT/hash analysis, ATT&CK mapping and a /proc snapshot; 1.5 added FTP/SMTP/SSH service probes and a persistence audit; 1.6 added TLS, Redis, SNMP and DNS zone-transfer checks; 1.7 added MySQL, -PostgreSQL, MongoDB and Memcached probes, again without changing an existing -tool or file format. +PostgreSQL, MongoDB and Memcached probes; 1.8 added parameter fuzzing, open +redirect and Host-header checks plus a network baseline, 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 96031d2..4ec2090 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.7.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.8.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current line. The 1.0 line promises that the on-disk JSON formats for findings, assets and traffic only gain fields, so state stays readable; older builds are still rebuilt rather than patched in place. @@ -66,6 +66,10 @@ only narrow what the proxy does (the scope gate still runs first). - **Firmware writing needs an explicit confirmation.** `esp_flash` refuses without `confirm=true`, validates an absolute image path and audits the attempt; it exists to provision the operator's own board. +- **Web input probes send markers, not exploits.** `param_fuzz` injects a + unique marker, a single quote and `{{1337*7}}`, then looks for reflection and + error signatures; `open_redirect` sends a URL on example.com; `host_header_- + injection` sends a `.invalid` canary. None extracts data or executes code. - **Database probes read one greeting, never a password.** `mysql_probe` reads the initial handshake, `postgres_probe` sends one StartupMessage with no password and reports the auth method, `mongo_probe` sends `isMaster` and diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 2136e20..3113881 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.7.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.8.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -39,10 +39,11 @@ testing it carries offensive verification (vuln_check, subdomain_enum, cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id, ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe, dns_zone_transfer, mysql_probe, postgres_probe, mongo_probe, -memcached_probe), defensive audits (hardening_audit, log_audit, ioc_scan, -web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, -persistence_audit) and ESP32 board tools (esp_info, esp_monitor, -esp_read_flash, esp_flash). +memcached_probe, param_fuzz, open_redirect, host_header_injection), defensive +audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, +integrity_baseline, mitre_map, process_snapshot, persistence_audit, +net_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 28263bc..520d883 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.7.0" +#define APEX_VERSION "1.8.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 diff --git a/src/tools_blue.c b/src/tools_blue.c index 91f8b98..2f14c10 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -1971,6 +1971,309 @@ static void t_persistence_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* -------------------------------------------------------------- net_baseline */ + +typedef struct { + int port; + unsigned long inode; + char process[64]; + int seen; +} net_entry; + +static int net_collect(net_entry *ents, int max) +{ + static const char *files[2] = { "/proc/net/tcp", "/proc/net/tcp6" }; + int n = 0; + int fi; + + for (fi = 0; fi < 2; fi++) { + FILE *f = fopen(files[fi], "rb"); + char line[1024]; + + if (f == NULL) + continue; + if (fgets(line, sizeof(line), f) == NULL) { + fclose(f); + continue; + } + while (fgets(line, sizeof(line), f) != NULL && n < max) { + char *fields[12]; + int nf = 0; + char *save = NULL; + char *tok; + char *colon; + int port; + unsigned long ino; + int i; + int dup = 0; + + for (tok = strtok_r(line, " \t\n", &save); tok != NULL && + nf < 12; tok = strtok_r(NULL, " \t\n", &save)) + fields[nf++] = tok; + if (nf < 10) + continue; + if (strcmp(fields[3], "0A") != 0) + continue; + colon = strrchr(fields[1], ':'); + if (colon == NULL) + continue; + port = (int)strtoul(colon + 1, NULL, 16); + if (port <= 0 || port > 65535) + continue; + ino = strtoul(fields[9], NULL, 10); + for (i = 0; i < n; i++) + if (ents[i].port == port) + dup = 1; + if (dup) + continue; + ents[n].port = port; + ents[n].inode = ino; + ents[n].process[0] = '\0'; + ents[n].seen = 0; + n++; + } + fclose(f); + } + return n; +} + +static void net_process_names(net_entry *ents, int n) +{ + DIR *proc; + struct dirent *pe; + int found = 0; + + if (n == 0) + return; + proc = opendir("/proc"); + if (proc == NULL) + return; + while ((pe = readdir(proc)) != NULL && found < n) { + char fdpath[64]; + DIR *fds; + struct dirent *fe; + + if (pe->d_name[0] < '0' || pe->d_name[0] > '9') + continue; + snprintf(fdpath, sizeof(fdpath), "/proc/%.32s/fd", pe->d_name); + fds = opendir(fdpath); + if (fds == NULL) + continue; + while ((fe = readdir(fds)) != NULL && found < n) { + char full[128]; + char link[128]; + ssize_t r; + unsigned long ino; + int i; + + if (fe->d_name[0] == '.') + continue; + snprintf(full, sizeof(full), "/proc/%.32s/fd/%.48s", + pe->d_name, fe->d_name); + r = readlink(full, link, sizeof(link) - 1); + if (r <= 0) + continue; + link[r] = '\0'; + if (strncmp(link, "socket:[", 8) != 0) + continue; + ino = strtoul(link + 8, NULL, 10); + for (i = 0; i < n; i++) { + char commpath[64]; + char comm[64]; + + if (ents[i].inode != ino || ents[i].process[0] != '\0') + continue; + snprintf(commpath, sizeof(commpath), "/proc/%.32s/comm", + pe->d_name); + if (read_text(commpath, comm, sizeof(comm)) > 0) { + trim_eol(comm); + snprintf(ents[i].process, + sizeof(ents[i].process), "%.48s", comm); + } else { + snprintf(ents[i].process, + sizeof(ents[i].process), "%s", "-"); + } + found++; + break; + } + } + closedir(fds); + } + closedir(proc); +} + +static int net_write_baseline(const char *path, net_entry *ents, int n) +{ + mcp_buf b; + int i; + int rc; + + mcp_buf_init(&b); + for (i = 0; i < n; i++) { + mcp_buf_printf(&b, "{\"port\":%d,\"process\":", ents[i].port); + apex_json_str(&b, ents[i].process); + mcp_buf_puts(&b, "}\n"); + } + rc = apex_write_file(path, b.p != NULL ? b.p : "", b.len, 0600); + mcp_buf_free(&b); + return rc; +} + +static void t_net_baseline(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *action = mcp_arg_string(args, "action"); + const char *baseline = mcp_arg_string(args, "baseline"); + int limit = mcp_arg_int(args, "limit", 500); + char base_path[APEX_PATH_FULL]; + net_entry current[512]; + net_entry base[512]; + int ncur; + int nbase = 0; + mcp_buf b; + int create; + int i; + + (void)user; + 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 > 500) + limit = 500; + if (baseline != NULL && *baseline != '\0') + snprintf(base_path, sizeof(base_path), "%s", baseline); + else + snprintf(base_path, sizeof(base_path), "%s/net-baseline.jsonl", + g_cfg.home); + ncur = net_collect(current, limit); + net_process_names(current, ncur); + if (create) { + if (net_write_baseline(base_path, current, ncur) != 0) { + mcp_reply_error(c, "cannot write the network baseline"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"action\":\"create\",\"baseline\":"); + apex_json_str(&b, base_path); + mcp_buf_printf(&b, ",\"listening\":%d,\"ports\":[", ncur); + for (i = 0; i < ncur; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"port\":"); + mcp_buf_printf(&b, "%d,\"process\":", current[i].port); + apex_json_str(&b, current[i].process); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + return; + } + { + FILE *f = fopen(base_path, "rb"); + char *line = NULL; + size_t cap = 0; + + if (f == NULL) { + mcp_reply_error(c, "no network baseline; run action=create"); + return; + } + while (nbase < 512 && getline(&line, &cap, f) >= 0) { + int port = (int)json_num_field(line, "port"); + + if (port <= 0 || port > 65535) + continue; + base[nbase].port = port; + base[nbase].inode = 0; + base[nbase].seen = 0; + json_str_field(line, "process", base[nbase].process, + sizeof(base[nbase].process)); + nbase++; + } + free(line); + fclose(f); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"action\":\"verify\",\"baseline\":"); + apex_json_str(&b, base_path); + mcp_buf_printf(&b, ",\"listening\":%d,\"new\":[", ncur); + { + int first = 1; + + for (i = 0; i < ncur; i++) { + int j; + int known = 0; + + for (j = 0; j < nbase; j++) + if (base[j].port == current[i].port) + known = 1; + if (known) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"port\":"); + mcp_buf_printf(&b, "%d,\"process\":", current[i].port); + apex_json_str(&b, current[i].process); + mcp_buf_puts(&b, "}"); + } + } + mcp_buf_puts(&b, "],\"gone\":["); + { + int first = 1; + + for (i = 0; i < nbase; i++) { + int j; + int seen = 0; + + for (j = 0; j < ncur; j++) + if (current[j].port == base[i].port) + seen = 1; + if (seen) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_printf(&b, "{\"port\":%d,\"process\":", base[i].port); + apex_json_str(&b, base[i].process); + mcp_buf_puts(&b, "}"); + } + } + mcp_buf_puts(&b, "],\"changed\":["); + { + int first = 1; + + for (i = 0; i < ncur; i++) { + int j; + + for (j = 0; j < nbase; j++) { + if (base[j].port != current[i].port) + continue; + if (base[j].process[0] != '\0' && + current[i].process[0] != '\0' && + strcmp(base[j].process, current[i].process) != 0) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_printf(&b, "{\"port\":%d,\"was\":", + current[i].port); + apex_json_str(&b, base[j].process); + mcp_buf_puts(&b, ",\"now\":"); + apex_json_str(&b, current[i].process); + mcp_buf_puts(&b, "}"); + } + break; + } + } + } + mcp_buf_printf(&b, "],\"baseline_ports\":%d}", nbase); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -2073,6 +2376,20 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"files to read, " "default 2000\"}}}", t_persistence_audit }, + { "net_baseline", + "Create or verify a baseline of listening TCP ports and the process that " + "owns each socket (from /proc/net/tcp{,6} and /proc//fd). Verify " + "reports new ports, ports that disappeared and ports whose process " + "changed, which catches a rogue service between two points in time. The " + "default baseline is $APEX_HOME/net-baseline.jsonl. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"action\":{\"type\":\"string\",\"enum\":[\"create\",\"verify\"]," + "\"description\":\"default verify\"}," + "\"baseline\":{\"type\":\"string\",\"description\":\"default " + "$APEX_HOME/net-baseline.jsonl\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max ports, default " + "500\"}}}", + t_net_baseline }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_red.c b/src/tools_red.c index 11a6254..deff72c 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -1525,6 +1525,529 @@ static void t_hash_id(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- param_fuzz */ + +static const char *SQL_SIGS[] = { + "SQL syntax", "mysql_fetch", "mysqli", "ORA-0", "PostgreSQL", + "SQLite/JDBCDriver", "Unclosed quotation", "SQLSTATE", + "quoted string not properly terminated", "pg_query", NULL +}; + +static const char *STACK_SIGS[] = { + "Traceback (most recent call last)", "Exception in thread", "at java.", + "Fatal error:", "Warning: ", "System.Exception", NULL +}; + +static const char *TPL_SIGS[] = { + "TemplateSyntaxError", "Jinja2", "Twig\\", "Smarty", "Undefined variable", + "FreeMarker", "Velocity", NULL +}; + +static int any_sig(const char *body, size_t len, const char *const *sigs) +{ + int i; + + for (i = 0; sigs[i] != NULL; i++) + if (find_bytes(body, len, sigs[i])) + return 1; + return 0; +} + +typedef struct { + const char *kind; + const char *value; +} fuzz_payload; + +static void t_param_fuzz(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 *params_arg = mcp_arg_string(args, "params"); + 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)); + int delay = mcp_arg_int(args, "delay_ms", 100); + char params[10][64]; + int nparams = 0; + char marker[48]; + fuzz_payload payloads[3]; + mcp_buf b; + int tested = 0; + int hits = 0; + int saved = 0; + int first = 1; + int i; + int p; + int is_post; + mcp_buf enc; + mcp_buf body; + + (void)user; + if (target == NULL || *target == '\0' || params_arg == NULL || + *params_arg == '\0') { + mcp_reply_error(c, "target and params are required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (path[0] != '/') { + mcp_reply_error(c, "path must start with /"); + return; + } + if (delay < 0 || delay > 1000) + delay = 100; + is_post = method != NULL && strcasecmp(method, "POST") == 0; + { + char *copy = strdup(params_arg); + char *save = NULL; + char *tok; + + if (copy == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + tok = strtok_r(copy, ",", &save); + while (tok != NULL && nparams < 10) { + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok != '\0') { + snprintf(params[nparams], sizeof(params[0]), "%.48s", + tok); + nparams++; + } + tok = strtok_r(NULL, ",", &save); + } + free(copy); + } + if (nparams == 0) { + mcp_reply_error(c, "no parameter names given"); + return; + } + snprintf(marker, sizeof(marker), "apex%ldz", (long)getpid()); + payloads[0].kind = "marker"; + payloads[0].value = marker; + payloads[1].kind = "quote"; + payloads[1].value = "'"; + payloads[2].kind = "template"; + payloads[2].value = "{{1337*7}}"; + if (!gated(c, "param_fuzz", target, port)) + return; + + 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_printf(&b, ",\"method\":\"%s\",\"findings\":[", + is_post ? "POST" : "GET"); + for (p = 0; p < nparams; p++) { + for (i = 0; i < 3; i++) { + char req[1800]; + char status[256]; + char *resp = NULL; + size_t len = 0; + int code; + int reflected; + int flags = 0; + int first_sig = 1; + mcp_buf signals; + char *evidence = NULL; + + mcp_buf_init(&enc); + url_enc(&enc, payloads[i].value); + mcp_buf_init(&body); + if (is_post) { + mcp_buf_printf(&body, "%s=%s", params[p], + 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, + params[p], 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); + continue; + } + tested++; + code = apex_status_code(status); + reflected = find_bytes(resp, len, payloads[i].value); + mcp_buf_init(&signals); + if (reflected && strcmp(payloads[i].kind, "marker") == 0) { + if (!first_sig) + mcp_buf_puts(&signals, ","); + first_sig = 0; + apex_json_str(&signals, "reflection"); + flags++; + } + if (any_sig(resp, len, SQL_SIGS)) { + if (!first_sig) + mcp_buf_puts(&signals, ","); + first_sig = 0; + apex_json_str(&signals, "sql-error"); + flags++; + } + if (any_sig(resp, len, STACK_SIGS)) { + if (!first_sig) + mcp_buf_puts(&signals, ","); + first_sig = 0; + apex_json_str(&signals, "stack-trace"); + flags++; + } + if (any_sig(resp, len, TPL_SIGS)) { + if (!first_sig) + mcp_buf_puts(&signals, ","); + first_sig = 0; + apex_json_str(&signals, "template-error"); + flags++; + } + if (strcmp(payloads[i].kind, "template") == 0 && + find_bytes(resp, len, "9359")) { + if (!first_sig) + mcp_buf_puts(&signals, ","); + first_sig = 0; + apex_json_str(&signals, "template-eval"); + flags++; + } + if (flags > 0) { + hits++; + if (saved < 3) { + char label[64]; + + snprintf(label, sizeof(label), "fuzz-%.20s-%.10s", + params[p], payloads[i].kind); + evidence = apex_evidence_save(label, resp, len); + saved++; + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"parameter\":"); + apex_json_str(&b, params[p]); + mcp_buf_puts(&b, ",\"payload\":"); + apex_json_str(&b, payloads[i].kind); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu," + "\"reflected\":%s,\"signals\":[", + code, (unsigned long)len, + reflected ? "true" : "false"); + if (signals.p != NULL) + mcp_buf_add(&b, signals.p, signals.len); + mcp_buf_puts(&b, "],\"evidence\":"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + free(evidence); + } + mcp_buf_free(&signals); + mcp_buf_free(&enc); + mcp_buf_free(&body); + free(resp); + if (delay > 0 && !(p == nparams - 1 && i == 2)) + sleep_ms(delay); + } + } + mcp_buf_printf(&b, "],\"tested\":%d,\"hits\":%d}", tested, hits); + apex_audit("param_fuzz", target, port, hits == 0, + hits == 0 ? "no reflection or error signature" + : "input handling signals found", path); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ------------------------------------------------------------- open_redirect */ + +static void response_location(const char *resp, size_t len, char *out, size_t n) +{ + size_t i = 0; + + out[0] = '\0'; + while (i < len) { + size_t start = i; + size_t end; + size_t w = 0; + + while (i < len && resp[i] != '\n') + i++; + end = i; + if (i < len) + i++; + if (end > start && resp[start] == '\r') + start++; + if (end >= start + 9 && strncasecmp(resp + start, "Location:", 9) == 0) { + const char *v = resp + start + 9; + + while (v < resp + end && (*v == ' ' || *v == '\t')) + v++; + while (v < resp + end && *v != '\r' && *v != '\n' && + w + 1 < n) + out[w++] = *v++; + while (w > 0 && (out[w - 1] == ' ' || out[w - 1] == '\t')) + w--; + out[w] = '\0'; + return; + } + } +} + +static void t_open_redirect(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 *external = mcp_arg_string(args, "external"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + char host[256]; + char variant[2][600]; + int nvariants = 1; + mcp_buf b; + int first = 1; + int confirmed = 0; + int i; + char *evidence = NULL; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (path[0] != '/') { + mcp_reply_error(c, "path must start with /"); + return; + } + if (param == NULL || *param == '\0') + param = "next"; + if (external == NULL || *external == '\0') + external = "https://example.com/apex-redirect"; + host[0] = '\0'; + { + const char *scheme = strstr(external, "://"); + + if (scheme == NULL) { + mcp_reply_error(c, "external must be an absolute URL"); + return; + } + scheme += 3; + { + size_t w = 0; + + while (scheme[w] != '\0' && scheme[w] != '/' && + scheme[w] != ':' && w + 1 < sizeof(host)) { + host[w] = scheme[w]; + w++; + } + host[w] = '\0'; + } + } + if (host[0] == '\0') { + mcp_reply_error(c, "cannot parse the external host"); + return; + } + snprintf(variant[0], sizeof(variant[0]), "%s", external); + snprintf(variant[1], sizeof(variant[1]), "//%s/apex-redirect", host); + nvariants = 2; + if (!gated(c, "open_redirect", target, port)) + return; + + 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_puts(&b, ",\"results\":["); + for (i = 0; i < nvariants; i++) { + char req[1800]; + char status[256]; + char location[600]; + char *resp = NULL; + size_t len = 0; + int code; + const char *sep = strchr(path, '?') != NULL ? "&" : "?"; + mcp_buf enc; + int hit = 0; + const char *via = "none"; + + mcp_buf_init(&enc); + url_enc(&enc, variant[i]); + snprintf(req, sizeof(req), "%s%s%s=%s", path, sep, param, + enc.p != NULL ? enc.p : ""); + mcp_buf_free(&enc); + status[0] = '\0'; + location[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", req, NULL, NULL, 8000, + &resp, &len, status, sizeof(status)) != 0) + continue; + code = apex_status_code(status); + response_location(resp, len, location, sizeof(location)); + if (((code == 301 || code == 302 || code == 303 || code == 307 || + code == 308) && strstr(location, host) != NULL)) { + hit = 1; + via = "location"; + } else if (strstr(location, host) != NULL) { + hit = 1; + via = "location"; + } else if (find_bytes(resp, len, "http-equiv") && + find_bytes(resp, len, host)) { + hit = 1; + via = "meta-refresh"; + } + if (hit) { + confirmed++; + if (evidence == NULL) + evidence = apex_evidence_save("redirect", resp, len); + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"value\":"); + apex_json_str(&b, variant[i]); + mcp_buf_printf(&b, ",\"status\":%d,\"location\":", code); + apex_json_str(&b, location); + mcp_buf_printf(&b, ",\"redirected\":%s,\"via\":\"%s\"}", + hit ? "true" : "false", via); + free(resp); + } + mcp_buf_printf(&b, "],\"confirmed\":%d,\"evidence\":", confirmed); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("open_redirect", target, port, confirmed == 0, + confirmed == 0 ? "no open redirect" : "redirect to an external host", + path); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(evidence); +} + +/* ------------------------------------------------------ host_header_injection */ + +static void t_host_header_injection(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 *canary = mcp_arg_string(args, "canary"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + char status[256]; + char *resp = NULL; + size_t len = 0; + int base_status = 0; + long base_len = 0; + mcp_buf b; + int first = 1; + int confirmed = 0; + int variant; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (path[0] != '/') { + mcp_reply_error(c, "path must start with /"); + return; + } + if (canary == NULL || *canary == '\0') + canary = "apex-canary.invalid"; + if (!gated(c, "host_header_injection", target, port)) + return; + status[0] = '\0'; + if (http_with_host(target, port, target, path, &resp, &len, status, + sizeof(status)) == 0) { + base_status = apex_status_code(status); + base_len = (long)len; + free(resp); + } + resp = NULL; + 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, ",\"canary\":"); + apex_json_str(&b, canary); + mcp_buf_printf(&b, ",\"baseline\":{\"status\":%d,\"bytes\":%ld}," + "\"findings\":[", base_status, base_len); + for (variant = 0; variant < 2; variant++) { + const char *label = variant == 0 ? "Host" : "X-Forwarded-Host"; + char location[600]; + char *evidence = NULL; + int code; + int reflected; + int redirected; + + status[0] = '\0'; + location[0] = '\0'; + if (variant == 0) { + if (http_with_host(target, port, canary, path, &resp, &len, + status, sizeof(status)) != 0) + continue; + } else { + char header[320]; + + snprintf(header, sizeof(header), "X-Forwarded-Host: %.200s\r\n", + canary); + if (apex_http_once(target, port, tls, "GET", path, NULL, header, + 8000, &resp, &len, status, + sizeof(status)) != 0) + continue; + } + code = apex_status_code(status); + response_location(resp, len, location, sizeof(location)); + reflected = find_bytes(resp, len, canary); + redirected = strstr(location, canary) != NULL; + if (reflected || redirected) { + confirmed++; + evidence = apex_evidence_save("host-header", resp, len); + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"header\":"); + apex_json_str(&b, label); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu," + "\"reflected\":%s,\"redirect\":%s,\"evidence\":", + code, (unsigned long)len, + reflected ? "true" : "false", + redirected ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + free(evidence); + free(resp); + resp = NULL; + } + mcp_buf_printf(&b, "],\"confirmed\":%d}", confirmed); + apex_audit("host_header_injection", target, port, confirmed == 0, + confirmed == 0 ? "canary not reflected" + : "canary reflected or redirected", + path); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -1658,6 +2181,54 @@ const mcp_tool TOOLS_RED[] = { "\"value\":{\"type\":\"string\"}}," "\"required\":[\"value\"]}", t_hash_id }, + { "param_fuzz", + "Inject three benign probes per parameter (a unique marker, a single " + "quote and {{1337*7}}) through GET query or POST form and report what " + "comes back: marker reflection, SQL error strings, stack traces, " + "template errors and template evaluation (9359). 100 ms apart, 10 " + "parameters max, first three hits saved as evidence. It proves handling " + "signals; it does not extract data. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"params\":{\"type\":\"string\",\"description\":\"comma list, max 10\"}," + "\"method\":{\"type\":\"string\",\"enum\":[\"GET\",\"POST\"]," + "\"description\":\"default GET\"}," + "\"delay_ms\":{\"type\":\"integer\",\"description\":\"default 100\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\",\"params\"]}", + t_param_fuzz }, + { "open_redirect", + "Send an external marker URL and a protocol-relative variant through one " + "redirect parameter and check the response Location header (or a meta " + "refresh) for the marker host. Reports each variant with status and " + "location, saves a confirmed hit as evidence. 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\",\"description\":\"default next\"}," + "\"external\":{\"type\":\"string\",\"description\":\"marker URL, " + "default https://example.com/apex-redirect\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_open_redirect }, + { "host_header_injection", + "Send a canary as Host (plain HTTP) and as X-Forwarded-Host, then report " + "whether it appears in the body or in a Location header, with the " + "baseline status and size for comparison. Each hit is saved as evidence. " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"canary\":{\"type\":\"string\",\"description\":\"default " + "apex-canary.invalid\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_host_header_injection }, }; 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 21727c4..9710111 100755 --- a/tests/gate_audit.py +++ b/tests/gate_audit.py @@ -21,7 +21,7 @@ import re import sys HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -EXPECTED_TOOLS = 77 +EXPECTED_TOOLS = 81 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. diff --git a/tests/run.py b/tests/run.py index 6a9edde..5e07439 100755 --- a/tests/run.py +++ b/tests/run.py @@ -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("77 tools registered", len(tools) == 77, len(tools)) +check("81 tools registered", len(tools) == 81, 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"]) == 77) + check("http tools/list", len(listing["result"]["tools"]) == 81) 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 @@ -3708,6 +3708,147 @@ for srv in (mysql_srv, pg_trust_srv, pg_md5_srv, pg_reject_srv, srv.close() shutil.rmtree(db_home, ignore_errors=True) +print("\n== web input handling and network baseline ==") + + +class _WebAdvHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + parts = urllib.parse.urlsplit(self.path) + qs = urllib.parse.parse_qs(parts.query) + code = 200 + location = None + if parts.path == "/search": + q = qs.get("q", [""])[0] + if "'" in q: + body = b"You have an error in your SQL syntax near ..." + elif "{{1337*7}}" in q: + body = b"result: 9359" + else: + body = ("echo:" + q).encode() + elif parts.path == "/plain": + body = b"static page" + elif parts.path == "/go": + target = qs.get("next", [""])[0] + if target.startswith("http") or target.startswith("//"): + code = 302 + location = target + body = b"" + else: + body = b"no redirect" + elif parts.path == "/safe-redirect": + body = b"no redirect" + elif parts.path == "/host": + body = ("host=" + self.headers.get("Host", "") + + " xfh=" + self.headers.get("X-Forwarded-Host", "")).encode() + elif parts.path == "/host-safe": + body = b"static" + else: + code = 404 + body = b"nope" + self.send_response(code) + if location is not None: + self.send_header("Location", location) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + if body: + self.wfile.write(body) + + def log_message(self, *args): + pass + + +adv_srv = http.server.HTTPServer(("127.0.0.1", 0), _WebAdvHandler) +adv_port = adv_srv.server_address[1] +threading.Thread(target=adv_srv.serve_forever, daemon=True).start() + +adv_home = tempfile.mkdtemp(prefix="apex-adv-") +write_scope(adv_home, {"label": "adv", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(adv_port)]}) + +l1 = socket.socket() +l1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +l1.bind(("127.0.0.1", 0)) +l1.listen(1) +l1_port = l1.getsockname()[1] + +res, _ = run([ + call(1, "param_fuzz", target="127.0.0.1", port=adv_port, path="/search", + params="q", delay_ms=0, tls=False), + call(2, "param_fuzz", target="127.0.0.1", port=adv_port, path="/plain", + params="q", delay_ms=0, tls=False), + call(3, "open_redirect", target="127.0.0.1", port=adv_port, path="/go", + param="next", tls=False), + call(4, "open_redirect", target="127.0.0.1", port=adv_port, + path="/safe-redirect", param="next", tls=False), + call(5, "host_header_injection", target="127.0.0.1", port=adv_port, + path="/host", tls=False), + call(6, "host_header_injection", target="127.0.0.1", port=adv_port, + path="/host-safe", tls=False), + call(7, "net_baseline", action="create"), + call(8, "param_fuzz", target="198.51.100.9", port=80, params="q"), +], home=adv_home) +by_id = {r.get("id"): r for r in res} +fuzz = json.loads(text(by_id[1])) +signals = {tuple(sorted(f["signals"])) for f in fuzz["findings"]} +flat = {s for f in fuzz["findings"] for s in f["signals"]} +check("param_fuzz tests every parameter and payload", fuzz["tested"] == 3, fuzz) +check("param_fuzz sees the marker reflection", "reflection" in flat, fuzz) +check("param_fuzz sees the SQL error", "sql-error" in flat, fuzz) +check("param_fuzz sees the template evaluation", "template-eval" in flat, fuzz) +check("param_fuzz saves evidence for its hits", + all(f["evidence"] and os.path.isfile(f["evidence"]) + for f in fuzz["findings"]), fuzz["findings"]) +clean_fuzz = json.loads(text(by_id[2])) +check("param_fuzz finds nothing on a static page", + clean_fuzz["hits"] == 0 and clean_fuzz["tested"] == 3, clean_fuzz) +redir = json.loads(text(by_id[3])) +check("open_redirect follows both external variants", + redir["confirmed"] == 2 and + all(r["redirected"] for r in redir["results"]) and + redir["results"][0]["location"].startswith("https://example.com"), + redir) +check("open_redirect keeps the hit as evidence", + redir["evidence"] and os.path.isfile(redir["evidence"]), redir) +safe_redir = json.loads(text(by_id[4])) +check("open_redirect stays quiet on a safe endpoint", + safe_redir["confirmed"] == 0, safe_redir) +hhi = json.loads(text(by_id[5])) +headers = {f["header"]: f for f in hhi["findings"]} +check("host_header_injection reflects Host and X-Forwarded-Host", + headers["Host"]["reflected"] is True and + headers["X-Forwarded-Host"]["reflected"] is True and + hhi["confirmed"] == 2, hhi) +check("host_header_injection saves evidence", + all(f["evidence"] and os.path.isfile(f["evidence"]) + for f in hhi["findings"]), hhi["findings"]) +safe_hhi = json.loads(text(by_id[6])) +check("host_header_injection stays quiet on a static page", + safe_hhi["confirmed"] == 0, safe_hhi) +made = json.loads(text(by_id[7])) +check("net_baseline records the listening ports", + made["listening"] >= 1 and + os.path.isfile(os.path.join(adv_home, "net-baseline.jsonl")), made) +l1.close() +l2 = socket.socket() +l2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) +l2.bind(("127.0.0.1", 0)) +l2.listen(1) +l2_port = l2.getsockname()[1] +res, _ = run([call(1, "net_baseline", action="verify")], home=adv_home) +ver = json.loads(text(res[0])) +new_ports = {e["port"] for e in ver["new"]} +gone_ports = {e["port"] for e in ver["gone"]} +check("net_baseline sees the new listener", l2_port in new_ports, ver["new"]) +check("net_baseline sees the closed listener", l1_port in gone_ports, + ver["gone"]) +l2.close() +check("param_fuzz refuses an out-of-scope target", err(by_id[8]), + text(by_id[8])) +adv_srv.shutdown() +adv_srv.server_close() +shutil.rmtree(adv_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"})