From f2a1fb4b591891180c90a6a15cfee946d20d879f Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 13:30:38 +0000 Subject: [PATCH] apex-twin 1.10.0: RDP and SMB negotiation, SUID baseline Red: - rdp_probe: X.224 Connection Request with an RDP negotiation request for TLS|CredSSP (0x0f). Parses the Connection Confirm for the selected protocol (RDP, TLS, CredSSP, RDSTLS, HYBRID_EX) or the failure code, and reports whether NLA is in use. One connection, no logon. - smb_probe: SMB2 NEGOTIATE offering 2.0.2, 2.1, 3.0, 3.0.2 and 3.1.1, then reports dialect, signing required/enabled, capabilities, max transact/read/ write and the server GUID; an SMB1 answer is reported as such. No session and no authentication. Blue: - suid_baseline: create/verify a SHA-256 manifest of SUID/SGID files under /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin, /bin and /sbin (symlinked directories skipped). Verify reports planted, removed and mode/hash-changed setuid binaries; optional root prefix for a mounted image. Tests: RDP frames selecting CredSSP and a negotiation failure, an SMB2 server answering 3.1.1 with signing and a fixed GUID, and a SUID tree where one file is planted, one removed and two change. 579 checks, ASan suite green, analyze clean, release-check green including distcheck 1.10.0. The SUID fixture documents a kernel behaviour: writing to a setuid file clears the setuid bit, so a rewritten binary appears as gone unless the mode is set again. --- CHANGELOG.md | 23 ++- README.md | 23 +-- SECURITY.md | 6 +- docs/apex-twin.1 | 11 +- src/apex.h | 2 +- src/tools_blue.c | 290 ++++++++++++++++++++++++++++++++++++ src/tools_proto.c | 347 ++++++++++++++++++++++++++++++++++++++++++++ tests/gate_audit.py | 2 +- tests/run.py | 138 +++++++++++++++++- 9 files changed, 822 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81cfb72..b163f6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,28 @@ 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.9.0 — 2026-11-21 — this change +## 1.10.0 — 2026-11-21 — this change + +- **RDP** (`rdp_probe`): sends an X.224 Connection Request with an RDP + negotiation request for TLS|CredSSP (and the rest), parses the Connection + Confirm for the selected protocol (RDP, TLS, CredSSP, RDSTLS, HYBRID_EX) and + reports whether NLA is in use or the negotiation failure code. No logon. +- **SMB** (`smb_probe`): sends an SMB2 NEGOTIATE offering 2.0.2, 2.1, 3.0, + 3.0.2 and 3.1.1, then reports the selected dialect, signing required/enabled, + capabilities, maximum sizes and the server GUID; an SMB1 answer is reported + as such. No session and no authentication. +- **Blue** (`suid_baseline`): create/verify a SHA-256 manifest of SUID/SGID + files under /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin, /bin and + /sbin (symlinked directories skipped). Verify reports planted, removed and + mode/hash-changed setuid binaries; optional root prefix for a mounted image. +- Tests with local fixtures: RDP negotiators that select CredSSP and that fail, + an SMB2 server answering 3.1.1 with signing and a GUID, and a SUID tree where + one file is planted, one removed and two change. 579 checks. Coverage 79.8%. +- The SUID fixture exposed a real kernel behaviour worth remembering: writing + to a setuid file clears its setuid bit, so a modified binary shows up as + "gone" (and as a new file only if it is made setuid again). + +## 1.9.0 — 2026-11-21 — 60075eb - **SSTI** (`ssti_probe`): five payloads (`{{1337*7}}`, `${1337*7}`, `#{1337*7}`, `<%= 1337*7 %>`, `{{1337*'7'}}`) with expected outputs; a diff --git a/README.md b/README.md index b510c65..b9cbcdc 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. -**85 tools · 569 end-to-end checks · 340 fuzz cases · 80.1% line coverage · ~408 KiB** +**88 tools · 579 end-to-end checks · 340 fuzz cases · 79.8% line coverage · ~420 KiB** ``` $ ./apex-twin --check -{"version":"1.9.0","tools":85,...,"scope":{"loaded":true,...}} +{"version":"1.10.0","tools":88,...,"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 (85) +## Tools (88) ### Scope and bookkeeping @@ -260,6 +260,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `ssti_probe` | Five template payloads with expected results; reports evaluation, reflection or template errors and the likely engine | | `xxe_probe` | XML with an external entity pointing at its own loopback listener; callback proves the parser resolved it | | `ldap_probe` | LDAPv3 anonymous bind plus rootDSE read (namingContexts, vendorName, supportedLDAPVersion) | +| `rdp_probe` | X.224 connection request; reports the selected protocol (RDP/TLS/CredSSP/RDSTLS) and NLA, or the failure code | +| `smb_probe` | SMB2 NEGOTIATE with five dialects; reports dialect, signing, capabilities, max sizes and server GUID | | `ftp_probe` | One FTP connection: banner, FEAT list, and whether the literal anonymous pair is accepted (audited) | | `smtp_probe` | One SMTP connection: banner, EHLO extensions, VRFY of up to 8 users classified exists/unknown/cannot-verify | | `ssh_audit` | Banner plus KEXINIT lists (kex, host key, ciphers, MACs) and deprecated algorithms flagged | @@ -287,6 +289,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `persistence_audit` | Cron, systemd units/timers and at jobs: flags /tmp paths, curl/wget piped to a shell, base64-to-shell, nc -e/socat, bash -i, setuid chmod | | `net_baseline` | Listening TCP ports with owning process names (`create`/`verify`); reports new, gone and process-changed ports | | `ssh_key_audit` | authorized_keys and private keys: unrestricted entries, ssh-rsa/ssh-dss, duplicates, loose permissions | +| `suid_baseline` | SUID/SGID SHA-256 manifest (`create`/`verify`); reports planted, removed and changed setuid binaries | ### ESP32 @@ -480,6 +483,8 @@ The full threat model, trust boundaries and a hardening checklist are in | Net baseline | 500 ports; process lookup capped by /proc walk | | SSTI | 5 payloads per call, 100 ms apart | | SSRF/XXE callbacks | one loopback listener, 1.2 s wait per probe | +| RDP/SMB | one connection and one negotiation each | +| SUID baseline | 2000 entries; 1 MiB per file hashed | --- @@ -490,7 +495,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 569 end-to-end checks +make test # version check + gate audit + 579 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 @@ -595,11 +600,11 @@ src/tools_traffic.c traffic_list / traffic_read src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id, param_fuzz, open_redirect, host_header_injection, ssti_probe, - xxe_probe, ldap_probe + xxe_probe, ldap_probe, rdp_probe, smb_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, - ssh_key_audit + ssh_key_audit, suid_baseline src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe, dns_zone_transfer @@ -634,7 +639,7 @@ examples/ scope.json ## Status -1.9.0. Built and run: 85 tools, 569 checks, 340 fuzz cases and 80.1% line +1.10.0. Built and run: 88 tools, 579 checks, 340 fuzz cases and 79.8% 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 @@ -661,8 +666,8 @@ verification, detection-rule export, integrity baselines and firmware writing 1.6 added TLS, Redis, SNMP and DNS zone-transfer checks; 1.7 added MySQL, PostgreSQL, MongoDB and Memcached probes; 1.8 added parameter fuzzing, open redirect and Host-header checks plus a network baseline; 1.9 added SSTI, XXE -and LDAP probes plus an SSH key audit, again without changing an existing tool -or file format. +and LDAP probes plus an SSH key audit; 1.10 added RDP and SMB negotiation checks +and a SUID baseline, again without changing an existing tool or file format. Not yet wired into a fleet router, and there is no TLS interception. diff --git a/SECURITY.md b/SECURITY.md index 0f64837..771d291 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.9.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.10.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. +- **RDP and SMB speak only the negotiation.** `rdp_probe` sends one X.224 + request and reads the selected protocol; `smb_probe` sends one SMB2 + NEGOTIATE and reads the dialect and signing flags. Neither creates a + session, authenticates or touches a share. - **SSTI and XXE probes prove evaluation, then stop.** `ssti_probe` sends arithmetic expressions and only looks for their result; `xxe_probe` points the external entity at its own loopback listener and never at a file or a diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index ae66e1e..e373204 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.9.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.10.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -40,10 +40,11 @@ cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id, ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe, dns_zone_transfer, mysql_probe, postgres_probe, mongo_probe, memcached_probe, param_fuzz, open_redirect, host_header_injection, ssti_probe, -xxe_probe, ldap_probe), defensive audits (hardening_audit, log_audit, ioc_scan, -web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, -persistence_audit, net_baseline, ssh_key_audit) and ESP32 board tools -(esp_info, esp_monitor, esp_read_flash, esp_flash). +xxe_probe, ldap_probe, rdp_probe, smb_probe), defensive audits (hardening_audit, +log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, +mitre_map, process_snapshot, persistence_audit, net_baseline, ssh_key_audit, +suid_baseline) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, +esp_flash). .SH MODES .TP .B apex-twin diff --git a/src/apex.h b/src/apex.h index f955724..2ac251e 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.9.0" +#define APEX_VERSION "1.10.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 87dd106..bb6f9bc 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -2557,6 +2557,280 @@ static void t_ssh_key_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------------- suid_baseline */ + +typedef struct { + char path[512]; + char mode[8]; + char hex[65]; + int seen; +} suid_entry; + +typedef struct { + suid_entry *e; + int n; + int max; + int truncated; +} suid_ctx; + +static void suid_scan_dir(suid_ctx *ctx, const char *dir) +{ + DIR *d = opendir(dir); + struct dirent *ent; + + if (d == NULL) + return; + while ((ent = readdir(d)) != NULL) { + char path[1024]; + struct stat st; + long size = 0; + + if (ctx->n >= ctx->max) { + ctx->truncated = 1; + break; + } + if (ent->d_name[0] == '.') + continue; + snprintf(path, sizeof(path), "%.800s/%.160s", dir, ent->d_name); + if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode)) + continue; + if ((st.st_mode & (S_ISUID | S_ISGID)) == 0) + continue; + snprintf(ctx->e[ctx->n].path, sizeof(ctx->e[0].path), "%.500s", + path); + snprintf(ctx->e[ctx->n].mode, sizeof(ctx->e[0].mode), "%04o", + (unsigned)(st.st_mode & 07777)); + ctx->e[ctx->n].hex[0] = '\0'; + if (hash_file(path, ctx->e[ctx->n].hex, &size) != 0) + ctx->e[ctx->n].hex[0] = '\0'; + ctx->e[ctx->n].seen = 0; + ctx->n++; + } + closedir(d); +} + +static void t_suid_baseline(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *dirs[] = { + "/usr/bin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin", + "/bin", "/sbin", NULL + }; + const char *action = mcp_arg_string(args, "action"); + const char *baseline = mcp_arg_string(args, "baseline"); + const char *root = mcp_arg_string(args, "root"); + int limit = mcp_arg_int(args, "limit", 2000); + char base[512]; + size_t bl; + char base_path[APEX_PATH_FULL]; + char path[1024]; + suid_entry *current = NULL; + suid_entry *base_entries = NULL; + int ncur = 0; + int nbase = 0; + int create; + int i; + mcp_buf b; + + (void)user; + if (action == NULL || *action == '\0') + action = "verify"; + create = strcmp(action, "create") == 0; + if (!create && strcmp(action, "verify") != 0) { + mcp_reply_error(c, "action must be create or verify"); + return; + } + if (limit <= 0 || limit > 10000) + limit = 2000; + 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 (baseline != NULL && *baseline != '\0') + snprintf(base_path, sizeof(base_path), "%s", baseline); + else + snprintf(base_path, sizeof(base_path), "%s/suid-baseline.jsonl", + g_cfg.home); + current = calloc((size_t)limit, sizeof(*current)); + base_entries = calloc(10000, sizeof(*base_entries)); + if (current == NULL || base_entries == NULL) { + free(current); + free(base_entries); + mcp_reply_error(c, "out of memory"); + return; + } + { + suid_ctx ctx; + int d; + + memset(&ctx, 0, sizeof(ctx)); + ctx.e = current; + ctx.max = limit; + for (d = 0; dirs[d] != NULL; d++) { + struct stat dst; + + snprintf(path, sizeof(path), "%s%s", base, dirs[d]); + if (lstat(path, &dst) != 0 || !S_ISDIR(dst.st_mode) || + S_ISLNK(dst.st_mode)) + continue; + suid_scan_dir(&ctx, path); + } + ncur = ctx.n; + } + if (create) { + mcp_buf lines; + + mcp_buf_init(&lines); + for (i = 0; i < ncur; i++) { + mcp_buf_puts(&lines, "{\"path\":"); + apex_json_str(&lines, current[i].path); + mcp_buf_printf(&lines, ",\"mode\":\"%s\",\"sha256\":\"%s\"}\n", + current[i].mode, current[i].hex); + } + if (apex_write_file(base_path, lines.p != NULL ? lines.p : "", + lines.len, 0600) != 0) { + mcp_buf_free(&lines); + free(current); + free(base_entries); + mcp_reply_error(c, "cannot write the SUID baseline"); + return; + } + mcp_buf_free(&lines); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"action\":\"create\",\"baseline\":"); + apex_json_str(&b, base_path); + mcp_buf_printf(&b, ",\"suid\":%d,\"entries\":[", ncur); + for (i = 0; i < ncur && i < 200; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, current[i].path); + mcp_buf_printf(&b, ",\"mode\":\"%s\"}", current[i].mode); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(current); + free(base_entries); + return; + } + { + FILE *f = fopen(base_path, "rb"); + char *line = NULL; + size_t cap = 0; + + if (f == NULL) { + free(current); + free(base_entries); + mcp_reply_error(c, "no SUID baseline; run action=create"); + return; + } + while (nbase < 10000 && getline(&line, &cap, f) >= 0) { + if (!json_str_field(line, "path", base_entries[nbase].path, + sizeof(base_entries[nbase].path))) + continue; + if (!json_str_field(line, "mode", base_entries[nbase].mode, + sizeof(base_entries[nbase].mode))) + continue; + if (!json_str_field(line, "sha256", base_entries[nbase].hex, + sizeof(base_entries[nbase].hex))) + base_entries[nbase].hex[0] = '\0'; + base_entries[nbase].seen = 0; + nbase++; + } + free(line); + fclose(f); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"action\":\"verify\",\"baseline\":"); + apex_json_str(&b, base_path); + mcp_buf_printf(&b, ",\"suid\":%d,\"new\":[", ncur); + { + int first = 1; + + for (i = 0; i < ncur; i++) { + int j; + int known = 0; + + for (j = 0; j < nbase; j++) + if (strcmp(base_entries[j].path, current[i].path) == 0) + known = 1; + if (known) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, current[i].path); + mcp_buf_printf(&b, ",\"mode\":\"%s\"}", current[i].mode); + } + } + mcp_buf_puts(&b, "],\"gone\":["); + { + int first = 1; + + for (i = 0; i < nbase; i++) { + int j; + int seen = 0; + + for (j = 0; j < ncur; j++) + if (strcmp(current[j].path, base_entries[i].path) == 0) + seen = 1; + if (seen) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, base_entries[i].path); + } + } + mcp_buf_puts(&b, "],\"changed\":["); + { + int first = 1; + + for (i = 0; i < ncur; i++) { + int j; + + for (j = 0; j < nbase; j++) { + int mode_changed; + int hash_changed; + + if (strcmp(base_entries[j].path, current[i].path) != 0) + continue; + mode_changed = strcmp(base_entries[j].mode, + current[i].mode) != 0; + hash_changed = + base_entries[j].hex[0] != '\0' && + current[i].hex[0] != '\0' && + strcmp(base_entries[j].hex, current[i].hex) != 0; + if (mode_changed || hash_changed) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, current[i].path); + mcp_buf_printf(&b, ",\"was_mode\":\"%s\"," + "\"now_mode\":\"%s\",\"was_sha256\":" + "\"%s\",\"now_sha256\":\"%s\"}", + base_entries[j].mode, current[i].mode, + base_entries[j].hex, current[i].hex); + } + break; + } + } + } + mcp_buf_printf(&b, "],\"baseline_entries\":%d}", nbase); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(current); + free(base_entries); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -2685,6 +2959,22 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"key files to read, " "default 200\"}}}", t_ssh_key_audit }, + { "suid_baseline", + "Create or verify a SHA-256 baseline of SUID/SGID files under /usr/bin, " + "/usr/sbin, /usr/local/bin, /usr/local/sbin, /bin and /sbin (symlinked " + "directories are skipped). Verify reports new setuid files, vanished " + "ones and files whose mode or hash changed, which catches a planted " + "setuid binary. The default baseline is $APEX_HOME/suid-baseline.jsonl; " + "the optional root prefix audits a mounted image. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"action\":{\"type\":\"string\",\"enum\":[\"create\",\"verify\"]," + "\"description\":\"default verify\"}," + "\"baseline\":{\"type\":\"string\",\"description\":\"default " + "$APEX_HOME/suid-baseline.jsonl\"}," + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max entries, default " + "2000\"}}}", + t_suid_baseline }, }; 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 4f1fb9c..b150577 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -1997,6 +1997,331 @@ static void t_ldap_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +static uint32_t le32_local(const unsigned char *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +/* ----------------------------------------------------------------- rdp_probe */ + +static const char *rdp_protocol_name(unsigned long p) +{ + switch (p) { + case 0: + return "RDP"; + case 1: + return "TLS"; + case 2: + return "CredSSP"; + case 3: + return "TLS|CredSSP"; + case 4: + return "RDSTLS"; + case 8: + return "HYBRID_EX"; + default: + return "unknown"; + } +} + +static void t_rdp_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", 3389); + static const unsigned char req[19] = { + 0x03, 0x00, 0x00, 0x13, 0x0e, 0xe0, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x08, 0x00, 0x0f, 0x00, 0x00, 0x00 + }; + unsigned char head[4]; + unsigned char buf[4096]; + unsigned long len; + unsigned long selected = 0; + long failure = -1; + int have_negotiation = 0; + int fd; + int i; + mcp_buf b; + + (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, "rdp_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the RDP service"); + return; + } + if (write(fd, req, sizeof(req)) != (ssize_t)sizeof(req)) { + close(fd); + mcp_reply_error(c, "cannot send the X.224 connection request"); + return; + } + if (apex_net_exact(fd, head, 4) != 0) { + close(fd); + mcp_reply_error(c, "no RDP response"); + return; + } + if (head[0] != 0x03) { + close(fd); + mcp_reply_error(c, "not a TPKT response"); + return; + } + len = ((unsigned long)head[2] << 8) | head[3]; + if (len < 7 || len > sizeof(buf) + 4) { + close(fd); + mcp_reply_error(c, "RDP response length out of range"); + return; + } + if (len > 4 && apex_net_exact(fd, buf, len - 4) != 0) { + close(fd); + mcp_reply_error(c, "short RDP response"); + return; + } + close(fd); + for (i = 0; i + 8 <= (int)(len - 4); i++) { + if (buf[i] == 0x02 && buf[i + 1] == 0x00 && + buf[i + 2] == 0x08 && buf[i + 3] == 0x00) { + selected = le32_local(buf + i + 4); + have_negotiation = 1; + break; + } + if (buf[i] == 0x03 && buf[i + 1] == 0x00 && + buf[i + 2] == 0x08 && buf[i + 3] == 0x00) { + failure = (long)le32_local(buf + i + 4); + have_negotiation = 1; + break; + } + } + if (failure >= 0) + apex_audit("rdp_probe", target, port, 1, "RDP negotiation failed", + "X.224"); + else + apex_audit("rdp_probe", target, port, 0, "RDP negotiated", + rdp_protocol_name(selected)); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"rdp\":true,\"negotiation\":%s," + "\"selected_code\":%lu,\"selected\":", + port, have_negotiation ? "true" : "false", selected); + apex_json_str(&b, rdp_protocol_name(selected)); + mcp_buf_printf(&b, ",\"nla\":%s,\"failure\":%s,\"failure_code\":%ld}", + (selected == 2 || selected == 3 || selected == 8) + ? "true" : "false", + failure >= 0 ? "true" : "false", failure); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ----------------------------------------------------------------- smb_probe */ + +static int write_bytes(int fd, const unsigned char *p, size_t n) +{ + size_t off = 0; + + while (off < n) { + ssize_t w = write(fd, p + off, n - off); + + if (w < 0) { + if (errno == EINTR) + continue; + return -1; + } + if (w == 0) + return -1; + off += (size_t)w; + } + return 0; +} + +static const char *smb_dialect_name(unsigned int d) +{ + switch (d) { + case 0x0202: + return "SMB 2.0.2"; + case 0x0210: + return "SMB 2.1"; + case 0x0300: + return "SMB 3.0"; + case 0x0302: + return "SMB 3.0.2"; + case 0x0311: + return "SMB 3.1.1"; + default: + return "unknown"; + } +} + +static void t_smb_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", 445); + unsigned char msg[160]; + unsigned char hdr[64]; + unsigned char body[64]; + static const unsigned int dialects[] = { + 0x0202, 0x0210, 0x0300, 0x0302, 0x0311 + }; + unsigned char nbt[4]; + unsigned char *resp = NULL; + unsigned long rlen; + unsigned int status = 0; + mcp_buf b; + int fd; + int i; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (!gated(c, "smb_probe", target, port)) + return; + memset(hdr, 0, sizeof(hdr)); + memcpy(hdr, "\xfeSMB", 4); + hdr[4] = 64; /* StructureSize */ + hdr[6] = 1; /* CreditCharge */ + hdr[14] = 1; /* CreditRequest */ + memset(body, 0, sizeof(body)); + body[0] = 36; /* StructureSize */ + body[2] = 5; /* DialectCount */ + body[4] = 1; /* SecurityMode: signing enabled */ + for (i = 0; i < 16; i++) + body[16 + i] = (unsigned char)(0xa0 + i); /* ClientGuid */ + for (i = 0; i < 5; i++) { + body[36 + i * 2] = (unsigned char)(dialects[i] & 0xff); + body[37 + i * 2] = (unsigned char)(dialects[i] >> 8); + } + memcpy(msg + 4, hdr, sizeof(hdr)); + memcpy(msg + 4 + sizeof(hdr), body, 46); + { + size_t total = 4 + sizeof(hdr) + 46; + + nbt[0] = 0x00; + nbt[1] = (unsigned char)((total - 4) >> 16); + nbt[2] = (unsigned char)((total - 4) >> 8); + nbt[3] = (unsigned char)(total - 4); + memcpy(msg, nbt, 4); + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the SMB service"); + return; + } + if (write_bytes(fd, msg, total) != 0) { + close(fd); + mcp_reply_error(c, "cannot send the SMB2 negotiate"); + return; + } + } + if (apex_net_exact(fd, nbt, 4) != 0) { + close(fd); + mcp_reply_error(c, "no SMB response"); + return; + } + rlen = ((unsigned long)nbt[1] << 16) | ((unsigned long)nbt[2] << 8) | + nbt[3]; + if (rlen < 32 || rlen > (1UL << 20)) { + close(fd); + mcp_reply_error(c, "SMB response length out of range"); + return; + } + resp = malloc(rlen); + if (resp == NULL) { + close(fd); + mcp_reply_error(c, "out of memory"); + return; + } + if (apex_net_exact(fd, resp, rlen) != 0) { + free(resp); + close(fd); + mcp_reply_error(c, "short SMB response"); + return; + } + close(fd); + if (memcmp(resp, "\xfeSMB", 4) == 0 && rlen >= 64) { + unsigned int secmode; + unsigned int dialect; + unsigned int caps; + char guid[40]; + unsigned long max_trans; + unsigned long max_read; + unsigned long max_write; + + status = le32_local(resp + 8); + if (status != 0) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "SMB2 negotiate failed with status " + "0x%08x", status); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + free(resp); + return; + } + secmode = resp[64 + 2] | ((unsigned int)resp[64 + 3] << 8); + dialect = resp[64 + 4] | ((unsigned int)resp[64 + 5] << 8); + caps = le32_local(resp + 64 + 24); + max_trans = le32_local(resp + 64 + 28); + max_read = le32_local(resp + 64 + 32); + max_write = le32_local(resp + 64 + 36); + snprintf(guid, sizeof(guid), + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-" + "%02x%02x%02x%02x%02x%02x", + resp[64 + 8], resp[64 + 9], resp[64 + 10], resp[64 + 11], + resp[64 + 12], resp[64 + 13], resp[64 + 14], resp[64 + 15], + resp[64 + 16], resp[64 + 17], resp[64 + 18], + resp[64 + 19], resp[64 + 20], resp[64 + 21], + resp[64 + 22], resp[64 + 23]); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"smb\":true,\"dialect\":", port); + apex_json_str(&b, smb_dialect_name(dialect)); + mcp_buf_printf(&b, ",\"dialect_code\":\"0x%04x\"," + "\"signing_required\":%s,\"signing_enabled\":%s," + "\"capabilities\":\"0x%08x\",\"max_transact\":%lu," + "\"max_read\":%lu,\"max_write\":%lu," + "\"server_guid\":", dialect, + (secmode & 2) ? "true" : "false", + (secmode & 1) ? "true" : "false", caps, max_trans, + max_read, max_write); + apex_json_str(&b, guid); + mcp_buf_puts(&b, "}"); + apex_audit("smb_probe", target, port, 0, "SMB2 negotiated", + smb_dialect_name(dialect)); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(resp); + return; + } + if (memcmp(resp, "\xffSMB", 4) == 0) { + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"smb\":true,\"dialect\":\"SMB1\"," + "\"signing_required\":null,\"signing_enabled\":null," + "\"server_guid\":null}", port); + apex_audit("smb_probe", target, port, 1, "SMB1 answered", "SMB1"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(resp); + return; + } + free(resp); + mcp_reply_error(c, "not an SMB response"); +} + const mcp_tool TOOLS_PROTO[] = { { "ftp_probe", "One-connection FTP check: read the 220 banner, ask FEAT, then try the " @@ -2093,6 +2418,28 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 389\"}}," "\"required\":[\"target\"]}", t_ldap_probe }, + { "rdp_probe", + "Send an X.224 Connection Request with an RDP negotiation request for " + "TLS|CredSSP (and the rest), then parse the Connection Confirm: the " + "selected protocol (RDP, TLS, CredSSP, RDSTLS, HYBRID_EX) and whether NLA " + "is in use, or the negotiation failure code. One connection, no logon. " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 3389\"}}," + "\"required\":[\"target\"]}", + t_rdp_probe }, + { "smb_probe", + "Send an SMB2 NEGOTIATE offering dialects 2.0.2, 2.1, 3.0, 3.0.2 and " + "3.1.1 and parse the response: dialect, signing required/enabled, " + "capabilities, maximum sizes and the server GUID. Falls back to an SMB1 " + "answer when that is what the server speaks. One connection, no session, " + "no authentication. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 445\"}}," + "\"required\":[\"target\"]}", + t_smb_probe }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/tests/gate_audit.py b/tests/gate_audit.py index c8be4b3..4926649 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 = 85 +EXPECTED_TOOLS = 88 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 de5dc14..1ebfa15 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("85 tools registered", len(tools) == 85, len(tools)) +check("88 tools registered", len(tools) == 88, 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"]) == 85) + check("http tools/list", len(listing["result"]["tools"]) == 88) 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 @@ -4082,6 +4082,140 @@ ldap_reject_srv.close() shutil.rmtree(key_root, ignore_errors=True) shutil.rmtree(sec_home, ignore_errors=True) +print("\n== RDP, SMB and SUID baseline ==") + + +def rdp_handler(failure): + def handle(conn): + conn.recv(19) + tag = b"\x03" if failure else b"\x02" + code = struct.pack("