diff --git a/CHANGELOG.md b/CHANGELOG.md index 66b4ad6..06d4414 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,24 @@ 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.12.0 — 2026-11-21 — this change +## 1.13.0 — 2026-11-21 — this change + +- **POP3** (`pop3_probe`): banner, CAPA capability list (STLS flagged), then + QUIT. No USER/PASS and no login. +- **SIP** (`sip_probe`): one UDP OPTIONS with a generated Via/From/To/Call-ID, + then the status line, Server header and Allow method list from the answer. +- **Telnet** (`telnet_probe`): reads the banner and decodes IAC WILL/WONT/DO/ + DONT option negotiations (subnegotiations skipped) and sends nothing. +- **Blue** (`package_integrity`): runs `dpkg -V` (optionally for one package) + or `rpm -Va`/`-V`, parses changed files with their status flags, and can + parse a saved verify output from a mounted image instead. It is a local + process, so the gate audit's LOCAL_EXEC exception covers it. +- Tests with local fixtures: a POP3 server with TOP/STLS/SASL, a UDP SIP agent + answering 200 with Server/Allow, a Telnet server sending IAC DO/WILL plus + banner text, a saved dpkg verify output, and a live `dpkg -V bash` run. + 615 checks. Coverage 79.4%. + +## 1.12.0 — 2026-11-21 — c8598f8 - **Docker** (`docker_api_probe`): queries `/version` and `/containers/json?all=1` without credentials and reports engine/API version, diff --git a/README.md b/README.md index 4927dc5..c0fb9ee 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. -**96 tools · 605 end-to-end checks · 340 fuzz cases · 79.5% line coverage · ~453 KiB** +**100 tools · 615 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~461 KiB** ``` $ ./apex-twin --check -{"version":"1.12.0","tools":96,...,"scope":{"loaded":true,...}} +{"version":"1.13.0","tools":100,...,"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 (96) +## Tools (100) ### Scope and bookkeeping @@ -268,6 +268,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `docker_api_probe` | Unauthenticated `/version` and `/containers/json`: engine version, container/running counts, names, images | | `elasticsearch_probe` | Unauthenticated `/`, cluster health and index list: cluster, version, status, node and index counts | | `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 | +| `telnet_probe` | Banner plus IAC WILL/WONT/DO/DONT decoding; sends nothing | | `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 | @@ -298,6 +301,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | | `module_audit` | Loaded modules and taint letters, kernel taint bits decoded (proprietary, out-of-tree, unsigned, ...) | +| `package_integrity` | `dpkg -V` / `rpm -V` changed files, optionally one package or a saved verify output | ### ESP32 @@ -497,6 +501,8 @@ The full threat model, trust boundaries and a hardening checklist are in | Capability baseline | 2000 entries; security.capability xattr only | | Docker/Elasticsearch | two or three GETs, no credentials | | Module audit | 500 modules; /proc and /sys reads only | +| POP3/SIP/Telnet | one connection or datagram each; no login | +| Package verify | 300 s cap; one package when requested | --- @@ -507,7 +513,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 605 end-to-end checks +make test # version check + gate audit + 615 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 @@ -614,11 +620,13 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, open_redirect, host_header_injection, ssti_probe, xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe, graphql_probe, docker_api_probe, - elasticsearch_probe, imap_probe + elasticsearch_probe, imap_probe, pop3_probe, sip_probe, + telnet_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, cap_baseline, module_audit + ssh_key_audit, suid_baseline, cap_baseline, module_audit, + package_integrity 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 @@ -653,7 +661,7 @@ examples/ scope.json ## Status -1.12.0. Built and run: 96 tools, 605 checks, 340 fuzz cases and 79.5% line +1.13.0. Built and run: 100 tools, 615 checks, 340 fuzz cases and 79.4% line coverage. The loop closes: a probe captures the exchange as a pair, a finding points at it, `finding_update` gives it a state, an asset records the host it came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a @@ -683,7 +691,8 @@ 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; 1.11 added VNC, MQTT and GraphQL checks plus a file capability baseline; 1.12 added Docker, Elasticsearch and IMAP checks plus a -kernel module/taint audit, again without changing an existing tool or file +kernel module/taint audit; 1.13 added POP3, SIP and Telnet checks plus package +integrity verification, 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 8ac9281..376357e 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.12.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.13.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. +- **Mail and telephony probes stop at the greeting.** `pop3_probe` reads the + banner and CAPA and quits; `sip_probe` sends one OPTIONS and reads the answer; + `telnet_probe` sends nothing at all. `package_integrity` verifies installed + files locally with the package manager and never uses the network. - **Container, search and IMAP probes issue reads only.** `docker_api_probe` asks `/version` and `/containers/json`; `elasticsearch_probe` asks `/`, cluster health and the index list; `imap_probe` reads CAPABILITY and logs diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index accc1a2..c36f237 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.12.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.13.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -41,11 +41,12 @@ 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, vnc_probe, mqtt_probe, -graphql_probe, docker_api_probe, elasticsearch_probe, imap_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, module_audit) and -ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash). +graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe, +sip_probe, telnet_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, module_audit, package_integrity) 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 e3b4118..389e790 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.12.0" +#define APEX_VERSION "1.13.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 5974372..65a031c 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -3254,6 +3254,160 @@ static void t_module_audit(mcp_conn *c, const mcp_json *args, void *user) free(mods); } +/* ---------------------------------------------------------- package_integrity */ + +static void pi_add(mcp_buf *files, int *first, int *modified, int *emitted, + int limit, const char *line) +{ + char copy[1024]; + char *flags; + char *path; + size_t n; + + while (*line == ' ' || *line == '\t') + line++; + n = strlen(line); + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r' || + line[n - 1] == ' ' || line[n - 1] == '\t')) + n--; + if (n == 0) + return; + if (n >= sizeof(copy)) + n = sizeof(copy) - 1; + memcpy(copy, line, n); + copy[n] = '\0'; + flags = copy; + path = strchr(flags, ' '); + if (path == NULL) + path = strchr(flags, '\t'); + if (path == NULL) + return; + *path++ = '\0'; + while (*path == ' ' || *path == '\t') + path++; + if (*path == '\0') + return; + (*modified)++; + if (*emitted >= limit) + return; + if (!*first) + mcp_buf_puts(files, ","); + *first = 0; + (*emitted)++; + mcp_buf_puts(files, "{\"flags\":"); + apex_json_str(files, flags); + mcp_buf_puts(files, ",\"path\":"); + apex_json_str(files, path); + mcp_buf_puts(files, "}"); +} + +static void t_package_integrity(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *manager = mcp_arg_string(args, "manager"); + const char *package = mcp_arg_string(args, "package"); + const char *output = mcp_arg_string(args, "output"); + int limit = mcp_arg_int(args, "limit", 200); + const char *tool = NULL; + char *argv[5]; + apex_proc p; + int rc; + int exit_code = 0; + mcp_buf files; + mcp_buf b; + int first = 1; + int modified = 0; + int emitted = 0; + + (void)user; + if (limit <= 0 || limit > 5000) + limit = 200; + if (manager == NULL || *manager == '\0') + manager = "auto"; + if (output != NULL && *output != '\0') { + FILE *f = fopen(output, "rb"); + char *line = NULL; + size_t cap = 0; + + if (f == NULL) { + mcp_reply_error(c, "cannot read the saved verify output"); + return; + } + tool = strcmp(manager, "rpm") == 0 ? "rpm" : "dpkg"; + mcp_buf_init(&files); + while (getline(&line, &cap, f) >= 0) + pi_add(&files, &first, &modified, &emitted, limit, line); + free(line); + fclose(f); + } else { + if (strcmp(manager, "auto") == 0) { + if (apex_have("dpkg")) + tool = "dpkg"; + else if (apex_have("rpm")) + tool = "rpm"; + } else if (strcmp(manager, "dpkg") == 0 && apex_have("dpkg")) { + tool = "dpkg"; + } else if (strcmp(manager, "rpm") == 0 && apex_have("rpm")) { + tool = "rpm"; + } + if (tool == NULL) { + mcp_reply_error(c, + "neither dpkg nor rpm is available (or the " + "requested manager is not installed)"); + return; + } + if (strcmp(tool, "dpkg") == 0) { + argv[0] = "dpkg"; + argv[1] = "-V"; + argv[2] = (package != NULL && *package != '\0') + ? (char *)package : NULL; + argv[3] = NULL; + } else { + argv[0] = "rpm"; + argv[1] = (package != NULL && *package != '\0') ? "-V" : "-Va"; + argv[2] = (package != NULL && *package != '\0') + ? (char *)package : NULL; + argv[3] = NULL; + } + rc = apex_run(argv, 300000, g_cfg.max_output, &p); + if (rc != 0) { + mcp_reply_error(c, "cannot run the package verifier"); + return; + } + exit_code = p.exit_code; + mcp_buf_init(&files); + if (p.out != NULL) { + char *copy = strdup(p.out); + char *save = NULL; + char *line; + + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + pi_add(&files, &first, &modified, &emitted, limit, + line); + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + apex_proc_free(&p); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"tool\":"); + apex_json_str(&b, tool); + mcp_buf_printf(&b, ",\"package\":"); + apex_json_str(&b, package != NULL ? package : ""); + mcp_buf_printf(&b, ",\"exit\":%d,\"modified\":%d,\"truncated\":%s," + "\"files\":[", exit_code, modified, + emitted < modified ? "true" : "false"); + if (files.p != NULL) + mcp_buf_add(&b, files.p, files.len); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&files); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -3431,6 +3585,21 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"max modules, default " "500\"}}}", t_module_audit }, + { "package_integrity", + "Verify installed package files against the package database: dpkg -V " + "(optionally for one package) or rpm -Va/-V. Reports each changed file " + "with its status flags. An optional output file parses a verify run " + "captured earlier from a mounted image; no network. Local process only.", + "{\"type\":\"object\",\"properties\":{" + "\"manager\":{\"type\":\"string\",\"enum\":[\"auto\",\"dpkg\",\"rpm\"]," + "\"description\":\"default auto\"}," + "\"package\":{\"type\":\"string\",\"description\":\"verify one package " + "instead of all\"}," + "\"output\":{\"type\":\"string\",\"description\":\"parse a saved verify " + "output instead of running\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"files to return, " + "default 200\"}}}", + t_package_integrity }, }; 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 175dc1d..1d35121 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -2738,6 +2738,426 @@ static void t_imap_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- pop3_probe */ + +static void pop3_cap_add(char caps[][64], int *n, const char *line) +{ + char tok[64]; + size_t w = 0; + + while (*line == ' ' || *line == '\t') + line++; + while (*line != '\0' && *line != ' ' && *line != '\t' && w + 1 < sizeof(tok)) + tok[w++] = *line++; + tok[w] = '\0'; + if (w == 0) + return; + if (*n < 32) + snprintf(caps[*n], sizeof(caps[0]), "%.48s", tok); + (*n)++; +} + +static void t_pop3_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", 110); + char banner[512]; + char line[512]; + char caps[32][64]; + int ncaps = 0; + int stls = 0; + int i; + int rounds; + 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, "pop3_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the POP3 service"); + return; + } + if (apex_net_line(fd, banner, sizeof(banner)) < 0 || + strncmp(banner, "+OK", 3) != 0) { + close(fd); + mcp_reply_error(c, "no POP3 banner"); + return; + } + if (apex_net_write(fd, "CAPA\r\n") == 0) { + for (rounds = 0; rounds < 40; rounds++) { + if (apex_net_line(fd, line, sizeof(line)) < 0) + break; + if (strcmp(line, ".") == 0) + break; + if (strncmp(line, "+OK", 3) == 0) + continue; + if (strncmp(line, "-ERR", 4) == 0) + break; + pop3_cap_add(caps, &ncaps, line); + } + } + { + static const char quit[] = "QUIT\r\n"; + + (void)write(fd, quit, sizeof(quit) - 1); + } + close(fd); + for (i = 0; i < ncaps && i < 32; i++) + if (strcasecmp(caps[i], "STLS") == 0) + stls = 1; + apex_audit("pop3_probe", target, port, stls, + stls ? "POP3 offers STLS" : "no POP3 STLS", banner); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"pop3\":true,\"banner\":", port); + apex_json_str(&b, banner); + mcp_buf_printf(&b, ",\"stls\":%s,\"capabilities\":[", + stls ? "true" : "false"); + for (i = 0; i < ncaps && i < 32; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, caps[i]); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* ----------------------------------------------------------------- sip_probe */ + +static void sip_header(const char *text, const char *key, char *out, size_t n) +{ + char pattern[64]; + const char *p; + size_t w = 0; + + out[0] = '\0'; + snprintf(pattern, sizeof(pattern), "\r\n%s:", key); + p = strstr(text, pattern); + if (p == NULL) + return; + p += strlen(pattern); + while (*p == ' ' || *p == '\t') + p++; + while (*p != '\0' && *p != '\r' && *p != '\n' && w + 1 < n) + out[w++] = *p++; + out[w] = '\0'; +} + +static void t_sip_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", 5060); + char req[2048]; + char resp[4096]; + char status_line[256]; + char server[256]; + char allow[512]; + struct addrinfo hints; + struct addrinfo *res = NULL; + struct addrinfo *use = NULL; + struct addrinfo *rp; + char service[16]; + int fd = -1; + int attempt; + int got = 0; + int code = 0; + mcp_buf b; + int first = 1; + 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, "sip_probe", target, port)) + return; + snprintf(service, sizeof(service), "%d", port); + snprintf(req, sizeof(req), + "OPTIONS sip:%.200s SIP/2.0\r\n" + "Via: SIP/2.0/UDP %.200s;branch=z9hG4bK%ld\r\n" + "Max-Forwards: 70\r\n" + "From: ;tag=%ld\r\n" + "To: \r\n" + "Call-ID: %ld@apex\r\n" + "CSeq: 1 OPTIONS\r\n" + "Contact: \r\n" + "User-Agent: apex-twin\r\n" + "Content-Length: 0\r\n\r\n", + target, target, (long)getpid(), target, (long)getpid(), target, + (long)getpid(), target); + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + if (getaddrinfo(target, service, &hints, &res) != 0) { + mcp_reply_error(c, "cannot resolve the target"); + return; + } + for (rp = res; rp != NULL; rp = rp->ai_next) { + fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + if (fd >= 0) { + use = rp; + break; + } + } + if (use == NULL) { + freeaddrinfo(res); + mcp_reply_error(c, "cannot open a UDP socket"); + return; + } + status_line[0] = server[0] = allow[0] = '\0'; + for (attempt = 0; attempt < 2 && !got; attempt++) { + struct pollfd pfd; + ssize_t r; + + if (sendto(fd, req, strlen(req), 0, use->ai_addr, + use->ai_addrlen) < 0) + break; + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + if (poll(&pfd, 1, 2000) <= 0) + continue; + r = recv(fd, resp, sizeof(resp) - 1, 0); + if (r > 0) { + resp[r] = '\0'; + got = 1; + } + } + close(fd); + freeaddrinfo(res); + if (!got) { + mcp_reply_error(c, "no SIP response"); + return; + } + { + const char *eol = strstr(resp, "\r\n"); + + snprintf(status_line, sizeof(status_line), "%.*s", + (int)(eol != NULL ? (size_t)(eol - resp) : strlen(resp)), + resp); + } + if (strncmp(status_line, "SIP/2.0 ", 8) == 0) + code = atoi(status_line + 8); + sip_header(resp, "Server", server, sizeof(server)); + sip_header(resp, "Allow", allow, sizeof(allow)); + apex_audit("sip_probe", target, port, code == 0, status_line, "OPTIONS"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"sip\":true,\"status\":%d," + "\"status_line\":", port, code); + apex_json_str(&b, status_line); + mcp_buf_puts(&b, ",\"server\":"); + apex_json_str(&b, server); + mcp_buf_puts(&b, ",\"allow\":["); + { + char copy[512]; + char *save = NULL; + char *tok; + + snprintf(copy, sizeof(copy), "%s", allow); + tok = strtok_r(copy, ", ", &save); + while (tok != NULL) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, tok); + tok = strtok_r(NULL, ", ", &save); + } + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + (void)i; +} + +/* --------------------------------------------------------------- telnet_probe */ + +static const char *telnet_option_name(int opt) +{ + switch (opt) { + case 0: + return "binary"; + case 1: + return "echo"; + case 3: + return "suppress-go-ahead"; + case 5: + return "status"; + case 24: + return "terminal-type"; + case 31: + return "window-size"; + case 32: + return "terminal-speed"; + case 33: + return "remote-flow-control"; + case 34: + return "linemode"; + case 36: + return "environment"; + default: + return "unknown"; + } +} + +static void t_telnet_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", 23); + unsigned char buf[4096]; + char banner[1024]; + size_t blen = 0; + mcp_buf b; + int first = 1; + int count = 0; + int fd; + size_t total = 0; + int rounds = 0; + + (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, "telnet_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the Telnet service"); + return; + } + while (total < sizeof(buf)) { + struct pollfd pfd; + ssize_t r; + + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + if (poll(&pfd, 1, 600) <= 0) + break; + r = read(fd, buf + total, sizeof(buf) - total); + if (r <= 0) + break; + total += (size_t)r; + if (total >= 64 && rounds > 4) + break; + rounds++; + } + close(fd); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"telnet\":%s,\"banner\":", port, + total > 0 ? "true" : "false"); + { + size_t i = 0; + + while (i < total) { + unsigned char ch = buf[i]; + + if (ch == 0xff && i + 1 < total) { + unsigned char cmd = buf[i + 1]; + + if (cmd >= 251 && cmd <= 254 && i + 2 < total) { + banner[blen] = '\0'; + i += 3; + (void)cmd; + continue; + } + if (cmd == 250) { + i += 2; + while (i + 1 < total && + !(buf[i] == 0xff && buf[i + 1] == 240)) + i++; + i += 2; + continue; + } + i += 2; + continue; + } + if (blen + 1 < sizeof(banner)) { + banner[blen++] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : ' '; + } + i++; + } + } + banner[blen] = '\0'; + apex_json_str(&b, banner); + mcp_buf_puts(&b, ",\"negotiations\":["); + { + size_t i = 0; + + while (i + 2 < total) { + if (buf[i] != 0xff) { + i++; + continue; + } + { + unsigned char cmd = buf[i + 1]; + unsigned char opt = buf[i + 2]; + const char *verb = NULL; + + if (cmd == 251) + verb = "WILL"; + else if (cmd == 252) + verb = "WONT"; + else if (cmd == 253) + verb = "DO"; + else if (cmd == 254) + verb = "DONT"; + if (verb != NULL) { + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + count++; + mcp_buf_puts(&b, "{\"verb\":\""); + mcp_buf_puts(&b, verb); + mcp_buf_printf(&b, "\",\"option\":%d,\"name\":", opt); + apex_json_str(&b, telnet_option_name(opt)); + mcp_buf_puts(&b, "}"); + i += 3; + continue; + } + if (cmd == 250) { + i += 2; + while (i + 1 < total && + !(buf[i] == 0xff && buf[i + 1] == 240)) + i++; + i += 2; + continue; + } + i += 2; + } + } + } + mcp_buf_printf(&b, "],\"negotiation_count\":%d,\"bytes\":%lu}", + count, (unsigned long)total); + 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 " @@ -2890,6 +3310,34 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 143\"}}," "\"required\":[\"target\"]}", t_imap_probe }, + { "pop3_probe", + "Read the POP3 banner, send CAPA and report the capability list with the " + "STLS flag, then QUIT. No USER/PASS and no login. Plain POP3 (110). " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 110\"}}," + "\"required\":[\"target\"]}", + t_pop3_probe }, + { "sip_probe", + "Send one SIP OPTIONS over UDP and parse the response: status line, " + "Server header and the Allow method list. No registration and no call. " + "Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 5060\"}}," + "\"required\":[\"target\"]}", + t_sip_probe }, + { "telnet_probe", + "Connect, read the banner and decode the IAC option negotiation (WILL, " + "WONT, DO, DONT and the option names; subnegotiations are skipped). " + "Nothing is sent and no login is attempted. Gate: the target must be in " + "scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 23\"}}," + "\"required\":[\"target\"]}", + t_telnet_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 d7f2b5b..dd995c4 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 = 96 +EXPECTED_TOOLS = 100 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. @@ -29,7 +29,7 @@ RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown", "traffic_list", "detect_rules", "mitre_map"} # Tools that spawn a local program for hardware, not a network target. They take # no target and cannot reach one through the argv they build. -LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash"} +LOCAL_EXEC = {"esp_info", "esp_read_flash", "esp_flash", "package_integrity"} TABLE_RE = re.compile(r"const mcp_tool (TOOLS_[A-Z_]+)\[\] = \{(.*?)\n\};", re.S) diff --git a/tests/run.py b/tests/run.py index c3596ad..8d13849 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("96 tools registered", len(tools) == 96, len(tools)) +check("100 tools registered", len(tools) == 100, 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"]) == 96) + check("http tools/list", len(listing["result"]["tools"]) == 100) 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 @@ -4573,6 +4573,112 @@ imap_srv.close() shutil.rmtree(mod_root, ignore_errors=True) shutil.rmtree(svc_home, ignore_errors=True) +print("\n== POP3, SIP, Telnet and package integrity ==") + + +def pop3_handler(conn): + f = conn.makefile("rb") + conn.sendall(b"+OK test POP3 ready\r\n") + f.readline() + conn.sendall(b"+OK\r\nTOP\r\nSTLS\r\nSASL PLAIN LOGIN\r\n.\r\n") + f.readline() + conn.sendall(b"+OK bye\r\n") + time.sleep(0.05) + + +def sip_agent(): + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind(("127.0.0.1", 0)) + sock.settimeout(0.2) + port = sock.getsockname()[1] + stop = threading.Event() + + def loop(): + while not stop.is_set(): + try: + _data, addr = sock.recvfrom(4096) + except socket.timeout: + continue + except OSError: + return + sock.sendto(b"SIP/2.0 200 OK\r\nServer: TestSIP/1.0\r\n" + b"Allow: INVITE, ACK, OPTIONS, BYE\r\n" + b"Content-Length: 0\r\n\r\n", addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, port, stop + + +def telnet_handler(conn): + conn.sendall(b"\xff\xfd\x01\xff\xfb\x03Hello telnet\r\n") + time.sleep(0.1) + + +pop3_srv, pop3_port = start_line_server(pop3_handler) +sip_sock, sip_port, sip_stop = sip_agent() +telnet_srv, telnet_port = start_line_server(telnet_handler) + +pkg_home = tempfile.mkdtemp(prefix="apex-pkg-") +pkg_output = os.path.join(pkg_home, "dpkg-verify.txt") +with open(pkg_output, "w") as f: + f.write("??5?????? /usr/bin/foo\n") + f.write("missing /etc/bar.conf\n") + +pkg_calls = [ + call(1, "pop3_probe", target="127.0.0.1", port=pop3_port), + call(2, "sip_probe", target="127.0.0.1", port=sip_port), + call(3, "telnet_probe", target="127.0.0.1", port=telnet_port), + call(4, "package_integrity", output=pkg_output), + call(5, "pop3_probe", target="198.51.100.9", port=110), +] +if shutil.which("dpkg"): + pkg_calls.append(call(6, "package_integrity", manager="dpkg", + package="bash")) +write_scope(pkg_home, {"label": "pkg", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(pop3_port), str(sip_port), + str(telnet_port)]}) +res, _ = run(pkg_calls, home=pkg_home) +by_id = {r.get("id"): r for r in res} +pop3 = json.loads(text(by_id[1])) +check("pop3_probe reads the banner and CAPA", + pop3["banner"].startswith("+OK") and "TOP" in pop3["capabilities"] and + "SASL" in pop3["capabilities"], pop3) +check("pop3_probe flags STLS", pop3["stls"] is True, pop3) +sip = json.loads(text(by_id[2])) +check("sip_probe reads the OPTIONS answer", + sip["sip"] is True and sip["status"] == 200 and + sip["server"] == "TestSIP/1.0", sip) +check("sip_probe lists the allowed methods", + {"OPTIONS", "INVITE", "BYE"} <= set(sip["allow"]), sip) +tel = json.loads(text(by_id[3])) +checks = {n["verb"]: n["name"] for n in tel["negotiations"]} +check("telnet_probe reads the banner past the IAC bytes", + tel["telnet"] is True and "Hello telnet" in tel["banner"], tel) +check("telnet_probe decodes the negotiations", + tel["negotiation_count"] == 2 and checks.get("DO") == "echo" and + checks.get("WILL") == "suppress-go-ahead", tel) +pkg = json.loads(text(by_id[4])) +check("package_integrity parses a dpkg verify output", + pkg["tool"] == "dpkg" and pkg["modified"] == 2 and + [f["path"] for f in pkg["files"]] == ["/usr/bin/foo", + "/etc/bar.conf"], pkg) +check("package_integrity keeps the status flags", + pkg["files"][0]["flags"] == "??5??????" and + pkg["files"][1]["flags"] == "missing", pkg["files"]) +if 6 in by_id: + live = json.loads(text(by_id[6])) + check("package_integrity runs dpkg for one package", + live["tool"] == "dpkg" and live["exit"] == 0 and + isinstance(live["files"], list), live) +check("pop3_probe refuses an out-of-scope target", err(by_id[5]), + text(by_id[5])) +pop3_srv.close() +telnet_srv.close() +sip_stop.set() +sip_sock.close() +shutil.rmtree(pkg_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"})