diff --git a/CHANGELOG.md b/CHANGELOG.md index 993f10d..4ef0542 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.36.0 — 2026-11-21 — this change +## 1.37.0 — 2026-11-21 — this change + +- **kubelet** (`kubelet_config_audit`): /var/lib/kubelet/config.yaml (root + prefix): anonymous authentication enabled, authorization mode AlwaysAllow, + readOnlyPort above zero and a world-writable config. +- **etcd** (`etcd_config_audit`): etcd.conf.yml/etcd.conf//etc/default/etcd: + client URLs on 0.0.0.0 or plain HTTP, client and peer cert auth off, auto-tls + and world-writable files. Both YAML and KEY=value forms are read. +- **RabbitMQ** (`rabbitmq_audit`): rabbitmq.conf and advanced.config: guest + loopback restriction removed, default guest/guest credentials, management + without a TLS port and world-writable files. +- **SNI** (`sni_vhost_check`): one s_client -servername handshake per in-scope + name, comparing certificate subject, SAN and SHA-256 fingerprint; different + certificates for one address mean SNI virtual hosts. +- Tests with vulnerable and hardened kubelet/etcd/RabbitMQ trees and a TLS + server that selects per SNI. 893 checks. Coverage 81.9%. + +## 1.36.0 — 2026-11-21 — b1165c5 - **BIND** (`bind9_config_audit`): named.conf plus .options/.local (root prefix): allow-query any, recursion yes without allow-recursion, diff --git a/README.md b/README.md index a06efac..dc0b099 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. -**183 tools · 880 end-to-end checks · 340 fuzz cases · 81.9% line coverage · ~717 KiB** +**187 tools · 893 end-to-end checks · 340 fuzz cases · 81.9% line coverage · ~730 KiB** ``` $ ./apex-twin --check -{"version":"1.36.0","tools":183,...,"scope":{"loaded":true,...}} +{"version":"1.37.0","tools":187,...,"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 (183) +## Tools (187) ### Scope and bookkeeping @@ -300,6 +300,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `webdav_probe` | OPTIONS + Depth:0 PROPFIND: 207 Multistatus means WebDAV is enabled | | `dns_wildcard_check` | Random label under a domain; an answer means wildcard DNS | | `dns_caa_check` | CAA records: flags, issue/issuewild/iodef tags and values | +| `sni_vhost_check` | Per-name `s_client -servername`: distinct certificate subjects/fingerprints | | `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN | | `pop3_probe` | Banner, CAPA list, STLS flag; no USER/PASS | | `sip_probe` | One UDP OPTIONS: status line, Server header, Allow methods | @@ -380,6 +381,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `bind9_config_audit` | named.conf: allow-query any, open recursion, transfer any, visible version | | `tomcat_audit` | server.xml/tomcat-users.xml: shutdown port, 0.0.0.0 connector, manager roles | | `proftpd_audit` | proftpd.conf: AllowAll, anonymous without AnonReadOnly, RootLogin, TLS off | +| `kubelet_config_audit` | kubelet config.yaml: anonymous auth, AlwaysAllow, readOnlyPort | +| `etcd_config_audit` | etcd config: 0.0.0.0/http URLs, client/peer cert auth off, auto-tls | +| `rabbitmq_audit` | rabbitmq.conf: loopback removed, guest/guest, management without TLS | ### ESP32 @@ -638,6 +642,8 @@ The full threat model, trust boundaries and a hardening checklist are in | Wildcard DNS | one dig query | | bind/tomcat/proftpd | config reads only; optional root prefix | | CAA | one gated dig query | +| kubelet/etcd/rabbitmq | config reads only; optional root prefix | +| SNI | one TLS handshake per name, no data | | USB audit | 200 devices, sysfs reads only | --- @@ -649,7 +655,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 880 end-to-end checks +make test # version check + gate audit + 893 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 @@ -766,7 +772,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, security_txt, http2_probe, ssh_hostkey_fingerprint, kerberos_discovery, winrm_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, - webdav_probe, dns_wildcard_check, dns_caa_check + webdav_probe, dns_wildcard_check, dns_caa_check, + sni_vhost_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, @@ -809,7 +816,7 @@ examples/ scope.json ## Status -1.36.0. Built and run: 183 tools, 880 checks, 340 fuzz cases and 81.9% line +1.37.0. Built and run: 187 tools, 893 checks, 340 fuzz cases and 81.9% 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 5b0939e..f1f9017 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.36.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.37.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. +- **SNI checks are TLS handshakes only.** `sni_vhost_check` connects once per + in-scope name and reads the certificate; Kubernetes, etcd and RabbitMQ + audits read configuration files. - **CAA is one DNS query.** `dns_caa_check` reads the CAA records of an in-scope domain; it does not request a certificate. BIND, Tomcat and ProFTPD audits read configuration files. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index ce4b68a..f520780 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.36.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.37.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -43,7 +43,7 @@ memcached_probe, param_fuzz, open_redirect, host_header_injection, ssti_probe, xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe, graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe, sip_probe, telnet_probe, http_methods, websocket_probe, ike_probe, snmp_walk, -ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -58,7 +58,8 @@ php_config_audit, dovecot_audit, openvpn_audit, postgresql_config_audit, exim_audit, elasticsearch_config_audit, squid_audit, unbound_audit, cups_audit, rsync_audit, dhcpd_audit, krb5_conf_audit, mongodb_config_audit, memcached_config_audit, ntpd_config_audit, -bind9_config_audit, tomcat_audit, proftpd_audit) and ESP32 board tools (esp_info, esp_monitor, +bind9_config_audit, tomcat_audit, proftpd_audit, kubelet_config_audit, +etcd_config_audit, rabbitmq_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, esp_app_info, esp_image_verify). .SH MODES diff --git a/src/apex.h b/src/apex.h index dcc68eb..5e791d5 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.36.0" +#define APEX_VERSION "1.37.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 b969efb..2f7d48e 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -10008,6 +10008,403 @@ static void t_proftpd_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------------ kubelet_config_audit */ + +static void t_kubelet_config_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *root = mcp_arg_string(args, "root"); + static char text[65536]; + char path[1024]; + char read_only[64]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int anonymous = 0; + int always_allow = 0; + int readonly_port = -1; + int in_anonymous = 0; + int anon_indent = 0; + int in_authz = 0; + int authz_indent = 0; + struct stat st; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), "%s/var/lib/kubelet/config.yaml", root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read kubelet config.yaml"); + return; + } + read_only[0] = '\0'; + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "kubelet config is writable by anyone"); + count++; + } + if (yaml_value(text, "readOnlyPort", read_only, sizeof(read_only))) + readonly_port = atoi(read_only); + { + char *copy = strdup(text); + char *save = NULL; + char *line; + + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *t = line; + int indent = 0; + + while (*t == ' ' || *t == '\t') { + indent++; + t++; + } + if (*t != '#' && *t != '\0') { + if (strncmp(t, "anonymous:", 10) == 0) { + in_anonymous = 1; + anon_indent = indent; + } else if (in_anonymous && + indent <= anon_indent) { + in_anonymous = 0; + } + if (in_anonymous && + strncmp(t, "enabled:", 8) == 0 && + strstr(t, "true") != NULL) + anonymous = 1; + if (strncmp(t, "authorization:", 14) == 0) { + in_authz = 1; + authz_indent = indent; + } else if (in_authz && + indent <= authz_indent) { + in_authz = 0; + } + if (in_authz && + strncmp(t, "mode:", 5) == 0 && + strstr(t, "AlwaysAllow") != NULL) + always_allow = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + if (anonymous) { + add_finding(&findings, &first, "anonymous-auth", "high", + "anonymous authentication is enabled"); + count++; + } + if (always_allow) { + add_finding(&findings, &first, "always-allow", "high", + "authorization mode is AlwaysAllow"); + count++; + } + if (readonly_port > 0) { + add_finding(&findings, &first, "readonly-port", "high", + "the read-only port is enabled"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"anonymous\":%s,\"always_allow\":%s," + "\"read_only_port\":%d,\"findings_count\":%d," + "\"findings\":[", + anonymous ? "true" : "false", + always_allow ? "true" : "false", readonly_port, 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); +} + +/* --------------------------------------------------------------- etcd_config_audit */ + +static int etcd_value(const char *text, const char *key, char *out, size_t n) +{ + char upper[96]; + size_t i; + + if (yaml_value(text, key, out, n)) + return 1; + for (i = 0; key[i] != '\0' && i + 1 < sizeof(upper); i++) + upper[i] = (char)toupper((unsigned char)key[i]); + upper[i] = '\0'; + { + const char *p = text; + size_t kl = strlen(upper); + size_t ql = strlen(key); + + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[1024]; + char *s; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + s = line; + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && + (strncasecmp(s, upper, kl) == 0 || + strncasecmp(s, key, ql) == 0)) { + char *eq = strchr(s, '='); + char *v; + size_t vl; + + if (eq != NULL) { + *eq = '\0'; + if (strcasecmp(s, upper) != 0 && + strcasecmp(s, key) != 0) { + p = eol != NULL ? eol + 1 : NULL; + continue; + } + v = eq + 1; + while (*v == ' ' || *v == '\t') + v++; + vl = strlen(v); + while (vl > 0 && + (v[vl - 1] == '"' || + v[vl - 1] == ' ' || + v[vl - 1] == '\t' || + v[vl - 1] == '\r')) + v[--vl] = '\0'; + if (*v == '"') + v++; + snprintf(out, n, "%.*s", (int)vl, v); + return 1; + } + } + p = eol != NULL ? eol + 1 : NULL; + } + } + return 0; +} + +static void t_etcd_config_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *files[] = { "/etc/etcd/etcd.conf.yml", + "/etc/etcd/etcd.conf", + "/etc/default/etcd", NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char urls[512]; + char client_auth[64]; + char peer_auth[64]; + char auto_tls[64]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + int open_urls = 0; + int client_off = 0; + int peer_off = 0; + int auto_tls_on = 0; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + urls[0] = client_auth[0] = peer_auth[0] = auto_tls[0] = '\0'; + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + static char text[65536]; + char value[512]; + 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 (etcd_value(text, "listen-client-urls", value, + sizeof(value))) { + snprintf(urls, sizeof(urls), "%.300s", value); + if (strstr(value, "0.0.0.0") != NULL || + strstr(value, "[::]") != NULL || + strstr(value, "http://") != NULL) + open_urls = 1; + } + if (etcd_value(text, "client-cert-auth", value, sizeof(value))) + snprintf(client_auth, sizeof(client_auth), "%.32s", value); + if (etcd_value(text, "peer-cert-auth", value, sizeof(value))) + snprintf(peer_auth, sizeof(peer_auth), "%.32s", value); + if (etcd_value(text, "auto-tls", value, sizeof(value))) + snprintf(auto_tls, sizeof(auto_tls), "%.32s", value); + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read an etcd configuration"); + return; + } + if (open_urls) { + add_finding(&findings, &first, "client-urls-open", "high", + "client URLs are plain HTTP or on every interface"); + count++; + } + if (strcasecmp(client_auth, "false") == 0 || + client_auth[0] == '\0') { + add_finding(&findings, &first, "client-cert-auth-off", "high", + "client certificate authentication is off"); + client_off = 1; + count++; + } + if (strcasecmp(peer_auth, "false") == 0 || peer_auth[0] == '\0') { + add_finding(&findings, &first, "peer-cert-auth-off", "medium", + "peer certificate authentication is off"); + peer_off = 1; + count++; + } + if (strcasecmp(auto_tls, "true") == 0) { + add_finding(&findings, &first, "auto-tls", "low", + "auto-tls generates self-signed certificates"); + auto_tls_on = 1; + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"listen_client_urls\":", files_read); + apex_json_str(&b, urls); + mcp_buf_printf(&b, ",\"client_cert_auth\":%s,\"peer_cert_auth\":%s," + "\"auto_tls\":%s,\"findings_count\":%d,\"findings\":[", + client_off ? "false" : "true", + peer_off ? "false" : "true", + auto_tls_on ? "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); +} + +/* -------------------------------------------------------------- rabbitmq_audit */ + +static void t_rabbitmq_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char default_user[64]; + char default_pass[64]; + char loopback[64]; + char mgmt_port[64]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + int loopback_removed = 0; + int default_guest = 0; + int mgmt_no_tls = 0; + int i; + static const char *files[] = { "/etc/rabbitmq/rabbitmq.conf", + "/etc/rabbitmq/advanced.config", NULL }; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + default_user[0] = default_pass[0] = loopback[0] = mgmt_port[0] = '\0'; + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + static char text[65536]; + char value[512]; + 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, "default_user", value, sizeof(value))) + snprintf(default_user, sizeof(default_user), "%.32s", + value); + if (conf_value(text, "default_pass", value, sizeof(value))) + snprintf(default_pass, sizeof(default_pass), "%.32s", + value); + if (conf_value(text, "loopback_users.guest", value, + sizeof(value))) + snprintf(loopback, sizeof(loopback), "%.32s", value); + if (conf_value(text, "management.tcp.port", value, + sizeof(value))) + snprintf(mgmt_port, sizeof(mgmt_port), "%.48s", value); + if (conf_value(text, "management.ssl.port", value, + sizeof(value)) || + conf_value(text, "management.tls.port", value, + sizeof(value))) + mgmt_port[0] = '\0'; /* TLS management is configured */ + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a RabbitMQ configuration"); + return; + } + if (strcasecmp(loopback, "false") == 0 || + strcasecmp(loopback, "none") == 0) { + loopback_removed = 1; + add_finding(&findings, &first, "loopback-removed", "high", + "the guest loopback restriction is removed"); + count++; + } + if ((default_user[0] == '\0' && default_pass[0] == '\0') || + (strcasecmp(default_user, "guest") == 0 && + strcasecmp(default_pass, "guest") == 0)) { + default_guest = 1; + add_finding(&findings, &first, "default-guest", "high", + "the default guest/guest account is in use"); + count++; + } + if (mgmt_port[0] != '\0') { + mgmt_no_tls = 1; + add_finding(&findings, &first, "management-no-tls", "medium", + "the management interface has no TLS port"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"loopback_removed\":%s," + "\"default_guest\":%s,\"management_tls\":%s," + "\"findings_count\":%d,\"findings\":[", + files_read, loopback_removed ? "true" : "false", + default_guest ? "true" : "false", + mgmt_no_tls ? "false" : "true", 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, " @@ -10554,6 +10951,27 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_proftpd_audit }, + { "kubelet_config_audit", + "Parse /var/lib/kubelet/config.yaml (root prefix): anonymous " + "authentication enabled, authorization mode AlwaysAllow, a read-only " + "port above zero and a world-writable config. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_kubelet_config_audit }, + { "etcd_config_audit", + "Parse etcd.conf.yml/etcd.conf//etc/default/etcd (root prefix): client " + "URLs on 0.0.0.0 or plain HTTP, client/peer cert auth off, auto-tls and " + "world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_etcd_config_audit }, + { "rabbitmq_audit", + "Parse rabbitmq.conf and advanced.config (root prefix): guest loopback " + "restriction removed, default guest/guest credentials, management " + "without a TLS port and world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_rabbitmq_audit }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_proto.c b/src/tools_proto.c index 41c03bc..233642e 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -5448,6 +5448,176 @@ static void t_alpn_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------ sni_vhost_check */ + +static void t_sni_vhost_check(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *names_arg = mcp_arg_string(args, "names"); + int port = mcp_arg_int(args, "port", 443); + char names[8][256]; + int nnames = 0; + char conn[320]; + char reason[512]; + char fingerprints[8][128]; + int nfp = 0; + mcp_buf b; + int first = 1; + int i; + + (void)user; + if (target == NULL || *target == '\0' || names_arg == NULL || + *names_arg == '\0') { + mcp_reply_error(c, "target and names are required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + { + char *copy = strdup(names_arg); + char *save = NULL; + char *tok; + + if (copy == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + tok = strtok_r(copy, ",", &save); + while (tok != NULL && nnames < 8) { + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok != '\0') { + snprintf(names[nnames], sizeof(names[0]), + "%.240s", tok); + nnames++; + } + tok = strtok_r(NULL, ",", &save); + } + free(copy); + } + if (nnames == 0) { + mcp_reply_error(c, "no names given"); + return; + } + if (!gated(c, "sni_vhost_check", target, port)) + return; + for (i = 0; i < nnames; i++) { + if (!apex_scope_check(names[i], port, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "name %s is outside the scope: %s", + names[i], reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + } + tls_conn_string(target, port, conn, sizeof(conn)); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"certificates\":[", port); + for (i = 0; i < nnames; i++) { + char *argv[12]; + int k = 0; + apex_proc p; + char subject[256]; + char fingerprint[128]; + char sans[512]; + mcp_buf pem; + char pem_path[APEX_PATH_FULL]; + + subject[0] = fingerprint[0] = sans[0] = '\0'; + mcp_buf_init(&pem); + argv[k++] = "openssl"; + argv[k++] = "s_client"; + argv[k++] = "-connect"; + argv[k++] = conn; + argv[k++] = "-servername"; + argv[k++] = names[i]; + argv[k++] = "-showcerts"; + argv[k] = NULL; + if (apex_run(argv, 20000, g_cfg.max_output, &p) == 0) { + if (p.out != NULL) + extract_first_pem(p.out, &pem); + apex_proc_free(&p); + } + if (pem.len > 0) { + snprintf(pem_path, sizeof(pem_path), + "%s/sni-%ld-%d.pem", g_cfg.evidence_dir, + (long)getpid(), i); + if (apex_write_file(pem_path, pem.p, pem.len, 0600) == 0) { + char *xargv[12]; + int x = 0; + apex_proc xp; + + xargv[x++] = "openssl"; + xargv[x++] = "x509"; + xargv[x++] = "-in"; + xargv[x++] = pem_path; + xargv[x++] = "-noout"; + xargv[x++] = "-subject"; + xargv[x++] = "-fingerprint"; + xargv[x++] = "-sha256"; + xargv[x++] = "-ext"; + xargv[x++] = "subjectAltName"; + xargv[x] = NULL; + if (apex_run(xargv, 10000, 65536, &xp) == 0) { + if (xp.out != NULL) { + header_value(xp.out, "subject=", + subject, + sizeof(subject)); + header_value(xp.out, + "Fingerprint=", + fingerprint, + sizeof(fingerprint)); + header_value(xp.out, "DNS:", + sans, sizeof(sans)); + } + apex_proc_free(&xp); + } + unlink(pem_path); + } + } + mcp_buf_free(&pem); + if (fingerprint[0] != '\0') { + int j; + int known = 0; + + for (j = 0; j < nfp; j++) + if (strcmp(fingerprints[j], fingerprint) == 0) + known = 1; + if (!known && nfp < 8) { + snprintf(fingerprints[nfp], + sizeof(fingerprints[0]), "%s", + fingerprint); + nfp++; + } + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"name\":"); + apex_json_str(&b, names[i]); + mcp_buf_puts(&b, ",\"subject\":"); + apex_json_str(&b, subject); + mcp_buf_puts(&b, ",\"fingerprint\":"); + apex_json_str(&b, fingerprint); + mcp_buf_puts(&b, ",\"san\":"); + apex_json_str(&b, sans); + mcp_buf_puts(&b, "}"); + } + mcp_buf_printf(&b, "],\"distinct_certificates\":%d," + "\"sni_vhosts\":%s}", nfp, + nfp > 1 ? "true" : "false"); + apex_audit("sni_vhost_check", target, port, nfp <= 1, + nfp > 1 ? "SNI serves distinct certificates" + : "one certificate for all names", "s_client -servername"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_PROTO[] = { { "ftp_probe", "One-connection FTP check: read the 220 banner, ask FEAT, then try the " @@ -5785,6 +5955,17 @@ const mcp_tool TOOLS_PROTO[] = { "\"protocols\":{\"type\":\"string\",\"description\":\"comma list, max 8\"}}," "\"required\":[\"target\"]}", t_alpn_probe }, + { "sni_vhost_check", + "Connect once per name with openssl s_client -servername and compare the " + "certificate subject, SAN and SHA-256 fingerprint. Different " + "certificates for one address mean SNI virtual hosts. All names must be " + "in scope. Gate: target and every name.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"names\":{\"type\":\"string\",\"description\":\"comma list, max 8\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}}," + "\"required\":[\"target\",\"names\"]}", + t_sni_vhost_check }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 739c8e6..1ba3945 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 = 183 +EXPECTED_TOOLS = 187 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 98f99af..6404d8f 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("183 tools registered", len(tools) == 183, len(tools)) +check("187 tools registered", len(tools) == 187, 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"]) == 183) + check("http tools/list", len(listing["result"]["tools"]) == 187) 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 @@ -8257,6 +8257,201 @@ shutil.rmtree(pf_root, ignore_errors=True) shutil.rmtree(pf_good_root, ignore_errors=True) shutil.rmtree(cfg8_home, ignore_errors=True) +print("\n== kubelet, etcd, RabbitMQ and SNI ==\n") + +kl_root = tempfile.mkdtemp(prefix="apex-kl-") +os.makedirs(os.path.join(kl_root, "var", "lib", "kubelet")) +kl_bad = os.path.join(kl_root, "var", "lib", "kubelet", "config.yaml") +with open(kl_bad, "w") as f: + f.write("anonymous:\n enabled: true\n") + f.write("authorization:\n mode: AlwaysAllow\n") + f.write("readOnlyPort: 10255\n") +os.chmod(kl_bad, 0o666) +kl_good_root = tempfile.mkdtemp(prefix="apex-klg-") +os.makedirs(os.path.join(kl_good_root, "var", "lib", "kubelet")) +with open(os.path.join(kl_good_root, "var", "lib", "kubelet", + "config.yaml"), "w") as f: + f.write("anonymous:\n enabled: false\n") + f.write("authorization:\n mode: Webhook\n") + f.write("readOnlyPort: 0\n") + +et_root = tempfile.mkdtemp(prefix="apex-et-") +os.makedirs(os.path.join(et_root, "etc", "etcd")) +et_bad = os.path.join(et_root, "etc", "etcd", "etcd.conf.yml") +with open(et_bad, "w") as f: + f.write("listen-client-urls: http://0.0.0.0:2379\n") + f.write("client-cert-auth: false\n") + f.write("peer-cert-auth: false\n") + f.write("auto-tls: true\n") +os.chmod(et_bad, 0o666) +et_good_root = tempfile.mkdtemp(prefix="apex-etg-") +os.makedirs(os.path.join(et_good_root, "etc", "etcd")) +with open(os.path.join(et_good_root, "etc", "etcd", "etcd.conf.yml"), + "w") as f: + f.write("listen-client-urls: https://127.0.0.1:2379\n") + f.write("client-cert-auth: true\n") + f.write("peer-cert-auth: true\n") + f.write("auto-tls: false\n") + +rb_root = tempfile.mkdtemp(prefix="apex-rb-") +os.makedirs(os.path.join(rb_root, "etc", "rabbitmq")) +rb_bad = os.path.join(rb_root, "etc", "rabbitmq", "rabbitmq.conf") +with open(rb_bad, "w") as f: + f.write("loopback_users.guest = false\n") + f.write("default_user = guest\n") + f.write("default_pass = guest\n") + f.write("management.tcp.port = 15672\n") +os.chmod(rb_bad, 0o666) +rb_good_root = tempfile.mkdtemp(prefix="apex-rbg-") +os.makedirs(os.path.join(rb_good_root, "etc", "rabbitmq")) +with open(os.path.join(rb_good_root, "etc", "rabbitmq", "rabbitmq.conf"), + "w") as f: + f.write("loopback_users.guest = true\n") + f.write("default_user = admin\n") + f.write("default_pass = strong-secret\n") + f.write("management.ssl.port = 15671\n") + +sni_dir = tempfile.mkdtemp(prefix="apex-sni-") + + +def make_cert(name): + cert = os.path.join(sni_dir, name + ".pem") + key = os.path.join(sni_dir, name + ".key") + subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", + "-nodes", "-keyout", key, "-out", cert, "-days", "2", + "-subj", "/CN=" + name, + "-addext", "subjectAltName=DNS:" + name], + check=True, capture_output=True) + return cert, key + + +sni_cert_a, sni_key_a = make_cert("a.test") +sni_cert_b, sni_key_b = make_cert("b.test") + + +def sni_server(cert_a, key_a, cert_b, key_b): + ctx_a = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx_a.load_cert_chain(cert_a, key_a) + ctx_b = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx_b.load_cert_chain(cert_b, key_b) + + def cb(sslobj, servername, _ctx): + if servername == "b.test": + sslobj.context = ctx_b + return None + + ctx_a.set_servername_callback(cb) + 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] + + def loop(): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + try: + tls = ctx_a.wrap_socket(conn, server_side=True) + try: + tls.recv(1) + except OSError: + pass + tls.close() + except (ssl.SSLError, OSError): + conn.close() + + threading.Thread(target=loop, daemon=True).start() + return srv, port + + +sni_srv, sni_port = sni_server(sni_cert_a, sni_key_a, sni_cert_b, sni_key_b) + +cfg9_home = tempfile.mkdtemp(prefix="apex-cfg9-home-") +write_scope(cfg9_home, {"label": "cfg9", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_domain": ["a.test", "b.test"], + "allow_port": [str(sni_port)]}) +res, _ = run([ + call(1, "kubelet_config_audit", root=kl_root), + call(2, "kubelet_config_audit", root=kl_good_root), + call(3, "etcd_config_audit", root=et_root), + call(4, "etcd_config_audit", root=et_good_root), + call(5, "rabbitmq_audit", root=rb_root), + call(6, "rabbitmq_audit", root=rb_good_root), + call(7, "sni_vhost_check", target="127.0.0.1", names="a.test,b.test", + port=sni_port), + call(8, "sni_vhost_check", target="127.0.0.1", names="a.test", + port=sni_port), + call(9, "kubelet_config_audit", root="/nonexistent-kl"), + call(10, "etcd_config_audit", root="/nonexistent-et"), + call(11, "rabbitmq_audit", root="/nonexistent-rb"), + call(12, "sni_vhost_check", target="127.0.0.1", names="evil.test", + port=sni_port), +], home=cfg9_home) +by_id = {r.get("id"): r for r in res} +kl = json.loads(text(by_id[1])) +kl_kinds = {f["id"] for f in kl["findings"]} +check("kubelet_config_audit flags anonymous, AlwaysAllow and readOnlyPort", + {"world-writable", "anonymous-auth", "always-allow", + "readonly-port"} <= kl_kinds and kl["read_only_port"] == 10255, kl) +kl_good = json.loads(text(by_id[2])) +check("kubelet_config_audit accepts a hardened config", + kl_good["findings_count"] == 0 and kl_good["anonymous"] is False and + kl_good["read_only_port"] == 0, kl_good) +et = json.loads(text(by_id[3])) +et_kinds = {f["id"] for f in et["findings"]} +check("etcd_config_audit flags open URLs and missing cert auth", + {"world-writable", "client-urls-open", "client-cert-auth-off", + "peer-cert-auth-off", "auto-tls"} <= et_kinds, et) +et_good = json.loads(text(by_id[4])) +check("etcd_config_audit accepts a hardened config", + et_good["findings_count"] == 0 and + et_good["client_cert_auth"] is True and + et_good["peer_cert_auth"] is True, et_good) +rb = json.loads(text(by_id[5])) +rb_kinds = {f["id"] for f in rb["findings"]} +check("rabbitmq_audit flags guest, loopback and management TLS", + {"world-writable", "loopback-removed", "default-guest", + "management-no-tls"} <= rb_kinds, rb) +rb_good = json.loads(text(by_id[6])) +check("rabbitmq_audit accepts a hardened config", + rb_good["findings_count"] == 0 and + rb_good["default_guest"] is False and + rb_good["management_tls"] is True, rb_good) +sni = json.loads(text(by_id[7])) +certs = {e["name"]: e for e in sni["certificates"]} +check("sni_vhost_check sees two distinct certificates", + sni["distinct_certificates"] == 2 and sni["sni_vhosts"] is True, sni) +check("sni_vhost_check reports each subject and SAN", + "a.test" in certs["a.test"]["subject"] and + "a.test" in certs["a.test"]["san"] and + "b.test" in certs["b.test"]["subject"] and + certs["a.test"]["fingerprint"] != certs["b.test"]["fingerprint"], certs) +sni_one = json.loads(text(by_id[8])) +check("sni_vhost_check reports a single certificate", + sni_one["distinct_certificates"] == 1 and + sni_one["sni_vhosts"] is False, sni_one) +check("kubelet_config_audit reports a missing config", err(by_id[9]), + text(by_id[9])) +check("etcd_config_audit reports a missing config", err(by_id[10]), + text(by_id[10])) +check("rabbitmq_audit reports a missing config", err(by_id[11]), + text(by_id[11])) +check("sni_vhost_check refuses an out-of-scope name", err(by_id[12]), + text(by_id[12])) +sni_srv.close() +shutil.rmtree(kl_root, ignore_errors=True) +shutil.rmtree(kl_good_root, ignore_errors=True) +shutil.rmtree(et_root, ignore_errors=True) +shutil.rmtree(et_good_root, ignore_errors=True) +shutil.rmtree(rb_root, ignore_errors=True) +shutil.rmtree(rb_good_root, ignore_errors=True) +shutil.rmtree(sni_dir, ignore_errors=True) +shutil.rmtree(cfg9_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"})