diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a26259..194d7c6 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.14.0 — 2026-11-21 — this change +## 1.15.0 — 2026-11-21 — this change + +- **HTTP methods** (`http_methods`): OPTIONS for the Allow list and Server + header, TRACE for echo detection (cross-site tracing). PUT/DELETE are named + if Allow advertises them but never sent. +- **WebSocket** (`websocket_probe`): GET with Upgrade/Connection and a random + Sec-WebSocket-Key; reports 101, Upgrade, Connection and + Sec-WebSocket-Accept. No frame is sent. +- **IKEv2** (`ike_probe`): one IKE_SA_INIT with an SA proposal (AES-CBC-128, + HMAC-SHA2-256, DH group 14) over UDP; reports version, exchange type, the + first notify (NO_PROPOSAL_CHOSEN, INVALID_KE_PAYLOAD, ...) and the responder + SPI. No PSK and no authentication. +- **Blue** (`firewall_audit`): runs `nft list ruleset` or `iptables-save` (or + parses a saved dump), reporting chain and rule counts and every chain whose + default policy is ACCEPT. Local process only (LOCAL_EXEC exception). +- Tests with local fixtures: an HTTP server for OPTIONS/TRACE/101 upgrade, a + UDP IKEv2 agent answering with NO_PROPOSAL_CHOSEN, and nft and iptables-save + ruleset dumps. 639 checks. Coverage 79.4%. + +## 1.14.0 — 2026-11-21 — d829955 - **ESP32 offline analysis** (`tools_esp.c`): `esp_partition_table` parses the 32-byte partition entries at 0x8000 (magic 0xAA50) with type/subtype names, diff --git a/README.md b/README.md index 6a2c914..98cffa6 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. -**104 tools · 627 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~473 KiB** +**108 tools · 639 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~486 KiB** ``` $ ./apex-twin --check -{"version":"1.14.0","tools":104,...,"scope":{"loaded":true,...}} +{"version":"1.15.0","tools":108,...,"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 (104) +## Tools (108) ### Scope and bookkeeping @@ -267,6 +267,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `graphql_probe` | Introspection query: schema exposed, type count, query/mutation names, evidence | | `docker_api_probe` | Unauthenticated `/version` and `/containers/json`: engine version, container/running counts, names, images | | `elasticsearch_probe` | Unauthenticated `/`, cluster health and index list: cluster, version, status, node and index counts | +| `http_methods` | OPTIONS Allow list and TRACE echo detection; names PUT/DELETE but never sends them | +| `websocket_probe` | Upgrade handshake: 101, Upgrade/Connection and Sec-WebSocket-Accept | +| `ike_probe` | IKEv2 SA_INIT (AES-CBC-128/HMAC-SHA2-256/DH14); version, exchange, notify, responder SPI | | `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN | | `pop3_probe` | Banner, CAPA list, STLS flag; no USER/PASS | | `sip_probe` | One UDP OPTIONS: status line, Server header, Allow methods | @@ -303,6 +306,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `module_audit` | Loaded modules and taint letters, kernel taint bits decoded (proprietary, out-of-tree, unsigned, ...) | | `package_integrity` | `dpkg -V` / `rpm -V` changed files, optionally one package or a saved verify output | | `mount_audit` | Mount table hardening: temp/shm mounts missing nosuid/nodev/noexec, home/media/mnt missing nosuid/nodev | +| `firewall_audit` | `nft list ruleset` / `iptables-save` (or saved dump): chain/rule counts and ACCEPT default policies | ### ESP32 @@ -509,6 +513,9 @@ The full threat model, trust boundaries and a hardening checklist are in | Package verify | 300 s cap; one package when requested | | Flash analysis | reads a local dump, 8/16/32 MiB caps | | Mount audit | 500 mounts; reads a table, not the filesystem | +| Method/WebSocket | one or two requests, no frames or writes | +| IKEv2 | one SA_INIT, two UDP attempts, no credentials | +| Firewall audit | reads the ruleset or a saved dump, 4 MiB cap | --- @@ -519,7 +526,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 627 end-to-end checks +make test # version check + gate audit + 639 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 @@ -627,12 +634,12 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe, graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe, sip_probe, - telnet_probe + telnet_probe, http_methods, websocket_probe, ike_probe src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, net_baseline, ssh_key_audit, suid_baseline, cap_baseline, module_audit, - package_integrity, mount_audit + package_integrity, mount_audit, firewall_audit src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit, @@ -668,7 +675,7 @@ examples/ scope.json ## Status -1.14.0. Built and run: 104 tools, 627 checks, 340 fuzz cases and 79.4% line +1.15.0. Built and run: 108 tools, 639 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 @@ -700,7 +707,8 @@ and a SUID baseline; 1.11 added VNC, MQTT and GraphQL checks plus a file capability baseline; 1.12 added Docker, Elasticsearch and IMAP checks plus a kernel module/taint audit; 1.13 added POP3, SIP and Telnet checks plus package integrity verification; 1.14 added offline ESP32 flash analysis and a mount -audit, again without changing an existing tool or file format. +audit; 1.15 added HTTP method, WebSocket and IKEv2 checks plus a firewall audit, +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 a4abba4..8df7142 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.14.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.15.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. +- **Method and protocol probes stay read-only.** `http_methods` sends OPTIONS + and TRACE but never PUT/DELETE; `websocket_probe` performs the handshake and + sends no frame; `ike_probe` sends one SA_INIT with no credentials or PSK; + `firewall_audit` reads the local ruleset. - **Firmware analysis reads local files only.** `esp_partition_table`, `esp_nvs_parse` and `firmware_scan` open a dump the operator supplies, cap it at 8/16/32 MiB and never touch a device. `mount_audit` reads a mount table diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index fcbbf7e..3b610f3 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.14.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.15.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -42,11 +42,11 @@ dns_zone_transfer, mysql_probe, postgres_probe, mongo_probe, memcached_probe, param_fuzz, open_redirect, host_header_injection, ssti_probe, xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe, graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe, -sip_probe, telnet_probe), defensive audits (hardening_audit, log_audit, -ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, -process_snapshot, persistence_audit, net_baseline, ssh_key_audit, -suid_baseline, cap_baseline, module_audit, package_integrity, mount_audit) and -ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, +sip_probe, telnet_probe, http_methods, websocket_probe, ike_probe), defensive +audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, +integrity_baseline, mitre_map, process_snapshot, persistence_audit, +net_baseline, ssh_key_audit, suid_baseline, cap_baseline, module_audit, +package_integrity, mount_audit, firewall_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan). .SH MODES .TP diff --git a/src/apex.h b/src/apex.h index 8bc3648..f00950b 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.14.0" +#define APEX_VERSION "1.15.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 8bddd53..ed7ff2c 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -3524,6 +3524,217 @@ static void t_mount_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------- firewall_audit */ + +typedef struct { + int chains; + int rules; + char accepts[32][64]; + int naccepts; +} fw_ctx; + +static void fw_accept(fw_ctx *ctx, const char *name) +{ + int i; + + for (i = 0; i < ctx->naccepts; i++) + if (strcmp(ctx->accepts[i], name) == 0) + return; + if (ctx->naccepts < 32) + snprintf(ctx->accepts[ctx->naccepts++], sizeof(ctx->accepts[0]), + "%.48s", name); +} + +static void fw_parse_nft(char *copy, fw_ctx *ctx) +{ + char *save = NULL; + char *line; + char current[64]; + + current[0] = '\0'; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *t = line; + size_t n; + + while (*t == ' ' || *t == '\t') + t++; + n = strlen(t); + while (n > 0 && (t[n - 1] == '\r' || t[n - 1] == ' ')) + t[--n] = '\0'; + if (strncmp(t, "chain ", 6) == 0) { + size_t w = 0; + + t += 6; + while (*t != '\0' && *t != ' ' && *t != '{' && + w + 1 < sizeof(current)) + current[w++] = *t++; + current[w] = '\0'; + ctx->chains++; + } else if (strstr(t, "policy accept") != NULL) { + if (current[0] != '\0') + fw_accept(ctx, current); + } else if (*t != '\0' && *t != '}' && + strncmp(t, "type ", 5) != 0 && + strncmp(t, "policy ", 7) != 0 && + strncmp(t, "table ", 6) != 0) { + ctx->rules++; + } + line = strtok_r(NULL, "\n", &save); + } +} + +static void fw_parse_iptables(char *copy, fw_ctx *ctx) +{ + char *save = NULL; + char *line; + + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + if (line[0] == ':') { + char name[64]; + char policy[32]; + + if (sscanf(line + 1, "%63s %31s", name, policy) == 2) { + ctx->chains++; + if (strcmp(policy, "ACCEPT") == 0) + fw_accept(ctx, name); + } + } else if (strncmp(line, "-A ", 3) == 0 || + strncmp(line, "-I ", 3) == 0) { + ctx->rules++; + } + line = strtok_r(NULL, "\n", &save); + } +} + +static void t_firewall_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *backend = mcp_arg_string(args, "backend"); + const char *output = mcp_arg_string(args, "output"); + int limit = mcp_arg_int(args, "limit", 500); + char *argv[5]; + apex_proc p; + int rc; + int exit_code = 0; + int nft = 0; + char *text = NULL; + size_t text_len = 0; + fw_ctx ctx; + mcp_buf b; + int i; + + (void)user; + if (backend == NULL || *backend == '\0') + backend = "auto"; + if (limit <= 0 || limit > 100000) + limit = 500; + (void)limit; + memset(&ctx, 0, sizeof(ctx)); + if (output != NULL && *output != '\0') { + FILE *f = fopen(output, "rb"); + long size; + struct stat st; + + if (f == NULL || stat(output, &st) != 0 || st.st_size <= 0 || + st.st_size > (4L << 20)) { + if (f != NULL) + fclose(f); + mcp_reply_error(c, "cannot read the saved ruleset"); + return; + } + size = (long)st.st_size; + text = malloc((size_t)size + 1); + if (text == NULL) { + fclose(f); + mcp_reply_error(c, "out of memory"); + return; + } + if (fread(text, 1, (size_t)size, f) != (size_t)size) { + free(text); + fclose(f); + mcp_reply_error(c, "cannot read the saved ruleset"); + return; + } + fclose(f); + text[size] = '\0'; + text_len = (size_t)size; + nft = strncmp(text, "*", 1) != 0; + if (strcmp(backend, "nft") == 0) + nft = 1; + else if (strcmp(backend, "iptables") == 0) + nft = 0; + } else { + if (strcmp(backend, "auto") == 0) { + if (apex_have("nft")) + nft = 1; + else if (apex_have("iptables-save")) + nft = 0; + else { + mcp_reply_error(c, "neither nft nor iptables-save is available"); + return; + } + } else if (strcmp(backend, "nft") == 0 && apex_have("nft")) { + nft = 1; + } else if (strcmp(backend, "iptables") == 0 && + apex_have("iptables-save")) { + nft = 0; + } else { + mcp_reply_error(c, "the requested firewall tool is not available"); + return; + } + if (nft) { + argv[0] = "nft"; + argv[1] = "list"; + argv[2] = "ruleset"; + argv[3] = NULL; + } else { + argv[0] = "iptables-save"; + argv[1] = NULL; + } + rc = apex_run(argv, 20000, g_cfg.max_output, &p); + if (rc != 0) { + mcp_reply_error(c, "cannot run the firewall tool"); + return; + } + exit_code = p.exit_code; + if (p.out == NULL || p.out_len == 0) { + mcp_reply_error(c, p.exit_code == 0 + ? "the firewall tool returned nothing" + : "cannot read the firewall ruleset"); + apex_proc_free(&p); + return; + } + text = strdup(p.out); + text_len = p.out_len; + apex_proc_free(&p); + if (text == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + } + if (nft) + fw_parse_nft(text, &ctx); + else + fw_parse_iptables(text, &ctx); + mcp_buf_init(&b); + mcp_buf_printf(&b, "{\"backend\":\"%s\",\"source\":\"%s\",\"exit\":%d," + "\"chains\":%d,\"rules\":%d,\"accept_policies\":[", + nft ? "nft" : "iptables", + output != NULL && *output != '\0' ? "file" : "live", + exit_code, ctx.chains, ctx.rules); + for (i = 0; i < ctx.naccepts; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, ctx.accepts[i]); + } + mcp_buf_printf(&b, "],\"findings_count\":%d}", ctx.naccepts); + free(text); + (void)text_len; + 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, " @@ -3728,6 +3939,19 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"mounts to read, " "default 500\"}}}", t_mount_audit }, + { "firewall_audit", + "Read the local firewall ruleset with nft list ruleset or iptables-save " + "(or parse a saved dump) and report the chain count, rule count and every " + "chain whose default policy is ACCEPT, which is where a missing rule " + "becomes a hole. Local process only; no network.", + "{\"type\":\"object\",\"properties\":{" + "\"backend\":{\"type\":\"string\",\"enum\":[\"auto\",\"nft\"," + "\"iptables\"],\"description\":\"default auto\"}," + "\"output\":{\"type\":\"string\",\"description\":\"parse a saved " + "ruleset instead of running\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"reserved, default " + "500\"}}}", + t_firewall_audit }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_proto.c b/src/tools_proto.c index 1d35121..b6debec 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -3158,6 +3158,190 @@ static void t_telnet_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- ike_probe */ + +static uint16_t ike_le16(const unsigned char *p) +{ + return (uint16_t)(p[0] | (p[1] << 8)); +} + +static const char *ike_notify_name(int code) +{ + switch (code) { + case 14: + return "NO_PROPOSAL_CHOSEN"; + case 17: + return "INVALID_KE_PAYLOAD"; + case 24: + return "INVALID_SYNTAX"; + case 34: + return "INVALID_MAJOR_VERSION"; + case 35: + return "UNSUPPORTED_CRITICAL_PAYLOAD"; + case 36: + return "INVALID_IKE_SPI"; + case 38: + return "INVALID_MESSAGE_ID"; + default: + return "notify"; + } +} + +static void t_ike_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 500); + unsigned char msg[128]; + unsigned char resp[4096]; + struct addrinfo hints; + struct addrinfo *res = NULL; + struct addrinfo *use = NULL; + struct addrinfo *rp; + char service[16]; + int fd = -1; + int attempt; + int got = 0; + ssize_t r = 0; + unsigned long seed; + int i; + int exchange = 0; + int version = 0; + int next_payload = 0; + int notify = -1; + char spi[40]; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!gated(c, "ike_probe", target, port)) + return; + memset(msg, 0, sizeof(msg)); + seed = (unsigned long)getpid() ^ (unsigned long)time(NULL); + for (i = 0; i < 8; i++) + msg[i] = (unsigned char)(seed >> (i * 8)); + msg[16] = 33; /* next payload: SA */ + msg[17] = 0x20; /* IKEv2 */ + msg[18] = 34; /* IKE_SA_INIT */ + msg[19] = 0x08; /* initiator */ + /* message id 0 */ + msg[24] = 64; /* length */ + msg[25] = 0; + msg[26] = 0; + msg[27] = 0; + /* SA payload */ + msg[28] = 0; /* next payload */ + msg[29] = 0; + msg[30] = 36; /* payload length */ + msg[31] = 0; + /* proposal */ + msg[32] = 0; /* last proposal */ + msg[33] = 32; /* proposal length */ + msg[34] = 0; + msg[35] = 1; /* proposal number */ + msg[36] = 1; /* protocol IKE */ + msg[37] = 0; /* SPI size */ + msg[38] = 3; /* transforms */ + msg[39] = 0; + /* ENCR AES-CBC-128 */ + msg[40] = 0; + msg[41] = 0; + msg[42] = 8; + msg[43] = 0; + msg[44] = 1; + msg[45] = 0; + msg[46] = 12; + msg[47] = 0; + /* PRF HMAC-SHA2-256 */ + msg[48] = 0; + msg[49] = 0; + msg[50] = 8; + msg[51] = 0; + msg[52] = 2; + msg[53] = 0; + msg[54] = 5; + msg[55] = 0; + /* DH group 14 */ + msg[56] = 0; + msg[57] = 0; + msg[58] = 8; + msg[59] = 0; + msg[60] = 4; + msg[61] = 0; + msg[62] = 14; + msg[63] = 0; + snprintf(service, sizeof(service), "%d", port); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + if (getaddrinfo(target, service, &hints, &res) != 0) { + mcp_reply_error(c, "cannot resolve the target"); + return; + } + for (rp = res; rp != NULL; rp = rp->ai_next) { + fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if (fd >= 0) { + use = rp; + break; + } + } + if (use == NULL) { + freeaddrinfo(res); + mcp_reply_error(c, "cannot open a UDP socket"); + return; + } + for (attempt = 0; attempt < 2 && !got; attempt++) { + struct pollfd pfd; + + if (sendto(fd, msg, 64, 0, use->ai_addr, use->ai_addrlen) < 0) + break; + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + if (poll(&pfd, 1, 2000) <= 0) + continue; + r = recv(fd, resp, sizeof(resp), 0); + if (r >= 28 && resp[17] >> 4 == 2) + got = 1; + } + close(fd); + freeaddrinfo(res); + if (!got) { + mcp_reply_error(c, "no IKEv2 response"); + return; + } + version = resp[17]; + exchange = resp[18]; + next_payload = resp[16]; + if (next_payload == 41 && (size_t)r >= 36) { + notify = ike_le16(resp + 34); + } + snprintf(spi, sizeof(spi), "%02x%02x%02x%02x%02x%02x%02x%02x", + resp[8], resp[9], resp[10], resp[11], resp[12], resp[13], + resp[14], resp[15]); + apex_audit("ike_probe", target, port, 1, "IKEv2 responder answered", + ike_notify_name(notify)); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"ike\":true,\"responded\":true," + "\"version\":\"%d.%d\",\"exchange\":%d,\"next_payload\":%d," + "\"notify_code\":%d,\"notify\":", port, version >> 4, + version & 0x0f, exchange, next_payload, notify); + apex_json_str(&b, notify >= 0 ? ike_notify_name(notify) : ""); + mcp_buf_puts(&b, ",\"responder_spi\":"); + apex_json_str(&b, spi); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_PROTO[] = { { "ftp_probe", "One-connection FTP check: read the 220 banner, ask FEAT, then try the " @@ -3338,6 +3522,17 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 23\"}}," "\"required\":[\"target\"]}", t_telnet_probe }, + { "ike_probe", + "Send an IKEv2 IKE_SA_INIT over UDP with one SA proposal (AES-CBC-128, " + "HMAC-SHA2-256, DH group 14) and report the response header, version, " + "exchange type, first notify (for example NO_PROPOSAL_CHOSEN or " + "INVALID_KE_PAYLOAD) and the responder SPI. No PSK, no authentication. " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 500\"}}," + "\"required\":[\"target\"]}", + t_ike_probe }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/src/tools_red.c b/src/tools_red.c index 43c89b9..a108b3e 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -17,6 +17,7 @@ */ #include #include +#include #include #include #include @@ -2816,6 +2817,244 @@ static void t_elasticsearch_probe(mcp_conn *c, const mcp_json *args, void *user) free(indices); } +/* -------------------------------------------------------------- http_methods */ + +static void response_header(const char *resp, size_t len, const char *name, + char *out, size_t n) +{ + size_t i = 0; + size_t nl = strlen(name); + + 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 + nl + 1 && + strncasecmp(resp + start, name, nl) == 0 && + resp[start + nl] == ':') { + const char *v = resp + start + nl + 1; + + 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 int allow_has(const char *allow, const char *method) +{ + const char *p = allow; + size_t ml = strlen(method); + + while (*p != '\0') { + const char *end = p; + + while (*end != '\0' && *end != ',') + end++; + while (*p == ' ' || *p == '\t') + p++; + if ((size_t)(end - p) == ml && strncasecmp(p, method, ml) == 0) + return 1; + p = *end == ',' ? end + 1 : end; + } + return 0; +} + +static void t_http_methods(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"); + 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 options_code = 0; + int trace_code = 0; + int trace_enabled = 0; + char allow[512]; + char server[256]; + mcp_buf b; + int first = 1; + + (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 (!gated(c, "http_methods", target, port)) + return; + status[0] = '\0'; + allow[0] = server[0] = '\0'; + if (apex_http_once(target, port, tls, "OPTIONS", path, NULL, NULL, 8000, + &resp, &len, status, sizeof(status)) == 0) { + options_code = apex_status_code(status); + response_header(resp, len, "Allow", allow, sizeof(allow)); + response_header(resp, len, "Server", server, sizeof(server)); + free(resp); + resp = NULL; + } + status[0] = '\0'; + if (apex_http_once(target, port, tls, "TRACE", path, NULL, NULL, 8000, + &resp, &len, status, sizeof(status)) == 0) { + trace_code = apex_status_code(status); + if (trace_code == 200 && resp != NULL && + find_bytes(resp, len, "TRACE ")) + trace_enabled = 1; + free(resp); + } + 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, ",\"options_status\":%d,\"trace_status\":%d," + "\"trace_enabled\":%s,\"server\":", options_code, + trace_code, trace_enabled ? "true" : "false"); + apex_json_str(&b, server); + mcp_buf_puts(&b, ",\"allow\":["); + { + char copy[512]; + char *save = NULL; + char *tok; + + snprintf(copy, sizeof(copy), "%s", allow); + tok = strtok_r(copy, ",", &save); + while (tok != NULL) { + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok != '\0') { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, tok); + } + tok = strtok_r(NULL, ",", &save); + } + } + mcp_buf_puts(&b, "],\"write_methods_allowed\":"); + mcp_buf_printf(&b, "%s}", + (allow_has(allow, "PUT") || allow_has(allow, "DELETE")) + ? "true" : "false"); + apex_audit("http_methods", target, port, !trace_enabled, + trace_enabled ? "TRACE is enabled" : "TRACE not enabled", path); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ------------------------------------------------------------ websocket_probe */ + +static void t_websocket_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"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + unsigned char raw[16]; + char key[32]; + char headers[512]; + char status[256]; + char *resp = NULL; + size_t len = 0; + int code = 0; + int upgraded = 0; + char upgrade[64]; + char connection[128]; + char accept[128]; + mcp_buf b; + int fd; + + (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 (!gated(c, "websocket_probe", target, port)) + return; + /* 16 bytes for the nonce, from /dev/urandom when available */ + memset(raw, 0, sizeof(raw)); + fd = open("/dev/urandom", O_RDONLY); + if (fd >= 0) { + ssize_t r = read(fd, raw, sizeof(raw)); + + (void)r; + close(fd); + } + { + char *b64 = apex_base64_alloc((const char *)raw, sizeof(raw)); + + if (b64 == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + snprintf(key, sizeof(key), "%.28s", b64); + free(b64); + } + snprintf(headers, sizeof(headers), + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n", key); + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", path, NULL, headers, 8000, + &resp, &len, status, sizeof(status)) != 0) { + mcp_reply_error(c, "cannot reach the WebSocket endpoint"); + return; + } + code = apex_status_code(status); + upgrade[0] = connection[0] = accept[0] = '\0'; + response_header(resp, len, "Upgrade", upgrade, sizeof(upgrade)); + response_header(resp, len, "Connection", connection, sizeof(connection)); + response_header(resp, len, "Sec-WebSocket-Accept", accept, sizeof(accept)); + upgraded = code == 101 && + strcasecmp(upgrade, "websocket") == 0 && + strcasestr(connection, "upgrade") != 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_printf(&b, ",\"status\":%d,\"upgraded\":%s,\"upgrade\":", + code, upgraded ? "true" : "false"); + apex_json_str(&b, upgrade); + mcp_buf_puts(&b, ",\"connection\":"); + apex_json_str(&b, connection); + mcp_buf_puts(&b, ",\"accept\":"); + apex_json_str(&b, accept); + mcp_buf_puts(&b, "}"); + apex_audit("websocket_probe", target, port, code == 101, + code == 101 ? "WebSocket upgrade accepted" + : "no WebSocket upgrade", path); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(resp); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -3067,6 +3306,30 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 9200\"}}," "\"required\":[\"target\"]}", t_elasticsearch_probe }, + { "http_methods", + "Send OPTIONS and TRACE to one path and report the Allow list, the Server " + "header and whether TRACE echoes the request (cross-site tracing). It " + "names PUT/DELETE if Allow advertises them but never sends a write " + "method. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_http_methods }, + { "websocket_probe", + "Send a WebSocket upgrade handshake (random Sec-WebSocket-Key, version " + "13) and report whether the server answers 101 with Upgrade: websocket, " + "Connection: Upgrade and a Sec-WebSocket-Accept value. No frame is sent. " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_websocket_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 abc0c49..8ca21a3 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 = 104 +EXPECTED_TOOLS = 108 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. @@ -29,7 +29,8 @@ RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown", "traffic_list", "detect_rules", "mitre_map"} # 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", "esp_flash", "package_integrity"} +LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash", "package_integrity", + "firewall_audit"} 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 64f793c..11b578e 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("104 tools registered", len(tools) == 104, len(tools)) +check("108 tools registered", len(tools) == 108, 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"]) == 104) + check("http tools/list", len(listing["result"]["tools"]) == 108) 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 @@ -4797,6 +4797,187 @@ check("esp_partition_table rejects a missing file", err(by_id[5]), shutil.rmtree(os.path.dirname(flash_path), ignore_errors=True) shutil.rmtree(flash_home, ignore_errors=True) +print("\n== HTTP methods, WebSocket, IKEv2 and firewall ==") + + +class _MethodHandler(http.server.BaseHTTPRequestHandler): + server_version = "TestHTTP/1.0" + sys_version = "" + + def do_OPTIONS(self): + self.send_response(200) + self.send_header("Allow", "GET, POST, OPTIONS, TRACE, PUT") + self.send_header("Content-Length", "0") + self.end_headers() + + def do_TRACE(self): + parts = urllib.parse.urlsplit(self.path) + if parts.path == "/safe": + self.send_response(405) + self.send_header("Content-Length", "0") + self.end_headers() + return + body = ("TRACE " + self.path + " HTTP/1.1\r\nHost: test\r\n").encode() + self.send_response(200) + self.send_header("Content-Type", "message/http") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + parts = urllib.parse.urlsplit(self.path) + if (parts.path == "/ws" and + self.headers.get("Upgrade", "").lower() == "websocket"): + self.send_response(101) + self.send_header("Upgrade", "websocket") + self.send_header("Connection", "Upgrade") + self.send_header("Sec-WebSocket-Accept", "testaccept") + self.end_headers() + return + body = b"plain page" + 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 + + +def ike_agent(): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("127.0.0.1", 0)) + sock.settimeout(0.2) + port = sock.getsockname()[1] + stop = threading.Event() + + def loop(): + while not stop.is_set(): + try: + data, addr = sock.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + if len(data) < 28: + continue + resp = bytearray(36) + resp[0:8] = data[0:8] + resp[8:16] = bytes.fromhex("1122334455667788") + resp[16] = 41 + resp[17] = 0x20 + resp[18] = 34 + resp[19] = 0x20 + resp[24] = 36 + resp[28] = 0 + resp[29] = 0 + resp[30] = 8 + resp[31] = 0 + resp[32] = 1 + resp[33] = 0 + resp[34] = 14 + resp[35] = 0 + sock.sendto(bytes(resp), addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, port, stop + + +method_srv = http.server.HTTPServer(("127.0.0.1", 0), _MethodHandler) +method_port = method_srv.server_address[1] +threading.Thread(target=method_srv.serve_forever, daemon=True).start() +ike_sock, ike_port, ike_stop = ike_agent() + +fw_dir = tempfile.mkdtemp(prefix="apex-fw-") +nft_path = os.path.join(fw_dir, "nft.txt") +with open(nft_path, "w") as f: + f.write("table inet filter {\n") + f.write("\tchain input {\n") + f.write("\t\ttype filter hook input priority filter; policy drop;\n") + f.write("\t\tct state established,related accept\n") + f.write("\t\ttcp dport 22 accept\n") + f.write("\t}\n") + f.write("\tchain forward {\n") + f.write("\t\ttype filter hook forward priority filter; policy accept;\n") + f.write("\t}\n") + f.write("}\n") +ipt_path = os.path.join(fw_dir, "iptables.txt") +with open(ipt_path, "w") as f: + f.write("*filter\n") + f.write(":INPUT DROP [0:0]\n") + f.write(":FORWARD ACCEPT [0:0]\n") + f.write(":OUTPUT ACCEPT [0:0]\n") + f.write("-A INPUT -p tcp --dport 22 -j ACCEPT\n") + f.write("-A INPUT -j DROP\n") + f.write("COMMIT\n") + +net_home = tempfile.mkdtemp(prefix="apex-net-") +write_scope(net_home, {"label": "net", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(method_port), str(ike_port)]}) +res, _ = run([ + call(1, "http_methods", target="127.0.0.1", port=method_port, + path="/", tls=False), + call(2, "http_methods", target="127.0.0.1", port=method_port, + path="/safe", tls=False), + call(3, "websocket_probe", target="127.0.0.1", port=method_port, + path="/ws", tls=False), + call(4, "websocket_probe", target="127.0.0.1", port=method_port, + path="/plain", tls=False), + call(5, "ike_probe", target="127.0.0.1", port=ike_port), + call(6, "http_methods", target="198.51.100.9", port=80, path="/"), + call(7, "firewall_audit", output=nft_path, backend="nft"), + call(8, "firewall_audit", output=ipt_path, backend="iptables"), +], home=net_home) +by_id = {r.get("id"): r for r in res} +methods = json.loads(text(by_id[1])) +check("http_methods reads OPTIONS and the Allow list", + methods["options_status"] == 200 and + {"TRACE", "PUT", "OPTIONS"} <= set(methods["allow"]) and + methods["server"] == "TestHTTP/1.0", methods) +check("http_methods detects TRACE echo", methods["trace_enabled"] is True and + methods["trace_status"] == 200, methods) +methods_safe = json.loads(text(by_id[2])) +check("http_methods reports TRACE disabled on a safe path", + methods_safe["trace_enabled"] is False and + methods_safe["trace_status"] == 405, methods_safe) +ws = json.loads(text(by_id[3])) +check("websocket_probe detects the upgrade", + ws["status"] == 101 and ws["upgraded"] is True and + ws["upgrade"].lower() == "websocket" and + ws["accept"] == "testaccept", ws) +ws_plain = json.loads(text(by_id[4])) +check("websocket_probe reports a plain HTTP answer", + ws_plain["upgraded"] is False and ws_plain["status"] == 200, ws_plain) +ike = json.loads(text(by_id[5])) +check("ike_probe reads the IKEv2 response", + ike["ike"] is True and ike["responded"] is True and + ike["version"] == "2.0" and ike["exchange"] == 34, ike) +check("ike_probe reports the notify and responder SPI", + ike["notify_code"] == 14 and + ike["notify"] == "NO_PROPOSAL_CHOSEN" and + ike["responder_spi"] == "1122334455667788", ike) +check("http_methods refuses an out-of-scope target", err(by_id[6]), + text(by_id[6])) +nft = json.loads(text(by_id[7])) +check("firewall_audit parses an nft ruleset", + nft["backend"] == "nft" and nft["chains"] == 2 and nft["rules"] == 2, + nft) +check("firewall_audit names ACCEPT policies", + nft["accept_policies"] == ["forward"], nft) +ipt = json.loads(text(by_id[8])) +check("firewall_audit parses iptables-save", + ipt["backend"] == "iptables" and ipt["chains"] == 3 and + ipt["rules"] == 2, ipt) +check("firewall_audit names the iptables ACCEPT chains", + set(ipt["accept_policies"]) == {"FORWARD", "OUTPUT"}, ipt) +method_srv.shutdown() +method_srv.server_close() +ike_stop.set() +ike_sock.close() +shutil.rmtree(fw_dir, ignore_errors=True) +shutil.rmtree(net_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"})