New build targets, no new features: make asan apex-twin-asan with -fsanitize=address,undefined make test-asan the whole suite against it (APEX_BIN override) make analyze gcc -fanalyzer over every translation unit Results: 239/239 checks pass against the ASan/UBSan binary with no report; a batch of error paths, network captures, report generation and evidence/traffic reads run with LeakSanitizer on: no leaks. make analyze is clean (0 warnings). The analyzer was red first on vendor/libmcp/mcp.h: 'b->p = realloc(b->p, want)' loses the only pointer to the old block when realloc fails. It now grows through a temporary and assigns after the NULL check. That is a real robustness fix, not a suppression. .gitignore covers apex-twin-asan and build-asan/. README documents the targets and the result.
APEX TWIN
An offensive-security MCP server in C99 + POSIX. One static binary, libc only, no Python in the serving path. It gives an agent real reconnaissance and real web testing behind a scope gate that refuses everything until a rules-of-engagement file says otherwise.
Derived from ARTEX's ideas (scope gates,
findings with evidence, budgets) but written from nothing in C, with the fleet's
libmcp transport and the ESP32 Marauder serial CLI folded in.
What it is not: an exploit framework. There is no payload that reads a database, no shell, no post-exploitation. Every tool either observes (scan, fetch, capture) or proves (headers, certificate, reflected payload). Transmission is a separate, explicitly armed switch.
Build
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # 239 end-to-end checks, no mocks
make asan # apex-twin-asan with ASan + UBSan
make test-asan # the whole suite against the sanitizer binary
make analyze # gcc -fanalyzer over every translation unit
make install # binary, README and both systemd units (DESTDIR/PREFIX respected)
make install puts the binary in $PREFIX/bin, the README in
$PREFIX/share/doc/apex-twin/ and both units in $PREFIX/lib/systemd/system/,
so a package can use DESTDIR=/tmp/pkg make install without surprises. The
proxy unit is separate: an engagement box may want the MCP server without an
open listener.
Flags are fixed: -std=c99 -Wall -Wextra -Wpedantic -Werror plus
-D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE.
The gate is the product
Every tool that can touch something calls apex_scope_check() before it opens a
socket or spawns a process, and appends the decision to audit.log before the
action. The rules, in the order they are applied:
| # | Rule | Result |
|---|---|---|
| 1 | no scope file | deny everything |
| 2 | scope expired | deny everything |
| 3 | target in deny_ip |
deny (deny beats allow) |
| 4 | port not in allow_port |
deny (empty list = all ports) |
| 5 | target in neither allow_ip nor allow_domain |
deny |
| 6 | private/loopback/link-local and allow_private is false |
deny |
| 7 | a name not in allow_domain that does not resolve entirely inside allow_ip |
deny |
Rule 7 exists because of DNS rebinding: a name that is not allow-listed must
resolve only to addresses the scope lists, and an unresolvable name is refused
rather than waved through. A name that is in allow_domain is trusted for its
addresses, but while allow_private is false it may not resolve into a private net
— an allow-listed name pointing at 10.0.0.5 would otherwise be a way in.
Radio transmission is gated a second time: serial_tx must be true and the
command must be on the allowlist. A receiver is a scanner; a transmitter is an
attack.
Scope file
$APEX_HOME/scope.json, default ~/.local/state/apex-twin/scope.json:
{
"label": "acme-q1",
"expires": "2026-03-31T23:59:59Z",
"allow_private": false,
"serial_tx": false,
"allow_ip": ["203.0.113.0/24", "198.51.100.7"],
"deny_ip": ["203.0.113.66"],
"allow_domain": ["app.acme.example", "*.acme.example"],
"allow_port": ["80", "443", "8000-8100"]
}
"*.acme.example" matches subdomains only; "acme.example" matches the apex and
below. expires accepts YYYY-MM-DD or full ISO-8601.
No scope file means no engagement. That is deliberate: a default that scans something is a liability, not a convenience.
The command guard
guard_check exists for the half of the work that happens in the operator's own
shell. It takes the exact command line, tokenises it, and applies the deny rules
before it looks at a target: recursive rm/chmod on a system path, dd,
mkfs or wipefs onto a device, shutdown/reboot, a firewall flush, stopping
a service, a pipe into an interpreter (curl … | sh), nc -e, and a redirect
into /etc. Only when no rule matched does it take the URLs, IPs, host:port
pairs and the arguments of known network commands, and ask apex_scope_check()
about each one.
The order is the contract and the suite proves it: rm -rf / <out-of-scope-url>
is refused for the delete, not for the URL — sending the operator to fix the
scope would be sending them to fix the wrong thing.
It is a speed bump with an audit trail, not a sandbox. The tokenizer does not expand variables or follow an interpreter, so a line can hide its targets; when it sees none it says so. Use it on commands a human can read.
Findings have a lifecycle
A finding starts open. finding_update moves it to confirmed,
false-positive or fixed, changes severity, confidence, remediation or tags,
and records a note on why. The file is written beside the old one and renamed,
so a reader sees the old version or the new one and never half of either, and
the update is audited like every other decision.
report_markdown prints the status of each finding, counts them in a lifecycle
table, and filters by status — which is what turns "confirmed findings only"
from a promise into an artefact you can send.
The inventory
A finding says what is wrong; an asset says what exists. asset_add puts a host,
domain or IP in $APEX_HOME/assets/, through the same gate as every other
target — an out-of-scope host cannot enter the inventory, and the refusal is
audited. One target is one record: a second observation merges into the
existing file, unions the port list and replaces the service text with the
latest reading, so a scan that runs twice does not grow two rows.
report_markdown with include_assets: true appends the inventory table to the
same file as the findings.
Captured traffic
http_capture is http_request that keeps the exchange: the request bytes (or
a reconstruction when TLS is handed to curl — the file says which) and the raw
response go to $APEX_HOME/traffic/tNNNN.http, with a tNNNN.json record
beside it holding target, method, path, status and byte counts. traffic_list
finds the pair, traffic_read shows it again as text, or base64 when the bytes
are not text.
The capture found an old bug the suite had never exercised: status_code()
took the first number in HTTP/1.1 200 OK, which is the 1 of the version, so
path discovery and both probes had been comparing status 1 for every answer.
The status is now parsed after the protocol token, and the test asserts 200.
The proxy
apex-twin --proxy 8798 is the same gate in front of a client that is not
MCP-aware: point curl -x http://127.0.0.1:8798 (or a browser) at it and every
request is checked with the scope before a socket opens, with the decision in
audit.log. Plain HTTP is forwarded, the absolute request line is rewritten to
origin form, and the exchange is stored through the same traffic/ store as
http_capture. CONNECT is tunnelled blind — this binary links no TLS stack,
so the proxy records host, port and byte counts rather than pretending to see
inside TLS. A request outside the scope gets 403 Forbidden with the gate's
reason in the body.
It serves one connection at a time. That is a deliberate trade: serial handling keeps the gate order obvious and an origin that stalls costs one timeout, not the process.
Before forwarding, the proxy loads $APEX_HOME/rewrite.json (APEX_REWRITE
overrides the path) and applies the first matching rule:
{"rules": [
{"match_host": "app.example.com", "match_path_prefix": "/api",
"set": [{"name": "X-Test", "value": "1"}],
"remove": ["User-Agent"], "note": "mark the request"},
{"match_host": "*", "match_path_prefix": "/admin",
"block": true, "note": "not part of this engagement"}
]}
match_host is case-insensitive, * matches any host, and match_path_prefix
is a prefix. set replaces a header the client sent and adds one it did not;
remove drops a header; block answers 403 with the note and writes a deny
line to audit.log. The applied rule is named in the traffic record and audited.
kill -HUP reloads the file; an invalid file is rejected whole and the previous
rules stay active. The scope gate still runs first: a rule can only narrow what
the proxy does, never widen the engagement.
Checks that end in a finding
Three web checks exist because the header audit alone leaves money on the table:
cors_checksends a GET with a markerOriginand grades the answer. A server that reflects any origin and setsAccess-Control-Allow-Credentials: truelets any site read authenticated responses —high, not "a header note".cookie_auditwalks everySet-Cookieand reports which of Secure, HttpOnly and SameSite is missing, including theSameSite=Nonewithout Secure case that browsers reject.http_optionsreadsAllow/Publicand flags TRACE, PUT and DELETE.
whois covers the ownership half (registrar, dates, netblock, abuse contact). It
talks to port 43, so allow_port has to include 43; without it the gate refuses,
which is the correct answer rather than a silent bypass.
Notifications
Set APEX_WEBHOOK to a URL and APEX_WEBHOOK_MIN_SEVERITY (default
critical); a finding at or above the floor is POSTed as JSON after it is on
disk, and so is the transition of a finding into confirmed. notify_test sends
one event so the path can be proven before anyone relies on it.
The webhook is operator infrastructure, not a target: it is not put through
the scope gate, and it is called with argv (no shell) so the JSON cannot be
re-read as a command. A failing webhook never fails the finding — the file and
the audit line are the product, the POST is a convenience. Without
APEX_WEBHOOK nothing is sent and nothing is lost.
Tools (45)
Scope and bookkeeping — scope_show, scope_check (ask the gate without
touching anything), scope_reload, capabilities, audit_log, evidence_save
Command guard — guard_check (may this shell line run: deny rules first,
then the scope of every target in it)
Inventory — asset_add (gated; merges by target, unions ports), asset_list,
asset_read, asset_update
Traffic — http_capture (request + raw response kept as a pair),
traffic_list, traffic_read
Network recon — portscan (in-process TCP connect, no nmap needed), nmap
(profiles quick/default/full/udp/vuln/http), dns (dig), whois, tls_cert
(openssl), banner, http_head
Web — http_request (any method, body, headers), http_headers (HSTS/CSP/
frame/nosniff/referrer/permissions audit), http_paths (built-in wordlist:
.git, .env, actuator, swagger, backups), cors_check (origin reflection with
credentials), cookie_audit (Secure/HttpOnly/SameSite), http_options (Allow,
TRACE/PUT/DELETE), sqli_probe (quote + boolean pair, reports differing answers
as a lead), xss_probe (marked payload, returns the reflection context), curl
Radio — marauder_info, marauder_commands, marauder_cmd, marauder_scan
Method — method_techniques, method_playbook, method_tool
Findings — finding_add, finding_list, finding_read, finding_update
(status open/confirmed/false-positive/fixed, severity, note), report_markdown
(Markdown or CSV, severity-sorted, filterable by target/severity/status, written
to $APEX_HOME/reports), evidence_list, evidence_read (text, or base64 when
the bytes are not text)
Notifications — notify_test (fire the configured webhook once and report
whether curl accepted it)
Method is not decoration. method_playbook returns the ordered steps for a
technique, the check that turns a lead into a finding, and the mistake that wastes
an engagement — 12 techniques across recon, enum, web, creds, AD, wifi and report,
plus a note per tool on what people get wrong with it.
Transport
apex-twin # MCP over stdin/stdout (one JSON-RPC line each way)
apex-twin --http 8797 # MCP over HTTP on 127.0.0.1:8797, POST /mcp
apex-twin --proxy 8798 # forward proxy on 127.0.0.1:8798 (curl -x)
apex-twin --check # scope, tool count, rewrite rules, webhook state, exit
HTTP and the proxy bind loopback only. A service that can scan and transmit
must not appear on a LAN by accident; reach it through a tunnel.
systemd/apex-twin.service and systemd/apex-twin-proxy.service run exactly
that: loopback ports, a 0700 state dir, dialout for the radio, and a capability
bounding set without CAP_NET_RAW (connect scans need none).
--check answers the operational questions without starting a server:
rewrite_rules, webhook_configured (a boolean; the URL is never printed) and
the loaded scope, alongside the version and tool count. capabilities returns
the same two fields to the model.
The radio
The Marauder bridge speaks the firmware CLI at 115200 baud, and it refuses to talk
to something that is not a radio. Before the first command it sends a bare CRLF:
a console answers that with its login prompt, a Marauder either stays quiet or
prints a prompt of its own. On this machine /dev/ttyACM0 is an Espressif USB
JTAG unit running a Mikronix console, and typing scanall into it produced
login: scanall: no such user and then 3 incorrect attempts, giving up. The
guard now refuses it by name instead.
Scans always end with stopscan, so the next command meets a clean device.
APEX_SERIAL=/dev/ttyACM0 APEX_BAUD=115200
Environment
| Variable | Default | Meaning |
|---|---|---|
APEX_HOME |
~/.local/state/apex-twin |
state dir (0700) |
APEX_SCOPE |
$APEX_HOME/scope.json |
scope file |
APEX_SERIAL |
/dev/ttyACM0 |
Marauder tty |
APEX_BAUD |
115200 |
serial baud |
APEX_DRY_RUN |
unset | 1 prints commands, runs none |
APEX_DEFAULT_TIMEOUT_MS |
60000 |
per-tool default |
APEX_MAX_TIMEOUT_MS |
900000 |
hard cap |
APEX_WEBHOOK |
unset | URL POSTed on a finding at or above the floor |
APEX_WEBHOOK_MIN_SEVERITY |
critical |
floor for the webhook |
APEX_REWRITE |
$APEX_HOME/rewrite.json |
proxy rewrite rules (SIGHUP reloads) |
Files it writes
$APEX_HOME/
scope.json the rules of engagement
audit.log one JSON line per decision, append-only
findings/f0001.json one finding per file
evidence/<ts>-<label>.bin raw proof, 0600
reports/report-<ts>.md rendered findings, 0600, never overwritten
assets/a0001.json one record per target, merged on the next look
traffic/t0001.json one capture: target, method, status, byte counts
traffic/t0001.http the request and the raw response, 0600
The audit line is written before the action, so a process that dies mid-scan still left its intent on disk. A report is the one artefact that leaves the state dir, and it is rendered from the finding files, not from memory: delete a finding and the next report no longer mentions it.
Tests
make test
239 checks, real binary, real DNS, real files written; no mocks. The suite was
seen red on purpose: with the "no scope" branch disabled by if (0 && ...),
three checks fail, because they assert the reason and not merely that an error
came back — a gate that falls through to the next deny branch looks identical
from isError alone. New guarantees are made to fail the same way: the report
JSON was missing its closing brace once (the suite refused to parse it), with the
slash guard in evidence_read disabled sub/../<blob> was returned, and with
the rm rule disabled the guard fell through to the scope and reported the URL
instead of the delete — the precedence check went red. Disabling the report's
status filter turned five checks red: every filtered report contained the
unfiltered set. Disabling the asset merge turned seven red, and while it was red
it exposed a real bug: the create path read an uninitialised struct, so a fresh
asset's port list was built on stack garbage. A memset fixed it; the sabotage
that found it is in the history of the suite. With the old status_code() back,
the capture reported status 1 instead of 200 and two checks went red. With
the proxy's gate call bypassed, the out-of-scope request was forwarded and three
checks went red (403 became 502, and the audit had no deny). Forcing the CORS
'reflected' flag to false and the cookie flags to true turned four checks red:
the risk grade fell to low and the missing Secure/HttpOnly issues disappeared.
Disabling the notification severity floor made a low finding post, and "a low
finding stays quiet" went red. Making the rewrite matcher return -1 turned seven
checks red: headers stayed, the block rule did not block, the traffic record lost
the rule name, and the rewrite audit was empty. Hardcoding the new operational
fields to 0/false turned three checks red: the rule count and the webhook state
disappeared from --check and capabilities.
A port is never assumed: an earlier version of the HTTP test used 18797, which on
this host is an SSH forward to another machine, and a foreign server answered
{"serverInfo":{"name":"koder"}} while the suite was green.
The suite is also run against apex-twin-asan (make test-asan), built with
-fsanitize=address,undefined. All 239 checks pass with no ASan or UBSan report,
and a separate batch of error paths, network captures and report generation was
run with leak detection on: no leaks. make analyze runs gcc -fanalyzer over
every translation unit; it was red first on vendor/libmcp/mcp.h, where
b->p = realloc(b->p, ...) loses the only pointer when realloc fails. Growing
through a temporary is correct and the analyzer is now silent. That is the kind
of finding this pass exists for.
Status
0.12.0. Built and run: 45 tools, 239 checks. 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 graded lead, report_markdown turns
findings and inventory into one Markdown or CSV file, and
evidence_read/traffic_read get the proof back. --proxy puts the same gate
in front of curl and a browser, with optional rewrite rules that can set or
remove a header or block a path, and APEX_WEBHOOK wakes someone when the
severity floor is crossed. make install ships the binary, this README and both
units; --check reports the operational state without starting a server. The
whole suite also runs under ASan/UBSan, and make analyze is clean. Not yet
wired into a fleet router.
Licence: AGPL-3.0, same as ARTEX.