diff --git a/CHANGELOG.md b/CHANGELOG.md index d0923c7..4bb09bf 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.41.0 — 2026-11-22 — this change +## 1.42.0 — 2026-11-22 — this change + +- **Chrony** (`chrony_config_audit`): both chrony.conf paths: `allow` with + `0.0.0.0/0`, `::/0` or `all`, a `cmdallow`/`bindcmdaddress` that leaves + localhost, and a world-writable file. +- **APT** (`apt_config_audit`): apt.conf.d, sources.list and sources.list.d: + `AllowUnauthenticated`, `AllowInsecureRepositories`, `trusted=yes`, a + plain-HTTP repository and world-writable files. +- **login.defs** (`login_defs_audit`): PASS_MAX_DAYS above 365, + PASS_MIN_DAYS/PASS_WARN_AGE of 0, a UMASK that leaves group or other access + (a umask masks bits: 022 only leaks read, 002 leaks group write), DES/MD5 + hashing and a world-writable file. +- **WebSocket** (`websocket_origin_check`): opens the upgrade twice with two + unrelated Origin headers; both 101 means Origin is not enforced, the + condition behind cross-site WebSocket hijacking. +- Tests with chrony/APT/login.defs trees and two WebSocket servers (any + origin, allowlist). 956 checks. Coverage 82.6%. + +## 1.41.0 — 2026-11-22 — ac36d21 - **Cron** (`cron_audit`): `/etc/crontab`, `/etc/cron.d` and the user crontabs (root prefix): a world-writable file or directory and job lines diff --git a/README.md b/README.md index 8494297..30dedac 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. -**202 tools · 944 end-to-end checks · 340 fuzz cases · 82.6% line coverage · ~767 KiB** +**206 tools · 956 end-to-end checks · 340 fuzz cases · 82.6% line coverage · ~780 KiB** ``` $ ./apex-twin --check -{"version":"1.41.0","tools":202,...,"scope":{"loaded":true,...}} +{"version":"1.42.0","tools":206,...,"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 (202) +## Tools (206) ### Scope and bookkeeping @@ -270,6 +270,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `elasticsearch_probe` | Unauthenticated `/`, cluster health and index list: cluster, version, status, node and index counts | | `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) | | `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 | @@ -399,6 +400,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `openldap_config_audit` | slapd.conf: cleartext rootpw, anonymous bind, default read access | | `cron_audit` | crontabs and cron.d: writable files/dirs, `curl \| sh` jobs | | `fail2ban_audit` | jail.local/conf: disabled sshd jail, ignore-all, maxretry 0, no banaction | +| `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 | ### ESP32 @@ -668,6 +672,8 @@ The full threat model, trust boundaries and a hardening checklist are in | dangling CNAME | up to eight dig queries, no data sent | | cron/fail2ban | config reads only; optional root prefix | | 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 | | USB audit | 200 devices, sysfs reads only | --- @@ -679,7 +685,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 944 end-to-end checks +make test # version check + gate audit + 956 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 @@ -799,7 +805,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, 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 + dns_dangling_cname, http_redirect_audit, + websocket_origin_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, @@ -842,7 +849,7 @@ examples/ scope.json ## Status -1.41.0. Built and run: 202 tools, 944 checks, 340 fuzz cases and 82.6% line +1.42.0. Built and run: 206 tools, 956 checks, 340 fuzz cases and 82.6% 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 0de9452..94b286d 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.41.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.42.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. +- **Chrony, APT and login.defs audits read local configuration.** The + WebSocket origin check performs two upgrade handshakes and opens no data + frames. - **Cron and fail2ban audits read local configuration; the redirect check makes GETs.** `http_redirect_audit` follows up to five redirects and re-checks the scope of every hop before following it. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index e048d69..3c78799 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.41.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.42.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -44,7 +44,8 @@ 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_dangling_cname, http_redirect_audit), +dns_ns_consistency, dns_dangling_cname, http_redirect_audit, +websocket_origin_check), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -62,7 +63,8 @@ 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, wireguard_config_audit, -ipsec_config_audit, openldap_config_audit, cron_audit, fail2ban_audit) +ipsec_config_audit, openldap_config_audit, cron_audit, fail2ban_audit, chrony_config_audit, +apt_config_audit, login_defs_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 0b896b8..57522eb 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.41.0" +#define APEX_VERSION "1.42.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 7bcbd9d..4138aea 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -11665,6 +11665,438 @@ static void t_fail2ban_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- chrony_audit */ + +/* Does a line that starts with word contain value? */ +static int conf_line_word(const char *text, const char *word, + const char *value) +{ + char *copy = strdup(text); + char *save = NULL; + char *line; + size_t wl = strlen(word); + 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 != '#' && strncasecmp(s, word, wl) == 0 && + (s[wl] == ' ' || s[wl] == '\t') && + strstr(s + wl, value) != NULL) { + found = 1; + break; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + return found; +} + +static void t_chrony_config_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + static const char *files[] = { "/etc/chrony/chrony.conf", + "/etc/chrony.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 allow_all = 0; + int cmd_open = 0; + int i; + + (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); + 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_line_word(text, "allow", "0.0.0.0/0") || + conf_line_word(text, "allow", "::/0") || + conf_line_word(text, "allow", "all")) + allow_all = 1; + if (conf_line_word(text, "cmdallow", "0.0.0.0/0") || + conf_line_word(text, "cmdallow", "::/0") || + conf_line_word(text, "cmdallow", "all")) + cmd_open = 1; + if (conf_value(text, "bindcmdaddress", value, sizeof(value)) && + (strcmp(value, "0.0.0.0") == 0 || + strcmp(value, "::") == 0)) + cmd_open = 1; + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a chrony configuration"); + return; + } + if (allow_all) { + add_finding(&findings, &first, "allow-all", "high", + "chronyd serves time to every address"); + count++; + } + if (cmd_open) { + add_finding(&findings, &first, "cmd-open", "high", + "the chronyc command port is reachable beyond " + "localhost"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"allow_all\":%s," + "\"command_open\":%s,\"findings_count\":%d," + "\"findings\":[", + files_read, allow_all ? "true" : "false", + cmd_open ? "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); +} + +/* ------------------------------------------------------------------ apt_audit */ + +static int apt_flag_true(const char *text, const char *key) +{ + char value[64]; + + if (!conf_value(text, key, value, sizeof(value))) + return 0; + return strcasecmp(value, "true") == 0; +} + +static void apt_scan_sources(mcp_buf *findings, int *first, int *count, + const char *path, int *http_repo, int *trusted) +{ + static char text[65536]; + struct stat st; + char *copy; + char *save = NULL; + char *line; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + 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 (strstr(s, "http://") != NULL && + (strncmp(s, "deb ", 4) == 0 || + strncmp(s, "deb-src ", 8) == 0 || + strncmp(s, "URIs:", 5) == 0)) + *http_repo = 1; + if (strstr(s, "trusted=yes") != NULL || + strncasecmp(s, "Trusted:", 8) == 0) + *trusted = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); +} + +static void apt_scan_conf_dir(mcp_buf *findings, int *first, int *count, + const char *dirpath, int *files, + int *unauth, int *insecure) +{ + DIR *d = opendir(dirpath); + struct dirent *ent; + + if (d == NULL) + return; + while ((ent = readdir(d)) != NULL) { + static char text[65536]; + char full[1200]; + struct stat st; + + if (ent->d_name[0] == '.') + continue; + if (strchr(ent->d_name, '.') != NULL) + 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 (apt_flag_true(text, "APT::Get::AllowUnauthenticated")) + *unauth = 1; + if (apt_flag_true(text, "Acquire::AllowInsecureRepositories")) + *insecure = 1; + } + closedir(d); +} + +static void t_apt_config_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 unauth = 0; + int insecure = 0; + int http_repo = 0; + int trusted = 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/apt/apt.conf.d", root); + apt_scan_conf_dir(&findings, &first, &count, path, &files, &unauth, + &insecure); + snprintf(path, sizeof(path), "%s/etc/apt/sources.list", root); + apt_scan_sources(&findings, &first, &count, path, &http_repo, + &trusted); + if (access(path, R_OK) == 0) + files++; + snprintf(path, sizeof(path), "%s/etc/apt/sources.list.d", root); + d = opendir(path); + if (d != NULL) { + struct dirent *ent; + + while ((ent = readdir(d)) != NULL) { + char full[1200]; + size_t nl = strlen(ent->d_name); + + if (ent->d_name[0] == '.') + continue; + if (nl < 6 || (strcmp(ent->d_name + nl - 5, ".list") != 0 && + strcmp(ent->d_name + nl - 7, ".sources") != 0)) + continue; + snprintf(full, sizeof(full), "%.900s/%.200s", path, + ent->d_name); + if (access(full, R_OK) == 0) + files++; + apt_scan_sources(&findings, &first, &count, full, + &http_repo, &trusted); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read an APT configuration"); + return; + } + if (unauth) { + add_finding(&findings, &first, "allow-unauthenticated", "high", + "APT allows unauthenticated packages"); + count++; + } + if (insecure) { + add_finding(&findings, &first, "insecure-repositories", "high", + "APT allows insecure repositories"); + count++; + } + if (trusted) { + add_finding(&findings, &first, "trusted-yes", "high", + "a repository bypasses signature checks"); + count++; + } + if (http_repo) { + add_finding(&findings, &first, "http-repository", "medium", + "a repository is fetched over plain HTTP"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"allow_unauthenticated\":%s," + "\"insecure_repositories\":%s,\"trusted\":%s," + "\"http_repository\":%s,\"findings_count\":%d," + "\"findings\":[", + files, unauth ? "true" : "false", + insecure ? "true" : "false", + trusted ? "true" : "false", + http_repo ? "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); +} + +/* ------------------------------------------------------------ login_defs_audit */ + +static void t_login_defs_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 value[128]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int max_days = 0; + int min_days_zero = 0; + int warn_zero = 0; + int umask_loose = 0; + int weak_hash = 0; + long n; + + (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/login.defs", root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read login.defs"); + return; + } + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "login.defs is writable by anyone"); + count++; + } + if (conf_value(text, "PASS_MAX_DAYS", value, sizeof(value))) { + char *end = NULL; + + n = strtol(value, &end, 10); + if (end != value && n > 365) { + max_days = (int)n; + add_finding(&findings, &first, "password-max-days", + "medium", + "passwords may live for %ld days", n); + count++; + } + } + if (conf_value(text, "PASS_MIN_DAYS", value, sizeof(value))) { + char *end = NULL; + + n = strtol(value, &end, 10); + if (end != value && n == 0) { + min_days_zero = 1; + add_finding(&findings, &first, "password-min-days", + "low", + "a password may be changed immediately"); + count++; + } + } + if (conf_value(text, "PASS_WARN_AGE", value, sizeof(value))) { + char *end = NULL; + + n = strtol(value, &end, 10); + if (end != value && n == 0) { + warn_zero = 1; + add_finding(&findings, &first, "password-warn-age", + "low", "no warning before a password expires"); + count++; + } + } + if (conf_value(text, "UMASK", value, sizeof(value))) { + char *end = NULL; + unsigned long u = strtoul(value, &end, 8); + + if (end != value) { + if ((u & 0002) == 0) { + umask_loose = 2; + add_finding(&findings, &first, "umask-world", + "high", + "new files stay writable by anyone"); + count++; + } else if ((u & 0020) == 0) { + umask_loose = 1; + add_finding(&findings, &first, "umask-group", + "medium", + "new files stay writable by the group"); + count++; + } else if ((u & 0004) == 0) { + umask_loose = 3; + add_finding(&findings, &first, "umask-read", + "low", + "new files stay readable by anyone"); + count++; + } + } + } + if (conf_value(text, "ENCRYPT_METHOD", value, sizeof(value)) && + (strcasecmp(value, "DES") == 0 || + strcasecmp(value, "MD5") == 0)) { + weak_hash = 1; + add_finding(&findings, &first, "weak-hash", "high", + "passwords are hashed with %s", value); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"password_max_days\":%d," + "\"password_min_days_zero\":%s," + "\"password_warn_zero\":%s,\"umask\":", max_days, + min_days_zero ? "true" : "false", + warn_zero ? "true" : "false"); + apex_json_str(&b, umask_loose == 2 ? "world-writable" + : umask_loose == 1 ? "group-writable" + : umask_loose == 3 ? "world-readable" : "tight"); + mcp_buf_printf(&b, ",\"weak_hash\":%s,\"findings_count\":%d," + "\"findings\":[", + weak_hash ? "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, " @@ -12303,6 +12735,27 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_fail2ban_audit }, + { "chrony_config_audit", + "Parse chrony.conf (root prefix, both usual paths): allow 0.0.0.0/0, " + "::/0 or all, a cmdallow beyond localhost, bindcmdaddress on every " + "interface and a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_chrony_config_audit }, + { "apt_config_audit", + "Parse apt.conf.d, sources.list and sources.list.d (root prefix): " + "AllowUnauthenticated, AllowInsecureRepositories, trusted=yes, plain " + "HTTP repositories and world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_apt_config_audit }, + { "login_defs_audit", + "Parse login.defs (root prefix): PASS_MAX_DAYS above 365, PASS_MIN_DAYS " + "and PASS_WARN_AGE of zero, a loose UMASK, DES/MD5 password hashing and " + "a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_login_defs_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 7e47a34..9eb8758 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -6038,6 +6038,145 @@ static void t_dns_dangling_cname(mcp_conn *c, const mcp_json *args, mcp_buf_free(&b); } +/* ------------------------------------------------------ websocket_origin_check */ + +static int ws_origin_attempt(const char *target, int port, int tls, + const char *path, const char *origin, + int *code, char *accept, size_t an) +{ + unsigned char raw[16]; + char key[32]; + char headers[768]; + char status[256]; + char *resp = NULL; + size_t len = 0; + char upgrade[64]; + char connection[128]; + int fd; + int upgraded = 0; + + memset(raw, 0, sizeof(raw)); + fd = open("/dev/urandom", O_RDONLY); + if (fd >= 0) { + ssize_t r = read(fd, raw, sizeof(raw)); + + (void)r; + close(fd); + } + { + char *b64 = apex_base64_alloc((const char *)raw, sizeof(raw)); + + if (b64 == NULL) + return -1; + snprintf(key, sizeof(key), "%.28s", b64); + free(b64); + } + snprintf(headers, sizeof(headers), + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + "Origin: %.200s\r\nSec-WebSocket-Key: %s\r\n" + "Sec-WebSocket-Version: 13\r\n", origin, key); + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", path, NULL, headers, 8000, + &resp, &len, status, sizeof(status)) != 0) + return -1; + *code = apex_status_code(status); + upgrade[0] = connection[0] = '\0'; + accept[0] = '\0'; + response_header(resp, len, "Upgrade", upgrade, sizeof(upgrade)); + response_header(resp, len, "Connection", connection, sizeof(connection)); + response_header(resp, len, "Sec-WebSocket-Accept", accept, an); + upgraded = *code == 101 && + strcasecmp(upgrade, "websocket") == 0 && + strcasestr(connection, "upgrade") != NULL; + free(resp); + return upgraded; +} + +static void t_websocket_origin_check(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *path = mcp_arg_string(args, "path"); + const char *origin = mcp_arg_string(args, "origin"); + const char *second = mcp_arg_string(args, "second_origin"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + char accept_a[128]; + char accept_b[128]; + int code_a = 0; + int code_b = 0; + int upgraded_a; + int upgraded_b; + int any_origin; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/"; + if (path[0] != '/') { + mcp_reply_error(c, "path must start with /"); + return; + } + if (origin == NULL || *origin == '\0') + origin = "https://apex-twin.invalid"; + if (second == NULL || *second == '\0') + second = "https://evil.apex-twin.invalid"; + if (strpbrk(origin, "\r\n") != NULL || + strpbrk(second, "\r\n") != NULL) { + mcp_reply_error(c, "origins must not contain control characters"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!gated(c, "websocket_origin_check", target, port)) + return; + accept_a[0] = accept_b[0] = '\0'; + upgraded_a = ws_origin_attempt(target, port, tls, path, origin, &code_a, + accept_a, sizeof(accept_a)); + if (upgraded_a < 0) { + mcp_reply_error(c, "cannot reach the WebSocket endpoint"); + return; + } + upgraded_b = ws_origin_attempt(target, port, tls, path, second, &code_b, + accept_b, sizeof(accept_b)); + if (upgraded_b < 0) { + mcp_reply_error(c, "cannot reach the WebSocket endpoint"); + return; + } + any_origin = upgraded_a == 1 && upgraded_b == 1; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port); + apex_json_str(&b, path); + mcp_buf_puts(&b, ",\"origins\":["); + apex_json_str(&b, origin); + mcp_buf_puts(&b, ","); + apex_json_str(&b, second); + mcp_buf_printf(&b, "],\"statuses\":[%d,%d],\"upgraded\":[%s,%s]," + "\"accepts\":[", code_a, code_b, + upgraded_a ? "true" : "false", + upgraded_b ? "true" : "false"); + apex_json_str(&b, accept_a); + mcp_buf_puts(&b, ","); + apex_json_str(&b, accept_b); + mcp_buf_printf(&b, "],\"any_origin\":%s}", + any_origin ? "true" : "false"); + apex_audit("websocket_origin_check", target, port, !any_origin, + any_origin + ? "the upgrade succeeds for two unrelated origins - Origin " + "is not enforced (CSWSH risk)" + : "the server refused at least one unrelated origin", path); + 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: " @@ -6313,6 +6452,19 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_websocket_probe }, + { "websocket_origin_check", + "Open the WebSocket twice with two unrelated Origin headers and report " + "both statuses. An upgrade for both means Origin is not enforced, the " + "condition behind cross-site WebSocket hijacking. Gate: the target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"tls\":{\"type\":\"boolean\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /\"}," + "\"origin\":{\"type\":\"string\"}," + "\"second_origin\":{\"type\":\"string\"}}," + "\"required\":[\"target\"]}", + t_websocket_origin_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 59d5487..ee1f9e6 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 = 202 +EXPECTED_TOOLS = 206 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 59e7e01..7031a8f 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("202 tools registered", len(tools) == 202, len(tools)) +check("206 tools registered", len(tools) == 206, 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"]) == 202) + check("http tools/list", len(listing["result"]["tools"]) == 206) 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 @@ -9293,9 +9293,208 @@ shutil.rmtree(f2b_good_root, ignore_errors=True) shutil.rmtree(redir_tls_dir, ignore_errors=True) shutil.rmtree(cfg13_home, ignore_errors=True) +print("\n== chrony, APT, login.defs and WebSocket origins ==\n") + +import base64 +import hashlib + +ch_root = tempfile.mkdtemp(prefix="apex-ch-") +os.makedirs(os.path.join(ch_root, "etc", "chrony")) +ch_bad = os.path.join(ch_root, "etc", "chrony", "chrony.conf") +with open(ch_bad, "w") as f: + f.write("pool 2.debian.pool.ntp.org iburst\n") + f.write("allow 0.0.0.0/0\n") + f.write("cmdallow all\n") + f.write("bindcmdaddress 0.0.0.0\n") +os.chmod(ch_bad, 0o666) +ch_good_root = tempfile.mkdtemp(prefix="apex-chg-") +os.makedirs(os.path.join(ch_good_root, "etc", "chrony")) +with open(os.path.join(ch_good_root, "etc", "chrony", "chrony.conf"), + "w") as f: + f.write("pool time.example.test iburst\n") + f.write("allow 10.0.0.0/24\n") + f.write("bindcmdaddress 127.0.0.1\n") + +apt_root = tempfile.mkdtemp(prefix="apex-apt-") +os.makedirs(os.path.join(apt_root, "etc", "apt", "apt.conf.d")) +apt_bad = os.path.join(apt_root, "etc", "apt", "apt.conf.d", "99insecure") +with open(apt_bad, "w") as f: + f.write('APT::Get::AllowUnauthenticated "true";\n') + f.write('Acquire::AllowInsecureRepositories "true";\n') +os.chmod(apt_bad, 0o666) +with open(os.path.join(apt_root, "etc", "apt", "sources.list"), "w") as f: + f.write("deb http://deb.example.test/ stable main trusted=yes\n") +apt_good_root = tempfile.mkdtemp(prefix="apex-aptg-") +os.makedirs(os.path.join(apt_good_root, "etc", "apt", "apt.conf.d")) +with open(os.path.join(apt_good_root, "etc", "apt", "apt.conf.d", + "99secure"), "w") as f: + f.write('APT::Get::AllowUnauthenticated "false";\n') + f.write('Acquire::AllowInsecureRepositories "false";\n') +with open(os.path.join(apt_good_root, "etc", "apt", "sources.list"), + "w") as f: + f.write("deb https://deb.example.test/ stable main\n") + +ld_root = tempfile.mkdtemp(prefix="apex-ldf-") +os.makedirs(os.path.join(ld_root, "etc")) +ld_bad = os.path.join(ld_root, "etc", "login.defs") +with open(ld_bad, "w") as f: + f.write("PASS_MAX_DAYS 99999\n") + f.write("PASS_MIN_DAYS 0\n") + f.write("PASS_WARN_AGE 0\n") + f.write("UMASK 022\n") + f.write("ENCRYPT_METHOD MD5\n") +os.chmod(ld_bad, 0o666) +ld_good_root = tempfile.mkdtemp(prefix="apex-ldfg-") +os.makedirs(os.path.join(ld_good_root, "etc")) +with open(os.path.join(ld_good_root, "etc", "login.defs"), "w") as f: + f.write("PASS_MAX_DAYS 90\n") + f.write("PASS_MIN_DAYS 7\n") + f.write("PASS_WARN_AGE 14\n") + f.write("UMASK 027\n") + f.write("ENCRYPT_METHOD YESCRYPT\n") + + +def ws_server(strict): + srv = socket.socket() + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(8) + port = srv.getsockname()[1] + guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + def loop(): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + try: + conn.settimeout(3) + data = b"" + while b"\r\n\r\n" not in data: + chunk = conn.recv(2048) + if not chunk: + break + data += chunk + request = data.decode("latin-1") + key = "" + origin = "" + for line in request.split("\r\n"): + lower = line.lower() + if lower.startswith("sec-websocket-key:"): + key = line.split(":", 1)[1].strip() + elif lower.startswith("origin:"): + origin = line.split(":", 1)[1].strip() + if strict and origin != "https://allowed.test": + body = b"forbidden" + conn.sendall( + b"HTTP/1.1 403 Forbidden\r\nContent-Length: " + + str(len(body)).encode() + + b"\r\nConnection: close\r\n\r\n" + body) + else: + accept = base64.b64encode(hashlib.sha1( + (key + guid).encode()).digest()).decode() + conn.sendall( + ("HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Accept: %s\r\n\r\n" % accept + ).encode()) + except OSError: + pass + finally: + conn.close() + + threading.Thread(target=loop, daemon=True).start() + return srv, port + + +ws_any_srv, ws_any_port = ws_server(False) +ws_strict_srv, ws_strict_port = ws_server(True) + +cfg14_home = tempfile.mkdtemp(prefix="apex-cfg14-home-") +write_scope(cfg14_home, {"label": "cfg14", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(ws_any_port), + str(ws_strict_port)]}) +res, _ = run([ + call(1, "chrony_config_audit", root=ch_root), + call(2, "chrony_config_audit", root=ch_good_root), + call(3, "apt_config_audit", root=apt_root), + call(4, "apt_config_audit", root=apt_good_root), + call(5, "login_defs_audit", root=ld_root), + call(6, "login_defs_audit", root=ld_good_root), + call(7, "websocket_origin_check", target="127.0.0.1", + port=ws_any_port, tls=False), + call(8, "websocket_origin_check", target="127.0.0.1", + port=ws_strict_port, tls=False, origin="https://allowed.test"), + call(9, "chrony_config_audit", root="/nonexistent-ch"), + call(10, "apt_config_audit", root="/nonexistent-apt"), + call(11, "login_defs_audit", root="/nonexistent-ldf"), + call(12, "websocket_origin_check", target="198.51.100.9", port=80), +], home=cfg14_home) +by_id = {r.get("id"): r for r in res} +ch = json.loads(text(by_id[1])) +ch_kinds = {f["id"] for f in ch["findings"]} +check("chrony_config_audit flags open serving and a command port", + {"world-writable", "allow-all", "cmd-open"} <= ch_kinds and + ch["allow_all"] is True and ch["command_open"] is True, ch) +ch_good = json.loads(text(by_id[2])) +check("chrony_config_audit accepts a scoped config", + ch_good["findings_count"] == 0 and ch_good["allow_all"] is False and + ch_good["command_open"] is False, ch_good) +apt = json.loads(text(by_id[3])) +apt_kinds = {f["id"] for f in apt["findings"]} +check("apt_config_audit flags unsigned, insecure and HTTP repos", + {"world-writable", "allow-unauthenticated", "insecure-repositories", + "trusted-yes", "http-repository"} <= apt_kinds and + apt["allow_unauthenticated"] is True and apt["http_repository"] is True, + apt) +apt_good = json.loads(text(by_id[4])) +check("apt_config_audit accepts a signed HTTPS config", + apt_good["findings_count"] == 0 and + apt_good["allow_unauthenticated"] is False and + apt_good["trusted"] is False, apt_good) +ld = json.loads(text(by_id[5])) +ld_kinds = {f["id"] for f in ld["findings"]} +check("login_defs_audit flags aging, umask and weak hashing", + {"world-writable", "password-max-days", "password-min-days", + "password-warn-age", "umask-read", "weak-hash"} <= ld_kinds and + ld["password_max_days"] == 99999 and ld["weak_hash"] is True, ld) +ld_good = json.loads(text(by_id[6])) +check("login_defs_audit accepts a hardened file", + ld_good["findings_count"] == 0 and ld_good["umask"] == "tight" and + ld_good["weak_hash"] is False, ld_good) +ws_any = json.loads(text(by_id[7])) +check("websocket_origin_check flags an unchecked Origin", + ws_any["any_origin"] is True and ws_any["statuses"] == [101, 101] and + ws_any["upgraded"] == [True, True], ws_any) +ws_strict = json.loads(text(by_id[8])) +check("websocket_origin_check accepts an Origin allowlist", + ws_strict["any_origin"] is False and + ws_strict["statuses"] == [101, 403] and + ws_strict["upgraded"] == [True, False], ws_strict) +check("chrony_config_audit reports a missing config", err(by_id[9]), + text(by_id[9])) +check("apt_config_audit reports a missing config", err(by_id[10]), + text(by_id[10])) +check("login_defs_audit reports a missing config", err(by_id[11]), + text(by_id[11])) +check("websocket_origin_check refuses an out-of-scope target", + err(by_id[12]), text(by_id[12])) +ws_any_srv.close() +ws_strict_srv.close() +shutil.rmtree(ch_root, ignore_errors=True) +shutil.rmtree(ch_good_root, ignore_errors=True) +shutil.rmtree(apt_root, ignore_errors=True) +shutil.rmtree(apt_good_root, ignore_errors=True) +shutil.rmtree(ld_root, ignore_errors=True) +shutil.rmtree(ld_good_root, ignore_errors=True) +shutil.rmtree(cfg14_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()