diff --git a/CHANGELOG.md b/CHANGELOG.md index df7aa91..16e4ede 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,31 @@ 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.5.0 — 2026-11-21 — this change +## 1.6.0 — 2026-11-21 — this change + +- **TLS** (`tls_audit`): four `openssl s_client` runs (TLS 1.0, 1.1, 1.2, + 1.3) plus one `-showcerts` run. Reports which versions negotiate, the cipher + each picks, flags TLS 1.0/1.1 and RC4/3DES/NULL/EXPORT/MD5 ciphers, and pulls + the first certificate through `openssl x509` for subject, issuer, validity + and DNS SANs. A failed handshake prints a session block too, so the tool keys + on `New, ..., Cipher is ...` and treats `(NONE)` as failure. +- **Redis** (`redis_probe`): one connection, PING; if it answers without AUTH, + also INFO and DBSIZE. Reports open access (audited), version, role, + connected clients and database size. It does not guess passwords. +- **SNMP** (`snmp_probe`): a hand-built SNMPv1/v2c GET for sysDescr.0 over UDP, + two attempts per community (default public, private; max 4); the raw answer + is saved as evidence. No net-snmp dependency. +- **DNS** (`dns_zone_transfer`): `dig AXFR` against one in-scope server for one + in-scope zone, with record counts per type, up to 200 raw records, the full + output as evidence, and explicit refused/unreachable reasons. +- Shared `gated_run()` helper: gate, audit, run and hand the output back, so + multi-command tools keep one gate call per command path. +- Tests with local fixtures: a Python TLS server with a generated certificate, + open and AUTH-required Redis servers, a UDP SNMP agent answering only + `public`, an AXFR server with SOA/NS/A records and a refusing variant, plus + the out-of-scope paths. 522 checks. Coverage 79.9%. + +## 1.5.0 — 2026-11-21 — b35500f - **Red, protocols** (`tools_proto.c`): `ftp_probe` reads the 220 banner, asks FEAT and tries the literal anonymous pair (USER anonymous / PASS diff --git a/README.md b/README.md index 08767f5..8b5c257 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. -**69 tools · 506 end-to-end checks · 340 fuzz cases · 79.8% line coverage · ~342 KiB** +**73 tools · 522 end-to-end checks · 340 fuzz cases · 79.9% line coverage · ~362 KiB** ``` $ ./apex-twin --check -{"version":"1.5.0","tools":69,...,"scope":{"loaded":true,...}} +{"version":"1.6.0","tools":73,...,"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 (69) +## Tools (73) ### Scope and bookkeeping @@ -257,6 +257,10 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `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 | +| `tls_audit` | TLS 1.0–1.3 probes, negotiated ciphers, weak-version/cipher flags, certificate subject/issuer/dates/SANs | +| `redis_probe` | PING/INFO/DBSIZE on one connection; reports open access, version, role, clients, dbsize | +| `snmp_probe` | Hand-built SNMPv1/v2c GET sysDescr.0 over UDP for up to four communities; raw answer as evidence | +| `dns_zone_transfer` | `dig AXFR` against one in-scope server and zone; record counts per type, raw records, evidence | ### Blue team @@ -456,6 +460,9 @@ The full threat model, trust boundaries and a hardening checklist are in | SSRF probe | 3 loopback variants, 1.2 s callback wait | | Service probes | One connection each; SMTP VRFY at most 8 users | | Persistence audit | 2000 files per call, 1 MiB per file, 100 findings | +| TLS audit | 4 protocol probes + 2 certificate runs per call | +| SNMP | 4 communities, 2 attempts each, 1.8 s wait | +| Zone transfer | one server, one in-scope zone, 30 s | --- @@ -466,7 +473,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 506 end-to-end checks +make test # version check + gate audit + 522 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 @@ -571,7 +578,8 @@ src/tools_traffic.c traffic_list / traffic_read src/tools_red.c vuln_check, subdomain_enum, cred_test src/tools_blue.c hardening_audit, log_audit, ioc_scan src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash -src/tools_proto.c ftp_probe, smtp_probe, ssh_audit +src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit, + redis_probe, snmp_probe, dns_zone_transfer src/sha256.c SHA-256/HMAC for integrity_baseline and jwt_audit src/tools_guard.c guard_check src/apex-twin.c MCP stdio + HTTP face, --check, --version @@ -601,7 +609,7 @@ examples/ scope.json ## Status -1.5.0. Built and run: 69 tools, 506 checks, 340 fuzz cases and 79.8% line +1.6.0. Built and run: 73 tools, 522 checks, 340 fuzz cases and 79.9% 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 @@ -624,8 +632,9 @@ keeps the gaps visible. wordlist path brute-forcing and access-log analysis; 1.3 added SSRF verification, detection-rule export, integrity baselines and firmware writing (confirm-gated); 1.4 added offline JWT/hash analysis, ATT&CK mapping and a -/proc snapshot; 1.5 added FTP/SMTP/SSH service probes and a persistence audit, -again without changing an existing tool or file format. +/proc snapshot; 1.5 added FTP/SMTP/SSH service probes and a persistence audit; +1.6 added TLS, Redis, SNMP and DNS zone-transfer checks, 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 d4a4c16..929842e 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.5.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.6.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. +- **TLS, Redis, SNMP and AXFR stay read-only.** `tls_audit` performs TLS + handshakes and reads the certificate; `redis_probe` sends PING, INFO and + DBSIZE only; `snmp_probe` sends a GET for sysDescr.0; `dns_zone_transfer` + asks one nameserver for one in-scope zone. No writes, no password guessing, + no payloads. - **Service probes are handshakes, not attacks.** `ftp_probe` tries only the literal anonymous FTP pair, `smtp_probe` sends EHLO and at most 8 VRFY commands, and `ssh_audit` reads one KEXINIT and never authenticates. Each diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index 941e64c..034befb 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.5.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.6.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -37,10 +37,11 @@ It is not an exploit framework: there is no shell, no exploit payload, no post\-exploitation, no C2 and no persistence. Besides reconnaissance and web testing it carries offensive verification (vuln_check, subdomain_enum, cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id, -ftp_probe, smtp_probe, ssh_audit), defensive audits (hardening_audit, -log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, -mitre_map, process_snapshot, persistence_audit) and ESP32 board tools -(esp_info, esp_monitor, esp_read_flash, esp_flash). +ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe, +dns_zone_transfer), defensive audits (hardening_audit, log_audit, ioc_scan, +web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, +persistence_audit) 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 47f931e..dc68a80 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.5.0" +#define APEX_VERSION "1.6.0" #define APEX_MAX_OUT (1u << 20) #define APEX_PATH_MAX 512 #define APEX_PATH_FULL 1024 diff --git a/src/tools.h b/src/tools.h index 7896ffc..fc6396a 100644 --- a/src/tools.h +++ b/src/tools.h @@ -13,6 +13,12 @@ int gated(mcp_conn *c, const char *tool, const char *target, int port); int gated_cmd(mcp_conn *c, const char *tool, const char *target, int port, char *const argv[], int timeout_ms, int *exit_code); +/* + * Gate, audit and run a command, handing the output back instead of replying. + * Returns 1 ran, 0 refused by the gate, -1 could not run, -2 dry run. + */ +int gated_run(const char *tool, const char *target, int port, + char *const argv[], int timeout_ms, apex_proc *p); int tcp_probe(const char *host, int port, int timeout_ms); int tcp_connect_host(const char *host, int port, int timeout_ms); diff --git a/src/tools_proto.c b/src/tools_proto.c index 98d9663..6a463fe 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -10,6 +10,9 @@ * on the service. Credentials in ftp_probe are the literal anonymous pair. */ #include +#include +#include +#include #include #include #include @@ -634,6 +637,1027 @@ static void t_ssh_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ---------------------------------------------------------------- tls_audit */ + +typedef struct { + const char *flag; + const char *label; +} tls_version_spec; + +static const tls_version_spec TLS_VERSIONS[] = { + { "-tls1", "TLSv1.0" }, + { "-tls1_1", "TLSv1.1" }, + { "-tls1_2", "TLSv1.2" }, + { "-tls1_3", "TLSv1.3" }, +}; + +static void tls_conn_string(const char *target, int port, char *out, size_t n) +{ + if (strchr(target, ':') != NULL && target[0] != '[') + snprintf(out, n, "[%s]:%d", target, port); + else + snprintf(out, n, "%s:%d", target, port); +} + +static void copy_token(const char *s, const char *end, char *out, size_t n) +{ + size_t w = 0; + + while (s < end && (*s == ' ' || *s == '\t')) + s++; + while (s < end && *s != ' ' && *s != '\t' && *s != '\r' && w + 1 < n) + out[w++] = *s++; + while (w > 0 && (out[w - 1] == ' ' || out[w - 1] == '\t')) + w--; + out[w] = '\0'; +} + +/* + * "New, TLSv1.2, Cipher is ECDHE-..." is the reliable line. A failed handshake + * prints "New, (NONE), Cipher is (NONE)" followed by a session block with + * "Protocol: TLSv1.3", so a bare Protocol match would be a false positive. + */ +static void tls_summary(const char *text, char *proto, size_t pn, + char *cipher, size_t cn) +{ + const char *p = text; + + proto[0] = '\0'; + cipher[0] = '\0'; + while (p != NULL && *p != '\0') { + const char *eol = strchr(p, '\n'); + size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p); + char line[512]; + char *cis; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + cis = strstr(line, "Cipher is "); + if (cis != NULL) { + copy_token(cis + 10, line + len, cipher, cn); + if (strncmp(line, "New, ", 5) == 0) { + char *start = line + 5; + char *comma = strchr(start, ','); + + copy_token(start, comma != NULL ? comma : line + len, + proto, pn); + } + if (strcmp(cipher, "(NONE)") == 0) { + proto[0] = '\0'; + cipher[0] = '\0'; + } + return; + } + p = eol != NULL ? eol + 1 : NULL; + } + /* -brief style fallback */ + { + const char *pp = strstr(text, "Protocol version:"); + const char *cp = strstr(text, "Cipher:"); + const char *eol; + + if (pp != NULL) { + pp += 17; + eol = strchr(pp, '\n'); + copy_token(pp, eol != NULL ? eol : pp + strlen(pp), proto, pn); + } + if (cp != NULL) { + cp += 7; + eol = strchr(cp, '\n'); + copy_token(cp, eol != NULL ? eol : cp + strlen(cp), cipher, cn); + } + } +} + +static int tls_probe_version(const char *target, const char *conn, int port, + const char *flag, char *proto, size_t pn, + char *cipher, size_t cn) +{ + char *argv[10]; + int i = 0; + apex_proc p; + int rc; + + (void)port; + argv[i++] = "openssl"; + argv[i++] = "s_client"; + argv[i++] = "-connect"; + argv[i++] = (char *)conn; + argv[i++] = "-servername"; + argv[i++] = (char *)target; + argv[i++] = (char *)flag; + argv[i] = NULL; + proto[0] = '\0'; + cipher[0] = '\0'; + rc = apex_run(argv, 15000, g_cfg.max_output, &p); + if (rc != 0) + return 0; + if (p.out != NULL) + tls_summary(p.out, proto, pn, cipher, cn); + apex_proc_free(&p); + return proto[0] != '\0'; +} + +static int extract_first_pem(const char *out, mcp_buf *pem) +{ + static const char begin_mark[] = "-----BEGIN CERTIFICATE-----"; + static const char end_mark[] = "-----END CERTIFICATE-----"; + const char *begin = strstr(out, begin_mark); + const char *end; + + if (begin == NULL) + return -1; + end = strstr(begin, end_mark); + if (end == NULL) + return -1; + end += strlen(end_mark); + mcp_buf_add(pem, begin, (size_t)(end - begin)); + mcp_buf_puts(pem, "\n"); + return 0; +} + +static void header_value(const char *text, const char *key, char *out, size_t n) +{ + const char *p = strstr(text, key); + size_t w = 0; + + out[0] = '\0'; + if (p == NULL) + return; + p += strlen(key); + while (*p == ' ' || *p == '\t') + p++; + while (*p != '\0' && *p != '\n' && *p != '\r' && w + 1 < n) + out[w++] = *p++; + while (w > 0 && (out[w - 1] == ' ' || out[w - 1] == '\t')) + w--; + out[w] = '\0'; +} + +static void t_tls_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + int port = mcp_arg_int(args, "port", 443); + char conn[320]; + char protos[4][64]; + char ciphers[4][128]; + int enabled[4]; + char weak[8][64]; + int nweak = 0; + char subject[256]; + char issuer[256]; + char not_before[128]; + char not_after[128]; + char sans[8][256]; + int nsans = 0; + int have_cert = 0; + char pem_path[APEX_PATH_FULL]; + mcp_buf pem; + mcp_buf b; + 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 (!apex_have("openssl")) { + mcp_reply_error(c, "openssl is not installed on this host"); + return; + } + if (!gated(c, "tls_audit", target, port)) + return; + tls_conn_string(target, port, conn, sizeof(conn)); + memset(enabled, 0, sizeof(enabled)); + for (i = 0; i < 4; i++) { + protos[i][0] = '\0'; + ciphers[i][0] = '\0'; + enabled[i] = tls_probe_version(target, conn, port, + TLS_VERSIONS[i].flag, + protos[i], sizeof(protos[i]), + ciphers[i], sizeof(ciphers[i])); + if (!enabled[i]) + snprintf(protos[i], sizeof(protos[i]), "%s", + TLS_VERSIONS[i].label); + } + /* weak protocols and broken ciphers */ + for (i = 0; i < 4; i++) { + if (!enabled[i]) + continue; + if (strcmp(TLS_VERSIONS[i].label, "TLSv1.0") == 0 || + strcmp(TLS_VERSIONS[i].label, "TLSv1.1") == 0) { + snprintf(weak[nweak], sizeof(weak[0]), "%s", + TLS_VERSIONS[i].label); + nweak++; + } + if (ciphers[i][0] != '\0' && + (strstr(ciphers[i], "RC4") != NULL || + strstr(ciphers[i], "3DES") != NULL || + strstr(ciphers[i], "DES-CBC") != NULL || + strstr(ciphers[i], "NULL") != NULL || + strstr(ciphers[i], "EXPORT") != NULL || + strstr(ciphers[i], "MD5") != NULL) && + nweak < 8) { + snprintf(weak[nweak], sizeof(weak[0]), "cipher:%.48s", + ciphers[i]); + nweak++; + } + } + + /* certificate: one -showcerts run, then x509 on the first PEM block */ + subject[0] = issuer[0] = not_before[0] = not_after[0] = '\0'; + mcp_buf_init(&pem); + { + char *argv[10]; + int k = 0; + apex_proc p; + + argv[k++] = "openssl"; + argv[k++] = "s_client"; + argv[k++] = "-connect"; + argv[k++] = conn; + argv[k++] = "-servername"; + argv[k++] = (char *)target; + argv[k++] = "-showcerts"; + argv[k] = NULL; + if (apex_run(argv, 20000, g_cfg.max_output, &p) == 0) { + if (p.out != NULL) + extract_first_pem(p.out, &pem); + apex_proc_free(&p); + } + } + if (pem.len > 0) { + char name[96]; + + snprintf(name, sizeof(name), "tls-%ld-%d.pem", (long)time(NULL), + (int)getpid()); + if (apex_path_join(pem_path, sizeof(pem_path), g_cfg.evidence_dir, + name) == 0 && + apex_write_file(pem_path, pem.p, pem.len, 0600) == 0) { + char *argv[10]; + int k = 0; + apex_proc p; + + argv[k++] = "openssl"; + argv[k++] = "x509"; + argv[k++] = "-in"; + argv[k++] = pem_path; + argv[k++] = "-noout"; + argv[k++] = "-subject"; + argv[k++] = "-issuer"; + argv[k++] = "-dates"; + argv[k++] = "-ext"; + argv[k++] = "subjectAltName"; + /* apex_run copies argv only for this call */ + { + char *xargv[12]; + int x; + + for (x = 0; x < k; x++) + xargv[x] = argv[x]; + xargv[x] = NULL; + if (apex_run(xargv, 10000, 65536, &p) == 0) { + if (p.out != NULL) { + header_value(p.out, "subject=", subject, + sizeof(subject)); + header_value(p.out, "issuer=", issuer, + sizeof(issuer)); + header_value(p.out, "notBefore=", + not_before, + sizeof(not_before)); + header_value(p.out, "notAfter=", not_after, + sizeof(not_after)); + have_cert = subject[0] != '\0'; + { + const char *dns = strstr(p.out, + "DNS:"); + + while (dns != NULL && nsans < 8) { + const char *end = dns + 4; + size_t w = 0; + + while (*end != '\0' && + *end != ',' && + *end != '\n' && + *end != '\r' && + w + 1 < + sizeof(sans[0])) + sans[nsans][w++] = *end++; + sans[nsans][w] = '\0'; + if (w > 0) + nsans++; + dns = strstr(end, "DNS:"); + } + } + } + apex_proc_free(&p); + } + } + unlink(pem_path); + } + } + mcp_buf_free(&pem); + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"protocols\":[", port); + for (i = 0; i < 4; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"version\":"); + apex_json_str(&b, TLS_VERSIONS[i].label); + mcp_buf_printf(&b, ",\"enabled\":%s,\"negotiated\":", + enabled[i] ? "true" : "false"); + apex_json_str(&b, enabled[i] ? protos[i] : ""); + mcp_buf_puts(&b, ",\"cipher\":"); + apex_json_str(&b, ciphers[i]); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "],\"enabled\":["); + { + int first = 1; + + for (i = 0; i < 4; i++) { + if (!enabled[i]) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + apex_json_str(&b, TLS_VERSIONS[i].label); + } + } + mcp_buf_puts(&b, "],\"weak\":["); + for (i = 0; i < nweak; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, weak[i]); + } + mcp_buf_puts(&b, "],\"certificate\":"); + if (have_cert) { + mcp_buf_puts(&b, "{\"subject\":"); + apex_json_str(&b, subject); + mcp_buf_puts(&b, ",\"issuer\":"); + apex_json_str(&b, issuer); + mcp_buf_puts(&b, ",\"not_before\":"); + apex_json_str(&b, not_before); + mcp_buf_puts(&b, ",\"not_after\":"); + apex_json_str(&b, not_after); + mcp_buf_puts(&b, ",\"sans\":["); + for (i = 0; i < nsans; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, sans[i]); + } + mcp_buf_puts(&b, "]}"); + } else { + mcp_buf_puts(&b, "null"); + } + mcp_buf_puts(&b, "}"); + apex_audit("tls_audit", target, port, nweak == 0, + nweak == 0 ? "no weak protocol or cipher" : "weak TLS settings", + have_cert ? subject : "no certificate"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* --------------------------------------------------------------- redis_probe */ + +static int redis_bulk(int fd, char *out, size_t n) +{ + char head[128]; + long len; + size_t off = 0; + + if (read_line(fd, head, sizeof(head)) < 0 || head[0] != '$') + return -1; + len = atol(head + 1); + if (len <= 0) + return -1; + if ((size_t)len >= n) + len = (long)(n - 1); + while (off < (size_t)len) { + ssize_t r = read(fd, out + off, (size_t)len - off); + + if (r < 0) { + if (errno == EINTR) + continue; + return -1; + } + if (r == 0) + break; + off += (size_t)r; + } + out[off] = '\0'; + /* the bulk payload is followed by CRLF; consume it before the next command */ + { + char crlf[2]; + + if (read(fd, crlf, 2) < 0) { + /* nothing to drain: the caller will read the next line anyway */ + } + } + return (int)off; +} + +static void redis_field(const char *info, const char *key, char *out, size_t n) +{ + const char *p = strstr(info, key); + + out[0] = '\0'; + if (p == NULL) + return; + p += strlen(key); + { + size_t w = 0; + + while (*p != '\0' && *p != '\r' && *p != '\n' && w + 1 < n) + out[w++] = *p++; + out[w] = '\0'; + } +} + +static void t_redis_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", 6379); + int fd; + char line[512]; + char info[65536]; + char version[64]; + char role[64]; + char clients[64]; + char os_name[128]; + int redis = 0; + int requires_auth = 0; + int ping_ok = 0; + long dbsize = -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 (!gated(c, "redis_probe", target, port)) + return; + fd = tcp_connect_host(target, port, 6000); + if (fd < 0) { + mcp_reply_error(c, "cannot connect to the Redis service"); + return; + } + info[0] = '\0'; + version[0] = role[0] = clients[0] = os_name[0] = '\0'; + if (write_all(fd, "PING\r\n") == 0 && + read_line(fd, line, sizeof(line)) >= 0) { + if (strncmp(line, "+PONG", 5) == 0) { + redis = 1; + ping_ok = 1; + } else if (strstr(line, "NOAUTH") != NULL || + strstr(line, "Authentication required") != NULL || + strstr(line, "invalid password") != NULL) { + redis = 1; + requires_auth = 1; + } + } + if (ping_ok && write_all(fd, "INFO\r\n") == 0) { + if (redis_bulk(fd, info, sizeof(info)) > 0) { + redis_field(info, "redis_version:", version, + sizeof(version)); + redis_field(info, "role:", role, sizeof(role)); + redis_field(info, "connected_clients:", clients, + sizeof(clients)); + redis_field(info, "os:", os_name, sizeof(os_name)); + } + } + if (ping_ok && write_all(fd, "DBSIZE\r\n") == 0 && + read_line(fd, line, sizeof(line)) >= 0 && line[0] == ':') + dbsize = atol(line + 1); + close(fd); + if (redis) { + apex_audit("redis_probe", target, port, !requires_auth, + requires_auth ? "authentication required" + : "unauthenticated access", + ping_ok ? "PING accepted" : "NOAUTH"); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"redis\":%s,\"requires_auth\":%s," + "\"ping\":%s,\"version\":", port, + redis ? "true" : "false", + requires_auth ? "true" : "false", + ping_ok ? "true" : "false"); + apex_json_str(&b, version); + mcp_buf_puts(&b, ",\"role\":"); + apex_json_str(&b, role); + mcp_buf_puts(&b, ",\"connected_clients\":"); + apex_json_str(&b, clients); + mcp_buf_puts(&b, ",\"os\":"); + apex_json_str(&b, os_name); + mcp_buf_printf(&b, ",\"dbsize\":%ld}", dbsize); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* --------------------------------------------------------------- snmp_probe */ + +static size_t ber_len(unsigned char *p, size_t n) +{ + if (n < 128) { + p[0] = (unsigned char)n; + return 1; + } + if (n < 256) { + p[0] = 0x81; + p[1] = (unsigned char)n; + return 2; + } + p[0] = 0x82; + p[1] = (unsigned char)(n >> 8); + p[2] = (unsigned char)n; + return 3; +} + +static size_t ber_tlv(unsigned char *out, unsigned char tag, + const unsigned char *val, size_t n) +{ + size_t l = ber_len(out + 1, n); + + out[0] = tag; + memcpy(out + 1 + l, val, n); + return 1 + l + n; +} + +/* SNMPv1/v2c GET sysDescr.0, assembled by hand (no net-snmp dependency). */ +static size_t snmp_build(unsigned char *msg, size_t cap, int version, + const char *community, unsigned long reqid) +{ + 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]; + size_t vc = 0; + size_t vb_len; + size_t vbl_len; + size_t pc = 0; + size_t pdu_len; + size_t mc = 0; + size_t c_len = strlen(community); + size_t ml; + + if (c_len > 64) + c_len = 64; + vc += ber_tlv(vb_c + vc, 0x06, oid, sizeof(oid)); + vb_c[vc++] = 0x05; + vb_c[vc++] = 0x00; + vb_len = ber_tlv(vb, 0x30, vb_c, vc); + vbl_len = ber_tlv(vbl, 0x30, vb, vb_len); + pdu_c[pc++] = 0x02; + pdu_c[pc++] = 0x04; + pdu_c[pc++] = (unsigned char)(reqid >> 24); + pdu_c[pc++] = (unsigned char)(reqid >> 16); + pdu_c[pc++] = (unsigned char)(reqid >> 8); + pdu_c[pc++] = (unsigned char)reqid; + pdu_c[pc++] = 0x02; + pdu_c[pc++] = 0x01; + pdu_c[pc++] = 0x00; + pdu_c[pc++] = 0x02; + pdu_c[pc++] = 0x01; + pdu_c[pc++] = 0x00; + memcpy(pdu_c + pc, vbl, vbl_len); + pc += vbl_len; + pdu_len = ber_tlv(pdu, 0xa0, pdu_c, pc); + msg_c[mc++] = 0x02; + msg_c[mc++] = 0x01; + msg_c[mc++] = (unsigned char)(version == 0 ? 0 : 1); + msg_c[mc++] = 0x04; + msg_c[mc++] = (unsigned char)c_len; + memcpy(msg_c + mc, community, c_len); + mc += c_len; + memcpy(msg_c + mc, pdu, pdu_len); + mc += pdu_len; + ml = ber_tlv(msg, 0x30, msg_c, mc); + if (ml > cap) + return 0; + return ml; +} + +/* Walk the response for the sysDescr OID and take the OctetString after it. */ +static int snmp_sysdescr(const unsigned char *buf, size_t n, char *out, size_t on) +{ + static const unsigned char oid[] = { + 0x2b, 0x06, 0x01, 0x02, 0x01, 0x01, 0x01, 0x00 + }; + size_t i; + + out[0] = '\0'; + if (n < 4 || buf[0] != 0x30) + return 0; + for (i = 0; i + sizeof(oid) + 2 <= n; i++) { + size_t j; + size_t len; + + if (memcmp(buf + i, oid, sizeof(oid)) != 0) + continue; + j = i + sizeof(oid); + if (buf[j] != 0x04) + continue; + j++; + len = buf[j++]; + if ((len & 0x80) != 0) { + size_t k = len & 0x7f; + size_t v = 0; + size_t m; + + if (k == 0 || k > 2 || j + k > n) + continue; + for (m = 0; m < k; m++) + v = (v << 8) | buf[j++]; + len = v; + } + if (j + len > n) + continue; + { + size_t w = 0; + size_t q; + + for (q = 0; q < len && w + 1 < on; q++) { + unsigned char ch = buf[j + q]; + + out[w++] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : ' '; + } + out[w] = '\0'; + } + return 1; + } + return 0; +} + +static void t_snmp_probe(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *communities_arg = mcp_arg_string(args, "communities"); + int port = mcp_arg_int(args, "port", 161); + char communities[4][64]; + int ncomm = 2; + struct addrinfo hints; + struct addrinfo *res = NULL; + struct addrinfo *use = NULL; + struct addrinfo *rp; + char service[16]; + int fd = -1; + mcp_buf b; + int first = 1; + int responded_any = 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; + } + snprintf(communities[0], sizeof(communities[0]), "%s", "public"); + snprintf(communities[1], sizeof(communities[1]), "%s", "private"); + if (communities_arg != NULL && *communities_arg != '\0') { + char *copy = strdup(communities_arg); + char *save = NULL; + char *tok; + + if (copy == NULL) { + mcp_reply_error(c, "out of memory"); + return; + } + ncomm = 0; + tok = strtok_r(copy, ",", &save); + while (tok != NULL && ncomm < 4) { + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok != '\0') { + snprintf(communities[ncomm], sizeof(communities[0]), + "%.48s", tok); + ncomm++; + } + tok = strtok_r(NULL, ",", &save); + } + free(copy); + } + if (ncomm == 0) { + mcp_reply_error(c, "no community string given"); + return; + } + if (!gated(c, "snmp_probe", 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; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"communities\":[", port); + 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()); + char sysdescr[1024]; + int responded = 0; + int attempt; + + sysdescr[0] = '\0'; + for (attempt = 0; attempt < 2 && !responded && mlen > 0; 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_sysdescr(resp, (size_t)r, sysdescr, + sizeof(sysdescr))) { + responded = 1; + responded_any = 1; + apex_evidence_save("snmp", (const char *)resp, + (size_t)r); + } + } + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"community\":"); + apex_json_str(&b, communities[i]); + mcp_buf_printf(&b, ",\"responded\":%s,\"sys_descr\":", + responded ? "true" : "false"); + apex_json_str(&b, sysdescr); + mcp_buf_puts(&b, "}"); + } + close(fd); + freeaddrinfo(res); + mcp_buf_printf(&b, "],\"responded\":%s}", + responded_any ? "true" : "false"); + apex_audit("snmp_probe", target, port, !responded_any, + responded_any ? "SNMP answered" : "no SNMP answer", + "v2c GET sysDescr.0"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* --------------------------------------------------------- dns_zone_transfer */ + +static int zone_name_ok(const char *zone) +{ + size_t i; + size_t n; + + if (zone == NULL || *zone == '\0') + return 0; + n = strlen(zone); + if (n > 253 || zone[0] == '.' || zone[n - 1] == '.') + return 0; + if (strstr(zone, "..") != NULL) + return 0; + for (i = 0; i < n; i++) { + unsigned char ch = (unsigned char)zone[i]; + + if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || ch == '-' || ch == '.' || + ch == '_')) + return 0; + } + return 1; +} + +static void t_dns_zone_transfer(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *server = mcp_arg_string(args, "server"); + const char *zone = mcp_arg_string(args, "zone"); + int port = mcp_arg_int(args, "port", 53); + int limit = mcp_arg_int(args, "limit", 500); + char portstr[16]; + char reason[512]; + char *argv[10]; + int i = 0; + apex_proc p; + int rc; + mcp_buf b; + mcp_buf records; + char type_names[16][24]; + int type_counts[16]; + int ntypes = 0; + int count = 0; + int emitted = 0; + int truncated = 0; + char *copy = NULL; + char *save = NULL; + char *line; + char *evidence = NULL; + + (void)user; + if (server == NULL || *server == '\0' || zone == NULL || *zone == '\0') { + mcp_reply_error(c, "server and zone are required"); + return; + } + if (!zone_name_ok(zone)) { + mcp_reply_error(c, "zone is not a plain domain name"); + return; + } + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port out of range"); + return; + } + if (limit <= 0 || limit > 5000) + limit = 500; + if (!apex_have("dig")) { + mcp_reply_error(c, "dig is not installed on this host"); + return; + } + if (!apex_scope_check(server, port, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + if (!apex_scope_check(zone, 0, reason, sizeof(reason))) { + mcp_buf_init(&b); + mcp_buf_printf(&b, "zone is outside the scope: %s", reason); + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + snprintf(portstr, sizeof(portstr), "%d", port); + argv[i++] = "dig"; + argv[i++] = "-p"; + argv[i++] = portstr; + argv[i++] = "+time=5"; + argv[i++] = "+tries=1"; + { + static char at_server[320]; + + snprintf(at_server, sizeof(at_server), "@%.240s", server); + argv[i++] = at_server; + } + argv[i++] = (char *)zone; + argv[i++] = "AXFR"; + argv[i] = NULL; + rc = gated_run("dns_zone_transfer", server, port, argv, 30000, &p); + if (rc != 1) { + mcp_reply_error(c, rc == -2 ? "dry run" : "cannot run dig"); + return; + } + mcp_buf_init(&records); + memset(type_names, 0, sizeof(type_names)); + memset(type_counts, 0, sizeof(type_counts)); + if (p.out != NULL) { + copy = strdup(p.out); + if (copy != NULL) { + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *fields[6] = { NULL, NULL, NULL, NULL, NULL, NULL }; + int nf = 0; + char *tok; + char *fsave = NULL; + char *dup; + int k; + + if (line[0] != ';' && line[0] != '\0') { + dup = strdup(line); + if (dup == NULL) + break; + tok = strtok_r(dup, " \t", &fsave); + while (tok != NULL && nf < 6) { + fields[nf++] = tok; + tok = strtok_r(NULL, " \t", &fsave); + } + if (nf >= 4 && fields[2] != NULL && + fields[3] != NULL && + strcasecmp(fields[2], "IN") == 0) { + count++; + for (k = 0; k < ntypes; k++) + if (strcasecmp(type_names[k], + fields[3]) == 0) + break; + if (k == ntypes && ntypes < 16) { + snprintf(type_names[ntypes], + sizeof(type_names[0]), + "%.20s", fields[3]); + type_counts[ntypes] = 0; + ntypes++; + } + if (k < ntypes) + type_counts[k]++; + if (emitted < limit && emitted < 200) { + if (emitted > 0) + mcp_buf_puts(&records, ","); + apex_json_str(&records, line); + emitted++; + } else { + truncated = 1; + } + } + free(dup); + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); + } + } + if (count > 0 && p.out != NULL) { + char label[128]; + + snprintf(label, sizeof(label), "axfr-%.60s", zone); + evidence = apex_evidence_save(label, p.out, p.out_len); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"server\":"); + apex_json_str(&b, server); + mcp_buf_puts(&b, ",\"zone\":"); + apex_json_str(&b, zone); + mcp_buf_printf(&b, ",\"port\":%d,\"success\":%s,\"records_count\":%d," + "\"truncated\":%s,\"types\":[", port, + count > 0 ? "true" : "false", count, + truncated ? "true" : "false"); + { + int k; + + for (k = 0; k < ntypes; k++) { + if (k > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"type\":"); + apex_json_str(&b, type_names[k]); + mcp_buf_printf(&b, ",\"count\":%d}", type_counts[k]); + } + } + mcp_buf_puts(&b, "],\"records\":["); + if (records.p != NULL) + mcp_buf_add(&b, records.p, records.len); + mcp_buf_puts(&b, "],\"reason\":"); + if (count > 0) + mcp_buf_puts(&b, "\"transfer succeeded\""); + else if (p.out != NULL && strstr(p.out, "Transfer failed") != NULL) + mcp_buf_puts(&b, "\"transfer refused\""); + else if (p.out != NULL && + (strstr(p.out, "connection timed out") != NULL || + strstr(p.out, "no servers could be reached") != NULL)) + mcp_buf_puts(&b, "\"server unreachable\""); + else + mcp_buf_puts(&b, "\"no records returned\""); + mcp_buf_puts(&b, ",\"evidence\":"); + if (evidence != NULL) + apex_json_str(&b, evidence); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, "}"); + apex_audit("dns_zone_transfer", server, port, count > 0, + count > 0 ? "AXFR succeeded" : "AXFR refused or empty", zone); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&records); + free(evidence); + apex_proc_free(&p); +} + const mcp_tool TOOLS_PROTO[] = { { "ftp_probe", "One-connection FTP check: read the 220 banner, ask FEAT, then try the " @@ -670,6 +1694,55 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 22\"}}," "\"required\":[\"target\"]}", t_ssh_audit }, + { "tls_audit", + "Probe one TLS endpoint four times (TLS 1.0, 1.1, 1.2, 1.3) with " + "openssl s_client, report which versions negotiate, the cipher each one " + "picks, and flag TLS 1.0/1.1 and RC4/3DES/NULL/EXPORT/MD5 ciphers. Pull " + "the server certificate and report subject, issuer, validity dates and " + "DNS SANs. Read-only; many handshakes, no authentication. Gate: the " + "target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}}," + "\"required\":[\"target\"]}", + t_tls_audit }, + { "redis_probe", + "One Redis connection: PING, and when it answers without authentication " + "also INFO and DBSIZE. Reports whether Redis answered, whether it wants " + "AUTH, the version, role, connected clients, OS string and database " + "size. No writes and no password guessing. Gate: the target must be in " + "scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 6379\"}}," + "\"required\":[\"target\"]}", + t_redis_probe }, + { "snmp_probe", + "Send an SNMPv1/v2c GET for sysDescr.0 over UDP with every community " + "string you give (default public, private; max 4), two attempts each. " + "Reports which community was answered and the sysDescr text, and saves " + "the raw response as evidence. Hand-built BER, no net-snmp needed. Gate: " + "the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 161\"}," + "\"communities\":{\"type\":\"string\",\"description\":\"comma list, " + "max 4\"}}," + "\"required\":[\"target\"]}", + t_snmp_probe }, + { "dns_zone_transfer", + "Try a DNS zone transfer: dig AXFR against one in-scope server for one " + "zone that is also in scope. Reports success, the record count per type, " + "up to 200 raw records and saves the whole output as evidence. Refusal, " + "timeout and empty answers are reported as such. Gate: server and zone.", + "{\"type\":\"object\",\"properties\":{" + "\"server\":{\"type\":\"string\",\"description\":\"nameserver in scope\"}," + "\"zone\":{\"type\":\"string\",\"description\":\"zone in scope\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 53\"}," + "\"limit\":{\"type\":\"integer\",\"description\":\"records to " + "return, default 500\"}}," + "\"required\":[\"server\",\"zone\"]}", + t_dns_zone_transfer }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/src/tools_recon.c b/src/tools_recon.c index fb4e5f1..9df1ff7 100644 --- a/src/tools_recon.c +++ b/src/tools_recon.c @@ -112,6 +112,24 @@ int gated_cmd(mcp_conn *c, const char *tool, const char *target, int port, return 1; } +int gated_run(const char *tool, const char *target, int port, + char *const argv[], int timeout_ms, apex_proc *p) +{ + char reason[512]; + int ok = apex_scope_check(target, port, reason, sizeof(reason)); + char *cmd = apex_join_argv(argv); + int rc; + + apex_audit(tool, target, port, ok, reason, cmd); + free(cmd); + if (!ok) + return 0; + if (g_cfg.dry_run) + return -2; + rc = apex_run(argv, timeout_ms, g_cfg.max_output, p); + return rc == 0 ? 1 : -1; +} + /* A plain TCP connect with a millisecond budget. Returns 0 open, -1 closed. */ int tcp_probe(const char *host, int port, int timeout_ms) { diff --git a/tests/gate_audit.py b/tests/gate_audit.py index fba6f3d..55b6cfe 100755 --- a/tests/gate_audit.py +++ b/tests/gate_audit.py @@ -21,8 +21,8 @@ import re import sys HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -EXPECTED_TOOLS = 69 -GATE = ("gated(", "gated_cmd(", "apex_scope_check(") +EXPECTED_TOOLS = 73 +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. RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown", diff --git a/tests/run.py b/tests/run.py index ebd7614..8e141d2 100755 --- a/tests/run.py +++ b/tests/run.py @@ -18,6 +18,7 @@ import select import shutil import signal import socket +import ssl import struct import subprocess import sys @@ -133,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("69 tools registered", len(tools) == 69, len(tools)) +check("73 tools registered", len(tools) == 73, 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", @@ -1559,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"]) == 69) + check("http tools/list", len(listing["result"]["tools"]) == 73) 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 @@ -3243,6 +3244,284 @@ empty = json.loads(text(by_id[2])) check("persistence_audit survives a missing root", empty["files_scanned"] == 0 and empty["findings_count"] == 0, empty) shutil.rmtree(persist_root, ignore_errors=True) + +print("\n== tls, redis, snmp and zone transfer ==") + + +def tls_server(cert, key): + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ctx.load_cert_chain(cert, key) + ctx.set_ciphers("ALL:@SECLEVEL=0") + srv = socket.socket() + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(8) + port = srv.getsockname()[1] + + def loop(): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + try: + tls = ctx.wrap_socket(conn, server_side=True) + try: + tls.recv(1) + except OSError: + pass + tls.close() + except (ssl.SSLError, OSError): + conn.close() + + threading.Thread(target=loop, daemon=True).start() + return srv, port + + +def redis_handler(require_auth): + def handle(conn): + f = conn.makefile("rb") + while True: + line = f.readline() + if not line: + return + cmd = line.strip().upper() + if cmd == b"PING": + conn.sendall(b"-NOAUTH Authentication required.\r\n" + if require_auth else b"+PONG\r\n") + elif cmd == b"INFO": + if require_auth: + conn.sendall(b"-NOAUTH Authentication required.\r\n") + continue + info = (b"# Server\r\nredis_version:7.2.4\r\n" + b"os:Linux 6.1 x86_64\r\n# Clients\r\n" + b"connected_clients:3\r\n# Replication\r\n" + b"role:master\r\n") + conn.sendall(b"$" + str(len(info)).encode() + b"\r\n" + + info + b"\r\n") + elif cmd == b"DBSIZE": + conn.sendall(b"-NOAUTH Authentication required.\r\n" + if require_auth else b":5\r\n") + else: + conn.sendall(b"-ERR unknown command\r\n") + return handle + + +def snmp_tlv(tag, value): + return bytes([tag, len(value)]) + value + + +def snmp_agent(allow_community): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.bind(("127.0.0.1", 0)) + s.settimeout(0.2) + port = s.getsockname()[1] + stop = threading.Event() + + def loop(): + while not stop.is_set(): + try: + data, addr = s.recvfrom(2048) + except socket.timeout: + continue + except OSError: + return + if len(data) < 9 or data[5] != 0x04: + continue + clen = data[6] + community = data[7:7 + clen] + if community != allow_community: + continue + oid = bytes([0x2b, 6, 1, 2, 1, 1, 1, 0]) + varbind = snmp_tlv(0x30, snmp_tlv(0x06, oid) + + snmp_tlv(0x04, b"Test SNMP agent 1.0")) + 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, community) + pdu) + s.sendto(resp, addr) + + threading.Thread(target=loop, daemon=True).start() + return s, port, stop + + +def dns_name_decode(msg, off): + labels = [] + while msg[off] != 0: + n = msg[off] + off += 1 + labels.append(msg[off:off + n].decode("ascii", "replace")) + off += n + return ".".join(labels), off + 1 + + +def dns_name_encode(name): + out = b"" + for label in name.rstrip(".").split("."): + out += bytes([len(label)]) + label.encode() + return out + b"\x00" + + +def dns_axfr_server(refuse): + srv = socket.socket() + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(4) + port = srv.getsockname()[1] + + def loop(): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + try: + head = conn.recv(2) + if len(head) < 2: + continue + need = struct.unpack(">H", head)[0] + msg = b"" + while len(msg) < need: + chunk = conn.recv(need - len(msg)) + if not chunk: + break + msg += chunk + if len(msg) < 12: + continue + tid = msg[:2] + name, off = dns_name_decode(msg, 12) + question = msg[12:off + 4] + if refuse: + resp = (tid + struct.pack(">HHHHH", 0x8405, 1, 0, 0, 0) + + question) + else: + ptr = b"\xc0\x0c" + soa = (dns_name_encode("ns1." + name) + + dns_name_encode("hostmaster." + name) + + struct.pack(">IIIII", 2026112101, 3600, 600, + 86400, 300)) + + def rr(owner, rtype, rdata): + return (owner + struct.pack(">HHIH", rtype, 1, 3600, + len(rdata)) + rdata) + + answers = [ + rr(ptr, 6, soa), + rr(ptr, 2, dns_name_encode("ns1." + name)), + rr(dns_name_encode("ns1." + name), 1, + socket.inet_aton("127.0.0.1")), + rr(ptr, 6, soa), + ] + resp = (tid + struct.pack(">HHHHH", 0x8400, 1, + len(answers), 0, 0) + + question + b"".join(answers)) + conn.sendall(struct.pack(">H", len(resp)) + resp) + finally: + conn.close() + + threading.Thread(target=loop, daemon=True).start() + return srv, port + + +tls_dir = tempfile.mkdtemp(prefix="apex-tls-") +tls_cert = os.path.join(tls_dir, "cert.pem") +tls_key = os.path.join(tls_dir, "key.pem") +subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", tls_key, "-out", tls_cert, "-days", "2", + "-subj", "/CN=localhost", + "-addext", "subjectAltName=DNS:localhost"], + check=True, capture_output=True) +tls_srv, tls_port = tls_server(tls_cert, tls_key) +redis_srv, redis_port = start_line_server(redis_handler(False)) +redis_auth_srv, redis_auth_port = start_line_server(redis_handler(True)) +snmp_sock, snmp_port, snmp_stop = snmp_agent(b"public") +dns_srv, dns_port = dns_axfr_server(False) +dns_refuse_srv, dns_refuse_port = dns_axfr_server(True) + +deep_home = tempfile.mkdtemp(prefix="apex-deep-") +write_scope(deep_home, {"label": "deep", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, + "allow_ip": ["127.0.0.1"], + "allow_domain": ["example.test"], + "allow_port": [str(tls_port), str(redis_port), + str(redis_auth_port), str(snmp_port), + str(dns_port), str(dns_refuse_port)]}) +res, _ = run([ + call(1, "tls_audit", target="127.0.0.1", port=tls_port), + call(2, "redis_probe", target="127.0.0.1", port=redis_port), + call(3, "redis_probe", target="127.0.0.1", port=redis_auth_port), + call(4, "snmp_probe", target="127.0.0.1", port=snmp_port, + communities="public"), + call(5, "snmp_probe", target="127.0.0.1", port=snmp_port, + communities="private"), + call(6, "dns_zone_transfer", server="127.0.0.1", port=dns_port, + zone="example.test"), + call(7, "dns_zone_transfer", server="127.0.0.1", port=dns_refuse_port, + zone="example.test"), + call(8, "dns_zone_transfer", server="127.0.0.1", port=dns_port, + zone="other.invalid"), + call(9, "tls_audit", target="198.51.100.9", port=443), +], home=deep_home) +by_id = {r.get("id"): r for r in res} +tls = json.loads(text(by_id[1])) +versions = {p["version"]: p for p in tls["protocols"]} +check("tls_audit probes all four protocol versions", len(versions) == 4, tls) +check("tls_audit finds the modern protocols", + versions["TLSv1.2"]["enabled"] and versions["TLSv1.3"]["enabled"], tls) +check("tls_audit names the negotiated cipher", + versions["TLSv1.2"]["cipher"].startswith("ECDHE-") or + versions["TLSv1.3"]["cipher"].startswith("TLS_"), tls) +weak = set(tls["weak"]) +check("tls_audit flags every weak protocol it can negotiate", + all(p["version"] in weak for p in tls["protocols"] + if p["enabled"] and p["version"] in ("TLSv1.0", "TLSv1.1")), tls) +cert = tls["certificate"] +check("tls_audit extracts the certificate", + cert is not None and "localhost" in cert["subject"] and + cert["not_after"] != "" and "localhost" in cert["sans"], cert) +redis = json.loads(text(by_id[2])) +check("redis_probe reports an open instance", + redis["redis"] is True and redis["requires_auth"] is False and + redis["ping"] is True, redis) +check("redis_probe reads version, role, clients and size", + redis["version"] == "7.2.4" and redis["role"] == "master" and + redis["connected_clients"] == "3" and redis["dbsize"] == 5, redis) +redis_auth = json.loads(text(by_id[3])) +check("redis_probe recognises an instance that wants AUTH", + redis_auth["redis"] is True and redis_auth["requires_auth"] is True and + redis_auth["ping"] is False, redis_auth) +snmp_ok = json.loads(text(by_id[4])) +check("snmp_probe accepts the public community", + snmp_ok["responded"] is True and + "Test SNMP agent" in snmp_ok["communities"][0]["sys_descr"], snmp_ok) +snmp_no = json.loads(text(by_id[5])) +check("snmp_probe reports a community that is ignored", + snmp_no["responded"] is False, snmp_no) +axfr = json.loads(text(by_id[6])) +types = {t["type"]: t["count"] for t in axfr["types"]} +check("dns_zone_transfer succeeds against the fixture", + axfr["success"] is True and axfr["records_count"] == 4, axfr) +check("dns_zone_transfer counts the records per type", + types == {"SOA": 2, "NS": 1, "A": 1}, types) +check("dns_zone_transfer returns the records and evidence", + len(axfr["records"]) == 4 and axfr["evidence"] and + os.path.isfile(axfr["evidence"]), axfr) +axfr_no = json.loads(text(by_id[7])) +check("dns_zone_transfer reports a refused transfer", + axfr_no["success"] is False and axfr_no["reason"] == "transfer refused", + axfr_no) +check("dns_zone_transfer refuses a zone outside the scope", err(by_id[8]), + text(by_id[8])) +check("tls_audit refuses an out-of-scope target", err(by_id[9]), + text(by_id[9])) + +for srv in (tls_srv, redis_srv, redis_auth_srv, dns_srv, dns_refuse_srv): + srv.close() +snmp_stop.set() +snmp_sock.close() +shutil.rmtree(tls_dir, ignore_errors=True) +shutil.rmtree(deep_home, ignore_errors=True) shutil.rmtree(proto_home, ignore_errors=True) print("\n== esp32 tools ==")