diff --git a/CHANGELOG.md b/CHANGELOG.md index 06e587a..77ffb32 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.43.0 — 2026-11-23 — this change +## 1.44.0 — 2026-11-23 — this change + +- **Certificates** (`ssl_cert_audit`): every certificate under + `/etc/ssl/certs` (root prefix) through `openssl x509`: expired or not yet + valid, SHA-1 signatures, RSA below 2048 or EC below 256 bits, a non-critical + `CA:TRUE` and world-writable files. Bundles and unparsable files are + counted as skipped. +- **timesyncd** (`timesyncd_audit`): `timesyncd.conf`: no NTP or fallback + server, a public fallback pool, `RootDistanceMaxSec` above five and poll + intervals outside 16..2048 seconds. +- **resolv.conf** (`resolv_conf_audit`): no nameserver, a single nameserver, + a well-known public resolver, a missing search domain and a world-writable + file. +- **SOA MNAME** (`dns_soa_mname_check`): the SOA primary must be one of the + zone's NS records; a stray primary means the delegation is misconfigured. +- Tests with five generated certificates (expired, SHA-1, RSA-1024, + non-critical CA, good), timesyncd/resolv.conf trees and a DNS agent with + delegated and stray SOA primaries. 983 checks. Coverage 82.8%. + +## 1.43.0 — 2026-11-23 — e5f634b - **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 diff --git a/README.md b/README.md index 81af208..9ae2c14 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. -**210 tools · 970 end-to-end checks · 340 fuzz cases · 82.7% line coverage · ~788 KiB** +**214 tools · 983 end-to-end checks · 340 fuzz cases · 82.8% line coverage · ~805 KiB** ``` $ ./apex-twin --check -{"version":"1.43.0","tools":210,...,"scope":{"loaded":true,...}} +{"version":"1.44.0","tools":214,...,"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 (210) +## Tools (214) ### Scope and bookkeeping @@ -272,6 +272,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `dns_soa_mname_check` | SOA MNAME must be one of the zone's NS records | | `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 | @@ -407,6 +408,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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` | +| `ssl_cert_audit` | /etc/ssl/certs: expired, SHA-1, weak key, non-critical CA | +| `timesyncd_audit` | timesyncd.conf: no servers, public fallback, lax polling | +| `resolv_conf_audit` | resolv.conf: no/single/public nameserver, no search domain | ### ESP32 @@ -680,6 +684,9 @@ The full threat model, trust boundaries and a hardening checklist are in | 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 | +| certificate store | local openssl parse only | +| timesyncd/resolv.conf | config reads only; optional root prefix | +| SOA MNAME | two dig queries | | USB audit | 200 devices, sysfs reads only | --- @@ -691,7 +698,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 970 end-to-end checks +make test # version check + gate audit + 983 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 @@ -812,7 +819,8 @@ 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, dns_fcrdns_check + websocket_origin_check, dns_fcrdns_check, + dns_soa_mname_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, @@ -855,7 +863,7 @@ examples/ scope.json ## Status -1.43.0. Built and run: 210 tools, 970 checks, 340 fuzz cases and 82.7% line +1.44.0. Built and run: 214 tools, 983 checks, 340 fuzz cases and 82.8% 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 901c41b..5f1dec2 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.43.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.44.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. +- **Certificate, timesyncd and resolv.conf audits read local files.** The + certificate audit parses each file with `openssl x509`; no network is used. - **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 diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index ecd5c05..7a8bb6f 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.43.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.44.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, dns_fcrdns_check), +websocket_origin_check, dns_fcrdns_check, dns_soa_mname_check), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -65,7 +65,7 @@ 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, pg_hba_audit, polkit_audit, -ldap_client_audit) +ldap_client_audit, ssl_cert_audit, timesyncd_audit, resolv_conf_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 603dc3f..c460398 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.43.0" +#define APEX_VERSION "1.44.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 50e2817..abca522 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -12408,6 +12408,457 @@ static void t_ldap_client_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- ssl_cert_audit */ + +/* OpenSSL prints "Nov 22 08:00:00 2026 GMT"; strptime is not exposed by + * the project's feature macros, so parse the fields and use timegm. */ +static time_t cert_parse_time(const char *s) +{ + static const char *months[] = { "Jan", "Feb", "Mar", "Apr", "May", + "Jun", "Jul", "Aug", "Sep", "Oct", + "Nov", "Dec" }; + char mon[8]; + int day; + int hh; + int mm; + int ss; + int year; + int i; + struct tm tm; + + if (sscanf(s, " %3s %d %d:%d:%d %d", mon, &day, &hh, &mm, &ss, + &year) != 6) + return (time_t)-1; + for (i = 0; i < 12; i++) + if (strcasecmp(mon, months[i]) == 0) + break; + if (i == 12) + return (time_t)-1; + memset(&tm, 0, sizeof(tm)); + tm.tm_year = year - 1900; + tm.tm_mon = i; + tm.tm_mday = day; + tm.tm_hour = hh; + tm.tm_min = mm; + tm.tm_sec = ss; + return timegm(&tm); +} + +static int cert_line_has_sha1(const char *text) +{ + const char *p = text; + + while ((p = strstr(p, "Signature Algorithm:")) != NULL) { + const char *eol = strchr(p, '\n'); + const char *q = p + 18; + size_t len = eol != NULL ? (size_t)(eol - q) : strlen(q); + char line[128]; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, q, len); + line[len] = '\0'; + if (strcasestr(line, "sha1") != NULL) + return 1; + p = eol != NULL ? eol : q + len; + } + return 0; +} + +static int cert_key_bits(const char *text) +{ + const char *p = strstr(text, "Public-Key: ("); + + if (p == NULL) + return 0; + return atoi(p + 13); +} + +static void cert_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *files, int *skipped) +{ + struct stat st; + char *argv[8]; + apex_proc p; + char *text; + char *nb; + char *na; + time_t now = time(NULL); + int ec; + + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) + return; + if (st.st_size > 32768) { + (*skipped)++; + return; + } + argv[0] = "openssl"; + argv[1] = "x509"; + argv[2] = "-in"; + argv[3] = (char *)path; + argv[4] = "-noout"; + argv[5] = "-text"; + argv[6] = NULL; + if (apex_run(argv, 15000, 256 * 1024, &p) != 0 || p.out == NULL) { + apex_proc_free(&p); + (*skipped)++; + return; + } + text = p.out; + if (strstr(text, "Public-Key: (") == NULL || + strstr(text, "Signature Algorithm:") == NULL) { + apex_proc_free(&p); + (*skipped)++; + return; + } + (*files)++; + if ((st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + ec = strstr(text, "id-ecPublicKey") != NULL; + { + int bits = cert_key_bits(text); + + if (bits > 0 && ((ec && bits < 256) || (!ec && bits < 2048))) { + add_finding(findings, first, "weak-key", "high", + "%s uses a %d-bit %s key", path, bits, + ec ? "EC" : "RSA"); + (*count)++; + } + } + if (cert_line_has_sha1(text)) { + add_finding(findings, first, "sha1-signature", "high", + "%s is signed with SHA-1", path); + (*count)++; + } + if (strstr(text, "CA:TRUE") != NULL && + strstr(text, "X509v3 Basic Constraints: critical") == NULL) { + add_finding(findings, first, "ca-not-critical", "medium", + "%s marks CA:TRUE without a critical constraint", + path); + (*count)++; + } + nb = strstr(text, "Not Before:"); + na = strstr(text, "Not After :"); + if (nb != NULL) { + time_t start = cert_parse_time(nb + 11); + + if (start != (time_t)-1 && start > now) { + add_finding(findings, first, "not-yet-valid", "medium", + "%s is not valid yet", path); + (*count)++; + } + } + if (na != NULL) { + time_t end = cert_parse_time(na + 12); + + if (end != (time_t)-1 && end < now) { + add_finding(findings, first, "expired", "high", + "%s has expired", path); + (*count)++; + } + } + apex_proc_free(&p); +} + +static void t_ssl_cert_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; + int skipped = 0; + DIR *d; + struct dirent *ent; + int seen = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + if (!apex_have("openssl")) { + mcp_reply_error(c, "openssl is not installed on this host"); + return; + } + snprintf(dirpath, sizeof(dirpath), "%s/etc/ssl/certs", root); + d = opendir(dirpath); + if (d == NULL) { + mcp_reply_error(c, "cannot read /etc/ssl/certs"); + return; + } + mcp_buf_init(&findings); + while ((ent = readdir(d)) != NULL && seen < 200) { + char path[1200]; + struct stat st; + + if (ent->d_name[0] == '.') + continue; + snprintf(path, sizeof(path), "%.900s/%.200s", dirpath, + ent->d_name); + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + seen++; + cert_scan_file(&findings, &first, &count, path, &files, + &skipped); + } + closedir(d); + if (files == 0 && skipped == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a certificate"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"skipped\":%d," + "\"findings_count\":%d,\"findings\":[", + files, skipped, 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); +} + +/* ------------------------------------------------------------ timesyncd_audit */ + +static void t_timesyncd_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + static char text[65536]; + char ntp[512]; + char fallback[512]; + char value[64]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int no_servers = 0; + int public_fallback = 0; + int loose_distance = 0; + int weak_poll = 0; + long n; + char *end; + + (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/systemd/timesyncd.conf", root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read timesyncd.conf"); + return; + } + ntp[0] = fallback[0] = '\0'; + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "timesyncd.conf is writable by anyone"); + count++; + } + ini_value(text, "Time", "NTP", ntp, sizeof(ntp)); + ini_value(text, "Time", "FallbackNTP", fallback, sizeof(fallback)); + if (ntp[0] == '\0' && fallback[0] == '\0') { + no_servers = 1; + add_finding(&findings, &first, "no-servers", "high", + "no NTP server is configured"); + count++; + } + if (strcasestr(fallback, "pool.ntp.org") != NULL) { + public_fallback = 1; + add_finding(&findings, &first, "public-fallback", "low", + "the fallback uses a public NTP pool"); + count++; + } + if (ini_value(text, "Time", "RootDistanceMaxSec", value, + sizeof(value))) { + end = NULL; + n = strtol(value, &end, 10); + if (end != value && n > 5) { + loose_distance = 1; + add_finding(&findings, &first, "root-distance", "low", + "RootDistanceMaxSec is %ld seconds", n); + count++; + } + } + if (ini_value(text, "Time", "PollIntervalMinSec", value, + sizeof(value))) { + end = NULL; + n = strtol(value, &end, 10); + if (end != value && n < 16) { + weak_poll = 1; + add_finding(&findings, &first, "weak-poll", "low", + "PollIntervalMinSec is %ld seconds", n); + count++; + } + } + if (ini_value(text, "Time", "PollIntervalMaxSec", value, + sizeof(value))) { + end = NULL; + n = strtol(value, &end, 10); + if (end != value && n > 2048) { + weak_poll = 1; + add_finding(&findings, &first, "weak-poll", "low", + "PollIntervalMaxSec is %ld seconds", n); + count++; + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_puts(&b, ",\"ntp\":"); + apex_json_str(&b, ntp); + mcp_buf_printf(&b, ",\"no_servers\":%s,\"public_fallback\":%s," + "\"loose_root_distance\":%s,\"weak_poll\":%s," + "\"findings_count\":%d,\"findings\":[", + no_servers ? "true" : "false", + public_fallback ? "true" : "false", + loose_distance ? "true" : "false", + weak_poll ? "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); +} + +/* ------------------------------------------------------------- resolv_conf_audit */ + +static int resolv_public(const char *ip) +{ + static const char *publics[] = { + "8.8.8.8", "8.8.4.4", "1.1.1.1", "1.0.0.1", "9.9.9.9", + "149.112.112.112", "208.67.222.222", "208.67.220.220", + "64.6.64.6", "64.6.65.6", "77.88.8.8", "77.88.8.1", NULL + }; + int i; + + for (i = 0; publics[i] != NULL; i++) + if (strcmp(ip, publics[i]) == 0) + return 1; + return 0; +} + +static void t_resolv_conf_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + static char text[65536]; + struct stat st; + char *copy; + char *save = NULL; + char *line; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int nameservers = 0; + int public_ns = 0; + int have_search = 0; + + (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/resolv.conf", root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read resolv.conf"); + return; + } + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "resolv.conf is writable by anyone"); + count++; + } + copy = strdup(text); + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (strncmp(s, "nameserver", 10) == 0 && + (s[10] == ' ' || s[10] == '\t')) { + char ip[128]; + size_t k = 0; + char *v = s + 10; + + while (*v == ' ' || *v == '\t') + v++; + while (v[k] != '\0' && v[k] != ' ' && + v[k] != '\t' && k + 1 < sizeof(ip)) { + ip[k] = v[k]; + k++; + } + ip[k] = '\0'; + if (k > 0) { + nameservers++; + if (resolv_public(ip)) + public_ns = 1; + } + } else if ((strncmp(s, "search", 6) == 0 || + strncmp(s, "domain", 6) == 0) && + (s[6] == ' ' || s[6] == '\t')) { + have_search = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + if (nameservers == 0) { + add_finding(&findings, &first, "no-nameserver", "high", + "no nameserver is configured"); + count++; + } else if (nameservers == 1) { + add_finding(&findings, &first, "single-nameserver", "low", + "only one nameserver is configured"); + count++; + } + if (public_ns) { + add_finding(&findings, &first, "public-resolver", "low", + "a public resolver is used"); + count++; + } + if (!have_search) { + add_finding(&findings, &first, "no-search", "low", + "no search domain is configured"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"nameservers\":%d,\"public_resolver\":%s," + "\"search\":%s,\"findings_count\":%d,\"findings\":[", + nameservers, public_ns ? "true" : "false", + have_search ? "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, " @@ -13088,6 +13539,28 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_ldap_client_audit }, + { "ssl_cert_audit", + "Parse every certificate under /etc/ssl/certs (root prefix) with " + "openssl: expired or not yet valid, SHA-1 signature, RSA below 2048 or " + "EC below 256 bits, a non-critical CA:TRUE and a world-writable file. " + "Bundles and unparsable files are counted as skipped. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_ssl_cert_audit }, + { "timesyncd_audit", + "Parse /etc/systemd/timesyncd.conf (root prefix): no NTP or fallback " + "server, a public fallback pool, RootDistanceMaxSec above five and a " + "poll interval outside 16..2048 seconds. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_timesyncd_audit }, + { "resolv_conf_audit", + "Parse /etc/resolv.conf (root prefix): no nameserver, a single " + "nameserver, a well-known public resolver, a missing search domain and " + "a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_resolv_conf_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 9765e97..cd4c60e 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -6335,6 +6335,112 @@ static void t_dns_fcrdns_check(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* -------------------------------------------------------- dns_soa_mname_check */ + +static void t_dns_soa_mname_check(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 mname[128]; + char names[8][128]; + char *out; + char *copy; + char *save = NULL; + char *tok; + int nns = 0; + int consistent = 0; + 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_have("dig")) { + mcp_reply_error(c, "dig is not installed on this host"); + 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_soa_mname_check", domain, 0, 1, "SOA and NS lookup", + "dig SOA/NS"); + mname[0] = '\0'; + out = ns_run(resolver, port, domain, "SOA"); + if (out != NULL) { + copy = strdup(out); + free(out); + if (copy != NULL) { + tok = strtok_r(copy, " \t\r\n", &save); + if (tok != NULL) { + size_t tl = strlen(tok); + + if (tl > 0 && tok[tl - 1] == '.') + tok[--tl] = '\0'; + snprintf(mname, sizeof(mname), "%.120s", tok); + } + free(copy); + } + } + if (mname[0] == '\0') { + mcp_reply_error(c, "no SOA record for the domain"); + return; + } + out = ns_run(resolver, port, domain, "NS"); + nns = ns_lines(out, names, 8); + free(out); + for (i = 0; i < nns; i++) { + if (strcasecmp(names[i], mname) == 0) + consistent = 1; + } + 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, ",\"mname\":"); + apex_json_str(&b, mname); + mcp_buf_puts(&b, ",\"nameservers\":["); + for (i = 0; i < nns; i++) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, names[i]); + } + mcp_buf_printf(&b, "],\"consistent\":%s}", + consistent ? "true" : "false"); + apex_audit("dns_soa_mname_check", domain, 0, consistent, + nns == 0 + ? "the zone publishes no NS records" + : consistent + ? "the SOA primary is one of the nameservers" + : "the SOA primary is not a nameserver", + mname); + 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: " @@ -6634,6 +6740,16 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default 0\"}}," "\"required\":[\"ip\"]}", t_dns_fcrdns_check }, + { "dns_soa_mname_check", + "Fetch the SOA and the NS set of a domain and check that the SOA MNAME " + "is one of the nameservers. A primary that is not delegated means the " + "zone is misconfigured. 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_soa_mname_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 4528180..ccebcfb 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 = 210 +EXPECTED_TOOLS = 214 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 7e87253..e35afc7 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("210 tools registered", len(tools) == 210, len(tools)) +check("214 tools registered", len(tools) == 214, 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"]) == 210) + check("http tools/list", len(listing["result"]["tools"]) == 214) 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 @@ -9691,11 +9691,209 @@ shutil.rmtree(lc_root, ignore_errors=True) shutil.rmtree(lc_good_root, ignore_errors=True) shutil.rmtree(cfg15_home, ignore_errors=True) +print("\n== certificates, timesyncd, resolv.conf and SOA MNAME ==\n") + +cert_root = tempfile.mkdtemp(prefix="apex-cert-") +cert_dir = os.path.join(cert_root, "etc", "ssl", "certs") +key_dir = os.path.join(cert_root, "keys") +os.makedirs(cert_dir) +os.makedirs(key_dir) +cert_specs = [ + ("expired.pem", ["-newkey", "rsa:2048", + "-not_before", "20200101000000Z", + "-not_after", "20210101000000Z", + "-subj", "/CN=expired.test"]), + ("sha1.pem", ["-newkey", "rsa:2048", "-sha1", "-days", "2", + "-subj", "/CN=sha1.test"]), + ("weak.pem", ["-newkey", "rsa:1024", "-days", "2", + "-subj", "/CN=weak.test"]), + ("canotcrit.pem", ["-newkey", "rsa:2048", "-days", "2", + "-subj", "/CN=ca.test", + "-addext", "basicConstraints=CA:TRUE"]), + ("good.pem", ["-newkey", "rsa:2048", "-days", "2", + "-subj", "/CN=good.test", + "-addext", "basicConstraints=critical,CA:FALSE"]), +] +for cert_name, cert_args in cert_specs: + subprocess.run(["openssl", "req", "-x509", "-nodes", + "-keyout", os.path.join(key_dir, cert_name + ".key"), + "-out", os.path.join(cert_dir, cert_name)] + cert_args, + check=True, capture_output=True) +os.chmod(os.path.join(cert_dir, "weak.pem"), 0o666) + +ts_root = tempfile.mkdtemp(prefix="apex-ts-") +os.makedirs(os.path.join(ts_root, "etc", "systemd")) +ts_bad = os.path.join(ts_root, "etc", "systemd", "timesyncd.conf") +with open(ts_bad, "w") as f: + f.write("[Time]\n") + f.write("FallbackNTP=0.debian.pool.ntp.org 1.debian.pool.ntp.org\n") + f.write("RootDistanceMaxSec=60\n") + f.write("PollIntervalMinSec=4\n") + f.write("PollIntervalMaxSec=4096\n") +os.chmod(ts_bad, 0o666) +ts_good_root = tempfile.mkdtemp(prefix="apex-tsg-") +os.makedirs(os.path.join(ts_good_root, "etc", "systemd")) +with open(os.path.join(ts_good_root, "etc", "systemd", "timesyncd.conf"), + "w") as f: + f.write("[Time]\n") + f.write("NTP=ntp.example.test\n") + f.write("RootDistanceMaxSec=5\n") + f.write("PollIntervalMinSec=32\n") + f.write("PollIntervalMaxSec=2048\n") + +rc_root = tempfile.mkdtemp(prefix="apex-rc-") +os.makedirs(os.path.join(rc_root, "etc")) +rc_bad = os.path.join(rc_root, "etc", "resolv.conf") +with open(rc_bad, "w") as f: + f.write("nameserver 8.8.8.8\n") +os.chmod(rc_bad, 0o666) +rc_good_root = tempfile.mkdtemp(prefix="apex-rcg-") +os.makedirs(os.path.join(rc_good_root, "etc")) +with open(os.path.join(rc_good_root, "etc", "resolv.conf"), "w") as f: + f.write("nameserver 10.0.0.1\n") + f.write("nameserver 10.0.0.2\n") + f.write("search example.test\n") + + +def dns_zone_agent(zones): + 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 rr(rtype, rdata): + return (b"\xc0\x0c" + + 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] + 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] + answers = [] + zone = zones.get(name.lower()) + if zone is not None: + if qtype == 6: + mname, names = zone + rdata = (dns_name_encode(mname) + + dns_name_encode("hostmaster." + name) + + struct.pack(">IIIII", 2026112201, 3600, 600, + 86400, 300)) + answers.append(rr(6, rdata)) + elif qtype == 2: + for ns_name in zone[1]: + answers.append(rr(2, dns_name_encode(ns_name))) + rcode = 0 if zone is not None 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 + + +soa_sock, soa_port, soa_stop = dns_zone_agent({ + "good.test": ("ns1.good.test", ["ns1.good.test", "ns2.good.test"]), + "bad.test": ("old.bad.test", ["ns1.bad.test"]), +}) + +cfg16_home = tempfile.mkdtemp(prefix="apex-cfg16-home-") +write_scope(cfg16_home, {"label": "cfg16", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_domain": ["good.test", "bad.test", "nx.test"], + "allow_port": [str(soa_port)]}) +res, _ = run([ + call(1, "ssl_cert_audit", root=cert_root), + call(2, "timesyncd_audit", root=ts_root), + call(3, "timesyncd_audit", root=ts_good_root), + call(4, "resolv_conf_audit", root=rc_root), + call(5, "resolv_conf_audit", root=rc_good_root), + call(6, "dns_soa_mname_check", domain="good.test", resolver="127.0.0.1", + port=soa_port), + call(7, "dns_soa_mname_check", domain="bad.test", resolver="127.0.0.1", + port=soa_port), + call(8, "ssl_cert_audit", root="/nonexistent-cert"), + call(9, "timesyncd_audit", root="/nonexistent-ts"), + call(10, "resolv_conf_audit", root="/nonexistent-rc"), + call(11, "dns_soa_mname_check", domain="evil.test"), + call(12, "dns_soa_mname_check", domain="nx.test", resolver="127.0.0.1", + port=soa_port), +], home=cfg16_home) +by_id = {r.get("id"): r for r in res} +certs = json.loads(text(by_id[1])) +cert_kinds = {f["id"] for f in certs["findings"]} +check("ssl_cert_audit flags expiry, SHA-1, weak keys and CA flags", + {"world-writable", "expired", "sha1-signature", "weak-key", + "ca-not-critical"} <= cert_kinds and certs["files"] == 5 and + certs["skipped"] == 0, certs) +check("ssl_cert_audit leaves the good certificate alone", + all("good.pem" not in f["detail"] for f in certs["findings"]), certs) +ts = json.loads(text(by_id[2])) +ts_kinds = {f["id"] for f in ts["findings"]} +check("timesyncd_audit flags servers, distance and polling", + {"world-writable", "public-fallback", "root-distance", + "weak-poll"} <= ts_kinds and ts["no_servers"] is False, ts) +ts_good = json.loads(text(by_id[3])) +check("timesyncd_audit accepts a scoped configuration", + ts_good["findings_count"] == 0 and ts_good["ntp"] == "ntp.example.test", + ts_good) +rc = json.loads(text(by_id[4])) +rc_kinds = {f["id"] for f in rc["findings"]} +check("resolv_conf_audit flags public, single and searchless setups", + {"world-writable", "public-resolver", "single-nameserver", + "no-search"} <= rc_kinds and rc["public_resolver"] is True, rc) +rc_good = json.loads(text(by_id[5])) +check("resolv_conf_audit accepts two internal servers", + rc_good["findings_count"] == 0 and rc_good["nameservers"] == 2 and + rc_good["search"] is True, rc_good) +soa_good = json.loads(text(by_id[6])) +check("dns_soa_mname_check accepts a delegated primary", + soa_good["consistent"] is True and + soa_good["mname"] == "ns1.good.test" and + len(soa_good["nameservers"]) == 2, soa_good) +soa_bad = json.loads(text(by_id[7])) +check("dns_soa_mname_check flags a stray primary", + soa_bad["consistent"] is False and + soa_bad["mname"] == "old.bad.test" and + soa_bad["nameservers"] == ["ns1.bad.test"], soa_bad) +check("ssl_cert_audit reports a missing directory", err(by_id[8]), + text(by_id[8])) +check("timesyncd_audit reports a missing config", err(by_id[9]), + text(by_id[9])) +check("resolv_conf_audit reports a missing config", err(by_id[10]), + text(by_id[10])) +check("dns_soa_mname_check refuses an out-of-scope domain", err(by_id[11]), + text(by_id[11])) +check("dns_soa_mname_check reports a missing SOA", err(by_id[12]), + text(by_id[12])) +soa_stop.set() +soa_sock.close() +shutil.rmtree(cert_root, ignore_errors=True) +shutil.rmtree(ts_root, ignore_errors=True) +shutil.rmtree(ts_good_root, ignore_errors=True) +shutil.rmtree(rc_root, ignore_errors=True) +shutil.rmtree(rc_good_root, ignore_errors=True) +shutil.rmtree(cfg16_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()