diff --git a/CHANGELOG.md b/CHANGELOG.md index 194d7c6..f17ab70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,29 @@ 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.15.0 — 2026-11-21 — this change +## 1.16.0 — 2026-11-21 — this change + +- **SNMP walk** (`snmp_walk`): GETNEXT over 1.3.6.1.2.1.1 for up to 30 steps, + decoding the returned OID and its value (string, integer, timeticks, counter, + IP address, OID). Reports sysDescr, sysObjectID, sysUpTime, sysName and + friends. +- **LDAP search** (`ldap_search`): anonymous bind, namingContexts resolved from + the rootDSE when no base is given, then one subtree search (scope 2, size + limit 20) for present(objectClass); collects the DNs with cn/uid/mail. +- **OpenAPI discovery** (`openapi_discovery`): six usual spec paths; reports + version, info title and the number of paths, saving the document as evidence. +- **Blue** (`systemd_audit`): unit files under /etc/systemd/system and + /usr/lib/systemd/system (optional root prefix): ExecStart in /tmp, + /dev/shm or /var/tmp, service units without User=, world-writable unit files + and the number of .wants/.requires links. +- Tests with local fixtures: a UDP SNMP agent returning a GETNEXT chain with + string/OID/timeticks values, an LDAP server with rootDSE plus two subtree + entries, an OpenAPI endpoint and a systemd tree. 649 checks. Coverage 79.5%. +- Two parser bugs the fixtures caught: the system OID prefix is 14 characters + (not 15), and the rootDSE search answer includes a searchResultDone that must + be drained before the subtree response is read. + +## 1.15.0 — 2026-11-21 — c38cbcc - **HTTP methods** (`http_methods`): OPTIONS for the Allow list and Server header, TRACE for echo detection (cross-site tracing). PUT/DELETE are named diff --git a/README.md b/README.md index 98cffa6..b6b9ae0 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. -**108 tools · 639 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~486 KiB** +**112 tools · 649 end-to-end checks · 340 fuzz cases · 79.5% line coverage · ~502 KiB** ``` $ ./apex-twin --check -{"version":"1.15.0","tools":108,...,"scope":{"loaded":true,...}} +{"version":"1.16.0","tools":112,...,"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 (108) +## Tools (112) ### Scope and bookkeeping @@ -270,6 +270,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `http_methods` | OPTIONS Allow list and TRACE echo detection; names PUT/DELETE but never sends them | | `websocket_probe` | Upgrade handshake: 101, Upgrade/Connection and Sec-WebSocket-Accept | | `ike_probe` | IKEv2 SA_INIT (AES-CBC-128/HMAC-SHA2-256/DH14); version, exchange, notify, responder SPI | +| `snmp_walk` | GETNEXT over the system group: OID, name and decoded value (string, integer, timeticks, OID) | +| `ldap_search` | Anonymous subtree search (size limit 20) from namingContexts; DNs plus cn/uid/mail | +| `openapi_discovery` | Six usual spec paths: OpenAPI/Swagger version, title and path count, evidence | | `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 | @@ -307,6 +310,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `package_integrity` | `dpkg -V` / `rpm -V` changed files, optionally one package or a saved verify output | | `mount_audit` | Mount table hardening: temp/shm mounts missing nosuid/nodev/noexec, home/media/mnt missing nosuid/nodev | | `firewall_audit` | `nft list ruleset` / `iptables-save` (or saved dump): chain/rule counts and ACCEPT default policies | +| `systemd_audit` | Units: ExecStart in /tmp, missing User= (root), world-writable files, .wants links | ### ESP32 @@ -516,6 +520,9 @@ The full threat model, trust boundaries and a hardening checklist are in | Method/WebSocket | one or two requests, no frames or writes | | IKEv2 | one SA_INIT, two UDP attempts, no credentials | | Firewall audit | reads the ruleset or a saved dump, 4 MiB cap | +| SNMP walk | 30 GETNEXT steps, 1.8 s per step | +| LDAP search | 20 entries, 30 messages, anonymous | +| Systemd audit | 500 units; reads unit files only | --- @@ -526,7 +533,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 639 end-to-end checks +make test # version check + gate audit + 649 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 @@ -634,12 +641,14 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe, graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe, sip_probe, - telnet_probe, http_methods, websocket_probe, ike_probe + telnet_probe, http_methods, websocket_probe, ike_probe, + snmp_walk, ldap_search, openapi_discovery 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, - package_integrity, mount_audit, firewall_audit + package_integrity, mount_audit, firewall_audit, + systemd_audit src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit, @@ -675,7 +684,7 @@ examples/ scope.json ## Status -1.15.0. Built and run: 108 tools, 639 checks, 340 fuzz cases and 79.4% line +1.16.0. Built and run: 112 tools, 649 checks, 340 fuzz cases and 79.5% 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 @@ -707,8 +716,9 @@ 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; 1.13 added POP3, SIP and Telnet checks plus package integrity verification; 1.14 added offline ESP32 flash analysis and a mount -audit; 1.15 added HTTP method, WebSocket and IKEv2 checks plus a firewall audit, -again without changing an existing tool or file format. +audit; 1.15 added HTTP method, WebSocket and IKEv2 checks plus a firewall audit; 1.16 +added SNMP walk, LDAP search and OpenAPI discovery plus a systemd audit, 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 8df7142..517cbed 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.15.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.16.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,11 @@ 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. +- **Directory and walk probes are bounded reads.** `snmp_walk` issues at most + 30 GETNEXT requests for the system group; `ldap_search` binds anonymously and + stops after 20 entries; `openapi_discovery` fetches six documents; + `systemd_audit` reads unit files. None writes or authenticates with a + credential. - **Method and protocol probes stay read-only.** `http_methods` sends OPTIONS and TRACE but never PUT/DELETE; `websocket_probe` performs the handshake and sends no frame; `ike_probe` sends one SA_INIT with no credentials or PSK; diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 3b610f3..103eb67 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.15.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.16.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -42,11 +42,12 @@ 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, pop3_probe, -sip_probe, telnet_probe, http_methods, websocket_probe, ike_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, mount_audit, firewall_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, +sip_probe, telnet_probe, http_methods, websocket_probe, ike_probe, snmp_walk, +ldap_search, openapi_discovery), 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, mount_audit, +firewall_audit, systemd_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan). .SH MODES .TP diff --git a/src/apex.h b/src/apex.h index f00950b..ad6e156 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.15.0" +#define APEX_VERSION "1.16.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 ed7ff2c..ac081e9 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -3735,6 +3735,187 @@ static void t_firewall_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------- systemd_audit */ + +typedef struct { + mcp_buf *b; + int first; + int count; + int units; + int enabled; + int max_units; +} sd_ctx; + +static void sd_finding(sd_ctx *ctx, const char *path, const char *kind, + const char *severity, const char *detail) +{ + if (ctx->count >= 100) + return; + if (!ctx->first) + mcp_buf_puts(ctx->b, ","); + ctx->first = 0; + ctx->count++; + mcp_buf_puts(ctx->b, "{\"path\":"); + apex_json_str(ctx->b, path); + mcp_buf_puts(ctx->b, ",\"kind\":"); + apex_json_str(ctx->b, kind); + mcp_buf_puts(ctx->b, ",\"severity\":"); + apex_json_str(ctx->b, severity); + mcp_buf_puts(ctx->b, ",\"detail\":"); + apex_json_str(ctx->b, detail); + mcp_buf_puts(ctx->b, "}"); +} + +static int sd_unit_name(const char *name) +{ + static const char *suffixes[] = { ".service", ".timer", ".socket", + ".mount", ".target", NULL }; + int i; + + for (i = 0; suffixes[i] != NULL; i++) { + size_t nl = strlen(name); + size_t sl = strlen(suffixes[i]); + + if (nl > sl && strcmp(name + nl - sl, suffixes[i]) == 0) + return 1; + } + return 0; +} + +static void sd_scan_file(sd_ctx *ctx, const char *path) +{ + static char text[65536]; + struct stat st; + int is_service; + const char *exec; + const char *tmp_path; + + if (ctx->units >= ctx->max_units) + return; + if (strstr(path, ".wants/") != NULL || strstr(path, ".requires/") != NULL) + return; + if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) + return; + is_service = strstr(path, ".service") != NULL && + strcmp(path + strlen(path) - 8, ".service") == 0; + ctx->units++; + if (read_text(path, text, sizeof(text)) < 0) + return; + if ((st.st_mode & 0002) != 0) + sd_finding(ctx, path, "world-writable-unit", "high", + "unit file is writable by anyone"); + exec = strstr(text, "ExecStart="); + if (exec != NULL) { + const char *eol = strchr(exec, '\n'); + + tmp_path = strstr(exec, "/tmp/"); + if (tmp_path == NULL) + tmp_path = strstr(exec, "/dev/shm/"); + if (tmp_path == NULL) + tmp_path = strstr(exec, "/var/tmp/"); + if (tmp_path != NULL && (eol == NULL || tmp_path < eol)) + sd_finding(ctx, path, "exec-start-temp", "medium", + "ExecStart runs a binary from a temporary directory"); + } + if (is_service && strstr(text, "User=") == NULL) + sd_finding(ctx, path, "runs-as-root", "low", + "service has no User= and runs as root"); +} + +static void sd_scan_dir(sd_ctx *ctx, const char *dir) +{ + DIR *d = opendir(dir); + struct dirent *ent; + + if (d == NULL) + return; + while ((ent = readdir(d)) != NULL && ctx->units < ctx->max_units) { + char path[1024]; + struct stat st; + size_t dl = strlen(dir); + size_t nl = strlen(ent->d_name); + + if (ent->d_name[0] == '.') + continue; + if (dl + nl + 2 > sizeof(path)) + continue; + memcpy(path, dir, dl); + path[dl] = '/'; + memcpy(path + dl + 1, ent->d_name, nl + 1); + if (lstat(path, &st) != 0) + continue; + if (S_ISDIR(st.st_mode)) { + if (strstr(path, ".wants") != NULL || + strstr(path, ".requires") != NULL) { + DIR *wd = opendir(path); + struct dirent *we; + + if (wd == NULL) + continue; + while ((we = readdir(wd)) != NULL) { + if (we->d_name[0] == '.') + continue; + ctx->enabled++; + } + closedir(wd); + } + continue; + } + if (S_ISLNK(st.st_mode)) + continue; + if (sd_unit_name(ent->d_name)) + sd_scan_file(ctx, path); + } + closedir(d); +} + +static void t_systemd_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *root = mcp_arg_string(args, "root"); + int limit = mcp_arg_int(args, "limit", 500); + char base[512]; + char path[1024]; + size_t bl; + mcp_buf b; + mcp_buf findings; + sd_ctx ctx; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) >= sizeof(base) - 2) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(base, sizeof(base), "%s", root); + bl = strlen(base); + while (bl > 0 && base[bl - 1] == '/') + base[--bl] = '\0'; + if (limit <= 0 || limit > 5000) + limit = 500; + mcp_buf_init(&findings); + memset(&ctx, 0, sizeof(ctx)); + ctx.b = &findings; + ctx.first = 1; + ctx.max_units = limit; + snprintf(path, sizeof(path), "%s/etc/systemd/system", base); + sd_scan_dir(&ctx, path); + snprintf(path, sizeof(path), "%s/usr/lib/systemd/system", base); + sd_scan_dir(&ctx, path); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"units\":%d,\"enabled_links\":%d," + "\"findings_count\":%d,\"findings\":[", + ctx.units, ctx.enabled, ctx.count); + if (findings.p != NULL) + mcp_buf_add(&b, findings.p, findings.len); + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&findings); +} + const mcp_tool TOOLS_BLUE[] = { { "hardening_audit", "Read-only posture audit of the local host: sshd_config (root login, " @@ -3952,6 +4133,17 @@ const mcp_tool TOOLS_BLUE[] = { "\"limit\":{\"type\":\"integer\",\"description\":\"reserved, default " "500\"}}}", t_firewall_audit }, + { "systemd_audit", + "Audit systemd units under /etc/systemd/system and /usr/lib/systemd/system " + "(optional root prefix for a mounted image): ExecStart pointing into " + "/tmp, /dev/shm or /var/tmp, service units without User= (running as " + "root), world-writable unit files, and the number of .wants/.requires " + "links. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"max units, default " + "500\"}}}", + t_systemd_audit }, }; const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]); diff --git a/src/tools_proto.c b/src/tools_proto.c index b6debec..cb6ad43 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -1214,19 +1214,18 @@ static size_t ber_tlv(unsigned char *out, unsigned char tag, return 1 + l + n; } -/* SNMPv1/v2c GET sysDescr.0, assembled by hand (no net-snmp dependency). */ +/* SNMPv1/v2c GET/GETNEXT for one OID, assembled by hand. */ static size_t snmp_build(unsigned char *msg, size_t cap, int version, - const char *community, unsigned long reqid) + const char *community, unsigned long reqid, + const unsigned char *oid, size_t oid_len, + unsigned char pdu_tag) { - static const unsigned char oid[] = { - 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00 - }; - unsigned char vb_c[64]; - unsigned char vb[80]; - unsigned char vbl[96]; - unsigned char pdu_c[192]; - unsigned char pdu[224]; - unsigned char msg_c[320]; + unsigned char vb_c[256]; + unsigned char vb[288]; + unsigned char vbl[320]; + unsigned char pdu_c[384]; + unsigned char pdu[416]; + unsigned char msg_c[512]; size_t vc = 0; size_t vb_len; size_t vbl_len; @@ -1238,7 +1237,9 @@ static size_t snmp_build(unsigned char *msg, size_t cap, int version, if (c_len > 64) c_len = 64; - vc += ber_tlv(vb_c + vc, 0x06, oid, sizeof(oid)); + if (oid_len > 64) + oid_len = 64; + vc += ber_tlv(vb_c + vc, 0x06, oid, oid_len); vb_c[vc++] = 0x05; vb_c[vc++] = 0x00; vb_len = ber_tlv(vb, 0x30, vb_c, vc); @@ -1257,7 +1258,7 @@ static size_t snmp_build(unsigned char *msg, size_t cap, int version, pdu_c[pc++] = 0x00; memcpy(pdu_c + pc, vbl, vbl_len); pc += vbl_len; - pdu_len = ber_tlv(pdu, 0xa0, pdu_c, pc); + pdu_len = ber_tlv(pdu, pdu_tag, pdu_c, pc); msg_c[mc++] = 0x02; msg_c[mc++] = 0x01; msg_c[mc++] = (unsigned char)(version == 0 ? 0 : 1); @@ -1409,13 +1410,18 @@ static void t_snmp_probe(mcp_conn *c, const mcp_json *args, void *user) for (i = 0; i < ncomm; i++) { unsigned char msg[512]; unsigned char resp[2048]; - size_t mlen = snmp_build(msg, sizeof(msg), 1, communities[i], - (unsigned long)getpid()); + static const unsigned char sysdescr_oid[] = { + 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00 + }; + size_t mlen; char sysdescr[1024]; int responded = 0; int attempt; sysdescr[0] = '\0'; + mlen = snmp_build(msg, sizeof(msg), 1, communities[i], + (unsigned long)getpid(), sysdescr_oid, + sizeof(sysdescr_oid), 0xa0); for (attempt = 0; attempt < 2 && !responded && mlen > 0; attempt++) { struct pollfd pfd; ssize_t r; @@ -1788,7 +1794,8 @@ static void ldap_attr_add(ldap_attr *attrs, int *n, const char *name, } static void ldap_parse_entry(const unsigned char *buf, size_t n, - ldap_attr *attrs, int *nattrs) + ldap_attr *attrs, int *nattrs, char *dn, + size_t dn_n) { size_t off = 0; unsigned char tag; @@ -1800,6 +1807,12 @@ static void ldap_parse_entry(const unsigned char *buf, size_t n, if (ber_next(buf, n, &off, &tag, &val, &vlen) != 0 || tag != 0x04) return; /* objectName */ + if (dn != NULL && dn_n > 0) { + size_t w = vlen < dn_n - 1 ? vlen : dn_n - 1; + + memcpy(dn, val, w); + dn[w] = '\0'; + } if (ber_next(buf, n, &off, &tag, &val, &vlen) != 0 || tag != 0x30) return; list = val; @@ -1958,7 +1971,7 @@ static void t_ldap_probe(mcp_conn *c, const mcp_json *args, void *user) if (t2 == 0x64) { root_dse = 1; ldap_parse_entry(v2, l2, attrs, - &nattrs); + &nattrs, NULL, 0); } else if (t2 == 0x65) { break; } @@ -3342,6 +3355,590 @@ static void t_ike_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- snmp_walk */ + +static size_t snmp_oid_comp(unsigned char *out, size_t w, unsigned long v) +{ + unsigned char tmp[8]; + int n = 0; + + do { + tmp[n++] = (unsigned char)(v & 0x7f); + v >>= 7; + } while (v != 0 && n < 8); + while (n > 0) { + n--; + out[w++] = (unsigned char)(tmp[n] | (n == 0 ? 0 : 0x80)); + } + return w; +} + +static size_t snmp_oid_encode(const char *dotted, unsigned char *out, + size_t cap) +{ + unsigned long parts[32]; + int np = 0; + const char *p = dotted; + size_t w = 0; + int i; + + while (*p != '\0' && np < 32) { + char *end = NULL; + unsigned long v = strtoul(p, &end, 10); + + if (end == p) + break; + parts[np++] = v; + p = end; + if (*p == '.') + p++; + else + break; + } + if (np < 2) + return 0; + w = snmp_oid_comp(out, w, parts[0] * 40 + parts[1]); + for (i = 2; i < np && w < cap; i++) + w = snmp_oid_comp(out, w, parts[i]); + return w <= cap ? w : 0; +} + +static void snmp_oid_dotted(const unsigned char *p, size_t n, char *out, + size_t on) +{ + size_t i = 1; + size_t w = 0; + + out[0] = '\0'; + if (n == 0) + return; + w = (size_t)snprintf(out, on, "%u.%u", p[0] / 40, p[0] % 40); + while (i < n) { + unsigned long v = 0; + + while (i < n && (p[i] & 0x80) != 0) + v = (v << 7) | (p[i++] & 0x7f); + if (i < n) + v = (v << 7) | p[i++]; + if (w + 1 < on) + w += (size_t)snprintf(out + w, on - w, ".%lu", v); + } +} + +static void snmp_value_text(unsigned char tag, const unsigned char *v, + size_t n, char *out, size_t on) +{ + size_t i; + + out[0] = '\0'; + switch (tag) { + case 0x04: + for (i = 0; i < n && i + 1 < on; i++) + out[i] = (v[i] >= 0x20 && v[i] < 0x7f) ? (char)v[i] : ' '; + out[i < on ? i : on - 1] = '\0'; + break; + case 0x02: + if (n > 0 && n <= 4) { + long val = (v[0] & 0x80) ? -1 : 0; + + for (i = 0; i < n; i++) + val = (val << 8) | v[i]; + snprintf(out, on, "%ld", val); + } + break; + case 0x41: + case 0x43: + if (n == 4) + snprintf(out, on, "%lu", (unsigned long)be32(v)); + break; + case 0x40: + if (n == 4) + snprintf(out, on, "%u.%u.%u.%u", v[0], v[1], v[2], v[3]); + break; + case 0x06: + snmp_oid_dotted(v, n, out, on); + break; + case 0x05: + snprintf(out, on, "%s", "null"); + break; + default: + snprintf(out, on, "type 0x%02x", tag); + break; + } +} + +static int snmp_parse_varbind(const unsigned char *buf, size_t n, char *oid, + size_t on, char *val, size_t vn) +{ + size_t off = 0; + size_t o2 = 0; + unsigned char tag; + const unsigned char *v; + size_t l; + + if (ber_next(buf, n, &off, &tag, &v, &l) != 0 || tag != 0x30) + return -1; + while (o2 < l) { + const unsigned char *pv; + size_t pl; + unsigned char pt; + + if (ber_next(v, l, &o2, &pt, &pv, &pl) != 0) + return -1; + if (pt != 0xa2) + continue; + { + int field = 0; + size_t o5 = 0; + + while (o5 < pl) { + unsigned char vt; + const unsigned char *vv; + size_t vl; + + if (ber_next(pv, pl, &o5, &vt, &vv, &vl) != 0) + return -1; + if (++field != 4) + continue; + { + size_t o6 = 0; + unsigned char bt; + const unsigned char *bv; + size_t bl; + size_t o7 = 0; + unsigned char ot; + const unsigned char *ov; + size_t ol; + + if (ber_next(vv, vl, &o6, &bt, &bv, &bl) != 0 || + bt != 0x30) + return -1; + if (ber_next(bv, bl, &o7, &ot, &ov, &ol) != 0 || + ot != 0x06) + return -1; + snmp_oid_dotted(ov, ol, oid, on); + if (ber_next(bv, bl, &o7, &ot, &ov, &ol) != 0) + return -1; + snmp_value_text(ot, ov, ol, val, vn); + return 0; + } + } + } + } + return -1; +} + +static const char *snmp_sys_name(const char *oid) +{ + static const struct { + const char *oid; + const char *name; + } names[] = { + { "1.3.6.1.2.1.1.1.0", "sysDescr" }, + { "1.3.6.1.2.1.1.2.0", "sysObjectID" }, + { "1.3.6.1.2.1.1.3.0", "sysUpTime" }, + { "1.3.6.1.2.1.1.4.0", "sysContact" }, + { "1.3.6.1.2.1.1.5.0", "sysName" }, + { "1.3.6.1.2.1.1.6.0", "sysLocation" }, + { "1.3.6.1.2.1.1.7.0", "sysServices" }, + { NULL, NULL } + }; + int i; + + for (i = 0; names[i].oid != NULL; i++) + if (strcmp(oid, names[i].oid) == 0) + return names[i].name; + return "unknown"; +} + +static void t_snmp_walk(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *community = mcp_arg_string(args, "community"); + int port = mcp_arg_int(args, "port", 161); + int max_steps = mcp_arg_int(args, "max_steps", 30); + struct addrinfo hints; + struct addrinfo *res = NULL; + struct addrinfo *use = NULL; + struct addrinfo *rp; + char service[16]; + int fd = -1; + char oid[128]; + char next_oid[160]; + char value[512]; + mcp_buf b; + int first = 1; + int count = 0; + int step; + int truncated = 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 (community == NULL || *community == '\0') + community = "public"; + if (max_steps <= 0 || max_steps > 100) + max_steps = 30; + if (!gated(c, "snmp_walk", target, port)) + return; + snprintf(service, sizeof(service), "%d", port); + 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; + } + snprintf(oid, sizeof(oid), "1.3.6.1.2.1.1"); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"community\":", port); + apex_json_str(&b, community); + mcp_buf_puts(&b, ",\"entries\":["); + for (step = 0; step < max_steps; step++) { + unsigned char msg[512]; + unsigned char resp[2048]; + unsigned char oid_raw[64]; + size_t oid_len = snmp_oid_encode(oid, oid_raw, sizeof(oid_raw)); + size_t mlen; + int got = 0; + int attempt; + + if (oid_len == 0) + break; + mlen = snmp_build(msg, sizeof(msg), 1, community, + (unsigned long)getpid() + (unsigned long)step, + oid_raw, oid_len, 0xa1); + for (attempt = 0; attempt < 2 && !got; attempt++) { + struct pollfd pfd; + ssize_t r; + + if (sendto(fd, msg, mlen, 0, use->ai_addr, + use->ai_addrlen) < 0) + break; + pfd.fd = fd; + pfd.events = POLLIN; + pfd.revents = 0; + if (poll(&pfd, 1, 1800) <= 0) + continue; + r = recv(fd, resp, sizeof(resp), 0); + if (r > 0 && snmp_parse_varbind(resp, (size_t)r, next_oid, + sizeof(next_oid), value, + sizeof(value)) == 0) + got = 1; + } + if (!got) + break; + if (strncmp(next_oid, "1.3.6.1.2.1.1.", 14) != 0) + break; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + count++; + mcp_buf_puts(&b, "{\"oid\":"); + apex_json_str(&b, next_oid); + mcp_buf_puts(&b, ",\"name\":"); + apex_json_str(&b, snmp_sys_name(next_oid)); + mcp_buf_puts(&b, ",\"value\":"); + apex_json_str(&b, value); + mcp_buf_puts(&b, "}"); + snprintf(oid, sizeof(oid), "%.120s", next_oid); + } + if (count >= max_steps) + truncated = 1; + close(fd); + freeaddrinfo(res); + mcp_buf_printf(&b, "],\"count\":%d,\"truncated\":%s}", count, + truncated ? "true" : "false"); + apex_audit("snmp_walk", target, port, count > 0, + count > 0 ? "SNMP system group walked" : "no SNMP data", + community); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* -------------------------------------------------------------- ldap_search */ + +static size_t ldap_build_search(unsigned char *msg, size_t cap, int msgid, + const char *base, int scope, + const char *const *attrs, int nattrs) +{ + unsigned char inner[1024]; + unsigned char abuf[512]; + size_t n = 0; + size_t an = 0; + size_t bl = strlen(base); + size_t sr_len; + size_t ml; + int i; + + if (bl > 400) + bl = 400; + inner[n++] = 0x04; + inner[n++] = (unsigned char)bl; + memcpy(inner + n, base, bl); + n += bl; + inner[n++] = 0x02; + inner[n++] = 0x01; + inner[n++] = (unsigned char)scope; + inner[n++] = 0x02; + inner[n++] = 0x01; + inner[n++] = 0x00; + inner[n++] = 0x02; + inner[n++] = 0x01; + inner[n++] = 20; /* size limit */ + inner[n++] = 0x02; + inner[n++] = 0x01; + inner[n++] = 10; /* time limit */ + inner[n++] = 0x02; + inner[n++] = 0x01; + inner[n++] = 0x00; /* typesOnly */ + inner[n++] = 0x87; + inner[n++] = 0x0b; + memcpy(inner + n, "objectClass", 11); + n += 11; + for (i = 0; i < nattrs; i++) { + size_t l = strlen(attrs[i]); + + if (l > 60) + l = 60; + abuf[an++] = 0x04; + abuf[an++] = (unsigned char)l; + memcpy(abuf + an, attrs[i], l); + an += l; + } + { + unsigned char seq[512]; + size_t sl = ber_tlv(seq, 0x30, abuf, an); + + memcpy(inner + n, seq, sl); + n += sl; + } + { + unsigned char sr[1200]; + unsigned char mc[1280]; + size_t m = 0; + + sr_len = ber_tlv(sr, 0x60, inner, n); + mc[m++] = 0x02; + mc[m++] = 0x01; + mc[m++] = (unsigned char)msgid; + memcpy(mc + m, sr, sr_len); + m += sr_len; + ml = ber_tlv(msg, 0x30, mc, m); + } + return ml <= cap ? ml : 0; +} + +static void t_ldap_search(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *base_arg = mcp_arg_string(args, "base"); + int port = mcp_arg_int(args, "port", 389); + static const char *attrs[] = { "cn", "uid", "mail" }; + char base[512]; + char dn[512]; + ldap_attr entry_attrs[16]; + unsigned char resp[8192]; + size_t rlen; + int fd; + int bind_code = -1; + mcp_buf b; + int first = 1; + int entries = 0; + int truncated = 0; + int rounds; + + (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, "ldap_search", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the LDAP service"); + return; + } + { + static const unsigned char bind[] = { + 0x30, 0x07, 0x02, 0x01, 0x03, 0x04, 0x00, 0x80, 0x00 + }; + + if (write(fd, bind, sizeof(bind)) != (ssize_t)sizeof(bind)) { + close(fd); + mcp_reply_error(c, "cannot send the bind request"); + return; + } + } + if (ber_read(fd, resp, sizeof(resp), &rlen) < 0 || + !ldap_result_code(resp, rlen, &bind_code)) { + close(fd); + mcp_reply_error(c, "no LDAP bind response"); + return; + } + if (bind_code != 0) { + close(fd); + mcp_reply_error(c, "anonymous bind rejected"); + return; + } + base[0] = '\0'; + if (base_arg != NULL && *base_arg != '\0') { + snprintf(base, sizeof(base), "%.400s", base_arg); + } else { + unsigned char msg[2048]; + size_t ml = ldap_build_search(msg, sizeof(msg), 2, "", 0, + (const char *const *)NULL, 0); + + if (ml == 0 || write(fd, msg, ml) != (ssize_t)ml) { + close(fd); + mcp_reply_error(c, "cannot send the rootDSE search"); + return; + } + { + int rr; + + for (rr = 0; rr < 4; rr++) { + size_t off = 0; + unsigned char t; + const unsigned char *v; + size_t l; + int op; + + if (ber_read(fd, resp, sizeof(resp), &rlen) < 0) + break; + if (ber_next(resp, rlen, &off, &t, &v, &l) != 0 || + ber_next(resp, rlen, &off, &t, &v, &l) != 0) + break; + op = t; + if (op == 0x64) { + int k; + + ldap_parse_entry(v, l, entry_attrs, &k, NULL, 0); + for (k = 0; k < 16; k++) + if (strcmp(entry_attrs[k].name, + "namingContexts") == 0) { + snprintf(base, sizeof(base), "%.400s", + entry_attrs[k].value); + break; + } + } else if (op == 0x65) { + break; + } + } + if (base[0] == '\0') { + close(fd); + mcp_reply_error(c, "no rootDSE response"); + return; + } + } + if (base[0] == '\0') { + close(fd); + mcp_reply_error(c, "no namingContexts in the rootDSE"); + return; + } + } + { + unsigned char msg[2048]; + size_t ml = ldap_build_search(msg, sizeof(msg), 3, base, 2, + attrs, + (int)(sizeof(attrs) / sizeof(attrs[0]))); + + if (ml == 0 || write(fd, msg, ml) != (ssize_t)ml) { + close(fd); + mcp_reply_error(c, "cannot send the LDAP search"); + return; + } + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"base\":", port); + apex_json_str(&b, base); + mcp_buf_puts(&b, ",\"entries\":["); + for (rounds = 0; rounds < 30; rounds++) { + int tag = ber_read(fd, resp, sizeof(resp), &rlen); + + if (tag < 0) + break; + if (tag == 0x30 && rlen > 2) { + size_t off = 0; + unsigned char t; + const unsigned char *v; + size_t l; + + if (ber_next(resp, rlen, &off, &t, &v, &l) != 0 || + ber_next(resp, rlen, &off, &t, &v, &l) != 0) + break; + if (t == 0x65) + break; + if (t != 0x64) + continue; + dn[0] = '\0'; + { + int nattrs = 0; + int k; + int afirst = 1; + + ldap_parse_entry(v, l, entry_attrs, &nattrs, dn, + sizeof(dn)); + if (entries >= 20) { + truncated = 1; + break; + } + entries++; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"dn\":"); + apex_json_str(&b, dn); + mcp_buf_puts(&b, ",\"attributes\":["); + for (k = 0; k < nattrs; k++) { + if (!afirst) + mcp_buf_puts(&b, ","); + afirst = 0; + mcp_buf_puts(&b, "{\"name\":"); + apex_json_str(&b, entry_attrs[k].name); + mcp_buf_puts(&b, ",\"value\":"); + apex_json_str(&b, entry_attrs[k].value); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "]}"); + } + } + } + close(fd); + mcp_buf_printf(&b, "],\"entries_count\":%d,\"truncated\":%s,\"anonymous\":true}", + entries, truncated ? "true" : "false"); + apex_audit("ldap_search", target, port, 1, "anonymous subtree search", base); + 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 " @@ -3533,6 +4130,32 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 500\"}}," "\"required\":[\"target\"]}", t_ike_probe }, + { "snmp_walk", + "Walk the SNMP system group (1.3.6.1.2.1.1) with GETNEXT, up to max_steps " + "requests, decoding each returned OID and its value (string, integer, " + "timeticks, counter, IP address, OID). Reports sysDescr, sysObjectID, " + "sysUpTime, sysName and friends. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 161\"}," + "\"community\":{\"type\":\"string\",\"description\":\"default public\"}," + "\"max_steps\":{\"type\":\"integer\",\"description\":\"default 30, " + "max 100\"}}," + "\"required\":[\"target\"]}", + t_snmp_walk }, + { "ldap_search", + "Bind anonymously, resolve the namingContexts from the rootDSE when no " + "base is given, then run one subtree search (scope 2, size limit 20) for " + "present(objectClass) and collect the entry DNs with cn/uid/mail. Stops " + "after 20 entries or the searchResultDone. Gate: the target must be in " + "scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 389\"}," + "\"base\":{\"type\":\"string\",\"description\":\"optional base DN; " + "default from namingContexts\"}}," + "\"required\":[\"target\"]}", + t_ldap_search }, }; 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 a108b3e..8e8cd80 100644 --- a/src/tools_red.c +++ b/src/tools_red.c @@ -3055,6 +3055,140 @@ static void t_websocket_probe(mcp_conn *c, const mcp_json *args, void *user) free(resp); } +/* ---------------------------------------------------------- openapi_discovery */ + +static int openapi_path_count(const char *body) +{ + const char *p = strstr(body, "\"paths\""); + int depth; + int in_string = 0; + int esc = 0; + int count = 0; + + if (p == NULL) + return 0; + p = strchr(p, '{'); + if (p == NULL) + return 0; + p++; + depth = 1; + while (*p != '\0' && depth > 0) { + char c = *p++; + + if (in_string) { + if (esc) + esc = 0; + else if (c == '\\') + esc = 1; + else if (c == '"') { + in_string = 0; + if (depth == 1) { + const char *q = p; + + while (*q == ' ' || *q == '\t' || *q == '\n' || + *q == '\r') + q++; + if (*q == ':') + count++; + } + } + continue; + } + if (c == '"') + in_string = 1; + else if (c == '{') + depth++; + else if (c == '}') + depth--; + } + return count; +} + +static void t_openapi_discovery(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *paths[] = { + "/openapi.json", "/swagger.json", "/api-docs", "/v3/api-docs", + "/swagger/v1/swagger.json", "/api/openapi.json", NULL + }; + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 80); + int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port)); + mcp_buf b; + int first = 1; + int found = 0; + 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, "openapi_discovery", target, port)) + return; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"specs\":[", port); + for (i = 0; paths[i] != NULL; i++) { + char status[256]; + char *resp = NULL; + size_t len = 0; + char version[64]; + char title[128]; + int code; + int paths_found; + char *evidence; + + status[0] = '\0'; + if (apex_http_once(target, port, tls, "GET", paths[i], NULL, NULL, + 8000, &resp, &len, status, sizeof(status)) != 0) + continue; + code = apex_status_code(status); + if (code != 200 || resp == NULL || + (strstr(resp, "\"openapi\"") == NULL && + strstr(resp, "\"swagger\"") == NULL) || + strstr(resp, "\"paths\"") == NULL) { + free(resp); + continue; + } + version[0] = title[0] = '\0'; + json_field(resp, "openapi", version, sizeof(version)); + if (version[0] == '\0') + json_field(resp, "swagger", version, sizeof(version)); + json_field(resp, "title", title, sizeof(title)); + paths_found = openapi_path_count(resp); + evidence = apex_evidence_save("openapi", resp, len); + found++; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"path\":"); + apex_json_str(&b, paths[i]); + mcp_buf_puts(&b, ",\"version\":"); + apex_json_str(&b, version); + mcp_buf_puts(&b, ",\"title\":"); + apex_json_str(&b, title); + mcp_buf_printf(&b, ",\"paths\":%d,\"evidence\":", paths_found); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + free(evidence); + free(resp); + } + mcp_buf_printf(&b, "],\"count\":%d}", found); + apex_audit("openapi_discovery", target, port, found == 0, + found == 0 ? "no OpenAPI document" : "OpenAPI document exposed", + "spec paths"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + const mcp_tool TOOLS_RED[] = { { "vuln_check", "Non-destructive verification of exposed artifacts on one web target: " @@ -3330,6 +3464,16 @@ const mcp_tool TOOLS_RED[] = { "\"tls\":{\"type\":\"boolean\"}}," "\"required\":[\"target\"]}", t_websocket_probe }, + { "openapi_discovery", + "Request the usual OpenAPI/Swagger locations and report every document " + "that comes back (version, info title, number of paths) with the body as " + "evidence. Six GETs, no credentials. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 80\"}," + "\"tls\":{\"type\":\"boolean\"}}," + "\"required\":[\"target\"]}", + t_openapi_discovery }, }; 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 8ca21a3..b386c9c 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 = 108 +EXPECTED_TOOLS = 112 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 11b578e..99eec51 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("108 tools registered", len(tools) == 108, len(tools)) +check("112 tools registered", len(tools) == 112, 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"]) == 108) + check("http tools/list", len(listing["result"]["tools"]) == 112) 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 @@ -4978,6 +4978,191 @@ ike_sock.close() shutil.rmtree(fw_dir, ignore_errors=True) shutil.rmtree(net_home, ignore_errors=True) +print("\n== SNMP walk, LDAP search, OpenAPI and systemd ==") + + +def enc_oid(dotted): + parts = [int(x) for x in dotted.split(".")] + out = bytes([40 * parts[0] + parts[1]]) + for value in parts[2:]: + comp = [] + while value: + comp.append(value & 0x7f) + value >>= 7 + if not comp: + comp = [0] + comp = comp[::-1] + for i, b in enumerate(comp): + out += bytes([b | (0x80 if i < len(comp) - 1 else 0)]) + return out + + +def snmp_walk_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() + items = [ + ("1.3.6.1.2.1.1.1.0", 0x04, b"Test agent"), + ("1.3.6.1.2.1.1.2.0", 0x06, enc_oid("1.3.6.1.4.1.999")), + ("1.3.6.1.2.1.1.3.0", 0x43, struct.pack(">I", 12345)), + ("1.3.6.1.2.1.1.5.0", 0x04, b"router-1"), + ("1.3.6.1.2.1.2.0.0", 0x02, b"\x01"), + ] + state = {"n": 0} + + def loop(): + while not stop.is_set(): + try: + _data, addr = sock.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + oid, tag, value = items[min(state["n"], len(items) - 1)] + state["n"] += 1 + varbind = snmp_tlv(0x30, snmp_tlv(0x06, enc_oid(oid)) + + snmp_tlv(tag, value)) + vbl = snmp_tlv(0x30, varbind) + pdu = snmp_tlv(0xA2, b"\x02\x04\x00\x00\x00\x01" + + b"\x02\x01\x00" + b"\x02\x01\x00" + vbl) + resp = snmp_tlv(0x30, b"\x02\x01\x01" + + snmp_tlv(0x04, b"public") + pdu) + sock.sendto(resp, addr) + + threading.Thread(target=loop, daemon=True).start() + return sock, port, stop + + +def ldap_entry(dn, attrs): + body = ber_tlv(0x04, dn.encode()) + body += ber_tlv(0x30, b"".join(ldap_attribute(k, v) for k, v in attrs)) + return ber_tlv(0x30, b"\x02\x01\x03" + ber_tlv(0x64, body)) + + +def ldap_search_handler(conn): + ldap_read_message(conn) + conn.sendall(ber_tlv(0x30, b"\x02\x01\x01" + + ber_tlv(0x61, b"\x0a\x01\x00\x04\x00\x04\x00"))) + ldap_read_message(conn) + root = ber_tlv(0x30, b"\x02\x01\x02" + + ber_tlv(0x64, b"\x04\x00" + + ber_tlv(0x30, + ldap_attribute("namingContexts", + "dc=example,dc=test")))) + done = ber_tlv(0x30, b"\x02\x01\x02" + + ber_tlv(0x65, b"\x0a\x01\x00\x04\x00\x04\x00")) + conn.sendall(root + done) + ldap_read_message(conn) + e1 = ldap_entry("cn=alice,dc=example,dc=test", + [("cn", "alice"), ("mail", "alice@example.test")]) + e2 = ldap_entry("cn=bob,dc=example,dc=test", [("cn", "bob")]) + conn.sendall(e1 + e2 + done) + + +class _OpenApiHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + if urllib.parse.urlsplit(self.path).path == "/openapi.json": + doc = {"openapi": "3.0.3", "info": {"title": "Test API"}, + "paths": {"/users": {"get": {}}, + "/pets": {"post": {}}, + "/health": {"get": {}}}} + body = json.dumps(doc, separators=(",", ":")).encode() + code = 200 + else: + body = b"not found" + code = 404 + 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 + + +snmp_sock, snmp_walk_port, snmp_walk_stop = snmp_walk_agent() +ldap_srv2, ldap_search_port = start_line_server(ldap_search_handler) +openapi_srv = http.server.HTTPServer(("127.0.0.1", 0), _OpenApiHandler) +openapi_port = openapi_srv.server_address[1] +threading.Thread(target=openapi_srv.serve_forever, daemon=True).start() + +sd_root = tempfile.mkdtemp(prefix="apex-sd-") +sd_dir = os.path.join(sd_root, "etc", "systemd", "system") +os.makedirs(os.path.join(sd_dir, "multi-user.target.wants")) +with open(os.path.join(sd_dir, "evil.service"), "w") as f: + f.write("[Service]\nExecStart=/tmp/evil\n") +with open(os.path.join(sd_dir, "good.service"), "w") as f: + f.write("[Service]\nUser=app\nExecStart=/usr/bin/app\n") +world = os.path.join(sd_dir, "world.service") +with open(world, "w") as f: + f.write("[Service]\nUser=app\nExecStart=/usr/bin/world\n") +os.chmod(world, 0o666) +os.symlink("../evil.service", + os.path.join(sd_dir, "multi-user.target.wants", "evil.service")) + +deep_home2 = tempfile.mkdtemp(prefix="apex-deep2-") +write_scope(deep_home2, {"label": "deep2", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(snmp_walk_port), + str(ldap_search_port), + str(openapi_port)]}) +res, _ = run([ + call(1, "snmp_walk", target="127.0.0.1", port=snmp_walk_port, + community="public"), + call(2, "ldap_search", target="127.0.0.1", port=ldap_search_port), + call(3, "openapi_discovery", target="127.0.0.1", port=openapi_port, + tls=False), + call(4, "systemd_audit", root=sd_root), + call(5, "snmp_walk", target="198.51.100.9", port=161), +], home=deep_home2) +by_id = {r.get("id"): r for r in res} +walk = json.loads(text(by_id[1])) +entries = {e["name"]: e["value"] for e in walk["entries"]} +check("snmp_walk collects the system group", + walk["count"] == 4 and entries.get("sysDescr") == "Test agent" and + entries.get("sysName") == "router-1", walk) +check("snmp_walk decodes OIDs and timeticks", + entries.get("sysObjectID") == "1.3.6.1.4.1.999" and + entries.get("sysUpTime") == "12345", entries) +ldap2 = json.loads(text(by_id[2])) +dns = {e["dn"]: e for e in ldap2["entries"]} +check("ldap_search resolves the naming context and finds entries", + ldap2["base"] == "dc=example,dc=test" and + ldap2["entries_count"] == 2, ldap2) +check("ldap_search collects the entry attributes", + "cn=alice,dc=example,dc=test" in dns and + {a["name"]: a["value"] + for a in dns["cn=alice,dc=example,dc=test"]["attributes"]}.get("mail") + == "alice@example.test", ldap2) +oapi = json.loads(text(by_id[3])) +check("openapi_discovery finds the document", + oapi["count"] == 1 and oapi["specs"][0]["version"] == "3.0.3" and + oapi["specs"][0]["title"] == "Test API", oapi) +check("openapi_discovery counts the paths and keeps evidence", + oapi["specs"][0]["paths"] == 3 and + os.path.isfile(oapi["specs"][0]["evidence"]), oapi["specs"][0]) +sd = json.loads(text(by_id[4])) +kinds = [f["kind"] for f in sd["findings"]] +check("systemd_audit counts the units and want links", + sd["units"] == 3 and sd["enabled_links"] == 1, sd) +check("systemd_audit flags temp execution and root services", + kinds.count("exec-start-temp") == 1 and + kinds.count("runs-as-root") == 1, kinds) +check("systemd_audit flags a world-writable unit", + "world-writable-unit" in kinds, kinds) +check("snmp_walk refuses an out-of-scope target", err(by_id[5]), + text(by_id[5])) +snmp_walk_stop.set() +snmp_sock.close() +ldap_srv2.close() +openapi_srv.shutdown() +openapi_srv.server_close() +shutil.rmtree(sd_root, ignore_errors=True) +shutil.rmtree(deep_home2, 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"})