diff --git a/CHANGELOG.md b/CHANGELOG.md index 0787469..2a2cbc3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,23 @@ 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.1.0 — 2026-11-21 — this change +## 1.2.0 — 2026-11-21 — this change + +- **Red:** `vhost_discovery` fuzzes the Host header against one in-scope IP + (built-in list or `names=`), diffs status, byte count and `` against a + baseline, and saves each deviation as evidence; plain HTTP only. `http_brute` + probes hidden paths from a built-in list, a comma list or a wordlist file + (comments allowed), treats 200/201/204/3xx/401/403 as hits, waits 100 ms + between requests and saves the first five 200/201 responses as evidence. +- **Blue:** `web_log_audit` reads an nginx/apache access log: 2xx/3xx/4xx/5xx + split, top IPs, scanner user agents (sqlmap, nikto, nmap, gobuster, nuclei, + ...), SQLi/traversal/XSS patterns after percent-decoding the URI (deduplicated + per pattern) and source IPs with a 4xx/5xx burst. +- Tests with local fixtures: a Host-routing origin, a path-routing origin with a + wordlist file, and a synthetic access log with encoded SQLi and traversal. + 456 checks. Coverage 79.6%. + +## 1.1.0 — 2026-11-21 — da4d9ab The suite grows from reconnaissance into a red/blue/hardware toolset. No existing tool changed behaviour or file format. diff --git a/README.md b/README.md index ef247dd..1e0a629 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. -**54 tools · 439 end-to-end checks · 340 fuzz cases · 79.0% line coverage · ~276 KiB** +**57 tools · 456 end-to-end checks · 340 fuzz cases · 79.6% line coverage · ~292 KiB** ``` $ ./apex-twin --check -{"version":"1.1.0","tools":54,...,"scope":{"loaded":true,...}} +{"version":"1.2.0","tools":57,...,"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 (54) +## Tools (57) ### Scope and bookkeeping @@ -249,6 +249,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `vuln_check` | Non-destructive verification of `/.git/HEAD`, `/.env` (keys only, values redacted), directory listing and `phpinfo`; raw response saved as evidence | | `subdomain_enum` | Built-in wordlist (or your names) under one in-scope domain; every name is gate-checked before it is resolved | | `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 | ### Blue team @@ -257,6 +259,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `hardening_audit` | Read-only local posture: sshd_config, sysctl, `/etc/shadow` mode, world-writable `/etc` dirs, listening sockets, firewall files, SUID count; scored findings | | `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 | ### ESP32 @@ -435,6 +438,8 @@ The full threat model, trust boundaries and a hardening checklist are in | Radio scan | 3–300 s, always ends with `stopscan` | | Credential attempts | 20 per call, 200 ms apart, stop on 429 | | 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 | --- @@ -445,7 +450,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 439 end-to-end checks +make test # version check + gate audit + 456 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 @@ -578,7 +583,7 @@ examples/ scope.json ## Status -1.1.0. Built and run: 54 tools, 439 checks, 340 fuzz cases and 79.0% line +1.2.0. Built and run: 57 tools, 456 checks, 340 fuzz cases and 79.6% 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 @@ -597,8 +602,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 without changing any existing -tool or file format. +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. Not yet wired into a fleet router, and there is no TLS interception. diff --git a/SECURITY.md b/SECURITY.md index c38e526..bab30c1 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.1.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.2.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. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index cc5ba1a..956b9da 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.1.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.2.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS diff --git a/src/apex.h b/src/apex.h index 4af8988..d143799 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.1.0" +#define APEX_VERSION "1.2.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 78df4b4..ccdc1eb 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -13,6 +13,7 @@ * None of these touch a network or change anything on disk. They are the * "did anyone notice" half of an engagement: run them on the host you defend. */ +#include <ctype.h> #include <dirent.h> #include <errno.h> #include <stdarg.h> @@ -713,6 +714,296 @@ static void t_ioc_scan(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ----------------------------------------------------------- web_log_audit */ + +typedef struct { + char ip[64]; + int total; + int c4xx; + int c5xx; +} web_ip; + +static const char *SCANNERS[] = { + "sqlmap", "nikto", "nmap", "masscan", "gobuster", "dirbuster", "ffuf", + "nuclei", "hydra", "zgrab", "acunetix", "nessus", "wpscan", "joomscan", + NULL +}; + +static const char *WEB_PATTERNS[] = { + "' or ", "union select", "../", "/etc/passwd", "<script", "onerror=", + "javascript:", "%3cscript", "sleep(", "benchmark(", NULL +}; + +static int hexval(int c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return -1; +} + +/* Percent-decode so log patterns see what the client actually sent. */ +static void url_decode(char *dst, size_t n, const char *src) +{ + size_t w = 0; + + while (*src != '\0' && w + 1 < n) { + if (*src == '%' && src[1] != '\0' && src[2] != '\0') { + int hi = hexval((unsigned char)src[1]); + int lo = hexval((unsigned char)src[2]); + + if (hi >= 0 && lo >= 0) { + dst[w++] = (char)((hi << 4) | lo); + src += 3; + continue; + } + } + dst[w++] = (*src == '+') ? ' ' : *src; + src++; + } + dst[w] = '\0'; +} + +static void lower_copy(char *dst, size_t n, const char *src) +{ + size_t i; + + for (i = 0; src[i] != '\0' && i + 1 < n; i++) + dst[i] = (char)tolower((unsigned char)src[i]); + dst[i] = '\0'; +} + +static void t_web_log_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *path = mcp_arg_string(args, "path"); + int limit = mcp_arg_int(args, "limit", 5000); + FILE *f; + char *line = NULL; + size_t cap = 0; + web_ip ips[64]; + int nips = 0; + int scanner_count[16]; + int lines = 0; + int requests = 0; + int c2 = 0; + int c3 = 0; + int c4 = 0; + int c5 = 0; + char suspicious[10][160]; + char suspicious_pat[10][24]; + int nsusp = 0; + int used[64]; + mcp_buf b; + int i; + int printed = 0; + + (void)user; + if (path == NULL || *path == '\0') + path = "/var/log/nginx/access.log"; + if (!allowed_log_path(path)) { + mcp_reply_error(c, "path must be under /var/log/ or the state dir"); + return; + } + if (limit <= 0 || limit > 50000) + limit = 5000; + memset(ips, 0, sizeof(ips)); + memset(scanner_count, 0, sizeof(scanner_count)); + memset(used, 0, sizeof(used)); + f = fopen(path, "rb"); + if (f == NULL) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "cannot read %s: %s", path, strerror(errno)); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + while (lines < limit && getline(&line, &cap, f) >= 0) { + char ip[64]; + char req[1024]; + char *q1; + char *q2; + char *after; + char *uri; + char *sp; + int code; + int k; + int hitip = -1; + + lines++; + if (sscanf(line, "%63s", ip) != 1) + continue; + q1 = strchr(line, '"'); + if (q1 == NULL) + continue; + q2 = strchr(q1 + 1, '"'); + if (q2 == NULL) + continue; + { + size_t n = (size_t)(q2 - q1 - 1); + + if (n >= sizeof(req)) + n = sizeof(req) - 1; + memcpy(req, q1 + 1, n); + req[n] = '\0'; + } + sp = strchr(req, ' '); + if (sp == NULL) + continue; + *sp = '\0'; + uri = sp + 1; + sp = strchr(uri, ' '); + if (sp != NULL) + *sp = '\0'; + after = q2 + 1; + while (*after == ' ') + after++; + code = atoi(after); + if (code <= 0) + continue; + requests++; + if (code >= 200 && code < 300) + c2++; + else if (code >= 300 && code < 400) + c3++; + else if (code >= 400 && code < 500) + c4++; + else if (code >= 500) + c5++; + for (k = 0; k < nips; k++) + if (strcmp(ips[k].ip, ip) == 0) + hitip = k; + if (hitip < 0 && nips < 64) { + snprintf(ips[nips].ip, sizeof(ips[nips].ip), "%s", ip); + hitip = nips++; + } + if (hitip >= 0) { + ips[hitip].total++; + if (code >= 400 && code < 500) + ips[hitip].c4xx++; + if (code >= 500) + ips[hitip].c5xx++; + } + { + /* user agent is the last quoted string on the line */ + char *q = q2 + 1; + char *last1 = NULL; + char *last2 = NULL; + + while ((q = strchr(q, '"')) != NULL) { + char *e = strchr(q + 1, '"'); + + if (e == NULL) + break; + last1 = q + 1; + last2 = e; + q = e + 1; + } + if (last1 != NULL && last2 != NULL) { + char lc[256]; + size_t n = (size_t)(last2 - last1); + + if (n >= sizeof(lc)) + n = sizeof(lc) - 1; + memcpy(lc, last1, n); + lc[n] = '\0'; + lower_copy(lc, sizeof(lc), lc); + for (k = 0; SCANNERS[k] != NULL; k++) + if (strstr(lc, SCANNERS[k]) != NULL) + scanner_count[k]++; + } + } + { + char decoded[1024]; + char low[1024]; + + url_decode(decoded, sizeof(decoded), uri); + lower_copy(low, sizeof(low), decoded); + for (k = 0; WEB_PATTERNS[k] != NULL; k++) { + int m; + int seen = 0; + + if (strstr(low, WEB_PATTERNS[k]) == NULL) + continue; + for (m = 0; m < nsusp; m++) + if (strcmp(suspicious_pat[m], WEB_PATTERNS[k]) == 0) + seen = 1; + if (!seen && nsusp < 10) { + snprintf(suspicious[nsusp], sizeof(suspicious[0]), + "%s", uri); + snprintf(suspicious_pat[nsusp], + sizeof(suspicious_pat[0]), "%s", + WEB_PATTERNS[k]); + nsusp++; + } + break; + } + } + } + free(line); + fclose(f); + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"lines\":%d,\"requests\":%d," + "\"status\":{\"2xx\":%d,\"3xx\":%d,\"4xx\":%d,\"5xx\":%d}," + "\"top_ips\":[", lines, requests, c2, c3, c4, c5); + for (i = 0; i < 10 && i < nips; i++) { + int best = -1; + int k; + + for (k = 0; k < nips; k++) + if (!used[k] && (best < 0 || ips[k].total > ips[best].total)) + best = k; + if (best < 0) + break; + used[best] = 1; + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"ip\":"); + apex_json_str(&b, ips[best].ip); + mcp_buf_printf(&b, ",\"count\":%d}", ips[best].total); + } + mcp_buf_puts(&b, "],\"scanners\":["); + for (i = 0; SCANNERS[i] != NULL; i++) { + if (scanner_count[i] == 0) + continue; + if (printed++ > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"name\":"); + apex_json_str(&b, SCANNERS[i]); + mcp_buf_printf(&b, ",\"count\":%d}", scanner_count[i]); + } + mcp_buf_puts(&b, "],\"suspicious\":["); + for (i = 0; i < nsusp; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"uri\":"); + apex_json_str(&b, suspicious[i]); + mcp_buf_puts(&b, ",\"pattern\":"); + apex_json_str(&b, suspicious_pat[i]); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "],\"burst_ips\":["); + printed = 0; + for (i = 0; i < nips; i++) { + if (ips[i].c4xx < 20 && ips[i].c5xx < 5) + continue; + if (printed++ > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"ip\":"); + apex_json_str(&b, ips[i].ip); + mcp_buf_printf(&b, ",\"4xx\":%d,\"5xx\":%d}", ips[i].c4xx, + ips[i].c5xx); + } + mcp_buf_puts(&b, "]}"); + 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, " @@ -745,6 +1036,18 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"files to scan, default " "2000, max 20000\"}}}", t_ioc_scan }, + { "web_log_audit", + "Read an nginx/apache access log: request count, 2xx/3xx/4xx/5xx split, " + "top source IPs, known scanner user agents (sqlmap, nikto, nmap, " + "gobuster, nuclei, ...), SQLi/traversal/XSS patterns in the URI, and " + "source IPs with a 4xx/5xx burst. Read-only; the path must be under " + "/var/log/ or the state directory.", + "{\"type\":\"object\",\"properties\":{" + "\"path\":{\"type\":\"string\",\"description\":\"default " + "/var/log/nginx/access.log\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"lines to read, " + "default 5000, max 50000\"}}}", + t_web_log_audit }, }; 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 8f5fc28..7b0612d 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -16,6 +16,7 @@ * what becomes a finding. */ #include <arpa/inet.h> +#include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <stdarg.h> @@ -24,7 +25,9 @@ #include <string.h> #include <strings.h> #include <sys/socket.h> +#include <sys/time.h> #include <time.h> +#include <unistd.h> #include "apex.h" #include "tools.h" @@ -549,6 +552,433 @@ static void t_cred_test(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------- vhost_discovery */ + +static const char *VHOSTS[] = { + "www", "mail", "admin", "api", "dev", "staging", "test", "blog", "shop", + "app", "portal", "vpn", "git", "jenkins", "grafana", "jira", "wiki", + "docs", "cdn", "static", "m", "mobile", "intranet", "internal", "sso", + "auth", "db", "backup", "old", "new", "demo", "beta", "status", "monitor", + NULL +}; + +static void title_of(const char *body, size_t len, char *out, size_t n) +{ + size_t i; + + out[0] = '\0'; + for (i = 0; i + 6 < len; i++) { + if (strncasecmp(body + i, "<title", 6) == 0) { + size_t j = i + 6; + size_t k = 0; + + while (j < len && body[j] != '>') + j++; + j++; + while (j < len && body[j] != '<' && k + 1 < n) { + char ch = body[j++]; + + if (ch != '\r' && ch != '\n' && ch != '\t') + out[k++] = ch; + } + out[k] = '\0'; + return; + } + } +} + +static int read_all_fd(int fd, mcp_buf *b, size_t cap) +{ + char buf[8192]; + + for (;;) { + ssize_t n = read(fd, buf, sizeof(buf)); + + if (n <= 0) + break; + if (b->len + (size_t)n > cap) { + mcp_buf_add(b, buf, cap - b->len); + break; + } + mcp_buf_add(b, buf, (size_t)n); + } + return b->len > 0 ? 0 : -1; +} + +/* GET with an arbitrary Host header; connects to ip, not to the vhost name. */ +static int http_with_host(const char *ip, int port, const char *host_hdr, + const char *path, char **out, size_t *out_len, + char *status, size_t sn) +{ + int fd = tcp_connect_host(ip, port, 5000); + mcp_buf req; + mcp_buf resp; + struct timeval tv; + int rc; + + if (fd < 0) + return -1; + tv.tv_sec = 8; + tv.tv_usec = 0; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + mcp_buf_init(&req); + mcp_buf_printf(&req, "GET %s HTTP/1.1\r\nHost: %s\r\n", path, host_hdr); + mcp_buf_printf(&req, "User-Agent: apex-twin/%s\r\n", APEX_VERSION); + mcp_buf_puts(&req, "Accept: */*\r\nConnection: close\r\n\r\n"); + if (write(fd, req.p, req.len) != (ssize_t)req.len) { + mcp_buf_free(&req); + close(fd); + return -1; + } + mcp_buf_free(&req); + mcp_buf_init(&resp); + rc = read_all_fd(fd, &resp, 1u << 20); + close(fd); + if (rc != 0) { + mcp_buf_free(&resp); + return -1; + } + if (status != NULL && sn > 0) { + size_t k = 0; + + while (resp.p[k] != '\0' && resp.p[k] != '\r' && k + 1 < sn) { + status[k] = resp.p[k]; + k++; + } + status[k] = '\0'; + } + *out = resp.p; + *out_len = resp.len; + resp.p = NULL; + mcp_buf_free(&resp); + return 0; +} + +static void t_vhost_discovery(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *base_host = mcp_arg_string(args, "base_host"); + const char *names_arg = mcp_arg_string(args, "names"); + const char *path = mcp_arg_string(args, "path"); + int limit = mcp_arg_int(args, "limit", 40); + int delay = mcp_arg_int(args, "delay_ms", 100); + int port = mcp_arg_int(args, "port", 80); + char *names_copy = NULL; + char *names_save = NULL; + char *next_name = NULL; + char status[256]; + char *resp = NULL; + size_t len = 0; + int base_status; + long base_len; + char base_title[128]; + int checked = 0; + int hits = 0; + int first = 1; + int i = 0; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (limit <= 0 || limit > 100) + limit = 40; + if (delay < 0 || delay > 1000) + delay = 100; + if (!gated(c, "vhost_discovery", target, port)) + return; + if (base_host == NULL || *base_host == '\0') + base_host = target; + + status[0] = '\0'; + if (http_with_host(target, port, base_host, path, &resp, &len, status, + sizeof(status)) != 0) { + mcp_reply_error(c, "no baseline response"); + return; + } + base_status = apex_status_code(status); + base_len = (long)len; + title_of(resp, len, base_title, sizeof(base_title)); + free(resp); + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"base_host\":", port); + apex_json_str(&b, base_host); + mcp_buf_printf(&b, ",\"baseline\":{\"status\":%d,\"bytes\":%ld,\"title\":", + base_status, base_len); + apex_json_str(&b, base_title); + mcp_buf_puts(&b, "},\"hits\":["); + + if (names_arg != NULL && *names_arg != '\0') { + names_copy = strdup(names_arg); + if (names_copy != NULL) + next_name = strtok_r(names_copy, ",", &names_save); + } + for (;;) { + const char *name; + char host[300]; + char reason[160]; + int differs = 0; + int code; + long blen; + char title[128]; + char *evidence = NULL; + + if (names_copy != NULL) { + name = next_name; + if (name == NULL) + break; + next_name = strtok_r(NULL, ",", &names_save); + } else { + if (VHOSTS[i] == NULL || i >= limit) + break; + name = VHOSTS[i++]; + } + while (*name == ' ' || *name == '\t') + name++; + if (*name == '\0') + continue; + if (strchr(name, '.') != NULL) + snprintf(host, sizeof(host), "%s", name); + else + snprintf(host, sizeof(host), "%s.%s", name, base_host); + checked++; + status[0] = '\0'; + if (http_with_host(target, port, host, path, &resp, &len, status, + sizeof(status)) != 0) + continue; + code = apex_status_code(status); + blen = (long)len; + title_of(resp, len, title, sizeof(title)); + if (code != base_status) { + snprintf(reason, sizeof(reason), "status %d vs %d", code, + base_status); + differs = 1; + } else if (blen > base_len + 24 || blen < base_len - 24) { + snprintf(reason, sizeof(reason), "bytes %ld vs %ld", blen, + base_len); + differs = 1; + } else if (strcmp(title, base_title) != 0) { + snprintf(reason, sizeof(reason), "title differs"); + differs = 1; + } else { + reason[0] = '\0'; + } + if (differs) { + char label[64]; + + snprintf(label, sizeof(label), "vhost-%.40s", host); + evidence = apex_evidence_save(label, resp, len); + hits++; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"host\":"); + apex_json_str(&b, host); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%ld,\"title\":", + code, blen); + apex_json_str(&b, title); + mcp_buf_puts(&b, ",\"reason\":"); + apex_json_str(&b, reason); + 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); + } + free(resp); + resp = NULL; + if (delay > 0) + sleep_ms(delay); + } + free(names_copy); + mcp_buf_printf(&b, "],\"checked\":%d,\"count\":%d}", checked, hits); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ---------------------------------------------------------------- http_brute */ + +static const char *BRUTE_PATHS[] = { + "admin", "administrator", "login", "wp-admin", "wp-login.php", ".git/HEAD", + ".env", "backup.zip", "backup.sql", "db.sql", "config.php", "config.json", + "robots.txt", "sitemap.xml", "api", "api/v1", "api/v2", "swagger.json", + "swagger-ui/", "openapi.json", "graphql", "health", "healthz", "metrics", + "debug", "console", "actuator", "actuator/env", "server-status", + "server-info", "phpinfo.php", "info.php", "test", "dev", "staging", "old", + "tmp", "uploads/", "backup/", "jenkins", "grafana", "kibana", "prometheus", + ".well-known/security.txt", "favicon.ico", "index.php~", "web.config", + ".svn/entries", NULL +}; + +static int brute_hit(int code) +{ + return code == 200 || code == 201 || code == 204 || code == 301 || + code == 302 || code == 307 || code == 308 || code == 401 || + code == 403; +} + +static void t_http_brute(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *base = mcp_arg_string(args, "path"); + const char *words_arg = mcp_arg_string(args, "words"); + const char *wordlist = mcp_arg_string(args, "wordlist"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + int limit = mcp_arg_int(args, "limit", 40); + int delay = mcp_arg_int(args, "delay_ms", 100); + char root[512]; + size_t rl; + char *list[256]; + int nlist = 0; + char *file_words = NULL; + mcp_buf b; + int tested = 0; + int hits = 0; + int evidence_saved = 0; + int first = 1; + int i; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (limit <= 0 || limit > 200) + limit = 40; + if (delay < 0 || delay > 1000) + delay = 100; + snprintf(root, sizeof(root), "%s", base != NULL && *base != '\0' + ? base : "/"); + rl = strlen(root); + while (rl > 0 && root[rl - 1] == '/') + root[--rl] = '\0'; + if (!gated(c, "http_brute", target, port)) + return; + + if (words_arg != NULL && *words_arg != '\0') { + char *copy = strdup(words_arg); + char *save = NULL; + char *tok; + + if (copy != NULL) { + tok = strtok_r(copy, ",", &save); + while (tok != NULL && nlist < 256) { + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok != '\0') + list[nlist++] = tok; + tok = strtok_r(NULL, ",", &save); + } + /* keep copy alive: list points into it */ + file_words = copy; + } + } else if (wordlist != NULL && *wordlist != '\0') { + FILE *f = fopen(wordlist, "rb"); + char line[512]; + + if (f == NULL) { + mcp_reply_error(c, "cannot read the wordlist"); + return; + } + while (fgets(line, sizeof(line), f) != NULL && nlist < 256) { + char *p = line; + + while (*p == ' ' || *p == '\t') + p++; + { + size_t n = strlen(p); + + while (n > 0 && (p[n - 1] == '\n' || p[n - 1] == '\r')) + p[--n] = '\0'; + } + if (*p == '\0' || *p == '#') + continue; + list[nlist] = strdup(p); + if (list[nlist] != NULL) + nlist++; + } + fclose(f); + } else { + for (i = 0; BRUTE_PATHS[i] != NULL && nlist < 256; i++) + list[nlist++] = (char *)BRUTE_PATHS[i]; + } + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"hits\":[", port); + for (i = 0; i < nlist && tested < limit; i++) { + char req[900]; + const char *word = list[i]; + char status[256]; + char *resp = NULL; + size_t len = 0; + int code; + + while (*word == '/') + word++; + if (*word == '\0') + continue; + if (root[0] != '\0') + snprintf(req, sizeof(req), "%s/%s", root, word); + else + snprintf(req, sizeof(req), "/%s", word); + status[0] = '\0'; + tested++; + if (apex_http_once(target, port, tls, "GET", req, NULL, NULL, 8000, + &resp, &len, status, sizeof(status)) != 0) + continue; + code = apex_status_code(status); + if (brute_hit(code)) { + hits++; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, req); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu", code, + (unsigned long)len); + if ((code == 200 || code == 201) && evidence_saved < 5) { + char *ev = apex_evidence_save("brute", resp, len); + + evidence_saved++; + mcp_buf_puts(&b, ",\"evidence\":"); + if (ev != NULL) { + apex_json_str(&b, ev); + free(ev); + } else { + mcp_buf_puts(&b, "null"); + } + } + mcp_buf_puts(&b, "}"); + } + free(resp); + if (delay > 0 && tested < limit) + sleep_ms(delay); + } + if (words_arg != NULL && *words_arg != '=' && file_words != NULL) + free(file_words); + if (wordlist != NULL && *wordlist != '\0') { + int k; + + for (k = 0; k < nlist; k++) + free(list[k]); + } + mcp_buf_printf(&b, "],\"tested\":%d,\"count\":%d}", tested, hits); + 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: " @@ -598,6 +1028,47 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_cred_test }, + { "vhost_discovery", + "Host-header fuzzing against one in-scope IP: requests the base path " + "with each candidate name as Host (built-in list or names=) and reports " + "the ones whose status, byte count or <title> differs from the baseline. " + "Plain HTTP only (TLS SNI would need a resolver override). Each hit " + "saves the response as evidence; 100 ms between requests.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\",\"description\":\"IP in scope\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"base_host\":{\"type\":\"string\",\"description\":\"Host header for " + "the baseline; default the target\"}," + "\"names\":{\"type\":\"string\",\"description\":\"comma list of vhost " + "names; default built-in list\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"default 40, max " + "100\"}," + "\"delay_ms\":{\"type\":\"integer\",\"description\":\"default " + "100\"}}," + "\"required\":[\"target\"]}", + t_vhost_discovery }, + { "http_brute", + "Probe a built-in path list, your own comma list, or a wordlist file for " + "hidden endpoints. Hits are 200/201/204/301/302/307/308/401/403; 404 is " + "ignored. 100 ms between requests, default 40 paths, max 200; the first " + "five 200/201 responses are saved as evidence. Gate: target in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"base path, default " + "/\"}," + "\"words\":{\"type\":\"string\",\"description\":\"comma list; wins " + "over wordlist\"}," + "\"wordlist\":{\"type\":\"string\",\"description\":\"file with one " + "path per line, # comments allowed\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"default 40, max " + "200\"}," + "\"delay_ms\":{\"type\":\"integer\",\"description\":\"default " + "100\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_http_brute }, }; 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 11528c5..83bcc88 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 = 54 +EXPECTED_TOOLS = 57 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. diff --git a/tests/run.py b/tests/run.py index 57c795a..b719a5b 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("54 tools registered", len(tools) == 54, len(tools)) +check("57 tools registered", len(tools) == 57, 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"]) == 54) + check("http tools/list", len(listing["result"]["tools"]) == 57) 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 @@ -2597,6 +2597,109 @@ check("cred_test refuses an endpoint that needs no authentication", lock = json.loads(text(by_id[9])) check("cred_test stops on a rate limit", lock["lockout"] is True and lock["attempts"] == 1, lock) +print("\n== vhost discovery and path brute force ==") + + +class _VhostHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + host = self.headers.get("Host", "") + if host.startswith("admin."): + code, body = 200, b"<html><title>Admin consoleok" + elif host.startswith("api."): + code, body = 201, b"API" + b"x" * 200 + b"" + elif host.startswith("www."): + code, body = 200, b"Homeroot" + else: + code, body = 404, b"not found" + self.send_response(code) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +vhost_srv = http.server.HTTPServer(("127.0.0.1", 0), _VhostHandler) +vport = vhost_srv.server_address[1] +threading.Thread(target=vhost_srv.serve_forever, daemon=True).start() + + +class _BruteHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + table = {"/admin": 200, "/api": 401, "/robots.txt": 200, + "/base/admin": 200} + code = table.get(path, 404) + body = b"ok" if code in (200, 401) else b"nope" + self.send_response(code) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +brute_srv = http.server.HTTPServer(("127.0.0.1", 0), _BruteHandler) +bport = brute_srv.server_address[1] +threading.Thread(target=brute_srv.serve_forever, daemon=True).start() + +vb_home = tempfile.mkdtemp(prefix="apex-vb-") +os.makedirs(os.path.join(vb_home, "wordlists"), exist_ok=True) +with open(os.path.join(vb_home, "wordlists", "paths.txt"), "w") as f: + f.write("# comment\nadmin\napi\nnope\n") +write_scope(vb_home, {"label": "vb", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(vport), str(bport)]}) +res, _ = run([ + call(1, "vhost_discovery", target="127.0.0.1", port=vport, + names="admin,api,missing", delay_ms=0, tls=False), + call(2, "http_brute", target="127.0.0.1", port=bport, + words="admin,api,missing,robots.txt", delay_ms=0, tls=False), + call(3, "http_brute", target="127.0.0.1", port=bport, + wordlist=os.path.join(vb_home, "wordlists", "paths.txt"), + delay_ms=0, tls=False), + call(4, "http_brute", target="127.0.0.1", port=bport, path="/base", + words="admin", delay_ms=0, tls=False), + call(5, "vhost_discovery", target="198.51.100.9", port=80), +], home=vb_home) +by_id = {r.get("id"): r for r in res} +vh = json.loads(text(by_id[1])) +check("vhost_discovery compares against a baseline", + vh["baseline"]["status"] == 404 and vh["checked"] == 3, vh) +check("vhost_discovery reports the deviating names", + vh["count"] == 2 and + {h["host"] for h in vh["hits"]} == {"admin.127.0.0.1", + "api.127.0.0.1"}, vh["hits"]) +check("vhost_discovery explains the difference", + all(h["reason"] for h in vh["hits"]), vh["hits"]) +check("vhost_discovery saves evidence", + all(h["evidence"] and os.path.isfile(h["evidence"]) + for h in vh["hits"]), vh["hits"]) +brute = json.loads(text(by_id[2])) +check("http_brute probes the whole list", + brute["tested"] == 4 and brute["count"] == 3, brute) +check("http_brute treats 401 as a hit", + any(h["status"] == 401 and h["path"] == "/api" for h in brute["hits"]), + brute["hits"]) +check("http_brute saves evidence for 200s", + any(h.get("evidence") and os.path.isfile(h["evidence"]) + for h in brute["hits"] if h["status"] == 200), brute["hits"]) +wl = json.loads(text(by_id[3])) +check("http_brute reads a wordlist file and skips comments", + wl["tested"] == 3 and {h["path"] for h in wl["hits"]} == + {"/admin", "/api"}, wl) +based = json.loads(text(by_id[4])) +check("http_brute honours the base path", + based["count"] == 1 and based["hits"][0]["path"] == "/base/admin", based) +check("vhost_discovery refuses an out-of-scope target", err(by_id[5]), + text(by_id[5])) +vhost_srv.shutdown() +vhost_srv.server_close() +brute_srv.shutdown() +brute_srv.server_close() +shutil.rmtree(vb_home, ignore_errors=True) red_srv.shutdown() red_srv.server_close() clean_srv.shutdown() @@ -2669,6 +2772,45 @@ check("ioc_scan names each pattern", check("ioc_scan leaves the clean file alone", not any(f["path"].endswith("clean.txt") for f in iocs["findings"]), iocs) check("ioc_scan reports the files it read", iocs["files_scanned"] >= 4, iocs) +print("\n== web log audit ==") +weblog = os.path.join(blue_home, "logs", "access.log") +with open(weblog, "w") as f: + for i in range(22): + f.write('203.0.113.50 - - [21/Nov/2026:10:00:%02d +0000] ' % i + + '"GET /?id=1%27%20or%20%271%27=%271 HTTP/1.1" 404 12 "-" ' + '"sqlmap/1.7"\n') + f.write('203.0.113.50 - - [21/Nov/2026:10:00:30 +0000] ' + '"GET /../../etc/passwd HTTP/1.1" 404 12 "-" "sqlmap/1.7"\n') + for i in range(5): + f.write('198.51.100.7 - - [21/Nov/2026:10:01:0%d +0000] ' + '"GET / HTTP/1.1" 200 100 "-" "Mozilla/5.0"\n' % i) + for i in range(2): + f.write('198.51.100.8 - - [21/Nov/2026:10:02:0%d +0000] ' + '"GET /admin HTTP/1.1" 500 5 "-" "Nikto/2.5"\n' % i) +res, _ = run([ + call(1, "web_log_audit", path=weblog), + call(2, "web_log_audit", path="/etc/passwd"), +], home=blue_home) +by_id = {r.get("id"): r for r in res} +wl = json.loads(text(by_id[1])) +check("web_log_audit counts the requests", wl["requests"] == 30, wl) +check("web_log_audit splits the status classes", + wl["status"]["4xx"] == 23 and wl["status"]["2xx"] == 5 and + wl["status"]["5xx"] == 2, wl["status"]) +check("web_log_audit names the top source", + wl["top_ips"][0]["ip"] == "203.0.113.50" and + wl["top_ips"][0]["count"] == 23, wl["top_ips"]) +check("web_log_audit recognises scanners", + any(s["name"] == "sqlmap" and s["count"] == 23 for s in wl["scanners"]) and + any(s["name"] == "nikto" for s in wl["scanners"]), wl["scanners"]) +check("web_log_audit flags SQLi and traversal patterns", + {s["pattern"] for s in wl["suspicious"]} >= {"' or ", "../"}, + wl["suspicious"]) +check("web_log_audit flags the 4xx burst source", + any(b["ip"] == "203.0.113.50" for b in wl["burst_ips"]), + 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== esp32 tools ==")