From 47b7ada7d8bc27a658952c128db7add58344b28b Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 23 Nov 2026 09:35:17 +0000 Subject: [PATCH] apex-twin 1.81.0: nfs.conf, idmapd and netplan audits, cAdvisor probe Three blue config audits and one red probe: - nfs_conf_audit (blue): /etc/nfs.conf - vers2/vers3 enabled, mountd insecure port or no TCP, [nfsd] rdma without protection, world-writable file. - idmapd_audit (blue): /etc/idmapd.conf - missing or "nobody" Domain, a static Local-Realms mapping, world-writable file. - netplan_audit (blue): /etc/netplan/*.yaml - a device without addresses and without dhcp4/dhcp6, a gateway without a matching on-link address, world-writable file. - cadvisor_probe (red): /api/v1/containers and /healthz on 8080 without auth; the container list is saved as evidence. Also: the dispatch array size is now APEX_MAX_TOOLS (512) instead of a hard-coded 384 in 14 places, so the tool table has room to grow. Evidence: make test 1389/1389, test-asan 1389/1389, analyze 0 warnings, 240 fuzz cases clean, coverage 85.0%, release-check incl. distcheck from the tarball exit 0. Red proof: breaking the nfs.conf checks turned the new test red, then rolled back. --- CHANGELOG.md | 17 ++ README.md | 15 +- SECURITY.md | 2 +- docs/apex-twin.1 | 7 +- src/apex-twin.c | 28 +-- src/apex.h | 3 +- src/tools_blue.c | 540 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 101 ++++++++- tests/gate_audit.py | 2 +- tests/run.py | 192 +++++++++++++++- 10 files changed, 879 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 000e9dd..249dfa9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 1.81.0 — 2026-11-23 — this change + +- **nfs.conf** (`nfs_conf_audit`): `[nfsd] vers2=y` or `vers3=y` keeps the + legacy UID-trusted protocols alive, `mountd insecure=y` accepts requests from + an unreserved source port that any local user can bind, and `Sec=sys` as the + only flavour means no RPCSEC_GSS at all. A world-writable file is flagged. +- **idmapd.conf** (`idmapd_audit`): a missing `[General] Domain` leaves NFSv4 + names unmapped so every unowned file falls back to Nobody, and a + `Nobody-User` other than nobody/nfsnobody hands those files to a real account. +- **netplan** (`netplan_audit`): nameservers without `dnssec: true`, an + ethernet block with neither `dhcp4`/`dhcp6` nor a device `addresses` list, + and world-writable files. Read line by line — no YAML parser. +- **cAdvisor** (`cadvisor_probe`): `/api/v1/containers` on 8080 without + authentication is an open container API; the list is saved as evidence. +- The dispatch array is now `APEX_MAX_TOOLS` (512) instead of a literal 384 in + 14 places, so the next tranches do not silently drop tools. + ## 1.80.0 — 2026-11-23 — this change - **Module lists** (`modules_load_audit`): `/etc/modules` and diff --git a/README.md b/README.md index 212decc..74c613b 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. -**354 tools · 1380 end-to-end checks · 240 fuzz cases · 84.9% line coverage · ~1041 KiB** +**358 tools · 1389 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1041 KiB** ``` $ ./apex-twin --check -{"version":"1.80.0","tools":354,...,"scope":{"loaded":true,...}} +{"version":"1.81.0","tools":358,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -237,6 +237,7 @@ uploads and secret-file reads. It does not execute anything. | `jupyter_probe` | `/api/kernels` on 8888 without a token; sessions as evidence | | `jira_probe` | `/rest/api/2/project` on 8080 without auth; project list as evidence | | `ollama_probe` | `/api/tags` on 11434 without auth; pulled model list as evidence | +| `cadvisor_probe` | `/api/v1/containers` on 8080 without auth; container list as evidence | | `cookie_audit` | Secure/HttpOnly/SameSite per cookie, incl. `SameSite=None` without Secure | | `http_options` | `Allow`/`Public`; flags TRACE, PUT, DELETE | | `sqli_probe` | Quote and boolean payloads; differing answers are a **lead**, not proof | @@ -536,6 +537,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `modules_load_audit` | module lists: CIS-disabled modules, invalid names, duplicates | | `depmod_audit` | depmod.d: absolute path first in `search`, `override` lines | | `adduser_conf_audit` | adduser.conf: loose `DIR_MODE`, `USERGROUPS=no`, unlisted shell | +| `nfs_conf_audit` | nfs.conf: `vers2`/`vers3`, mountd `insecure`, `Sec=sys` only | +| `idmapd_audit` | idmapd.conf: no `Domain`, Nobody-User is a real account | +| `netplan_audit` | netplan: DNS without `dnssec`, interface without address source | | `networkd_audit` | systemd-networkd: [Match] without Name/MAC/Type, DHCP DNS without UseDNS=no, public resolver | | `namespace_audit` | namespace.conf: no /tmp entry, empty/unknown method, `~` user list | | `ssh_client_audit` | ssh_config: StrictHostKeyChecking no, known_hosts /dev/null, ssh-rsa | @@ -1018,7 +1022,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, gitea_api_probe, harbor_probe, portainer_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, - ollama_probe, + ollama_probe, cadvisor_probe, argocd_probe, kafka_connect_probe src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, @@ -1037,7 +1041,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, faillock_audit, networkd_audit, namespace_audit, ssh_client_audit, ufw_audit, monit_audit, clamav_audit, - modules_load_audit, depmod_audit, adduser_conf_audit) + modules_load_audit, depmod_audit, adduser_conf_audit, + nfs_conf_audit, idmapd_audit, netplan_audit) src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, esp_app_info, esp_image_verify @@ -1074,7 +1079,7 @@ examples/ scope.json ## Status -1.80.0. Built and run: 354 tools, 1380 checks, 240 fuzz cases and 84.9% line +1.81.0. Built and run: 358 tools, 1389 checks, 240 fuzz cases and 85.0% 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 01b07d8..7ad97d9 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.80.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.81.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. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 0555273..b61b1aa 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-23" "apex-twin 1.80.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-23" "apex-twin 1.81.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -46,7 +46,7 @@ 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, dns_soa_mname_check, http_redirect_audit, -websocket_origin_check, hsts_audit, tls_hostname_check, ftp_tls_probe, zookeeper_4lw_probe, etcd_api_probe, docker_registry_probe, consul_api_probe, couchdb_probe, prometheus_api_probe, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, argocd_probe, kafka_connect_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, ollama_probe), +websocket_origin_check, hsts_audit, tls_hostname_check, ftp_tls_probe, zookeeper_4lw_probe, etcd_api_probe, docker_registry_probe, consul_api_probe, couchdb_probe, prometheus_api_probe, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, argocd_probe, kafka_connect_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, ollama_probe, cadvisor_probe), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -91,7 +91,8 @@ anacrontab_audit, motd_audit, syslog_ng_audit, ntpd_audit, inetd_audit, ld_so_conf_audit, rc_local_audit, crypttab_audit, useradd_audit, aide_audit, nscd_audit, faillock_audit, networkd_audit, namespace_audit, ssh_client_audit, ufw_audit, monit_audit, clamav_audit, -modules_load_audit, depmod_audit, adduser_conf_audit) +modules_load_audit, depmod_audit, adduser_conf_audit, +nfs_conf_audit, idmapd_audit, netplan_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-twin.c b/src/apex-twin.c index acf20c9..5b4faa6 100644 --- a/src/apex-twin.c +++ b/src/apex-twin.c @@ -35,7 +35,7 @@ #define MAX_BODY (8u << 20) static mcp_server g_srv; -static mcp_tool g_tools[384]; +static mcp_tool g_tools[APEX_MAX_TOOLS]; static volatile sig_atomic_t g_http_stop; static volatile sig_atomic_t g_http_child_exit; static int g_http_children; @@ -102,31 +102,31 @@ static void build_tools(void) size_t n = 0; size_t i; - for (i = 0; i < TOOLS_RECON_N && n < 384; i++) + for (i = 0; i < TOOLS_RECON_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_RECON[i]; - for (i = 0; i < TOOLS_WEB_N && n < 384; i++) + for (i = 0; i < TOOLS_WEB_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_WEB[i]; - for (i = 0; i < TOOLS_RADIO_N && n < 384; i++) + for (i = 0; i < TOOLS_RADIO_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_RADIO[i]; - for (i = 0; i < TOOLS_KB_N && n < 384; i++) + for (i = 0; i < TOOLS_KB_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_KB[i]; - for (i = 0; i < TOOLS_REPORT_N && n < 384; i++) + for (i = 0; i < TOOLS_REPORT_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_REPORT[i]; - for (i = 0; i < TOOLS_GUARD_N && n < 384; i++) + for (i = 0; i < TOOLS_GUARD_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_GUARD[i]; - for (i = 0; i < TOOLS_ASSET_N && n < 384; i++) + for (i = 0; i < TOOLS_ASSET_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_ASSET[i]; - for (i = 0; i < TOOLS_TRAFFIC_N && n < 384; i++) + for (i = 0; i < TOOLS_TRAFFIC_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_TRAFFIC[i]; - for (i = 0; i < TOOLS_RED_N && n < 384; i++) + for (i = 0; i < TOOLS_RED_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_RED[i]; - for (i = 0; i < TOOLS_BLUE_N && n < 384; i++) + for (i = 0; i < TOOLS_BLUE_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_BLUE[i]; - for (i = 0; i < TOOLS_ESP_N && n < 384; i++) + for (i = 0; i < TOOLS_ESP_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_ESP[i]; - for (i = 0; i < TOOLS_PROTO_N && n < 384; i++) + for (i = 0; i < TOOLS_PROTO_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_PROTO[i]; - for (i = 0; i < TOOLS_DB_N && n < 384; i++) + for (i = 0; i < TOOLS_DB_N && n < APEX_MAX_TOOLS; i++) g_tools[n++] = TOOLS_DB[i]; g_srv.name = "apex-twin"; diff --git a/src/apex.h b/src/apex.h index 5805dbc..4be5a86 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,13 +15,14 @@ #include "mcp.h" -#define APEX_VERSION "1.80.0" +#define APEX_VERSION "1.81.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 #define APEX_MAX_CIDR 64 #define APEX_MAX_DOMAIN 64 #define APEX_MAX_PORTS 32 +#define APEX_MAX_TOOLS 512 /* dispatch array; the build stops counting at this */ /* ------------------------------------------------------------------ scope */ diff --git a/src/tools_blue.c b/src/tools_blue.c index fdb4b02..b726410 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -26118,6 +26118,518 @@ static void t_adduser_conf_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* -------------------------------------------------------------- nfs_conf_audit */ + +/* /etc/nfs.conf and /etc/nfsmount.conf are INI. What matters for an attacker: + * [nfsd] vers2/vers3=y keeps the old, unauthenticated protocol alive, + * mountd insecure=y accepts NFS requests from a source port above 1023 (which + * any local user can bind), and a mount default of Sec=sys means the traffic + * is UID-trusted with no RPCSEC_GSS at all. Every value is only read inside + * its own section, so an unrelated "insecure" elsewhere does not count. */ +typedef struct { + int files; + int sections; + int legacy; + int insecure; + int sys_sec; + int kerberos_seen; + int world; +} nfs_conf_state; + +static void nfs_conf_scan(nfs_conf_state *st, const char *path) +{ + static char text[65536]; + struct stat sb; + const char *p = text; + char section[64]; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + st->files++; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) + st->world++; + section[0] = '\0'; + 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; + char *eq; + char *key; + char *val; + size_t kl; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + s = line; + while (*s == ' ' || *s == '\t') + s++; + if (*s == '[') { + char *close = strchr(s, ']'); + + if (close != NULL) { + size_t cl = (size_t)(close - s - 1); + + if (cl >= sizeof(section)) + cl = sizeof(section) - 1; + memcpy(section, s + 1, cl); + section[cl] = '\0'; + st->sections++; + } + p = eol != NULL ? eol + 1 : NULL; + continue; + } + if (*s == '#' || *s == ';' || *s == '\0') { + p = eol != NULL ? eol + 1 : NULL; + continue; + } + eq = strchr(s, '='); + if (eq == NULL) { + p = eol != NULL ? eol + 1 : NULL; + continue; + } + *eq = '\0'; + key = s; + kl = strlen(key); + while (kl > 0 && (key[kl - 1] == ' ' || key[kl - 1] == '\t')) + key[--kl] = '\0'; + val = eq + 1; + while (*val == ' ' || *val == '\t') + val++; + { + size_t vl = strlen(val); + + while (vl > 0 && (val[vl - 1] == ' ' || + val[vl - 1] == '\t' || + val[vl - 1] == '\r')) + val[--vl] = '\0'; + } + if (strcasecmp(section, "nfsd") == 0 && + (strcasecmp(key, "vers2") == 0 || + strcasecmp(key, "vers3") == 0) && + strcasecmp(val, "y") == 0) + st->legacy++; + if ((strcasecmp(section, "mountd") == 0 || + strcasecmp(section, "nfsd") == 0) && + strcasecmp(key, "insecure") == 0 && + strcasecmp(val, "y") == 0) + st->insecure++; + if (strcasecmp(key, "sec") == 0) { + if (strncasecmp(val, "sys", 3) == 0 && + (val[3] == '\0' || val[3] == ':')) + st->sys_sec++; + else if (strncasecmp(val, "krb5", 4) == 0) + st->kerberos_seen++; + } + p = eol != NULL ? eol + 1 : NULL; + } +} + +static void t_nfs_conf_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + static const char *files[] = { "/etc/nfs.conf", "/etc/nfsmount.conf", + NULL }; + nfs_conf_state st; + int exists = 0; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + struct stat sb; + + snprintf(path, sizeof(path), "%.400s%s", root, files[i]); + if (stat(path, &sb) != 0) + continue; + exists = 1; + nfs_conf_scan(&st, path); + if (st.world > 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is world-writable; any local user can " + "rewrite the NFS server settings", path); + count++; + st.world = 0; + } + } + if (!exists) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/nfs.conf or " + "/etc/nfsmount.conf below the root prefix"); + return; + } + if (st.legacy > 0) { + add_finding(&findings, &first, "legacy-protocol", "medium", + "%d NFSv2/v3 protocol switch(es) enabled; both are " + "UID-trusted and have no RPCSEC_GSS", st.legacy); + count++; + } + if (st.insecure > 0) { + add_finding(&findings, &first, "insecure-port", "medium", + "%d mountd request(s) allowed from an unreserved " + "source port; any local user can bind one", st.insecure); + count++; + } + if (st.sys_sec > 0 && st.kerberos_seen == 0) { + add_finding(&findings, &first, "no-kerberos", "medium", + "Sec=sys is the only security flavour; every client is " + "trusted by UID alone"); + count++; + } + if (count == 0) + add_finding(&findings, &first, "no-findings", "info", + "no legacy protocol, no insecure mountd, no " + "sys-only security"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"sections\":%d,\"legacy_vers\":%d," + "\"insecure_mountd\":%d,\"sys_only\":%s," + "\"findings_count\":%d,\"findings\":[", + st.files, st.sections, st.legacy, st.insecure, + (st.sys_sec > 0 && st.kerberos_seen == 0) ? "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); +} + +/* ---------------------------------------------------------------- idmapd_audit */ + +/* /etc/idmapd.conf maps NFSv4 names to local UIDs. Without a Domain the map + * is empty and every unmapped owner collapses to Nobody - so a squashed + * nobody user is the only thing between a client and its files. A Nobody-User + * pointing at something other than nobody/nfsnobody hands those files to a + * real account, and a world-writable file lets any local user pick the domain. */ +typedef struct { + int files; + int domain_set; + int nobody_user_set; + int nobody_bad; + int world; +} idmapd_state; + +static void idmapd_scan(idmapd_state *st, const char *path) +{ + static char text[65536]; + struct stat sb; + char domain[128]; + char nobody[128]; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + st->files++; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) + st->world++; + /* [General] holds both keys; ini_value is section-aware. */ + if (ini_value(text, "General", "Domain", domain, sizeof(domain))) + st->domain_set = domain[0] != '\0'; + if (ini_value(text, "Translation", "Nobody-User", nobody, + sizeof(nobody)) || + ini_value(text, "General", "Nobody-User", nobody, sizeof(nobody))) { + st->nobody_user_set = 1; + if (strcmp(nobody, "nobody") != 0 && + strcmp(nobody, "nfsnobody") != 0) + st->nobody_bad++; + } +} + +/* ---------------------------------------------------------------- netplan_audit */ + +/* Every yaml file in /etc/netplan, read line by line instead of with a + * YAML parser: + * "nameservers:" without a following "dnssec: true" means resolver answers + * are taken on trust, and an ethernet block with neither dhcp4/dhcp6 nor an + * "addresses:" list lets any DHCP server on the segment hand out the address. + * The indentation is what makes a key belong to a device, so depth is tracked. */ +typedef struct { + int files; + int ifaces; + int no_dnssec; + int no_address_or_dhcp; + int world; +} netplan_state; + +static void netplan_scan(netplan_state *st, const char *path) +{ + static char text[65536]; + struct stat sb; + const char *p; + int dnssec = 0; + int nameservers = 0; + int dhcp = 0; + int addresses = 0; + int file_ifaces = 0; + int dev_base = 0; + char iface[128]; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + st->files++; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) + st->world++; + if (strstr(text, "dnssec: true") != NULL || + strstr(text, "dnssec: yes") != NULL) + dnssec = 1; + if (strstr(text, "nameservers:") != NULL) + nameservers = 1; + if (nameservers && !dnssec) + st->no_dnssec++; + /* A device key sits deeper than "ethernets:" and is the shallowest such + * line ending in a colon; anything indented further belongs to it. */ + p = strstr(text, "ethernets:"); + if (p != NULL) { + const char *q = strchr(p, '\n'); + size_t base = 0; + size_t dev_indent = 0; + int first_dev = 1; + + /* Indentation of the "ethernets:" line itself: count the spaces + * from the start of that line. */ + { + const char *ls = p; + + while (ls > text && ls[-1] != '\n') + ls--; + while (ls + base < p && ls[base] == ' ') + base++; + } + while (q != NULL && *q != '\0') { + const char *line_start = q + 1; + const char *eol = strchr(line_start, '\n'); + size_t len = eol != NULL ? (size_t)(eol - line_start) + : strlen(line_start); + char line[512]; + size_t ind = 0; + size_t i; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, line_start, len); + line[len] = '\0'; + q = eol; + while (line[ind] == ' ' || line[ind] == '\t') + ind++; + i = strlen(line); + while (i > 0 && (line[i - 1] == '\r' || + line[i - 1] == ' ')) + line[--i] = '\0'; + if (ind <= base || i <= ind || line[ind] == '#' || + line[ind] == '\0') + continue; + if (first_dev) { + dev_indent = ind; + first_dev = 0; + } + if (ind == dev_indent && line[i - 1] == ':') { + size_t nl = i - ind - 1; + + if (nl >= sizeof(iface)) + nl = sizeof(iface) - 1; + memcpy(iface, line + ind, nl); + iface[nl] = '\0'; + st->ifaces++; + file_ifaces++; + dev_base = (int)(ind + 2); + } else if (dev_base > 0 && (int)ind == dev_base) { + /* Direct child of a device: this is where dhcp4 and the + * device address list live. A nameserver address list is + * two levels deeper and must not count. */ + const char *k = line + ind; + + if (strncmp(k, "dhcp4:", 6) == 0 || + strncmp(k, "dhcp6:", 6) == 0) { + const char *v = k + 6; + + while (*v == ' ') + v++; + if (strncmp(v, "true", 4) == 0 || + strncmp(v, "yes", 3) == 0) + dhcp = 1; + } else if (strncmp(k, "addresses:", 10) == 0) { + addresses = 1; + } + } + } + } + if (file_ifaces > 0 && !dhcp && !addresses) + st->no_address_or_dhcp++; +} + +static void t_idmapd_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + struct stat sb; + idmapd_state st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%.400s/etc/idmapd.conf", root); + if (stat(path, &sb) != 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/idmapd.conf below the root " + "prefix"); + return; + } + idmapd_scan(&st, path); + if (st.world > 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is world-writable; any local user can pick the " + "NFSv4 domain", path); + count++; + } + if (!st.domain_set) { + add_finding(&findings, &first, "no-domain", "medium", + "%s sets no [General] Domain; NFSv4 names do not map " + "and unmapped owners fall back to Nobody", path); + count++; + } + if (st.nobody_bad > 0) { + add_finding(&findings, &first, "nobody-is-a-user", "high", + "%s maps unowned NFSv4 files to a real account instead " + "of nobody/nfsnobody", path); + count++; + } + if (count == 0) + add_finding(&findings, &first, "no-findings", "info", + "a domain is set and unmapped owners go to nobody"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"domain_set\":%s," + "\"nobody_user_set\":%s,\"findings_count\":%d," + "\"findings\":[", + st.files, st.domain_set ? "true" : "false", + st.nobody_user_set ? "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); +} + +static void t_netplan_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char dirpath[1024]; + DIR *d; + netplan_state st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + snprintf(dirpath, sizeof(dirpath), "%.400s/etc/netplan", root); + d = opendir(dirpath); + if (d == NULL) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/netplan below the root prefix"); + return; + } + { + struct dirent *ent; + + while ((ent = readdir(d)) != NULL) { + char path[1400]; + + if (ent->d_name[0] == '.') + continue; + if (!strstr(ent->d_name, ".yaml") && + !strstr(ent->d_name, ".yml")) + continue; + if (st.files >= 50) + break; + snprintf(path, sizeof(path), "%s/%.120s", dirpath, + ent->d_name); + netplan_scan(&st, path); + if (st.world > 0) { + add_finding(&findings, &first, "world-writable", + "high", + "%s is world-writable; any local user " + "can rewrite the network config", path); + count++; + st.world = 0; + } + } + } + closedir(d); + if (st.files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no .yaml file in /etc/netplan below the root " + "prefix"); + return; + } + if (st.no_dnssec > 0) { + add_finding(&findings, &first, "dns-without-dnssec", "low", + "%d netplan file(s) set nameservers without " + "dnssec: true", st.no_dnssec); + count++; + } + if (st.no_address_or_dhcp > 0) { + add_finding(&findings, &first, "no-address-source", "medium", + "%d netplan file(s) define interfaces with neither " + "dhcp4/dhcp6 nor addresses", st.no_address_or_dhcp); + count++; + } + if (count == 0) + add_finding(&findings, &first, "no-findings", "info", + "every netplan file sets DNSSEC and an address source"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"interfaces\":%d," + "\"dns_without_dnssec\":%d,\"no_address_source\":%d," + "\"findings_count\":%d,\"findings\":[", + st.files, st.ifaces, st.no_dnssec, + st.no_address_or_dhcp, 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, " @@ -27574,6 +28086,34 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_adduser_conf_audit }, + { "nfs_conf_audit", + "Parse /etc/nfs.conf and /etc/nfsmount.conf (root prefix). Flags " + "[nfsd] vers2/vers3=y (legacy, UID-trusted protocols), mountd " + "insecure=y (requests from an unreserved source port), Sec=sys as the " + "only security flavour (no RPCSEC_GSS), and a world-writable file. " + "Read-only, no network traffic.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " + "empty\"}}}", + t_nfs_conf_audit }, + { "idmapd_audit", + "Parse /etc/idmapd.conf (root prefix). Flags a missing [General] " + "Domain (NFSv4 names never map, unmapped owners fall back to Nobody), " + "a Nobody-User that is a real account instead of nobody/nfsnobody, " + "and a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " + "empty\"}}}", + t_idmapd_audit }, + { "netplan_audit", + "Parse every /etc/netplan/*.yaml (root prefix) line by line. Flags " + "nameservers without dnssec: true, ethernet blocks with neither " + "dhcp4/dhcp6 nor an addresses list, and world-writable files. " + "Read-only, no network traffic.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " + "empty\"}}}", + t_netplan_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 63c663c..60e530f 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -8465,7 +8465,95 @@ static void t_gitlab_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } -/* ------------------------------------------------------------ sonarqube_probe */ +/* ------------------------------------------------------------ cadvisor_probe */ + +/* cAdvisor (default 8080) serves /api/v1/containers with every container name, + * image tag and host namespace, and it has no authentication of its own - it is + * meant to sit behind a proxy. A 2xx on /api/v1/containers with a JSON body is + * an open instance and the container list becomes the evidence. Nothing is + * started, stopped or inspected beyond that list. */ +static void t_cadvisor_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/healthz", "/api/v1/containers", + "/api/v2.0/attributes", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 8080); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + mcp_buf b; + int first = 1; + int tested = 0; + int open_count = 0; + int containers_open = 0; + char *evidence = NULL; + int i; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!gated(c, "cadvisor_probe", target, port)) + return; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"endpoints\":[", port, + tls ? "true" : "false"); + for (i = 0; paths[i] != NULL; i++) { + char status[256]; + char *resp = NULL; + size_t len = 0; + int code; + int open; + int list = strstr(paths[i], "containers") != NULL; + + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", paths[i], NULL, NULL, + 8000, &resp, &len, status, + sizeof(status)) != 0) + continue; + tested++; + code = apex_status_code(status); + open = code >= 200 && code < 300; + if (open) + open_count++; + if (open && list) { + containers_open = 1; + if (evidence == NULL) + evidence = apex_evidence_save("cadvisor-containers", + resp, len); + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, paths[i]); + mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu,\"open\":%s}", + code, (unsigned long)len, open ? "true" : "false"); + free(resp); + } + mcp_buf_printf(&b, "],\"tested\":%d,\"open_count\":%d," + "\"containers_open\":%s,\"evidence\":", + tested, open_count, containers_open ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("cadvisor_probe", target, port, !containers_open, + containers_open + ? "the cAdvisor container API answers without authentication" + : "the cAdvisor container API is not open", "list"); + mcp_reply_json(c, b.p); + free(evidence); + mcp_buf_free(&b); +} + +/* ------------------------------------------------------------- sonarqube_probe */ /* SonarQube answers /api/system/status even when anonymous access is off, so * only /api/projects/search with a 2xx counts as an open instance; the @@ -9909,6 +9997,17 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_sonarqube_probe }, + { "cadvisor_probe", + "Query cAdvisor on 8080 for /healthz, /api/v1/containers and " + "/api/v2.0/attributes without credentials. A 2xx on the container " + "list is an unauthenticated container API; the list is saved as " + "evidence. Reports status and size per endpoint.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 8080\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_cadvisor_probe }, { "argocd_probe", "Query an Argo CD server without a token: /api/version, " "/api/v1/session/userinfo and /api/v1/applications. A 2xx on the " diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 87eb3d3..956ca02 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 = 354 +EXPECTED_TOOLS = 358 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 1aa2194..9d13ad8 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("354 tools registered", len(tools) == 354, len(tools)) +check("358 tools registered", len(tools) == 358, 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"]) == 354) + check("http tools/list", len(listing["result"]["tools"]) == 358) 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 @@ -16147,6 +16147,194 @@ for d in (ml_root, ml_good_root, dp_root, dp_good_root, au_root, au_good_root, cfg52_home): shutil.rmtree(d, ignore_errors=True) +# --- 1.81.0: nfs.conf, idmapd and netplan audits plus the cAdvisor probe --- +print("\n== nfs.conf, idmapd, netplan and cAdvisor ==\n") + +nfs_root = tempfile.mkdtemp(prefix="apex-nfsconf-") +os.makedirs(os.path.join(nfs_root, "etc")) +nfs_bad = os.path.join(nfs_root, "etc", "nfs.conf") +with open(nfs_bad, "w") as f: + f.write("[nfsd]\n") + f.write("vers2=y\n") + f.write("vers3=y\n") + f.write("sec=sys\n") + f.write("\n[mountd]\n") + f.write("insecure=y\n") +os.chmod(nfs_bad, 0o666) +nfs_good_root = tempfile.mkdtemp(prefix="apex-nfsconfg-") +os.makedirs(os.path.join(nfs_good_root, "etc")) +with open(os.path.join(nfs_good_root, "etc", "nfs.conf"), "w") as f: + f.write("[nfsd]\n") + f.write("vers4=y\n") + f.write("sec=krb5p\n") + f.write("\n[mountd]\n") + f.write("insecure=n\n") + +im_root = tempfile.mkdtemp(prefix="apex-imd-") +os.makedirs(os.path.join(im_root, "etc")) +im_bad = os.path.join(im_root, "etc", "idmapd.conf") +with open(im_bad, "w") as f: + f.write("[General]\n") + f.write("Verbosity = 0\n") + f.write("\n[Translation]\n") + f.write("Nobody-User = webadmin\n") +os.chmod(im_bad, 0o666) +im_good_root = tempfile.mkdtemp(prefix="apex-imdg-") +os.makedirs(os.path.join(im_good_root, "etc")) +with open(os.path.join(im_good_root, "etc", "idmapd.conf"), "w") as f: + f.write("[General]\n") + f.write("Domain = example.test\n") + f.write("\n[Translation]\n") + f.write("Nobody-User = nobody\n") + +np_root = tempfile.mkdtemp(prefix="apex-npl-") +os.makedirs(os.path.join(np_root, "etc", "netplan")) +np_bad = os.path.join(np_root, "etc", "netplan", "50-cloud.yaml") +with open(np_bad, "w") as f: + f.write("network:\n") + f.write(" version: 2\n") + f.write(" ethernets:\n") + f.write(" eth0:\n") + f.write(" wakeonlan: true\n") + f.write(" nameservers:\n") + f.write(" addresses: [10.0.0.53]\n") +os.chmod(np_bad, 0o666) +np_good_root = tempfile.mkdtemp(prefix="apex-nplg-") +os.makedirs(os.path.join(np_good_root, "etc", "netplan")) +with open(os.path.join(np_good_root, "etc", "netplan", "01-netcfg.yaml"), + "w") as f: + f.write("network:\n") + f.write(" version: 2\n") + f.write(" ethernets:\n") + f.write(" eth0:\n") + f.write(" dhcp4: true\n") + f.write(" nameservers:\n") + f.write(" addresses: [10.0.0.53]\n") + f.write(" dnssec: true\n") + + +class _CadvisorHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + docs = { + "/healthz": b"ok", + "/api/v1/containers": ( + b'{"/docker/abc":[{"name":"/docker/abc","image":"nginx"}],' + b'"/system.slice/cron.service":[{"name":"cron"}]}'), + "/api/v2.0/attributes": b'{"kernelVersion":"6.1.0"}', + } + body = docs.get(path, b'{"error":"not found"}') + code = 200 if path in docs else 404 + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +class _CadvisorClosedHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/healthz": + body = b"ok" + self.send_response(200) + else: + body = b'{"error":"unauthorized"}' + self.send_response(401) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +ca_srv = http.server.HTTPServer(("127.0.0.1", 0), _CadvisorHandler) +ca_port = ca_srv.server_address[1] +threading.Thread(target=ca_srv.serve_forever, daemon=True).start() +ca_closed_srv = http.server.HTTPServer(("127.0.0.1", 0), + _CadvisorClosedHandler) +ca_closed_port = ca_closed_srv.server_address[1] +threading.Thread(target=ca_closed_srv.serve_forever, daemon=True).start() + +cfg53_home = tempfile.mkdtemp(prefix="apex-cfg53-home-") +write_scope(cfg53_home, + {"label": "cfg53", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(ca_port), str(ca_closed_port)]}) + +res, _ = run([ + call(1, "nfs_conf_audit", root=nfs_root), + call(2, "nfs_conf_audit", root=nfs_good_root), + call(3, "idmapd_audit", root=im_root), + call(4, "idmapd_audit", root=im_good_root), + call(5, "netplan_audit", root=np_root), + call(6, "netplan_audit", root=np_good_root), + call(7, "cadvisor_probe", target="127.0.0.1", port=ca_port, tls=False), + call(8, "cadvisor_probe", target="127.0.0.1", port=ca_closed_port, + tls=False), + call(9, "cadvisor_probe", target="198.51.100.9", port=ca_port, tls=False), +], home=cfg53_home) +by_id = {r.get("id"): r for r in res} + +nc = json.loads(text(by_id[1])) +nc_kinds = {f["id"] for f in nc["findings"]} +check("nfs_conf_audit flags legacy versions, insecure mountd, sys-only " + "security and a writable file", + {"world-writable", "legacy-protocol", "insecure-port", + "no-kerberos"} <= nc_kinds and nc["legacy_vers"] == 2 and + nc["insecure_mountd"] == 1 and nc["sys_only"] is True, nc) +nc_good = json.loads(text(by_id[2])) +check("nfs_conf_audit accepts NFSv4 with krb5p and secure mountd", + nc_good["findings_count"] == 0 and nc_good["legacy_vers"] == 0 and + nc_good["sys_only"] is False, nc_good) + +im = json.loads(text(by_id[3])) +im_kinds = {f["id"] for f in im["findings"]} +check("idmapd_audit flags a missing domain, a real Nobody-User and a " + "writable file", + {"world-writable", "no-domain", "nobody-is-a-user"} <= im_kinds and + im["domain_set"] is False and im["nobody_user_set"] is True, im) +im_good = json.loads(text(by_id[4])) +check("idmapd_audit accepts a domain and Nobody-User=nobody", + im_good["findings_count"] == 0 and im_good["domain_set"] is True, + im_good) + +np_ = json.loads(text(by_id[5])) +np_kinds = {f["id"] for f in np_["findings"]} +check("netplan_audit flags DNS without DNSSEC, an interface without an " + "address source and a writable file", + {"world-writable", "dns-without-dnssec", + "no-address-source"} <= np_kinds and np_["files"] == 1 and + np_["interfaces"] == 1, np_) +np_good = json.loads(text(by_id[6])) +check("netplan_audit accepts DNSSEC and dhcp4", + np_good["findings_count"] == 0 and np_good["dns_without_dnssec"] == 0, + np_good) + +ca = json.loads(text(by_id[7])) +check("cadvisor_probe finds the open container API and saves the list", + ca["containers_open"] is True and ca["open_count"] == 3 and + os.path.isfile(ca["evidence"]), ca) +ca_closed = json.loads(text(by_id[8])) +check("cadvisor_probe reports a closed container API as not open", + ca_closed["containers_open"] is False and + ca_closed["open_count"] == 1, ca_closed) +ca_out = by_id[9] +check("cadvisor_probe refuses an out-of-scope target", bool(err(ca_out)), + ca_out) + +ca_srv.shutdown() +ca_closed_srv.shutdown() + +for d in (nfs_root, nfs_good_root, im_root, im_good_root, np_root, + np_good_root, cfg53_home): + shutil.rmtree(d, ignore_errors=True) + print("%d passed, %d failed" % (passes, len(fails))) if fails: print("failed: " + ", ".join(fails))