diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bb09bf..06e587a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,24 @@ 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.42.0 — 2026-11-22 — this change +## 1.43.0 — 2026-11-23 — this change + +- **pg_hba** (`pg_hba_audit`): every `/etc/postgresql//main`, plus + the flat paths: a `trust` method, a rule matching `0.0.0.0/0` or `::/0` and + a world-writable file. +- **polkit** (`polkit_audit`): `rules.d/*.rules` and + `localauthority/50-local.d/*.pkla`: `polkit.Result.YES`, `ResultAny=yes` or + `ResultInactive=yes` and world-writable files. +- **LDAP client** (`ldap_client_audit`): `ldap.conf` from Debian and + OpenLDAP: a plaintext `ldap://` URI, `TLS_REQCERT never`/`allow` and a + world-writable file. +- **FCrDNS** (`dns_fcrdns_check`): a PTR lookup followed by A/AAAA of the PTR + name; a missing PTR or a forward answer that never returns the address + fails forward-confirmed reverse DNS. +- Tests with pg_hba/polkit/ldap.conf trees and a DNS agent answering matching, + mismatching and absent PTR records. 970 checks. Coverage 82.7%. + +## 1.42.0 — 2026-11-22 — a194ace - **Chrony** (`chrony_config_audit`): both chrony.conf paths: `allow` with `0.0.0.0/0`, `::/0` or `all`, a `cmdallow`/`bindcmdaddress` that leaves diff --git a/README.md b/README.md index 30dedac..81af208 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. -**206 tools · 956 end-to-end checks · 340 fuzz cases · 82.6% line coverage · ~780 KiB** +**210 tools · 970 end-to-end checks · 340 fuzz cases · 82.7% line coverage · ~788 KiB** ``` $ ./apex-twin --check -{"version":"1.42.0","tools":206,...,"scope":{"loaded":true,...}} +{"version":"1.43.0","tools":210,...,"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 (206) +## Tools (210) ### Scope and bookkeeping @@ -271,6 +271,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `http_methods` | OPTIONS Allow list and TRACE echo detection; names PUT/DELETE but never sends them | | `websocket_probe` | Upgrade handshake: 101, Upgrade/Connection and Sec-WebSocket-Accept | | `websocket_origin_check` | Two unrelated Origins; both 101 means Origin is not enforced (CSWSH) | +| `dns_fcrdns_check` | PTR then A/AAAA; a forward answer without the address fails FCrDNS | | `ike_probe` | IKEv2 SA_INIT (AES-CBC-128/HMAC-SHA2-256/DH14); version, exchange, notify, responder SPI | | `snmp_walk` | GETNEXT over the system group: OID, name and decoded value (string, integer, timeticks, OID) | | `ldap_search` | Anonymous subtree search (size limit 20) from namingContexts; DNs plus cn/uid/mail | @@ -403,6 +404,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `chrony_config_audit` | chrony.conf: allow all, open command port, world-writable | | `apt_config_audit` | apt.conf.d/sources: unsigned, insecure, trusted=yes, plain HTTP | | `login_defs_audit` | login.defs: aging, PASS_MIN_DAYS 0, loose UMASK, DES/MD5 | +| `pg_hba_audit` | pg_hba.conf: `trust`, `0.0.0.0/0`, world-writable | +| `polkit_audit` | rules.d/pkla: `polkit.Result.YES`, `ResultAny=yes` | +| `ldap_client_audit` | ldap.conf: plaintext `ldap://` URI, `TLS_REQCERT never` | ### ESP32 @@ -674,6 +678,8 @@ The full threat model, trust boundaries and a hardening checklist are in | redirect chain | up to five GETs, every hop re-gated | | chrony/apt/login.defs | config reads only; optional root prefix | | WebSocket origin | two upgrade handshakes, no data frames | +| pg_hba/polkit/ldap client | config reads only; optional root prefix | +| FCrDNS | one PTR and up to four forward queries | | USB audit | 200 devices, sysfs reads only | --- @@ -685,7 +691,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 956 end-to-end checks +make test # version check + gate audit + 970 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 @@ -806,7 +812,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, sni_vhost_check, tls_client_auth_probe, kubernetes_api_probe, dns_ns_consistency, dns_dangling_cname, http_redirect_audit, - websocket_origin_check + websocket_origin_check, dns_fcrdns_check 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, @@ -849,7 +855,7 @@ examples/ scope.json ## Status -1.42.0. Built and run: 206 tools, 956 checks, 340 fuzz cases and 82.6% line +1.43.0. Built and run: 210 tools, 970 checks, 340 fuzz cases and 82.7% 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 94b286d..901c41b 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.42.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.43.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,8 @@ 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. +- **pg_hba, polkit and LDAP client audits read local configuration.** The + FCrDNS check performs a PTR lookup and then forward A/AAAA lookups. - **Chrony, APT and login.defs audits read local configuration.** The WebSocket origin check performs two upgrade handshakes and opens no data frames. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 3c78799..ecd5c05 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.42.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.43.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -45,7 +45,7 @@ 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_dangling_cname, http_redirect_audit, -websocket_origin_check), +websocket_origin_check, dns_fcrdns_check), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -64,7 +64,8 @@ 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, wireguard_config_audit, ipsec_config_audit, openldap_config_audit, cron_audit, fail2ban_audit, chrony_config_audit, -apt_config_audit, login_defs_audit) +apt_config_audit, login_defs_audit, pg_hba_audit, polkit_audit, +ldap_client_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). diff --git a/src/apex.h b/src/apex.h index 57522eb..603dc3f 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.42.0" +#define APEX_VERSION "1.43.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 4138aea..50e2817 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -12097,6 +12097,317 @@ static void t_login_defs_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- pg_hba_audit */ + +/* Does the line contain word as a whole token? */ +static int line_has_token(const char *line, const char *word) +{ + char copy[1024]; + char *save = NULL; + char *tok; + size_t wl = strlen(word); + + snprintf(copy, sizeof(copy), "%.1000s", line); + tok = strtok_r(copy, " \t", &save); + while (tok != NULL) { + if (strlen(tok) == wl && strcasecmp(tok, word) == 0) + return 1; + tok = strtok_r(NULL, " \t", &save); + } + return 0; +} + +static void hba_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *files, int *trust, + int *any_host) +{ + static char text[65536]; + struct stat st; + char *copy; + char *save = NULL; + char *line; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + (*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)++; + } + copy = strdup(text); + if (copy == NULL) + return; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && *s != '\0') { + if (line_has_token(s, "trust")) + *trust = 1; + if (line_has_token(s, "0.0.0.0/0") || + line_has_token(s, "::/0")) + *any_host = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); +} + +static void t_pg_hba_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int trust = 0; + int any_host = 0; + DIR *d; + + (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/postgresql/pg_hba.conf", root); + hba_scan_file(&findings, &first, &count, path, &files, &trust, + &any_host); + snprintf(path, sizeof(path), "%s/etc/pg_hba.conf", root); + hba_scan_file(&findings, &first, &count, path, &files, &trust, + &any_host); + snprintf(path, sizeof(path), "%s/etc/postgresql", root); + d = opendir(path); + if (d != NULL) { + struct dirent *ent; + + while ((ent = readdir(d)) != NULL) { + char full[1200]; + + if (ent->d_name[0] == '.') + continue; + snprintf(full, sizeof(full), "%.900s/%.150s/main/" + "pg_hba.conf", path, ent->d_name); + hba_scan_file(&findings, &first, &count, full, &files, + &trust, &any_host); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a pg_hba.conf"); + return; + } + if (trust) { + add_finding(&findings, &first, "trust-auth", "high", + "a pg_hba rule accepts a client without a password"); + count++; + } + if (any_host) { + add_finding(&findings, &first, "any-host", "medium", + "a pg_hba rule matches every address"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"trust\":%s,\"any_host\":%s," + "\"findings_count\":%d,\"findings\":[", + files, trust ? "true" : "false", + any_host ? "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); +} + +/* --------------------------------------------------------------- polkit_audit */ + +static void polkit_scan_dir(mcp_buf *findings, int *first, int *count, + const char *dirpath, const char *suffix, + int *files, int *allow_rules, int *pkla_allow) +{ + DIR *d = opendir(dirpath); + struct dirent *ent; + size_t sl = strlen(suffix); + + if (d == NULL) + return; + while ((ent = readdir(d)) != NULL) { + static char text[65536]; + char full[1200]; + struct stat st; + size_t nl = strlen(ent->d_name); + + if (ent->d_name[0] == '.') + continue; + if (nl <= sl || strcmp(ent->d_name + nl - sl, suffix) != 0) + continue; + snprintf(full, sizeof(full), "%.900s/%.200s", dirpath, + ent->d_name); + if (stat(full, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + if (read_text(full, text, sizeof(text)) <= 0) + continue; + (*files)++; + if ((st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", full); + (*count)++; + } + if (strcmp(suffix, ".rules") == 0 && + strstr(text, "polkit.Result.YES") != NULL) { + (*allow_rules)++; + add_finding(findings, first, "allow-rule", "medium", + "%s returns polkit.Result.YES", full); + (*count)++; + } + if (strcmp(suffix, ".pkla") == 0 && + (strstr(text, "ResultAny=yes") != NULL || + strstr(text, "ResultInactive=yes") != NULL)) { + (*pkla_allow)++; + add_finding(findings, first, "pkla-allow", "medium", + "%s grants the action to any subject", full); + (*count)++; + } + } + closedir(d); +} + +static void t_polkit_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int allow_rules = 0; + int pkla_allow = 0; + + (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/polkit-1/rules.d", root); + polkit_scan_dir(&findings, &first, &count, path, ".rules", &files, + &allow_rules, &pkla_allow); + snprintf(path, sizeof(path), + "%s/etc/polkit-1/localauthority/50-local.d", root); + polkit_scan_dir(&findings, &first, &count, path, ".pkla", &files, + &allow_rules, &pkla_allow); + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a polkit rule"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"allow_rules\":%d," + "\"pkla_allow\":%d,\"findings_count\":%d," + "\"findings\":[", + files, allow_rules, pkla_allow, 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); +} + +/* ---------------------------------------------------------- ldap_client_audit */ + +static void t_ldap_client_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *files[] = { "/etc/ldap/ldap.conf", + "/etc/openldap/ldap.conf", NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char value[512]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + int plaintext = 0; + int no_check = 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, "URI", value, sizeof(value)) && + strstr(value, "ldap://") != NULL) + plaintext = 1; + if (conf_value(text, "TLS_REQCERT", value, sizeof(value)) && + (strcasecmp(value, "never") == 0 || + strcasecmp(value, "allow") == 0)) + no_check = 1; + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read an LDAP client configuration"); + return; + } + if (plaintext) { + add_finding(&findings, &first, "plaintext-uri", "high", + "the directory URI is not ldaps://"); + count++; + } + if (no_check) { + add_finding(&findings, &first, "no-cert-check", "high", + "TLS_REQCERT does not verify the server"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"plaintext_uri\":%s," + "\"no_cert_check\":%s,\"findings_count\":%d," + "\"findings\":[", + files_read, plaintext ? "true" : "false", + no_check ? "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, " @@ -12756,6 +13067,27 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_login_defs_audit }, + { "pg_hba_audit", + "Parse pg_hba.conf from /etc/postgresql//main and the flat " + "paths (root prefix): a trust method and an every-address rule, plus a " + "world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_pg_hba_audit }, + { "polkit_audit", + "Parse polkit rules.d/*.rules and localauthority/50-local.d/*.pkla (root " + "prefix): polkit.Result.YES rules, ResultAny/ResultInactive yes and " + "world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_polkit_audit }, + { "ldap_client_audit", + "Parse ldap.conf (root prefix, Debian and OpenLDAP paths): a plaintext " + "ldap:// URI, TLS_REQCERT never or allow, and a world-writable file. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_ldap_client_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 9eb8758..9765e97 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -6177,6 +6177,164 @@ static void t_websocket_origin_check(mcp_conn *c, const mcp_json *args, mcp_buf_free(&b); } +/* ------------------------------------------------------------- dns_fcrdns_check */ + +static char *dig_ptr(const char *resolver, int port, const char *ip) +{ + 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++] = "-x"; + argv[i++] = (char *)ip; + 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 int same_address(const char *a, const char *b) +{ + unsigned char ra[16]; + unsigned char rb[16]; + + if (inet_pton(AF_INET, a, ra) == 1 && inet_pton(AF_INET, b, rb) == 1) + return memcmp(ra, rb, 4) == 0; + if (inet_pton(AF_INET6, a, ra) == 1 && + inet_pton(AF_INET6, b, rb) == 1) + return memcmp(ra, rb, 16) == 0; + return 0; +} + +static void t_dns_fcrdns_check(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *ip = mcp_arg_string(args, "ip"); + const char *resolver = mcp_arg_string(args, "resolver"); + int port = mcp_arg_int(args, "port", 0); + char reason[512]; + unsigned char raw[16]; + char names[4][128]; + char fwd[12][64]; + int nptr = 0; + int nfwd = 0; + int matched = 0; + int i; + char *out; + mcp_buf b; + int first = 1; + + (void)user; + if (ip == NULL || *ip == '\0') { + mcp_reply_error(c, "ip is required"); + return; + } + if (inet_pton(AF_INET, ip, raw) != 1 && + inet_pton(AF_INET6, ip, raw) != 1) { + mcp_reply_error(c, "ip must be an IPv4 or IPv6 address"); + return; + } + if (port < 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!apex_have("dig")) { + mcp_reply_error(c, "dig is not installed on this host"); + return; + } + if (!apex_scope_check(ip, 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_fcrdns_check", ip, 0, 1, "PTR and forward lookup", + "dig -x"); + out = dig_ptr(resolver, port, ip); + nptr = ns_lines(out, names, 4); + free(out); + for (i = 0; i < nptr; i++) { + char tmp[8][128]; + int n; + int j; + + out = ns_run(resolver, port, names[i], "A"); + n = ns_lines(out, tmp, 8); + free(out); + for (j = 0; j < n && nfwd < 12; j++) { + snprintf(fwd[nfwd++], 64, "%.60s", tmp[j]); + if (same_address(tmp[j], ip)) + matched = 1; + } + out = ns_run(resolver, port, names[i], "AAAA"); + n = ns_lines(out, tmp, 8); + free(out); + for (j = 0; j < n && nfwd < 12; j++) { + snprintf(fwd[nfwd++], 64, "%.60s", tmp[j]); + if (same_address(tmp[j], ip)) + matched = 1; + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"ip\":"); + apex_json_str(&b, ip); + mcp_buf_puts(&b, ",\"resolver\":"); + apex_json_str(&b, resolver != NULL ? resolver : ""); + mcp_buf_puts(&b, ",\"ptr\":["); + for (i = 0; i < nptr; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, names[i]); + } + mcp_buf_puts(&b, "],\"forward\":["); + first = 1; + for (i = 0; i < nfwd; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, fwd[i]); + } + mcp_buf_printf(&b, "],\"forward_confirmed\":%s}", + matched ? "true" : "false"); + apex_audit("dns_fcrdns_check", ip, 0, matched, + nptr == 0 ? "no PTR record for the address" + : matched + ? "the PTR name resolves back to the address" + : "the PTR name does not resolve back to the " + "address", + nptr > 0 ? names[0] : ""); + 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: " @@ -6465,6 +6623,17 @@ const mcp_tool TOOLS_RED[] = { "\"second_origin\":{\"type\":\"string\"}}," "\"required\":[\"target\"]}", t_websocket_origin_check }, + { "dns_fcrdns_check", + "Resolve the PTR record of an address with dig -x, then resolve the PTR " + "name back over A and AAAA. A missing PTR or a forward answer that never " + "returns the address means forward-confirmed reverse DNS fails. Gate: " + "the address (and resolver).", + "{\"type\":\"object\",\"properties\":{" + "\"ip\":{\"type\":\"string\"}," + "\"resolver\":{\"type\":\"string\",\"description\":\"optional DNS server\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default 0\"}}," + "\"required\":[\"ip\"]}", + t_dns_fcrdns_check }, { "openapi_discovery", "Request the usual OpenAPI/Swagger locations and report every document " "that comes back (version, info title, number of paths) with the body as " diff --git a/tests/gate_audit.py b/tests/gate_audit.py index ee1f9e6..4528180 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 = 206 +EXPECTED_TOOLS = 210 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 7031a8f..7e87253 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("206 tools registered", len(tools) == 206, len(tools)) +check("210 tools registered", len(tools) == 210, 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"]) == 206) + check("http tools/list", len(listing["result"]["tools"]) == 210) 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 @@ -9491,10 +9491,211 @@ shutil.rmtree(ld_root, ignore_errors=True) shutil.rmtree(ld_good_root, ignore_errors=True) shutil.rmtree(cfg14_home, ignore_errors=True) +print("\n== pg_hba, polkit, LDAP clients and FCrDNS ==\n") + +hba_root = tempfile.mkdtemp(prefix="apex-hba-") +os.makedirs(os.path.join(hba_root, "etc", "postgresql", "16", "main")) +hba_bad = os.path.join(hba_root, "etc", "postgresql", "16", "main", + "pg_hba.conf") +with open(hba_bad, "w") as f: + f.write("local all all peer\n") + f.write("host all all 0.0.0.0/0 trust\n") +os.chmod(hba_bad, 0o666) +hba_good_root = tempfile.mkdtemp(prefix="apex-hbag-") +os.makedirs(os.path.join(hba_good_root, "etc", "postgresql", "16", "main")) +with open(os.path.join(hba_good_root, "etc", "postgresql", "16", "main", + "pg_hba.conf"), "w") as f: + f.write("local all all peer\n") + f.write("host all all 10.0.0.0/8 " + "scram-sha-256\n") + +pk_root = tempfile.mkdtemp(prefix="apex-pk-") +os.makedirs(os.path.join(pk_root, "etc", "polkit-1", "rules.d")) +os.makedirs(os.path.join(pk_root, "etc", "polkit-1", "localauthority", + "50-local.d")) +pk_rules = os.path.join(pk_root, "etc", "polkit-1", "rules.d", "50-allow.rules") +with open(pk_rules, "w") as f: + f.write("polkit.addRule(function(action, subject) {\n") + f.write(' if (action.id == "org.freedesktop.systemd1.manage-units") {\n') + f.write(" return polkit.Result.YES;\n }\n});\n") +os.chmod(pk_rules, 0o666) +with open(os.path.join(pk_root, "etc", "polkit-1", "localauthority", + "50-local.d", "50-allow.pkla"), "w") as f: + f.write("[Allow units]\nIdentity=unix-group:users\n") + f.write("Action=org.freedesktop.systemd1.manage-units\n") + f.write("ResultAny=yes\n") +pk_good_root = tempfile.mkdtemp(prefix="apex-pkg-") +os.makedirs(os.path.join(pk_good_root, "etc", "polkit-1", "rules.d")) +os.makedirs(os.path.join(pk_good_root, "etc", "polkit-1", "localauthority", + "50-local.d")) +with open(os.path.join(pk_good_root, "etc", "polkit-1", "rules.d", + "50-admin.rules"), "w") as f: + f.write("polkit.addRule(function(action, subject) {\n") + f.write(" return polkit.Result.AUTH_ADMIN;\n});\n") +with open(os.path.join(pk_good_root, "etc", "polkit-1", "localauthority", + "50-local.d", "50-admin.pkla"), "w") as f: + f.write("[Admin]\nIdentity=unix-group:admin\n") + f.write("Action=org.freedesktop.systemd1.manage-units\n") + f.write("ResultAny=no\n") + +lc_root = tempfile.mkdtemp(prefix="apex-lc-") +os.makedirs(os.path.join(lc_root, "etc", "ldap")) +lc_bad = os.path.join(lc_root, "etc", "ldap", "ldap.conf") +with open(lc_bad, "w") as f: + f.write("URI ldap://ldap.example.test\n") + f.write("BASE dc=example,dc=test\n") + f.write("TLS_REQCERT never\n") +os.chmod(lc_bad, 0o666) +lc_good_root = tempfile.mkdtemp(prefix="apex-lcg-") +os.makedirs(os.path.join(lc_good_root, "etc", "ldap")) +with open(os.path.join(lc_good_root, "etc", "ldap", "ldap.conf"), "w") as f: + f.write("URI ldaps://ldap.example.test\n") + f.write("BASE dc=example,dc=test\n") + f.write("TLS_REQCERT demand\n") + + +def dns_record_agent(records): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("127.0.0.1", 0)) + sock.settimeout(0.2) + port = sock.getsockname()[1] + stop = threading.Event() + + def loop(): + while not stop.is_set(): + try: + data, addr = sock.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + if len(data) < 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 = [] + if key in records: + value, kind = records[key] + rdata = (dns_name_encode(value) if kind == "name" + else socket.inet_aton(value)) + answers.append(b"\xc0\x0c" + + struct.pack(">HHIH", qtype, 1, 300, + len(rdata)) + rdata) + known = any(k[0] == name.lower() for k in records) + 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 + + +fcr_sock, fcr_port, fcr_stop = dns_record_agent({ + ("1.0.0.127.in-addr.arpa", 12): ("host.good.test", "name"), + ("host.good.test", 1): ("127.0.0.1", "addr"), + ("2.0.0.127.in-addr.arpa", 12): ("host.bad.test", "name"), + ("host.bad.test", 1): ("127.0.0.9", "addr"), +}) + +cfg15_home = tempfile.mkdtemp(prefix="apex-cfg15-home-") +write_scope(cfg15_home, {"label": "cfg15", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, + "allow_ip": ["127.0.0.1", "127.0.0.2", "127.0.0.3"], + "allow_port": [str(fcr_port)]}) +res, _ = run([ + call(1, "pg_hba_audit", root=hba_root), + call(2, "pg_hba_audit", root=hba_good_root), + call(3, "polkit_audit", root=pk_root), + call(4, "polkit_audit", root=pk_good_root), + call(5, "ldap_client_audit", root=lc_root), + call(6, "ldap_client_audit", root=lc_good_root), + call(7, "dns_fcrdns_check", ip="127.0.0.1", resolver="127.0.0.1", + port=fcr_port), + call(8, "dns_fcrdns_check", ip="127.0.0.2", resolver="127.0.0.1", + port=fcr_port), + call(9, "dns_fcrdns_check", ip="127.0.0.3", resolver="127.0.0.1", + port=fcr_port), + call(10, "pg_hba_audit", root="/nonexistent-hba"), + call(11, "polkit_audit", root="/nonexistent-pk"), + call(12, "ldap_client_audit", root="/nonexistent-lc"), + call(13, "dns_fcrdns_check", ip="198.51.100.9"), + call(14, "dns_fcrdns_check", ip="not-an-address"), +], home=cfg15_home) +by_id = {r.get("id"): r for r in res} +hba = json.loads(text(by_id[1])) +hba_kinds = {f["id"] for f in hba["findings"]} +check("pg_hba_audit flags trust and an every-address rule", + {"world-writable", "trust-auth", "any-host"} <= hba_kinds and + hba["trust"] is True and hba["any_host"] is True, hba) +hba_good = json.loads(text(by_id[2])) +check("pg_hba_audit accepts peer and a scoped host rule", + hba_good["findings_count"] == 0 and hba_good["trust"] is False and + hba_good["any_host"] is False, hba_good) +pk = json.loads(text(by_id[3])) +pk_kinds = {f["id"] for f in pk["findings"]} +check("polkit_audit flags YES rules and pkla grants", + {"world-writable", "allow-rule", "pkla-allow"} <= pk_kinds and + pk["allow_rules"] == 1 and pk["pkla_allow"] == 1, pk) +pk_good = json.loads(text(by_id[4])) +check("polkit_audit accepts admin-authenticated rules", + pk_good["findings_count"] == 0 and pk_good["allow_rules"] == 0 and + pk_good["pkla_allow"] == 0, pk_good) +lc = json.loads(text(by_id[5])) +lc_kinds = {f["id"] for f in lc["findings"]} +check("ldap_client_audit flags plaintext URI and no cert check", + {"world-writable", "plaintext-uri", "no-cert-check"} <= lc_kinds and + lc["plaintext_uri"] is True and lc["no_cert_check"] is True, lc) +lc_good = json.loads(text(by_id[6])) +check("ldap_client_audit accepts ldaps and a strict check", + lc_good["findings_count"] == 0 and + lc_good["plaintext_uri"] is False and + lc_good["no_cert_check"] is False, lc_good) +fcr_good = json.loads(text(by_id[7])) +check("dns_fcrdns_check confirms a matching PTR", + fcr_good["forward_confirmed"] is True and + fcr_good["ptr"] == ["host.good.test"] and + "127.0.0.1" in fcr_good["forward"], fcr_good) +fcr_bad = json.loads(text(by_id[8])) +check("dns_fcrdns_check flags a forward mismatch", + fcr_bad["forward_confirmed"] is False and + fcr_bad["ptr"] == ["host.bad.test"] and + "127.0.0.9" in fcr_bad["forward"], fcr_bad) +fcr_none = json.loads(text(by_id[9])) +check("dns_fcrdns_check reports a missing PTR", + fcr_none["forward_confirmed"] is False and fcr_none["ptr"] == [], + fcr_none) +check("pg_hba_audit reports a missing config", err(by_id[10]), + text(by_id[10])) +check("polkit_audit reports missing rules", err(by_id[11]), + text(by_id[11])) +check("ldap_client_audit reports a missing config", err(by_id[12]), + text(by_id[12])) +check("dns_fcrdns_check refuses an out-of-scope address", err(by_id[13]), + text(by_id[13])) +check("dns_fcrdns_check rejects a malformed address", err(by_id[14]), + text(by_id[14])) +fcr_stop.set() +fcr_sock.close() +shutil.rmtree(hba_root, ignore_errors=True) +shutil.rmtree(hba_good_root, ignore_errors=True) +shutil.rmtree(pk_root, ignore_errors=True) +shutil.rmtree(pk_good_root, ignore_errors=True) +shutil.rmtree(lc_root, ignore_errors=True) +shutil.rmtree(lc_good_root, ignore_errors=True) +shutil.rmtree(cfg15_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()