From a975f596662535526736953634594cfe8da9ca34 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 23 Nov 2026 10:17:45 +0000 Subject: [PATCH] apex-twin 1.82.0: apt auth, aliases and netgroup audits, TeamCity probe Three blue config audits: - apt_auth_audit: /etc/apt/auth.conf(+.d) - credentials for a host reached over plain http:// and a group/world-readable or writable file. - aliases_audit: mail piped into a command, root mail forwarded to another local account, writable alias file. - netgroup_audit: member triple with an empty host field (NIS wildcard that matches every host), plus a writable netgroup file. One red probe: - teamcity_probe: /app/rest/projects and /app/rest/users on 8111 without a token; a 2xx list is saved as evidence. Verified: make test 1398/1398, test-asan 1398/1398, analyze 0 warnings (one real NULL-dereference report fixed in netgroup continuation handling), fuzz 240 cases, distcheck 1.82.0 from the tarball, coverage 85.0%. Red proof: renaming the root-forward finding id makes the aliases check fail, rolled back. --- CHANGELOG.md | 18 ++ README.md | 15 +- SECURITY.md | 2 +- docs/apex-twin.1 | 7 +- src/apex.h | 2 +- src/tools_blue.c | 496 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 101 +++++++++ tests/gate_audit.py | 2 +- tests/run.py | 175 +++++++++++++++- 9 files changed, 805 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 249dfa9..712df42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 1.82.0 - 2026-11-24 - this change + +- **apt auth** (`apt_auth_audit`): `/etc/apt/auth.conf` and + `auth.conf.d/*.conf`. A machine/login line whose host is reached over + plain `http://` sends the repository password in clear text, and a file + that is group- or world-readable (or writable) hands the credentials to + every local user. +- **aliases** (`aliases_audit`): an alias that pipes mail into a command + (the MTA runs it, often as a privileged user), root mail forwarded to + another local account, and a writable alias file that changes where all + mail goes. +- **netgroup** (`netgroup_audit`): a member triple with an empty host field + (`user,domain,`) matches every host in the domain - the classic NIS + wildcard that turns a host restriction into no restriction. +- **TeamCity** (`teamcity_probe`): `/app/rest/projects` and + `/app/rest/users` on 8111 without a token. A 2xx project or user list is + an unauthenticated CI API; the answer is saved as evidence. + ## 1.81.0 — 2026-11-23 — this change - **nfs.conf** (`nfs_conf_audit`): `[nfsd] vers2=y` or `vers3=y` keeps the diff --git a/README.md b/README.md index 74c613b..8fe212f 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. -**358 tools · 1389 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1041 KiB** +**362 tools · 1398 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1041 KiB** ``` $ ./apex-twin --check -{"version":"1.81.0","tools":358,...,"scope":{"loaded":true,...}} +{"version":"1.82.0","tools":362,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -238,6 +238,7 @@ uploads and secret-file reads. It does not execute anything. | `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 | +| `teamcity_probe` | `/app/rest/projects` and `/app/rest/users` without auth; project and user 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 | @@ -540,6 +541,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `apt_auth_audit` | apt auth.conf: credentials over plain HTTP, world-readable/writable file | +| `aliases_audit` | aliases: mail piped into a command, root mail forwarded to another account | +| `netgroup_audit` | netgroup: member with an empty host field (matches any host) | | `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 | @@ -1022,7 +1026,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, cadvisor_probe, + ollama_probe, cadvisor_probe, teamcity_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, @@ -1042,7 +1046,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, ssh_client_audit, ufw_audit, monit_audit, clamav_audit, modules_load_audit, depmod_audit, adduser_conf_audit, - nfs_conf_audit, idmapd_audit, netplan_audit) + nfs_conf_audit, idmapd_audit, netplan_audit, + apt_auth_audit, aliases_audit, netgroup_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 @@ -1079,7 +1084,7 @@ examples/ scope.json ## Status -1.81.0. Built and run: 358 tools, 1389 checks, 240 fuzz cases and 85.0% line +1.82.0. Built and run: 362 tools, 1398 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 7ad97d9..7bca694 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.81.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.82.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 b61b1aa..c8ec610 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.81.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.82.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, cadvisor_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, teamcity_probe), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -92,7 +92,8 @@ 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, -nfs_conf_audit, idmapd_audit, netplan_audit) +nfs_conf_audit, idmapd_audit, netplan_audit, +apt_auth_audit, aliases_audit, netgroup_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 4be5a86..b11d94a 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.81.0" +#define APEX_VERSION "1.82.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 b726410..182088d 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -26630,6 +26630,475 @@ static void t_netplan_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- apt_auth_audit */ + +/* /etc/apt/auth.conf and the *.conf files in auth.conf.d use the netrc + * grammar: + * "machine login password ". One machine line + * opens an entry; login/password belong to the entry above it. + * A machine value written with an http:// scheme ships the credentials in + * clear text, and a file any local user can read hands them out directly. */ +typedef struct { + int files; + int entries; + int plain_http; + int credentials; + int world_readable; + int world_writable; +} apt_auth_state; + +static void apt_auth_scan_file(apt_auth_state *st, const char *path) +{ + static char text[65536]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + st->files++; + if (stat(path, &sb) == 0) { + if ((sb.st_mode & 0002) != 0) + st->world_writable++; + if ((sb.st_mode & 0004) != 0 && (sb.st_mode & 0022) == 0) + st->world_readable++; + } + p = text; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[2048]; + char *tok[8]; + char *save = NULL; + char *word; + int n = 0; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + for (word = strtok_r(line, " \t\r", &save); word != NULL; + word = strtok_r(NULL, " \t\r", &save)) { + if (n < (int)(sizeof(tok) / sizeof(tok[0]))) + tok[n] = word; + n++; + } + if (n < 2) + continue; + if (strcmp(tok[0], "machine") == 0) { + st->entries++; + if (strncmp(tok[1], "http://", 7) == 0) + st->plain_http++; + } else if (strcmp(tok[0], "login") == 0 || + strcmp(tok[0], "password") == 0) { + st->credentials++; + } + } +} + +static void t_apt_auth_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1200]; + apt_auth_state st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + DIR *d; + + (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/apt/auth.conf", root); + apt_auth_scan_file(&st, path); + snprintf(path, sizeof(path), "%.400s/etc/apt/auth.conf.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, ".conf") != 0) + continue; + snprintf(full, sizeof(full), "%.900s/%.200s", path, + ent->d_name); + apt_auth_scan_file(&st, full); + } + closedir(d); + } + /* files==0 is the only "unreadable" case; the counters decide the rest */ + if (st.files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/apt/auth.conf or " + "auth.conf.d below the root prefix"); + return; + } + if (st.world_writable > 0) { + add_finding(&findings, &first, "world-writable", "high", + "%d APT auth file(s) can be rewritten by any local " + "user; the stored repository credentials are theirs", + st.world_writable); + count++; + } + if (st.world_readable > 0) { + add_finding(&findings, &first, "world-readable", "high", + "%d APT auth file(s) are readable by every local " + "user; the repository password is in clear text", + st.world_readable); + count++; + } + if (st.plain_http > 0) { + add_finding(&findings, &first, "credentials-over-http", "high", + "%d machine entr(ies) name an http:// repository, so " + "the credentials travel in clear text", st.plain_http); + count++; + } + if (count == 0) + add_finding(&findings, &first, "no-findings", "info", + "the credentials stay on https and the files are " + "neither world-readable nor world-writable"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"entries\":%d," + "\"plain_http\":%d,\"credentials\":%d," + "\"world_readable\":%d,\"world_writable\":%d," + "\"findings_count\":%d,\"findings\":[", + st.files, st.entries, st.plain_http, st.credentials, + st.world_readable, st.world_writable, 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); +} + +/* ----------------------------------------------------------------- aliases_audit */ + +/* /etc/aliases is "name: target, target". A target that starts with "|" is a + * command the MTA runs as its own user, so a pipe into a writable program is + * command execution on every message; an alias that forwards to a local user + * keeps working after that account is gone, and a file any local user can + * write hands out the whole mail routing. */ +typedef struct { + int files; + int aliases; + int pipe_cmds; + int root_forward; + int world_writable; + int world_readable; +} aliases_state; + +static void aliases_scan_file(aliases_state *st, const char *path) +{ + static char text[65536]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + st->files++; + if (stat(path, &sb) == 0) { + if ((sb.st_mode & 0002) != 0) + st->world_writable++; + if ((sb.st_mode & 0004) != 0 && (sb.st_mode & 0022) == 0) + st->world_readable++; + } + p = text; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[2048]; + char *colon; + char *name; + char *target; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + if (line[0] == '#' || line[0] == '\0') + continue; + colon = strchr(line, ':'); + if (colon == NULL) + continue; + *colon = '\0'; + name = line; + while (*name == ' ' || *name == '\t') + name++; + target = colon + 1; + while (*target == ' ' || *target == '\t') + target++; + if (*name == '\0' || *target == '\0' || *target == '#') + continue; + st->aliases++; + if (*target == '|') { + st->pipe_cmds++; + } else if (strcmp(name, "root") == 0) { + /* forward to anything but root itself keeps mail away */ + const char *atom = target; + size_t alen = strcspn(atom, " ,\t"); + + if (alen != 4 || strncmp(atom, "root", 4) != 0) + st->root_forward++; + } + } +} + +static void t_aliases_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1200]; + aliases_state st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + DIR *d; + + (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/aliases", root); + aliases_scan_file(&st, path); + snprintf(path, sizeof(path), "%.400s/etc/aliases.d", root); + d = opendir(path); + if (d != NULL) { + struct dirent *ent; + + while ((ent = readdir(d)) != NULL) { + char full[1200]; + + if (ent->d_name[0] == '.') + continue; + snprintf(full, sizeof(full), "%.900s/%.200s", path, + ent->d_name); + aliases_scan_file(&st, full); + } + closedir(d); + } + snprintf(path, sizeof(path), "%.400s/etc/mail/aliases", root); + if (st.files == 0) + aliases_scan_file(&st, path); + if (st.files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/aliases, aliases.d or " + "/etc/mail/aliases below the root prefix"); + return; + } + if (st.world_writable > 0) { + add_finding(&findings, &first, "world-writable", "high", + "%d alias file(s) are writable by any local user; " + "they decide where every mail goes", + st.world_writable); + count++; + } + if (st.world_readable > 0) { + add_finding(&findings, &first, "world-readable", "medium", + "%d alias file(s) are readable by every local user", + st.world_readable); + count++; + } + if (st.pipe_cmds > 0) { + add_finding(&findings, &first, "pipe-to-command", "high", + "%d alias(es) pipe mail into a command the MTA runs " + "as its own user", st.pipe_cmds); + count++; + } + if (st.root_forward > 0) { + add_finding(&findings, &first, "root-forward", "low", + "root mail is forwarded to another local account; a " + "privileged message lands in a shared mailbox"); + count++; + } + if (count == 0) + add_finding(&findings, &first, "no-findings", "info", + "no pipe alias, root mail stays local and the files " + "are not world-writable"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"aliases\":%d," + "\"pipe_commands\":%d,\"root_forward\":%d," + "\"world_readable\":%d,\"world_writable\":%d," + "\"findings_count\":%d,\"findings\":[", + st.files, st.aliases, st.pipe_cmds, st.root_forward, + st.world_readable, st.world_writable, 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); +} + +/* --------------------------------------------------------------- netgroup_audit */ + +/* /etc/netgroup lines are "name member member ...", members are + * "(host,user,domain)" triples, and an empty field in a triple means + * "anything". An empty host field therefore trusts every host in the netgroup + * and a bare "-" excludes nobody; a file any local user can write lets them + * add themselves to a trusted group. */ +typedef struct { + int files; + int entries; + int any_host; + int world_writable; + int world_readable; +} netgroup_state; + +static void netgroup_scan_file(netgroup_state *st, const char *path) +{ + static char text[65536]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + st->files++; + if (stat(path, &sb) == 0) { + if ((sb.st_mode & 0002) != 0) + st->world_writable++; + if ((sb.st_mode & 0004) != 0 && (sb.st_mode & 0022) == 0) + st->world_readable++; + } + p = text; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len; + char line[2048]; + const char *q; + + /* netgroup allows backslash continuation; join those lines */ + for (;;) { + if (eol == NULL) + break; + if (eol <= p) + break; + if (eol[-1] != '\\') + break; + eol = strchr(eol + 1, '\n'); + } + len = eol != NULL ? (size_t)(eol - p) : strlen(p); + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + p = eol != NULL ? eol + 1 : NULL; + if (line[0] == '#' || line[0] == '\0') + continue; + st->entries++; + /* Look at every "(a,b,c)" triple in the line. */ + q = line; + while ((q = strchr(q, '(')) != NULL) { + const char *close = strchr(q, ')'); + const char *comma = strchr(q, ','); + + if (close == NULL) + break; + if (comma != NULL && comma < close && comma == q + 1) { + /* "(,user,domain)" or "( , ...)" - host field empty */ + const char *h = q + 1; + + while (*h == ' ' || *h == '\t') + h++; + if (*h == ',' || *h == ')') + st->any_host++; + } + q = close + 1; + } + /* A trailing comma-separated member "-" removes nobody; a line + * that is only "-" is a delete entry and carries no trust. */ + if (strcmp(line, "-") == 0) + st->entries--; + } +} + +static void t_netgroup_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1200]; + netgroup_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/netgroup", root); + netgroup_scan_file(&st, path); + if (st.files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/netgroup below the root " + "prefix"); + return; + } + if (st.world_writable > 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is writable by any local user; they can add " + "themselves to a trusted netgroup", path); + count++; + } + if (st.world_readable > 0) { + add_finding(&findings, &first, "world-readable", "low", + "%s lists trusted hosts and users for every local " + "account", path); + count++; + } + if (st.any_host > 0) { + add_finding(&findings, &first, "any-host-member", "high", + "%d netgroup member(s) leave the host field empty, so " + "every host in the group is trusted", st.any_host); + count++; + } + if (count == 0) + add_finding(&findings, &first, "no-findings", "info", + "every member names its host and the file is not " + "world-writable"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"entries\":%d," + "\"any_host\":%d,\"world_readable\":%d," + "\"world_writable\":%d,\"findings_count\":%d," + "\"findings\":[", + st.files, st.entries, st.any_host, st.world_readable, + st.world_writable, 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, " @@ -28114,6 +28583,33 @@ const mcp_tool TOOLS_BLUE[] = { "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " "empty\"}}}", t_netplan_audit }, + { "apt_auth_audit", + "Parse /etc/apt/auth.conf and auth.conf.d/*.conf (root prefix). " + "Flags a machine entry naming an http:// repository (credentials in " + "clear text), any login/password pair in a world-readable file, and " + "a world-writable auth file. Read-only, no network traffic.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " + "empty\"}}}", + t_apt_auth_audit }, + { "aliases_audit", + "Parse /etc/aliases, aliases.d/* and /etc/mail/aliases (root prefix). " + "Flags an alias that pipes mail into a command, root mail forwarded " + "to another account, and an alias file that is world-readable or " + "world-writable. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " + "empty\"}}}", + t_aliases_audit }, + { "netgroup_audit", + "Parse /etc/netgroup (root prefix), including backslash " + "continuations. Flags a member with an empty host field (every host " + "trusted), and a file that is world-readable or world-writable. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default " + "empty\"}}}", + t_netgroup_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 60e530f..8a4f734 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -8553,6 +8553,96 @@ static void t_cadvisor_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* --------------------------------------------------------------- teamcity_probe */ + +/* TeamCity on 8111 answers /app/rest/server without a token even for a + * guest, so only the project and user collections count as exposure: a 200 + * that lists projects or user accounts is read without authentication at + * all. Those two answers are saved as evidence. */ +static void t_teamcity_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/app/rest/server", + "/app/rest/projects", + "/app/rest/users", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 8111); + 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 data_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, "teamcity_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 data = strstr(paths[i], "projects") != NULL || + strstr(paths[i], "users") != 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 && + (resp == NULL || strstr(resp, "\"error\"") == NULL); + if (open) + open_count++; + if (open && data) { + data_open = 1; + if (evidence == NULL) + evidence = apex_evidence_save("teamcity-rest", + 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," + "\"data_open\":%s,\"evidence\":", + tested, open_count, data_open ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("teamcity_probe", target, port, !data_open, + data_open + ? "the TeamCity REST API lists projects or users without a token" + : "the TeamCity REST API requires a token", "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 @@ -9997,6 +10087,17 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_sonarqube_probe }, + { "teamcity_probe", + "Query a TeamCity server without a token: /app/rest/server, " + "/app/rest/projects and /app/rest/users on 8111. A 2xx that lists " + "projects or users means the REST API is open; the answer is saved " + "as evidence. Gate: the target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 8111\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_teamcity_probe }, { "cadvisor_probe", "Query cAdvisor on 8080 for /healthz, /api/v1/containers and " "/api/v2.0/attributes without credentials. A 2xx on the container " diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 956ca02..bb9e12d 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 = 358 +EXPECTED_TOOLS = 362 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 9d13ad8..94c2d46 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("358 tools registered", len(tools) == 358, len(tools)) +check("362 tools registered", len(tools) == 362, 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"]) == 358) + check("http tools/list", len(listing["result"]["tools"]) == 362) 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 @@ -16335,6 +16335,177 @@ 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) +# --- 1.82.0: apt auth, aliases and netgroup audits plus the TeamCity probe --- +print("\n== apt auth, aliases, netgroup and TeamCity ==\n") + +aa_root = tempfile.mkdtemp(prefix="apex-aa-") +os.makedirs(os.path.join(aa_root, "etc", "apt", "auth.conf.d")) +aa_bad = os.path.join(aa_root, "etc", "apt", "auth.conf") +with open(aa_bad, "w") as f: + f.write("machine http://repo.example.test/apt\n") + f.write("login svcuser\n") + f.write("password s3cr3t\n") +os.chmod(aa_bad, 0o666) +aa_good_root = tempfile.mkdtemp(prefix="apex-aag-") +os.makedirs(os.path.join(aa_good_root, "etc", "apt", "auth.conf.d")) +aa_good_dir = os.path.join(aa_good_root, "etc", "apt", "auth.conf.d") +aa_good = os.path.join(aa_good_dir, "10-private.conf") +with open(aa_good, "w") as f: + f.write("machine https://repo.example.test/apt\n") + f.write("login svcuser\n") + f.write("password s3cr3t\n") +os.chmod(aa_good, 0o600) + +al_root = tempfile.mkdtemp(prefix="apex-al-") +os.makedirs(os.path.join(al_root, "etc")) +al_bad = os.path.join(al_root, "etc", "aliases") +with open(al_bad, "w") as f: + f.write("# aliases\n") + f.write("root: ops@example.test\n") + f.write("postmaster: |/usr/local/bin/ticket-open\n") + f.write("abuse: security\n") +os.chmod(al_bad, 0o666) +al_good_root = tempfile.mkdtemp(prefix="apex-alg-") +os.makedirs(os.path.join(al_good_root, "etc")) +al_good = os.path.join(al_good_root, "etc", "aliases") +with open(al_good, "w") as f: + f.write("root: root\n") + f.write("postmaster: root\n") + f.write("abuse: security\n") +os.chmod(al_good, 0o644) + +ng_root = tempfile.mkdtemp(prefix="apex-ng-") +os.makedirs(os.path.join(ng_root, "etc")) +ng_bad = os.path.join(ng_root, "etc", "netgroup") +with open(ng_bad, "w") as f: + f.write("# trusted\n") + f.write("trusted (,admin,) (,ops,)\n") + f.write("builders (build01,ci,) (build02,ci,)\n") +os.chmod(ng_bad, 0o666) +ng_good_root = tempfile.mkdtemp(prefix="apex-ngg-") +os.makedirs(os.path.join(ng_good_root, "etc")) +ng_good = os.path.join(ng_good_root, "etc", "netgroup") +with open(ng_good, "w") as f: + f.write("trusted (admin01,admin,example.test)\n") + f.write("builders (build01,ci,example.test) (build02,ci,example.test)\n") +os.chmod(ng_good, 0o644) + +class _TeamCityHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/app/rest/server": + body = b'{"version":"2023.11.3","buildNumber":"147512"}' + self.send_response(200) + elif path == "/app/rest/projects": + body = b'{"count":2,"project":[{"id":"Demo","name":"Demo"},' \ + b'{"id":"Infra","name":"Infra"}]}' + self.send_response(200) + elif path == "/app/rest/users": + body = b'{"count":2,"user":[{"username":"admin"},' \ + b'{"username":"builder"}]}' + self.send_response(200) + else: + body = b'{"error":"not found"}' + self.send_response(404) + 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 _TeamCityClosedHandler(_TeamCityHandler): + def do_GET(self): + body = b'{"error":"Authentication required"}' + 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) + + +tc_srv = http.server.HTTPServer(("127.0.0.1", 0), _TeamCityHandler) +tc_port = tc_srv.server_address[1] +threading.Thread(target=tc_srv.serve_forever, daemon=True).start() +tc_closed_srv = http.server.HTTPServer(("127.0.0.1", 0), + _TeamCityClosedHandler) +tc_closed_port = tc_closed_srv.server_address[1] +threading.Thread(target=tc_closed_srv.serve_forever, daemon=True).start() + +cfg54_home = tempfile.mkdtemp(prefix="apex-cfg54-home-") +write_scope(cfg54_home, + {"label": "cfg54", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(tc_port), str(tc_closed_port)]}) + +res, _ = run([ + call(1, "apt_auth_audit", root=aa_root), + call(2, "apt_auth_audit", root=aa_good_root), + call(3, "aliases_audit", root=al_root), + call(4, "aliases_audit", root=al_good_root), + call(5, "netgroup_audit", root=ng_root), + call(6, "netgroup_audit", root=ng_good_root), + call(7, "teamcity_probe", target="127.0.0.1", port=tc_port, tls=False), + call(8, "teamcity_probe", target="127.0.0.1", port=tc_closed_port, + tls=False), + call(9, "teamcity_probe", target="198.51.100.9", port=tc_port, tls=False), +], home=cfg54_home) +by_id = {r.get("id"): r for r in res} + +aa = json.loads(text(by_id[1])) +aa_kinds = {f["id"] for f in aa["findings"]} +check("apt_auth_audit flags http credentials and a world-writable file", + {"world-writable", "credentials-over-http"} <= aa_kinds and + aa["plain_http"] == 1 and aa["entries"] == 1, aa) +aa_good_res = json.loads(text(by_id[2])) +check("apt_auth_audit accepts https credentials in a 0600 file", + aa_good_res["entries"] == 1 and aa_good_res["plain_http"] == 0 and + aa_good_res["world_readable"] == 0 and + aa_good_res["world_writable"] == 0, aa_good_res) + +al = json.loads(text(by_id[3])) +al_kinds = {f["id"] for f in al["findings"]} +check("aliases_audit flags a pipe alias, a root forward and a writable file", + {"world-writable", "pipe-to-command", "root-forward"} <= al_kinds and + al["pipe_commands"] == 1 and al["root_forward"] == 1, al) +al_good_res = json.loads(text(by_id[4])) +check("aliases_audit accepts root mail staying local and no pipe alias", + al_good_res["pipe_commands"] == 0 and + al_good_res["root_forward"] == 0 and + al_good_res["world_writable"] == 0, al_good_res) + +ng = json.loads(text(by_id[5])) +ng_kinds = {f["id"] for f in ng["findings"]} +check("netgroup_audit flags an empty host field and a writable file", + {"world-writable", "any-host-member"} <= ng_kinds and + ng["any_host"] == 2, ng) +ng_good_res = json.loads(text(by_id[6])) +check("netgroup_audit accepts members that name their host", + ng_good_res["any_host"] == 0 and + ng_good_res["world_writable"] == 0 and + ng_good_res["entries"] == 2, ng_good_res) + +tc = json.loads(text(by_id[7])) +check("teamcity_probe finds the open REST API and saves evidence", + tc["data_open"] is True and tc["open_count"] == 3 and + os.path.isfile(tc["evidence"]), tc) +tc_closed = json.loads(text(by_id[8])) +check("teamcity_probe reports a 401 REST API as not open", + tc_closed["data_open"] is False and tc_closed["open_count"] == 0, + tc_closed) +tc_out = by_id[9] +check("teamcity_probe refuses an out-of-scope target", bool(err(tc_out)), + tc_out) + +tc_srv.shutdown() +tc_closed_srv.shutdown() + +for d in (aa_root, aa_good_root, al_root, al_good_root, ng_root, + ng_good_root, cfg54_home): + shutil.rmtree(d, ignore_errors=True) + print("%d passed, %d failed" % (passes, len(fails))) if fails: print("failed: " + ", ".join(fails))