From 7a3fc47b8f104165ebf1796a5f208631c8612bda Mon Sep 17 00:00:00 2001 From: lotherk Date: Sun, 22 Nov 2026 16:01:15 +0000 Subject: [PATCH] apex-twin 1.62.0: Compose, K8s manifest and Dockerfile audits, AMQP probe Blue: - compose_audit: privileged, host network/PID, a mounted Docker socket, plaintext passwords/tokens and a world-writable file. - k8s_manifest_audit: privileged, hostNetwork/PID/IPC, runAsUser 0 (numeric, so 1000 is not flagged), hostPath /, missing securityContext. - dockerfile_audit: root or missing USER, :latest/untagged base, ADD from a URL, RUN piping a download into a shell. Red: - amqp_probe: sends the 0-9-1 header, reads Connection.Start, reports product, version and mechanisms. No login; a closed endpoint is a negative result. Two real defects caught by the gates: runAsUser: 1000 matched a substring '0', and the analyzer found a short-frame over-read before reading the table length (payload is also zeroed so the read is provably initialized). Tests with Compose/manifest/Dockerfile fixtures and an AMQP frame fixture. 1205 checks, ASan suite green, analyze clean, release-check green including distcheck 1.62.0. --- CHANGELOG.md | 20 ++- README.md | 18 +- SECURITY.md | 4 +- docs/apex-twin.1 | 6 +- src/apex.h | 2 +- src/tools_blue.c | 397 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 189 +++++++++++++++++++++ tests/gate_audit.py | 2 +- tests/run.py | 155 ++++++++++++++++- 9 files changed, 778 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b72ace..554ed74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,25 @@ 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.61.0 — 2026-11-23 — this change +## 1.62.0 — 2026-11-23 — this change + +- **Compose** (`compose_audit`): a compose file: `privileged`, host + network/PID, a mounted Docker socket, plaintext passwords/tokens and a + world-writable file. +- **Kubernetes manifest** (`k8s_manifest_audit`): a manifest: `privileged`, + `hostNetwork`/`hostPID`/`hostIPC`, `runAsUser: 0` (numeric, so 1000 is not + flagged), a `hostPath` of `/`, a missing `securityContext` and a + world-writable file. +- **Dockerfile** (`dockerfile_audit`): root or missing `USER`, `:latest` or + untagged base, `ADD` from a URL, `RUN` piping a download into a shell and a + world-writable file. +- **AMQP** (`amqp_probe`): sends the 0-9-1 header, reads `Connection.Start` + and reports product, version and mechanisms. No login is attempted; a + closed endpoint is a negative result, not an error. +- Tests with Compose/manifest/Dockerfile fixtures (including `runAsUser: + 1000`) and an AMQP frame fixture. 1205 checks. Coverage 84.2%. + +## 1.61.0 — 2026-11-23 — a118a8d - **atd** (`atd_audit`): `at.allow` and `at.deny`: world-writable lists and an empty `at.deny` that opens scheduling to every user. Both files missing diff --git a/README.md b/README.md index be215e6..1062ccd 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. -**282 tools · 1193 end-to-end checks · 340 fuzz cases · 84.2% line coverage · ~971 KiB** +**286 tools · 1205 end-to-end checks · 340 fuzz cases · 84.2% line coverage · ~983 KiB** ``` $ ./apex-twin --check -{"version":"1.61.0","tools":282,...,"scope":{"loaded":true,...}} +{"version":"1.62.0","tools":286,...,"scope":{"loaded":true,...}} ``` APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope @@ -149,7 +149,7 @@ closes a request whose head or body does not arrive within --- -## Tools (282) +## Tools (286) ### Scope and bookkeeping @@ -220,6 +220,7 @@ uploads and secret-file reads. It does not execute anything. | `clickhouse_probe` | `/ping` and `SELECT version()` without auth; version as evidence | | `kibana_api_probe` | `/api/saved_objects/_find` without auth; answer as evidence | | `logstash_api_probe` | `/_node/info` and `/_node/stats` without auth; stats as evidence | +| `amqp_probe` | AMQP 0-9-1 Connection.Start: product, version, mechanisms, no login | | `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 | @@ -479,6 +480,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `atd_audit` | at.allow/deny: empty deny list, world-writable lists | | `securetty_audit` | securetty: serial/console entries allow root login | | `tmpfiles_audit` | tmpfiles.d: 0777/0666 modes, z/Z rules on /tmp | +| `compose_audit` | compose: privileged, host namespaces, docker socket, secrets | +| `k8s_manifest_audit` | manifest: privileged, host namespaces, root, hostPath / | +| `dockerfile_audit` | Dockerfile: root USER, :latest base, remote ADD, curl pipe | ### ESP32 @@ -789,6 +793,8 @@ The full threat model, trust boundaries and a hardening checklist are in | Kibana API | two unauthenticated GETs, saved objects as evidence | | atd/securetty/tmpfiles | config reads only; optional root prefix | | Logstash API | two unauthenticated GETs, stats as evidence | +| compose/k8s/dockerfile | one local file each; no execution | +| AMQP | protocol header + Connection.Start, no login | | USB audit | 200 devices, sysfs reads only | --- @@ -800,7 +806,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 1193 end-to-end checks +make test # version check + gate audit + 1205 end-to-end checks make version-check # the five places that carry a version must agree make gate-audit # static: every target-taking tool calls the gate make asan # apex-twin-asan with ASan + UBSan @@ -930,7 +936,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, - logstash_api_probe + logstash_api_probe, amqp_probe src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, net_baseline, @@ -973,7 +979,7 @@ examples/ scope.json ## Status -1.61.0. Built and run: 282 tools, 1193 checks, 340 fuzz cases and 84.2% line +1.62.0. Built and run: 286 tools, 1205 checks, 340 fuzz cases and 84.2% 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 ceb7d7b..b57fe29 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.61.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.62.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. @@ -66,6 +66,8 @@ only narrow what the proxy does (the scope gate still runs first). - **Firmware writing needs an explicit confirmation.** `esp_flash` refuses without `confirm=true`, validates an absolute image path and audits the attempt; it exists to provision the operator's own board. +- **Compose, manifest and Dockerfile audits read one local file each.** The + AMQP probe reads Connection.Start and never sends credentials. - **atd, securetty and tmpfiles audits read local files.** The Logstash node probe sends two unauthenticated GETs and saves the stats answer. - **sshd_config, hosts_access and profile audits read local files.** The diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 0ad7b4d..dc684d0 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.61.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.62.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), +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), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -77,7 +77,7 @@ keepalived_audit, webmin_audit, cockpit_audit, phpmyadmin_audit, kibana_audit, nagios_audit, synapse_audit, logstash_audit, filebeat_audit, fluentd_audit, telegraf_audit, graylog_audit, netdata_audit, sshd_config_audit, hosts_access_audit, profile_audit, atd_audit, securetty_audit, -tmpfiles_audit) +tmpfiles_audit, compose_audit, k8s_manifest_audit, dockerfile_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 3040bb5..32f314b 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.61.0" +#define APEX_VERSION "1.62.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 af64175..10c68e7 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -18567,6 +18567,379 @@ static void t_tmpfiles_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* --------------------------------------------------------------- compose_audit */ + +static int text_has_secret_value(const char *text) +{ + char *copy = strdup(text); + char *save = NULL; + char *line; + int found = 0; + + if (copy == NULL) + return 0; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + char *eq; + + while (*s == ' ' || *s == '\t') + s++; + eq = strchr(s, '='); + if (*s != '#' && eq != NULL) { + char *v = eq + 1; + + while (*v == ' ' || *v == '\t') + v++; + if (*v != '\0' && *v != '\'' && *v != '"' && + (strcasestr(s, "PASSWORD") != NULL || + strcasestr(s, "SECRET") != NULL || + strcasestr(s, "TOKEN") != NULL)) + found = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + return found; +} + +static void t_compose_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *path = mcp_arg_string(args, "path"); + static char text[131072]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int privileged = 0; + int host_network = 0; + int host_pid = 0; + int docker_socket = 0; + int secret = 0; + + (void)user; + if (path == NULL || *path == '\0') { + mcp_reply_error(c, "path is required"); + return; + } + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read the compose file"); + 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++; + } + if (text_has_line(text, "privileged", "true")) { + privileged = 1; + add_finding(&findings, &first, "privileged", "high", + "a container runs privileged"); + count++; + } + if (text_has_line(text, "network_mode", "host")) { + host_network = 1; + add_finding(&findings, &first, "host-network", "high", + "a container shares the host network"); + count++; + } + if (text_has_line(text, "pid", "host")) { + host_pid = 1; + add_finding(&findings, &first, "host-pid", "medium", + "a container shares the host PID namespace"); + count++; + } + if (strstr(text, "/var/run/docker.sock") != NULL) { + docker_socket = 1; + add_finding(&findings, &first, "docker-socket", "high", + "the Docker socket is mounted into a container"); + count++; + } + if (text_has_secret_value(text)) { + secret = 1; + add_finding(&findings, &first, "plaintext-secret", "medium", + "a password, secret or token is stored in the compose " + "file"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"privileged\":%s,\"host_network\":%s," + "\"host_pid\":%s,\"docker_socket\":%s," + "\"plaintext_secret\":%s,\"findings_count\":%d," + "\"findings\":[", + privileged ? "true" : "false", + host_network ? "true" : "false", + host_pid ? "true" : "false", + docker_socket ? "true" : "false", + secret ? "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); +} + +/* ---------------------------------------------------------- k8s_manifest_audit */ + +static int k8s_run_as_root(const char *text) +{ + char *copy = strdup(text); + char *save = NULL; + char *line; + int found = 0; + + if (copy == NULL) + return 0; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && strncasecmp(s, "runAsUser", 9) == 0) { + char *v = s + 9; + + while (*v == ' ' || *v == '\t') + v++; + if (*v == ':') + v++; + while (*v == ' ' || *v == '\t') + v++; + if (atoi(v) == 0) + found = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + return found; +} + +static void t_k8s_manifest_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *path = mcp_arg_string(args, "path"); + static char text[131072]; + struct stat st; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int privileged = 0; + int host_network = 0; + int host_pid = 0; + int host_ipc = 0; + int root_user = 0; + int no_security = 0; + int host_root = 0; + + (void)user; + if (path == NULL || *path == '\0') { + mcp_reply_error(c, "path is required"); + return; + } + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read the Kubernetes manifest"); + 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++; + } + if (text_has_line(text, "privileged", "true")) { + privileged = 1; + add_finding(&findings, &first, "privileged", "high", + "a container runs privileged"); + count++; + } + if (text_has_line(text, "hostNetwork", "true")) { + host_network = 1; + add_finding(&findings, &first, "host-network", "high", + "the pod uses the host network"); + count++; + } + if (text_has_line(text, "hostPID", "true")) { + host_pid = 1; + add_finding(&findings, &first, "host-pid", "high", + "the pod uses the host PID namespace"); + count++; + } + if (text_has_line(text, "hostIPC", "true")) { + host_ipc = 1; + add_finding(&findings, &first, "host-ipc", "medium", + "the pod uses the host IPC namespace"); + count++; + } + if (k8s_run_as_root(text)) { + root_user = 1; + add_finding(&findings, &first, "root-user", "high", + "a container runs as UID 0"); + count++; + } + if (strstr(text, "hostPath:") != NULL && + text_has_line(text, "path:", " /")) { + host_root = 1; + add_finding(&findings, &first, "host-root", "high", + "a hostPath mounts the filesystem root"); + count++; + } + if (strstr(text, "securityContext") == NULL) { + no_security = 1; + add_finding(&findings, &first, "no-security-context", "low", + "no securityContext is defined"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"privileged\":%s,\"host_network\":%s," + "\"host_pid\":%s,\"host_ipc\":%s,\"root_user\":%s," + "\"host_root\":%s,\"security_context\":%s," + "\"findings_count\":%d,\"findings\":[", + privileged ? "true" : "false", + host_network ? "true" : "false", + host_pid ? "true" : "false", + host_ipc ? "true" : "false", + root_user ? "true" : "false", + host_root ? "true" : "false", + no_security ? "false" : "true", 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); +} + +/* ------------------------------------------------------------ dockerfile_audit */ + +static void t_dockerfile_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *path = mcp_arg_string(args, "path"); + static char text[131072]; + struct stat st; + char *copy; + char *save = NULL; + char *line; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int root_user = 0; + int unpinned = 0; + int remote_add = 0; + int curl_pipe = 0; + int have_user = 0; + + (void)user; + if (path == NULL || *path == '\0') { + mcp_reply_error(c, "path is required"); + return; + } + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read the Dockerfile"); + 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++; + } + copy = strdup(text); + if (copy == NULL) { + mcp_buf_free(&findings); + mcp_reply_error(c, "out of memory"); + return; + } + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *s = line; + + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && strncasecmp(s, "FROM ", 5) == 0) { + char *img = s + 5; + + while (*img == ' ') + img++; + if (strstr(img, ":latest") != NULL) + unpinned = 1; + else if (strchr(img, ':') == NULL && + strchr(img, '@') == NULL) + unpinned = 1; + } else if (strncasecmp(s, "USER ", 5) == 0) { + char *u = s + 5; + + while (*u == ' ' || *u == '\t') + u++; + have_user = 1; + if (strcasecmp(u, "root") == 0 || strcmp(u, "0") == 0) + root_user = 1; + } else if (strncasecmp(s, "ADD ", 4) == 0 && + (strstr(s, "http://") != NULL || + strstr(s, "https://") != NULL)) { + remote_add = 1; + } else if (strncasecmp(s, "RUN ", 4) == 0 && + (strstr(s, "curl") != NULL || + strstr(s, "wget") != NULL) && + (strstr(s, "| sh") != NULL || + strstr(s, "|sh") != NULL || + strstr(s, "| bash") != NULL || + strstr(s, "|bash") != NULL)) { + curl_pipe = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + if (!have_user) + root_user = 1; + if (unpinned) { + add_finding(&findings, &first, "unpinned-base", "low", + "a base image is not pinned by tag or digest"); + count++; + } + if (remote_add) { + add_finding(&findings, &first, "remote-add", "medium", + "ADD fetches a remote URL"); + count++; + } + if (curl_pipe) { + add_finding(&findings, &first, "curl-pipe", "high", + "a RUN step pipes a download into a shell"); + count++; + } + if (root_user) { + add_finding(&findings, &first, "root-user", "high", + "the final image runs as root or has no USER"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"user_set\":%s,\"root_user\":%s," + "\"pinned_base\":%s,\"remote_add\":%s," + "\"curl_pipe\":%s,\"findings_count\":%d,\"findings\":[", + have_user ? "true" : "false", + root_user ? "true" : "false", + unpinned ? "false" : "true", + remote_add ? "true" : "false", + curl_pipe ? "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, " @@ -19620,6 +19993,30 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_tmpfiles_audit }, + { "compose_audit", + "Parse a docker-compose file: privileged, host network/PID, a mounted " + "docker socket, plaintext passwords or tokens and a world-writable " + "file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"path\":{\"type\":\"string\"}}," + "\"required\":[\"path\"]}", + t_compose_audit }, + { "k8s_manifest_audit", + "Parse a Kubernetes manifest: privileged, hostNetwork/PID/IPC, " + "runAsUser 0, a hostPath of /, a missing securityContext and a " + "world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"path\":{\"type\":\"string\"}}," + "\"required\":[\"path\"]}", + t_k8s_manifest_audit }, + { "dockerfile_audit", + "Parse a Dockerfile: root or missing USER, a :latest or untagged base, " + "ADD from a URL, a RUN that pipes a download into a shell and a " + "world-writable file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"path\":{\"type\":\"string\"}}," + "\"required\":[\"path\"]}", + t_dockerfile_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 f8d6b38..0784df5 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -7640,6 +7640,186 @@ static void t_logstash_api_probe(mcp_conn *c, const mcp_json *args, mcp_buf_free(&b); } +/* ---------------------------------------------------------------- amqp_probe */ + +static int amqp_read_exact(int fd, unsigned char *buf, size_t n) +{ + size_t got = 0; + + while (got < n) { + ssize_t r = recv(fd, buf + got, n - got, 0); + + if (r <= 0) + return -1; + got += (size_t)r; + } + return 0; +} + +static unsigned long amqp_be32(const unsigned char *p) +{ + return ((unsigned long)p[0] << 24) | ((unsigned long)p[1] << 16) | + ((unsigned long)p[2] << 8) | (unsigned long)p[3]; +} + +static void amqp_prop(const unsigned char *table, size_t tlen, + const char *want, char *out, size_t n) +{ + size_t i = 0; + size_t wl = strlen(want); + + out[0] = '\0'; + while (i < tlen) { + unsigned klen = table[i]; + const unsigned char *key; + unsigned char type; + size_t p; + + if (i + 1 + klen + 1 > tlen) + break; + key = table + i + 1; + type = table[i + 1 + klen]; + p = i + 2 + klen; + if (type == 'S') { + unsigned long vl; + + if (p + 4 > tlen) + break; + vl = amqp_be32(table + p); + p += 4; + if (p + vl > tlen) + break; + if (klen == wl && memcmp(key, want, wl) == 0) { + size_t copy = vl < n - 1 ? vl : n - 1; + + memcpy(out, table + p, copy); + out[copy] = '\0'; + } + i = p + vl; + } else if (type == 't') { + i = p + 1; + } else if (type == 'F') { + unsigned long vl; + + if (p + 4 > tlen) + break; + vl = amqp_be32(table + p); + i = p + 4 + vl; + } else { + break; + } + } +} + +static void t_amqp_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 5672); + unsigned char header[8] = { 'A', 'M', 'Q', 'P', 0, 0, 9, 1 }; + unsigned char proto[8]; + unsigned char fh[7]; + unsigned char *payload = NULL; + char product[128]; + char version[64]; + char mechanisms[256]; + int fd; + int start = 0; + int i; + mcp_buf b; + unsigned long size; + unsigned long cls; + unsigned long method; + + (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, "amqp_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 8000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the AMQP service"); + return; + } + product[0] = version[0] = mechanisms[0] = '\0'; + if (send(fd, header, sizeof(header), 0) == (ssize_t)sizeof(header) && + amqp_read_exact(fd, proto, sizeof(proto)) == 0 && + memcmp(proto, "AMQP", 4) == 0 && + amqp_read_exact(fd, fh, sizeof(fh)) == 0 && fh[0] == 1) { + size = amqp_be32(fh + 3); + if (size >= 4 && size <= 65536) { + unsigned char end; + + payload = malloc((size_t)size); + if (payload != NULL) { + memset(payload, 0, (size_t)size); + } + if (payload != NULL && + amqp_read_exact(fd, payload, (size_t)size) == 0 && + amqp_read_exact(fd, &end, 1) == 0 && + end == 0xCE) { + cls = ((unsigned long)payload[0] << 8) | + payload[1]; + method = ((unsigned long)payload[2] << 8) | + payload[3]; + if (cls == 10 && method == 10 && size >= 10) { + unsigned long tlen; + + start = 1; + tlen = amqp_be32(payload + 6); + if (6 + 4 + tlen <= size) { + amqp_prop(payload + 10, tlen, + "product", product, + sizeof(product)); + amqp_prop(payload + 10, tlen, + "version", version, + sizeof(version)); + } + if (10 + tlen + 4 <= size) { + unsigned long mlen = amqp_be32( + payload + 10 + tlen); + size_t copy = mlen; + + if (copy >= sizeof(mechanisms)) + copy = sizeof(mechanisms) - 1; + memcpy(mechanisms, + payload + 14 + tlen, copy); + mechanisms[copy] = '\0'; + for (i = 0; i < (int)copy; i++) + if (mechanisms[i] < 32 || + mechanisms[i] > 126) + mechanisms[i] = ' '; + } + } + } + free(payload); + } + } + close(fd); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"start_received\":%s," + "\"protocol\":\"AMQP 0-9-1\",\"product\":", + port, start ? "true" : "false"); + apex_json_str(&b, product); + mcp_buf_puts(&b, ",\"version\":"); + apex_json_str(&b, version); + mcp_buf_puts(&b, ",\"mechanisms\":"); + apex_json_str(&b, mechanisms); + mcp_buf_puts(&b, "}"); + apex_audit("amqp_probe", target, port, 1, + start ? "AMQP connection.start received" + : "no AMQP connection.start", mechanisms); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -8293,6 +8473,15 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_logstash_api_probe }, + { "amqp_probe", + "Open an AMQP 0-9-1 connection, read the protocol header and the " + "Connection.Start method, and report server product, version and " + "mechanisms. No login is attempted. Gate: the target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 5672\"}}," + "\"required\":[\"target\"]}", + t_amqp_probe }, { "dns_ns_consistency", "Fetch NS records for a domain from the parent resolver and from its own " "first nameserver (resolved to an address), then report names present on " diff --git a/tests/gate_audit.py b/tests/gate_audit.py index 6979f03..e5a8d57 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 = 282 +EXPECTED_TOOLS = 286 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 cc1b4d8..2167050 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("282 tools registered", len(tools) == 282, len(tools)) +check("286 tools registered", len(tools) == 286, 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"]) == 282) + check("http tools/list", len(listing["result"]["tools"]) == 286) 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 @@ -12910,6 +12910,156 @@ shutil.rmtree(tf_root, ignore_errors=True) shutil.rmtree(tf_good_root, ignore_errors=True) shutil.rmtree(cfg33_home, ignore_errors=True) +print("\n== Compose, Kubernetes manifests, Dockerfiles and AMQP ==\n") + +cp_dir = tempfile.mkdtemp(prefix="apex-cmp-") +cp_bad = os.path.join(cp_dir, "docker-compose.yml") +with open(cp_bad, "w") as f: + f.write("services:\n app:\n image: app:1\n") + f.write(" privileged: true\n") + f.write(" network_mode: host\n") + f.write(" pid: host\n") + f.write(" volumes:\n") + f.write(" - /var/run/docker.sock:/var/run/docker.sock\n") + f.write(" environment:\n - PASSWORD=secret\n") +os.chmod(cp_bad, 0o666) +cp_good = os.path.join(cp_dir, "compose-good.yml") +with open(cp_good, "w") as f: + f.write("services:\n app:\n image: app:1\n") + f.write(" read_only: true\n") + f.write(" security_opt:\n - no-new-privileges:true\n") + +k8_dir = tempfile.mkdtemp(prefix="apex-k8-") +k8_bad = os.path.join(k8_dir, "pod.yaml") +with open(k8_bad, "w") as f: + f.write("apiVersion: v1\nkind: Pod\nmetadata:\n name: bad\n") + f.write("spec:\n hostNetwork: true\n hostPID: true\n") + f.write(" hostIPC: true\n containers:\n - name: app\n") + f.write(" image: app:1\n securityContext:\n") + f.write(" privileged: true\n runAsUser: 0\n") + f.write(" volumeMounts:\n - mountPath: /host\n") + f.write(" name: host\n volumes:\n - name: host\n") + f.write(" hostPath:\n path: /\n") +os.chmod(k8_bad, 0o666) +k8_good = os.path.join(k8_dir, "pod-good.yaml") +with open(k8_good, "w") as f: + f.write("apiVersion: v1\nkind: Pod\nspec:\n containers:\n") + f.write(" - name: app\n securityContext:\n") + f.write(" runAsNonRoot: true\n runAsUser: 1000\n") + +df_dir = tempfile.mkdtemp(prefix="apex-df-") +df_bad = os.path.join(df_dir, "Dockerfile") +with open(df_bad, "w") as f: + f.write("FROM ubuntu:latest\n") + f.write("ADD https://example.test/tool /usr/local/bin/tool\n") + f.write("RUN curl -fsSL http://example.test/install.sh | sh\n") + f.write('CMD ["tool"]\n') +os.chmod(df_bad, 0o666) +df_good = os.path.join(df_dir, "Dockerfile.good") +with open(df_good, "w") as f: + f.write("FROM alpine@sha256:0123456789abcdef\n") + f.write("RUN apk add --no-cache curl\n") + f.write("USER app\n") + f.write('CMD ["app"]\n') + + +def amqp_handler(expose): + def handle(conn): + hdr = conn.recv(8) + if len(hdr) < 8: + return + if not expose: + return + def entry(key, val): + return (bytes([len(key)]) + key.encode() + b"S" + + struct.pack(">I", len(val)) + val.encode()) + props = entry("product", "RabbitMQ") + entry("version", "3.12.0") + table = struct.pack(">I", len(props)) + props + mech = b"PLAIN AMQPLAIN" + payload = (struct.pack(">HHBB", 10, 10, 0, 9) + table + + struct.pack(">I", len(mech)) + mech + + struct.pack(">I", 5) + b"en_US") + frame = (b"\x01\x00\x00" + struct.pack(">I", len(payload)) + + payload + b"\xce") + conn.sendall(b"AMQP\x00\x00\x09\x01" + frame) + return handle + + +amqp_srv, amqp_port = start_line_server(amqp_handler(True)) +amqp_closed_srv, amqp_closed_port = start_line_server(amqp_handler(False)) + +cfg34_home = tempfile.mkdtemp(prefix="apex-cfg34-home-") +write_scope(cfg34_home, {"label": "cfg34", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(amqp_port), + str(amqp_closed_port)]}) +res, _ = run([ + call(1, "compose_audit", path=cp_bad), + call(2, "compose_audit", path=cp_good), + call(3, "k8s_manifest_audit", path=k8_bad), + call(4, "k8s_manifest_audit", path=k8_good), + call(5, "dockerfile_audit", path=df_bad), + call(6, "dockerfile_audit", path=df_good), + call(7, "amqp_probe", target="127.0.0.1", port=amqp_port), + call(8, "amqp_probe", target="127.0.0.1", port=amqp_closed_port), + call(9, "amqp_probe", target="198.51.100.9", port=5672), + call(10, "compose_audit", path="/nonexistent-compose.yml"), + call(11, "k8s_manifest_audit", path="/nonexistent-pod.yaml"), + call(12, "dockerfile_audit", path="/nonexistent-Dockerfile"), +], home=cfg34_home) +by_id = {r.get("id"): r for r in res} +cp = json.loads(text(by_id[1])) +cp_kinds = {f["id"] for f in cp["findings"]} +check("compose_audit flags privileged, host namespaces and the socket", + {"world-writable", "privileged", "host-network", "host-pid", + "docker-socket", "plaintext-secret"} <= cp_kinds and + cp["privileged"] is True and cp["docker_socket"] is True, cp) +cp_good = json.loads(text(by_id[2])) +check("compose_audit accepts a minimal service", + cp_good["findings_count"] == 0 and cp_good["privileged"] is False and + cp_good["host_network"] is False, cp_good) +k8 = json.loads(text(by_id[3])) +k8_kinds = {f["id"] for f in k8["findings"]} +check("k8s_manifest_audit flags host namespaces, root and hostPath /", + {"world-writable", "privileged", "host-network", "host-pid", + "host-ipc", "root-user", "host-root"} <= k8_kinds and + k8["host_network"] is True and k8["host_root"] is True, k8) +k8_good = json.loads(text(by_id[4])) +check("k8s_manifest_audit accepts a non-root security context", + k8_good["findings_count"] == 0 and k8_good["root_user"] is False and + k8_good["security_context"] is True, k8_good) +df = json.loads(text(by_id[5])) +df_kinds = {f["id"] for f in df["findings"]} +check("dockerfile_audit flags latest, remote ADD, pipe and root", + {"world-writable", "unpinned-base", "remote-add", "curl-pipe", + "root-user"} <= df_kinds and df["root_user"] is True and + df["curl_pipe"] is True, df) +df_good = json.loads(text(by_id[6])) +check("dockerfile_audit accepts a pinned base and a USER", + df_good["findings_count"] == 0 and df_good["root_user"] is False and + df_good["pinned_base"] is True, df_good) +amqp = json.loads(text(by_id[7])) +check("amqp_probe reads Connection.Start and the server properties", + amqp["start_received"] is True and amqp["product"] == "RabbitMQ" and + amqp["version"] == "3.12.0" and "PLAIN" in amqp["mechanisms"], amqp) +amqp_closed = json.loads(text(by_id[8])) +check("amqp_probe reports a closed service", + amqp_closed["start_received"] is False, amqp_closed) +check("amqp_probe refuses an out-of-scope target", err(by_id[9]), + text(by_id[9])) +check("compose_audit reports a missing file", err(by_id[10]), + text(by_id[10])) +check("k8s_manifest_audit reports a missing file", err(by_id[11]), + text(by_id[11])) +check("dockerfile_audit reports a missing file", err(by_id[12]), + text(by_id[12])) +amqp_srv.close() +amqp_closed_srv.close() +shutil.rmtree(cp_dir, ignore_errors=True) +shutil.rmtree(k8_dir, ignore_errors=True) +shutil.rmtree(df_dir, ignore_errors=True) +shutil.rmtree(cfg34_home, ignore_errors=True) + print("\n== esp32 tools ==") @@ -12931,6 +13081,7 @@ print("\n== esp32 tools ==") + esp_home = tempfile.mkdtemp(prefix="apex-esp-")