From 1a5a7bcc3d47e996b242cc0eb138917931931dbd Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 20:33:36 +0000 Subject: [PATCH] apex-twin 1.32.0: PostgreSQL, Exim and Elasticsearch audits, OCSP probe Blue: - postgresql_config_audit: /etc/postgresql// (root prefix) postgresql.conf and pg_hba.conf: listen_addresses on every interface, ssl = off, trust and md5/password entries, world-writable files. - exim_audit: exim4.conf/exim.conf and conf.d: relay_from_hosts covering every host, an accept rule for any host, an empty or missing tls_advertise_hosts and world-writable files. - elasticsearch_config_audit: elasticsearch.yml: network.host on every interface, xpack.security.enabled false, single-node discovery and a world-writable config. Red: - tls_ocsp_probe: one openssl s_client -status handshake; reports stapled or not, the OCSP response status and the certificate status (good/revoked/ unknown), plus protocol and cipher. conf_value now also strips single quotes (PostgreSQL writes listen_addresses as '*'), and the 36-tool table is unchanged at 192 slots. Tests with vulnerable and hardened PostgreSQL, Exim and Elasticsearch trees plus a TLS server without stapling. 830 checks, ASan suite green, analyze clean, release-check green including distcheck 1.32.0. --- CHANGELOG.md | 22 +- README.md | 18 +- SECURITY.md | 5 +- docs/apex-twin.1 | 7 +- src/apex.h | 2 +- src/tools_blue.c | 583 +++++++++++++++++++++++++++++++++++++++++++- src/tools_proto.c | 109 +++++++++ tests/gate_audit.py | 2 +- tests/run.py | 139 ++++++++++- 9 files changed, 871 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 924b287..92e9b8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,27 @@ 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.31.0 — 2026-11-21 — this change +## 1.32.0 — 2026-11-21 — this change + +- **PostgreSQL** (`postgresql_config_audit`): scans /etc/postgresql// + (root prefix) for postgresql.conf and pg_hba.conf: listen_addresses + on every interface, ssl = off, trust and md5/password entries, world-writable + files. +- **Exim** (`exim_audit`): exim4.conf/exim.conf and conf.d: relay_from_hosts + covering every host, an accept rule for any host, an empty or missing + tls_advertise_hosts and world-writable files. +- **Elasticsearch** (`elasticsearch_config_audit`): elasticsearch.yml: + network.host on every interface, xpack.security.enabled false, single-node + discovery and a world-writable config. +- **OCSP** (`tls_ocsp_probe`): one `openssl s_client -status` handshake; + reports whether a response is stapled, its response status and the + certificate status (good/revoked/unknown), plus protocol and cipher. +- conf_value now also strips single quotes, which PostgreSQL writes around + listen_addresses. +- Tests with vulnerable and hardened PostgreSQL, Exim and Elasticsearch trees + plus a TLS server without stapling. 830 checks. Coverage 81.2%. + +## 1.31.0 — 2026-11-21 — 409c80f - **PHP** (`php_config_audit`): finds /etc/php.ini or /etc/php/*/*/php.ini (root prefix) and flags expose_php, display_errors, allow_url_include, diff --git a/README.md b/README.md index 883cc6b..5ffa5ca 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. -**163 tools · 817 end-to-end checks · 340 fuzz cases · 81.3% line coverage · ~660 KiB** +**167 tools · 830 end-to-end checks · 340 fuzz cases · 81.2% line coverage · ~672 KiB** ``` $ ./apex-twin --check -{"version":"1.31.0","tools":163,...,"scope":{"loaded":true,...}} +{"version":"1.32.0","tools":167,...,"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 (163) +## Tools (167) ### Scope and bookkeeping @@ -295,6 +295,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `winrm_probe` | GET /wsman: 401/405 with Negotiate/NTLM/Kerberos identifies WinRM; evidence on hit | | `dnssec_check` | DNSKEY/DS with +dnssec: signed, algorithm, key bits; flags unsigned/RSASHA1/short keys | | `smtp_starttls_probe` | EHLO/STARTTLS and a real TLS upgrade via openssl s_client -starttls smtp | +| `tls_ocsp_probe` | `s_client -status`: stapled or not, OCSP response and certificate status | | `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 | @@ -360,6 +361,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack. | `php_config_audit` | php.ini: expose_php, display_errors, URL include/fopen, disable_functions, cookie_secure | | `dovecot_audit` | dovecot.conf: ssl = no, plaintext auth, PLAIN mechanism, writable drop-ins | | `openvpn_audit` | server.conf: no tls-auth/tls-crypt, BF-CBC/DES, SHA1/MD5 HMAC, duplicate-cn | +| `postgresql_config_audit` | postgresql.conf/pg_hba.conf: listen-all, ssl off, trust, md5/password | +| `exim_audit` | exim.conf: relay_from_hosts all, accept-any, no TLS advertisement, writable config | +| `elasticsearch_config_audit` | elasticsearch.yml: network.host all, security disabled, single-node | ### ESP32 @@ -608,6 +612,8 @@ The full threat model, trust boundaries and a hardening checklist are in | DNSSEC | two gated dig queries | | php/dovecot/openvpn | config reads only; optional root prefix | | SMTP STARTTLS | one handshake, no auth, no mail | +| postgres/exim/elasticsearch | config reads only; optional root prefix | +| OCSP | one TLS handshake, no responder call | | USB audit | 200 devices, sysfs reads only | --- @@ -619,7 +625,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus ```sh make # apex-twin -make test # version check + gate audit + 817 end-to-end checks +make test # version check + gate audit + 830 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 @@ -735,7 +741,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery, crlf_probe, dns_version_bind, oidc_discovery, security_txt, http2_probe, ssh_hostkey_fingerprint, kerberos_discovery, winrm_probe, dnssec_check, - smtp_starttls_probe + smtp_starttls_probe, tls_ocsp_probe src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, net_baseline, @@ -778,7 +784,7 @@ examples/ scope.json ## Status -1.31.0. Built and run: 163 tools, 817 checks, 340 fuzz cases and 81.3% line +1.32.0. Built and run: 167 tools, 830 checks, 340 fuzz cases and 81.2% 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 diff --git a/SECURITY.md b/SECURITY.md index 0a4096a..2449da7 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.31.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current +is **1.32.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,9 @@ 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. +- **OCSP is read from one handshake.** `tls_ocsp_probe` opens one TLS + connection with `openssl s_client -status` and reads the stapled response; + it does not contact the OCSP responder itself. - **STARTTLS is a handshake, not a login.** `smtp_starttls_probe` sends EHLO, STARTTLS and reads the TLS handshake; it never authenticates and never sends mail. PHP, Dovecot and OpenVPN audits read configuration files. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index ea66846..5ba9af1 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.31.0" "User Commands" +.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.32.0" "User Commands" .SH NAME apex-twin \- scope\-gated offensive\-security MCP server .SH SYNOPSIS @@ -43,7 +43,7 @@ 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, snmp_walk, -ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe), +ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe), defensive audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map, process_snapshot, persistence_audit, @@ -54,7 +54,8 @@ pam_audit, ssh_known_hosts_audit, logrotate_audit, nfs_exports_audit, samba_audit, snmpd_audit, rsyslog_audit, apparmor_audit, selinux_audit, usb_audit, docker_audit, www_audit, audit_rules, postfix_audit, nginx_audit, mysql_config_audit, apache_audit, haproxy_audit, redis_config_audit, -php_config_audit, dovecot_audit, openvpn_audit) and ESP32 board tools (esp_info, esp_monitor, +php_config_audit, dovecot_audit, openvpn_audit, postgresql_config_audit, +exim_audit, elasticsearch_config_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash, esp_partition_table, esp_nvs_parse, firmware_scan, esp_app_info, esp_image_verify). .SH MODES diff --git a/src/apex.h b/src/apex.h index 55678d0..fb5c04f 100644 --- a/src/apex.h +++ b/src/apex.h @@ -15,7 +15,7 @@ #include "mcp.h" -#define APEX_VERSION "1.31.0" +#define APEX_VERSION "1.32.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 36bfd34..63b3d9e 100644 --- a/src/tools_blue.c +++ b/src/tools_blue.c @@ -6767,7 +6767,9 @@ static int conf_value(const char *text, const char *key, char *out, size_t n) while (vl > 0 && (v[vl - 1] == ';' || v[vl - 1] == ' ' || v[vl - 1] == '\t' || v[vl - 1] == '\r')) v[--vl] = '\0'; - if (vl >= 2 && v[0] == '"' && v[vl - 1] == '"') { + if (vl >= 2 && + ((v[0] == '"' && v[vl - 1] == '"') || + (v[0] == '\'' && v[vl - 1] == '\''))) { v++; vl -= 2; } @@ -7992,6 +7994,564 @@ static void t_openvpn_audit(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&findings); } +/* ------------------------------------------------------- postgresql_config_audit */ + +static void pg_scan_hba(mcp_buf *findings, int *first, int *count, + const char *path, int *files, int *trust_entries, + int *weak_auth) +{ + FILE *f = fopen(path, "rb"); + char *line = NULL; + size_t cap = 0; + int lineno = 0; + struct stat st; + + if (f == NULL) + return; + (*files)++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + while (getline(&line, &cap, f) >= 0) { + char *tokens[8]; + int ntok = 0; + char *t = line; + char *save = NULL; + char *tok; + int method_index; + const char *method; + + lineno++; + while (*t == ' ' || *t == '\t') + t++; + trim_eol(t); + if (*t == '\0' || *t == '#') + continue; + tok = strtok_r(t, " \t", &save); + while (tok != NULL && ntok < 8) { + tokens[ntok++] = tok; + tok = strtok_r(NULL, " \t", &save); + } + if (ntok < 4) + continue; + /* local has 4 fields, host/hostssl/hostnossl have 5 and options */ + method_index = strcasecmp(tokens[0], "local") == 0 ? 3 : 4; + if (method_index >= ntok) + continue; + method = tokens[method_index]; + if (strcasecmp(method, "trust") == 0) { + add_finding(findings, first, "trust-auth", "high", + "%s line %d allows passwordless trust " + "authentication", path, lineno); + (*trust_entries)++; + (*count)++; + } else if (strcasecmp(method, "md5") == 0 || + strcasecmp(method, "password") == 0) { + if (!*weak_auth) + add_finding(findings, first, "weak-auth", "medium", + "%s uses md5/password instead of " + "scram-sha-256", path); + *weak_auth = 1; + (*count)++; + } + } + free(line); + fclose(f); +} + +static void t_postgresql_config_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *root = mcp_arg_string(args, "root"); + char base[512]; + char path[1024]; + DIR *d; + struct dirent *ver; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files = 0; + int trust_entries = 0; + int weak_auth = 0; + int listen_all = 0; + int ssl_off = 0; + char listen[256]; + char ssl_value[64]; + + (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); + listen[0] = ssl_value[0] = '\0'; + mcp_buf_init(&findings); + snprintf(path, sizeof(path), "%s/etc/postgresql", base); + d = opendir(path); + if (d != NULL) { + while ((ver = readdir(d)) != NULL) { + char vdir[1024]; + DIR *vd; + struct dirent *cluster; + + if (ver->d_name[0] == '.') + continue; + snprintf(vdir, sizeof(vdir), "%.800s/%.160s", path, + ver->d_name); + vd = opendir(vdir); + if (vd == NULL) + continue; + while ((cluster = readdir(vd)) != NULL) { + char cdir[1024]; + char conf[1024]; + char hba[1024]; + static char text[65536]; + struct stat st; + + if (cluster->d_name[0] == '.') + continue; + snprintf(cdir, sizeof(cdir), "%.800s/%.160s", + vdir, cluster->d_name); + snprintf(conf, sizeof(conf), + "%.900s/postgresql.conf", cdir); + snprintf(hba, sizeof(hba), "%.900s/pg_hba.conf", + cdir); + if (read_text(conf, text, sizeof(text)) > 0) { + char value[512]; + + files++; + if (stat(conf, &st) == 0 && + (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, + "world-writable", "high", + "%s is writable by " + "anyone", conf); + count++; + } + if (conf_value(text, "listen_addresses", + value, sizeof(value))) { + snprintf(listen, + sizeof(listen), + "%.200s", value); + if (conf_has_word(value, "*") || + conf_has_word(value, "0.0.0.0")) + listen_all = 1; + } + if (conf_value(text, "ssl", value, + sizeof(value))) { + snprintf(ssl_value, + sizeof(ssl_value), + "%.32s", value); + if (strcasecmp(value, "off") == 0) + ssl_off = 1; + } + } + pg_scan_hba(&findings, &first, &count, hba, &files, + &trust_entries, &weak_auth); + } + closedir(vd); + } + closedir(d); + } + if (files == 0) { + snprintf(path, sizeof(path), "%s/etc/postgresql.conf", base); + { + static char text[65536]; + char value[512]; + struct stat st; + + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, + "cannot read a PostgreSQL " + "configuration"); + return; + } + files++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", + "high", + "%s is writable by anyone", path); + count++; + } + if (conf_value(text, "listen_addresses", value, + sizeof(value))) { + snprintf(listen, sizeof(listen), "%.200s", + value); + if (conf_has_word(value, "*") || + conf_has_word(value, "0.0.0.0")) + listen_all = 1; + } + if (conf_value(text, "ssl", value, sizeof(value))) { + snprintf(ssl_value, sizeof(ssl_value), "%.32s", + value); + if (strcasecmp(value, "off") == 0) + ssl_off = 1; + } + } + } + if (listen_all) { + add_finding(&findings, &first, "listen-all", "high", + "PostgreSQL listens on every interface"); + count++; + } + if (ssl_off) { + add_finding(&findings, &first, "ssl-off", "high", + "TLS is disabled in postgresql.conf"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, base); + mcp_buf_printf(&b, ",\"files\":%d,\"listen_addresses\":", files); + apex_json_str(&b, listen); + mcp_buf_puts(&b, ",\"ssl\":"); + apex_json_str(&b, ssl_value); + mcp_buf_printf(&b, ",\"trust_entries\":%d,\"findings_count\":%d," + "\"findings\":[", trust_entries, 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); +} + +/* ------------------------------------------------------------------ exim_audit */ + +static void exim_scan_file(mcp_buf *findings, int *first, int *count, + const char *path, int *files, int *relay_all, + int *accept_all, int *no_tls, + char *relay_value, size_t relay_n, + char *tls_value, size_t tls_n) +{ + static char text[65536]; + struct stat st; + char value[512]; + char *copy; + char *save = NULL; + char *line; + + if (read_text(path, text, sizeof(text)) < 0) + return; + (*files)++; + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(findings, first, "world-writable", "high", + "%s is writable by anyone", path); + (*count)++; + } + if (conf_value(text, "relay_from_hosts", value, sizeof(value))) { + snprintf(relay_value, relay_n, "%.200s", value); + if (conf_has_word(value, "*") || + conf_has_word(value, "0.0.0.0/0") || + conf_has_word(value, "::/0")) + *relay_all = 1; + } + if (conf_value(text, "tls_advertise_hosts", value, sizeof(value))) { + snprintf(tls_value, tls_n, "%.100s", value); + if (value[0] == '\0') + *no_tls = 1; + } else { + *no_tls = 1; + } + copy = strdup(text); + if (copy == NULL) + return; + line = strtok_r(copy, "\n", &save); + while (line != NULL) { + char *t = line; + + while (*t == ' ' || *t == '\t') + t++; + if (*t == '#' || *t == '\0') { + line = strtok_r(NULL, "\n", &save); + continue; + } + if (strncmp(t, "accept", 6) == 0 && + (strstr(t, "hosts = *") != NULL || + strstr(t, "hosts=*") != NULL || + strstr(t, "hosts = 0.0.0.0/0") != NULL)) { + if (!*accept_all) + add_finding(findings, first, "accept-any", + "high", + "%s has an accept rule for every " + "host", path); + *accept_all = 1; + (*count)++; + } + line = strtok_r(NULL, "\n", &save); + } + free(copy); +} + +static void t_exim_audit(mcp_conn *c, const mcp_json *args, void *user) +{ + static const char *files[] = { "/etc/exim4/exim4.conf", + "/etc/exim4/exim4.conf.template", + "/etc/exim/exim.conf", NULL }; + const char *root = mcp_arg_string(args, "root"); + char path[1024]; + char relay_value[256]; + char tls_value[128]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int files_read = 0; + int relay_all = 0; + int accept_all = 0; + int no_tls = 0; + int i; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + relay_value[0] = tls_value[0] = '\0'; + mcp_buf_init(&findings); + for (i = 0; files[i] != NULL; i++) { + snprintf(path, sizeof(path), "%.400s%s", root, files[i]); + if (access(path, R_OK) == 0) + exim_scan_file(&findings, &first, &count, path, + &files_read, &relay_all, &accept_all, + &no_tls, relay_value, sizeof(relay_value), + tls_value, sizeof(tls_value)); + } + snprintf(path, sizeof(path), "%s/etc/exim4/conf.d", root); + { + DIR *d = opendir(path); + struct dirent *ent; + + if (d != NULL) { + while ((ent = readdir(d)) != NULL) { + char full[1024]; + char sub[1024]; + DIR *sd; + struct dirent *se; + size_t nl = strlen(ent->d_name); + + if (ent->d_name[0] == '.') + continue; + snprintf(sub, sizeof(sub), "%.800s/%.160s", + path, ent->d_name); + sd = opendir(sub); + if (sd == NULL) { + if (nl >= 6 && + strcmp(ent->d_name + nl - 5, + ".conf") == 0) + exim_scan_file(&findings, &first, + &count, sub, + &files_read, + &relay_all, + &accept_all, + &no_tls, + relay_value, + sizeof(relay_value), + tls_value, + sizeof(tls_value)); + continue; + } + while ((se = readdir(sd)) != NULL) { + size_t sl = strlen(se->d_name); + + if (se->d_name[0] == '.') + continue; + if (sl < 6 || + strcmp(se->d_name + sl - 5, + ".conf") != 0) + continue; + snprintf(full, sizeof(full), + "%.800s/%.160s", sub, + se->d_name); + exim_scan_file(&findings, &first, &count, + full, &files_read, + &relay_all, &accept_all, + &no_tls, relay_value, + sizeof(relay_value), + tls_value, + sizeof(tls_value)); + } + closedir(sd); + } + closedir(d); + } + } + if (files_read == 0) { + mcp_buf_free(&findings); + mcp_reply_error(c, "cannot read an Exim configuration"); + return; + } + if (relay_all) { + add_finding(&findings, &first, "relay-from-all", "high", + "relay_from_hosts covers every host"); + count++; + } + if (no_tls) { + add_finding(&findings, &first, "tls-not-advertised", "medium", + "tls_advertise_hosts is empty or not set"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_printf(&b, ",\"files\":%d,\"relay_from_hosts\":", files_read); + apex_json_str(&b, relay_value); + mcp_buf_puts(&b, ",\"tls_advertise_hosts\":"); + apex_json_str(&b, tls_value); + mcp_buf_printf(&b, ",\"findings_count\":%d,\"findings\":[", 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); +} + +/* ---------------------------------------------------- elasticsearch_config_audit */ + +static int yaml_value(const char *text, const char *key, char *out, size_t n) +{ + const char *p = text; + size_t kl = strlen(key); + + out[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[1024]; + char *s; + char *v; + size_t vl; + + if (len >= sizeof(line)) + len = sizeof(line) - 1; + memcpy(line, p, len); + line[len] = '\0'; + s = line; + while (*s == ' ' || *s == '\t') + s++; + if (*s != '#' && strncasecmp(s, key, kl) == 0 && + s[kl] == ':') { + v = s + kl + 1; + while (*v == ' ' || *v == '\t') + v++; + vl = strlen(v); + while (vl > 0 && (v[vl - 1] == '\r' || + v[vl - 1] == ' ' || + v[vl - 1] == '\t')) + v[--vl] = '\0'; + if (vl >= 2 && + ((v[0] == '"' && v[vl - 1] == '"') || + (v[0] == '\'' && v[vl - 1] == '\''))) { + v++; + vl -= 2; + } + if (vl >= n) + vl = n - 1; + memcpy(out, v, vl); + out[vl] = '\0'; + return 1; + } + p = eol != NULL ? eol + 1 : NULL; + } + return 0; +} + +static void t_elasticsearch_config_audit(mcp_conn *c, const mcp_json *args, + void *user) +{ + const char *root = mcp_arg_string(args, "root"); + static char text[65536]; + char path[1024]; + char network_host[256]; + char http_port[64]; + char security[64]; + char discovery[128]; + mcp_buf b; + mcp_buf findings; + int first = 1; + int count = 0; + int network_all = 0; + int security_off = 0; + struct stat st; + + (void)user; + if (root == NULL) + root = ""; + if (strlen(root) > 400) { + mcp_reply_error(c, "root path too long"); + return; + } + snprintf(path, sizeof(path), "%s/etc/elasticsearch/elasticsearch.yml", + root); + if (read_text(path, text, sizeof(text)) <= 0) { + mcp_reply_error(c, "cannot read elasticsearch.yml"); + return; + } + network_host[0] = http_port[0] = security[0] = discovery[0] = '\0'; + mcp_buf_init(&findings); + if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) { + add_finding(&findings, &first, "world-writable", "high", + "elasticsearch.yml is writable by anyone"); + count++; + } + if (yaml_value(text, "network.host", network_host, + sizeof(network_host))) { + if (conf_has_word(network_host, "0.0.0.0") || + conf_has_word(network_host, "::") || + conf_has_word(network_host, "[::]") || + conf_has_word(network_host, "*")) + network_all = 1; + } + if (network_all) { + add_finding(&findings, &first, "network-all", "high", + "Elasticsearch binds to every interface"); + count++; + } + yaml_value(text, "http.port", http_port, sizeof(http_port)); + if (yaml_value(text, "xpack.security.enabled", security, + sizeof(security)) && + strcasecmp(security, "false") == 0) { + add_finding(&findings, &first, "security-off", "high", + "the security layer is disabled"); + security_off = 1; + count++; + } + if (yaml_value(text, "discovery.type", discovery, + sizeof(discovery)) && + strcasecmp(discovery, "single-node") == 0) { + add_finding(&findings, &first, "single-node", "low", + "single-node discovery is configured"); + count++; + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"root\":"); + apex_json_str(&b, root); + mcp_buf_puts(&b, ",\"path\":"); + apex_json_str(&b, path); + mcp_buf_puts(&b, ",\"network_host\":"); + apex_json_str(&b, network_host); + mcp_buf_puts(&b, ",\"http_port\":"); + apex_json_str(&b, http_port); + mcp_buf_printf(&b, ",\"security_enabled\":%s,\"findings_count\":%d," + "\"findings\":[", + security_off ? "false" : "true", 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, " @@ -8434,6 +8994,27 @@ const mcp_tool TOOLS_BLUE[] = { "{\"type\":\"object\",\"properties\":{" "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", t_openvpn_audit }, + { "postgresql_config_audit", + "Parse postgresql.conf and pg_hba.conf under /etc/postgresql (root " + "prefix): listen_addresses on every interface, ssl = off, trust entries " + "and md5/password auth in pg_hba, plus world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_postgresql_config_audit }, + { "exim_audit", + "Parse exim4.conf/exim.conf and conf.d (root prefix): relay_from_hosts " + "covering every host, an accept rule for any host, an empty or missing " + "tls_advertise_hosts and world-writable files. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_exim_audit }, + { "elasticsearch_config_audit", + "Parse elasticsearch.yml (root prefix): network.host on every interface, " + "xpack.security.enabled false, single-node discovery and a " + "world-writable config. Read-only.", + "{\"type\":\"object\",\"properties\":{" + "\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}", + t_elasticsearch_config_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 1b836bc..1ad461b 100644 --- a/src/tools_proto.c +++ b/src/tools_proto.c @@ -5223,6 +5223,105 @@ static void t_smtp_starttls_probe(mcp_conn *c, const mcp_json *args, void *user) mcp_buf_free(&b); } +/* ------------------------------------------------------------- tls_ocsp_probe */ + +static void ocsp_after(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 != '\r' && *p != '\n' && *p != ' ' && + w + 1 < n) + out[w++] = *p++; + out[w] = '\0'; +} + +static void t_tls_ocsp_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", 443); + char conn[320]; + char protocol[64]; + char cipher[128]; + char response_status[64]; + char cert_status[64]; + int stapled = 0; + 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 (!apex_have("openssl")) { + mcp_reply_error(c, "openssl is not installed on this host"); + return; + } + if (!gated(c, "tls_ocsp_probe", target, port)) + return; + tls_conn_string(target, port, conn, sizeof(conn)); + protocol[0] = cipher[0] = '\0'; + response_status[0] = cert_status[0] = '\0'; + { + char *argv[12]; + 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++] = "-status"; + argv[k] = NULL; + if (apex_run(argv, 20000, g_cfg.max_output, &p) != 0) { + mcp_reply_error(c, "cannot run openssl s_client"); + return; + } + if (p.out != NULL) { + tls_summary(p.out, protocol, sizeof(protocol), cipher, + sizeof(cipher)); + if (strstr(p.out, "OCSP response: no response sent") == NULL && + strstr(p.out, "OCSP response:") != NULL) + stapled = 1; + ocsp_after(p.out, "OCSP Response Status:", + response_status, sizeof(response_status)); + ocsp_after(p.out, "Cert Status:", cert_status, + sizeof(cert_status)); + } + apex_proc_free(&p); + } + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"target\":"); + apex_json_str(&b, target); + mcp_buf_printf(&b, ",\"port\":%d,\"tls\":true,\"protocol\":", port); + apex_json_str(&b, protocol); + mcp_buf_puts(&b, ",\"cipher\":"); + apex_json_str(&b, cipher); + mcp_buf_printf(&b, ",\"ocsp_stapled\":%s,\"response_status\":", + stapled ? "true" : "false"); + apex_json_str(&b, response_status); + mcp_buf_puts(&b, ",\"cert_status\":"); + apex_json_str(&b, cert_status); + mcp_buf_puts(&b, "}"); + apex_audit("tls_ocsp_probe", target, port, stapled, + stapled ? "OCSP response stapled" : "no OCSP staple", + cert_status[0] != '\0' ? cert_status : response_status); + 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 " @@ -5540,6 +5639,16 @@ const mcp_tool TOOLS_PROTO[] = { "\"port\":{\"type\":\"integer\",\"description\":\"default 25\"}}," "\"required\":[\"target\"]}", t_smtp_starttls_probe }, + { "tls_ocsp_probe", + "Open one TLS connection with openssl s_client -status and report whether " + "the server staples an OCSP response, its response status and the " + "certificate status (good/revoked/unknown), with the negotiated protocol " + "and cipher. No authentication beyond the handshake. Gate: target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}}," + "\"required\":[\"target\"]}", + t_tls_ocsp_probe }, }; const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]); diff --git a/tests/gate_audit.py b/tests/gate_audit.py index a921ca5..6076e02 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 = 163 +EXPECTED_TOOLS = 167 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 f4b676b..1276f86 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("163 tools registered", len(tools) == 163, len(tools)) +check("167 tools registered", len(tools) == 167, 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"]) == 163) + check("http tools/list", len(listing["result"]["tools"]) == 167) 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 @@ -7460,6 +7460,141 @@ shutil.rmtree(ov_good_root, ignore_errors=True) shutil.rmtree(tls_sec_dir, ignore_errors=True) shutil.rmtree(cfg3_home, ignore_errors=True) +print("\n== PostgreSQL, Exim, Elasticsearch and OCSP ==\n") + +pg_root = tempfile.mkdtemp(prefix="apex-pg-") +os.makedirs(os.path.join(pg_root, "etc", "postgresql", "16", "main")) +with open(os.path.join(pg_root, "etc", "postgresql", "16", "main", + "postgresql.conf"), "w") as f: + f.write("listen_addresses = '*'\n") + f.write("ssl = off\n") +pg_hba = os.path.join(pg_root, "etc", "postgresql", "16", "main", + "pg_hba.conf") +with open(pg_hba, "w") as f: + f.write("local all postgres trust\n") + f.write("host all all 0.0.0.0/0 md5\n") +os.chmod(pg_hba, 0o666) +pg_good_root = tempfile.mkdtemp(prefix="apex-pgg-") +os.makedirs(os.path.join(pg_good_root, "etc", "postgresql", "16", "main")) +with open(os.path.join(pg_good_root, "etc", "postgresql", "16", "main", + "postgresql.conf"), "w") as f: + f.write("listen_addresses = 'localhost'\n") + f.write("ssl = on\n") +with open(os.path.join(pg_good_root, "etc", "postgresql", "16", "main", + "pg_hba.conf"), "w") as f: + f.write("host all all 127.0.0.1/32 scram-sha-256\n") + +ex_root = tempfile.mkdtemp(prefix="apex-ex-") +os.makedirs(os.path.join(ex_root, "etc", "exim4")) +ex_bad = os.path.join(ex_root, "etc", "exim4", "exim4.conf") +with open(ex_bad, "w") as f: + f.write("relay_from_hosts = *\n") + f.write("tls_advertise_hosts =\n") + f.write("acl_check_rcpt:\n accept hosts = *\n") +os.chmod(ex_bad, 0o666) +ex_good_root = tempfile.mkdtemp(prefix="apex-exg-") +os.makedirs(os.path.join(ex_good_root, "etc", "exim4")) +with open(os.path.join(ex_good_root, "etc", "exim4", "exim4.conf"), + "w") as f: + f.write("relay_from_hosts = 127.0.0.1 : :1\n") + f.write("tls_advertise_hosts = *\n") + +es_root = tempfile.mkdtemp(prefix="apex-es-") +os.makedirs(os.path.join(es_root, "etc", "elasticsearch")) +es_bad = os.path.join(es_root, "etc", "elasticsearch", "elasticsearch.yml") +with open(es_bad, "w") as f: + f.write("network.host: 0.0.0.0\n") + f.write("http.port: 9200\n") + f.write("xpack.security.enabled: false\n") + f.write("discovery.type: single-node\n") +os.chmod(es_bad, 0o666) +es_good_root = tempfile.mkdtemp(prefix="apex-esg-") +os.makedirs(os.path.join(es_good_root, "etc", "elasticsearch")) +with open(os.path.join(es_good_root, "etc", "elasticsearch", + "elasticsearch.yml"), "w") as f: + f.write("network.host: 127.0.0.1\n") + f.write("http.port: 9200\n") + f.write("xpack.security.enabled: true\n") + +ocsp_dir = tempfile.mkdtemp(prefix="apex-ocsp-") +ocsp_cert = os.path.join(ocsp_dir, "cert.pem") +ocsp_key = os.path.join(ocsp_dir, "key.pem") +subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", ocsp_key, "-out", ocsp_cert, "-days", "2", + "-subj", "/CN=localhost"], + check=True, capture_output=True) +ocsp_srv, ocsp_port = tls_server(ocsp_cert, ocsp_key) + +cfg4_home = tempfile.mkdtemp(prefix="apex-cfg4-home-") +write_scope(cfg4_home, {"label": "cfg4", "expires": "2099-12-31T23:59:59Z", + "allow_private": True, "allow_ip": ["127.0.0.1"], + "allow_port": [str(ocsp_port)]}) +res, _ = run([ + call(1, "postgresql_config_audit", root=pg_root), + call(2, "postgresql_config_audit", root=pg_good_root), + call(3, "exim_audit", root=ex_root), + call(4, "exim_audit", root=ex_good_root), + call(5, "elasticsearch_config_audit", root=es_root), + call(6, "elasticsearch_config_audit", root=es_good_root), + call(7, "tls_ocsp_probe", target="127.0.0.1", port=ocsp_port), + call(8, "postgresql_config_audit", root="/nonexistent-pg"), + call(9, "exim_audit", root="/nonexistent-ex"), + call(10, "elasticsearch_config_audit", root="/nonexistent-es"), + call(11, "tls_ocsp_probe", target="198.51.100.9", port=443), +], home=cfg4_home) +by_id = {r.get("id"): r for r in res} +pg = json.loads(text(by_id[1])) +pg_kinds = {f["id"] for f in pg["findings"]} +check("postgresql_config_audit flags listen-all, ssl off and trust", + {"listen-all", "ssl-off", "trust-auth", "weak-auth"} <= pg_kinds, pg) +check("postgresql_config_audit flags the writable pg_hba", + "world-writable" in pg_kinds and pg["trust_entries"] == 1, pg) +pg_good = json.loads(text(by_id[2])) +check("postgresql_config_audit accepts a hardened cluster", + pg_good["findings_count"] == 0 and + pg_good["listen_addresses"] == "localhost" and + pg_good["ssl"] == "on", pg_good) +ex = json.loads(text(by_id[3])) +ex_kinds = {f["id"] for f in ex["findings"]} +check("exim_audit flags relay, accept-any and missing TLS", + {"relay-from-all", "accept-any", "tls-not-advertised"} <= ex_kinds, ex) +check("exim_audit flags the writable config", + "world-writable" in {f["id"] for f in ex["findings"]}, ex) +ex_good = json.loads(text(by_id[4])) +check("exim_audit accepts a hardened config", + ex_good["findings_count"] == 0 and + ex_good["tls_advertise_hosts"] == "*", ex_good) +es = json.loads(text(by_id[5])) +es_kinds = {f["id"] for f in es["findings"]} +check("elasticsearch_config_audit flags network, security and discovery", + {"world-writable", "network-all", "security-off", "single-node"} <= + es_kinds, es) +es_good = json.loads(text(by_id[6])) +check("elasticsearch_config_audit accepts a hardened config", + es_good["findings_count"] == 0 and + es_good["network_host"] == "127.0.0.1", es_good) +ocsp = json.loads(text(by_id[7])) +check("tls_ocsp_probe reports a server without stapling", + ocsp["ocsp_stapled"] is False and + ocsp["protocol"].startswith("TLSv1.") and ocsp["cipher"] != "", ocsp) +check("postgresql_config_audit reports a missing config", err(by_id[8]), + text(by_id[8])) +check("exim_audit reports a missing config", err(by_id[9]), + text(by_id[9])) +check("elasticsearch_config_audit reports a missing config", + err(by_id[10]), text(by_id[10])) +check("tls_ocsp_probe refuses an out-of-scope target", err(by_id[11]), + text(by_id[11])) +ocsp_srv.close() +shutil.rmtree(pg_root, ignore_errors=True) +shutil.rmtree(pg_good_root, ignore_errors=True) +shutil.rmtree(ex_root, ignore_errors=True) +shutil.rmtree(ex_good_root, ignore_errors=True) +shutil.rmtree(es_root, ignore_errors=True) +shutil.rmtree(es_good_root, ignore_errors=True) +shutil.rmtree(ocsp_dir, ignore_errors=True) +shutil.rmtree(cfg4_home, ignore_errors=True) + print("\n== esp32 tools ==") esp_home = tempfile.mkdtemp(prefix="apex-esp-") write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})