diff --git a/CHANGELOG.md b/CHANGELOG.md index c5a31a7..49f7c3c 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.20.0 — 2026-11-21 — this change +## 1.21.0 — 2026-11-21 — this change + +- **SMB shares** (`smb_shares`): after the anonymous SMB 2.1 session, tries + TREE_CONNECT for 14 common share names (IPC$, C$, ADMIN$, users, data, + backup, public, www, home, share, files, tmp, downloads, media) and reports + the reachable ones with their NT status. No listing and no file access. +- **E-mail security** (`email_security_audit`): gated dig queries for SPF, + DMARC (_dmarc), DKIM (selector._domainkey) and MX; reports records, SPF + policy (-all/~all/?all/+all), DMARC p= and the gaps (missing records, +all, + p=none). +- **Blue** (`www_audit`): walks /var/www, /srv/www and /usr/share/nginx/html + (optional root prefix) for world-writable files and directories, .env/ + wp-config/config.php/.htpasswd/id_rsa, backups (.bak/.old/.sql/.zip/.tar.gz), + .git directories and directories without an index. +- The tool table hit its 128-slot cap again at 130 tools; it is now 192. +- Tests with an SMB share fixture (allow/deny), a UDP DNS TXT/MX agent and a + web-root tree. 706 checks. Coverage 80.3%. + +## 1.20.0 — 2026-11-21 — 99649e2 - **TLS cipher matrix** (`tls_cipher_matrix`): one `openssl s_client` per weak cipher (3DES, RC4, NULL, EXPORT, CBC by default) for TLS 1.2 or 1.3; reports diff --git a/README.md b/README.md index fa184e3..6a976f9 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. -**127 tools · 695 end-to-end checks · 340 fuzz cases · 80.1% line coverage · ~548 KiB** +**130 tools · 706 end-to-end checks · 340 fuzz cases · 80.3% line coverage · ~560 KiB** ``` $ ./apex-twin --check -{"version":"1.20.0","tools":127,...,"scope":{"loaded":true,...}} +{"version":"1.21.0","tools":130,...,"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 (127) +## Tools (130) ### Scope and bookkeeping @@ -280,6 +280,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `cache_audit` | Clean vs parameterized URL: Cache-Control/Age/Vary/X-Cache, parameterized-cacheable finding | | `tls_cipher_matrix` | Weak cipher list per TLS version; reports which suites negotiate | | `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 | | `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 | @@ -325,6 +327,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `pam_audit` | pam.d: pam_permit, pam_unix nullok, pam_exec and missing faillock/tally lockout | | `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 | ### ESP32 @@ -548,6 +551,9 @@ The full threat model, trust boundaries and a hardening checklist are in | Cipher matrix | 12 ciphers, one handshake each, gated once | | SMB null session | negotiate 2.1, session + IPC$ only | | Docker audit | reads socket mode, group file, daemon.json | +| 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 | --- @@ -558,7 +564,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 695 end-to-end checks +make test # version check + gate audit + 706 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 @@ -669,7 +675,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, telnet_probe, http_methods, websocket_probe, ike_probe, snmp_walk, ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, api_auth_audit, cache_audit, - tls_cipher_matrix, smb_null_session + tls_cipher_matrix, smb_null_session, smb_shares, + email_security_audit 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, @@ -712,7 +719,7 @@ examples/ scope.json ## Status -1.20.0. Built and run: 127 tools, 695 checks, 340 fuzz cases and 80.1% line +1.21.0. Built and run: 130 tools, 706 checks, 340 fuzz cases and 80.3% 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 @@ -750,6 +757,7 @@ added CSRF, kernel, sudoers and auditd checks and fixed evidence ordering for 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. Not yet wired into a fleet router, and there is no TLS interception. diff --git a/SECURITY.md b/SECURITY.md index 7f85a77..b6553f0 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.20.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.21.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,10 @@ 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. +- **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 + TXT/MX records for an in-scope domain. - **SMB stays at the session and IPC$.** `smb_null_session` negotiates SMB 2.1, tries an anonymous session setup and only connects to IPC$; it does not enumerate shares or read files. `tls_cipher_matrix` performs one handshake diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 493097b..a46f7a3 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.20.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.21.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS diff --git a/src/apex-twin.c b/src/apex-twin.c index ba6af79..7af02b5 100644 --- a/src/apex-twin.c +++ b/src/apex-twin.c @@ -35,7 +35,7 @@ #define MAX_BODY (8u << 20) static mcp_server g_srv; -static mcp_tool g_tools[128]; +static mcp_tool g_tools[192]; static volatile sig_atomic_t g_http_stop; static volatile sig_atomic_t g_http_child_exit; static int g_http_children; @@ -102,31 +102,31 @@ static void build_tools(void) size_t n = 0; size_t i; - for (i = 0; i < TOOLS_RECON_N && n < 128; i++) + for (i = 0; i < TOOLS_RECON_N && n < 192; i++) g_tools[n++] = TOOLS_RECON[i]; - for (i = 0; i < TOOLS_WEB_N && n < 128; i++) + for (i = 0; i < TOOLS_WEB_N && n < 192; i++) g_tools[n++] = TOOLS_WEB[i]; - for (i = 0; i < TOOLS_RADIO_N && n < 128; i++) + for (i = 0; i < TOOLS_RADIO_N && n < 192; i++) g_tools[n++] = TOOLS_RADIO[i]; - for (i = 0; i < TOOLS_KB_N && n < 128; i++) + for (i = 0; i < TOOLS_KB_N && n < 192; i++) g_tools[n++] = TOOLS_KB[i]; - for (i = 0; i < TOOLS_REPORT_N && n < 128; i++) + for (i = 0; i < TOOLS_REPORT_N && n < 192; i++) g_tools[n++] = TOOLS_REPORT[i]; - for (i = 0; i < TOOLS_GUARD_N && n < 128; i++) + for (i = 0; i < TOOLS_GUARD_N && n < 192; i++) g_tools[n++] = TOOLS_GUARD[i]; - for (i = 0; i < TOOLS_ASSET_N && n < 128; i++) + for (i = 0; i < TOOLS_ASSET_N && n < 192; i++) g_tools[n++] = TOOLS_ASSET[i]; - for (i = 0; i < TOOLS_TRAFFIC_N && n < 128; i++) + for (i = 0; i < TOOLS_TRAFFIC_N && n < 192; i++) g_tools[n++] = TOOLS_TRAFFIC[i]; - for (i = 0; i < TOOLS_RED_N && n < 128; i++) + for (i = 0; i < TOOLS_RED_N && n < 192; i++) g_tools[n++] = TOOLS_RED[i]; - for (i = 0; i < TOOLS_BLUE_N && n < 128; i++) + for (i = 0; i < TOOLS_BLUE_N && n < 192; i++) g_tools[n++] = TOOLS_BLUE[i]; - for (i = 0; i < TOOLS_ESP_N && n < 128; i++) + for (i = 0; i < TOOLS_ESP_N && n < 192; i++) g_tools[n++] = TOOLS_ESP[i]; - for (i = 0; i < TOOLS_PROTO_N && n < 128; i++) + for (i = 0; i < TOOLS_PROTO_N && n < 192; i++) g_tools[n++] = TOOLS_PROTO[i]; - for (i = 0; i < TOOLS_DB_N && n < 128; i++) + for (i = 0; i < TOOLS_DB_N && n < 192; i++) g_tools[n++] = TOOLS_DB[i]; g_srv.name = "apex-twin"; diff --git a/src/apex.h b/src/apex.h index 8006a52..5ed2f18 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.20.0" +#define APEX_VERSION "1.21.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 6275f56..6478f18 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -4938,6 +4938,189 @@ static void t_docker_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ----------------------------------------------------------------- www_audit */ + +typedef struct { + mcp_buf *b; + int first; + int count; + int files; + int max_files; +} www_ctx; + +static void www_finding(www_ctx *ctx, const char *path, const char *kind, + 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, "{\"path\":"); + apex_json_str(ctx->b, path); + mcp_buf_puts(ctx->b, ",\"kind\":"); + apex_json_str(ctx->b, kind); + 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 int www_ends_with(const char *name, const char *suffix) +{ + size_t nl = strlen(name); + size_t sl = strlen(suffix); + + return nl > sl && strcmp(name + nl - sl, suffix) == 0; +} + +static int www_has_index(const char *dir) +{ + static const char *names[] = { "index.html", "index.htm", "index.php", + NULL }; + int i; + + for (i = 0; names[i] != NULL; i++) { + char path[1024]; + struct stat st; + + snprintf(path, sizeof(path), "%.800s/%.160s", dir, names[i]); + if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) + return 1; + } + return 0; +} + +static void www_walk(www_ctx *ctx, const char *dir, int depth) +{ + DIR *d; + struct dirent *ent; + + if (depth > 4 || ctx->files >= ctx->max_files) + return; + d = opendir(dir); + if (d == NULL) + return; + { + const char *slash = strrchr(dir, '/'); + const char *base = slash != NULL ? slash + 1 : dir; + + if (depth >= 1 && depth <= 2 && strcmp(base, ".git") != 0 && + !www_has_index(dir)) + www_finding(ctx, dir, "no-index", "low", + "directory has no index file (listing may be exposed)"); + } + while ((ent = readdir(d)) != NULL && ctx->files < ctx->max_files) { + char path[1024]; + struct stat st; + size_t dl = strlen(dir); + size_t nl = strlen(ent->d_name); + + if (ent->d_name[0] == '.' && + (ent->d_name[1] == '\0' || + (ent->d_name[1] == '.' && ent->d_name[2] == '\0'))) + continue; + if (dl + nl + 2 > sizeof(path)) + continue; + memcpy(path, dir, dl); + path[dl] = '/'; + memcpy(path + dl + 1, ent->d_name, nl + 1); + if (lstat(path, &st) != 0) + continue; + if (S_ISLNK(st.st_mode)) + continue; + if (S_ISDIR(st.st_mode)) { + if ((st.st_mode & 0002) != 0) + www_finding(ctx, path, "world-writable", "high", + "web directory is writable by anyone"); + if (strcmp(ent->d_name, ".git") == 0) + www_finding(ctx, path, "git-dir", "high", + "repository metadata is inside the web root"); + www_walk(ctx, path, depth + 1); + continue; + } + if (!S_ISREG(st.st_mode)) + continue; + ctx->files++; + if ((st.st_mode & 0002) != 0) + www_finding(ctx, path, "world-writable", "high", + "web content is writable by anyone"); + if (strcmp(ent->d_name, ".env") == 0) + www_finding(ctx, path, "env-file", "high", + "environment file inside the web root"); + if (strcmp(ent->d_name, "wp-config.php") == 0 || + strcmp(ent->d_name, "config.php") == 0) + www_finding(ctx, path, "config-file", "high", + "application configuration is downloadable"); + if (strcmp(ent->d_name, ".htpasswd") == 0 || + strcmp(ent->d_name, "id_rsa") == 0) + www_finding(ctx, path, "secret-file", "high", + "credential material inside the web root"); + if (www_ends_with(ent->d_name, ".bak") || + www_ends_with(ent->d_name, ".old") || + www_ends_with(ent->d_name, ".sql") || + www_ends_with(ent->d_name, ".zip") || + www_ends_with(ent->d_name, ".tar.gz")) + www_finding(ctx, path, "backup-file", "medium", + "backup or dump file inside the web root"); + } + closedir(d); +} + +static void t_www_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *roots[] = { "/var/www", "/srv/www", + "/usr/share/nginx/html", NULL }; + const char *root = mcp_arg_string(args, "root"); + int limit = mcp_arg_int(args, "limit", 2000); + char base[512]; + char path[1024]; + size_t bl; + mcp_buf b; + mcp_buf findings; + www_ctx ctx; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) >= sizeof(base) - 2) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(base, sizeof(base), "%s", root); + bl = strlen(base); + while (bl > 0 && base[bl - 1] == '/') + base[--bl] = '\0'; + if (limit <= 0 || limit > 20000) + limit = 2000; + mcp_buf_init(&findings); + memset(&ctx, 0, sizeof(ctx)); + ctx.b = &findings; + ctx.first = 1; + ctx.max_files = limit; + for (i = 0; roots[i] != NULL; i++) { + struct stat st; + + snprintf(path, sizeof(path), "%s%s", base, roots[i]); + if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) + www_walk(&ctx, path, 0); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"files\":%d,\"findings_count\":%d,\"findings\":[", + ctx.files, 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); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -5230,6 +5413,16 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_docker_audit }, + { "www_audit", + "Walk the usual web roots (/var/www, /srv/www, /usr/share/nginx/html; " + "optional root prefix for a mounted image) and flag world-writable " + "content, .env/wp-config/config.php/.htpasswd/id_rsa, backup and dump " + "files, .git directories and directories without an index file. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"files, default " + "2000\"}}}", + t_www_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 ef78e4e..50eeef1 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -4593,6 +4593,175 @@ static void t_smb_null_session(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- smb_shares */ + +static size_t smb_utf16_share(unsigned char *out, size_t cap, + const char *host, const char *share) +{ + size_t w = 0; + const char *p; + + if (cap < 8) + return 0; + out[w++] = 0x5c; + out[w++] = 0; + for (p = host; *p != '\0' && w + 6 < cap; p++) { + out[w++] = (unsigned char)*p; + out[w++] = 0; + } + out[w++] = 0x5c; + out[w++] = 0; + for (p = share; *p != '\0' && w + 3 < cap; p++) { + out[w++] = (unsigned char)*p; + out[w++] = 0; + } + return w; +} + +static int smb_tree_connect(int fd, unsigned long long session, int msgid, + const char *host, const char *share, + unsigned int *status) +{ + unsigned char hdr[64]; + unsigned char body[16]; + unsigned char msg[1024]; + unsigned char resp[2048]; + unsigned char path[800]; + size_t plen; + size_t rlen = 0; + + plen = smb_utf16_share(path, sizeof(path), host, share); + if (plen == 0) + return -1; + smb2_req_header(hdr, 3, (unsigned long long)msgid, session); + memset(body, 0, sizeof(body)); + body[0] = 9; + body[4] = 0x48; + body[5] = 0x00; + body[6] = (unsigned char)(plen & 0xff); + body[7] = (unsigned char)((plen >> 8) & 0xff); + memcpy(msg, hdr, 64); + memcpy(msg + 64, body, 8); + memcpy(msg + 72, path, plen); + if (smb2_exchange(fd, msg, 72 + plen, resp, sizeof(resp), &rlen) != 0) + return -1; + *status = le32_local(resp + 8); + return 0; +} + +static void t_smb_shares(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *shares[] = { + "IPC$", "C$", "ADMIN$", "users", "data", "backup", "public", + "www", "home", "share", "files", "tmp", "downloads", "media", NULL + }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 445); + unsigned char hdr[64]; + unsigned char body[64]; + unsigned char msg[160]; + unsigned char resp[2048]; + size_t rlen = 0; + unsigned int status; + unsigned long long session = 0; + int anonymous = 0; + mcp_buf b; + int fd; + int first = 1; + int accessible = 0; + int tested = 0; + int i; + char sess_hex[24]; + size_t k; + + (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, "smb_shares", target, port)) + return; + fd = tcp_connect_host(target, port, 8000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the SMB service"); + return; + } + smb2_req_header(hdr, 0, 0, 0); + memset(body, 0, sizeof(body)); + body[0] = 36; + body[2] = 1; + body[4] = 1; + for (k = 0; k < 16; k++) + body[16 + k] = (unsigned char)(0x50 + k); + body[36] = 0x10; + body[37] = 0x02; + memcpy(msg, hdr, 64); + memcpy(msg + 64, body, 38); + if (smb2_exchange(fd, msg, 102, resp, sizeof(resp), &rlen) != 0 || + le32_local(resp + 8) != 0) { + close(fd); + mcp_reply_error(c, "SMB negotiate failed"); + return; + } + smb2_req_header(hdr, 1, 1, 0); + memset(body, 0, 24); + body[0] = 25; + body[3] = 1; + body[12] = 0x58; + memcpy(msg, hdr, 64); + memcpy(msg + 64, body, 24); + if (smb2_exchange(fd, msg, 88, resp, sizeof(resp), &rlen) != 0) { + close(fd); + mcp_reply_error(c, "no SMB session response"); + return; + } + status = le32_local(resp + 8); + if (status == 0) { + anonymous = 1; + for (k = 0; k < 8; k++) + session |= (unsigned long long)resp[40 + k] << (k * 8); + } + snprintf(sess_hex, sizeof(sess_hex), "%016llx", session); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"smb\":true,\"anonymous_session\":%s," + "\"session_id\":", port, anonymous ? "true" : "false"); + apex_json_str(&b, sess_hex); + mcp_buf_puts(&b, ",\"shares\":["); + if (anonymous) { + for (i = 0; shares[i] != NULL; i++) { + unsigned int st = 0; + + tested++; + if (smb_tree_connect(fd, session, 2 + i, target, shares[i], + &st) != 0) + continue; + if (st == 0) + accessible++; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"name\":"); + apex_json_str(&b, shares[i]); + mcp_buf_printf(&b, ",\"status\":\"0x%08x\",\"accessible\":%s}", + st, st == 0 ? "true" : "false"); + } + } + close(fd); + mcp_buf_printf(&b, "],\"tested\":%d,\"accessible_count\":%d}", tested, + accessible); + apex_audit("smb_shares", target, port, accessible == 0, + accessible == 0 ? "no share reachable anonymously" + : "shares reachable anonymously", "TREE_CONNECT"); + 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 " @@ -4854,6 +5023,17 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 445\"}}," "\"required\":[\"target\"]}", t_smb_null_session }, + { "smb_shares", + "After an anonymous SMB 2.1 session, try TREE_CONNECT for a built-in list " + "of common share names (IPC$, C$, ADMIN$, users, data, backup, public, " + "www, home, share, files, tmp, downloads, media) and report which ones " + "are reachable and their NT status. No directory listing and no file " + "access. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 445\"}}," + "\"required\":[\"target\"]}", + t_smb_shares }, }; 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 53f64f9..59d6c25 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -3602,6 +3602,274 @@ static void t_cache_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------- email_security_audit */ + +static char *email_dig(const char *name, const char *type, + const char *resolver, int port) +{ + char portstr[16]; + char at_server[300]; + char *argv[12]; + int i = 0; + apex_proc p; + char *out = NULL; + + argv[i++] = "dig"; + argv[i++] = "+short"; + argv[i++] = "+time=3"; + argv[i++] = "+tries=1"; + if (port > 0) { + snprintf(portstr, sizeof(portstr), "%d", port); + argv[i++] = "-p"; + argv[i++] = portstr; + } + if (resolver != NULL && *resolver != '\0') { + snprintf(at_server, sizeof(at_server), "@%.200s", resolver); + argv[i++] = at_server; + } + argv[i++] = (char *)name; + argv[i++] = (char *)type; + argv[i] = NULL; + if (apex_run(argv, 15000, g_cfg.max_output, &p) != 0) + return NULL; + if (p.exit_code == 0 && p.out != NULL && p.out_len > 0) { + out = strdup(p.out); + } + apex_proc_free(&p); + return out; +} + +static void email_record_copy(const char *text, char *out, size_t n) +{ + size_t w = 0; + + out[0] = '\0'; + while (*text == '"' || *text == ' ' || *text == '\t') + text++; + while (*text != '\0' && *text != '\n' && *text != '\r' && + *text != '"' && w + 1 < n) + out[w++] = *text++; + out[w] = '\0'; +} + +static void email_finding(mcp_buf *b, int *first, const char *id, + const char *severity, const char *detail) +{ + if (!*first) + mcp_buf_puts(b, ","); + *first = 0; + mcp_buf_puts(b, "{\"id\":"); + apex_json_str(b, id); + mcp_buf_puts(b, ",\"severity\":"); + apex_json_str(b, severity); + mcp_buf_puts(b, ",\"detail\":"); + apex_json_str(b, detail); + mcp_buf_puts(b, "}"); +} + +static void t_email_security_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *domain = mcp_arg_string(args, "domain"); + const char *selector = mcp_arg_string(args, "selector"); + const char *resolver = mcp_arg_string(args, "resolver"); + int port = mcp_arg_int(args, "port", 0); + char dmarc_name[320]; + char dkim_name[400]; + char reason[512]; + char *spf_out = NULL; + char *dmarc_out = NULL; + char *dkim_out = NULL; + char *mx_out = NULL; + char spf_record[256]; + char dmarc_record[256]; + char dkim_record[256]; + char spf_policy[32]; + char dmarc_policy[32]; + int spf = 0; + int dmarc = 0; + int dkim = 0; + int mx_count = 0; + char mx_records[10][128]; + mcp_buf b; + int first = 1; + int findings = 0; + int i; + + (void)user; + if (domain == NULL || *domain == '\0') { + mcp_reply_error(c, "domain is required"); + return; + } + if (selector == NULL || *selector == '\0') + selector = "default"; + if (port < 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!apex_scope_check(domain, 0, 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; + } + if (resolver != NULL && *resolver != '\0' && + !apex_scope_check(resolver, port, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "resolver is outside the scope: %s", reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + apex_audit("email_security_audit", domain, 0, 1, "SPF/DMARC/DKIM/MX", + "dig TXT/MX"); + spf_out = email_dig(domain, "TXT", resolver, port); + snprintf(dmarc_name, sizeof(dmarc_name), "_dmarc.%.200s", domain); + dmarc_out = email_dig(dmarc_name, "TXT", resolver, port); + snprintf(dkim_name, sizeof(dkim_name), "%.40s._domainkey.%.200s", + selector, domain); + dkim_out = email_dig(dkim_name, "TXT", resolver, port); + mx_out = email_dig(domain, "MX", resolver, port); + spf_record[0] = dmarc_record[0] = dkim_record[0] = '\0'; + spf_policy[0] = dmarc_policy[0] = '\0'; + if (spf_out != NULL && strstr(spf_out, "v=spf1") != NULL) { + spf = 1; + email_record_copy(strstr(spf_out, "v=spf1"), spf_record, + sizeof(spf_record)); + if (strstr(spf_record, "-all") != NULL) + snprintf(spf_policy, sizeof(spf_policy), "%s", "fail"); + else if (strstr(spf_record, "~all") != NULL) + snprintf(spf_policy, sizeof(spf_policy), "%s", "softfail"); + else if (strstr(spf_record, "?all") != NULL) + snprintf(spf_policy, sizeof(spf_policy), "%s", "neutral"); + else if (strstr(spf_record, "+all") != NULL) + snprintf(spf_policy, sizeof(spf_policy), "%s", "pass"); + else + snprintf(spf_policy, sizeof(spf_policy), "%s", "none"); + } + if (dmarc_out != NULL && strstr(dmarc_out, "v=DMARC1") != NULL) { + const char *p; + + dmarc = 1; + email_record_copy(strstr(dmarc_out, "v=DMARC1"), dmarc_record, + sizeof(dmarc_record)); + p = strstr(dmarc_record, "p="); + if (p != NULL) { + size_t w = 0; + + p += 2; + while (*p != '\0' && *p != ';' && *p != ' ' && + w + 1 < sizeof(dmarc_policy)) + dmarc_policy[w++] = *p++; + dmarc_policy[w] = '\0'; + } + } + if (dkim_out != NULL && + (strstr(dkim_out, "v=DKIM1") != NULL || + strstr(dkim_out, "p=") != NULL)) { + dkim = 1; + email_record_copy(dkim_out, dkim_record, sizeof(dkim_record)); + } + if (mx_out != NULL) { + char *copy = strdup(mx_out); + char *save = NULL; + char *line; + + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + while (*line == ' ' || *line == '\t') + line++; + if (*line != '\0') { + mx_count++; + if (mx_count <= 10) + snprintf(mx_records[mx_count - 1], + sizeof(mx_records[0]), "%.100s", + line); + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"domain\":"); + apex_json_str(&b, domain); + mcp_buf_puts(&b, ",\"selector\":"); + apex_json_str(&b, selector); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"domain\":"); + apex_json_str(&b, domain); + mcp_buf_puts(&b, ",\"selector\":"); + apex_json_str(&b, selector); + mcp_buf_puts(&b, ",\"resolver\":"); + apex_json_str(&b, resolver != NULL ? resolver : ""); + mcp_buf_puts(&b, ",\"spf\":{\"present\":"); + mcp_buf_printf(&b, "%s,\"record\":", spf ? "true" : "false"); + apex_json_str(&b, spf_record); + mcp_buf_puts(&b, ",\"policy\":"); + apex_json_str(&b, spf_policy); + mcp_buf_puts(&b, "},\"dmarc\":{\"present\":"); + mcp_buf_printf(&b, "%s,\"record\":", dmarc ? "true" : "false"); + apex_json_str(&b, dmarc_record); + mcp_buf_puts(&b, ",\"policy\":"); + apex_json_str(&b, dmarc_policy); + mcp_buf_puts(&b, "},\"dkim\":{\"present\":"); + mcp_buf_printf(&b, "%s,\"record\":", dkim ? "true" : "false"); + apex_json_str(&b, dkim_record); + mcp_buf_printf(&b, "},\"mx\":{\"count\":%d,\"records\":[", mx_count); + for (i = 0; i < mx_count && i < 10; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, mx_records[i]); + } + mcp_buf_puts(&b, "]},\"findings\":["); + first = 1; + { + int count = 0; + + if (!spf) { + email_finding(&b, &first, "missing-spf", "medium", + "no SPF record published"); + count++; + } + if (spf && strcmp(spf_policy, "pass") == 0) { + email_finding(&b, &first, "spf-all-pass", "high", + "SPF ends with +all"); + count++; + } + if (!dmarc) { + email_finding(&b, &first, "missing-dmarc", "medium", + "no DMARC record published"); + count++; + } + if (dmarc && strcmp(dmarc_policy, "none") == 0) { + email_finding(&b, &first, "dmarc-none", "low", + "DMARC policy is none"); + count++; + } + if (!dkim) { + email_finding(&b, &first, "missing-dkim", "low", + "no DKIM record for the selector"); + count++; + } + if (mx_count == 0) { + email_finding(&b, &first, "missing-mx", "low", + "no MX record published"); + count++; + } + findings = count; + } + mcp_buf_printf(&b, "],\"findings_count\":%d}", findings); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(spf_out); + free(dmarc_out); + free(dkim_out); + free(mx_out); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -3925,6 +4193,21 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_cache_audit }, + { "email_security_audit", + "Check a domain's e-mail security DNS: SPF (v=spf1, -all/~all/?all/+all " + "policy), DMARC (_dmarc TXT, p= policy), DKIM (selector._domainkey TXT) " + "and MX records, queried with gated dig. Reports each record and the " + "gaps, e.g. missing SPF/DMARC or +all. Gate: domain (and resolver).", + "{\"type\":\"object\",\"properties\":{" + "\"domain\":{\"type\":\"string\"}," + "\"selector\":{\"type\":\"string\",\"description\":\"default " + "default\"}," + "\"resolver\":{\"type\":\"string\",\"description\":\"optional DNS " + "server\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"dig -p, default " + "0 (system resolver)\"}}," + "\"required\":[\"domain\"]}", + t_email_security_audit }, }; 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 7e6b8c8..e898aba 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 = 127 +EXPECTED_TOOLS = 130 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 89569c0..4b3de07 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("127 tools registered", len(tools) == 127, len(tools)) +check("130 tools registered", len(tools) == 130, 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"]) == 127) + check("http tools/list", len(listing["result"]["tools"]) == 130) 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 @@ -5748,6 +5748,200 @@ shutil.rmtree(tls2_dir, ignore_errors=True) shutil.rmtree(docker_root, ignore_errors=True) shutil.rmtree(deep_home3, ignore_errors=True) +print("\n== SMB shares, e-mail security and web root ==") + + +def smb_share_handler(allow): + def handle(conn): + head = conn.recv(4) + need = int.from_bytes(head[1:4], "big") + body = b"" + while len(body) < need: + chunk = conn.recv(need - len(body)) + if not chunk: + return + body += chunk + conn.sendall(smb2_negotiate_response(0x0210)) + head = conn.recv(4) + need = int.from_bytes(head[1:4], "big") + body = b"" + while len(body) < need: + chunk = conn.recv(need - len(body)) + if not chunk: + return + body += chunk + session_status = 0 if allow else 0xC0000022 + conn.sendall(smb_nbt( + smb_null_header(1, session_status, 1, 0x1122334455667788) + + struct.pack(" len(data): + continue + qtype = struct.unpack(">H", data[off:off + 2])[0] + question = data[12:off + 4] + answers = [] + + def rr(rtype, rdata): + return (b"\xc0\x0c" + + struct.pack(">HHIH", rtype, 1, 300, len(rdata)) + + rdata) + + if qtype == 16: + if name == "example.test": + answers.append(rr(16, txt("v=spf1 mx -all"))) + elif name == "_dmarc.example.test": + answers.append(rr(16, txt("v=DMARC1; p=reject"))) + elif name == "default._domainkey.example.test": + answers.append(rr(16, txt("v=DKIM1; k=rsa; p=ABC"))) + elif qtype == 15 and name == "example.test": + answers.append(rr(15, struct.pack(">H", 10) + + dns_name_encode("mail.example.test"))) + resp = (tid + struct.pack(">HHHHH", 0x8400, 1, len(answers), 0, 0) + + question + b"".join(answers)) + sock.sendto(resp, addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, port, stop + + +smb_share_srv, smb_share_port = start_line_server(smb_share_handler(True)) +smb_share_deny_srv, smb_share_deny_port = start_line_server( + smb_share_handler(False)) +dns_sock, dns_port, dns_stop = dns_txt_agent() + +www_root = tempfile.mkdtemp(prefix="apex-www-") +html = os.path.join(www_root, "var", "www", "html") +os.makedirs(html) +with open(os.path.join(html, "index.html"), "w") as f: + f.write("ok") +with open(os.path.join(html, ".env"), "w") as f: + f.write("SECRET=1\n") +with open(os.path.join(html, "config.php.bak"), "w") as f: + f.write("