apex-twin 1.17.0: kernel, sudoers, CSRF and auditd audits

Red:
- csrf_audit: fetch one page, list its forms (action, method, input count) and
  flag forms without an input whose name contains csrf, token or nonce; the
  page is evidence.

Blue:
- kernel_hardening: 12 sysctls (ASLR, kptr_restrict, dmesg_restrict,
  perf_event_paranoid, unprivileged_bpf_disabled, ptrace_scope,
  protected_hardlinks/symlinks, suid_dumpable, modules_disabled,
  bpf_jit_harden) plus core_pattern, scored with per-check findings; optional
  root prefix.
- sudoers_audit: /etc/sudoers and /etc/sudoers.d, flagging NOPASSWD,
  !authenticate, broad ALL=(ALL), direct user rules and world-writable files.
- auditd_audit: event type counts, AVC denials, failed auth, top exe paths and
  keys from an auditd log under /var/log or the state directory.

Fixed evidence ordering: sort by mtime and nanoseconds before the filename, so
two blobs written in the same second no longer flip (a flake the coverage build
exposed).

Tests with a sysctl tree, a sudoers tree, a two-form page and an auditd log.
663 checks, ASan suite green, analyze clean, release-check green including
distcheck 1.17.0.
This commit is contained in:
lotherk committed 2026-11-21 15:38:56 +00:00
1 parent 4018eb0ea4
commit 816fd0fb57
10 files changed
+819 -20

No files matched your search

+23 -1
View File
@@ -8,7 +8,29 @@ fields, and state from an older version is read by a newer one.
There are no git tags. The hash next to a version is the commit that introduced
it; the current entry is the commit that adds this section.
## 1.16.0 — 2026-11-21 — this change
## 1.17.0 — 2026-11-21 — this change
- **CSRF** (`csrf_audit`): fetch one page, list its forms (action, method,
input count) and flag forms without an input whose name contains csrf,
token or nonce; the page is saved as evidence.
- **Kernel** (`kernel_hardening`): reads 12 sysctls (ASLR, kptr_restrict,
dmesg_restrict, perf_event_paranoid, unprivileged_bpf_disabled, ptrace_scope,
protected_hardlinks/symlinks, suid_dumpable, modules_disabled,
bpf_jit_harden) plus core_pattern, scores them and reports each weak value;
optional root prefix for a mounted image.
- **Sudoers** (`sudoers_audit`): /etc/sudoers and /etc/sudoers.d, flagging
NOPASSWD, !authenticate, broad ALL=(ALL), direct user rules and
world-writable files.
- **auditd** (`auditd_audit`): event type counts, AVC denials, failed
USER_AUTH/USER_LOGIN/USER_ACCT, top exe paths and audit keys from an auditd
log under /var/log or the state directory.
- Fixed evidence ordering: sort by mtime and nanoseconds before the filename,
so two blobs written in the same second no longer flip order (a flake the
coverage build exposed).
- Tests with a sysctl tree, a sudoers tree, a two-form page and an auditd log.
663 checks. Coverage 79.7%.
## 1.16.0 — 2026-11-21 — 4018eb0
- **SNMP walk** (`snmp_walk`): GETNEXT over 1.3.6.1.2.1.1 for up to 30 steps,
decoding the returned OID and its value (string, integer, timeticks, counter,
+16 -8
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.
**112 tools · 649 end-to-end checks · 340 fuzz cases · 79.5% line coverage · ~502 KiB**
**116 tools · 663 end-to-end checks · 340 fuzz cases · 79.7% line coverage · ~519 KiB**
```
$ ./apex-twin --check
{"version":"1.16.0","tools":112,...,"scope":{"loaded":true,...}}
{"version":"1.17.0","tools":116,...,"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 (112)
## Tools (116)
### Scope and bookkeeping
@@ -273,6 +273,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `snmp_walk` | GETNEXT over the system group: OID, name and decoded value (string, integer, timeticks, OID) |
| `ldap_search` | Anonymous subtree search (size limit 20) from namingContexts; DNs plus cn/uid/mail |
| `openapi_discovery` | Six usual spec paths: OpenAPI/Swagger version, title and path count, evidence |
| `csrf_audit` | Forms on one page: action, method, input count and missing CSRF token fields |
| `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 |
@@ -311,6 +312,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `mount_audit` | Mount table hardening: temp/shm mounts missing nosuid/nodev/noexec, home/media/mnt missing nosuid/nodev |
| `firewall_audit` | `nft list ruleset` / `iptables-save` (or saved dump): chain/rule counts and ACCEPT default policies |
| `systemd_audit` | Units: ExecStart in /tmp, missing User= (root), world-writable files, .wants links |
| `kernel_hardening` | Sysctl hardening set (ASLR, kptr, dmesg, perf, BPF, ptrace, symlinks, core_pattern) with score |
| `sudoers_audit` | NOPASSWD, !authenticate, broad ALL, direct user rules, world-writable sudoers |
| `auditd_audit` | auditd type counts, AVC denials, failed auth, top exe paths and keys |
### ESP32
@@ -523,6 +527,9 @@ The full threat model, trust boundaries and a hardening checklist are in
| SNMP walk | 30 GETNEXT steps, 1.8 s per step |
| LDAP search | 20 entries, 30 messages, anonymous |
| Systemd audit | 500 units; reads unit files only |
| Kernel hardening | 12 sysctls; root prefix for mounted images |
| Sudoers audit | 200 files, 100 findings; read-only |
| auditd | 5000 lines; path limited to /var/log or the state dir |
---
@@ -533,7 +540,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 649 end-to-end checks
make test # version check + gate audit + 663 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
@@ -642,7 +649,7 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery,
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
snmp_walk, ldap_search, openapi_discovery, csrf_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,
@@ -684,7 +691,7 @@ examples/ scope.json
## Status
1.16.0. Built and run: 112 tools, 649 checks, 340 fuzz cases and 79.5% line
1.17.0. Built and run: 116 tools, 663 checks, 340 fuzz cases and 79.7% 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
@@ -717,8 +724,9 @@ capability baseline; 1.12 added Docker, Elasticsearch and IMAP checks plus a
kernel module/taint audit; 1.13 added POP3, SIP and Telnet checks plus package
integrity verification; 1.14 added offline ESP32 flash analysis and a mount
audit; 1.15 added HTTP method, WebSocket and IKEv2 checks plus a firewall audit; 1.16
added SNMP walk, LDAP search and OpenAPI discovery plus a systemd audit, again
without changing an existing tool or file format.
added SNMP walk, LDAP search and OpenAPI discovery plus a systemd audit; 1.17
added CSRF, kernel, sudoers and auditd checks and fixed evidence ordering for
same-second files, again without changing an existing file format.
Not yet wired into a fleet router, and there is no TLS interception.
+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.16.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.17.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.
- **Form and local audits are reads.** `csrf_audit` fetches one page and parses
its forms; `kernel_hardening`, `sudoers_audit` and `auditd_audit` read local
files, with the audit log restricted to /var/log and the state directory.
- **Directory and walk probes are bounded reads.** `snmp_walk` issues at most
30 GETNEXT requests for the system group; `ldap_search` binds anonymously and
stops after 20 entries; `openapi_discovery` fetches six documents;
+6 -5
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.16.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.17.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -43,11 +43,12 @@ 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), defensive audits (hardening_audit, log_audit,
ioc_scan, web_log_audit, detect_rules, integrity_baseline, mitre_map,
process_snapshot, persistence_audit, net_baseline, ssh_key_audit,
ldap_search, openapi_discovery, csrf_audit), defensive audits (hardening_audit,
log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline,
mitre_map, process_snapshot, persistence_audit, net_baseline, ssh_key_audit,
suid_baseline, cap_baseline, module_audit, package_integrity, mount_audit,
firewall_audit, systemd_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash,
firewall_audit, systemd_audit, kernel_hardening, sudoers_audit,
auditd_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash,
esp_partition_table, esp_nvs_parse, firmware_scan).
.SH MODES
.TP
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.16.0"
#define APEX_VERSION "1.17.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+7 -1
View File
@@ -321,6 +321,7 @@ typedef struct {
char name[256];
long bytes;
time_t mtime;
long nsec;
} evidence_item;
static int evidence_cmp(const void *a, const void *b)
@@ -328,7 +329,11 @@ static int evidence_cmp(const void *a, const void *b)
const evidence_item *x = a;
const evidence_item *y = b;
/* names start with a UTC timestamp: descending is newest first */
/* newest first; the name only breaks exact ties */
if (x->mtime != y->mtime)
return x->mtime < y->mtime ? 1 : -1;
if (x->nsec != y->nsec)
return x->nsec < y->nsec ? 1 : -1;
return strcmp(y->name, x->name);
}
@@ -363,6 +368,7 @@ int apex_evidence_list(mcp_buf *b, int limit)
ent->d_name);
items[count].bytes = (long)st.st_size;
items[count].mtime = st.st_mtime;
items[count].nsec = (long)st.st_mtim.tv_nsec;
count++;
}
closedir(d);
+433
View File
@@ -3916,6 +3916,411 @@ static void t_systemd_audit(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&findings);
}
/* ------------------------------------------------------------ kernel_hardening */
typedef struct {
const char *id;
const char *path;
const char *expect;
const char *severity;
int kind; /* 0 exact, 1 at-least, 2 not-pipe */
int want;
} kh_check;
static const kh_check KH_CHECKS[] = {
{ "aslr", "/proc/sys/kernel/randomize_va_space", "2", "high", 0, 2 },
{ "kptr-restrict", "/proc/sys/kernel/kptr_restrict", "1 or 2", "medium", 1, 1 },
{ "dmesg-restrict", "/proc/sys/kernel/dmesg_restrict", "1", "medium", 0, 1 },
{ "perf-paranoid", "/proc/sys/kernel/perf_event_paranoid", ">= 2", "medium", 1, 2 },
{ "unprivileged-bpf", "/proc/sys/kernel/unprivileged_bpf_disabled", "1", "medium", 1, 1 },
{ "ptrace-scope", "/proc/sys/kernel/yama/ptrace_scope", ">= 1", "medium", 1, 1 },
{ "protected-hardlinks", "/proc/sys/fs/protected_hardlinks", "1", "medium", 0, 1 },
{ "protected-symlinks", "/proc/sys/fs/protected_symlinks", "1", "medium", 0, 1 },
{ "suid-dumpable", "/proc/sys/fs/suid_dumpable", "0", "high", 0, 0 },
{ "modules-disabled", "/proc/sys/kernel/modules_disabled", "1", "low", 0, 1 },
{ "bpf-jit-harden", "/proc/sys/net/core/bpf_jit_harden", "1 or 2", "low", 1, 1 },
{ "core-pattern", "/proc/sys/kernel/core_pattern", "no pipe", "high", 2, 0 },
};
static void t_kernel_hardening(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
int limit = mcp_arg_int(args, "limit", 64);
char base[512];
size_t bl;
char path[1024];
mcp_buf b;
mcp_buf findings;
int first = 1;
int count = 0;
int score = 100;
int i;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) >= sizeof(base) - 2) {
mcp_reply_error(c, "root path too long");
return;
}
snprintf(base, sizeof(base), "%s", root);
bl = strlen(base);
while (bl > 0 && base[bl - 1] == '/')
base[--bl] = '\0';
if (limit <= 0 || limit > 64)
limit = 64;
mcp_buf_init(&findings);
for (i = 0; i < (int)(sizeof(KH_CHECKS) / sizeof(KH_CHECKS[0])) &&
i < limit; i++) {
char value[128];
int v;
int ok = 0;
snprintf(path, sizeof(path), "%s%s", base, KH_CHECKS[i].path);
if (read_text(path, value, sizeof(value)) <= 0)
continue;
trim_eol(value);
v = atoi(value);
if (KH_CHECKS[i].kind == 0)
ok = v == KH_CHECKS[i].want;
else if (KH_CHECKS[i].kind == 1)
ok = v >= KH_CHECKS[i].want;
else
ok = value[0] != '|';
if (ok)
continue;
count++;
if (count >= 2)
score -= 8;
else
score -= 10;
if (!first)
mcp_buf_puts(&findings, ",");
first = 0;
mcp_buf_puts(&findings, "{\"id\":");
apex_json_str(&findings, KH_CHECKS[i].id);
mcp_buf_puts(&findings, ",\"severity\":");
apex_json_str(&findings, KH_CHECKS[i].severity);
mcp_buf_puts(&findings, ",\"value\":");
apex_json_str(&findings, value);
mcp_buf_puts(&findings, ",\"expected\":");
apex_json_str(&findings, KH_CHECKS[i].expect);
mcp_buf_puts(&findings, "}");
}
if (score < 0)
score = 0;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, base);
mcp_buf_printf(&b, ",\"score\":%d,\"findings_count\":%d,\"findings\":[",
score, 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);
}
/* -------------------------------------------------------------- sudoers_audit */
typedef struct {
mcp_buf *b;
int first;
int count;
int files;
int rules;
} sudo_ctx;
static void sudo_finding(sudo_ctx *ctx, const char *path, int line,
const char *kind, const char *severity,
const char *detail)
{
if (ctx->count >= 100)
return;
if (!ctx->first)
mcp_buf_puts(ctx->b, ",");
ctx->first = 0;
ctx->count++;
mcp_buf_puts(ctx->b, "{\"path\":");
apex_json_str(ctx->b, path);
mcp_buf_printf(ctx->b, ",\"line\":%d,\"kind\":", line);
apex_json_str(ctx->b, kind);
mcp_buf_puts(ctx->b, ",\"severity\":");
apex_json_str(ctx->b, severity);
mcp_buf_puts(ctx->b, ",\"detail\":");
apex_json_str(ctx->b, detail);
mcp_buf_puts(ctx->b, "}");
}
static int sudo_direct_user(const char *line)
{
static const char *prefixes[] = {
"Defaults", "User_Alias", "Runas_Alias", "Host_Alias",
"Cmnd_Alias", "#include", "#includedir", "%", "+", NULL
};
int i;
if (line[0] == '#' || line[0] == '\0')
return 0;
for (i = 0; prefixes[i] != NULL; i++)
if (strncmp(line, prefixes[i], strlen(prefixes[i])) == 0)
return 0;
return isalpha((unsigned char)line[0]) != 0;
}
static void sudo_scan_file(sudo_ctx *ctx, const char *path)
{
FILE *f;
struct stat st;
char *line = NULL;
size_t cap = 0;
int lineno = 0;
if (ctx->files >= 200)
return;
f = fopen(path, "rb");
if (f == NULL)
return;
ctx->files++;
if (stat(path, &st) == 0 && (st.st_mode & 0002) != 0)
sudo_finding(ctx, path, 0, "world-writable", "high",
"sudoers file is writable by anyone");
while (getline(&line, &cap, f) >= 0) {
char *t = line;
size_t n;
lineno++;
while (*t == ' ' || *t == '\t')
t++;
n = strlen(t);
while (n > 0 && (t[n - 1] == '\n' || t[n - 1] == '\r'))
t[--n] = '\0';
if (t[0] == '\0' || t[0] == '#')
continue;
ctx->rules++;
if (strstr(t, "NOPASSWD") != NULL)
sudo_finding(ctx, path, lineno, "nopasswd", "medium",
"rule allows running sudo without a password");
if (strstr(t, "!authenticate") != NULL)
sudo_finding(ctx, path, lineno, "no-authenticate", "high",
"rule disables authentication");
if (strstr(t, "ALL=(ALL") != NULL &&
strstr(t, "NOPASSWD") == NULL)
sudo_finding(ctx, path, lineno, "broad-all", "medium",
"rule grants every command as every user");
if (sudo_direct_user(t) && strstr(t, "ALL") != NULL)
sudo_finding(ctx, path, lineno, "direct-user", "low",
"rule names a user directly instead of an alias");
}
free(line);
fclose(f);
}
static void t_sudoers_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
char base[512];
char path[1024];
size_t bl;
mcp_buf b;
mcp_buf findings;
sudo_ctx ctx;
DIR *d;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) >= sizeof(base) - 2) {
mcp_reply_error(c, "root path too long");
return;
}
snprintf(base, sizeof(base), "%s", root);
bl = strlen(base);
while (bl > 0 && base[bl - 1] == '/')
base[--bl] = '\0';
mcp_buf_init(&findings);
memset(&ctx, 0, sizeof(ctx));
ctx.b = &findings;
ctx.first = 1;
snprintf(path, sizeof(path), "%s/etc/sudoers", base);
sudo_scan_file(&ctx, path);
snprintf(path, sizeof(path), "%s/etc/sudoers.d", base);
d = opendir(path);
if (d != NULL) {
struct dirent *ent;
while ((ent = readdir(d)) != NULL) {
char full[1024];
struct stat st;
if (ent->d_name[0] == '.')
continue;
snprintf(full, sizeof(full), "%.800s/%.160s", path,
ent->d_name);
if (stat(full, &st) != 0 || !S_ISREG(st.st_mode))
continue;
sudo_scan_file(&ctx, full);
}
closedir(d);
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, base);
mcp_buf_printf(&b, ",\"files\":%d,\"rules\":%d,\"findings_count\":%d,"
"\"findings\":[", ctx.files, ctx.rules, ctx.count);
if (findings.p != NULL)
mcp_buf_add(&b, findings.p, findings.len);
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
mcp_buf_free(&findings);
}
/* --------------------------------------------------------------- auditd_audit */
typedef struct {
char name[160];
int count;
} audit_cnt;
static void audit_count(audit_cnt *arr, int *n, int max, const char *name)
{
int i;
if (name == NULL || *name == '\0')
return;
for (i = 0; i < *n; i++)
if (strcmp(arr[i].name, name) == 0) {
arr[i].count++;
return;
}
if (*n < max) {
snprintf(arr[*n].name, sizeof(arr[0].name), "%.120s", name);
arr[*n].count = 1;
(*n)++;
}
}
static int audit_value(const char *line, const char *key, char *out, size_t n)
{
const char *p = strstr(line, key);
size_t w = 0;
out[0] = '\0';
if (p == NULL)
return 0;
p += strlen(key);
if (*p == '"') {
p++;
while (*p != '\0' && *p != '"' && w + 1 < n)
out[w++] = *p++;
} else {
while (*p != '\0' && *p != ' ' && *p != '\n' && *p != '\r' &&
w + 1 < n)
out[w++] = *p++;
}
out[w] = '\0';
return w > 0;
}
static void audit_count_json(mcp_buf *b, const audit_cnt *arr, int n,
const char *key)
{
int i;
mcp_buf_puts(b, "\"");
mcp_buf_puts(b, key);
mcp_buf_puts(b, "\":[");
for (i = 0; i < n; i++) {
if (i > 0)
mcp_buf_puts(b, ",");
mcp_buf_puts(b, "{\"name\":");
apex_json_str(b, arr[i].name);
mcp_buf_printf(b, ",\"count\":%d}", arr[i].count);
}
mcp_buf_puts(b, "]");
}
static void t_auditd_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
int limit = mcp_arg_int(args, "limit", 5000);
FILE *f;
char *line = NULL;
size_t cap = 0;
int lines = 0;
int avc = 0;
int failed_auth = 0;
audit_cnt types[24];
audit_cnt exes[12];
audit_cnt keys[12];
int ntypes = 0;
int nexes = 0;
int nkeys = 0;
mcp_buf b;
(void)user;
if (path == NULL || *path == '\0')
path = "/var/log/audit/audit.log";
if (!allowed_log_path(path)) {
mcp_reply_error(c, "path must be under /var/log/ or the state dir");
return;
}
if (limit <= 0 || limit > 50000)
limit = 5000;
memset(types, 0, sizeof(types));
memset(exes, 0, sizeof(exes));
memset(keys, 0, sizeof(keys));
f = fopen(path, "rb");
if (f == NULL) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot read %s: %s", path, strerror(errno));
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
while (lines < limit && getline(&line, &cap, f) >= 0) {
char type[64];
char res[32];
char exe[160];
char key[160];
lines++;
if (!audit_value(line, "type=", type, sizeof(type)))
snprintf(type, sizeof(type), "%s", "UNKNOWN");
audit_count(types, &ntypes, 24, type);
if (strcmp(type, "AVC") == 0)
avc++;
if (audit_value(line, "res=", res, sizeof(res)) &&
strcmp(res, "failed") == 0 &&
(strncmp(type, "USER_AUTH", 9) == 0 ||
strncmp(type, "USER_LOGIN", 10) == 0 ||
strncmp(type, "USER_ACCT", 9) == 0))
failed_auth++;
if (audit_value(line, "exe=", exe, sizeof(exe)))
audit_count(exes, &nexes, 12, exe);
if (audit_value(line, "key=", key, sizeof(key)) &&
strcmp(key, "(null)") != 0)
audit_count(keys, &nkeys, 12, key);
}
free(line);
fclose(f);
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"lines\":%d,\"avc_denials\":%d,"
"\"failed_auth\":%d,", lines, avc, failed_auth);
audit_count_json(&b, types, ntypes, "types");
mcp_buf_puts(&b, ",");
audit_count_json(&b, exes, nexes, "top_exe");
mcp_buf_puts(&b, ",");
audit_count_json(&b, keys, nkeys, "keys");
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_BLUE[] = {
{ "hardening_audit",
"Read-only posture audit of the local host: sshd_config (root login, "
@@ -4144,6 +4549,34 @@ const mcp_tool TOOLS_BLUE[] = {
"\"limit\":{\"type\":\"integer\",\"description\":\"max units, default "
"500\"}}}",
t_systemd_audit },
{ "kernel_hardening",
"Read the kernel hardening sysctls (ASLR, kptr_restrict, dmesg_restrict, "
"perf_event_paranoid, unprivileged_bpf_disabled, ptrace_scope, "
"protected_hardlinks/symlinks, suid_dumpable, modules_disabled, "
"bpf_jit_harden) and core_pattern, score them and report every weak "
"value. The optional root prefix audits a mounted image. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"checks, default 64\"}}}",
t_kernel_hardening },
{ "sudoers_audit",
"Parse /etc/sudoers and /etc/sudoers.d (optional root prefix) and flag "
"NOPASSWD, !authenticate, broad ALL=(ALL) grants, direct user rules and "
"world-writable sudoers files, with file and line. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_sudoers_audit },
{ "auditd_audit",
"Summarise an auditd log: lines read, event type counts, AVC denials, "
"failed USER_AUTH/USER_LOGIN/USER_ACCT events, the most frequent exe "
"paths and audit keys. Read-only; the path must be under /var/log/ or the "
"state directory.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"default "
"/var/log/audit/audit.log\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"lines, default "
"5000\"}}}",
t_auditd_audit },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+177
View File
@@ -3189,6 +3189,171 @@ static void t_openapi_discovery(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
}
/* ----------------------------------------------------------------- csrf_audit */
static const char *find_ci(const char *hay, const char *end, const char *needle)
{
size_t nl = strlen(needle);
const char *p;
for (p = hay; p + nl <= end; p++)
if (strncasecmp(p, needle, nl) == 0)
return p;
return NULL;
}
static void html_attr(const char *start, const char *end, const char *name,
char *out, size_t n)
{
size_t nl = strlen(name);
const char *p = start;
size_t w = 0;
out[0] = '\0';
while (p < end) {
const char *hit = find_ci(p, end, name);
if (hit == NULL)
return;
p = hit + nl;
if (p >= end || *p != '=')
continue;
p++;
while (p < end && (*p == ' ' || *p == '\t'))
p++;
if (p < end && (*p == '"' || *p == '\'')) {
char quote = *p++;
while (p < end && *p != quote && w + 1 < n)
out[w++] = *p++;
out[w] = '\0';
return;
}
while (p < end && *p != ' ' && *p != '\t' && *p != '>' &&
w + 1 < n)
out[w++] = *p++;
out[w] = '\0';
return;
}
}
static void t_csrf_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", apex_looks_tls(port));
char status[256];
char *resp = NULL;
size_t len = 0;
int code = 0;
mcp_buf b;
int first = 1;
int forms = 0;
int tokenless = 0;
char *evidence = NULL;
const char *p;
const char *end;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (path[0] != '/') {
mcp_reply_error(c, "path must start with /");
return;
}
if (!gated(c, "csrf_audit", target, port))
return;
status[0] = '\0';
if (apex_http_once(target, port, tls, "GET", path, NULL, NULL, 8000,
&resp, &len, status, sizeof(status)) != 0) {
mcp_reply_error(c, "cannot fetch the page");
return;
}
code = apex_status_code(status);
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port);
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"status\":%d,\"forms\":[", code);
end = resp + len;
p = resp;
while (forms < 20) {
const char *fs = find_ci(p, end, "<form");
const char *fe;
char action[256];
char method[16];
int inputs = 0;
int has_token = 0;
const char *ip;
if (fs == NULL)
break;
fe = find_ci(fs, end, "</form>");
if (fe == NULL)
fe = end;
html_attr(fs, fe, "action", action, sizeof(action));
html_attr(fs, fe, "method", method, sizeof(method));
if (method[0] == '\0')
snprintf(method, sizeof(method), "%s", "GET");
ip = fs;
while (ip < fe) {
const char *in = find_ci(ip, fe, "<input");
if (in == NULL)
break;
inputs++;
{
const char *ie = find_ci(in, fe, ">");
char name[128];
if (ie == NULL)
ie = fe;
html_attr(in, ie, "name", name, sizeof(name));
if (strcasestr(name, "csrf") != NULL ||
strcasestr(name, "token") != NULL ||
strcasestr(name, "nonce") != NULL)
has_token = 1;
ip = ie + 1;
}
}
forms++;
if (!has_token)
tokenless++;
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"action\":");
apex_json_str(&b, action);
mcp_buf_puts(&b, ",\"method\":");
apex_json_str(&b, method);
mcp_buf_printf(&b, ",\"inputs\":%d,\"has_token\":%s}", inputs,
has_token ? "true" : "false");
p = fe;
}
if (tokenless > 0)
evidence = apex_evidence_save("csrf", resp, len);
mcp_buf_printf(&b, "],\"form_count\":%d,\"tokenless\":%d,\"evidence\":",
forms, tokenless);
if (evidence != NULL)
apex_json_str(&b, evidence);
else
mcp_buf_puts(&b, "null");
mcp_buf_puts(&b, "}");
apex_audit("csrf_audit", target, port, tokenless == 0,
tokenless == 0 ? "forms carry a token"
: "forms without a CSRF token", path);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(evidence);
free(resp);
}
const mcp_tool TOOLS_RED[] = {
{ "vuln_check",
"Non-destructive verification of exposed artifacts on one web target: "
@@ -3474,6 +3639,18 @@ const mcp_tool TOOLS_RED[] = {
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_openapi_discovery },
{ "csrf_audit",
"Fetch one page, list its forms (action, method, input count) and flag the "
"ones without an input whose name contains csrf, token or nonce. The page "
"is saved as evidence when a tokenless form is found. One GET. Gate: the "
"target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_csrf_audit },
};
const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[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 = 112
EXPECTED_TOOLS = 116
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.
+151 -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("112 tools registered", len(tools) == 112, len(tools))
check("116 tools registered", len(tools) == 116, 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"]) == 112)
check("http tools/list", len(listing["result"]["tools"]) == 116)
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
@@ -5163,6 +5163,155 @@ openapi_srv.server_close()
shutil.rmtree(sd_root, ignore_errors=True)
shutil.rmtree(deep_home2, ignore_errors=True)
print("\n== kernel, sudoers, CSRF and auditd ==")
def write_sysctl(root, rel, value):
path = os.path.join(root, rel)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(value + "\n")
kh_root = tempfile.mkdtemp(prefix="apex-kh-")
write_sysctl(kh_root, "proc/sys/kernel/randomize_va_space", "0")
write_sysctl(kh_root, "proc/sys/kernel/kptr_restrict", "1")
write_sysctl(kh_root, "proc/sys/kernel/dmesg_restrict", "0")
write_sysctl(kh_root, "proc/sys/kernel/perf_event_paranoid", "3")
write_sysctl(kh_root, "proc/sys/kernel/unprivileged_bpf_disabled", "1")
write_sysctl(kh_root, "proc/sys/kernel/yama/ptrace_scope", "0")
write_sysctl(kh_root, "proc/sys/fs/protected_hardlinks", "1")
write_sysctl(kh_root, "proc/sys/fs/protected_symlinks", "1")
write_sysctl(kh_root, "proc/sys/fs/suid_dumpable", "2")
write_sysctl(kh_root, "proc/sys/kernel/modules_disabled", "0")
write_sysctl(kh_root, "proc/sys/net/core/bpf_jit_harden", "0")
write_sysctl(kh_root, "proc/sys/kernel/core_pattern",
"|/usr/lib/systemd/systemd-coredump %P")
sudo_root = tempfile.mkdtemp(prefix="apex-sudo-")
os.makedirs(os.path.join(sudo_root, "etc", "sudoers.d"))
with open(os.path.join(sudo_root, "etc", "sudoers"), "w") as f:
f.write("Defaults env_reset\n")
f.write("root ALL=(ALL:ALL) ALL\n")
f.write("alice ALL=(ALL) NOPASSWD: ALL\n")
extra = os.path.join(sudo_root, "etc", "sudoers.d", "extra")
with open(extra, "w") as f:
f.write("%wheel ALL=(ALL) ALL\n")
world_sudo = os.path.join(sudo_root, "etc", "sudoers.d", "world")
with open(world_sudo, "w") as f:
f.write("bob ALL=(ALL) ALL\n")
os.chmod(world_sudo, 0o666)
class _CsrfHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
if path == "/form":
body = (
'<html><form action="/login" method="POST">'
'<input name="user">'
'<input type="hidden" name="csrf_token" value="x">'
'</form>'
'<form action="/comment">'
'<input name="text"><input type="submit" value="go">'
'</form></html>'
).encode()
elif path == "/safe":
body = ('<form action="/login" method="POST">'
'<input name="csrf" value="y"></form>').encode()
else:
body = b"<html>no forms</html>"
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
csrf_srv = http.server.HTTPServer(("127.0.0.1", 0), _CsrfHandler)
csrf_port = csrf_srv.server_address[1]
threading.Thread(target=csrf_srv.serve_forever, daemon=True).start()
sec_home2 = tempfile.mkdtemp(prefix="apex-sec2-")
audit_log = os.path.join(sec_home2, "audit-fixture.log")
with open(audit_log, "w") as f:
f.write('type=SYSCALL msg=audit(1): exe="/usr/bin/sudo" key="sudo"\n')
f.write('type=AVC msg=audit(2): avc: denied { read } '
'exe="/usr/sbin/sshd" key="denied"\n')
f.write('type=USER_AUTH msg=audit(3): res=failed exe="/usr/bin/login"\n')
f.write('type=USER_AUTH msg=audit(4): res=success exe="/usr/bin/login"\n')
write_scope(sec_home2, {"label": "sec2", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(csrf_port)]})
res, _ = run([
call(1, "kernel_hardening", root=kh_root),
call(2, "sudoers_audit", root=sudo_root),
call(3, "csrf_audit", target="127.0.0.1", port=csrf_port, path="/form",
tls=False),
call(4, "csrf_audit", target="127.0.0.1", port=csrf_port, path="/safe",
tls=False),
call(5, "auditd_audit", path=audit_log),
call(6, "csrf_audit", target="198.51.100.9", port=80, path="/form"),
call(7, "kernel_hardening", root="/nonexistent-kh"),
call(8, "sudoers_audit", root="/nonexistent-sudo"),
], home=sec_home2)
by_id = {r.get("id"): r for r in res}
kh = json.loads(text(by_id[1]))
ids = {f["id"] for f in kh["findings"]}
check("kernel_hardening flags the weak sysctls",
kh["findings_count"] == 7 and
{"aslr", "dmesg-restrict", "ptrace-scope", "suid-dumpable",
"modules-disabled", "bpf-jit-harden", "core-pattern"} == ids, kh)
check("kernel_hardening scores the findings", kh["score"] == 42, kh)
sudo = json.loads(text(by_id[2]))
skinds = [f["kind"] for f in sudo["findings"]]
check("sudoers_audit reads both files and the rules",
sudo["files"] == 3 and sudo["rules"] == 5, sudo)
check("sudoers_audit flags NOPASSWD and broad grants",
skinds.count("nopasswd") == 1 and skinds.count("broad-all") == 3,
skinds)
check("sudoers_audit flags direct users and world-writable files",
skinds.count("direct-user") == 3 and
skinds.count("world-writable") == 1, skinds)
csrf = json.loads(text(by_id[3]))
check("csrf_audit lists the forms and finds the tokenless one",
csrf["form_count"] == 2 and csrf["tokenless"] == 1 and
csrf["forms"][0]["has_token"] is True and
csrf["forms"][1]["has_token"] is False, csrf)
check("csrf_audit keeps the page as evidence",
csrf["evidence"] and os.path.isfile(csrf["evidence"]), csrf)
csrf_safe = json.loads(text(by_id[4]))
check("csrf_audit accepts a page with tokens",
csrf_safe["form_count"] == 1 and csrf_safe["tokenless"] == 0, csrf_safe)
audit = json.loads(text(by_id[5]))
types = {t["name"]: t["count"] for t in audit["types"]}
check("auditd_audit counts the event types",
audit["lines"] == 4 and types.get("AVC") == 1 and
types.get("USER_AUTH") == 2, audit)
check("auditd_audit counts denied AVC and failed auth",
audit["avc_denials"] == 1 and audit["failed_auth"] == 1, audit)
check("auditd_audit reports exe paths and keys",
any(e["name"] == "/usr/bin/sudo" for e in audit["top_exe"]) and
{k["name"] for k in audit["keys"]} == {"sudo", "denied"}, audit)
check("csrf_audit refuses an out-of-scope target", err(by_id[6]),
text(by_id[6]))
kh_missing = json.loads(text(by_id[7]))
check("kernel_hardening survives a missing root",
kh_missing["findings_count"] == 0 and kh_missing["score"] == 100,
kh_missing)
sudo_missing = json.loads(text(by_id[8]))
check("sudoers_audit survives a missing root",
sudo_missing["files"] == 0 and sudo_missing["rules"] == 0,
sudo_missing)
csrf_srv.shutdown()
csrf_srv.server_close()
shutil.rmtree(kh_root, ignore_errors=True)
shutil.rmtree(sudo_root, ignore_errors=True)
shutil.rmtree(sec_home2, ignore_errors=True)
print("\n== esp32 tools ==")
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})