diff --git a/CHANGELOG.md b/CHANGELOG.md index ce759fc..b54df31 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.38.0 — 2026-11-21 — this change +## 1.39.0 — 2026-11-21 — this change + +- **Kubernetes** (`kubernetes_api_probe`): GET `/version`, `/api`, `/apis` and + `/healthz` without a token; a 2xx answer is unauthenticated access, audited, + with the first two responses saved as evidence. +- **Grafana** (`grafana_audit`): grafana.ini with section-aware INI parsing: + anonymous access, default/empty admin password, plain HTTP and the default + secret key. +- **Prometheus** (`prometheus_audit`): prometheus.yml/web.yml: missing + basic_auth_users, missing external_labels, plain-HTTP scrape targets and + world-writable files. +- **NS consistency** (`dns_ns_consistency`): compares the parent NS set with + the set served by the domain's own first nameserver (resolved to an address) + and reports names missing on either side. +- The tool table hit its 192-slot cap at 195 tools; it is now 256. +- Tests with a Kubernetes HTTP fixture (open and 401), Grafana/Prometheus + trees and two DNS agents on different loopback addresses (consistent and + stale delegation). 918 checks. Coverage 82.2%. + +## 1.38.0 — 2026-11-21 — ebb046c - **Consul** (`consul_config_audit`): consul.hcl and consul.d/*.hcl: ACL default policy allow, bind_addr on every interface, incoming/outgoing diff --git a/README.md b/README.md index 3dcdaf9..2774131 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. -**191 tools · 905 end-to-end checks · 340 fuzz cases · 82.1% line coverage · ~738 KiB** +**195 tools · 918 end-to-end checks · 340 fuzz cases · 82.2% line coverage · ~746 KiB** ``` $ ./apex-twin --check -{"version":"1.38.0","tools":191,...,"scope":{"loaded":true,...}} +{"version":"1.39.0","tools":195,...,"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 (191) +## Tools (195) ### Scope and bookkeeping @@ -302,6 +302,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `dns_caa_check` | CAA records: flags, issue/issuewild/iodef tags and values | | `sni_vhost_check` | Per-name `s_client -servername`: distinct certificate subjects/fingerprints | | `tls_client_auth_probe` | `s_client -msg`: CertificateRequest means mutual TLS required | +| `kubernetes_api_probe` | Unauthenticated `/version`, `/api`, `/apis`, `/healthz`; 2xx is open access | +| `dns_ns_consistency` | Parent vs authoritative NS sets; reports names missing on either side | | `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 | @@ -388,6 +390,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `consul_config_audit` | consul.hcl: ACL allow, bind 0.0.0.0, verify flags off, no gossip encryption | | `vault_config_audit` | vault.hcl: tls_disable, UI on, mlock off, Shamir without auto-unseal | | `zookeeper_audit` | zoo.cfg: open 4lw whitelist, clientPortAddress all, missing authProvider | +| `grafana_audit` | grafana.ini: anonymous access, default admin password, plain HTTP, default secret | +| `prometheus_audit` | prometheus.yml/web.yml: no basic auth, no external labels, HTTP targets | ### ESP32 @@ -650,6 +654,9 @@ The full threat model, trust boundaries and a hardening checklist are in | SNI | one TLS handshake per name, no data | | consul/vault/zookeeper | config reads only; optional root prefix | | mTLS | one handshake, no client certificate presented | +| grafana/prometheus | config reads only; optional root prefix | +| Kubernetes API | four unauthenticated GETs | +| NS consistency | up to three dig queries | | USB audit | 200 devices, sysfs reads only | --- @@ -661,7 +668,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 905 end-to-end checks +make test # version check + gate audit + 918 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 @@ -779,7 +786,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, kerberos_discovery, winrm_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check, - sni_vhost_check, tls_client_auth_probe + sni_vhost_check, tls_client_auth_probe, + kubernetes_api_probe, dns_ns_consistency 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, @@ -822,7 +830,7 @@ examples/ scope.json ## Status -1.38.0. Built and run: 191 tools, 905 checks, 340 fuzz cases and 82.1% line +1.39.0. Built and run: 195 tools, 918 checks, 340 fuzz cases and 82.2% 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 diff --git a/SECURITY.md b/SECURITY.md index ef1f7f9..67ca264 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.38.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.39.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,9 @@ 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. +- **Kubernetes and NS checks are unauthenticated reads.** `kubernetes_api_probe` + sends four GETs without a token; `dns_ns_consistency` queries NS/A records. + Grafana and Prometheus audits read configuration files. - **mTLS detection is one handshake.** `tls_client_auth_probe` reads the CertificateRequest from `s_client -msg` and presents no certificate. Consul, Vault and ZooKeeper audits read configuration files. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 35bcc12..a85059c 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.38.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.39.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -43,7 +43,8 @@ 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, http_methods, websocket_probe, ike_probe, snmp_walk, -ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check, sni_vhost_check, tls_client_auth_probe), +ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check, sni_vhost_check, tls_client_auth_probe, kubernetes_api_probe, +dns_ns_consistency), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -60,7 +61,7 @@ cups_audit, rsync_audit, dhcpd_audit, krb5_conf_audit, mongodb_config_audit, memcached_config_audit, ntpd_config_audit, bind9_config_audit, tomcat_audit, proftpd_audit, kubelet_config_audit, etcd_config_audit, rabbitmq_audit, consul_config_audit, vault_config_audit, -zookeeper_audit) and ESP32 board tools (esp_info, esp_monitor, +zookeeper_audit, grafana_audit, prometheus_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, esp_app_info, esp_image_verify). .SH MODES diff --git a/src/apex-twin.c b/src/apex-twin.c index 7af02b5..b6c31d5 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[192]; +static mcp_tool g_tools[256]; 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 < 192; i++) + for (i = 0; i < TOOLS_RECON_N && n < 256; i++) g_tools[n++] = TOOLS_RECON[i]; - for (i = 0; i < TOOLS_WEB_N && n < 192; i++) + for (i = 0; i < TOOLS_WEB_N && n < 256; i++) g_tools[n++] = TOOLS_WEB[i]; - for (i = 0; i < TOOLS_RADIO_N && n < 192; i++) + for (i = 0; i < TOOLS_RADIO_N && n < 256; i++) g_tools[n++] = TOOLS_RADIO[i]; - for (i = 0; i < TOOLS_KB_N && n < 192; i++) + for (i = 0; i < TOOLS_KB_N && n < 256; i++) g_tools[n++] = TOOLS_KB[i]; - for (i = 0; i < TOOLS_REPORT_N && n < 192; i++) + for (i = 0; i < TOOLS_REPORT_N && n < 256; i++) g_tools[n++] = TOOLS_REPORT[i]; - for (i = 0; i < TOOLS_GUARD_N && n < 192; i++) + for (i = 0; i < TOOLS_GUARD_N && n < 256; i++) g_tools[n++] = TOOLS_GUARD[i]; - for (i = 0; i < TOOLS_ASSET_N && n < 192; i++) + for (i = 0; i < TOOLS_ASSET_N && n < 256; i++) g_tools[n++] = TOOLS_ASSET[i]; - for (i = 0; i < TOOLS_TRAFFIC_N && n < 192; i++) + for (i = 0; i < TOOLS_TRAFFIC_N && n < 256; i++) g_tools[n++] = TOOLS_TRAFFIC[i]; - for (i = 0; i < TOOLS_RED_N && n < 192; i++) + for (i = 0; i < TOOLS_RED_N && n < 256; i++) g_tools[n++] = TOOLS_RED[i]; - for (i = 0; i < TOOLS_BLUE_N && n < 192; i++) + for (i = 0; i < TOOLS_BLUE_N && n < 256; i++) g_tools[n++] = TOOLS_BLUE[i]; - for (i = 0; i < TOOLS_ESP_N && n < 192; i++) + for (i = 0; i < TOOLS_ESP_N && n < 256; i++) g_tools[n++] = TOOLS_ESP[i]; - for (i = 0; i < TOOLS_PROTO_N && n < 192; i++) + for (i = 0; i < TOOLS_PROTO_N && n < 256; i++) g_tools[n++] = TOOLS_PROTO[i]; - for (i = 0; i < TOOLS_DB_N && n < 192; i++) + for (i = 0; i < TOOLS_DB_N && n < 256; i++) g_tools[n++] = TOOLS_DB[i]; g_srv.name = "apex-twin"; diff --git a/src/apex.h b/src/apex.h index 107f36d..2257299 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.38.0" +#define APEX_VERSION "1.39.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 bc48acd..9981b96 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -10770,6 +10770,267 @@ static void t_zookeeper_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- grafana_audit */ + +/* INI reader: only a value inside the named [section] counts. */ +static int ini_value(const char *text, const char *section, const char *key, + char *out, size_t n) +{ + const char *p = text; + char current[64]; + + current[0] = '\0'; + out[0] = '\0'; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[1024]; + char *s; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + s = line; + while (*s == ' ' || *s == '\t') + s++; + if (*s == '[') { + char *close = strchr(s, ']'); + + if (close != NULL) { + size_t cl = (size_t)(close - s - 1); + + if (cl >= sizeof(current)) + cl = sizeof(current) - 1; + memcpy(current, s + 1, cl); + current[cl] = '\0'; + } + } else if (*s != '#' && *s != ';' && *s != '\0' && + strcasecmp(current, section) == 0) { + char *eq = strchr(s, '='); + + if (eq != NULL) { + char *k = s; + char *v; + size_t ke; + + *eq = '\0'; + ke = strlen(k); + while (ke > 0 && (k[ke - 1] == ' ' || + k[ke - 1] == '\t')) + k[--ke] = '\0'; + v = eq + 1; + while (*v == ' ' || *v == '\t') + v++; + if (strcasecmp(k, key) == 0) { + size_t vl = strlen(v); + + while (vl > 0 && (v[vl - 1] == ' ' || + v[vl - 1] == '\t' || + v[vl - 1] == '\r')) + v[--vl] = '\0'; + if (vl >= 2 && v[0] == '"' && + v[vl - 1] == '"') { + v++; + vl -= 2; + } + if (vl >= n) + vl = n - 1; + memcpy(out, v, vl); + out[vl] = '\0'; + return 1; + } + } + } + p = eol != NULL ? eol + 1 : NULL; + } + return 0; +} + +static void t_grafana_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + static char text[65536]; + char path[1024]; + char value[256]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int anonymous = 0; + int default_admin = 0; + int http_only = 0; + int default_secret = 0; + struct stat st; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), "%s/etc/grafana/grafana.ini", root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read grafana.ini"); + return; + } + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "grafana.ini is writable by anyone"); + count++; + } + if (ini_value(text, "auth.anonymous", "enabled", value, sizeof(value)) && + strcasecmp(value, "true") == 0) { + anonymous = 1; + add_finding(&findings, &first, "anonymous-enabled", "high", + "anonymous access is enabled"); + count++; + } + if (!ini_value(text, "security", "admin_password", value, + sizeof(value)) || + value[0] == '\0' || strcasecmp(value, "admin") == 0) { + default_admin = 1; + add_finding(&findings, &first, "default-admin", "high", + "the admin password is default or empty"); + count++; + } + if (!ini_value(text, "server", "protocol", value, sizeof(value)) || + strcasecmp(value, "http") == 0) { + http_only = 1; + add_finding(&findings, &first, "http", "medium", + "the web interface is served over plain HTTP"); + count++; + } + if (!ini_value(text, "security", "secret_key", value, sizeof(value)) || + value[0] == '\0' || + strcmp(value, "SW2YcwTIb9zpOOhoPsMm") == 0) { + default_secret = 1; + add_finding(&findings, &first, "default-secret", "medium", + "the secret key is default or empty"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"anonymous\":%s,\"default_admin\":%s," + "\"http\":%s,\"default_secret\":%s,\"findings_count\":%d," + "\"findings\":[", + anonymous ? "true" : "false", + default_admin ? "true" : "false", + http_only ? "true" : "false", + default_secret ? "true" : "false", count); + if (findings.p != NULL) + mcp_buf_add(&b, findings.p, findings.len); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&findings); +} + +/* ------------------------------------------------------------ prometheus_audit */ + +static void t_prometheus_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + static char prom[65536]; + static char web[65536]; + char path[1024]; + char value[256]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int basic_auth = 0; + int external_labels = 0; + int http_target = 0; + int web_read = 0; + struct stat st; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%s/etc/prometheus/prometheus.yml", root); + if (read_text(path, prom, sizeof(prom)) <= 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read prometheus.yml"); + return; + } + files++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "prometheus.yml is writable by anyone"); + count++; + } + if (yaml_value(prom, "external_labels", value, sizeof(value))) + external_labels = 1; + { + char *copy = strdup(prom); + char *save = NULL; + char *line; + + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + if (strstr(line, "http://") != NULL) + http_target = 1; + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + snprintf(path, sizeof(path), "%s/etc/prometheus/web.yml", root); + if (read_text(path, web, sizeof(web)) > 0) { + web_read = 1; + files++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "web.yml is writable by anyone"); + count++; + } + if (strstr(web, "basic_auth_users") != NULL && + strstr(web, "{}") == NULL) + basic_auth = 1; + } + if (!basic_auth) { + add_finding(&findings, &first, "no-auth", "medium", + web_read ? "the web config has no basic_auth_users" + : "no web config means the API is open"); + count++; + } + if (!external_labels) { + add_finding(&findings, &first, "no-external-labels", "low", + "no external_labels identify the server"); + count++; + } + if (http_target) { + add_finding(&findings, &first, "http-target", "low", + "a scrape target uses plain HTTP"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"basic_auth\":%s," + "\"external_labels\":%s,\"findings_count\":%d," + "\"findings\":[", + files, basic_auth ? "true" : "false", + external_labels ? "true" : "false", count); + if (findings.p != NULL) + mcp_buf_add(&b, findings.p, findings.len); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&findings); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -11358,6 +11619,20 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_zookeeper_audit }, + { "grafana_audit", + "Parse grafana.ini (root prefix, INI sections): anonymous access, " + "default/empty admin password, plain HTTP and the default secret key. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_grafana_audit }, + { "prometheus_audit", + "Parse prometheus.yml and web.yml (root prefix): missing basic_auth_users, " + "missing external_labels, plain-HTTP scrape targets and world-writable " + "files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_prometheus_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 057f1b0..5561712 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -5555,6 +5555,314 @@ static void t_dns_caa_check(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* -------------------------------------------------------- kubernetes_api_probe */ + +static void t_kubernetes_api_probe(mcp_conn *c, const mcp_json *args, + void *user) +{ + static const char *paths[] = { "/version", "/api", "/apis", "/healthz", + NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 6443); + int tls = mcp_arg_bool(args, "tls", + port == 6443 || apex_looks_tls(port)); + mcp_buf b; + int first = 1; + int tested = 0; + int open_count = 0; + int saved = 0; + int i; + + (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, "kubernetes_api_probe", target, port)) + return; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"endpoints\":[", port, + tls ? "true" : "false"); + for (i = 0; paths[i] != NULL; i++) { + char status[256]; + char *resp = NULL; + size_t len = 0; + int code; + int open; + int json = 0; + char *evidence = NULL; + + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", paths[i], NULL, NULL, + 8000, &resp, &len, status, + sizeof(status)) != 0) + continue; + tested++; + code = apex_status_code(status); + open = code >= 200 && code < 300; + if (resp != NULL && find_bytes(resp, len, "{")) + json = 1; + if (open) { + open_count++; + if (saved < 2) { + char label[64]; + + snprintf(label, sizeof(label), "kube-%.24s", + paths[i] + 1); + evidence = apex_evidence_save(label, resp, len); + saved++; + } + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, paths[i]); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu,\"open\":%s," + "\"json\":%s,\"evidence\":", + code, (unsigned long)len, + open ? "true" : "false", json ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + free(evidence); + free(resp); + } + mcp_buf_printf(&b, "],\"tested\":%d,\"open_count\":%d}", tested, + open_count); + apex_audit("kubernetes_api_probe", target, port, open_count == 0, + open_count == 0 + ? "the API requires authentication or is absent" + : "the Kubernetes API answers without a token", "list"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ---------------------------------------------------------- dns_ns_consistency */ + +static int ns_lines(const char *text, char names[][128], int max) +{ + char *copy; + char *save = NULL; + char *line; + int n = 0; + + if (text == NULL) + return 0; + copy = strdup(text); + if (copy == NULL) + return 0; + line = strtok_r(copy, "\n", &save); + while (line != NULL && n < max) { + char *t = line; + size_t len; + int known = 0; + int k; + + while (*t == ' ' || *t == '\t') + t++; + len = strlen(t); + while (len > 0 && (t[len - 1] == '\r' || t[len - 1] == ' ' || + t[len - 1] == '\t')) + t[--len] = '\0'; + if (len > 0 && t[len - 1] == '.') + t[--len] = '\0'; + if (len == 0) { + line = strtok_r(NULL, "\n", &save); + continue; + } + for (k = 0; k < n; k++) + if (strcasecmp(names[k], t) == 0) + known = 1; + if (!known) { + snprintf(names[n], 128, "%.120s", t); + n++; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + return n; +} + +static char *ns_run(const char *resolver, int port, const char *name, + const char *type) +{ + char portstr[16]; + char at_server[300]; + char *argv[12]; + int i = 0; + apex_proc p; + char *out = NULL; + + snprintf(portstr, sizeof(portstr), "%d", port > 0 ? port : 53); + argv[i++] = "dig"; + argv[i++] = "+short"; + argv[i++] = "+time=3"; + argv[i++] = "+tries=1"; + argv[i++] = "-p"; + argv[i++] = portstr; + if (resolver != NULL && *resolver != '\0') { + snprintf(at_server, sizeof(at_server), "@%.200s", resolver); + argv[i++] = at_server; + } + argv[i++] = (char *)name; + argv[i++] = (char *)type; + argv[i] = NULL; + if (apex_run(argv, 15000, 32 * 1024, &p) != 0) + return NULL; + if (p.out != NULL) { + out = p.out; + p.out = NULL; + } + apex_proc_free(&p); + return out; +} + +static void t_dns_ns_consistency(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *domain = mcp_arg_string(args, "domain"); + const char *resolver = mcp_arg_string(args, "resolver"); + int port = mcp_arg_int(args, "port", 0); + char reason[512]; + char parent[16][128]; + char auth[16][128]; + int nparent = 0; + int nauth = 0; + char missing[16][128]; + char extra[16][128]; + int nmissing = 0; + int nextra = 0; + char server[256]; + char *out; + int i; + mcp_buf b; + int first = 1; + + (void)user; + if (domain == NULL || *domain == '\0') { + mcp_reply_error(c, "domain is required"); + return; + } + if (port < 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!apex_scope_check(domain, 0, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + if (resolver != NULL && *resolver != '\0' && + !apex_scope_check(resolver, port, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "resolver is outside the scope: %s", reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + apex_audit("dns_ns_consistency", domain, 0, 1, "NS comparison", + "parent vs authoritative"); + out = ns_run(resolver, port, domain, "NS"); + nparent = ns_lines(out, parent, 16); + free(out); + if (nparent == 0) { + mcp_reply_error(c, "no NS records found for the domain"); + return; + } + snprintf(server, sizeof(server), "%.200s", parent[0]); + out = ns_run(resolver, port, parent[0], "A"); + if (out != NULL) { + char ips[4][128]; + int nips = ns_lines(out, ips, 4); + + if (nips > 0) + snprintf(server, sizeof(server), "%.100s", ips[0]); + free(out); + } + out = ns_run(server, port, domain, "NS"); + nauth = ns_lines(out, auth, 16); + free(out); + for (i = 0; i < nparent; i++) { + int j; + int found = 0; + + for (j = 0; j < nauth; j++) + if (strcasecmp(parent[i], auth[j]) == 0) + found = 1; + if (!found && nmissing < 16) + snprintf(missing[nmissing++], 128, "%.120s", parent[i]); + } + for (i = 0; i < nauth; i++) { + int j; + int found = 0; + + for (j = 0; j < nparent; j++) + if (strcasecmp(auth[i], parent[j]) == 0) + found = 1; + if (!found && nextra < 16) + snprintf(extra[nextra++], 128, "%.120s", auth[i]); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"domain\":"); + apex_json_str(&b, domain); + mcp_buf_puts(&b, ",\"resolver\":"); + apex_json_str(&b, resolver != NULL ? resolver : ""); + mcp_buf_puts(&b, ",\"authoritative_server\":"); + apex_json_str(&b, server); + mcp_buf_puts(&b, ",\"parent\":["); + for (i = 0; i < nparent; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, parent[i]); + } + mcp_buf_puts(&b, "],\"authoritative\":["); + first = 1; + for (i = 0; i < nauth; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, auth[i]); + } + mcp_buf_puts(&b, "],\"missing\":["); + first = 1; + for (i = 0; i < nmissing; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, missing[i]); + } + mcp_buf_puts(&b, "],\"extra\":["); + first = 1; + for (i = 0; i < nextra; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, extra[i]); + } + mcp_buf_printf(&b, "],\"consistent\":%s}", + (nmissing == 0 && nextra == 0 && nauth > 0) + ? "true" : "false"); + apex_audit("dns_ns_consistency", domain, 0, + nmissing == 0 && nextra == 0 && nauth > 0, + (nmissing == 0 && nextra == 0 && nauth > 0) + ? "parent and authoritative NS sets agree" + : "parent and authoritative NS sets differ", server); + 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: " @@ -6032,6 +6340,28 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default 0\"}}," "\"required\":[\"domain\"]}", t_dns_caa_check }, + { "kubernetes_api_probe", + "Query a Kubernetes API without a token: /version, /api, /apis and " + "/healthz. Any 2xx answer is unauthenticated access, audited, with the " + "first two responses saved as evidence. TLS is assumed on 6443. Gate: " + "the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 6443\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_kubernetes_api_probe }, + { "dns_ns_consistency", + "Fetch NS records for a domain from the parent resolver and from its own " + "first nameserver (resolved to an address), then report names present on " + "only one side. A mismatch hints at stale delegation or an unfinished " + "migration. Gate: the domain (and resolver).", + "{\"type\":\"object\",\"properties\":{" + "\"domain\":{\"type\":\"string\"}," + "\"resolver\":{\"type\":\"string\",\"description\":\"optional DNS server\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default 0\"}}," + "\"required\":[\"domain\"]}", + t_dns_ns_consistency }, }; 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 ef52ce9..d874092 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 = 191 +EXPECTED_TOOLS = 195 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 7b29bc3..244c9e4 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("191 tools registered", len(tools) == 191, len(tools)) +check("195 tools registered", len(tools) == 195, 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"]) == 191) + check("http tools/list", len(listing["result"]["tools"]) == 195) 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 @@ -8629,6 +8629,243 @@ shutil.rmtree(zk_good_root, ignore_errors=True) shutil.rmtree(mtls_dir, ignore_errors=True) shutil.rmtree(cfg10_home, ignore_errors=True) +print("\n== Kubernetes API, Grafana, Prometheus and NS consistency ==\n") + + +class _KubeHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + docs = { + "/version": b'{"major":"1","gitVersion":"v1.30.0"}', + "/api": b'{"kind":"APIVersions"}', + "/apis": b'{"kind":"APIGroupList"}', + "/healthz": b"ok", + } + body = docs.get(path, b"not found") + code = 200 if path in docs else 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 _KubeAuthHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = b"unauthorized" + self.send_response(401) + self.send_header("WWW-Authenticate", "Bearer") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +kube_srv = http.server.HTTPServer(("127.0.0.1", 0), _KubeHandler) +kube_port = kube_srv.server_address[1] +threading.Thread(target=kube_srv.serve_forever, daemon=True).start() +kube_auth_srv = http.server.HTTPServer(("127.0.0.1", 0), _KubeAuthHandler) +kube_auth_port = kube_auth_srv.server_address[1] +threading.Thread(target=kube_auth_srv.serve_forever, daemon=True).start() + +gf_root = tempfile.mkdtemp(prefix="apex-gf-") +os.makedirs(os.path.join(gf_root, "etc", "grafana")) +gf_bad = os.path.join(gf_root, "etc", "grafana", "grafana.ini") +with open(gf_bad, "w") as f: + f.write("[server]\nprotocol = http\n") + f.write("[security]\nadmin_user = admin\nadmin_password = admin\n") + f.write("secret_key = SW2YcwTIb9zpOOhoPsMm\n") + f.write("[auth.anonymous]\nenabled = true\n") +os.chmod(gf_bad, 0o666) +gf_good_root = tempfile.mkdtemp(prefix="apex-gfg-") +os.makedirs(os.path.join(gf_good_root, "etc", "grafana")) +with open(os.path.join(gf_good_root, "etc", "grafana", "grafana.ini"), + "w") as f: + f.write("[server]\nprotocol = https\n") + f.write("[security]\nadmin_user = ops\nadmin_password = strong-pass\n") + f.write("secret_key = a-very-long-random-secret\n") + f.write("[auth.anonymous]\nenabled = false\n") + +pr_root = tempfile.mkdtemp(prefix="apex-pr-") +os.makedirs(os.path.join(pr_root, "etc", "prometheus")) +pr_bad = os.path.join(pr_root, "etc", "prometheus", "prometheus.yml") +with open(pr_bad, "w") as f: + f.write("global:\n scrape_interval: 15s\n") + f.write("scrape_configs:\n - job_name: web\n") + f.write(" static_configs:\n") + f.write(' - targets: ["http://10.0.0.5:9100"]\n') +os.chmod(pr_bad, 0o666) +with open(os.path.join(pr_root, "etc", "prometheus", "web.yml"), "w") as f: + f.write("tls_server_config:\n cert_file: srv.pem\n key_file: srv.key\n") +pr_good_root = tempfile.mkdtemp(prefix="apex-prg-") +os.makedirs(os.path.join(pr_good_root, "etc", "prometheus")) +with open(os.path.join(pr_good_root, "etc", "prometheus", + "prometheus.yml"), "w") as f: + f.write("global:\n external_labels:\n cluster: test\n") + f.write("scrape_configs:\n - job_name: web\n") + f.write(" static_configs:\n") + f.write(' - targets: ["https://10.0.0.5:9100"]\n') +with open(os.path.join(pr_good_root, "etc", "prometheus", "web.yml"), + "w") as f: + f.write("basic_auth_users:\n admin: $2y$10$abcdef\n") + + +def ns_agent(ns_for): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind((ns_for[0], ns_for[1])) + sock.settimeout(0.2) + stop = threading.Event() + + def rr(name, rtype, rdata): + return (dns_name_encode(name) + + struct.pack(">HHIH", rtype, 1, 300, len(rdata)) + rdata) + + def loop(): + while not stop.is_set(): + try: + data, addr = sock.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + if len(data) < 12: + continue + tid = data[:2] + qname, off = dns_name_decode(data, 12) + if off + 4 > len(data): + continue + qtype = struct.unpack(">H", data[off:off + 2])[0] + question = data[12:off + 4] + answers = [] + for name, rtype, value in ns_for[2]: + if name == qname and rtype == qtype: + if rtype == 2: + answers.append(rr(value, 2, dns_name_encode(value))) + elif rtype == 1: + answers.append(rr(value, 1, + socket.inet_aton(value))) + resp = (tid + struct.pack(">HHHHH", 0x8400, 1, len(answers), 0, 0) + + question + b"".join(answers)) + sock.sendto(resp, addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, stop + + +ns_port = 0 +probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) +probe.bind(("127.0.0.2", 0)) +ns_port = probe.getsockname()[1] +probe.close() + +parent_sock, parent_stop = ns_agent(("127.0.0.1", ns_port, [ + ("good.test", 2, "ns1.good.test"), + ("good.test", 2, "ns2.good.test"), + ("split.test", 2, "ns1.split.test"), + ("split.test", 2, "ns2.split.test"), + ("ns1.good.test", 1, "127.0.0.1"), + ("ns1.split.test", 1, "127.0.0.2"), +])) +auth_sock, auth_stop = ns_agent(("127.0.0.2", ns_port, [ + ("good.test", 2, "ns1.good.test"), + ("good.test", 2, "ns2.good.test"), + ("split.test", 2, "ns1.split.test"), +])) + +cfg11_home = tempfile.mkdtemp(prefix="apex-cfg11-home-") +write_scope(cfg11_home, {"label": "cfg11", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, + "allow_ip": ["127.0.0.1", "127.0.0.2"], + "allow_domain": ["good.test", "split.test"], + "allow_port": [str(kube_port), str(kube_auth_port), + str(ns_port)]}) +res, _ = run([ + call(1, "kubernetes_api_probe", target="127.0.0.1", port=kube_port, + tls=False), + call(2, "kubernetes_api_probe", target="127.0.0.1", + port=kube_auth_port, tls=False), + call(3, "grafana_audit", root=gf_root), + call(4, "grafana_audit", root=gf_good_root), + call(5, "prometheus_audit", root=pr_root), + call(6, "prometheus_audit", root=pr_good_root), + call(7, "dns_ns_consistency", domain="good.test", resolver="127.0.0.1", + port=ns_port), + call(8, "dns_ns_consistency", domain="split.test", resolver="127.0.0.1", + port=ns_port), + call(9, "kubernetes_api_probe", target="198.51.100.9", port=6443), + call(10, "grafana_audit", root="/nonexistent-gf"), + call(11, "prometheus_audit", root="/nonexistent-pr"), + call(12, "dns_ns_consistency", domain="evil.test"), +], home=cfg11_home) +by_id = {r.get("id"): r for r in res} +kube = json.loads(text(by_id[1])) +kube_paths = {e["path"]: e for e in kube["endpoints"]} +check("kubernetes_api_probe finds the open API", + kube["open_count"] == 4 and kube["tested"] == 4 and + kube_paths["/version"]["open"] is True and + kube_paths["/version"]["json"] is True and + kube_paths["/healthz"]["open"] is True, kube) +check("kubernetes_api_probe saves evidence", + any(e["evidence"] and os.path.isfile(e["evidence"]) + for e in kube["endpoints"]), kube["endpoints"]) +kube_auth = json.loads(text(by_id[2])) +check("kubernetes_api_probe reports a protected API", + kube_auth["open_count"] == 0 and + all(e["status"] == 401 for e in kube_auth["endpoints"]), kube_auth) +gf = json.loads(text(by_id[3])) +gf_kinds = {f["id"] for f in gf["findings"]} +check("grafana_audit flags anonymous, admin, http and secret", + {"world-writable", "anonymous-enabled", "default-admin", "http", + "default-secret"} <= gf_kinds, gf) +gf_good = json.loads(text(by_id[4])) +check("grafana_audit accepts a hardened config", + gf_good["findings_count"] == 0 and gf_good["anonymous"] is False, + gf_good) +pr = json.loads(text(by_id[5])) +pr_kinds = {f["id"] for f in pr["findings"]} +check("prometheus_audit flags auth, labels and http targets", + {"world-writable", "no-auth", "no-external-labels", "http-target"} <= + pr_kinds, pr) +pr_good = json.loads(text(by_id[6])) +check("prometheus_audit accepts a hardened config", + pr_good["findings_count"] == 0 and pr_good["basic_auth"] is True and + pr_good["external_labels"] is True, pr_good) +ns_good = json.loads(text(by_id[7])) +check("dns_ns_consistency accepts matching NS sets", + ns_good["consistent"] is True and len(ns_good["parent"]) == 2 and + len(ns_good["authoritative"]) == 2 and not ns_good["missing"], ns_good) +ns_split = json.loads(text(by_id[8])) +check("dns_ns_consistency reports the stale NS", + ns_split["consistent"] is False and + ns_split["missing"] == ["ns2.split.test"] and + ns_split["authoritative_server"] == "127.0.0.2", ns_split) +check("kubernetes_api_probe refuses an out-of-scope target", err(by_id[9]), + text(by_id[9])) +check("grafana_audit reports a missing config", err(by_id[10]), + text(by_id[10])) +check("prometheus_audit reports a missing config", err(by_id[11]), + text(by_id[11])) +check("dns_ns_consistency refuses an out-of-scope domain", err(by_id[12]), + text(by_id[12])) +kube_srv.shutdown() +kube_srv.server_close() +kube_auth_srv.shutdown() +kube_auth_srv.server_close() +parent_stop.set() +parent_sock.close() +auth_stop.set() +auth_sock.close() +shutil.rmtree(gf_root, ignore_errors=True) +shutil.rmtree(gf_good_root, ignore_errors=True) +shutil.rmtree(pr_root, ignore_errors=True) +shutil.rmtree(pr_good_root, ignore_errors=True) +shutil.rmtree(cfg11_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"})