diff --git a/CHANGELOG.md b/CHANGELOG.md index 78887d7..66b4ad6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,27 @@ fields, and state from an older version is read by a newer one. There are no git tags. The hash next to a version is the commit that introduced it; the current entry is the commit that adds this section. -## 1.11.0 — 2026-11-21 — this change +## 1.12.0 — 2026-11-21 — this change + +- **Docker** (`docker_api_probe`): queries `/version` and + `/containers/json?all=1` without credentials and reports engine/API version, + OS, container and running counts, container names and images. An open API is + audited; 401/403 is reported as protected; the version reply is evidence. +- **Elasticsearch** (`elasticsearch_probe`): GET `/`, `/_cluster/health` and + `/_cat/indices` without credentials; reports cluster name, version, tagline, + health, node and index counts, and treats 401/403 as protected. +- **IMAP** (`imap_probe`): banner, CAPABILITY list, STARTTLS and + LOGINDISABLED flags, then LOGOUT. No LOGIN; plain IMAP only. +- **Blue** (`module_audit`): reads `/proc/modules`, the per-module taint letters + in `/sys/module//taint` and `/proc/sys/kernel/tainted`, decodes the + taint bits and lists every tainted module; all three paths can point at a + mounted image. +- The tool table grows to 128 slots (`g_tools[128]`) so the next tools fit. +- Tests with local fixtures: Docker open and 401, Elasticsearch root/health/ + indices, an IMAP server with STARTTLS+LOGINDISABLED, and a fake module tree + with two tainted modules and taint value 12289. 605 checks. Coverage 79.5%. + +## 1.11.0 — 2026-11-21 — 48ca583 - **VNC** (`vnc_probe`): reads the RFB version, echoes it, then reads the offered security types (3.7/3.8 list or 3.3 single type), names each one and diff --git a/README.md b/README.md index 43f8ec4..4927dc5 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. -**92 tools · 593 end-to-end checks · 340 fuzz cases · 79.3% line coverage · ~437 KiB** +**96 tools · 605 end-to-end checks · 340 fuzz cases · 79.5% line coverage · ~453 KiB** ``` $ ./apex-twin --check -{"version":"1.11.0","tools":92,...,"scope":{"loaded":true,...}} +{"version":"1.12.0","tools":96,...,"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 (92) +## Tools (96) ### Scope and bookkeeping @@ -265,6 +265,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `vnc_probe` | RFB version and offered security types; flags None authentication | | `mqtt_probe` | MQTT 3.1.1 CONNECT without credentials; CONNACK code, anonymous broker detection | | `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 | +| `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN | | `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 | @@ -294,6 +297,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `ssh_key_audit` | authorized_keys and private keys: unrestricted entries, ssh-rsa/ssh-dss, duplicates, loose permissions | | `suid_baseline` | SUID/SGID SHA-256 manifest (`create`/`verify`); reports planted, removed and changed setuid binaries | | `cap_baseline` | File capability xattr manifest (`create`/`verify`); reports new, gone and changed capability sets | +| `module_audit` | Loaded modules and taint letters, kernel taint bits decoded (proprietary, out-of-tree, unsigned, ...) | ### ESP32 @@ -491,6 +495,8 @@ The full threat model, trust boundaries and a hardening checklist are in | SUID baseline | 2000 entries; 1 MiB per file hashed | | VNC/MQTT | one connection and one handshake each | | Capability baseline | 2000 entries; security.capability xattr only | +| Docker/Elasticsearch | two or three GETs, no credentials | +| Module audit | 500 modules; /proc and /sys reads only | --- @@ -501,7 +507,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 593 end-to-end checks +make test # version check + gate audit + 605 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 @@ -607,11 +613,12 @@ 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, ssti_probe, xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, - mqtt_probe, graphql_probe + mqtt_probe, graphql_probe, docker_api_probe, + elasticsearch_probe, imap_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 + ssh_key_audit, suid_baseline, cap_baseline, module_audit 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 @@ -646,7 +653,7 @@ examples/ scope.json ## Status -1.11.0. Built and run: 92 tools, 593 checks, 340 fuzz cases and 79.3% line +1.12.0. Built and run: 96 tools, 605 checks, 340 fuzz cases and 79.5% line coverage. The loop closes: a probe captures the exchange as a pair, a finding points at it, `finding_update` gives it a state, an asset records the host it came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a @@ -675,7 +682,9 @@ PostgreSQL, MongoDB and Memcached probes; 1.8 added parameter fuzzing, open redirect and Host-header checks plus a network baseline; 1.9 added SSTI, XXE and LDAP probes plus an SSH key audit; 1.10 added RDP and SMB negotiation checks and a SUID baseline; 1.11 added VNC, MQTT and GraphQL checks plus a file -capability baseline, again without changing an existing tool or file format. +capability baseline; 1.12 added Docker, Elasticsearch and IMAP checks plus a +kernel module/taint 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 13714a8..8ac9281 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.11.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.12.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,11 @@ 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. +- **Container, search and IMAP probes issue reads only.** `docker_api_probe` + asks `/version` and `/containers/json`; `elasticsearch_probe` asks `/`, + cluster health and the index list; `imap_probe` reads CAPABILITY and logs + out. None authenticates, starts a container, runs a query against user data + or logs into a mailbox. - **VNC and MQTT stop at the handshake.** `vnc_probe` reads the offered security types and never authenticates; `mqtt_probe` sends one CONNECT with no credentials, reads CONNACK and disconnects. `graphql_probe` sends only an diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 7e03f06..accc1a2 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.11.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.12.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -41,10 +41,11 @@ ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe, 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), 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) -and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash). +graphql_probe, docker_api_probe, elasticsearch_probe, imap_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) and +ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash). .SH MODES .TP .B apex-twin diff --git a/src/apex-twin.c b/src/apex-twin.c index 38990fd..ba6af79 100644 --- a/src/apex-twin.c +++ b/src/apex-twin.c @@ -35,7 +35,7 @@ #define MAX_BODY (8u << 20) static mcp_server g_srv; -static mcp_tool g_tools[96]; +static mcp_tool g_tools[128]; static volatile sig_atomic_t g_http_stop; static volatile sig_atomic_t g_http_child_exit; static int g_http_children; @@ -102,31 +102,31 @@ static void build_tools(void) size_t n = 0; size_t i; - for (i = 0; i < TOOLS_RECON_N && n < 96; i++) + for (i = 0; i < TOOLS_RECON_N && n < 128; i++) g_tools[n++] = TOOLS_RECON[i]; - for (i = 0; i < TOOLS_WEB_N && n < 96; i++) + for (i = 0; i < TOOLS_WEB_N && n < 128; i++) g_tools[n++] = TOOLS_WEB[i]; - for (i = 0; i < TOOLS_RADIO_N && n < 96; i++) + for (i = 0; i < TOOLS_RADIO_N && n < 128; i++) g_tools[n++] = TOOLS_RADIO[i]; - for (i = 0; i < TOOLS_KB_N && n < 96; i++) + for (i = 0; i < TOOLS_KB_N && n < 128; i++) g_tools[n++] = TOOLS_KB[i]; - for (i = 0; i < TOOLS_REPORT_N && n < 96; i++) + for (i = 0; i < TOOLS_REPORT_N && n < 128; i++) g_tools[n++] = TOOLS_REPORT[i]; - for (i = 0; i < TOOLS_GUARD_N && n < 96; i++) + for (i = 0; i < TOOLS_GUARD_N && n < 128; i++) g_tools[n++] = TOOLS_GUARD[i]; - for (i = 0; i < TOOLS_ASSET_N && n < 96; i++) + for (i = 0; i < TOOLS_ASSET_N && n < 128; i++) g_tools[n++] = TOOLS_ASSET[i]; - for (i = 0; i < TOOLS_TRAFFIC_N && n < 96; i++) + for (i = 0; i < TOOLS_TRAFFIC_N && n < 128; i++) g_tools[n++] = TOOLS_TRAFFIC[i]; - for (i = 0; i < TOOLS_RED_N && n < 96; i++) + for (i = 0; i < TOOLS_RED_N && n < 128; i++) g_tools[n++] = TOOLS_RED[i]; - for (i = 0; i < TOOLS_BLUE_N && n < 96; i++) + for (i = 0; i < TOOLS_BLUE_N && n < 128; i++) g_tools[n++] = TOOLS_BLUE[i]; - for (i = 0; i < TOOLS_ESP_N && n < 96; i++) + for (i = 0; i < TOOLS_ESP_N && n < 128; i++) g_tools[n++] = TOOLS_ESP[i]; - for (i = 0; i < TOOLS_PROTO_N && n < 96; i++) + for (i = 0; i < TOOLS_PROTO_N && n < 128; i++) g_tools[n++] = TOOLS_PROTO[i]; - for (i = 0; i < TOOLS_DB_N && n < 96; i++) + for (i = 0; i < TOOLS_DB_N && n < 128; i++) g_tools[n++] = TOOLS_DB[i]; g_srv.name = "apex-twin"; diff --git a/src/apex.h b/src/apex.h index 7601e29..e3b4118 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.11.0" +#define APEX_VERSION "1.12.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 81c8cd4..5974372 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -3090,6 +3090,170 @@ static void t_cap_baseline(mcp_conn *c, const mcp_json *args, void *user) free(base_entries); } +/* --------------------------------------------------------------- module_audit */ + +typedef struct { + char name[64]; + char taint[32]; +} mod_entry; + +static const struct { + int bit; + const char *name; +} TAINT_BITS[] = { + { 0, "proprietary" }, + { 1, "forced-module" }, + { 2, "cpu-out-of-spec" }, + { 3, "forced-unload" }, + { 4, "machine-check" }, + { 5, "bad-page" }, + { 6, "user" }, + { 7, "die" }, + { 8, "acpi-override" }, + { 9, "warn" }, + { 10, "staging" }, + { 11, "firmware-workaround" }, + { 12, "out-of-tree" }, + { 13, "unsigned" }, + { 14, "softlockup" }, + { 15, "livepatch" }, + { 16, "aux" }, + { 17, "randstruct" }, + { 18, "test" }, + { -1, NULL } +}; + +static void t_module_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *modules_path = mcp_arg_string(args, "modules"); + const char *sysfs = mcp_arg_string(args, "sysfs"); + const char *tainted_path = mcp_arg_string(args, "tainted"); + int limit = mcp_arg_int(args, "limit", 500); + mod_entry *mods = NULL; + int nmods = 0; + FILE *f; + char *line = NULL; + size_t cap = 0; + int tainted = 0; + int out_of_tree = 0; + int unsigned_mods = 0; + int findings = 0; + char kernel_taint[32]; + unsigned long taint_value = 0; + mcp_buf b; + + (void)user; + if (modules_path == NULL || *modules_path == '\0') + modules_path = "/proc/modules"; + if (sysfs == NULL || *sysfs == '\0') + sysfs = "/sys/module"; + if (tainted_path == NULL || *tainted_path == '\0') + tainted_path = "/proc/sys/kernel/tainted"; + if (limit <= 0 || limit > 5000) + limit = 500; + mods = calloc((size_t)limit, sizeof(*mods)); + if (mods == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + f = fopen(modules_path, "rb"); + if (f == NULL) { + free(mods); + mcp_reply_error(c, "cannot read the module list"); + return; + } + while (nmods < limit && getline(&line, &cap, f) >= 0) { + char name[64]; + int w = 0; + + while (line[w] == ' ' || line[w] == '\t') + w++; + { + int k = 0; + + while (line[w] != '\0' && line[w] != ' ' && + line[w] != '\t' && line[w] != '\n' && + k + 1 < (int)sizeof(name)) + name[k++] = line[w++]; + name[k] = '\0'; + } + if (name[0] == '\0') + continue; + snprintf(mods[nmods].name, sizeof(mods[nmods].name), "%s", name); + mods[nmods].taint[0] = '\0'; + { + char path[512]; + char buf[64]; + + snprintf(path, sizeof(path), "%.400s/%.60s/taint", sysfs, name); + if (read_text(path, buf, sizeof(buf)) > 0) { + trim_eol(buf); + snprintf(mods[nmods].taint, + sizeof(mods[nmods].taint), "%.24s", buf); + } + } + nmods++; + } + free(line); + fclose(f); + kernel_taint[0] = '\0'; + if (read_text(tainted_path, kernel_taint, sizeof(kernel_taint)) > 0) { + trim_eol(kernel_taint); + taint_value = strtoul(kernel_taint, NULL, 10); + } + for (int i = 0; i < nmods; i++) { + if (mods[i].taint[0] == '\0') + continue; + tainted++; + if (strchr(mods[i].taint, 'O') != NULL) + out_of_tree++; + if (strchr(mods[i].taint, 'E') != NULL) + unsigned_mods++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"modules_path\":"); + apex_json_str(&b, modules_path); + mcp_buf_printf(&b, ",\"modules\":%d,\"tainted_modules\":%d," + "\"out_of_tree\":%d,\"unsigned\":%d," + "\"kernel_tainted\":%lu,\"kernel_flags\":[", + nmods, tainted, out_of_tree, unsigned_mods, taint_value); + { + int first = 1; + int t; + + for (t = 0; TAINT_BITS[t].bit >= 0; t++) { + if ((taint_value & (1UL << TAINT_BITS[t].bit)) == 0) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, TAINT_BITS[t].name); + } + } + mcp_buf_puts(&b, "],\"findings\":["); + { + int first = 1; + + for (int i = 0; i < nmods; i++) { + if (mods[i].taint[0] == '\0') + continue; + findings++; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"module\":"); + apex_json_str(&b, mods[i].name); + mcp_buf_puts(&b, ",\"taint\":"); + apex_json_str(&b, mods[i].taint); + mcp_buf_puts(&b, "}"); + } + } + mcp_buf_printf(&b, "],\"findings_count\":%d}", findings); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(mods); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -3251,6 +3415,22 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"max entries, default " "2000\"}}}", t_cap_baseline }, + { "module_audit", + "Read the loaded kernel modules (/proc/modules), the per-module taint " + "letters (/sys/module//taint) and the kernel taint value " + "(/proc/sys/kernel/tainted), decode the taint bits (proprietary, forced, " + "staging, out-of-tree, unsigned, ...) and list every tainted module. The " + "three paths can be overridden to audit a mounted image. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"modules\":{\"type\":\"string\",\"description\":\"default " + "/proc/modules\"}," + "\"sysfs\":{\"type\":\"string\",\"description\":\"default " + "/sys/module\"}," + "\"tainted\":{\"type\":\"string\",\"description\":\"default " + "/proc/sys/kernel/tainted\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max modules, default " + "500\"}}}", + t_module_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 7878521..175dc1d 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -2604,6 +2604,140 @@ static void t_mqtt_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- imap_probe */ + +static void imap_cap_add(char caps[][64], int *n, const char *tok) +{ + int i; + + if (*tok == '\0') + return; + for (i = 0; i < *n; i++) + if (strcasecmp(caps[i], tok) == 0) + return; + if (*n < 32) + snprintf(caps[*n], sizeof(caps[0]), "%.48s", tok); + (*n)++; +} + +static void imap_cap_list(char caps[][64], int *n, const char *text) +{ + char copy[768]; + char *save = NULL; + char *tok; + + snprintf(copy, sizeof(copy), "%s", text); + tok = strtok_r(copy, " \t", &save); + while (tok != NULL) { + char clean[64]; + size_t w = 0; + + while (*tok != '\0' && *tok != ']' && w + 1 < sizeof(clean)) + clean[w++] = *tok++; + clean[w] = '\0'; + imap_cap_add(caps, n, clean); + tok = strtok_r(NULL, " \t", &save); + } +} + +static void t_imap_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", 143); + char banner[512]; + char line[1024]; + char caps[32][64]; + int ncaps = 0; + int starttls = 0; + int logindisabled = 0; + int i; + int rounds; + int fd; + 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, "imap_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the IMAP service"); + return; + } + if (apex_net_line(fd, banner, sizeof(banner)) < 0 || + (strncmp(banner, "* OK", 4) != 0 && + strncmp(banner, "* PREAUTH", 9) != 0)) { + close(fd); + mcp_reply_error(c, "no IMAP banner"); + return; + } + { + const char *cap = strstr(banner, "[CAPABILITY "); + + if (cap != NULL) { + const char *end = strchr(cap, ']'); + char inside[512]; + size_t n = end != NULL ? (size_t)(end - cap - 12) + : strlen(cap + 12); + + if (n >= sizeof(inside)) + n = sizeof(inside) - 1; + memcpy(inside, cap + 12, n); + inside[n] = '\0'; + imap_cap_list(caps, &ncaps, inside); + } + } + if (apex_net_write(fd, "a1 CAPABILITY\r\n") == 0) { + for (rounds = 0; rounds < 20; rounds++) { + int len = apex_net_line(fd, line, sizeof(line)); + + if (len < 0) + break; + if (strncmp(line, "* CAPABILITY ", 13) == 0) + imap_cap_list(caps, &ncaps, line + 13); + if (strncmp(line, "a1 ", 3) == 0) + break; + } + } + { + static const char logout[] = "a2 LOGOUT\r\n"; + + (void)write(fd, logout, sizeof(logout) - 1); + } + close(fd); + for (i = 0; i < ncaps && i < 32; i++) { + if (strcasecmp(caps[i], "STARTTLS") == 0) + starttls = 1; + if (strcasecmp(caps[i], "LOGINDISABLED") == 0) + logindisabled = 1; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"imap\":true,\"banner\":", port); + apex_json_str(&b, banner); + mcp_buf_printf(&b, ",\"starttls\":%s,\"logindisabled\":%s," + "\"capabilities\":[", starttls ? "true" : "false", + logindisabled ? "true" : "false"); + for (i = 0; i < ncaps && i < 32; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, caps[i]); + } + mcp_buf_puts(&b, "]}"); + apex_audit("imap_probe", target, port, starttls, + starttls ? "STARTTLS offered" : "no STARTTLS", banner); + 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 " @@ -2746,6 +2880,16 @@ const mcp_tool TOOLS_PROTO[] = { "default apex\"}}," "\"required\":[\"target\"]}", t_mqtt_probe }, + { "imap_probe", + "Read the IMAP banner, send CAPABILITY and report the capability list " + "with STARTTLS and LOGINDISABLED flags. No LOGIN is attempted and the " + "session is closed with LOGOUT. Plain IMAP (143); implicit TLS (993) is " + "not negotiated. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 143\"}}," + "\"required\":[\"target\"]}", + t_imap_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 2b54992..43c89b9 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -2521,6 +2521,301 @@ static void t_graphql_probe(mcp_conn *c, const mcp_json *args, void *user) free(resp); } +/* ---------------------------------------------------------- docker_api_probe */ + +static void json_field(const char *text, const char *key, char *out, size_t n) +{ + char pattern[80]; + const char *p; + size_t w = 0; + + out[0] = '\0'; + snprintf(pattern, sizeof(pattern), "\"%s\":\"", key); + p = strstr(text, pattern); + if (p == NULL) + return; + p += strlen(pattern); + while (*p != '\0' && *p != '"' && w + 1 < n) { + if (*p == '\\' && p[1] != '\0') + p++; + out[w++] = *p++; + } + out[w] = '\0'; +} + +static int count_needle(const char *text, const char *needle) +{ + int count = 0; + const char *p = text; + + while ((p = strstr(p, needle)) != NULL) { + count++; + p += strlen(needle); + } + return count; +} + +static void collect_named(const char *text, const char *key, + char out[][128], int max, int *count) +{ + char pattern[80]; + const char *p; + int n = 0; + + snprintf(pattern, sizeof(pattern), "\"%s\":\"", key); + p = text; + while (n < max && (p = strstr(p, pattern)) != NULL) { + size_t w = 0; + + p += strlen(pattern); + while (*p != '\0' && *p != '"' && w + 1 < 128) { + if (*p == '\\' && p[1] != '\0') + p++; + out[n][w++] = *p++; + } + out[n][w] = '\0'; + n++; + } + *count = n; +} + +static void t_docker_api_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", 2375); + char status[256]; + char *version = NULL; + char *containers = NULL; + size_t vlen = 0; + size_t clen = 0; + int vcode; + int ccode = 0; + char ver[64]; + char api[64]; + char os_name[64]; + char names[10][128]; + char image_names[10][128]; + int nnames = 0; + int nimages = 0; + int count = 0; + int running = 0; + char *evidence = NULL; + 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, "docker_api_probe", target, port)) + return; + status[0] = '\0'; + if (apex_http_once(target, port, 0, "GET", "/version", NULL, NULL, 8000, + &version, &vlen, status, sizeof(status)) != 0) { + mcp_reply_error(c, "cannot reach the Docker API"); + return; + } + vcode = apex_status_code(status); + ver[0] = api[0] = os_name[0] = '\0'; + if (vcode == 200) { + json_field(version, "Version", ver, sizeof(ver)); + json_field(version, "ApiVersion", api, sizeof(api)); + json_field(version, "Os", os_name, sizeof(os_name)); + status[0] = '\0'; + if (apex_http_once(target, port, 0, "GET", "/containers/json?all=1", + NULL, NULL, 10000, &containers, &clen, status, + sizeof(status)) == 0) { + ccode = apex_status_code(status); + count = count_needle(containers, "\"Id\":\""); + running = count_needle(containers, "\"State\":\"running\""); + { + const char *p = containers; + + nnames = 0; + while (nnames < 10 && + (p = strstr(p, "\"Names\":[")) != NULL) { + size_t w = 0; + + p += 9; + if (*p == '"') { + p++; + while (*p != '\0' && *p != '"' && w + 1 < 128) + names[nnames][w++] = *p++; + names[nnames][w] = '\0'; + nnames++; + } + } + nimages = 0; + collect_named(containers, "Image", image_names, 10, + &nimages); + } + } + } + if (vcode == 200 || vcode == 401 || vcode == 403) + apex_audit("docker_api_probe", target, port, vcode != 200, + vcode == 200 ? "unauthenticated Docker API" + : "Docker API requires authentication", + "/version"); + evidence = apex_evidence_save("docker", version, vlen); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"docker\":%s,\"protected\":%s," + "\"version\":", port, + (vcode == 200 || vcode == 401 || vcode == 403) + ? "true" : "false", + vcode == 401 || vcode == 403 ? "true" : "false"); + apex_json_str(&b, ver); + mcp_buf_puts(&b, ",\"api_version\":"); + apex_json_str(&b, api); + mcp_buf_puts(&b, ",\"os\":"); + apex_json_str(&b, os_name); + mcp_buf_printf(&b, ",\"containers\":%d,\"running\":%d,\"containers_status\":%d," + "\"names\":[", count, running, ccode); + { + int i; + + for (i = 0; i < nnames && i < 10; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, names[i]); + } + } + mcp_buf_printf(&b, "],\"image_count\":%d,\"images\":[", nimages); + { + int i; + + for (i = 0; i < nimages && i < 10; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, image_names[i]); + } + } + mcp_buf_puts(&b, "],\"evidence\":"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(evidence); + free(version); + free(containers); +} + +/* ------------------------------------------------------- elasticsearch_probe */ + +static void t_elasticsearch_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", 9200); + char status[256]; + char *root = NULL; + char *health = NULL; + char *indices = NULL; + size_t rlen = 0; + size_t hlen = 0; + size_t ilen = 0; + int rcode; + int hcode = 0; + int icode = 0; + char cluster[128]; + char version[64]; + char tagline[128]; + char hstatus[32]; + char *evidence = NULL; + int index_count = 0; + int nodes = -1; + 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, "elasticsearch_probe", target, port)) + return; + status[0] = '\0'; + if (apex_http_once(target, port, 0, "GET", "/", NULL, NULL, 8000, &root, + &rlen, status, sizeof(status)) != 0) { + mcp_reply_error(c, "cannot reach the Elasticsearch API"); + return; + } + rcode = apex_status_code(status); + cluster[0] = version[0] = tagline[0] = hstatus[0] = '\0'; + if (rcode == 200) { + json_field(root, "cluster_name", cluster, sizeof(cluster)); + json_field(root, "number", version, sizeof(version)); + json_field(root, "tagline", tagline, sizeof(tagline)); + status[0] = '\0'; + if (apex_http_once(target, port, 0, "GET", "/_cluster/health", NULL, + NULL, 8000, &health, &hlen, status, + sizeof(status)) == 0) { + hcode = apex_status_code(status); + json_field(health, "status", hstatus, sizeof(hstatus)); + { + const char *p = strstr(health, "\"number_of_nodes\":"); + int n; + + if (p != NULL && sscanf(p + 18, "%d", &n) == 1) + nodes = n; + } + } + status[0] = '\0'; + if (apex_http_once(target, port, 0, "GET", + "/_cat/indices?format=json&h=index", NULL, NULL, + 8000, &indices, &ilen, status, + sizeof(status)) == 0) { + icode = apex_status_code(status); + index_count = count_needle(indices, "\"index\":\""); + } + } + if (rcode == 200 || rcode == 401 || rcode == 403) + apex_audit("elasticsearch_probe", target, port, rcode != 200, + rcode == 200 ? "unauthenticated Elasticsearch API" + : "Elasticsearch requires authentication", + "/"); + evidence = apex_evidence_save("elasticsearch", root, rlen); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"elasticsearch\":%s,\"protected\":%s," + "\"cluster_name\":", port, + (rcode == 200 || rcode == 401 || rcode == 403) + ? "true" : "false", + rcode == 401 || rcode == 403 ? "true" : "false"); + apex_json_str(&b, cluster); + mcp_buf_puts(&b, ",\"version\":"); + apex_json_str(&b, version); + mcp_buf_puts(&b, ",\"tagline\":"); + apex_json_str(&b, tagline); + mcp_buf_puts(&b, ",\"health\":"); + apex_json_str(&b, hstatus); + mcp_buf_printf(&b, ",\"nodes\":%d,\"indices\":%d,\"health_status\":%d," + "\"indices_status\":%d,\"evidence\":", + nodes, index_count, hcode, icode); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(evidence); + free(root); + free(health); + free(indices); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -2750,6 +3045,28 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_graphql_probe }, + { "docker_api_probe", + "Query the Docker Engine API without credentials: /version (engine " + "version, API version, OS) and /containers/json?all=1 (container count, " + "running count, images). An open API is audited and the version reply is " + "saved as evidence; 401/403 is reported as protected. Plain HTTP (2375), " + "one or two GETs. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 2375\"}}," + "\"required\":[\"target\"]}", + t_docker_api_probe }, + { "elasticsearch_probe", + "Query an Elasticsearch HTTP API without credentials: GET / (cluster " + "name, version, tagline), /_cluster/health (status, node count) and " + "/_cat/indices (index count). An open API is audited and the root reply " + "is saved as evidence; 401/403 is reported as protected. Gate: the " + "target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 9200\"}}," + "\"required\":[\"target\"]}", + t_elasticsearch_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 a69af62..d7f2b5b 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 = 92 +EXPECTED_TOOLS = 96 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 41366e8..c3596ad 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("92 tools registered", len(tools) == 92, len(tools)) +check("96 tools registered", len(tools) == 96, 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"]) == 92) + check("http tools/list", len(listing["result"]["tools"]) == 96) 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 @@ -4401,6 +4401,178 @@ gql_srv.server_close() shutil.rmtree(cap_root, ignore_errors=True) shutil.rmtree(cap_home, ignore_errors=True) +print("\n== Docker, Elasticsearch, IMAP and kernel modules ==") + + +class _DockerHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/version": + doc = {"Version": "24.0.7", "ApiVersion": "1.43", + "Os": "linux", "Arch": "amd64"} + body = json.dumps(doc, separators=(",", ":")).encode() + code = 200 + elif path == "/containers/json": + doc = [ + {"Id": "abc123", "Names": ["/web"], "Image": "nginx:latest", + "State": "running"}, + {"Id": "def456", "Names": ["/db"], "Image": "postgres:16", + "State": "exited"}, + ] + body = json.dumps(doc, separators=(",", ":")).encode() + code = 200 + else: + body = b"not found" + code = 404 + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +class _DockerProtectedHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = b"unauthorized" + self.send_response(401) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +class _ElasticHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/": + doc = {"name": "node-1", "cluster_name": "apex-cluster", + "version": {"number": "8.13.0"}, + "tagline": "You Know, for Search"} + elif path == "/_cluster/health": + doc = {"cluster_name": "apex-cluster", "status": "yellow", + "number_of_nodes": 2} + elif path == "/_cat/indices": + doc = [{"index": "users"}, {"index": "logs"}, + {"index": "events"}] + else: + doc = {"error": "not found"} + body = json.dumps(doc, separators=(",", ":")).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def imap_handler(conn): + f = conn.makefile("rb") + conn.sendall(b"* OK [CAPABILITY IMAP4rev1 STARTTLS AUTH=PLAIN] " + b"test ready\r\n") + f.readline() + conn.sendall(b"* CAPABILITY IMAP4rev1 STARTTLS AUTH=PLAIN " + b"LOGINDISABLED\r\n") + conn.sendall(b"a1 OK done\r\n") + f.readline() + conn.sendall(b"* BYE\r\na2 OK logout\r\n") + time.sleep(0.05) + + +docker_srv = http.server.HTTPServer(("127.0.0.1", 0), _DockerHandler) +docker_port = docker_srv.server_address[1] +threading.Thread(target=docker_srv.serve_forever, daemon=True).start() +docker_prot_srv = http.server.HTTPServer(("127.0.0.1", 0), + _DockerProtectedHandler) +docker_prot_port = docker_prot_srv.server_address[1] +threading.Thread(target=docker_prot_srv.serve_forever, daemon=True).start() +es_srv = http.server.HTTPServer(("127.0.0.1", 0), _ElasticHandler) +es_port = es_srv.server_address[1] +threading.Thread(target=es_srv.serve_forever, daemon=True).start() +imap_srv, imap_port = start_line_server(imap_handler) + +mod_root = tempfile.mkdtemp(prefix="apex-mod-") +mods_path = os.path.join(mod_root, "modules") +with open(mods_path, "w") as f: + f.write("nvidia 123 1 - Live 0x0000000000000000\n") + f.write("evilmod 456 0 - Live 0x0000000000000000\n") + f.write("cleanmod 789 0 - Live 0x0000000000000000\n") +sysfs_root = os.path.join(mod_root, "sys") +for name, taint in (("nvidia", "OE"), ("evilmod", "E")): + os.makedirs(os.path.join(sysfs_root, name)) + with open(os.path.join(sysfs_root, name, "taint"), "w") as f: + f.write(taint + "\n") +tainted_file = os.path.join(mod_root, "tainted") +with open(tainted_file, "w") as f: + f.write("12289\n") + +svc_home = tempfile.mkdtemp(prefix="apex-svc-") +write_scope(svc_home, {"label": "svc", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(docker_port), str(docker_prot_port), + str(es_port), str(imap_port)]}) +res, _ = run([ + call(1, "docker_api_probe", target="127.0.0.1", port=docker_port), + call(2, "docker_api_probe", target="127.0.0.1", port=docker_prot_port), + call(3, "elasticsearch_probe", target="127.0.0.1", port=es_port), + call(4, "imap_probe", target="127.0.0.1", port=imap_port), + call(5, "module_audit", modules=mods_path, sysfs=sysfs_root, + tainted=tainted_file), + call(6, "docker_api_probe", target="198.51.100.9", port=2375), +], home=svc_home) +by_id = {r.get("id"): r for r in res} +docker = json.loads(text(by_id[1])) +check("docker_api_probe reads the engine version", + docker["docker"] is True and docker["version"] == "24.0.7" and + docker["api_version"] == "1.43" and docker["os"] == "linux", docker) +check("docker_api_probe counts containers and images", + docker["containers"] == 2 and docker["running"] == 1 and + docker["image_count"] == 2 and docker["names"] == ["/web", "/db"], + docker) +check("docker_api_probe keeps the version reply as evidence", + docker["evidence"] and os.path.isfile(docker["evidence"]), docker) +docker_no = json.loads(text(by_id[2])) +check("docker_api_probe reports a protected daemon", + docker_no["docker"] is True and docker_no["protected"] is True, + docker_no) +es = json.loads(text(by_id[3])) +check("elasticsearch_probe reads the cluster document", + es["elasticsearch"] is True and es["cluster_name"] == "apex-cluster" and + es["version"] == "8.13.0" and es["tagline"] == "You Know, for Search", + es) +check("elasticsearch_probe reads health and index count", + es["health"] == "yellow" and es["nodes"] == 2 and es["indices"] == 3, + es) +imap = json.loads(text(by_id[4])) +caps = set(imap["capabilities"]) +check("imap_probe reads the capabilities", + imap["imap"] is True and {"IMAP4rev1", "AUTH=PLAIN"} <= caps, imap) +check("imap_probe flags STARTTLS and LOGINDISABLED", + imap["starttls"] is True and imap["logindisabled"] is True, imap) +mods = json.loads(text(by_id[5])) +check("module_audit counts and taints the modules", + mods["modules"] == 3 and mods["tainted_modules"] == 2 and + mods["out_of_tree"] == 1 and mods["unsigned"] == 2, mods) +check("module_audit decodes the kernel taint bits", + {"proprietary", "out-of-tree", "unsigned"} <= + set(mods["kernel_flags"]), mods["kernel_flags"]) +check("module_audit names the tainted modules", + {f["module"] for f in mods["findings"]} == {"nvidia", "evilmod"}, mods) +check("docker_api_probe refuses an out-of-scope target", err(by_id[6]), + text(by_id[6])) +for srv in (docker_srv, docker_prot_srv, es_srv): + srv.shutdown() + srv.server_close() +imap_srv.close() +shutil.rmtree(mod_root, ignore_errors=True) +shutil.rmtree(svc_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"})