diff --git a/CHANGELOG.md b/CHANGELOG.md index 49f7c3c..092230f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,23 @@ 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.21.0 — 2026-11-21 — this change +## 1.22.0 — 2026-11-21 — this change + +- **SMTP relay** (`smtp_open_relay`): EHLO, MAIL FROM an .invalid sender, RCPT + TO an external recipient; 250/251/252 means the server relays without + authentication. DATA is never sent, so no mail leaves the server; 530 is + reported as an auth requirement. +- **DNS resolver** (`dns_open_resolver`): one gated recursive dig against an + in-scope server; an answer means the resolver is open (amplification risk). +- **AppArmor** (`apparmor_audit`): reads the profile list (root prefix), + counts enforce/complain and names complain profiles; flags an AppArmor with + no active profile. +- **SELinux** (`selinux_audit`): enforce file, SELINUX=/SELINUXTYPE= and the + boolean count; flags disabled, permissive and a host without SELinux. +- Tests with SMTP relay/refusing fixtures, DNS recursive/refusing agents, + AppArmor profile and SELinux trees. 717 checks. Coverage 80.4%. + +## 1.21.0 — 2026-11-21 — 930b356 - **SMB shares** (`smb_shares`): after the anonymous SMB 2.1 session, tries TREE_CONNECT for 14 common share names (IPC$, C$, ADMIN$, users, data, diff --git a/README.md b/README.md index 6a976f9..f3a6c86 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. -**130 tools · 706 end-to-end checks · 340 fuzz cases · 80.3% line coverage · ~560 KiB** +**134 tools · 717 end-to-end checks · 340 fuzz cases · 80.4% line coverage · ~573 KiB** ``` $ ./apex-twin --check -{"version":"1.21.0","tools":130,...,"scope":{"loaded":true,...}} +{"version":"1.22.0","tools":134,...,"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 (130) +## Tools (134) ### Scope and bookkeeping @@ -282,6 +282,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `smb_null_session` | SMB 2.1 negotiate, anonymous session, IPC$ tree connect | | `smb_shares` | Share-name dictionary over the anonymous session; reports reachable shares and NT status | | `email_security_audit` | SPF, DMARC, DKIM and MX via gated dig; policy and gaps | +| `smtp_open_relay` | EHLO/MAIL/RCPT for an external recipient; open relay detection, no DATA | +| `dns_open_resolver` | One recursive query against an in-scope resolver; answer means open | | `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN | | `pop3_probe` | Banner, CAPA list, STLS flag; no USER/PASS | | `sip_probe` | One UDP OPTIONS: status line, Server header, Allow methods | @@ -328,6 +330,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `log_timeline` | Merge auth and access logs into one sorted chronology with source tags | | `docker_audit` | docker.sock mode, docker group members, daemon.json TCP/TLS/insecure registries | | `www_audit` | Web roots: world-writable content, .env/config/keys, backups, .git, missing index | +| `apparmor_audit` | Profile list: enforce/complain counts, complain profiles named | +| `selinux_audit` | enforce, SELINUX=/SELINUXTYPE=, boolean count; disabled/permissive findings | ### ESP32 @@ -554,6 +558,9 @@ The full threat model, trust boundaries and a hardening checklist are in | SMB shares | 14 share names over the anonymous session | | E-mail DNS | 4 dig queries per call; domain and resolver gated | | Web root | 2000 files, depth 4, 100 findings | +| SMTP relay | one MAIL and one RCPT, never DATA | +| DNS resolver | one recursive dig query | +| MAC audits | read /sys and /etc state only | --- @@ -564,7 +571,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 706 end-to-end checks +make test # version check + gate audit + 717 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 @@ -676,7 +683,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, snmp_walk, ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, api_auth_audit, cache_audit, tls_cipher_matrix, smb_null_session, smb_shares, - email_security_audit + email_security_audit, smtp_open_relay, dns_open_resolver 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, @@ -719,7 +726,7 @@ examples/ scope.json ## Status -1.21.0. Built and run: 130 tools, 706 checks, 340 fuzz cases and 80.3% line +1.22.0. Built and run: 134 tools, 717 checks, 340 fuzz cases and 80.4% 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 @@ -758,7 +765,8 @@ same-second files; 1.18 added RPC and NTP probes plus sshd_config and PAM audits; 1.19 added ESP app parsing, API auth and cache audits plus a log timeline; 1.20 added a TLS cipher matrix, SMB null-session check and Docker audit; 1.21 added SMB share probing, e-mail security checks and a web-root -audit, again without changing an existing file format. +audit; 1.22 added SMTP relay and DNS resolver checks plus AppArmor/SELinux +audits, again without changing an existing file format. Not yet wired into a fleet router, and there is no TLS interception. diff --git a/SECURITY.md b/SECURITY.md index b6553f0..520e1c9 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.21.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.22.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,9 @@ 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. +- **Relay checks never send mail.** `smtp_open_relay` stops after RCPT and + never issues DATA; `dns_open_resolver` sends one recursive query; + `apparmor_audit` and `selinux_audit` read kernel/config state only. - **SMB share probing stops at TREE_CONNECT.** `smb_shares` tries a fixed list of share names over the anonymous session and reports status codes; it never lists a directory or reads a file. `email_security_audit` only queries DNS diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index a46f7a3..c9bd6b3 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.21.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.22.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS diff --git a/src/apex.h b/src/apex.h index 5ed2f18..0f0dad9 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.21.0" +#define APEX_VERSION "1.22.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 6478f18..77e626a 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -5121,6 +5121,247 @@ static void t_www_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* -------------------------------------------------------------- apparmor_audit */ + +typedef struct { + mcp_buf *b; + int first; + int count; +} aa_ctx; + +static void aa_finding(aa_ctx *ctx, const char *id, const char *severity, + const char *detail) +{ + if (ctx->count >= 100) + return; + if (!ctx->first) + mcp_buf_puts(ctx->b, ","); + ctx->first = 0; + ctx->count++; + mcp_buf_puts(ctx->b, "{\"id\":"); + apex_json_str(ctx->b, id); + mcp_buf_puts(ctx->b, ",\"severity\":"); + apex_json_str(ctx->b, severity); + mcp_buf_puts(ctx->b, ",\"detail\":"); + apex_json_str(ctx->b, detail); + mcp_buf_puts(ctx->b, "}"); +} + +static void t_apparmor_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + static char text[65536]; + char path[1024]; + mcp_buf b; + mcp_buf findings; + aa_ctx ctx; + int available = 0; + int profiles = 0; + int enforce = 0; + int complain = 0; + char complain_names[20][128]; + int ncomplain = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), + "%s/sys/kernel/security/apparmor/profiles", root); + mcp_buf_init(&findings); + memset(&ctx, 0, sizeof(ctx)); + ctx.b = &findings; + ctx.first = 1; + if (read_text(path, text, sizeof(text)) >= 0) { + char *copy = strdup(text); + char *save = NULL; + char *line; + + available = 1; + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *open = strchr(line, '('); + + if (open != NULL && strstr(line, "(enforce)") != NULL) { + profiles++; + enforce++; + } else if (open != NULL && + strstr(line, "(complain)") != NULL) { + size_t n = (size_t)(open - line); + + profiles++; + complain++; + while (n > 0 && (line[n - 1] == ' ' || + line[n - 1] == '\t')) + n--; + if (ncomplain < 20 && n < sizeof(complain_names[0])) { + memcpy(complain_names[ncomplain], line, n); + complain_names[ncomplain][n] = '\0'; + ncomplain++; + } + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + { + int i; + + for (i = 0; i < ncomplain; i++) { + char detail[192]; + + snprintf(detail, sizeof(detail), + "profile %.120s is in complain mode", complain_names[i]); + aa_finding(&ctx, "complain-profile", "medium", detail); + } + } + if (available && profiles == 0) + aa_finding(&ctx, "no-profiles", "low", + "AppArmor is loaded but no profile is active"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"available\":%s,\"profiles\":%d,\"enforce\":%d," + "\"complain\":%d,\"complain_profiles\":[", + available ? "true" : "false", profiles, enforce, complain); + { + int i; + + for (i = 0; i < ncomplain; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, complain_names[i]); + } + } + mcp_buf_printf(&b, "],\"findings_count\":%d,\"findings\":[", ctx.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); +} + +/* ---------------------------------------------------------------- selinux_audit */ + +static void t_selinux_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char buf[128]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int present = 0; + int enforce = 0; + char mode[32]; + char policy[64]; + int booleans = 0; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + mode[0] = policy[0] = '\0'; + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%s/sys/fs/selinux/enforce", root); + if (read_text(path, buf, sizeof(buf)) > 0) { + trim_eol(buf); + present = 1; + enforce = atoi(buf) == 1; + } + snprintf(path, sizeof(path), "%s/etc/selinux/config", root); + if (read_text(path, buf, sizeof(buf)) > 0) { + char *line = buf; + + while (*line != '\0') { + char *eol = strchr(line, '\n'); + size_t len = eol != NULL ? (size_t)(eol - line) : strlen(line); + + if (len > 8 && strncmp(line, "SELINUX=", 8) == 0) { + size_t n = len - 8; + + if (n >= sizeof(mode)) + n = sizeof(mode) - 1; + memcpy(mode, line + 8, n); + mode[n] = '\0'; + } else if (len > 12 && strncmp(line, "SELINUXTYPE=", 12) == 0) { + size_t n = len - 12; + + if (n >= sizeof(policy)) + n = sizeof(policy) - 1; + memcpy(policy, line + 12, n); + policy[n] = '\0'; + } + line = eol != NULL ? eol + 1 : line + len; + } + } + if (mode[0] == '\0') + snprintf(mode, sizeof(mode), "%s", + present ? (enforce ? "enforcing" : "permissive") + : "unknown"); + snprintf(path, sizeof(path), "%s/sys/fs/selinux/booleans", root); + { + DIR *d = opendir(path); + struct dirent *ent; + + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + if (ent->d_name[0] != '.') + booleans++; + } + closedir(d); + } + } + if (!present) { + if (!first) + mcp_buf_puts(&findings, ","); + first = 0; + count++; + mcp_buf_puts(&findings, "{\"id\":\"not-present\",\"severity\":\"low\"," + "\"detail\":\"SELinux is not available on this host\"}"); + } else if (strcmp(mode, "disabled") == 0) { + if (!first) + mcp_buf_puts(&findings, ","); + first = 0; + count++; + mcp_buf_puts(&findings, "{\"id\":\"disabled\",\"severity\":\"high\"," + "\"detail\":\"SELinux is configured disabled\"}"); + } else if (strcmp(mode, "permissive") == 0 || !enforce) { + if (!first) + mcp_buf_puts(&findings, ","); + first = 0; + count++; + mcp_buf_puts(&findings, "{\"id\":\"permissive\",\"severity\":\"medium\"," + "\"detail\":\"SELinux only logs, it does not enforce\"}"); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"present\":%s,\"enforce\":%s,\"mode\":", + present ? "true" : "false", enforce ? "true" : "false"); + apex_json_str(&b, mode); + mcp_buf_puts(&b, ",\"policy_type\":"); + apex_json_str(&b, policy); + mcp_buf_printf(&b, ",\"booleans\":%d,\"findings_count\":%d,\"findings\":[", + booleans, 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, " @@ -5423,6 +5664,20 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"files, default " "2000\"}}}", t_www_audit }, + { "apparmor_audit", + "Read the AppArmor profile list (root prefix supported), count enforce " + "and complain profiles and name the profiles that only log. Flags an " + "AppArmor without any active profile. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_apparmor_audit }, + { "selinux_audit", + "Read the SELinux state (root prefix supported): /sys/fs/selinux/enforce, " + "/etc/selinux/config (SELINUX=, SELINUXTYPE=) and the boolean count. " + "Flags disabled, permissive and a host without SELinux. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_selinux_audit }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_proto.c b/src/tools_proto.c index 50eeef1..d1cfc87 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -4762,6 +4762,116 @@ static void t_smb_shares(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------ smtp_open_relay */ + +static void t_smtp_open_relay(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *sender = mcp_arg_string(args, "sender"); + const char *recipient = mcp_arg_string(args, "recipient"); + int port = mcp_arg_int(args, "port", 25); + char banner[512]; + char reply[4096]; + char features[8][64]; + int nfeat = 0; + int banner_code; + int ehlo_code = 0; + int mail_code = 0; + int rcpt_code = 0; + int open_relay = 0; + int auth_required = 0; + int fd; + mcp_buf b; + int i; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (sender == NULL || *sender == '\0') + sender = "relay-test@apex.invalid"; + if (recipient == NULL || *recipient == '\0') + recipient = "postmaster@example.com"; + if (!gated(c, "smtp_open_relay", target, port)) + return; + fd = tcp_connect_host(target, port, 8000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the SMTP service"); + return; + } + banner[0] = '\0'; + banner_code = (read_line(fd, banner, sizeof(banner)) >= 0) + ? reply_code(banner) : 0; + if (banner_code != 220) { + close(fd); + mcp_reply_error(c, "no SMTP banner"); + return; + } + if (write_all(fd, "EHLO apex-twin\r\n") == 0) { + if (read_reply(fd, reply, sizeof(reply)) > 0) { + char *save = NULL; + char *line = strtok_r(reply, "\n", &save); + + ehlo_code = reply_code(line); + line = strtok_r(NULL, "\n", &save); + while (line != NULL && nfeat < 8) { + if (reply_feature(line, features[nfeat], + sizeof(features[0])) == 0) + nfeat++; + line = strtok_r(NULL, "\n", &save); + } + } + } + { + char cmd[320]; + + snprintf(cmd, sizeof(cmd), "MAIL FROM:<%.200s>\r\n", sender); + if (write_all(fd, cmd) == 0 && + read_reply(fd, reply, sizeof(reply)) > 0) + mail_code = reply_code(reply); + } + if (mail_code == 250 || mail_code == 251) { + char cmd[320]; + + snprintf(cmd, sizeof(cmd), "RCPT TO:<%.200s>\r\n", recipient); + if (write_all(fd, cmd) == 0 && + read_reply(fd, reply, sizeof(reply)) > 0) + rcpt_code = reply_code(reply); + } + if (rcpt_code == 250 || rcpt_code == 251 || rcpt_code == 252) + open_relay = 1; + if (mail_code == 530 || mail_code == 538 || rcpt_code == 530 || + rcpt_code == 550 || rcpt_code == 553) + auth_required = mail_code == 530 || mail_code == 538; + { + static const char quit[] = "QUIT\r\n"; + + (void)write(fd, quit, sizeof(quit) - 1); + } + close(fd); + apex_audit("smtp_open_relay", target, port, !open_relay, + open_relay ? "SMTP relays without authentication" + : "SMTP does not relay", "MAIL/RCPT"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"banner_code\":%d,\"ehlo_code\":%d," + "\"mail_code\":%d,\"rcpt_code\":%d,\"open_relay\":%s," + "\"auth_required\":%s,\"features\":[", + port, banner_code, ehlo_code, mail_code, rcpt_code, + open_relay ? "true" : "false", + auth_required ? "true" : "false"); + for (i = 0; i < nfeat; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, features[i]); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_PROTO[] = { { "ftp_probe", "One-connection FTP check: read the 220 banner, ask FEAT, then try the " @@ -5034,6 +5144,21 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 445\"}}," "\"required\":[\"target\"]}", t_smb_shares }, + { "smtp_open_relay", + "Check whether an SMTP server relays mail for external domains without " + "authentication: EHLO, MAIL FROM an .invalid sender and RCPT TO an " + "external recipient. A 250/251/252 for RCPT is an open relay. DATA is " + "never sent, so no mail leaves the server. Gate: the target must be in " + "scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 25\"}," + "\"sender\":{\"type\":\"string\",\"description\":\"default " + "relay-test@apex.invalid\"}," + "\"recipient\":{\"type\":\"string\",\"description\":\"default " + "postmaster@example.com\"}}," + "\"required\":[\"target\"]}", + t_smtp_open_relay }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/src/tools_red.c b/src/tools_red.c index 59d6c25..c773793 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -3870,6 +3870,103 @@ static void t_email_security_audit(mcp_conn *c, const mcp_json *args, free(mx_out); } +/* ----------------------------------------------------------- dns_open_resolver */ + +static void t_dns_open_resolver(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *server = mcp_arg_string(args, "server"); + const char *query = mcp_arg_string(args, "query"); + const char *rtype = mcp_arg_string(args, "type"); + int port = mcp_arg_int(args, "port", 53); + char reason[512]; + char portstr[16]; + char at_server[300]; + char *argv[10]; + int i = 0; + apex_proc p; + mcp_buf b; + int first = 1; + int count = 0; + int open_resolver = 0; + + (void)user; + if (server == NULL || *server == '\0') { + mcp_reply_error(c, "server is required"); + return; + } + if (query == NULL || *query == '\0') + query = "example.com"; + if (rtype == NULL || *rtype == '\0') + rtype = "A"; + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!apex_scope_check(server, port, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + apex_audit("dns_open_resolver", server, port, 1, "recursive query", query); + snprintf(portstr, sizeof(portstr), "%d", port); + snprintf(at_server, sizeof(at_server), "@%.200s", server); + argv[i++] = "dig"; + argv[i++] = "+short"; + argv[i++] = "+time=3"; + argv[i++] = "+tries=1"; + argv[i++] = "-p"; + argv[i++] = portstr; + argv[i++] = at_server; + argv[i++] = (char *)query; + argv[i++] = (char *)rtype; + argv[i] = NULL; + if (apex_run(argv, 15000, 64 * 1024, &p) != 0) { + mcp_reply_error(c, "cannot run dig"); + return; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"server\":"); + apex_json_str(&b, server); + mcp_buf_printf(&b, ",\"port\":%d,\"query\":", port); + apex_json_str(&b, query); + mcp_buf_puts(&b, ",\"type\":"); + apex_json_str(&b, rtype); + mcp_buf_printf(&b, ",\"exit\":%d,\"answers\":[", p.exit_code); + if (p.out != NULL) { + char *copy = strdup(p.out); + char *save = NULL; + char *line; + + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL && count < 10) { + while (*line == ' ' || *line == '\t') + line++; + if (*line != '\0') { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, line); + count++; + open_resolver = 1; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + mcp_buf_printf(&b, "],\"answer_count\":%d,\"open_resolver\":%s}", + count, open_resolver ? "true" : "false"); + apex_proc_free(&p); + apex_audit("dns_open_resolver", server, port, !open_resolver, + open_resolver ? "resolver answered a recursive query" + : "resolver refused or is not recursive", query); + 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: " @@ -4208,6 +4305,19 @@ const mcp_tool TOOLS_RED[] = { "0 (system resolver)\"}}," "\"required\":[\"domain\"]}", t_email_security_audit }, + { "dns_open_resolver", + "Ask a DNS server for an external name with recursion (dig +short) and " + "report whether it answers: an answer means the resolver is open and can " + "be abused for amplification. One query, gate on the server. Gate: the " + "server must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"server\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 53\"}," + "\"query\":{\"type\":\"string\",\"description\":\"default " + "example.com\"}," + "\"type\":{\"type\":\"string\",\"description\":\"default A\"}}," + "\"required\":[\"server\"]}", + t_dns_open_resolver }, }; const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[0]); diff --git a/tests/gate_audit.py b/tests/gate_audit.py index e898aba..e6aad6d 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 = 130 +EXPECTED_TOOLS = 134 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 4b3de07..304bc67 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("130 tools registered", len(tools) == 130, len(tools)) +check("134 tools registered", len(tools) == 134, 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"]) == 130) + check("http tools/list", len(listing["result"]["tools"]) == 134) 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 @@ -5942,6 +5942,172 @@ dns_sock.close() shutil.rmtree(www_root, ignore_errors=True) shutil.rmtree(www_home, ignore_errors=True) +print("\n== SMTP relay, DNS resolver, AppArmor and SELinux ==") + + +def smtp_relay_handler(open_relay): + def handle(conn): + f = conn.makefile("rb") + conn.sendall(b"220 test ESMTP\r\n") + while True: + line = f.readline() + if not line: + return + up = line.upper() + if up.startswith(b"EHLO"): + conn.sendall(b"250-test greets you\r\n250 SIZE 10240000\r\n") + elif up.startswith(b"MAIL"): + conn.sendall(b"250 sender ok\r\n" if open_relay else + b"530 5.7.0 Authentication required\r\n") + elif up.startswith(b"RCPT"): + conn.sendall(b"250 recipient ok\r\n") + elif up.startswith(b"QUIT"): + conn.sendall(b"221 bye\r\n") + return + else: + conn.sendall(b"250 ok\r\n") + return handle + + +def dns_resolver_agent(open_resolver): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("127.0.0.1", 0)) + sock.settimeout(0.2) + port = sock.getsockname()[1] + stop = threading.Event() + + def loop(): + while not stop.is_set(): + try: + data, addr = sock.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + if len(data) < 12: + continue + tid = data[:2] + name, off = dns_name_decode(data, 12) + qtype = struct.unpack(">H", data[off:off + 2])[0] + question = data[12:off + 4] + answers = b"" + rcode = 5 + if open_resolver and name == "example.com" and qtype == 1: + rcode = 0 + answers = (b"\xc0\x0c" + + struct.pack(">HHIH", 1, 1, 60, 4) + + socket.inet_aton("93.184.216.34")) + resp = (tid + struct.pack(">HHHHH", 0x8400 | rcode, 1, + 1 if answers else 0, 0, 0) + + question + answers) + sock.sendto(resp, addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, port, stop + + +smtp_relay_srv, smtp_relay_port = start_line_server(smtp_relay_handler(True)) +smtp_closed_srv, smtp_closed_port = start_line_server( + smtp_relay_handler(False)) +dns_open_sock, dns_open_port, dns_open_stop = dns_resolver_agent(True) +dns_closed_sock, dns_closed_port, dns_closed_stop = dns_resolver_agent(False) + +aa_root = tempfile.mkdtemp(prefix="apex-aa-") +os.makedirs(os.path.join(aa_root, "sys", "kernel", "security", "apparmor")) +with open(os.path.join(aa_root, "sys", "kernel", "security", "apparmor", + "profiles"), "w") as f: + f.write("/usr/sbin/cupsd (enforce)\n") + f.write("/usr/bin/foo (complain)\n") + f.write("docker-default (enforce)\n") + +se_root = tempfile.mkdtemp(prefix="apex-se-") +os.makedirs(os.path.join(se_root, "sys", "fs", "selinux", "booleans")) +os.makedirs(os.path.join(se_root, "etc", "selinux")) +with open(os.path.join(se_root, "sys", "fs", "selinux", "enforce"), "w") as f: + f.write("1\n") +with open(os.path.join(se_root, "etc", "selinux", "config"), "w") as f: + f.write("SELINUX=enforcing\nSELINUXTYPE=targeted\n") +for name in ("httpd_can_network_connect", "ssh_sysadm_login", "use_nfs_home"): + with open(os.path.join(se_root, "sys", "fs", "selinux", "booleans", + name), "w") as f: + f.write("0\n") + +se_perm = tempfile.mkdtemp(prefix="apex-sep-") +os.makedirs(os.path.join(se_perm, "sys", "fs", "selinux")) +os.makedirs(os.path.join(se_perm, "etc", "selinux")) +with open(os.path.join(se_perm, "sys", "fs", "selinux", "enforce"), "w") as f: + f.write("0\n") +with open(os.path.join(se_perm, "etc", "selinux", "config"), "w") as f: + f.write("SELINUX=permissive\nSELINUXTYPE=targeted\n") + +sec_home3 = tempfile.mkdtemp(prefix="apex-sec3-") +write_scope(sec_home3, {"label": "sec3", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(smtp_relay_port), + str(smtp_closed_port), + str(dns_open_port), + str(dns_closed_port)]}) +res, _ = run([ + call(1, "smtp_open_relay", target="127.0.0.1", port=smtp_relay_port), + call(2, "smtp_open_relay", target="127.0.0.1", port=smtp_closed_port), + call(3, "dns_open_resolver", server="127.0.0.1", port=dns_open_port), + call(4, "dns_open_resolver", server="127.0.0.1", port=dns_closed_port), + call(5, "apparmor_audit", root=aa_root), + call(6, "selinux_audit", root=se_root), + call(7, "selinux_audit", root=se_perm), + call(8, "smtp_open_relay", target="198.51.100.9", port=25), + call(9, "dns_open_resolver", server="198.51.100.9", port=53), +], home=sec_home3) +by_id = {r.get("id"): r for r in res} +relay = json.loads(text(by_id[1])) +check("smtp_open_relay detects the open relay", + relay["open_relay"] is True and relay["mail_code"] == 250 and + relay["rcpt_code"] == 250, relay) +closed = json.loads(text(by_id[2])) +check("smtp_open_relay reports the auth requirement", + closed["open_relay"] is False and closed["auth_required"] is True and + closed["mail_code"] == 530, closed) +resolver = json.loads(text(by_id[3])) +check("dns_open_resolver detects recursion", + resolver["open_resolver"] is True and + resolver["answers"] == ["93.184.216.34"], resolver) +resolver_no = json.loads(text(by_id[4])) +check("dns_open_resolver reports a refusing server", + resolver_no["open_resolver"] is False and + resolver_no["answer_count"] == 0, resolver_no) +aa = json.loads(text(by_id[5])) +check("apparmor_audit counts enforce and complain profiles", + aa["available"] is True and aa["profiles"] == 3 and + aa["enforce"] == 2 and aa["complain"] == 1, aa) +check("apparmor_audit names the complain profile", + aa["complain_profiles"] == ["/usr/bin/foo"] and + aa["findings_count"] == 1, aa) +se = json.loads(text(by_id[6])) +check("selinux_audit reads an enforcing host", + se["present"] is True and se["enforce"] is True and + se["mode"] == "enforcing" and se["policy_type"] == "targeted" and + se["booleans"] == 3, se) +check("selinux_audit leaves an enforcing host alone", + se["findings_count"] == 0, se) +se_no = json.loads(text(by_id[7])) +check("selinux_audit flags permissive mode", + se_no["enforce"] is False and + {f["id"] for f in se_no["findings"]} == {"permissive"}, se_no) +check("smtp_open_relay refuses an out-of-scope target", err(by_id[8]), + text(by_id[8])) +check("dns_open_resolver refuses an out-of-scope server", err(by_id[9]), + text(by_id[9])) +smtp_relay_srv.close() +smtp_closed_srv.close() +dns_open_stop.set() +dns_open_sock.close() +dns_closed_stop.set() +dns_closed_sock.close() +shutil.rmtree(aa_root, ignore_errors=True) +shutil.rmtree(se_root, ignore_errors=True) +shutil.rmtree(se_perm, ignore_errors=True) +shutil.rmtree(sec_home3, ignore_errors=True) + print("\n== esp32 tools ==") esp_home = tempfile.mkdtemp(prefix="apex-esp-") write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})