diff --git a/CHANGELOG.md b/CHANGELOG.md index e58fb0a..cf8c072 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## 1.79.0 — 2026-11-23 — this change + +- **ufw** (`ufw_audit`): `ENABLED=no` in `/etc/ufw/ufw.conf`, a + `DEFAULT_INPUT_POLICY` that is not `DROP`/`REJECT`, and every + `-A ufw-user-* -j ACCEPT` in `user.rules` that reaches a database, remote + access or mail port with no `-s` restriction. A world-writable `ufw.conf` or + `user.rules` is reported too. +- **monit** (`monit_audit`): an `set httpd` block that does not bind + `localhost`, an `allow user:password` with a literal password instead of a + hash, and a world-writable `monitrc`. +- **ClamAV** (`clamav_audit`): `TCPSocket` enabled at all, a `TCPAddr` beyond + loopback, a `VirusEvent`/`OnUpdateExecute` hook, `LogRotate no`, and a + world-writable `clamd.conf`. +- **Jira** (`jira_probe`): `/rest/api/2/project` on port 8080 without + credentials; a 2xx means the project inventory is public and the body is + saved as evidence. +- Fixed while writing the tests: `clamav_audit` now reads `LogRotate no` as + off (it only understood `false` and `0`). + ## 1.78.0 — 2026-11-23 — this change - **crypttab** (`crypttab_audit`): a world-writable `/etc/crypttab` lets a diff --git a/README.md b/README.md index 98566ac..6bd52c8 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. -**346 tools · 1362 end-to-end checks · 240 fuzz cases · 84.9% line coverage · ~1041 KiB** +**350 tools · 1371 end-to-end checks · 240 fuzz cases · 84.9% line coverage · ~1041 KiB** ``` $ ./apex-twin --check -{"version":"1.76.0","tools":339,...,"scope":{"loaded":true,...}} +{"version":"1.79.0","tools":350,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -235,6 +235,7 @@ uploads and secret-file reads. It does not execute anything. | `rundeck_probe` | `/api/14/projects` without a token; project list as evidence | | `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 | | `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 | @@ -528,6 +529,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `crypttab_audit` | crypttab: readable key file, `none` key, discard | | `useradd_audit` | useradd defaults: empty INACTIVE, bad SHELL, writable skel | | `aide_audit` | AIDE: `!` on /etc or /bin, md5-only rules, db in /tmp | +| `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 | | `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 | @@ -1009,7 +1013,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, - gitlab_probe, jupyter_probe, + gitlab_probe, jupyter_probe, jira_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, @@ -1026,7 +1030,8 @@ src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, ld_so_conf_audit, rc_local_audit, nscd_audit, crypttab_audit, useradd_audit, aide_audit, faillock_audit, networkd_audit, namespace_audit, - ssh_client_audit) + ssh_client_audit, ufw_audit, monit_audit, + clamav_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 @@ -1063,7 +1068,7 @@ examples/ scope.json ## Status -1.78.0. Built and run: 346 tools, 1362 checks, 240 fuzz cases and 84.9% line +1.79.0. Built and run: 350 tools, 1371 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 0ec781c..1602108 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.78.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.79.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 686096e..e9d8adb 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.78.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-23" "apex-twin 1.79.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), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -90,7 +90,7 @@ 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) +networkd_audit, namespace_audit, ssh_client_audit, ufw_audit, monit_audit, clamav_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 9bf6005..adcb003 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.78.0" +#define APEX_VERSION "1.79.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 b640c76..4c9a266 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -24925,6 +24925,691 @@ static void t_aide_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ---------------------------------------------------------------- ufw_audit */ + +/* ufw spreads its state over three files: /etc/ufw/ufw.conf says whether the + * firewall is on at all, /etc/default/ufw holds the default policies and + * /etc/ufw/user.rules is an iptables-restore dump with one "-A ufw-user-*" + * line per rule. An ACCEPT on a database port with no -s restriction is the + * finding that matters: the rule is reachable from anywhere. */ +static int ufw_sensitive_port(int port) +{ + switch (port) { + case 22: + case 23: + case 111: + case 445: + case 1433: + case 1521: + case 2049: + case 3306: + case 3389: + case 5432: + case 5900: + case 6379: + case 9200: + case 11211: + case 27017: + return 1; + default: + return 0; + } +} + +/* The port field can be a list ("80,443") or a range ("3000:4000"); the first + * sensitive member is enough. */ +static int ufw_ports_hit(const char *spec) +{ + const char *p = spec; + + if (spec == NULL) + return 0; + while (*p != '\0') { + int port = 0; + int digits = 0; + + while (*p >= '0' && *p <= '9') { + port = port * 10 + (*p - '0'); + digits = 1; + p++; + } + if (digits && ufw_sensitive_port(port)) + return 1; + while (*p != '\0' && *p != ',' && *p != ':') + p++; + if (*p == ',') + p++; + else if (*p == ':') + p++; + else + break; + } + return 0; +} + +static void ufw_scan_rules(mcp_buf *findings, int *first, int *count, + const char *path, int *rules, int *open_sensitive, + int *writable) +{ + static char text[262144]; + 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: a local user can open any " + "port the kernel offers", path); + (*count)++; + (*writable)++; + } + 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[64]; + int n = 0; + int i; + int restricted = 0; + int accept = 0; + int hit = 0; + char *save = NULL; + char *word; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + if (line[0] != '-') + continue; + word = strtok_r(line, " \t", &save); + while (word != NULL && n < 64) { + tok[n++] = word; + word = strtok_r(NULL, " \t", &save); + } + if (n < 3 || strcmp(tok[0], "-A") != 0) + continue; + (*rules)++; + for (i = 0; i < n; i++) { + if (strcmp(tok[i], "-s") == 0 && i + 1 < n) { + if (strcmp(tok[i + 1], "0.0.0.0/0") != 0 && + strcmp(tok[i + 1], "::/0") != 0) + restricted = 1; + } + if ((strcmp(tok[i], "--dport") == 0 || + strcmp(tok[i], "--dports") == 0) && + i + 1 < n && ufw_ports_hit(tok[i + 1])) + hit = 1; + if (strcmp(tok[i], "-j") == 0 && i + 1 < n && + strcmp(tok[i + 1], "ACCEPT") == 0) + accept = 1; + } + if (hit && accept && !restricted) { + add_finding(findings, first, "open-sensitive-port", "high", + "%s: an ACCEPT rule reaches a service port " + "from any source", path); + (*count)++; + (*open_sensitive)++; + } + } +} + +/* Read "ENABLED=yes|no" out of ufw.conf. Returns 1, 0, or -1 when the line is + * missing or the file cannot be read: a ufw.conf without ENABLED leaves the + * firewall off until an admin starts it by hand. */ +static int ufw_enabled(const char *path, mcp_buf *findings, int *first, + int *count, int *writable) +{ + static char text[65536]; + struct stat st; + const char *p; + int enabled = -1; + + if (read_text(path, text, sizeof(text)) <= 0) + return -1; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + (*writable)++; + } + 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[256]; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + if (strncasecmp(line, "ENABLED=", 8) == 0) { + char *v = line + 8; + + while (*v == ' ' || *v == '\t') + v++; + enabled = strcasecmp(v, "yes") == 0 ? 1 : 0; + } + } + return enabled; +} + +/* /etc/default/ufw carries the policy ufw applies to traffic it has no rule + * for. DEFAULT_INPUT_POLICY="ACCEPT" is the one that matters: every port that + * is not explicitly denied stays reachable. */ +static int ufw_default_input_accept(const char *path, mcp_buf *findings, + int *first, int *count) +{ + static char text[65536]; + const char *p; + int accept = 0; + + if (read_text(path, text, sizeof(text)) <= 0) + return 0; + 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[256]; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + trim_eol(line); + p = eol != NULL ? eol + 1 : NULL; + if (strncasecmp(line, "DEFAULT_INPUT_POLICY=", 21) == 0) { + char *v = line + 21; + + while (*v == '"' || *v == '\'' || *v == ' ' || + *v == '\t') + v++; + if (strncasecmp(v, "ACCEPT", 6) == 0) { + accept = 1; + add_finding(findings, first, "default-accept", + "high", + "DEFAULT_INPUT_POLICY is ACCEPT: every " + "port without an explicit drop rule " + "stays open"); + (*count)++; + } + } + } + return accept; +} + +static void t_ufw_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int enabled = -1; + int default_accept = 0; + int rules = 0; + int open_sensitive = 0; + int writable = 0; + struct stat st; + + (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/ufw/ufw.conf", root); + if (stat(path, &st) == 0) { + files++; + enabled = ufw_enabled(path, &findings, &first, &count, + &writable); + } + snprintf(path, sizeof(path), "%.400s/etc/default/ufw", root); + if (stat(path, &st) == 0) { + files++; + default_accept = ufw_default_input_accept(path, &findings, + &first, &count); + } + snprintf(path, sizeof(path), "%.400s/etc/ufw/user.rules", root); + if (stat(path, &st) == 0) { + files++; + ufw_scan_rules(&findings, &first, &count, path, &rules, + &open_sensitive, &writable); + } + snprintf(path, sizeof(path), "%.400s/etc/ufw/user6.rules", root); + if (stat(path, &st) == 0) { + files++; + ufw_scan_rules(&findings, &first, &count, path, &rules, + &open_sensitive, &writable); + } + if (files == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no ufw configuration found"); + return; + } + if (enabled == 0) { + add_finding(&findings, &first, "disabled", "high", + "ENABLED=no in ufw.conf: the ruleset is not loaded at " + "boot, so the host starts with no filtering"); + count++; + } else if (enabled < 0) { + add_finding(&findings, &first, "enabled-unset", "medium", + "ufw.conf has no ENABLED line, so ufw stays down " + "until an admin starts it by hand"); + count++; + } + if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "ufw is enabled, drops by default and every open " + "service port is source-restricted"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"enabled\":%s," + "\"default_accept\":%s,\"rules\":%d," + "\"open_sensitive\":%d,\"writable\":%d," + "\"findings_count\":%d,\"findings\":[", + files, enabled == 1 ? "true" : + (enabled == 0 ? "false" : "null"), + default_accept ? "true" : "false", rules, + open_sensitive, 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); +} + +/* -------------------------------------------------------------- monit_audit */ + +/* monitrc is a flat keyword file: "set httpd port 2812 and use address 0.0.0.0 + * allow admin:plaintext". Two shapes matter. An httpd block that does not say + * "use address localhost" (or binds a non-loopback address) exposes the + * control API. An "allow user:password" with a literal password rather than a + * hash ($2a$, $1$, {SHA}) hands the password to anyone who reads the file. */ +struct monit_state { + int httpd; + int httpd_public; + int plain_users; + int checks; + int no_alert; + int writable; +}; + +static int monit_is_hash(const char *pw) +{ + return pw[0] == '$' || pw[0] == '{' || + strncmp(pw, "crypt", 5) == 0; +} + +static void monit_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, struct monit_state *st) +{ + static char text[131072]; + struct stat statbuf; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + if (stat(path, &statbuf) == 0 && (statbuf.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone: a local user can add a " + "check that runs a command of their choice", path); + (*count)++; + st->writable = 1; + } + 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[32]; + int n = 0; + char *save = NULL; + char *word; + + 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'; + } + word = strtok_r(line, " \t", &save); + while (word != NULL && n < 32) { + tok[n++] = word; + word = strtok_r(NULL, " \t", &save); + } + if (n == 0) + continue; + if (strcmp(tok[0], "set") == 0 && n >= 2 && + strcmp(tok[1], "httpd") == 0) { + int i; + int localhost = 0; + + st->httpd = 1; + for (i = 2; i < n; i++) { + if (strcmp(tok[i], "localhost") == 0) + localhost = 1; + if (strcmp(tok[i], "0.0.0.0") == 0 || + strcmp(tok[i], "::") == 0 || + strcmp(tok[i], "*") == 0) + localhost = 0; + } + if (!localhost) + st->httpd_public = 1; + } else if (strcmp(tok[0], "allow") == 0 && n >= 2) { + char *colon = strchr(tok[1], ':'); + + if (colon != NULL && colon[1] != '\0' && + strcmp(colon + 1, "*") != 0 && + !monit_is_hash(colon + 1)) { + add_finding(findings, first, "plain-password", + "high", + "%s: user '%.*s' is allowed with a " + "plaintext password", path, + (int)(colon - tok[1]), tok[1]); + (*count)++; + st->plain_users++; + } + } else if (strcmp(tok[0], "check") == 0) { + st->checks++; + } + } +} + +static void t_monit_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *files[] = { "/etc/monit/monitrc", + "/etc/monitrc", NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + struct monit_state st; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + struct stat sb; + + snprintf(path, sizeof(path), "%.400s%s", root, files[i]); + if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) + continue; + files_read++; + monit_scan_file(&findings, &first, &count, path, &st); + } + snprintf(path, sizeof(path), "%.400s/etc/monit/monitrc.d", root); + { + DIR *d = opendir(path); + struct dirent *ent; + + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char sub[1300]; + + if (ent->d_name[0] == '.') + continue; + snprintf(sub, sizeof(sub), "%s/%s", path, + ent->d_name); + files_read++; + monit_scan_file(&findings, &first, &count, sub, + &st); + } + closedir(d); + } + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no monit configuration found"); + return; + } + if (st.httpd_public) { + add_finding(&findings, &first, "httpd-public", "high", + "set httpd does not bind to localhost: the monit " + "control API is reachable from the network"); + count++; + } + if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "monit exposes no public httpd and allows only " + "hashed passwords"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"httpd\":%s," + "\"httpd_public\":%s,\"plain_users\":%d," + "\"checks\":%d,\"writable\":%s," + "\"findings_count\":%d,\"findings\":[", + files_read, st.httpd ? "true" : "false", + st.httpd_public ? "true" : "false", st.plain_users, + st.checks, st.writable ? "true" : "false", count); + if (findings.p != NULL) + mcp_buf_add(&b, findings.p, findings.len); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&findings); +} + +/* ------------------------------------------------------------- clamav_audit */ + +/* clamd.conf and freshclam.conf are "Keyword value" files with # comments. The + * shapes worth reporting: TCPSocket enabled (clamd listens on TCP at all), + * TCPSocket bound beyond loopback, no LocalSocket for local scanners to use + * instead, and a VirusEvent/OnUpdateExecute hook, which runs as the clamd user + * on every detection and is a persistence path when the config is writable. */ +struct clam_state { + int tcp_socket; + int tcp_public; + int local_socket; + int hooks; + int log_rotate_off; + int writable; +}; + +static void clam_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, struct clam_state *st) +{ + static char text[131072]; + struct stat sb; + const char *p; + + if (read_text(path, text, sizeof(text)) <= 0) + return; + if (stat(path, &sb) == 0 && (sb.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone: a local user can point " + "clamd at their own binary", path); + (*count)++; + st->writable = 1; + } + 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 *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; + key = line; + while (*key == ' ' || *key == '\t') + key++; + if (*key == '#' || *key == '\0') + continue; + eq = strchr(key, ' '); + if (eq == NULL) + eq = strchr(key, '='); + if (eq == NULL) + continue; + *eq = '\0'; + val = eq + 1; + while (*val == ' ' || *val == '\t') + val++; + trim_eol(val); + /* A value may carry a trailing comment. */ + { + char *hash = strchr(val, '#'); + + if (hash != NULL) { + *hash = '\0'; + trim_eol(val); + } + } + if (strcasecmp(key, "TCPSocket") == 0) { + if (strcmp(val, "0") != 0) + st->tcp_socket = 1; + } else if (strcasecmp(key, "TCPAddr") == 0) { + if (strcmp(val, "127.0.0.1") != 0 && + strcmp(val, "::1") != 0 && strcmp(val, "localhost") + != 0) + st->tcp_public = 1; + } else if (strcasecmp(key, "LocalSocket") == 0) { + if (*val != '\0') + st->local_socket = 1; + } else if (strcasecmp(key, "VirusEvent") == 0 || + strcasecmp(key, "OnUpdateExecute") == 0) { + add_finding(findings, first, "exec-hook", "medium", + "%s: %s runs a command on every event; " + "anyone who can write the config gets code " + "execution as the clamav user", path, key); + (*count)++; + st->hooks++; + } else if (strcasecmp(key, "LogRotate") == 0) { + if (strcasecmp(val, "false") == 0 || + strcasecmp(val, "no") == 0 || strcmp(val, "0") == 0) + st->log_rotate_off = 1; + } + } +} + +static void t_clamav_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *files[] = { "/etc/clamav/clamd.conf", + "/etc/clamd.conf", + "/etc/clamav/freshclam.conf", NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + struct clam_state st; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + memset(&st, 0, sizeof(st)); + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + struct stat sb; + + snprintf(path, sizeof(path), "%.400s%s", root, files[i]); + if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) + continue; + files_read++; + clam_scan_file(&findings, &first, &count, path, &st); + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "no ClamAV configuration found"); + return; + } + if (st.tcp_socket) { + add_finding(&findings, &first, "tcp-socket", "medium", + "TCPSocket is enabled: clamd accepts commands over " + "TCP; a LocalSocket is the safer transport"); + count++; + } + if (st.tcp_public) { + add_finding(&findings, &first, "tcp-public", "high", + "TCPAddr is not a loopback address: clamd control " + "reaches the network"); + count++; + } + if (!st.local_socket && !st.tcp_socket) { + add_finding(&findings, &first, "no-transport", "low", + "neither LocalSocket nor TCPSocket is set: clamd " + "cannot be reached, which usually means nobody was " + "meant to use it"); + count++; + } + if (st.log_rotate_off) { + add_finding(&findings, &first, "log-rotate-off", "low", + "LogRotate is off: the scan log grows without bound " + "and can fill the disk"); + count++; + } + if (count == 0) { + add_finding(&findings, &first, "no-findings", "info", + "clamd listens on a local socket only, with no exec " + "hooks"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"tcp_socket\":%s," + "\"tcp_public\":%s,\"local_socket\":%s," + "\"hooks\":%d,\"log_rotate_off\":%s," + "\"writable\":%s,\"findings_count\":%d,\"findings\":[", + files_read, st.tcp_socket ? "true" : "false", + st.tcp_public ? "true" : "false", + st.local_socket ? "true" : "false", st.hooks, + st.log_rotate_off ? "true" : "false", + st.writable ? "true" : "false", count); + if (findings.p != NULL) + mcp_buf_add(&b, findings.p, findings.len); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&findings); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -26332,6 +27017,31 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_aide_audit }, + { "ufw_audit", + "Parse /etc/ufw/ufw.conf, /etc/default/ufw, user.rules and user6.rules " + "(root prefix): ENABLED=no or a missing ENABLED line, " + "DEFAULT_INPUT_POLICY=ACCEPT, an ACCEPT rule that reaches a service " + "port (22, 445, 3306, 5432, 6379, 27017, ...) from any source, and a " + "world-writable rule file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_ufw_audit }, + { "monit_audit", + "Parse /etc/monit/monitrc, /etc/monitrc and monitrc.d (root prefix): a " + "'set httpd' that does not bind to localhost, an 'allow user:password' " + "with a plaintext password instead of a hash, and a world-writable " + "config. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_monit_audit }, + { "clamav_audit", + "Parse clamd.conf and freshclam.conf (root prefix): TCPSocket enabled, " + "a TCPAddr beyond loopback, no LocalSocket at all, a VirusEvent or " + "OnUpdateExecute hook that runs as the clamav user, LogRotate off and " + "a world-writable config. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_clamav_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 ad4b701..370b00a 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -9001,6 +9001,92 @@ static void t_jupyter_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------------ jira_probe */ + +/* Jira REST without credentials: /rest/api/2/serverInfo and + * /rest/api/2/project answer anonymously on old or misconfigured instances + * even when the web UI asks for a login. Only a 2xx on /rest/api/2/project + * counts as open, and the project list becomes the evidence. */ +static void t_jira_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { "/rest/api/2/serverInfo", + "/rest/api/2/project", NULL }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 8080); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + mcp_buf b; + int first = 1; + int tested = 0; + int open_count = 0; + int projects_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, "jira_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 project = strcmp(paths[i], "/rest/api/2/project") == 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 (project) + projects_open = 1; + if (evidence == NULL) { + label[0] = '\0'; + snprintf(label, sizeof(label), "jira-%d", i); + evidence = apex_evidence_save(label, 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}", code); + 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("jira_probe", target, port, !projects_open, + projects_open + ? "the Jira project API answers without credentials" + : "the Jira project API requires credentials", "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: " @@ -9780,6 +9866,16 @@ const mcp_tool TOOLS_RED[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 8080\"}}," "\"required\":[\"target\"]}", t_airflow_probe }, + { "jira_probe", + "Query Jira on 8080 without credentials: /rest/api/2/serverInfo and " + "/rest/api/2/project. A 2xx on the project list means the whole project " + "inventory is public; its body is saved as evidence. Gate: the target " + "and port must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"},\"tls\":{\"type\":\"boolean\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 8080\"}}," + "\"required\":[\"target\"]}", + t_jira_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 2f767ba..7f08e8f 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 = 346 +EXPECTED_TOOLS = 350 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 a394923..bf63ba3 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("346 tools registered", len(tools) == 346, len(tools)) +check("350 tools registered", len(tools) == 350, 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"]) == 346) + check("http tools/list", len(listing["result"]["tools"]) == 350) 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 @@ -15788,6 +15788,187 @@ for d in (nscd_root, nscd_good_root, fl_root, fl_good_root, cfg48_home, sc_good_root, cfg49_home): shutil.rmtree(d, ignore_errors=True) +print("\n== ufw, monit, ClamAV and Jira ==\n") + +ufw_root = tempfile.mkdtemp(prefix="apex-ufw-") +os.makedirs(os.path.join(ufw_root, "etc", "ufw")) +ufw_conf = os.path.join(ufw_root, "etc", "ufw", "ufw.conf") +with open(ufw_conf, "w") as f: + f.write("ENABLED=no\n") +os.chmod(ufw_conf, 0o666) +ufw_rules = os.path.join(ufw_root, "etc", "ufw", "user.rules") +with open(ufw_rules, "w") as f: + f.write("-A ufw-user-input -p tcp --dport 23 -j ACCEPT\n") + f.write("-A ufw-user-input -p tcp --dport 445 -j ACCEPT\n") + f.write("-A ufw-user-input -p tcp --dport 443 -s 10.0.0.0/8 -j ACCEPT\n") + +ufw_good_root = tempfile.mkdtemp(prefix="apex-ufwg-") +os.makedirs(os.path.join(ufw_good_root, "etc", "ufw")) +with open(os.path.join(ufw_good_root, "etc", "ufw", "ufw.conf"), "w") as f: + f.write("ENABLED=yes\n") +os.makedirs(os.path.join(ufw_good_root, "etc", "default")) +with open(os.path.join(ufw_good_root, "etc", "default", "ufw"), "w") as f: + f.write('DEFAULT_INPUT_POLICY="DROP"\n') +with open(os.path.join(ufw_good_root, "etc", "ufw", "user.rules"), + "w") as f: + f.write("-A ufw-user-input -p tcp --dport 443 -j ACCEPT\n") + +monit_root = tempfile.mkdtemp(prefix="apex-monit-") +os.makedirs(os.path.join(monit_root, "etc")) +monitrc = os.path.join(monit_root, "etc", "monitrc") +with open(monitrc, "w") as f: + f.write("set daemon 60\n") + f.write("set httpd port 2812 and use address 0.0.0.0\n") + f.write(" allow admin:plainpw\n") + f.write("check process sshd with pidfile /var/run/sshd.pid\n") +os.chmod(monitrc, 0o666) + +monit_good_root = tempfile.mkdtemp(prefix="apex-monitg-") +os.makedirs(os.path.join(monit_good_root, "etc")) +with open(os.path.join(monit_good_root, "etc", "monitrc"), "w") as f: + f.write("set daemon 60\n") + f.write("set httpd port 2812 and use address localhost\n") + f.write(" allow admin:$2y$10$abcdefghijklmnopqrstuv\n") + +cl_root = tempfile.mkdtemp(prefix="apex-clam-") +os.makedirs(os.path.join(cl_root, "etc")) +clamd = os.path.join(cl_root, "etc", "clamd.conf") +with open(clamd, "w") as f: + f.write("TCPSocket 3310\n") + f.write("TCPAddr 0.0.0.0\n") + f.write("VirusEvent /usr/local/bin/notify.sh\n") + f.write("LogRotate no\n") +os.chmod(clamd, 0o666) +with open(os.path.join(cl_root, "etc", "freshclam.conf"), "w") as f: + f.write("UpdateLogFile /var/log/freshclam.log\n") + f.write("NotifyClamd /etc/clamd.conf\n") + +cl_good_root = tempfile.mkdtemp(prefix="apex-clamg-") +os.makedirs(os.path.join(cl_good_root, "etc")) +with open(os.path.join(cl_good_root, "etc", "clamd.conf"), "w") as f: + f.write("LocalSocket /run/clamav/clamd.ctl\n") + f.write("LogRotate yes\n") + +class _JiraHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + docs = { + "/rest/api/2/serverInfo": b'{"version":"9.4.0"}', + "/rest/api/2/project": (b'[{"key":"OPS","name":"Operations"},' + b'{"key":"DEV","name":"Development"}]'), + } + body = docs.get(path, b'{"errorMessages":["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 _JiraClosedHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + path = urllib.parse.urlsplit(self.path).path + if path == "/rest/api/2/serverInfo": + body = b'{"version":"9.4.0"}' + self.send_response(200) + else: + body = b'{"errorMessages":["You are not authenticated"]}' + 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 + + +jr_srv = http.server.HTTPServer(("127.0.0.1", 0), _JiraHandler) +jr_port = jr_srv.server_address[1] +threading.Thread(target=jr_srv.serve_forever, daemon=True).start() +jr_closed_srv = http.server.HTTPServer(("127.0.0.1", 0), _JiraClosedHandler) +jr_closed_port = jr_closed_srv.server_address[1] +threading.Thread(target=jr_closed_srv.serve_forever, daemon=True).start() + +cfg51_home = tempfile.mkdtemp(prefix="apex-cfg51-home-") +write_scope(cfg51_home, + {"label": "cfg51", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(jr_port), str(jr_closed_port)]}) + +res, _ = run([ + call(1, "ufw_audit", root=ufw_root), + call(2, "ufw_audit", root=ufw_good_root), + call(3, "monit_audit", root=monit_root), + call(4, "monit_audit", root=monit_good_root), + call(5, "clamav_audit", root=cl_root), + call(6, "clamav_audit", root=cl_good_root), + call(7, "jira_probe", target="127.0.0.1", port=jr_port, tls=False), + call(8, "jira_probe", target="127.0.0.1", port=jr_closed_port, tls=False), + call(9, "jira_probe", target="198.51.100.9", port=jr_port, tls=False), +], home=cfg51_home) +by_id = {r.get("id"): r for r in res} + +uf = json.loads(text(by_id[1])) +uf_kinds = {f["id"] for f in uf["findings"]} +check("ufw_audit flags a disabled firewall, open sensitive ports and a " + "writable config", + {"world-writable", "disabled", "open-sensitive-port"} <= uf_kinds and + uf["enabled"] is False and uf["open_sensitive"] >= 2, uf) +uf_good = json.loads(text(by_id[2])) +check("ufw_audit accepts an enabled firewall with a drop policy", + {f["id"] for f in uf_good["findings"]} == {"no-findings"} and + uf_good["enabled"] is True and uf_good["default_accept"] is False, + uf_good) + +mo = json.loads(text(by_id[3])) +mo_kinds = {f["id"] for f in mo["findings"]} +check("monit_audit flags a public httpd, a plain password and a writable " + "monitrc", + {"world-writable", "httpd-public", "plain-password"} <= mo_kinds and + mo["httpd_public"] is True and mo["plain_users"] == 1, mo) +mo_good = json.loads(text(by_id[4])) +check("monit_audit accepts a loopback httpd with a hashed password", + {f["id"] for f in mo_good["findings"]} == {"no-findings"} and + mo_good["httpd_public"] is False and mo_good["plain_users"] == 0, + mo_good) + +cl = json.loads(text(by_id[5])) +cl_kinds = {f["id"] for f in cl["findings"]} +check("clamav_audit flags a public TCPSocket, an exec hook and no log " + "rotation", + {"world-writable", "tcp-public", "exec-hook", + "log-rotate-off"} <= cl_kinds + and cl["tcp_public"] is True and cl["hooks"] == 1 and + cl["local_socket"] is False, cl) +cl_good = json.loads(text(by_id[6])) +check("clamav_audit accepts a local socket without hooks", + {f["id"] for f in cl_good["findings"]} == {"no-findings"} and + cl_good["tcp_socket"] is False and cl_good["local_socket"] is True, + cl_good) + +jr = json.loads(text(by_id[7])) +check("jira_probe finds an open project API and saves the list", + jr["projects_open"] is True and jr["open_count"] == 2 and + os.path.isfile(jr["evidence"]), jr) +jr_closed = json.loads(text(by_id[8])) +check("jira_probe reports a closed project API as not open", + jr_closed["projects_open"] is False and + jr_closed["open_count"] == 1, jr_closed) +jr_out = by_id[9] +check("jira_probe refuses an out-of-scope target", bool(err(jr_out)), jr_out) + +jr_srv.shutdown() +jr_closed_srv.shutdown() + +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) + print("%d passed, %d failed" % (passes, len(fails))) if fails: print("failed: " + ", ".join(fails))