From 48ca583c5cfe75fea2e83834c91b9b970844b9c9 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 13:48:28 +0000 Subject: [PATCH] apex-twin 1.11.0: VNC, MQTT and GraphQL probes, capability baseline Red: - vnc_probe: reads the RFB version, echoes it, then reads the security types (3.7/3.8 list or 3.3 single type), names them and flags None authentication (audited). A zero-length list reports the server's reason. No authentication. - mqtt_probe: one MQTT 3.1.1 CONNECT with a clean session and no username or password; reads the CONNACK code, disconnects, reports an anonymous broker (code 0) or the refusal reason. - graphql_probe: POSTs a compact introspection query and reports whether the schema is exposed, the type count, query/mutation type names and a reason when introspection is disabled or the endpoint is missing; evidence on hit. Blue: - cap_baseline: create/verify a baseline of Linux file capabilities (security.capability xattr) under the same paths as suid_baseline, reporting new, gone and changed capability sets; optional root prefix. Tests: RFB 3.8 with None+VNC auth, RFB 3.3, a zero-security-type server, MQTT brokers answering 0 and 5, GraphQL endpoints with a schema, disabled introspection and a 404, and a capability tree (real caps need CAP_SETFCAP, so the diff is exercised with a fabricated baseline entry). 593 checks, ASan suite green, analyze clean, release-check green including distcheck 1.11.0. --- CHANGELOG.md | 25 +++- README.md | 24 ++-- SECURITY.md | 6 +- docs/apex-twin.1 | 12 +- src/apex.h | 2 +- src/tools_blue.c | 276 +++++++++++++++++++++++++++++++++++++++ src/tools_proto.c | 306 ++++++++++++++++++++++++++++++++++++++++++++ src/tools_red.c | 140 ++++++++++++++++++++ tests/gate_audit.py | 2 +- tests/run.py | 189 ++++++++++++++++++++++++++- 10 files changed, 962 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b163f6c..78887d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,30 @@ 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.10.0 — 2026-11-21 — this change +## 1.11.0 — 2026-11-21 — this change + +- **VNC** (`vnc_probe`): reads the RFB version, echoes it, then reads the + offered security types (3.7/3.8 list or 3.3 single type), names each one and + flags None authentication (audited). A zero-length list reports the server's + reason string. No authentication is attempted. +- **MQTT** (`mqtt_probe`): sends one MQTT 3.1.1 CONNECT with a clean session + and no username/password, reads the CONNACK return code, disconnects, and + reports an anonymous broker (code 0) or the refusal reason. +- **GraphQL** (`graphql_probe`): POSTs a compact introspection query and + reports whether the schema is exposed, the type count, the query/mutation + type names and a reason when introspection is disabled or the endpoint is + missing; a successful dump is saved as evidence. +- **Blue** (`cap_baseline`): create/verify a baseline of Linux file + capabilities (`security.capability` xattr) under the same system paths as + the SUID baseline, reporting new, gone and changed capability sets. +- Tests with local fixtures: RFB 3.8 with None+VNC auth, RFB 3.3 and a + zero-security-type server, MQTT brokers answering 0 and 5, a GraphQL + endpoint with a small schema plus a disabled and a missing one, and a + capability tree (the fixture cannot set real capabilities without + CAP_SETFCAP, so the diff is exercised through a fabricated baseline entry). + 593 checks. Coverage 79.3%. + +## 1.10.0 — 2026-11-21 — f2a1fb4 - **RDP** (`rdp_probe`): sends an X.224 Connection Request with an RDP negotiation request for TLS|CredSSP (and the rest), parses the Connection diff --git a/README.md b/README.md index b9cbcdc..43f8ec4 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. -**88 tools · 579 end-to-end checks · 340 fuzz cases · 79.8% line coverage · ~420 KiB** +**92 tools · 593 end-to-end checks · 340 fuzz cases · 79.3% line coverage · ~437 KiB** ``` $ ./apex-twin --check -{"version":"1.10.0","tools":88,...,"scope":{"loaded":true,...}} +{"version":"1.11.0","tools":92,...,"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 (88) +## Tools (92) ### Scope and bookkeeping @@ -262,6 +262,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `vnc_probe` | RFB version and offered security types; flags None authentication | +| `mqtt_probe` | MQTT 3.1.1 CONNECT without credentials; CONNACK code, anonymous broker detection | +| `graphql_probe` | Introspection query: schema exposed, type count, query/mutation names, evidence | | `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 | @@ -290,6 +293,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `cap_baseline` | File capability xattr manifest (`create`/`verify`); reports new, gone and changed capability sets | ### ESP32 @@ -485,6 +489,8 @@ The full threat model, trust boundaries and a hardening checklist are in | 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 | +| VNC/MQTT | one connection and one handshake each | +| Capability baseline | 2000 entries; security.capability xattr only | --- @@ -495,7 +501,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 579 end-to-end checks +make test # version check + gate audit + 593 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 @@ -600,11 +606,12 @@ 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, rdp_probe, smb_probe + xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, + mqtt_probe, graphql_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, suid_baseline + ssh_key_audit, suid_baseline, cap_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 @@ -639,7 +646,7 @@ examples/ scope.json ## Status -1.10.0. Built and run: 88 tools, 579 checks, 340 fuzz cases and 79.8% line +1.11.0. Built and run: 92 tools, 593 checks, 340 fuzz cases and 79.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 @@ -667,7 +674,8 @@ verification, detection-rule export, integrity baselines and firmware writing 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; 1.10 added RDP and SMB negotiation checks -and a SUID baseline, again without changing an existing tool or file format. +and a SUID baseline; 1.11 added VNC, MQTT and GraphQL checks plus a file +capability 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 771d291..13714a8 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.10.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.11.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. +- **VNC and MQTT stop at the handshake.** `vnc_probe` reads the offered + security types and never authenticates; `mqtt_probe` sends one CONNECT with + no credentials, reads CONNACK and disconnects. `graphql_probe` sends only an + introspection query, and `cap_baseline` only reads the capability xattr. - **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 diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index e373204..7e03f06 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.10.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.11.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -40,11 +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, 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). +xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe, +graphql_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, cap_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 2ac251e..7601e29 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.10.0" +#define APEX_VERSION "1.11.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 bb6f9bc..81c8cd4 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -23,6 +23,7 @@ #include #include #include +#include #include #include "apex.h" @@ -2831,6 +2832,264 @@ static void t_suid_baseline(mcp_conn *c, const mcp_json *args, void *user) free(base_entries); } +/* -------------------------------------------------------------- cap_baseline */ + +typedef struct { + char path[512]; + char caps[192]; + int seen; +} cap_entry; + +typedef struct { + cap_entry *e; + int n; + int max; +} cap_ctx; + +static void cap_scan_dir(cap_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; + unsigned char raw[64]; + ssize_t got; + int i; + size_t w = 0; + + if (ctx->n >= ctx->max) + 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; + got = getxattr(path, "security.capability", raw, sizeof(raw)); + if (got <= 0) + continue; + snprintf(ctx->e[ctx->n].path, sizeof(ctx->e[0].path), "%.500s", + path); + for (i = 0; i < (int)got && w + 3 < sizeof(ctx->e[0].caps); i++) { + snprintf(ctx->e[ctx->n].caps + w, + sizeof(ctx->e[0].caps) - w, "%02x", raw[i]); + w += 2; + } + ctx->e[ctx->n].caps[w] = '\0'; + ctx->e[ctx->n].seen = 0; + ctx->n++; + } + closedir(d); +} + +static void t_cap_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]; + cap_entry *current = NULL; + cap_entry *base_entries = NULL; + int ncur; + 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/cap-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; + } + { + cap_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; + cap_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_puts(&lines, ",\"caps\":"); + apex_json_str(&lines, current[i].caps); + mcp_buf_puts(&lines, "}\n"); + } + 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 capability 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, ",\"capabilities\":%d}", ncur); + 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 capability 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, "caps", base_entries[nbase].caps, + sizeof(base_entries[nbase].caps))) + continue; + 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, ",\"capabilities\":%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_puts(&b, ",\"caps\":"); + apex_json_str(&b, current[i].caps); + mcp_buf_puts(&b, "}"); + } + } + 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++) { + if (strcmp(base_entries[j].path, current[i].path) != 0) + continue; + if (strcmp(base_entries[j].caps, current[i].caps) != 0) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, current[i].path); + mcp_buf_puts(&b, ",\"was\":"); + apex_json_str(&b, base_entries[j].caps); + mcp_buf_puts(&b, ",\"now\":"); + apex_json_str(&b, current[i].caps); + mcp_buf_puts(&b, "}"); + } + 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, " @@ -2975,6 +3234,23 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"max entries, default " "2000\"}}}", t_suid_baseline }, + { "cap_baseline", + "Create or verify a baseline of Linux file capabilities (the " + "security.capability xattr) under /usr/bin, /usr/sbin, /usr/local/bin, " + "/usr/local/sbin, /bin and /sbin. Verify reports new capability-bearing " + "files, vanished ones and changed capability sets, which catches a " + "binary granted CAP_SETUID or CAP_NET_RAW. The default baseline is " + "$APEX_HOME/cap-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/cap-baseline.jsonl\"}," + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max entries, default " + "2000\"}}}", + t_cap_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 b150577..7878521 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -2322,6 +2322,288 @@ static void t_smb_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_reply_error(c, "not an SMB response"); } +/* ---------------------------------------------------------------- vnc_probe */ + +static const char *vnc_auth_name(int t) +{ + switch (t) { + case 1: + return "None"; + case 2: + return "VNC Authentication"; + case 5: + return "RA2"; + case 6: + return "RA2ne"; + case 16: + return "Tight"; + case 17: + return "Ultra"; + case 18: + return "TLS"; + case 19: + return "VeNCrypt"; + case 20: + return "SASL"; + case 21: + return "MD5"; + case 22: + return "xvp"; + case 30: + return "Apple Remote Desktop"; + case 35: + return "RSA-AES"; + default: + return "unknown"; + } +} + +static void t_vnc_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", 5900); + unsigned char ver[13]; + char version[16]; + char reason[512]; + int major; + int minor; + int types[32]; + int ntypes = 0; + int none_auth = 0; + int i; + int fd; + 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, "vnc_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the VNC service"); + return; + } + if (apex_net_exact(fd, ver, 12) != 0 || memcmp(ver, "RFB ", 4) != 0) { + close(fd); + mcp_reply_error(c, "no RFB version banner"); + return; + } + memcpy(version, ver, 12); + version[12] = '\0'; + { + char *nl = strchr(version, '\n'); + + if (nl != NULL) + *nl = '\0'; + } + major = atoi(version + 4); + minor = 0; + { + char *dot = strchr(version + 4, '.'); + + if (dot != NULL) + minor = atoi(dot + 1); + } + if (write_bytes(fd, ver, 12) != 0) { + close(fd); + mcp_reply_error(c, "cannot send the RFB version"); + return; + } + reason[0] = '\0'; + if (major == 3 && minor >= 7) { + unsigned char count; + + if (apex_net_exact(fd, &count, 1) != 0) { + close(fd); + mcp_reply_error(c, "no VNC security types"); + return; + } + if (count == 0) { + unsigned char lb[4]; + unsigned long rl; + + if (apex_net_exact(fd, lb, 4) == 0) { + rl = ((unsigned long)lb[0] << 24) | + ((unsigned long)lb[1] << 16) | + ((unsigned long)lb[2] << 8) | lb[3]; + if (rl > 0 && rl < sizeof(reason)) { + if (apex_net_exact(fd, (unsigned char *)reason, + rl) != 0) + reason[0] = '\0'; + else + reason[rl] = '\0'; + } + } + } else { + unsigned char list[32]; + + if ((int)count > (int)sizeof(list)) + count = sizeof(list); + if (apex_net_exact(fd, list, count) == 0) { + for (i = 0; i < (int)count; i++) + types[ntypes++] = list[i]; + } + } + } else if (major == 3 && minor == 3) { + unsigned char tb[4]; + + if (apex_net_exact(fd, tb, 4) == 0) + types[ntypes++] = (int)(((unsigned int)tb[0] << 24) | + ((unsigned int)tb[1] << 16) | + ((unsigned int)tb[2] << 8) | tb[3]); + } + close(fd); + for (i = 0; i < ntypes; i++) + if (types[i] == 1) + none_auth = 1; + apex_audit("vnc_probe", target, port, !none_auth, + none_auth ? "VNC offers None authentication" + : "VNC requires authentication", version); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"vnc\":true,\"version\":", port); + apex_json_str(&b, version); + mcp_buf_puts(&b, ",\"security_types\":["); + for (i = 0; i < ntypes; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_printf(&b, "{\"code\":%d,\"name\":", types[i]); + apex_json_str(&b, vnc_auth_name(types[i])); + mcp_buf_puts(&b, "}"); + } + mcp_buf_printf(&b, "],\"none_auth\":%s,\"reason\":", + none_auth ? "true" : "false"); + apex_json_str(&b, reason); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ---------------------------------------------------------------- mqtt_probe */ + +static const char *mqtt_reason(int code) +{ + switch (code) { + case 0: + return "accepted"; + case 1: + return "unacceptable protocol version"; + case 2: + return "identifier rejected"; + case 3: + return "server unavailable"; + case 4: + return "bad username or password"; + case 5: + return "not authorized"; + default: + return "unknown"; + } +} + +static void t_mqtt_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *client_id = mcp_arg_string(args, "client_id"); + int port = mcp_arg_int(args, "port", 1883); + unsigned char pkt[256]; + unsigned char reply[16]; + unsigned char head[2]; + char client[64]; + size_t cidlen; + size_t rem; + size_t n = 0; + int fd; + int code = -1; + 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 (client_id != NULL && *client_id != '\0') + snprintf(client, sizeof(client), "%.48s", client_id); + else + snprintf(client, sizeof(client), "apex%ld", (long)getpid()); + cidlen = strlen(client); + rem = 10 + 2 + cidlen; + if (rem > 120) { + mcp_reply_error(c, "client_id too long"); + return; + } + if (!gated(c, "mqtt_probe", target, port)) + return; + pkt[n++] = 0x10; /* CONNECT */ + pkt[n++] = (unsigned char)rem; + pkt[n++] = 0x00; + pkt[n++] = 0x04; + memcpy(pkt + n, "MQTT", 4); + n += 4; + pkt[n++] = 0x04; /* protocol level 3.1.1 */ + pkt[n++] = 0x02; /* clean session, no credentials */ + pkt[n++] = 0x00; + pkt[n++] = 0x3c; /* keepalive 60 s */ + pkt[n++] = (unsigned char)(cidlen >> 8); + pkt[n++] = (unsigned char)(cidlen & 0xff); + memcpy(pkt + n, client, cidlen); + n += cidlen; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the MQTT broker"); + return; + } + if (write_bytes(fd, pkt, n) != 0) { + close(fd); + mcp_reply_error(c, "cannot send the MQTT CONNECT"); + return; + } + if (apex_net_exact(fd, head, 2) != 0 || head[0] != 0x20) { + close(fd); + mcp_reply_error(c, "no MQTT CONNACK"); + return; + } + if (head[1] > sizeof(reply)) { + close(fd); + mcp_reply_error(c, "MQTT CONNACK too long"); + return; + } + if (apex_net_exact(fd, reply, head[1]) == 0 && head[1] >= 2) + code = reply[1]; + { + static const unsigned char disc[2] = { 0xe0, 0x00 }; + + (void)write_bytes(fd, disc, 2); + } + close(fd); + apex_audit("mqtt_probe", target, port, code != 0, + code == 0 ? "anonymous MQTT connect accepted" + : "MQTT connect refused", mqtt_reason(code)); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"mqtt\":true,\"connack\":%d," + "\"accepted\":%s,\"anonymous\":%s,\"reason\":", + port, code, code == 0 ? "true" : "false", + code == 0 ? "true" : "false"); + apex_json_str(&b, mqtt_reason(code)); + 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 " @@ -2440,6 +2722,30 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 445\"}}," "\"required\":[\"target\"]}", t_smb_probe }, + { "vnc_probe", + "Read the RFB version banner, echo it and read the offered security " + "types (3.7/3.8 list or 3.3 single type). Reports the version, each type " + "by name and whether None authentication (type 1) is offered, which is " + "audited. No authentication is attempted. Gate: the target must be in " + "scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 5900\"}}," + "\"required\":[\"target\"]}", + t_vnc_probe }, + { "mqtt_probe", + "Send an MQTT 3.1.1 CONNECT with a clean session and no username or " + "password, read the CONNACK return code and disconnect. Code 0 means the " + "broker accepts anonymous clients and is audited; the other codes are " + "reported by name. No subscription and no publish. Gate: the target must " + "be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 1883\"}," + "\"client_id\":{\"type\":\"string\",\"description\":\"optional, " + "default apex\"}}," + "\"required\":[\"target\"]}", + t_mqtt_probe }, }; 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 03a719d..2b54992 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -2394,6 +2394,133 @@ static void t_xxe_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------- graphql_probe */ + +static void gql_name_after(const char *text, const char *key, char *out, + size_t n) +{ + const char *p = strstr(text, key); + const char *name; + size_t w = 0; + + out[0] = '\0'; + if (p == NULL) + return; + name = strstr(p, "\"name\":\""); + if (name == NULL) + return; + name += 8; + while (*name != '\0' && *name != '"' && w + 1 < n) + out[w++] = *name++; + out[w] = '\0'; +} + +static int gql_kind_count(const char *body, size_t len) +{ + int count = 0; + size_t i; + + for (i = 0; i + 8 <= len; i++) + if (memcmp(body + i, "\"kind\":\"", 8) == 0) + count++; + return count; +} + +static void t_graphql_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *path = mcp_arg_string(args, "path"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + static const char body[] = + "{\"query\":\"{__schema{queryType{name} mutationType{name} " + "types{name kind}}}\"}"; + char status[256]; + char *resp = NULL; + size_t len = 0; + int code = 0; + int introspection = 0; + int types = 0; + char query_type[128]; + char mutation_type[128]; + char reason[192]; + char *evidence = NULL; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (path == NULL || *path == '\0') + path = "/graphql"; + if (path[0] != '/') { + mcp_reply_error(c, "path must start with /"); + return; + } + if (!gated(c, "graphql_probe", target, port)) + return; + status[0] = '\0'; + if (apex_http_once(target, port, tls, "POST", path, body, + "Content-Type: application/json\r\n", 10000, &resp, + &len, status, sizeof(status)) != 0) { + mcp_reply_error(c, "cannot reach the GraphQL endpoint"); + return; + } + code = apex_status_code(status); + query_type[0] = mutation_type[0] = reason[0] = '\0'; + if (find_bytes(resp, len, "__schema") && + find_bytes(resp, len, "\"types\"")) { + introspection = 1; + types = gql_kind_count(resp, len); + gql_name_after(resp, "\"queryType\"", query_type, + sizeof(query_type)); + gql_name_after(resp, "\"mutationType\"", mutation_type, + sizeof(mutation_type)); + } else if (find_bytes(resp, len, "introspection") && + (find_bytes(resp, len, "disabled") || + find_bytes(resp, len, "not allowed") || + find_bytes(resp, len, "forbidden") || + find_bytes(resp, len, "not enabled"))) { + snprintf(reason, sizeof(reason), "%s", + "introspection is disabled"); + } else if (code == 404) { + snprintf(reason, sizeof(reason), "%s", "endpoint not found"); + } else { + snprintf(reason, sizeof(reason), "%s", + "no __schema in the response"); + } + if (introspection) + evidence = apex_evidence_save("graphql", resp, len); + apex_audit("graphql_probe", target, port, !introspection, + introspection ? "GraphQL introspection enabled" + : "introspection not available", path); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port); + apex_json_str(&b, path); + mcp_buf_printf(&b, ",\"status\":%d,\"graphql\":%s,\"introspection\":%s," + "\"types_count\":%d,\"query_type\":", code, + introspection ? "true" : "false", + introspection ? "true" : "false", types); + apex_json_str(&b, query_type); + mcp_buf_puts(&b, ",\"mutation_type\":"); + apex_json_str(&b, mutation_type); + mcp_buf_puts(&b, ",\"reason\":"); + apex_json_str(&b, reason); + mcp_buf_puts(&b, ",\"evidence\":"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + free(evidence); + free(resp); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -2610,6 +2737,19 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_xxe_probe }, + { "graphql_probe", + "POST a compact introspection query to one endpoint and report whether " + "the schema is exposed: type count, query and mutation type names, the " + "HTTP status, and a reason when introspection is disabled or the " + "endpoint is missing. A successful schema dump is saved as evidence. " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"path\":{\"type\":\"string\",\"description\":\"default /graphql\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_graphql_probe }, }; 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 4926649..a69af62 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 = 88 +EXPECTED_TOOLS = 92 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 1ebfa15..41366e8 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("88 tools registered", len(tools) == 88, len(tools)) +check("92 tools registered", len(tools) == 92, 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"]) == 88) + check("http tools/list", len(listing["result"]["tools"]) == 92) 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 @@ -4216,6 +4216,191 @@ for srv in (rdp_srv, rdp_fail_srv, smb_srv): shutil.rmtree(suid_root, ignore_errors=True) shutil.rmtree(plat_home, ignore_errors=True) +print("\n== VNC, MQTT, GraphQL and capabilities ==") + + +def vnc_handler(types): + def handle(conn): + conn.sendall(b"RFB 003.008\n") + conn.recv(12) + conn.sendall(bytes([len(types)]) + bytes(types)) + time.sleep(0.05) + return handle + + +def vnc33_handler(type_code): + def handle(conn): + conn.sendall(b"RFB 003.003\n") + conn.recv(12) + conn.sendall(struct.pack(">I", type_code)) + time.sleep(0.05) + return handle + + +def vnc_zero_handler(conn): + conn.sendall(b"RFB 003.008\n") + conn.recv(12) + reason = b"No security types" + conn.sendall(b"\x00" + struct.pack(">I", len(reason)) + reason) + time.sleep(0.05) + + +def mqtt_handler(code): + def handle(conn): + head = conn.recv(2) + if len(head) < 2: + return + need = head[1] + body = b"" + while len(body) < need: + chunk = conn.recv(need - len(body)) + if not chunk: + break + body += chunk + conn.sendall(bytes([0x20, 0x02, 0x00, code])) + time.sleep(0.05) + return handle + + +class _GraphqlHandler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + need = int(self.headers.get("Content-Length", "0")) + self.rfile.read(need) + parts = urllib.parse.urlsplit(self.path) + code = 200 + if parts.path == "/graphql": + doc = {"data": {"__schema": { + "queryType": {"name": "Query"}, + "mutationType": {"name": "Mutation"}, + "types": [ + {"name": "Query", "kind": "OBJECT"}, + {"name": "User", "kind": "OBJECT"}, + {"name": "String", "kind": "SCALAR"}, + ]}}} + body = json.dumps(doc, separators=(",", ":")).encode() + elif parts.path == "/graphql-disabled": + doc = {"errors": [{"message": + "GraphQL introspection is disabled"}]} + body = json.dumps(doc, separators=(",", ":")).encode() + else: + code = 404 + body = b"not found" + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +vnc_none_srv, vnc_none_port = start_line_server(vnc_handler([1, 2])) +vnc_auth_srv, vnc_auth_port = start_line_server(vnc_handler([2])) +vnc33_srv, vnc33_port = start_line_server(vnc33_handler(1)) +vnc_zero_srv, vnc_zero_port = start_line_server(vnc_zero_handler) +mqtt_ok_srv, mqtt_ok_port = start_line_server(mqtt_handler(0)) +mqtt_deny_srv, mqtt_deny_port = start_line_server(mqtt_handler(5)) +gql_srv = http.server.HTTPServer(("127.0.0.1", 0), _GraphqlHandler) +gql_port = gql_srv.server_address[1] +threading.Thread(target=gql_srv.serve_forever, daemon=True).start() + +cap_root = tempfile.mkdtemp(prefix="apex-cap-") +os.makedirs(os.path.join(cap_root, "usr", "bin")) +cap_tool = os.path.join(cap_root, "usr", "bin", "tool") +with open(cap_tool, "wb") as f: + f.write(b"plain tool") + +cap_home = tempfile.mkdtemp(prefix="apex-cap-home-") +write_scope(cap_home, {"label": "cap", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(vnc_none_port), + str(vnc_auth_port), str(vnc33_port), + str(vnc_zero_port), str(mqtt_ok_port), + str(mqtt_deny_port), str(gql_port)]}) +res, _ = run([ + call(1, "vnc_probe", target="127.0.0.1", port=vnc_none_port), + call(2, "vnc_probe", target="127.0.0.1", port=vnc_auth_port), + call(3, "mqtt_probe", target="127.0.0.1", port=mqtt_ok_port), + call(4, "mqtt_probe", target="127.0.0.1", port=mqtt_deny_port), + call(5, "graphql_probe", target="127.0.0.1", port=gql_port, + path="/graphql", tls=False), + call(6, "graphql_probe", target="127.0.0.1", port=gql_port, + path="/graphql-disabled", tls=False), + call(7, "graphql_probe", target="198.51.100.9", port=80, + path="/graphql"), + call(8, "cap_baseline", action="create", root=cap_root), + call(9, "vnc_probe", target="127.0.0.1", port=vnc33_port), + call(10, "vnc_probe", target="127.0.0.1", port=vnc_zero_port), + call(11, "graphql_probe", target="127.0.0.1", port=gql_port, + path="/missing", tls=False), +], home=cap_home) +by_id = {r.get("id"): r for r in res} +vnc = json.loads(text(by_id[1])) +check("vnc_probe reads the RFB version and security types", + vnc["version"] == "RFB 003.008" and len(vnc["security_types"]) == 2, + vnc) +check("vnc_probe detects None authentication", + vnc["none_auth"] is True and + {t["name"] for t in vnc["security_types"]} == + {"None", "VNC Authentication"}, vnc) +vnc_auth = json.loads(text(by_id[2])) +check("vnc_probe reports an auth-only server", + vnc_auth["none_auth"] is False and + vnc_auth["security_types"][0]["name"] == "VNC Authentication", vnc_auth) +mqtt_ok = json.loads(text(by_id[3])) +check("mqtt_probe accepts an anonymous broker", + mqtt_ok["connack"] == 0 and mqtt_ok["accepted"] is True and + mqtt_ok["anonymous"] is True, mqtt_ok) +mqtt_no = json.loads(text(by_id[4])) +check("mqtt_probe reports a refused connection", + mqtt_no["connack"] == 5 and mqtt_no["accepted"] is False and + mqtt_no["reason"] == "not authorized", mqtt_no) +gql = json.loads(text(by_id[5])) +check("graphql_probe dumps the introspection schema", + gql["introspection"] is True and gql["types_count"] == 3 and + gql["query_type"] == "Query" and gql["mutation_type"] == "Mutation", gql) +check("graphql_probe keeps the schema as evidence", + gql["evidence"] and os.path.isfile(gql["evidence"]), gql) +gql_off = json.loads(text(by_id[6])) +check("graphql_probe reports disabled introspection", + gql_off["introspection"] is False and + "disabled" in gql_off["reason"], gql_off) +check("graphql_probe refuses an out-of-scope target", err(by_id[7]), + text(by_id[7])) +vnc33 = json.loads(text(by_id[9])) +check("vnc_probe handles the RFB 3.3 single type", + vnc33["version"] == "RFB 003.003" and vnc33["none_auth"] is True and + vnc33["security_types"][0]["name"] == "None", vnc33) +vnc_zero = json.loads(text(by_id[10])) +check("vnc_probe reports a server with no security types", + vnc_zero["security_types"] == [] and vnc_zero["none_auth"] is False and + "No security types" in vnc_zero["reason"], vnc_zero) +gql_missing = json.loads(text(by_id[11])) +check("graphql_probe reports a missing endpoint", + gql_missing["introspection"] is False and + gql_missing["reason"] == "endpoint not found", gql_missing) +caps = json.loads(text(by_id[8])) +check("cap_baseline scans a tree without capabilities", + caps["capabilities"] == 0 and + os.path.isfile(os.path.join(cap_home, "cap-baseline.jsonl")), caps) +with open(os.path.join(cap_home, "cap-baseline.jsonl"), "a") as f: + f.write(json.dumps({"path": cap_tool, + "caps": "0100000200200000000000000000000000000000"}, + separators=(",", ":")) + "\n") +res, _ = run([call(1, "cap_baseline", action="verify", root=cap_root)], + home=cap_home) +cap_ver = json.loads(text(res[0])) +check("cap_baseline reports a vanished capability entry", + cap_tool in set(cap_ver["gone"]), cap_ver) +for srv in (vnc_none_srv, vnc_auth_srv, vnc33_srv, vnc_zero_srv, mqtt_ok_srv, + mqtt_deny_srv): + srv.close() +gql_srv.shutdown() +gql_srv.server_close() +shutil.rmtree(cap_root, ignore_errors=True) +shutil.rmtree(cap_home, 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"})