From 28e931ea6010e705a317f82eb2bc9223d7dfa4b9 Mon Sep 17 00:00:00 2001 From: lotherk Date: Mon, 23 Nov 2026 08:52:54 +0000 Subject: [PATCH] apex-twin 1.80.0: modules-load, depmod and adduser.conf audits, Ollama probe Three blue config audits: modules_load_audit (/etc/modules and modules-load.d: CIS-blacklisted names, entries that are not module names, duplicates, world-writable), depmod_audit (depmod.d: absolute path first in a search line, override lines, world-writable) and adduser_conf_audit (DIR_MODE with group/other access, USERGROUPS=no, DSHELL not in /etc/shells, world-writable). Red: ollama_probe reads /api/tags on 11434 without credentials and saves the pulled model list as evidence. Verified: make test 1380/1380, test-asan 1380/1380, analyze 0 warnings, fuzz 240 cases without a sanitizer report, gate-audit 354 tools, version-check 1.80.0 in 5 places, release-check incl. distcheck exit 0, coverage 84.9%. Red proof: neutralising the CIS blacklist check made the new modules_load_audit check fail; rolled back. --- CHANGELOG.md | 17 ++ README.md | 14 +- SECURITY.md | 2 +- docs/apex-twin.1 | 7 +- src/apex.h | 2 +- src/tools_blue.c | 532 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 98 ++++++++ tests/gate_audit.py | 2 +- tests/run.py | 182 ++++++++++++++- 9 files changed, 844 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf8c072..000e9dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 1.80.0 — 2026-11-23 — this change + +- **Module lists** (`modules_load_audit`): `/etc/modules` and + `/etc/modules-load.d`: a name from the CIS blacklist (cramfs, hfsplus, udf, + usb-storage, dccp, sctp, rds, tipc, ...), a line that is not a module name at + all (a path, a semicolon), a duplicate across files, and a world-writable + list. +- **depmod** (`depmod_audit`): `/etc/depmod.d`: an absolute path in first + position of a `search` line (a module tree of the attacker's choosing wins + over `updates`), any `override` line, and a world-writable file. +- **adduser.conf** (`adduser_conf_audit`): a `DIR_MODE` that gives group or + other access to new home directories, `USERGROUPS=no`, a `DSHELL` that is + not listed in `/etc/shells`, and a world-writable config. Read-only. +- **Ollama** (`ollama_probe`): `/api/tags` on 11434 without credentials lists + every pulled model; the list is saved as evidence. `/api/version` answering + alone is not enough — nothing is pulled, deleted or prompted. + ## 1.79.0 — 2026-11-23 — this change - **ufw** (`ufw_audit`): `ENABLED=no` in `/etc/ufw/ufw.conf`, a diff --git a/README.md b/README.md index 6bd52c8..212decc 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. -**350 tools · 1371 end-to-end checks · 240 fuzz cases · 84.9% line coverage · ~1041 KiB** +**354 tools · 1380 end-to-end checks · 240 fuzz cases · 84.9% line coverage · ~1041 KiB** ``` $ ./apex-twin --check -{"version":"1.79.0","tools":350,...,"scope":{"loaded":true,...}} +{"version":"1.80.0","tools":354,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -236,6 +236,7 @@ uploads and secret-file reads. It does not execute anything. | `airflow_probe` | `/api/v1/dags` without auth; DAG inventory as evidence | | `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 | | `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 | @@ -532,6 +533,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `ufw_audit` | ufw: disabled, default ACCEPT, an open ACCEPT on a service port, writable rules | | `monit_audit` | monitrc: public httpd, plain `allow user:pw`, writable config | | `clamav_audit` | clamd/freshclam: public TCPSocket, exec hooks, LogRotate off | +| `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 | | `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 | @@ -1014,6 +1018,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, argocd_probe, kafka_connect_probe src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, @@ -1031,7 +1036,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, crypttab_audit, useradd_audit, aide_audit, faillock_audit, networkd_audit, namespace_audit, ssh_client_audit, ufw_audit, monit_audit, - clamav_audit) + clamav_audit, + modules_load_audit, depmod_audit, adduser_conf_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 @@ -1068,7 +1074,7 @@ examples/ scope.json ## Status -1.79.0. Built and run: 350 tools, 1371 checks, 240 fuzz cases and 84.9% line +1.80.0. Built and run: 354 tools, 1380 checks, 240 fuzz cases and 84.9% line coverage. The loop closes: a probe captures the exchange as a pair, a finding points at it, `finding_update` gives it a state, an asset records the host it came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a diff --git a/SECURITY.md b/SECURITY.md index 1602108..01b07d8 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.79.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.80.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 e9d8adb..0555273 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.79.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-23" "apex-twin 1.80.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), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -90,7 +90,8 @@ pam_env_audit, hosts_audit, dnf_repo_audit, 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) +networkd_audit, namespace_audit, ssh_client_audit, ufw_audit, monit_audit, clamav_audit, +modules_load_audit, depmod_audit, adduser_conf_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 adcb003..5805dbc 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.79.0" +#define APEX_VERSION "1.80.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 4c9a266..fdb4b02 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -25610,6 +25610,514 @@ static void t_clamav_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------- modules_load_audit */ + +/* A module name is letters, digits, '_' and '-'. Anything else (a slash, a + * semicolon, whitespace) means the line is not a module name at all, and a + * loader that pipes the line somewhere treats it as something else. */ +static int module_name_ok(const char *s) +{ + if (*s == '\0') + return 0; + while (*s != '\0') { + if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || + (*s >= '0' && *s <= '9') || *s == '_' || *s == '-')) + return 0; + s++; + } + return 1; +} + +/* Modules the CIS benchmark wants blacklisted: unmaintained filesystems and + * transports that add kernel attack surface nobody asked for. Loading one by + * name is the opposite of blocking it. */ +static int module_cis_disabled(const char *name) +{ + static const char *list[] = { "cramfs", "freevxfs", "jffs2", "hfs", + "hfsplus", "udf", "usb-storage", + "firewire-core", "dccp", "sctp", "rds", + "tipc", NULL }; + int i; + + for (i = 0; list[i] != NULL; i++) + if (strcasecmp(name, list[i]) == 0) + return 1; + return 0; +} + +#define MOD_SEEN_MAX 256 + +static void modules_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, char (*seen)[64], + int *nseen, int *modules) +{ + 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[512]; + char *s; + char *hash; + int i; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + hash = strchr(line, '#'); + if (hash != NULL) + *hash = '\0'; + trim_eol(line); + s = line; + while (*s == ' ' || *s == '\t') + s++; + trim_eol(s); + p = eol != NULL ? eol + 1 : NULL; + if (*s == '\0') + continue; + (*modules)++; + if (!module_name_ok(s)) { + add_finding(findings, first, "invalid-name", "medium", + "%s loads something that is not a module name: %s", + path, s); + (*count)++; + continue; + } + if (module_cis_disabled(s)) { + add_finding(findings, first, "cis-disabled-module", "low", + "%s loads %s, which CIS asks to blacklist", path, + s); + (*count)++; + } + for (i = 0; i < *nseen; i++) { + if (strcmp(seen[i], s) == 0) { + add_finding(findings, first, "duplicate", "info", + "%s loads %s again", path, s); + (*count)++; + break; + } + } + if (i == *nseen && *nseen < MOD_SEEN_MAX) { + snprintf(seen[*nseen], sizeof(seen[0]), "%.63s", s); + (*nseen)++; + } + } +} + +static void t_modules_load_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char dirpath[1024]; + static char seen[MOD_SEEN_MAX][64]; + int nseen = 0; + DIR *d; + struct dirent *ent; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int modules = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mcp_buf_init(&findings); + /* /etc/modules is the old flat list: one name per line, no suffix. */ + snprintf(dirpath, sizeof(dirpath), "%.400s/etc/modules", root); + { + struct stat st; + + if (stat(dirpath, &st) == 0) { + files++; + modules_scan_file(&findings, &first, &count, dirpath, seen, + &nseen, &modules); + } + } + snprintf(dirpath, sizeof(dirpath), "%.400s/etc/modules-load.d", root); + d = opendir(dirpath); + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char path[1200]; + + if (ent->d_name[0] == '.') + continue; + if (strstr(ent->d_name, ".conf") == NULL) + continue; + snprintf(path, sizeof(path), "%.800s/%.200s", dirpath, + ent->d_name); + files++; + modules_scan_file(&findings, &first, &count, path, seen, + &nseen, &modules); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/modules or /etc/modules-load.d"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"modules\":%d,\"unique\":%d," + "\"findings_count\":%d,\"findings\":[", + files, modules, nseen, 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); +} + +/* --------------------------------------------------------------- depmod_audit */ + +/* depmod reads /etc/depmod.d slash star dot conf. "search" lists the + * directories under /lib/modules in priority order; a foreign path in front of + * "updates" lets a file outside the module tree win, and "override mod other" + * makes one module answer to another module's name. Both are hijack + * primitives. */ +static void depmod_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *search_lines, + int *override_lines, int *foreign_first) +{ + 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 *s; + char *hash; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + hash = strchr(line, '#'); + if (hash != NULL) + *hash = '\0'; + trim_eol(line); + s = line; + while (*s == ' ' || *s == '\t') + s++; + trim_eol(s); + p = eol != NULL ? eol + 1 : NULL; + if (*s == '\0') + continue; + if (strncmp(s, "search", 6) == 0 && + (s[6] == ' ' || s[6] == '\t')) { + char *tok = s + 6; + int pos = 0; + + (*search_lines)++; + while (*tok != '\0') { + char dir[256]; + size_t n = 0; + + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok == '\0') + break; + while (*tok != '\0' && *tok != ' ' && + *tok != '\t') { + if (n + 1 < sizeof(dir)) + dir[n++] = *tok; + tok++; + } + dir[n] = '\0'; + pos++; + /* "updates" and "built-in" are the normal + * entries; anything absolute in front of them + * points depmod at a directory of our choosing. */ + if (dir[0] == '/' && pos == 1) { + add_finding(findings, first, + "foreign-search-path", "high", + "%s puts %s first in the search " + "order", path, dir); + (*count)++; + (*foreign_first)++; + } + } + } else if (strncmp(s, "override", 8) == 0 && + (s[8] == ' ' || s[8] == '\t')) { + add_finding(findings, first, "override", "medium", + "%s overrides a module name: %s", path, s + 8); + (*count)++; + (*override_lines)++; + } + } +} + +static void t_depmod_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char dirpath[1024]; + DIR *d; + struct dirent *ent; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int search_lines = 0; + int override_lines = 0; + int foreign_first = 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(dirpath, sizeof(dirpath), "%.400s/etc/depmod.d", root); + d = opendir(dirpath); + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char path[1200]; + + if (ent->d_name[0] == '.') + continue; + if (strstr(ent->d_name, ".conf") == NULL) + continue; + snprintf(path, sizeof(path), "%.800s/%.200s", dirpath, + ent->d_name); + files++; + depmod_scan_file(&findings, &first, &count, path, + &search_lines, &override_lines, + &foreign_first); + } + closedir(d); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/depmod.d"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"search_lines\":%d," + "\"foreign_first\":%d,\"override_lines\":%d," + "\"findings_count\":%d,\"findings\":[", + files, search_lines, foreign_first, override_lines, + 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); +} + +/* -------------------------------------------------------- adduser_conf_audit */ + +/* adduser.conf is shell-ish KEY=VALUE. DIR_MODE is an octal mode for new home + * directories: 0750 is the hard setting, anything with the group or other bit + * set lets a second user read a home directory that was meant to be private. + * USERGROUPS=no gives every user the shared "users" group instead of one group + * per user, and a DSHELL outside /etc/shells is a shell nobody maintains. */ +static void adduser_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, char *dir_mode, + size_t dir_mode_cap, int *dir_mode_set, + char *dshell, size_t dshell_cap, + int *usergroups_no) +{ + 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 *s; + char *eq; + char *val; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + s = line; + while (*s == ' ' || *s == '\t') + s++; + p = eol != NULL ? eol + 1 : NULL; + if (*s == '#' || *s == '\0') + continue; + eq = strchr(s, '='); + if (eq == NULL) + continue; + *eq = '\0'; + val = eq + 1; + trim_eol(s); + while (*val == ' ' || *val == '\t') + val++; + trim_eol(val); + if (strcasecmp(s, "DIR_MODE") == 0) { + snprintf(dir_mode, dir_mode_cap, "%s", val); + *dir_mode_set = 1; + } else if (strcasecmp(s, "DSHELL") == 0) { + snprintf(dshell, dshell_cap, "%s", val); + } else if (strcasecmp(s, "USERGROUPS") == 0) { + if (strcasecmp(val, "no") == 0 || + strcasecmp(val, "false") == 0 || + strcmp(val, "0") == 0) { + *usergroups_no = 1; + add_finding(findings, first, "usergroups-no", "medium", + "%s sets USERGROUPS=no: new users share one " + "group", path); + (*count)++; + } + } + } +} + +static void t_adduser_conf_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char dir_mode[32]; + char dshell[256]; + char shells_path[1024]; + static char shells[65536]; + int dir_mode_set = 0; + int usergroups_no = 0; + int shell_ok = 0; + long mode_val; + char *end = NULL; + 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; + } + dir_mode[0] = '\0'; + dshell[0] = '\0'; + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%.400s/etc/adduser.conf", root); + { + struct stat st; + + if (stat(path, &st) != 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read /etc/adduser.conf below the " + "root prefix"); + return; + } + } + adduser_scan_file(&findings, &first, &count, path, dir_mode, + sizeof(dir_mode), &dir_mode_set, dshell, + sizeof(dshell), &usergroups_no); + if (dir_mode_set) { + mode_val = strtol(dir_mode, &end, 8); + if (end != dir_mode && *end == '\0') { + /* Group or other write/read: 0750 and stricter are fine. */ + if ((mode_val & 0027) != 0) { + add_finding(&findings, &first, "loose-dir-mode", + "medium", + "%s:%s gives group or other access to " + "new home directories", path, dir_mode); + count++; + } + } + } + if (dshell[0] != '\0') { + snprintf(shells_path, sizeof(shells_path), "%.400s/etc/shells", + root); + if (read_text(shells_path, shells, sizeof(shells)) > 0) { + const char *sp = shells; + + while (sp != NULL && *sp != '\0') { + const char *eol = strchr(sp, '\n'); + size_t len = eol != NULL ? (size_t)(eol - sp) + : strlen(sp); + char sl[256]; + + if (len >= sizeof(sl)) + len = sizeof(sl) - 1; + memcpy(sl, sp, len); + sl[len] = '\0'; + trim_eol(sl); + if (strcmp(sl, dshell) == 0) + shell_ok = 1; + sp = eol != NULL ? eol + 1 : NULL; + } + if (!shell_ok) { + add_finding(&findings, &first, "shell-not-listed", + "low", + "%s is the default shell but is not in " + "/etc/shells", dshell); + count++; + } + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_puts(&b, ",\"dir_mode\":"); + if (dir_mode_set) + apex_json_str(&b, dir_mode); + else + mcp_buf_puts(&b, "null"); + mcp_buf_printf(&b, ",\"usergroups_no\":%s,\"dshell\":", + usergroups_no ? "true" : "false"); + if (dshell[0] != '\0') + apex_json_str(&b, dshell); + else + mcp_buf_puts(&b, "null"); + mcp_buf_printf(&b, ",\"findings_count\":%d,\"findings\":[", 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, " @@ -27042,6 +27550,30 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_clamav_audit }, + { "modules_load_audit", + "Parse /etc/modules and /etc/modules-load.d/*.conf (root prefix): " + "world-writable file, an entry that is not a plain module name (a path, " + "whitespace or a semicolon), a module CIS asks to blacklist (cramfs, " + "hfsplus, udf, usb-storage, dccp, sctp) and a module loaded twice. " + "Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_modules_load_audit }, + { "depmod_audit", + "Parse /etc/depmod.d/*.conf (root prefix): a search line whose first " + "entry is an absolute path outside /lib/modules (module hijack), an " + "override line that makes one module answer to another name, and a " + "world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_depmod_audit }, + { "adduser_conf_audit", + "Parse /etc/adduser.conf (root prefix): DIR_MODE with group or other " + "access to new home directories, USERGROUPS=no, a DSHELL that is not " + "listed in /etc/shells and a world-writable config. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_adduser_conf_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 370b00a..63c663c 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -9087,6 +9087,94 @@ static void t_jira_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ----------------------------------------------------------------- ollama_probe */ + +/* Ollama has no authentication at all unless it sits behind a proxy. An open + * /api/tags lists every pulled model (an attacker can then pull weights or run + * prompts on the host's GPU) and /api/ps shows what is loaded right now. Only a + * 2xx on /api/tags with a JSON body counts as open; the model list becomes the + * evidence. Nothing is pulled, deleted or prompted. */ +static void t_ollama_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/api/version", "/api/tags", "/api/ps", + NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 11434); + 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 models_open = 0; + char *evidence = NULL; + char label[64]; + 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, "ollama_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 = 0; + int tags = strcmp(paths[i], "/api/tags") == 0; + + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", paths[i], NULL, NULL, + 8000, &resp, &len, status, sizeof(status)) == 0) { + tested++; + code = apex_status_code(status); + if (code >= 200 && code < 300 && resp != NULL && len > 0) { + open_count++; + if (tags) + models_open = 1; + if (evidence == NULL) { + label[0] = '\0'; + snprintf(label, sizeof(label), "ollama-%d", i); + evidence = apex_evidence_save(label, resp, len); + } + } + } + free(resp); + 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}", code); + } + mcp_buf_printf(&b, "],\"tested\":%d,\"open_count\":%d," + "\"models_open\":%s,\"evidence\":", + tested, open_count, models_open ? "true" : "false"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("ollama_probe", target, port, !models_open, + models_open + ? "the Ollama model API answers without credentials" + : "the Ollama model API does not list models anonymously", + "list"); + mcp_reply_json(c, b.p); + free(evidence); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -9876,6 +9964,16 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 8080\"}}," "\"required\":[\"target\"]}", t_jira_probe }, + { "ollama_probe", + "Query Ollama (default 11434) without credentials: /api/version, " + "/api/tags and /api/ps. A 2xx on /api/tags lists every pulled model and " + "is saved as evidence; that API has no authentication of its own. Gate: " + "the target and port must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"},\"tls\":{\"type\":\"boolean\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 11434\"}}," + "\"required\":[\"target\"]}", + t_ollama_probe }, { "gitlab_probe", "Query the GitLab API (default 443) without a token: /api/v4/version " "and /api/v4/projects. A 2xx on the project list means public " diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 7f08e8f..87eb3d3 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 = 350 +EXPECTED_TOOLS = 354 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 bf63ba3..1aa2194 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("350 tools registered", len(tools) == 350, len(tools)) +check("354 tools registered", len(tools) == 354, 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"]) == 350) + check("http tools/list", len(listing["result"]["tools"]) == 354) 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 @@ -15969,6 +15969,184 @@ for d in (ufw_root, ufw_good_root, monit_root, monit_good_root, cl_root, cl_good_root, cfg51_home): shutil.rmtree(d, ignore_errors=True) +# --- 1.80.0: modules-load, depmod and adduser.conf audits, Ollama probe --- +print("\n== modules-load, depmod, adduser.conf and Ollama ==\n") + +ml_root = tempfile.mkdtemp(prefix="apex-ml-") +os.makedirs(os.path.join(ml_root, "etc", "modules-load.d")) +with open(os.path.join(ml_root, "etc", "modules"), "w") as f: + f.write("sctp\n") +ml_bad = os.path.join(ml_root, "etc", "modules-load.d", "bad.conf") +with open(ml_bad, "w") as f: + f.write("# a comment\n") + f.write("hfsplus\n") + f.write("sctp\n") + f.write("/tmp/not-a-module\n") +os.chmod(ml_bad, 0o666) + +ml_good_root = tempfile.mkdtemp(prefix="apex-mlg-") +os.makedirs(os.path.join(ml_good_root, "etc", "modules-load.d")) +with open(os.path.join(ml_good_root, "etc", "modules-load.d", "ok.conf"), + "w") as f: + f.write("overlay\n") + f.write("br_netfilter\n") + +dp_root = tempfile.mkdtemp(prefix="apex-dp-") +os.makedirs(os.path.join(dp_root, "etc", "depmod.d")) +dp_bad = os.path.join(dp_root, "etc", "depmod.d", "evil.conf") +with open(dp_bad, "w") as f: + f.write("search /tmp/modules updates built-in\n") + f.write("override drm /lib/modules/evil.ko\n") +os.chmod(dp_bad, 0o666) + +dp_good_root = tempfile.mkdtemp(prefix="apex-dpg-") +os.makedirs(os.path.join(dp_good_root, "etc", "depmod.d")) +with open(os.path.join(dp_good_root, "etc", "depmod.d", "ok.conf"), "w") as f: + f.write("search updates built-in\n") + +au_root = tempfile.mkdtemp(prefix="apex-au-") +os.makedirs(os.path.join(au_root, "etc")) +au_conf = os.path.join(au_root, "etc", "adduser.conf") +with open(au_conf, "w") as f: + f.write("DIR_MODE=0755\n") + f.write("USERGROUPS=no\n") + f.write("DSHELL=/bin/zsh\n") +os.chmod(au_conf, 0o666) +with open(os.path.join(au_root, "etc", "shells"), "w") as f: + f.write("/bin/sh\n") + f.write("/bin/bash\n") + +au_good_root = tempfile.mkdtemp(prefix="apex-aug-") +os.makedirs(os.path.join(au_good_root, "etc")) +with open(os.path.join(au_good_root, "etc", "adduser.conf"), "w") as f: + f.write("DIR_MODE=0750\n") + f.write("USERGROUPS=yes\n") + f.write("DSHELL=/bin/bash\n") +with open(os.path.join(au_good_root, "etc", "shells"), "w") as f: + f.write("/bin/sh\n") + f.write("/bin/bash\n") + + +class _OllamaHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + docs = { + "/api/version": b'{"version":"0.3.6"}', + "/api/tags": (b'{"models":[{"name":"llama3:8b"},' + b'{"name":"phi3:latest"}]}'), + "/api/ps": b'{"models":[]}', + } + 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 _OllamaClosedHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/api/version": + body = b'{"version":"0.3.6"}' + 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 + + +ol_srv = http.server.HTTPServer(("127.0.0.1", 0), _OllamaHandler) +ol_port = ol_srv.server_address[1] +threading.Thread(target=ol_srv.serve_forever, daemon=True).start() +ol_closed_srv = http.server.HTTPServer(("127.0.0.1", 0), + _OllamaClosedHandler) +ol_closed_port = ol_closed_srv.server_address[1] +threading.Thread(target=ol_closed_srv.serve_forever, daemon=True).start() + +cfg52_home = tempfile.mkdtemp(prefix="apex-cfg52-home-") +write_scope(cfg52_home, + {"label": "cfg52", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(ol_port), str(ol_closed_port)]}) + +res, _ = run([ + call(1, "modules_load_audit", root=ml_root), + call(2, "modules_load_audit", root=ml_good_root), + call(3, "depmod_audit", root=dp_root), + call(4, "depmod_audit", root=dp_good_root), + call(5, "adduser_conf_audit", root=au_root), + call(6, "adduser_conf_audit", root=au_good_root), + call(7, "ollama_probe", target="127.0.0.1", port=ol_port, tls=False), + call(8, "ollama_probe", target="127.0.0.1", port=ol_closed_port, + tls=False), + call(9, "ollama_probe", target="198.51.100.9", port=ol_port, tls=False), +], home=cfg52_home) +by_id = {r.get("id"): r for r in res} + +ml = json.loads(text(by_id[1])) +ml_kinds = {f["id"] for f in ml["findings"]} +check("modules_load_audit flags a CIS module, an invalid name and a " + "duplicate", + {"world-writable", "cis-disabled-module", "invalid-name", + "duplicate"} <= ml_kinds and ml["modules"] == 4 and ml["unique"] == 2, + ml) +ml_good = json.loads(text(by_id[2])) +check("modules_load_audit accepts ordinary module names", + ml_good["findings_count"] == 0 and ml_good["unique"] == 2, ml_good) + +dp = json.loads(text(by_id[3])) +dp_kinds = {f["id"] for f in dp["findings"]} +check("depmod_audit flags a foreign search path and an override", + {"world-writable", "foreign-search-path", "override"} <= dp_kinds and + dp["foreign_first"] == 1 and dp["override_lines"] == 1, dp) +dp_good = json.loads(text(by_id[4])) +check("depmod_audit accepts the stock search order", + dp_good["findings_count"] == 0 and dp_good["foreign_first"] == 0, + dp_good) + +au = json.loads(text(by_id[5])) +au_kinds = {f["id"] for f in au["findings"]} +check("adduser_conf_audit flags a loose DIR_MODE, USERGROUPS=no and an " + "unlisted shell", + {"world-writable", "loose-dir-mode", "usergroups-no", + "shell-not-listed"} <= au_kinds and + au["dir_mode"] == "0755" and au["usergroups_no"] is True and + au["dshell"] == "/bin/zsh", au) +au_good = json.loads(text(by_id[6])) +check("adduser_conf_audit accepts 0750, USERGROUPS=yes and a listed shell", + au_good["findings_count"] == 0 and au_good["dir_mode"] == "0750" and + au_good["usergroups_no"] is False, au_good) + +ol = json.loads(text(by_id[7])) +check("ollama_probe finds the open model API and saves the model list", + ol["models_open"] is True and ol["open_count"] == 3 and + os.path.isfile(ol["evidence"]), ol) +ol_closed = json.loads(text(by_id[8])) +check("ollama_probe reports a closed model API as not open", + ol_closed["models_open"] is False and ol_closed["open_count"] == 1, + ol_closed) +ol_out = by_id[9] +check("ollama_probe refuses an out-of-scope target", bool(err(ol_out)), + ol_out) + +ol_srv.shutdown() +ol_closed_srv.shutdown() + +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) + print("%d passed, %d failed" % (passes, len(fails))) if fails: print("failed: " + ", ".join(fails))