From 979b605ff165a07d9979d47904c44bae4b0239d0 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 21:19:19 +0000 Subject: [PATCH] apex-twin 1.72.0: pam_env, hosts and dnf repo audits, SonarQube probe Three blue config audits and one red API probe (+4 tools, 322 -> 326): - pam_env_audit: LD_PRELOAD/LD_LIBRARY_PATH in /etc/environment or pam_env.conf (code injection into every login), a world-writable PATH entry, a world-writable file. The pam_env.conf variable name is the first token before DEFAULT=/OVERRIDE=, not the text before the '='. - hosts_audit: a dotted name pinned to loopback/private/link-local, the same name with two different addresses, a world-writable /etc/hosts. - dnf_repo_audit: gpgcheck=0, repo_gpgcheck=0, sslverify=0, a plain http baseurl, a world-writable .repo file. - sonarqube_probe: /api/system/status answers even with anonymous access off, so only a 2xx on /api/projects/search counts as open; the project list becomes the evidence. Evidence: make test 1322/1322, test-asan 1322/1322, analyze 0 warnings, 240 fuzz cases, coverage 84.8%, release-check exit 0 including distcheck of the 1.72.0 tarball. Red proof: disabling the gpgcheck branch turned the dnf check red, then the change was reverted. --- CHANGELOG.md | 21 +- README.md | 15 +- SECURITY.md | 2 +- docs/apex-twin.1 | 7 +- src/apex.h | 2 +- src/tools_blue.c | 500 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 96 +++++++++ tests/gate_audit.py | 2 +- tests/run.py | 172 ++++++++++++++- 9 files changed, 802 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf9d5ed..cd0163d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,26 @@ fields, and state from an older version is read by a newer one. There are no git tags. The hash next to a version is the commit that introduced it; the current entry is the commit that adds this section. -## 1.71.0 — 2026-11-23 — this change +## 1.72.0 — 2026-11-23 — this change + +- **pam_env** (`pam_env_audit`): `LD_PRELOAD` or `LD_LIBRARY_PATH` set in + `/etc/environment` or `/etc/security/pam_env.conf`, which loads foreign code + into every login; a `PATH` entry that is a world-writable directory; and a + world-writable file. `pam_env.conf` writes `KEY DEFAULT=...`, so the variable + name is the first token, not the text before the `=`. +- **hosts** (`hosts_audit`): a dotted name mapped to a loopback, private or + link-local address (a pin or hijack), the same name listed with two different + addresses, and a world-writable `/etc/hosts`. A bare name such as `localhost` + is not flagged, only a dotted one. +- **dnf/yum repos** (`dnf_repo_audit`): `gpgcheck=0`, `repo_gpgcheck=0` and + `sslverify=0` in `/etc/dnf/dnf.conf` or `/etc/yum.repos.d/*.repo`, a plain + `http://` baseurl, and a world-writable repo file. +- **SonarQube** (`sonarqube_probe`): `/api/system/status` and + `/api/projects/search` on 9000 without credentials. `/api/system/status` + answers even when anonymous access is off, so only a 2xx on the project + search counts as an open instance, and that body becomes the evidence. + +## 1.71.0 — 2026-11-23 - **limits.conf** (`limits_audit`): `nofile`, `nproc` or `memlock` set to `unlimited`, a `core` limit above zero (core dumps), and world-writable diff --git a/README.md b/README.md index 66bc0bd..1e1d5db 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. -**322 tools · 1314 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1041 KiB** +**326 tools · 1322 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1041 KiB** ``` $ ./apex-twin --check -{"version":"1.71.0","tools":322,...,"scope":{"loaded":true,...}} +{"version":"1.72.0","tools":326,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -230,6 +230,7 @@ uploads and secret-file reads. It does not execute anything. | `portainer_probe` | `/api/status` and `/api/users/admin/check`; setup-open or unauth admin check | | `argocd_probe` | `/api/v1/applications` without a token; deployed apps as evidence | | `kafka_connect_probe` | `/connectors` on 8083 without auth; connector list as evidence | +| `sonarqube_probe` | `/api/projects/search` on 9000 without auth; project 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 | @@ -510,6 +511,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `gitconfig_audit` | gitconfig: sslVerify off, HTTP rewrite, store helper | | `npmrc_audit` | npmrc: strict-ssl off, HTTP registry, cleartext token | | `pip_conf_audit` | pip.conf: HTTP index, trusted-host override | +| `pam_env_audit` | environment/pam_env.conf: global LD_PRELOAD, writable PATH | +| `hosts_audit` | hosts: private pin, conflicting addresses, writable file | +| `dnf_repo_audit` | dnf/yum repos: gpgcheck off, sslverify off, plain http | | `podman_audit` | registries.conf: insecure or http registry, unsigned policy | | `buildkitd_audit` | buildkitd.toml: insecure registry, tcp without CA, no rootless | | `supervisor_audit` | supervisord.conf: exposed web UI, no username, root programs | @@ -986,7 +990,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, 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, + gitea_api_probe, harbor_probe, portainer_probe, sonarqube_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, @@ -996,7 +1000,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, systemd_audit (and ~160 more service config audits, newest: podman_audit, buildkitd_audit, supervisor_audit, fstab_audit, modprobe_audit, grub_audit, - limits_audit, access_conf_audit, pwquality_audit) + limits_audit, access_conf_audit, pwquality_audit, + pam_env_audit, hosts_audit, dnf_repo_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 @@ -1033,7 +1038,7 @@ examples/ scope.json ## Status -1.71.0. Built and run: 322 tools, 1314 checks, 240 fuzz cases and 84.8% line +1.72.0. Built and run: 326 tools, 1322 checks, 240 fuzz cases and 84.8% line coverage. The loop closes: a probe captures the exchange as a pair, a finding points at it, `finding_update` gives it a state, an asset records the host it came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a diff --git a/SECURITY.md b/SECURITY.md index 2a7c52f..5bbf34d 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.71.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.72.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 0eb1100..78eb42e 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.71.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-23" "apex-twin 1.72.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), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -85,7 +85,8 @@ authorized_keys_audit, ld_preload_audit, gitconfig_audit, npmrc_audit, pip_conf_audit, podman_audit, buildkitd_audit, supervisor_audit, fstab_audit, modprobe_audit, grub_audit, -limits_audit, access_conf_audit, pwquality_audit) +limits_audit, access_conf_audit, pwquality_audit, +pam_env_audit, hosts_audit, dnf_repo_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 7512e09..5e1ded2 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.71.0" +#define APEX_VERSION "1.72.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 e35f5df..d29622f 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -22,6 +22,8 @@ #include #include #include +#include +#include #include #include #include @@ -22100,6 +22102,483 @@ static void t_pwquality_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ---------------------------------------------------------------- pam_env_audit */ + +/* /etc/environment is a plain KEY=VALUE list; pam_env.conf is "KEY DEFAULT=... + * OVERRIDE=...". Both end up in the environment of every session, so a + * global LD_PRELOAD there is code injection into every login. PATH entries + * are checked one by one against world-writable directories. */ +static void pam_env_scan(mcp_buf *findings, int *first, int *count, + const char *path, int *keys, int *inject, + int *bad_path) +{ + static char text[65536]; + struct stat st; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + 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[1024]; + char *eq; + char *key; + char *val; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + eq = strchr(line, '='); + if (eq == NULL) + continue; + *eq = '\0'; + key = line; + while (*key == ' ' || *key == '\t') + key++; + trim_eol(key); + /* pam_env.conf writes "KEY DEFAULT=..." or "KEY OVERRIDE=...", so + * the variable name is only the first token before the '='. */ + { + char *space = key; + + while (*space != '\0' && *space != ' ' && *space != '\t') + space++; + *space = '\0'; + } + val = eq + 1; + while (*val == ' ' || *val == '\t') + val++; + trim_eol(val); + if (*key == '\0' || *key == '#') + continue; + (*keys)++; + if (strcmp(key, "LD_PRELOAD") == 0 || + strcmp(key, "LD_LIBRARY_PATH") == 0) { + add_finding(findings, first, "global-preload", "high", + "%s: %s is set for every session, which " + "loads foreign code into each login", + path, key); + (*count)++; + (*inject)++; + } else if (strcmp(key, "PATH") == 0) { + char copy[1024]; + char *tok; + char *save = NULL; + + snprintf(copy, sizeof(copy), "%s", val); + for (tok = strtok_r(copy, ":", &save); tok != NULL; + tok = strtok_r(NULL, ":", &save)) { + struct stat ds; + + if (*tok == '\0') + continue; + if (stat(tok, &ds) != 0) + continue; + if ((ds.st_mode & 0002) != 0) { + add_finding(findings, first, + "writable-path", "high", + "%s: PATH contains " + "world-writable %s", + path, tok); + (*count)++; + (*bad_path)++; + } + } + } + } +} + +static void t_pam_env_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int keys = 0; + int inject = 0; + int bad_path = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%.400s/etc/environment", root); + if (stat(path, &st) == 0) { + files++; + pam_env_scan(&findings, &first, &count, path, &keys, &inject, + &bad_path); + } + snprintf(path, sizeof(path), "%.400s/etc/security/pam_env.conf", root); + if (stat(path, &st) == 0) { + files++; + pam_env_scan(&findings, &first, &count, path, &keys, &inject, + &bad_path); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/environment or pam_env.conf"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"keys\":%d,\"preload\":%d," + "\"writable_path\":%d,\"findings_count\":%d," + "\"findings\":[", + files, keys, inject, bad_path, 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); +} + +/* ------------------------------------------------------------------ hosts_audit */ + +/* /etc/hosts maps names to addresses before DNS. A public name pointed at + * loopback or a private address is a pin or a hijack; the same name twice + * with different addresses is a conflict. Only the first three fields count, + * the rest of the line is comments or ignored aliases. */ +static int is_private_addr(const char *ip) +{ + struct in_addr v4; + struct in6_addr v6; + + if (inet_pton(AF_INET, ip, &v4) == 1) { + unsigned long a = ntohl(v4.s_addr); + + if ((a >> 24) == 127 || (a >> 24) == 10) + return 1; + if ((a >> 20) == ((172 << 4) | 1)) + return 1; + if ((a >> 16) == ((192 << 8) | 168)) + return 1; + if ((a >> 16) == ((169 << 8) | 254)) + return 1; + return 0; + } + if (inet_pton(AF_INET6, ip, &v6) == 1) { + static const unsigned char loop[16] = { 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1 }; + + if (memcmp(&v6, loop, 16) == 0) + return 1; + if ((v6.s6_addr[0] & 0xfe) == 0xfc) + return 1; + if (v6.s6_addr[0] == 0xfe && (v6.s6_addr[1] & 0xc0) == 0x80) + return 1; + return 0; + } + return 0; +} + +static void t_hosts_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + static char text[65536]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int entries = 0; + int pinned = 0; + int conflicts = 0; + char seen_names[64][128]; + char seen_addrs[64][64]; + int seen_n = 0; + const char *p; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), "%.400s/etc/hosts", root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read /etc/hosts"); + return; + } + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "%s is writable by anyone", path); + count++; + } + 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[1024]; + char *tok; + char *save = NULL; + char *addr = NULL; + int names = 0; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + { + char *hash = strchr(line, '#'); + + if (hash != NULL) + *hash = '\0'; + } + for (tok = strtok_r(line, " \t", &save); tok != NULL; + tok = strtok_r(NULL, " \t", &save)) { + if (addr == NULL) { + addr = tok; + continue; + } + names++; + if (names > 3) + break; + /* A bare host name such as "localhost" belongs to loopback + * by definition; only a dotted name pointed at a private + * address is a pin worth reporting. */ + if (is_private_addr(addr) && strchr(tok, '.') != NULL) { + add_finding(&findings, &first, + "private-pin", "medium", + "%s maps %s to the private address " + "%s", path, tok, addr); + count++; + pinned++; + } + { + int i; + int known = 0; + + for (i = 0; i < seen_n; i++) { + if (strcmp(seen_names[i], tok) != 0) + continue; + known = 1; + if (strcmp(seen_addrs[i], addr) != 0) { + add_finding(&findings, &first, + "address-conflict", + "low", + "%s lists %s for both " + "%s and %s", path, + tok, seen_addrs[i], + addr); + count++; + conflicts++; + } + break; + } + if (!known && seen_n < 64) { + snprintf(seen_names[seen_n], + sizeof(seen_names[0]), "%s", tok); + snprintf(seen_addrs[seen_n], + sizeof(seen_addrs[0]), "%s", + addr); + seen_n++; + } + } + } + if (addr != NULL) + entries++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"entries\":%d,\"private_pins\":%d," + "\"conflicts\":%d,\"findings_count\":%d,\"findings\":[", + entries, pinned, conflicts, 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); +} + +/* -------------------------------------------------------------- dnf_repo_audit */ + +/* Repo files are INI with one [id] per section. gpgcheck=0 or a plain http + * baseurl means packages arrive unsigned or in the clear. A .repo file that + * anyone can write is worse than either. */ +static void dnf_scan_repo(mcp_buf *findings, int *first, int *count, + const char *path, int *sections, int *nogpg, + int *plain_http, int *nossl) +{ + static char text[65536]; + struct stat st; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + 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[1024]; + char *eq; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s == '[') { + (*sections)++; + continue; + } + if (*s == '#' || *s == ';' || *s == '\0') + continue; + eq = strchr(s, '='); + if (eq == NULL) + continue; + *eq = '\0'; + { + char *key = s; + char *val = eq + 1; + + trim_eol(key); + while (*val == ' ' || *val == '\t') + val++; + trim_eol(val); + if (strcmp(key, "gpgcheck") == 0 && + strcmp(val, "0") == 0) { + add_finding(findings, first, "no-gpgcheck", + "high", + "%s: gpgcheck=0 accepts " + "unsigned packages", path); + (*count)++; + (*nogpg)++; + } else if (strcmp(key, "repo_gpgcheck") == 0 && + strcmp(val, "0") == 0) { + add_finding(findings, first, + "no-repo-gpgcheck", "medium", + "%s: repo_gpgcheck=0 leaves " + "metadata unsigned", path); + (*count)++; + } else if (strcmp(key, "sslverify") == 0 && + strcmp(val, "0") == 0) { + add_finding(findings, first, "no-sslverify", + "high", + "%s: sslverify=0 disables the " + "transport check", path); + (*count)++; + (*nossl)++; + } else if (strcmp(key, "baseurl") == 0 && + strncmp(val, "http://", 7) == 0) { + add_finding(findings, first, "plain-http", + "medium", + "%s: baseurl %s is plain " + "HTTP", path, val); + (*count)++; + (*plain_http)++; + } + } + } + } +} + +static void t_dnf_repo_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + struct stat st; + DIR *d; + struct dirent *ent; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int sections = 0; + int nogpg = 0; + int plain_http = 0; + int nossl = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%.400s/etc/dnf/dnf.conf", root); + if (stat(path, &st) == 0) { + files++; + dnf_scan_repo(&findings, &first, &count, path, §ions, &nogpg, + &plain_http, &nossl); + } + snprintf(path, sizeof(path), "%.400s/etc/yum.repos.d", root); + d = opendir(path); + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char file[1200]; + + if (ent->d_name[0] == '.') + continue; + if (strstr(ent->d_name, ".repo") == NULL) + continue; + snprintf(file, sizeof(file), "%.800s/%.200s", path, + ent->d_name); + files++; + dnf_scan_repo(&findings, &first, &count, file, §ions, + &nogpg, &plain_http, &nossl); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read a dnf or yum repository file"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"sections\":%d,\"no_gpgcheck\":%d," + "\"plain_http\":%d,\"no_sslverify\":%d," + "\"findings_count\":%d,\"findings\":[", + files, sections, nogpg, plain_http, nossl, 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, " @@ -23365,6 +23844,27 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_pwquality_audit }, + { "pam_env_audit", + "Parse /etc/environment and /etc/security/pam_env.conf (root prefix): " + "a global LD_PRELOAD or LD_LIBRARY_PATH, a PATH entry that is " + "world-writable and a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_pam_env_audit }, + { "hosts_audit", + "Parse /etc/hosts (root prefix): a name pinned to loopback or a " + "private address, the same name listed with two different addresses, " + "and a world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_hosts_audit }, + { "dnf_repo_audit", + "Parse /etc/dnf/dnf.conf and /etc/yum.repos.d/*.repo (root prefix): " + "gpgcheck=0, repo_gpgcheck=0, sslverify=0, a plain http baseurl and a " + "world-writable repo file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_dnf_repo_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 ffc049c..c32f028 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -8291,6 +8291,92 @@ static void t_kafka_connect_probe(mcp_conn *c, const mcp_json *args, 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 + * project list becomes the evidence. */ +static void t_sonarqube_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/api/system/status", + "/api/projects/search", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 9000); + 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 projects_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, "sonarqube_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 projects = strstr(paths[i], "projects") != 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 && projects) { + projects_open = 1; + if (evidence == NULL) + evidence = apex_evidence_save("sonarqube-projects", + 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," + "\"projects_open\":%s,\"evidence\":", + tested, open_count, projects_open ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("sonarqube_probe", target, port, !projects_open, + projects_open + ? "the SonarQube project API answers without authentication" + : "the SonarQube project API requires authentication", "list"); + mcp_reply_json(c, b.p); + free(evidence); + mcp_buf_free(&b); +} + /* ------------------------------------------------------------- portainer_probe */ static void t_portainer_probe(mcp_conn *c, const mcp_json *args, void *user) @@ -9197,6 +9283,16 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_kafka_connect_probe }, + { "sonarqube_probe", + "Query a SonarQube instance without credentials: /api/system/status " + "and /api/projects/search on 9000. A 2xx project list means anonymous " + "access is on; the list is saved as evidence. Gate: the target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 9000\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_sonarqube_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 f9ed0ce..c939fa7 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 = 322 +EXPECTED_TOOLS = 326 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 bdafee3..eb34cc5 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("322 tools registered", len(tools) == 322, len(tools)) +check("326 tools registered", len(tools) == 326, 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"]) == 322) + check("http tools/list", len(listing["result"]["tools"]) == 326) 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 @@ -14797,7 +14797,173 @@ check("a zero-byte blob reads back as empty text", back) shutil.rmtree(lim_home, ignore_errors=True) -print("\n== summary ==") +print("\n== pam_env, hosts, dnf repos and SonarQube ==") + +pe_root = tempfile.mkdtemp(prefix="apex-pe-") +os.makedirs(os.path.join(pe_root, "etc", "security")) +pe_bad = os.path.join(pe_root, "etc", "environment") +pe_writable_dir = os.path.join(pe_root, "bin") +os.makedirs(pe_writable_dir) +os.chmod(pe_writable_dir, 0o777) +with open(pe_bad, "w") as f: + f.write("LD_PRELOAD=/tmp/evil.so\n") + f.write("PATH=%s:/usr/bin\n" % pe_writable_dir) + f.write("LANG=C\n") +os.chmod(pe_bad, 0o666) +with open(os.path.join(pe_root, "etc", "security", "pam_env.conf"), "w") as f: + f.write("LD_LIBRARY_PATH DEFAULT=/opt/lib\n") +pe_good_root = tempfile.mkdtemp(prefix="apex-peg-") +os.makedirs(os.path.join(pe_good_root, "etc")) +with open(os.path.join(pe_good_root, "etc", "environment"), "w") as f: + f.write("PATH=/usr/local/bin:/usr/bin:/bin\n") + f.write("LANG=C.UTF-8\n") + +h_root = tempfile.mkdtemp(prefix="apex-hosts-") +os.makedirs(os.path.join(h_root, "etc")) +with open(os.path.join(h_root, "etc", "hosts"), "w") as f: + f.write("127.0.0.1\tlocalhost\n") + f.write("10.1.2.3\tintranet.example.test\n") + f.write("203.0.113.10\twww.example.test\n") + f.write("203.0.113.11\twww.example.test\n") + f.write("::1\tlocalhost6\n") +os.chmod(os.path.join(h_root, "etc", "hosts"), 0o666) +h_good_root = tempfile.mkdtemp(prefix="apex-hostsg-") +os.makedirs(os.path.join(h_good_root, "etc")) +with open(os.path.join(h_good_root, "etc", "hosts"), "w") as f: + f.write("127.0.0.1\tlocalhost\n") + f.write("203.0.113.10\twww.example.test\n") + +dnf_root = tempfile.mkdtemp(prefix="apex-dnf-") +os.makedirs(os.path.join(dnf_root, "etc", "yum.repos.d")) +os.makedirs(os.path.join(dnf_root, "etc", "dnf")) +dnf_bad = os.path.join(dnf_root, "etc", "yum.repos.d", "evil.repo") +with open(dnf_bad, "w") as f: + f.write("[base]\n") + f.write("name=Base\n") + f.write("baseurl=http://mirror.example.test/base\n") + f.write("gpgcheck=0\n") + f.write("repo_gpgcheck=0\n") + f.write("sslverify=0\n") +os.chmod(dnf_bad, 0o666) +dnf_good_root = tempfile.mkdtemp(prefix="apex-dnfg-") +os.makedirs(os.path.join(dnf_good_root, "etc", "yum.repos.d")) +with open(os.path.join(dnf_good_root, "etc", "yum.repos.d", "base.repo"), + "w") as f: + f.write("[base]\n") + f.write("name=Base\n") + f.write("baseurl=https://mirror.example.test/base\n") + f.write("gpgcheck=1\n") + f.write("repo_gpgcheck=1\n") + f.write("sslverify=1\n") + +cfg44_home = tempfile.mkdtemp(prefix="apex-cfg44-home-") +write_scope(cfg44_home, + {"label": "cfg44", "expires": "2099-01-01T00:00:00Z", + "allow_ip": ["127.0.0.1/32"], "allow_private": True, + "allow_port": ["1-65535"]}) + +class _SonarHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/api/system/status": + body = b'{"status":"UP","version":"10.6"}' + self.send_response(200) + elif path == "/api/projects/search": + body = b'{"components":[{"key":"shop"},{"key":"portal"}]}' + self.send_response(200) + else: + body = b'{"errors":[{"msg":"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 _SonarAuthHandler(_SonarHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/api/system/status": + body = b'{"status":"UP"}' + self.send_response(200) + elif path == "/api/projects/search": + body = b'{"errors":[{"msg":"Insufficient privileges"}]}' + self.send_response(403) + else: + body = b'{"errors":[{"msg":"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) + + +sq_srv = http.server.HTTPServer(("127.0.0.1", 0), _SonarHandler) +sq_port = sq_srv.server_address[1] +threading.Thread(target=sq_srv.serve_forever, daemon=True).start() +sqa_srv = http.server.HTTPServer(("127.0.0.1", 0), _SonarAuthHandler) +sqa_port = sqa_srv.server_address[1] +threading.Thread(target=sqa_srv.serve_forever, daemon=True).start() + +res, _ = run([ + call(1, "pam_env_audit", root=pe_root), + call(2, "pam_env_audit", root=pe_good_root), + call(3, "hosts_audit", root=h_root), + call(4, "hosts_audit", root=h_good_root), + call(5, "dnf_repo_audit", root=dnf_root), + call(6, "dnf_repo_audit", root=dnf_good_root), + call(7, "sonarqube_probe", target="127.0.0.1", port=sq_port), + call(8, "sonarqube_probe", target="127.0.0.1", port=sqa_port), +], home=cfg44_home) +by_id = {r.get("id"): r for r in res} +pe = json.loads(text(by_id[1])) +check("pam_env_audit flags a global preload, a writable PATH and a " + "writable file", + {"global-preload", "writable-path", "world-writable"} <= + {f["id"] for f in pe["findings"]} and pe["files"] == 2 and + pe["preload"] == 2, pe) +pe_good = json.loads(text(by_id[2])) +check("pam_env_audit accepts a plain PATH and no preload", + pe_good["findings_count"] == 0 and pe_good["preload"] == 0, + pe_good) + +ho = json.loads(text(by_id[3])) +check("hosts_audit flags a private pin and an address conflict", + {"private-pin", "address-conflict", "world-writable"} <= + {f["id"] for f in ho["findings"]} and ho["conflicts"] == 1, ho) +ho_good = json.loads(text(by_id[4])) +check("hosts_audit accepts localhost and one public address", + ho_good["findings_count"] == 0 and ho_good["private_pins"] == 0, + ho_good) + +dn = json.loads(text(by_id[5])) +check("dnf_repo_audit flags gpgcheck off, plain http and a writable repo", + {"no-gpgcheck", "no-repo-gpgcheck", "no-sslverify", "plain-http", + "world-writable"} <= {f["id"] for f in dn["findings"]} and + dn["no_gpgcheck"] == 1 and dn["plain_http"] == 1 and + dn["no_sslverify"] == 1, dn) +dn_good = json.loads(text(by_id[6])) +check("dnf_repo_audit accepts a signed https repository", + dn_good["findings_count"] == 0 and dn_good["no_gpgcheck"] == 0, + dn_good) + +sq = json.loads(text(by_id[7])) +check("sonarqube_probe finds an open project API and saves the list", + sq["projects_open"] is True and sq["open_count"] == 2 and + os.path.isfile(sq["evidence"]), sq) +sqa = json.loads(text(by_id[8])) +check("sonarqube_probe reports a closed project API as not open", + sqa["projects_open"] is False and sqa["open_count"] == 1, sqa) +sq_srv.shutdown() +sqa_srv.shutdown() + +for d in (pe_root, pe_good_root, h_root, h_good_root, dnf_root, + dnf_good_root, cfg44_home): + shutil.rmtree(d, ignore_errors=True) + print("%d passed, %d failed" % (passes, len(fails))) if fails: print("failed: " + ", ".join(fails))