apex-twin 1.46.0: dnsmasq, nsswitch and Jenkins audits, TLS hostname check

Blue:
- dnsmasq_audit: dnsmasq.conf and dnsmasq.d/*.conf: wildcard or missing
  interface restriction, no bind-interfaces, missing bogus-priv or
  domain-needed and world-writable files.
- nsswitch_audit: nsswitch.conf: compat/NIS in passwd/group/shadow, direct
  LDAP without sssd, hosts lookups that skip files, world-writable.
- jenkins_audit: config.xml from three usual homes: security disabled, an
  unsecured authorization strategy, missing CSRF protection, a fixed agent
  port and a world-writable file.

Red:
- tls_hostname_check: one handshake with the name as SNI; matches SAN DNS
  names (one-label wildcard), IP SANs and falls back to CN only when no DNS
  SAN exists.

extract_first_pem returns 0 on success, not a length; the first version
tested > 0 and always reported 'no certificate presented'. tools_proto.c
also needed <arpa/inet.h> for inet_pton.

Tests with dnsmasq/nsswitch/Jenkins trees and a certificate carrying
other.test, *.wild.test and IP:127.0.0.1. 1011 checks, ASan suite green,
analyze clean, release-check green including distcheck 1.46.0.
This commit is contained in:
lotherk committed 2026-11-22 10:09:46 +00:00
1 parent 38ce77698d
commit b4996fd55d
9 files changed
+883 -15

No files matched your search

+18 -1
View File
@@ -8,7 +8,24 @@ fields, and state from an older version is read by a newer one.
There are no git tags. The hash next to a version is the commit that introduced
it; the current entry is the commit that adds this section.
## 1.45.0 — 2026-11-23 — this change
## 1.46.0 — 2026-11-23 — this change
- **dnsmasq** (`dnsmasq_audit`): `dnsmasq.conf` and `dnsmasq.d/*.conf`: a
wildcard or missing interface restriction, no `bind-interfaces`, missing
`bogus-priv`/`domain-needed` and world-writable files.
- **nsswitch** (`nsswitch_audit`): `nsswitch.conf`: `compat`/NIS in
passwd/group/shadow, direct LDAP without sssd, hosts lookups that skip
files and a world-writable file.
- **Jenkins** (`jenkins_audit`): `config.xml` from three usual homes:
security disabled, an unsecured authorization strategy, missing CSRF
protection, a fixed agent port and a world-writable file.
- **TLS hostname** (`tls_hostname_check`): one handshake with the name as
SNI; matches SAN DNS names (one-label wildcards), IP SANs and falls back to
CN only when no DNS SAN exists.
- Tests with dnsmasq/nsswitch/Jenkins trees and a certificate carrying
`other.test`, `*.wild.test` and `IP:127.0.0.1`. 1011 checks. Coverage 82.9%.
## 1.45.0 — 2026-11-23 — 38ce776
- **journald** (`journald_audit`): `journald.conf`: `Storage=volatile` or
`none`, `ForwardToSyslog=no`, `SystemMaxUse` above one gigabyte, `Seal=no`
+13 -6
View File
@@ -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.
**218 tools · 996 end-to-end checks · 340 fuzz cases · 82.8% line coverage · ~813 KiB**
**222 tools · 1011 end-to-end checks · 340 fuzz cases · 82.9% line coverage · ~826 KiB**
```
$ ./apex-twin --check
{"version":"1.45.0","tools":218,...,"scope":{"loaded":true,...}}
{"version":"1.46.0","tools":222,...,"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 (218)
## Tools (222)
### Scope and bookkeeping
@@ -204,6 +204,7 @@ uploads and secret-file reads. It does not execute anything.
| `cors_check` | Marker `Origin`; grades reflection with credentials as high risk |
| `http_redirect_audit` | Follows redirects per hop inside the scope; flags HTTPS-to-HTTP downgrades |
| `hsts_audit` | HSTS max-age, includeSubDomains and preload, or a missing header |
| `tls_hostname_check` | SAN/CN wildcard match for the requested SNI name |
| `cookie_audit` | Secure/HttpOnly/SameSite per cookie, incl. `SameSite=None` without Secure |
| `http_options` | `Allow`/`Public`; flags TRACE, PUT, DELETE |
| `sqli_probe` | Quote and boolean payloads; differing answers are a **lead**, not proof |
@@ -415,6 +416,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `journald_audit` | journald.conf: volatile storage, forwarding, size, sealing |
| `coredump_audit` | coredump.conf: disk storage keeps cores, no compression |
| `nftables_audit` | nftables: accept policy, no conntrack, exposed admin ports |
| `dnsmasq_audit` | dnsmasq.conf: wildcard listener, missing bogus-priv/domain-needed |
| `nsswitch_audit` | nsswitch.conf: NIS compat, direct LDAP, hosts without files |
| `jenkins_audit` | config.xml: security off, AnyoneCanDoAnything, no CSRF, fixed agent port |
### ESP32
@@ -693,6 +697,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| SOA MNAME | two dig queries |
| journald/coredump/nftables | config reads only; optional root prefix |
| HSTS | one TLS GET |
| dnsmasq/nsswitch/jenkins | config reads only; optional root prefix |
| TLS hostname | one handshake with the name as SNI |
| USB audit | 200 devices, sysfs reads only |
---
@@ -704,7 +710,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 996 end-to-end checks
make test # version check + gate audit + 1011 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
@@ -826,7 +832,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery,
kubernetes_api_probe, dns_ns_consistency,
dns_dangling_cname, http_redirect_audit,
websocket_origin_check, dns_fcrdns_check,
dns_soa_mname_check, hsts_audit
dns_soa_mname_check, hsts_audit,
tls_hostname_check
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,
@@ -869,7 +876,7 @@ examples/ scope.json
## Status
1.45.0. Built and run: 218 tools, 996 checks, 340 fuzz cases and 82.8% line
1.46.0. Built and run: 222 tools, 1011 checks, 340 fuzz cases and 82.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
+3 -1
View File
@@ -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.45.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.46.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,8 @@ 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.
- **dnsmasq, nsswitch and Jenkins audits read local files.** The TLS
hostname check is one handshake with the name as SNI.
- **journald, coredump and nftables audits read local files.** The HSTS
check makes one TLS GET.
- **Certificate, timesyncd and resolv.conf audits read local files.** The
+4 -3
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.45.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.46.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -46,7 +46,7 @@ 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, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check, sni_vhost_check, tls_client_auth_probe, kubernetes_api_probe,
dns_ns_consistency, dns_dangling_cname, http_redirect_audit,
websocket_origin_check, dns_fcrdns_check, dns_soa_mname_check, http_redirect_audit,
websocket_origin_check, hsts_audit),
websocket_origin_check, hsts_audit, tls_hostname_check),
defensive
audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules,
integrity_baseline, mitre_map, process_snapshot, persistence_audit,
@@ -67,7 +67,8 @@ zookeeper_audit, grafana_audit, prometheus_audit, wireguard_config_audit,
ipsec_config_audit, openldap_config_audit, cron_audit, fail2ban_audit, chrony_config_audit,
apt_config_audit, login_defs_audit, pg_hba_audit, polkit_audit,
ldap_client_audit, ssl_cert_audit, timesyncd_audit, resolv_conf_audit, journald_audit,
coredump_audit, nftables_audit)
coredump_audit, nftables_audit, dnsmasq_audit, nsswitch_audit,
jenkins_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).
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.45.0"
#define APEX_VERSION "1.46.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+413
View File
@@ -13197,6 +13197,398 @@ static void t_nftables_audit(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&findings);
}
/* -------------------------------------------------------------- dnsmasq_audit */
static int dnsmasq_has_line(const char *text, const char *key)
{
char *copy = strdup(text);
char *save = NULL;
char *line;
size_t kl = strlen(key);
int found = 0;
if (copy == NULL)
return 0;
line = strtok_r(copy, "\n", &save);
while (line != NULL) {
char *s = line;
while (*s == ' ' || *s == '\t')
s++;
if (*s != '#' && strncmp(s, key, kl) == 0 &&
(s[kl] == '=' || s[kl] == ' ' || s[kl] == '\t' ||
s[kl] == '\0')) {
found = 1;
break;
}
line = strtok_r(NULL, "\n", &save);
}
free(copy);
return found;
}
static void dnsmasq_scan_file(mcp_buf *findings, int *first, int *count,
const char *path, int *files, int *interface,
int *listen, int *wildcard, int *bind,
int *bogus, int *domain_needed)
{
static char text[65536];
struct stat st;
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 (dnsmasq_has_line(text, "interface"))
*interface = 1;
if (dnsmasq_has_line(text, "listen-address"))
*listen = 1;
if (dnsmasq_has_line(text, "interface=0.0.0.0") ||
dnsmasq_has_line(text, "interface=::") ||
dnsmasq_has_line(text, "interface=*"))
*wildcard = 1;
if (dnsmasq_has_line(text, "bind-interfaces") ||
dnsmasq_has_line(text, "bind-dynamic"))
*bind = 1;
if (dnsmasq_has_line(text, "bogus-priv"))
*bogus = 1;
if (dnsmasq_has_line(text, "domain-needed"))
*domain_needed = 1;
}
static void t_dnsmasq_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
char path[1024];
mcp_buf b;
mcp_buf findings;
int first = 1;
int count = 0;
int files = 0;
int interface = 0;
int listen = 0;
int wildcard = 0;
int bind = 0;
int bogus = 0;
int domain_needed = 0;
DIR *d;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) > 400) {
mcp_reply_error(c, "root path too long");
return;
}
mcp_buf_init(&findings);
snprintf(path, sizeof(path), "%s/etc/dnsmasq.conf", root);
dnsmasq_scan_file(&findings, &first, &count, path, &files,
&interface, &listen, &wildcard, &bind, &bogus,
&domain_needed);
snprintf(path, sizeof(path), "%s/etc/dnsmasq.d", root);
d = opendir(path);
if (d != NULL) {
struct dirent *ent;
while ((ent = readdir(d)) != NULL) {
char full[1200];
size_t nl = strlen(ent->d_name);
if (ent->d_name[0] == '.')
continue;
if (nl < 6 || strcmp(ent->d_name + nl - 5, ".conf") != 0)
continue;
snprintf(full, sizeof(full), "%.900s/%.200s", path,
ent->d_name);
dnsmasq_scan_file(&findings, &first, &count, full,
&files, &interface, &listen,
&wildcard, &bind, &bogus,
&domain_needed);
}
closedir(d);
}
if (files == 0) {
mcp_buf_free(&findings);
mcp_reply_error(c, "cannot read a dnsmasq configuration");
return;
}
if (wildcard || (!interface && !listen)) {
add_finding(&findings, &first, "all-interfaces", "medium",
"dnsmasq answers on every interface");
count++;
} else if (!bind) {
add_finding(&findings, &first, "no-bind-interfaces", "low",
"the interface list is not enforced with "
"bind-interfaces");
count++;
}
if (!bogus) {
add_finding(&findings, &first, "no-bogus-priv", "low",
"reverse lookups for private ranges are forwarded");
count++;
}
if (!domain_needed) {
add_finding(&findings, &first, "no-domain-needed", "low",
"plain names are forwarded upstream");
count++;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, root);
mcp_buf_printf(&b, ",\"files\":%d,\"restricted\":%s,"
"\"bind_interfaces\":%s,\"bogus_priv\":%s,"
"\"domain_needed\":%s,\"findings_count\":%d,"
"\"findings\":[",
files,
((interface || listen) && !wildcard) ? "true" : "false",
bind ? "true" : "false", bogus ? "true" : "false",
domain_needed ? "true" : "false", 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);
}
/* -------------------------------------------------------------- nsswitch_audit */
static int nss_db_line(const char *text, const char *db, char *out, size_t n)
{
char *copy = strdup(text);
char *save = NULL;
char *line;
size_t dl = strlen(db);
int found = 0;
if (copy == NULL)
return 0;
line = strtok_r(copy, "\n", &save);
while (line != NULL) {
char *s = line;
while (*s == ' ' || *s == '\t')
s++;
if (*s != '#' && strncmp(s, db, dl) == 0 && s[dl] == ':') {
char *v = s + dl + 1;
while (*v == ' ' || *v == '\t')
v++;
{
size_t vl = strlen(v);
while (vl > 0 && (v[vl - 1] == ' ' ||
v[vl - 1] == '\t' ||
v[vl - 1] == '\r'))
v[--vl] = '\0';
snprintf(out, n, "%.200s", v);
}
found = 1;
break;
}
line = strtok_r(NULL, "\n", &save);
}
free(copy);
return found;
}
static void t_nsswitch_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
char path[1024];
static char text[65536];
char passwd[256];
char group[256];
char shadow[256];
char hosts[256];
struct stat st;
mcp_buf b;
mcp_buf findings;
int first = 1;
int count = 0;
int nis = 0;
int direct_ldap = 0;
int no_files = 0;
int i;
(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/nsswitch.conf", root);
if (read_text(path, text, sizeof(text)) <= 0) {
mcp_reply_error(c, "cannot read nsswitch.conf");
return;
}
passwd[0] = group[0] = shadow[0] = hosts[0] = '\0';
mcp_buf_init(&findings);
if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0) {
add_finding(&findings, &first, "world-writable", "high",
"nsswitch.conf is writable by anyone");
count++;
}
nss_db_line(text, "passwd", passwd, sizeof(passwd));
nss_db_line(text, "group", group, sizeof(group));
nss_db_line(text, "shadow", shadow, sizeof(shadow));
nss_db_line(text, "hosts", hosts, sizeof(hosts));
if (conf_has_word(passwd, "compat") || conf_has_word(group, "compat") ||
conf_has_word(shadow, "compat")) {
nis = 1;
add_finding(&findings, &first, "nis-compat", "high",
"the compat module reads NIS maps");
count++;
}
{
static const char *dbs[] = { "passwd", "group", "shadow", NULL };
for (i = 0; dbs[i] != NULL; i++) {
const char *v = i == 0 ? passwd : i == 1 ? group : shadow;
if (conf_has_word(v, "ldap") &&
!conf_has_word(v, "sss")) {
direct_ldap = 1;
add_finding(&findings, &first,
"direct-ldap", "medium",
"%s talks to LDAP without sssd",
dbs[i]);
count++;
break;
}
}
}
if (hosts[0] != '\0' && !conf_has_word(hosts, "files")) {
no_files = 1;
add_finding(&findings, &first, "no-files", "low",
"hosts lookups skip /etc/hosts");
count++;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, root);
mcp_buf_puts(&b, ",\"passwd\":");
apex_json_str(&b, passwd);
mcp_buf_puts(&b, ",\"hosts\":");
apex_json_str(&b, hosts);
mcp_buf_printf(&b, ",\"nis\":%s,\"direct_ldap\":%s,"
"\"hosts_files\":%s,\"findings_count\":%d,"
"\"findings\":[",
nis ? "true" : "false",
direct_ldap ? "true" : "false",
no_files ? "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);
}
/* --------------------------------------------------------------- jenkins_audit */
static void t_jenkins_audit(mcp_conn *c, const mcp_json *args, void *user)
{
static const char *files[] = { "/var/lib/jenkins/config.xml",
"/var/jenkins_home/config.xml",
"/etc/jenkins/config.xml", NULL };
const char *root = mcp_arg_string(args, "root");
char path[1024];
static char text[131072];
struct stat st;
mcp_buf b;
mcp_buf findings;
int first = 1;
int count = 0;
int files_read = 0;
int no_security = 0;
int unsecured = 0;
int no_csrf = 0;
int agent_port = 0;
int i;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) > 400) {
mcp_reply_error(c, "root path too long");
return;
}
mcp_buf_init(&findings);
for (i = 0; files[i] != NULL; i++) {
snprintf(path, sizeof(path), "%.400s%s", root, files[i]);
if (read_text(path, text, sizeof(text)) <= 0)
continue;
files_read++;
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 (strstr(text, "<useSecurity>false</useSecurity>") != NULL) {
no_security = 1;
add_finding(&findings, &first, "no-security", "high",
"Jenkins security is disabled");
count++;
}
if (strstr(text, "AnyoneCanDoAnything") != NULL ||
strstr(text, "AuthorizationStrategy$Unsecured") != NULL) {
unsecured = 1;
add_finding(&findings, &first, "unsecured-authz", "high",
"everyone has full control");
count++;
}
if (strstr(text, "<crumbIssuer") == NULL) {
no_csrf = 1;
add_finding(&findings, &first, "no-csrf", "medium",
"CSRF protection is not configured");
count++;
}
{
const char *p = strstr(text, "<slaveAgentPort>");
if (p != NULL) {
int port = atoi(p + 16);
if (port > 0) {
agent_port = port;
add_finding(&findings, &first,
"agent-port", "medium",
"the agent port is fixed at %d",
port);
count++;
}
}
}
break;
}
if (files_read == 0) {
mcp_buf_free(&findings);
mcp_reply_error(c, "cannot read a Jenkins config.xml");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, root);
mcp_buf_printf(&b, ",\"security\":%s,\"unsecured_authz\":%s,"
"\"csrf\":%s,\"agent_port\":%d,\"findings_count\":%d,"
"\"findings\":[",
no_security ? "false" : "true",
unsecured ? "true" : "false",
no_csrf ? "false" : "true", agent_port, 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, "
@@ -13920,6 +14312,27 @@ const mcp_tool TOOLS_BLUE[] = {
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_nftables_audit },
{ "dnsmasq_audit",
"Parse dnsmasq.conf and dnsmasq.d/*.conf (root prefix): answers on "
"every interface, no bind-interfaces, missing bogus-priv or "
"domain-needed and world-writable files. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_dnsmasq_audit },
{ "nsswitch_audit",
"Parse nsswitch.conf (root prefix): compat/NIS in passwd/group/shadow, "
"direct LDAP without sssd, hosts lookups that skip files and a "
"world-writable file. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_nsswitch_audit },
{ "jenkins_audit",
"Parse Jenkins config.xml (root prefix, three usual homes): security "
"disabled, an unsecured authorization strategy, missing CSRF protection, "
"a fixed agent port and a world-writable file. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_jenkins_audit },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+262
View File
@@ -9,6 +9,7 @@
* protocol handshake, and close. Nothing is brute-forced and nothing is written
* on the service. Credentials in ftp_probe are the literal anonymous pair.
*/
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
@@ -5691,6 +5692,256 @@ static void t_tls_client_auth_probe(mcp_conn *c, const mcp_json *args,
mcp_buf_free(&b);
}
/* ------------------------------------------------------- tls_hostname_check */
static int cert_same_ip(const char *a, const char *b)
{
unsigned char ra[16];
unsigned char rb[16];
if (inet_pton(AF_INET, a, ra) == 1 && inet_pton(AF_INET, b, rb) == 1)
return memcmp(ra, rb, 4) == 0;
if (inet_pton(AF_INET6, a, ra) == 1 &&
inet_pton(AF_INET6, b, rb) == 1)
return memcmp(ra, rb, 16) == 0;
return 0;
}
static int cert_pattern_match(const char *pattern, const char *name)
{
const char *dot;
if (pattern[0] != '*')
return strcasecmp(pattern, name) == 0;
if (pattern[1] != '.')
return 0;
dot = strchr(name, '.');
return dot != NULL && strcasecmp(dot, pattern + 1) == 0;
}
static void cert_san_line(const char *text, char *out, size_t n)
{
const char *p = strstr(text, "Subject Alternative Name:");
const char *v;
const char *eol;
size_t len;
out[0] = '\0';
if (p == NULL)
return;
v = p + strlen("Subject Alternative Name:");
while (*v == ' ' || *v == '\t' || *v == '\r')
v++;
if (*v == '\n') {
v++;
while (*v == ' ' || *v == '\t')
v++;
}
eol = strchr(v, '\n');
len = eol != NULL ? (size_t)(eol - v) : strlen(v);
if (len >= n)
len = n - 1;
memcpy(out, v, len);
out[len] = '\0';
while (len > 0 && (out[len - 1] == ' ' || out[len - 1] == '\t' ||
out[len - 1] == '\r'))
out[--len] = '\0';
}
static void cert_match_name(const char *sans, const char *subject,
const char *name, int *matched, char *by,
size_t bn)
{
char copy[1024];
char *save = NULL;
char *tok;
unsigned char raw[16];
int dns_seen = 0;
int is_ip;
by[0] = '\0';
*matched = 0;
is_ip = inet_pton(AF_INET, name, raw) == 1 ||
inet_pton(AF_INET6, name, raw) == 1;
snprintf(copy, sizeof(copy), "%.1000s", sans);
tok = strtok_r(copy, ",", &save);
while (tok != NULL) {
char *t = tok;
while (*t == ' ' || *t == '\t')
t++;
if (strncasecmp(t, "DNS:", 4) == 0) {
dns_seen = 1;
t += 4;
if (!is_ip && cert_pattern_match(t, name)) {
*matched = 1;
snprintf(by, bn, "san");
}
} else if (strncasecmp(t, "IP Address:", 11) == 0) {
t += 11;
if (is_ip && cert_same_ip(t, name)) {
*matched = 1;
snprintf(by, bn, "san");
}
}
tok = strtok_r(NULL, ",", &save);
}
if (!*matched && !is_ip && !dns_seen) {
const char *p = strcasestr(subject, "CN=");
if (p != NULL) {
char cn[256];
size_t k = 0;
p += 3;
while (*p == ' ' || *p == '\t')
p++;
while (p[k] != '\0' && p[k] != ',' && p[k] != '/' &&
k + 1 < sizeof(cn)) {
cn[k] = p[k];
k++;
}
cn[k] = '\0';
while (k > 0 && (cn[k - 1] == ' ' || cn[k - 1] == '\t'))
cn[--k] = '\0';
if (cert_pattern_match(cn, name)) {
*matched = 1;
snprintf(by, bn, "cn");
}
}
}
}
static void t_tls_hostname_check(mcp_conn *c, const mcp_json *args,
void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *name = mcp_arg_string(args, "name");
int port = mcp_arg_int(args, "port", 443);
char conn[320];
char reason[512];
char subject[512];
char sans[1024];
char matched_by[16];
int matched = 0;
int reached = 0;
mcp_buf b;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (name == NULL || *name == '\0')
name = target;
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_hostname_check", target, port))
return;
if (!apex_scope_check(name, port, reason, sizeof(reason))) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "name %s is outside the scope: %s", name,
reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
tls_conn_string(target, port, conn, sizeof(conn));
subject[0] = sans[0] = matched_by[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 *)name;
argv[k++] = "-showcerts";
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) {
mcp_buf pem;
mcp_buf_init(&pem);
if (extract_first_pem(p.out, &pem) == 0) {
char pem_path[APEX_PATH_FULL];
snprintf(pem_path, sizeof(pem_path),
"%s/hostname-%ld.pem",
g_cfg.evidence_dir, (long)getpid());
if (apex_write_file(pem_path, pem.p, pem.len,
0600) == 0) {
char *xargv[12];
int x = 0;
apex_proc xp;
xargv[x++] = "openssl";
xargv[x++] = "x509";
xargv[x++] = "-in";
xargv[x++] = pem_path;
xargv[x++] = "-noout";
xargv[x++] = "-subject";
xargv[x++] = "-ext";
xargv[x++] = "subjectAltName";
xargv[x] = NULL;
if (apex_run(xargv, 10000, 65536, &xp) == 0) {
if (xp.out != NULL) {
header_value(xp.out,
"subject=",
subject,
sizeof(subject));
cert_san_line(xp.out, sans,
sizeof(sans));
reached = 1;
}
apex_proc_free(&xp);
}
unlink(pem_path);
}
}
mcp_buf_free(&pem);
}
apex_proc_free(&p);
}
if (!reached) {
mcp_reply_error(c, "no certificate presented");
return;
}
cert_match_name(sans, subject, name, &matched, matched_by,
sizeof(matched_by));
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"name\":", port);
apex_json_str(&b, name);
mcp_buf_puts(&b, ",\"subject\":");
apex_json_str(&b, subject);
mcp_buf_puts(&b, ",\"san\":");
apex_json_str(&b, sans);
mcp_buf_printf(&b, ",\"matched\":%s,\"matched_by\":",
matched ? "true" : "false");
apex_json_str(&b, matched_by);
mcp_buf_puts(&b, "}");
apex_audit("tls_hostname_check", target, port, matched,
matched ? "the certificate covers the requested name"
: "the certificate does not cover the requested name",
name);
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 "
@@ -6048,6 +6299,17 @@ const mcp_tool TOOLS_PROTO[] = {
"\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}},"
"\"required\":[\"target\"]}",
t_tls_client_auth_probe },
{ "tls_hostname_check",
"Open one TLS connection with the name as SNI, read the subject and "
"subjectAltName, and check whether the certificate covers the name "
"(exact, one-label wildcard, or IP). SAN wins over CN. Gate: the target "
"and the name.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"name\":{\"type\":\"string\",\"description\":\"default: target\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}},"
"\"required\":[\"target\"]}",
t_tls_hostname_check },
};
const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]);
+1 -1
View File
@@ -21,7 +21,7 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 218
EXPECTED_TOOLS = 222
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.
+168 -2
View File
@@ -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("218 tools registered", len(tools) == 218, len(tools))
check("222 tools registered", len(tools) == 222, 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"]) == 218)
check("http tools/list", len(listing["result"]["tools"]) == 222)
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
@@ -10070,6 +10070,171 @@ shutil.rmtree(nft_good_root, ignore_errors=True)
shutil.rmtree(hsts_dir, ignore_errors=True)
shutil.rmtree(cfg17_home, ignore_errors=True)
print("\n== dnsmasq, nsswitch, Jenkins and TLS hostnames ==\n")
dm_root = tempfile.mkdtemp(prefix="apex-dm-")
os.makedirs(os.path.join(dm_root, "etc", "dnsmasq.d"))
dm_bad = os.path.join(dm_root, "etc", "dnsmasq.conf")
with open(dm_bad, "w") as f:
f.write("interface=0.0.0.0\n")
os.chmod(dm_bad, 0o666)
with open(os.path.join(dm_root, "etc", "dnsmasq.d", "extra.conf"), "w") as f:
f.write("cache-size=1000\n")
dm_good_root = tempfile.mkdtemp(prefix="apex-dmg-")
os.makedirs(os.path.join(dm_good_root, "etc"))
with open(os.path.join(dm_good_root, "etc", "dnsmasq.conf"), "w") as f:
f.write("interface=eth0\n")
f.write("bind-interfaces\n")
f.write("bogus-priv\n")
f.write("domain-needed\n")
ns_root = tempfile.mkdtemp(prefix="apex-ns-")
os.makedirs(os.path.join(ns_root, "etc"))
ns_bad = os.path.join(ns_root, "etc", "nsswitch.conf")
with open(ns_bad, "w") as f:
f.write("passwd: compat\n")
f.write("group: compat\n")
f.write("shadow: compat\n")
f.write("hosts: dns\n")
os.chmod(ns_bad, 0o666)
ns_good_root = tempfile.mkdtemp(prefix="apex-nsg-")
os.makedirs(os.path.join(ns_good_root, "etc"))
with open(os.path.join(ns_good_root, "etc", "nsswitch.conf"), "w") as f:
f.write("passwd: files sss\n")
f.write("group: files sss\n")
f.write("shadow: files sss\n")
f.write("hosts: files dns\n")
jk_root = tempfile.mkdtemp(prefix="apex-jk-")
os.makedirs(os.path.join(jk_root, "var", "lib", "jenkins"))
jk_bad = os.path.join(jk_root, "var", "lib", "jenkins", "config.xml")
with open(jk_bad, "w") as f:
f.write("<hudson>\n")
f.write(" <useSecurity>false</useSecurity>\n")
f.write(' <authorizationStrategy class="hudson.security.'
'AuthorizationStrategy$Unsecured"/>\n')
f.write(" <slaveAgentPort>50000</slaveAgentPort>\n")
f.write("</hudson>\n")
os.chmod(jk_bad, 0o666)
jk_good_root = tempfile.mkdtemp(prefix="apex-jkg-")
os.makedirs(os.path.join(jk_good_root, "var", "lib", "jenkins"))
with open(os.path.join(jk_good_root, "var", "lib", "jenkins",
"config.xml"), "w") as f:
f.write("<hudson>\n")
f.write(" <useSecurity>true</useSecurity>\n")
f.write(' <authorizationStrategy class="hudson.security.'
'GlobalMatrixAuthorizationStrategy"/>\n')
f.write(' <crumbIssuer class="hudson.security.csrf.'
'DefaultCrumbIssuer"/>\n')
f.write(" <slaveAgentPort>-1</slaveAgentPort>\n")
f.write("</hudson>\n")
hn_dir = tempfile.mkdtemp(prefix="apex-hn-")
hn_cert = os.path.join(hn_dir, "cert.pem")
hn_key = os.path.join(hn_dir, "key.pem")
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", hn_key, "-out", hn_cert, "-days", "2",
"-subj", "/CN=other.test",
"-addext", "subjectAltName=DNS:other.test,"
"DNS:*.wild.test,IP:127.0.0.1"],
check=True, capture_output=True)
hn_srv, hn_port = tls_server(hn_cert, hn_key)
cfg18_home = tempfile.mkdtemp(prefix="apex-cfg18-home-")
write_scope(cfg18_home, {"label": "cfg18", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_domain": ["other.test", "absent.test",
"foo.wild.test", "wild.test"],
"allow_port": [str(hn_port)]})
res, _ = run([
call(1, "dnsmasq_audit", root=dm_root),
call(2, "dnsmasq_audit", root=dm_good_root),
call(3, "nsswitch_audit", root=ns_root),
call(4, "nsswitch_audit", root=ns_good_root),
call(5, "jenkins_audit", root=jk_root),
call(6, "jenkins_audit", root=jk_good_root),
call(7, "tls_hostname_check", target="127.0.0.1", port=hn_port,
name="other.test"),
call(8, "tls_hostname_check", target="127.0.0.1", port=hn_port,
name="absent.test"),
call(9, "tls_hostname_check", target="127.0.0.1", port=hn_port,
name="foo.wild.test"),
call(10, "tls_hostname_check", target="127.0.0.1", port=hn_port,
name="wild.test"),
call(11, "tls_hostname_check", target="127.0.0.1", port=hn_port,
name="127.0.0.1"),
call(12, "tls_hostname_check", target="127.0.0.1", port=hn_port,
name="evil.test"),
call(13, "dnsmasq_audit", root="/nonexistent-dm"),
call(14, "nsswitch_audit", root="/nonexistent-ns"),
call(15, "jenkins_audit", root="/nonexistent-jk"),
], home=cfg18_home)
by_id = {r.get("id"): r for r in res}
dm = json.loads(text(by_id[1]))
dm_kinds = {f["id"] for f in dm["findings"]}
check("dnsmasq_audit flags a wildcard listener and weak defaults",
{"world-writable", "all-interfaces", "no-bogus-priv",
"no-domain-needed"} <= dm_kinds and dm["restricted"] is False, dm)
dm_good = json.loads(text(by_id[2]))
check("dnsmasq_audit accepts a restricted resolver",
dm_good["findings_count"] == 0 and dm_good["restricted"] is True and
dm_good["bind_interfaces"] is True, dm_good)
ns = json.loads(text(by_id[3]))
ns_kinds = {f["id"] for f in ns["findings"]}
check("nsswitch_audit flags compat, ldap and hosts order",
{"world-writable", "nis-compat", "no-files"} <= ns_kinds and
ns["nis"] is True and ns["hosts_files"] is False, ns)
ns_good = json.loads(text(by_id[4]))
check("nsswitch_audit accepts files with sss",
ns_good["findings_count"] == 0 and ns_good["nis"] is False and
ns_good["direct_ldap"] is False, ns_good)
jk = json.loads(text(by_id[5]))
jk_kinds = {f["id"] for f in jk["findings"]}
check("jenkins_audit flags no security, no CSRF and a fixed port",
{"world-writable", "no-security", "unsecured-authz", "no-csrf",
"agent-port"} <= jk_kinds and jk["security"] is False and
jk["agent_port"] == 50000, jk)
jk_good = json.loads(text(by_id[6]))
check("jenkins_audit accepts secured config",
jk_good["findings_count"] == 0 and jk_good["security"] is True and
jk_good["csrf"] is True, jk_good)
hn_exact = json.loads(text(by_id[7]))
check("tls_hostname_check matches a SAN name",
hn_exact["matched"] is True and hn_exact["matched_by"] == "san",
hn_exact)
hn_absent = json.loads(text(by_id[8]))
check("tls_hostname_check reports a missing name",
hn_absent["matched"] is False and hn_absent["matched_by"] == "",
hn_absent)
hn_wild = json.loads(text(by_id[9]))
check("tls_hostname_check matches a one-label wildcard",
hn_wild["matched"] is True and hn_wild["matched_by"] == "san",
hn_wild)
hn_apex = json.loads(text(by_id[10]))
check("tls_hostname_check does not let a wildcard cover the apex",
hn_apex["matched"] is False, hn_apex)
hn_ip = json.loads(text(by_id[11]))
check("tls_hostname_check matches an IP SAN",
hn_ip["matched"] is True and "IP Address:127.0.0.1" in hn_ip["san"],
hn_ip)
check("tls_hostname_check refuses an out-of-scope name", err(by_id[12]),
text(by_id[12]))
check("dnsmasq_audit reports a missing config", err(by_id[13]),
text(by_id[13]))
check("nsswitch_audit reports a missing config", err(by_id[14]),
text(by_id[14]))
check("jenkins_audit reports a missing config", err(by_id[15]),
text(by_id[15]))
hn_srv.close()
shutil.rmtree(dm_root, ignore_errors=True)
shutil.rmtree(dm_good_root, ignore_errors=True)
shutil.rmtree(ns_root, ignore_errors=True)
shutil.rmtree(ns_good_root, ignore_errors=True)
shutil.rmtree(jk_root, ignore_errors=True)
shutil.rmtree(jk_good_root, ignore_errors=True)
shutil.rmtree(hn_dir, ignore_errors=True)
shutil.rmtree(cfg18_home, ignore_errors=True)
print("\n== esp32 tools ==")
@@ -10077,6 +10242,7 @@ print("\n== esp32 tools ==")
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})
esp_m, esp_s = pty.openpty()