apex-twin 1.0.4: detailed README, CNCL license, scope edge tests

- README rewritten for a first-time reader: the gate and its rule order, quick
  start, all 45 tools by group, transports, proxy and rewrite rules, findings/
  assets/traffic/reports, state layout, security model, limits, build and
  release targets, install layout, environment, source layout, 1.x promise.
- License changed to CNCL 1.1 (Could Not Care Less License). LICENSE carries the
  unchanged text; README, SECURITY.md and the man page point at it. make dist and
  make install ship LICENSE.
- Scope gap tests: deny_ip beats allow_ip, port range endpoints and neighbours,
  /25 boundary, IPv6 CIDR accept/refuse, apex vs subdomain vs wildcard matching
  (*.name not matching the apex), embedded host:port, trailing FQDN dot, and a
  failed scope_reload closing the gate. scope.c 75.9% -> 82.8%, total 79.4%.

397 checks, analyze clean, release-check green including distcheck 1.0.4.
This commit is contained in:
lotherk committed 2026-11-21 10:42:27 +00:00
1 parent 186d5d85af
commit 32ece44c58
9 files changed
+649 -436

No files matched your search

+16 -1
View File
@@ -8,7 +8,22 @@ 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.3 — 2026-11-21 — this change
## 1.0.4 — 2026-11-21 — this change
- 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.
- README rewritten for a first-time reader: what the gate does and in which
order, quick start, all 45 tools by group, proxy/rewrite, findings and
reports, state layout, security model, limits, build and release targets,
install layout, environment, source layout and the 1.x promise.
- Scope gap tests: deny_ip beating allow_ip, port range endpoints and their
neighbours, a /25 boundary, IPv6 CIDR accept/refuse, apex vs subdomain vs
wildcard domain matching (including `*.name` not matching the apex), an
embedded `host:port`, a trailing FQDN dot, and a failed `scope_reload`
closing the gate. Coverage 78.7% -> 79.4%; `scope.c` 75.9% -> 82.8%.
397 checks.
## 1.0.3 — 2026-11-21 — 186d5d8
- Fixed `tls_cert`: it called `openssl s_client -connect 443`, i.e. a bare port,
so openssl tried to resolve "443" as a host and every call failed. It now
+83
View File
@@ -0,0 +1,83 @@
# CNCL — Could Not Care Less License
Version 1.1 (2026-11-19)
Version 1.1 adds the paragraph on military use; the grant is unchanged: 1.0 and
1.1 permit exactly the same things.
No rights reserved. No obligations imposed. Couldn't care less.
## Preamble
Software is the product of collective human knowledge.
Every idea builds upon ideas that came before. Every invention stands on the accumulated discoveries, mistakes, experiments, and imagination of generations.
We do not believe in artificial boundaries around creativity.
We do not believe that creating something grants us the moral authority to dictate what others may do with it.
We live in an age where knowledge, tools, and artificial intelligence make creation accessible to everyone. The distinction between author, user, modifier, and creator is becoming increasingly meaningless.
We are not here to control what happens next.
We are here to create.
## The License
This software is made available to the world.
Do whatever you want with it.
Use it. Copy it. Modify it. Break it. Fix it. Sell it. Give it away. Incorporate it into something else. Keep your modifications private. Publish them. Feed it to AI. Build something nobody has thought of yet.
Use it commercially or personally. Combine it with other software. Release it under another license.
You owe the original author nothing.
No attribution required. No royalties. No source disclosure. No reciprocal licensing. No contribution requirements. No permission needed.
There are no conditions attached to your use of this software.
There is no expectation that you will give anything back.
There is no expectation that you will even care.
## Military use
We have no illusions about armies, and no say over them either. If this software
ends up in a weapon, that is your business, not ours.
But since you asked: using it to defend people is not the same as using it to
attack them. Use it to protect. Do not use it to conquer.
There is nothing to enforce here either. This paragraph is the author's position,
not a term of the license: no condition, no revocation, no court. It does not add
an obligation to CNCL 1.0, and it is not a promise that the license is "ethical".
It is one sentence of opinion in a license that has no terms -- take it or leave
it, as with everything else here.
## Disclaimer
The software is provided "AS IS", without warranty of any kind.
The authors accept no responsibility for its use, misuse, modification, distribution, or consequences.
## The CNCL Principle
We acknowledge that everything we create is built upon something that existed before us.
We do not claim ownership over the collective intelligence of humanity.
We do not expect recognition, compensation, or control.
Take it. Change it. Make it better. Make it worse. Make something entirely different.
Or don't.
We Could Not Care Less.
---
CNCL — Could Not Care Less.
Created for everyone. Controlled by no one.
+2 -2
View File
@@ -156,7 +156,7 @@ dist:
@test -n "$(VERSION)" || { echo "dist: cannot read APEX_VERSION"; exit 1; }
rm -rf $(DISTNAME) $(DIST)
mkdir -p $(DISTNAME)
cp Makefile README.md SECURITY.md CHANGELOG.md .gitignore $(DISTNAME)/
cp Makefile README.md SECURITY.md CHANGELOG.md LICENSE .gitignore $(DISTNAME)/
cp -a src vendor tests docs examples systemd $(DISTNAME)/
find $(DISTNAME) -type f \( -name '*.o' -o -name '*.gcda' -o -name '*.gcno' \
-o -name '*.gcov' \) -delete
@@ -190,7 +190,7 @@ install: apex-twin
mkdir -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(DOCDIR) $(DESTDIR)$(UNITDIR) \
$(DESTDIR)$(MANDIR)
install -m 0755 apex-twin $(DESTDIR)$(BINDIR)/apex-twin
install -m 0644 README.md CHANGELOG.md SECURITY.md $(DESTDIR)$(DOCDIR)/
install -m 0644 README.md CHANGELOG.md SECURITY.md LICENSE $(DESTDIR)$(DOCDIR)/
install -m 0644 docs/operations.md docs/artex-port.md $(DESTDIR)$(DOCDIR)/
install -m 0644 docs/apex-twin.1 $(DESTDIR)$(MANDIR)/apex-twin.1
install -m 0644 systemd/apex-twin.service $(DESTDIR)$(UNITDIR)/apex-twin.service
+480 -428
View File
@@ -5,198 +5,272 @@ 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.
Derived from [ARTEX](https://github.com/Autumn-27/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.
**45 tools · 397 end-to-end checks · 340 fuzz cases · 79.4% line coverage · ~246 KiB**
**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.
## Documentation
- [docs/operations.md](docs/operations.md) — install, state directory and
backup, scope lifecycle, systemd, proxy and rewrite rules, webhook, upgrade,
troubleshooting, limits.
- [docs/artex-port.md](docs/artex-port.md) — what was ported from ARTEX and what
was deliberately left out.
- [SECURITY.md](SECURITY.md) — threat model, trust boundaries, hardening
checklist and how to report a problem.
- [CHANGELOG.md](CHANGELOG.md) — what changed in each version, with the commit
that introduced it.
- `man apex-twin` (source: `docs/apex-twin.1`) — modes, environment, scope rules,
files and limits in one page.
## Build
```sh
make # apex-twin, ~239 kB static-ish binary, zero warnings under -Werror
make test # version check + gate audit + 373 end-to-end checks
make asan # apex-twin-asan with ASan + UBSan
make test-asan # the whole suite against the sanitizer binary
make version-check # the five places that carry a version must agree
make gate-audit # static audit: every target-taking tool calls the gate
make analyze # gcc -fanalyzer over every translation unit
make coverage # -O0 --coverage build, suite, per-file gcov report
make fuzz # mutated scope/rewrite/MCP inputs against the ASan binary
make fuzz-red # builds a deliberately broken binary; fuzz must reject it
make fuzz-proxy # mutated raw requests against the ASan proxy
make fuzz-http # mutated raw HTTP against the ASan MCP HTTP face
make install # binary, README and both systemd units (DESTDIR/PREFIX respected)
make dist # apex-twin-<version>.tar.gz: source, tests, docs, units
make distcheck # build the tarball, unpack it, build and test it there
make release-check # gate audit, suites, sanitizer, analyzer, fuzzers, distcheck
```
$ ./apex-twin --check
{"version":"1.0.4","tools":45,...,"scope":{"loaded":true,...}}
```
`make install` puts the binary in `$PREFIX/bin`, the documentation set (README,
CHANGELOG, SECURITY, operations, port map) in `$PREFIX/share/doc/apex-twin/`,
the `apex-twin(1)` man page in `$PREFIX/share/man/man1/` 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.
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
gates, findings with evidence, budgets). The C implementation is written from
nothing; it takes the ideas, not the code.
Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
`-D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE`.
---
## 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 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.
The MCP client is the agent. This process is the gate, the tools and the records.
---
## 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:
A tool never decides for itself whether a target is fair game. Every tool that
can touch a network calls one of two helpers from `src/tools.h`:
```c
gated(c, "nmap", target, port); /* scope check, no action */
gated_cmd(c, "nmap", target, port, argv, timeout, NULL); /* scope check + spawn */
```
Both consult `apex_scope_check()`, write the audit line **before** the action,
and refuse with `mcp_reply_error` naming the reason. `scope_check` is the same
decision without an action, for planning.
`tests/gate_audit.py` enforces the invariant statically: it parses every
`TOOLS_*[]` table and handler body and fails if a tool whose schema names a
`target` does not call the gate (four record filters excepted), or if a handler
opens a socket or spawns a process without it. `make test` runs that audit before
the suite.
### Rules, in the order they are applied
| # | Rule | Result |
|---|---|---|
| 1 | no scope file | deny everything |
| 1 | no scope file loaded | 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) |
| 3 | target in `deny_ip` | deny (**deny beats allow**) |
| 4 | `port > 0` and not in `allow_port` | deny |
| 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 |
| 7 | a name outside `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.
Notes that matter:
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`:
```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.
- `port <= 0` means **the caller enumerates ports itself** (used by `portscan`,
which filters every probe with `apex_port_in_scope()`). It is not a wildcard
for a single-port action.
- A name in `allow_domain` is trusted for its addresses, but while
`allow_private` is false it may not resolve into a private network.
- A name outside `allow_domain` must resolve, and every address it returns must
be inside `allow_ip`; an unresolvable name is refused, never waved through.
- `*.example.com` matches subdomains only; `example.com` matches the apex and its
subdomains. A trailing FQDN dot and an embedded `host:port` are normalised
before the check.
No scope file means no engagement. That is deliberate: a default that scans
something is a liability, not a convenience.
## The command guard
---
## Quick start
```sh
make # build (zero warnings under -Werror)
mkdir -p ~/.local/state/apex-twin
cat > ~/.local/state/apex-twin/scope.json <<'EOF'
{
"label": "lab",
"expires": "2099-12-31T23:59:59Z",
"allow_private": false,
"serial_tx": false,
"allow_ip": ["192.0.2.0/24"],
"deny_ip": ["192.0.2.66"],
"allow_domain": ["example.com"],
"allow_port": ["80", "443", "8000-8100"]
}
EOF
apex-twin --check # is the scope loaded, what is the tool count?
apex-twin # MCP over stdin/stdout
```
An MCP client then calls `scope_show`, `portscan`, `http_headers`,
`finding_add`, `report_markdown`, and so on. A minimal stdio exchange:
```json
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"scope_check","arguments":{"target":"192.0.2.5","port":80}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"http_headers","arguments":{"target":"example.com","port":80,"path":"/"}}}
```
---
## Transports and modes
| Mode | Command | Listener |
|---|---|---|
| MCP over stdio | `apex-twin` | none |
| MCP over HTTP | `apex-twin --http 8797` | `127.0.0.1:8797`, `POST /mcp` |
| Forward proxy | `apex-twin --proxy 8798` | `127.0.0.1:8798` |
| Diagnostics | `apex-twin --check` | none; prints JSON and exits |
| Version | `apex-twin --version` | none |
Both listeners bind **loopback only** and do not authenticate. Reach them
through an SSH tunnel or a VPN; never put them on a LAN interface. The HTTP face
serves at most `APEX_HTTP_MAX_CHILDREN` connections at once (503 beyond) and
closes a request whose head or body does not arrive within
`APEX_HTTP_HEAD_TIMEOUT_MS`.
`--check` reports the operational state without starting a server:
`rewrite_rules`, `webhook_configured` (a boolean; the URL is never printed),
`proxy_max_children`, `audit_max_bytes`, `http_max_children`,
`http_head_timeout_ms`, `evidence_max_bytes` and the loaded scope.
---
## Tools (45)
### Scope and bookkeeping
| Tool | What it does |
|---|---|
| `scope_show` | The loaded rules of engagement as JSON |
| `scope_check` | Ask the gate about one target/port without touching it |
| `scope_reload` | Reload the scope file, optionally from another path |
| `capabilities` | State dir, programs present, limits, dry-run flag |
| `audit_log` | The newest audit lines (one JSON object per decision) |
| `evidence_save` | Store a raw proof blob (`APEX_EVIDENCE_MAX_BYTES` cap) |
| `notify_test` | Fire the configured webhook once and report the result |
### Command guard
| Tool | What it does |
|---|---|
| `guard_check` | May this shell line run? Deny rules first, then the scope of every URL/IP/host in it |
`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.
shell. It tokenises the command, applies the deny rules, and only then checks
targets. Order is the contract: `rm -rf / <out-of-scope-url>` is refused for the
delete, not for the URL.
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.
Deny rules: recursive `rm`/`chmod` on a system path, `rm -rf *` after `cd` into
one, `find -delete`, `dd`/`mkfs`/`wipefs`/`mkswap`/`shred` on a device,
`shutdown`/`reboot`/`halt`/`init 0|6`/`kill 1`, `systemctl stop|disable|mask`,
firewall flushes (`iptables -F/-X`, `nft flush`, `ufw disable`, `pfctl -F`), a
pipe into an interpreter that reads stdin, `nc -e`/`socat EXEC:`, and writes or
`mv` into `/etc`. It also notes (but allows) `sudo`, world-writable `chmod 777`,
uploads and secret-file reads. It does not execute anything.
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.
### Network reconnaissance
## Findings have a lifecycle
| Tool | What it does |
|---|---|
| `portscan` | TCP connect scan in-process; no nmap needed; per-probe scope filter |
| `nmap` | Profiles: `quick`, `default` (top-100 + `-sV`), `full` (`-p-`), `udp`, `vuln`, `http` |
| `dns` | `dig` for A/AAAA/MX/TXT/NS/SOA/CNAME/SRV/CAA/PTR |
| `whois` | Registration and netblock record; speaks to port 43, so allow it |
| `tls_cert` | `openssl s_client` chain and verification for `host:port` |
| `banner` | Read the first bytes a service sends |
| `http_head` | Request the head of a URL and return it verbatim |
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.
### Web
`finding_add` is idempotent for the same target and title: the second call
(case-insensitive, whitespace runs collapsed) returns the existing id with
`duplicate: true` instead of writing a second file, and the duplicate is
audited. The stored severity is not overwritten — use `finding_update` for
that. A different target or a different title is a new finding.
| Tool | What it does |
|---|---|
| `http_request` | Any method, headers and body; response verbatim |
| `http_headers` | Audit HSTS/CSP/frame/nosniff/referrer/permissions with reasons |
| `http_paths` | Built-in wordlist: `.git`, `.env`, admin, actuator, swagger, backups |
| `cors_check` | Marker `Origin`; grades reflection with credentials as high risk |
| `cookie_audit` | Secure/HttpOnly/SameSite per cookie, incl. `SameSite=None` without Secure |
| `http_options` | `Allow`/`Public`; flags TRACE, PUT, DELETE |
| `sqli_probe` | Quote and boolean payloads; differing answers are a **lead**, not proof |
| `xss_probe` | Marked payload; returns the reflection context |
| `curl` | `curl` for a gated path when the operator wants its behaviour |
`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. `format: "json"` writes the same
thing as a machine-readable document: the filters that were applied, counts by
severity and status, the finding records, and the asset list when
`include_assets` is set.
### Traffic and evidence
## The inventory
| Tool | What it does |
|---|---|
| `http_capture` | One request and the raw response stored as a pair |
| `traffic_list` | Captures, newest last, filterable by target |
| `traffic_read` | One pair back as text, or base64 when the bytes are not text |
| `evidence_list` | Saved proof blobs, newest first |
| `evidence_read` | One blob back, text or base64 |
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.
### Inventory and findings
`report_markdown` with `include_assets: true` appends the inventory table to the
same file as the findings.
| Tool | What it does |
|---|---|
| `asset_add` | Gated inventory entry; merges by target and unions ports |
| `asset_list` / `asset_read` / `asset_update` | Inventory access, atomic updates |
| `finding_add` | Record a finding; duplicate target+title returns the existing id |
| `finding_list` / `finding_read` | Query findings |
| `finding_update` | Lifecycle `open`/`confirmed`/`false-positive`/`fixed`, severity, note |
| `report_markdown` | Markdown, CSV or JSON report written under `$APEX_HOME/reports` |
## Captured traffic
### Radio (ESP32 Marauder)
`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.
| Tool | What it does |
|---|---|
| `marauder_info` | Ask `info` and `help`; refuses a device that looks like a console |
| `marauder_commands` | The allowlist and which commands transmit |
| `marauder_cmd` | One allowlisted command, output returned |
| `marauder_scan` | A receive-only scan for N seconds, always ending in `stopscan` |
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 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.
### Method
| Tool | What it does |
|---|---|
| `method_techniques` | 11 techniques across recon/enum/web/creds/AD/wifi/report, filterable |
| `method_playbook` | The ordered plan for a phase |
| `method_tool` | When to use a tool and the mistake that wastes the engagement |
---
## 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.
```sh
apex-twin --proxy 8798
curl -x http://127.0.0.1:8798 http://target.example/
```
It serves each accepted connection in a child process: a `CONNECT` tunnel does
not block the next request, and two captures can be written at once because the
traffic store reserves ids with `O_EXCL`. Each child inherits the scope and the
rewrite rules loaded at fork time; `SIGHUP` in the parent reloads the rules for
connections accepted afterwards. At most `APEX_PROXY_MAX_CHILDREN` (default 64,
max 1024) children run at once; beyond that the parent answers
`503 Service Unavailable` with a `proxy busy` reason and audits it. Slow origins
are bounded by the per-stage timeouts.
Every request passes the scope gate **before** the origin socket is opened, and
the decision is appended to `audit.log`. Plain HTTP is forwarded with the request
line rewritten to origin form, and the exchange is stored through the same
traffic store as `http_capture`. `CONNECT` is tunnelled blind and recorded as
metadata only: this binary links no TLS stack, so it does not pretend to see
inside TLS.
Before forwarding, the proxy loads `$APEX_HOME/rewrite.json` (`APEX_REWRITE`
overrides the path) and applies the first matching rule:
Each accepted connection gets its own child process: a tunnel does not block the
next request, and parallel captures cannot overwrite each other (traffic ids are
reserved with `O_EXCL`). At most `APEX_PROXY_MAX_CHILDREN` (default 64) children
run at once; beyond that the parent answers `503` with `proxy busy` and audits
the refusal.
Bodies: `Content-Length` and `Transfer-Encoding: chunked` are forwarded. A
chunked body is validated against a 1 MiB payload cap and relayed unchanged;
over the cap answers `413`, malformed framing `400`, both decided before the
origin is opened. Captured responses are capped at 1 MiB and marked truncated.
### Rewrite rules
`$APEX_HOME/rewrite.json` (`APEX_REWRITE` overrides) holds ordered rules:
```json
{"rules": [
@@ -208,321 +282,299 @@ overrides the path) and applies the first matching rule:
]}
```
`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.
The first matching rule is applied: `block` answers `403` with the note and a
deny line in the audit; `set` replaces a client header and adds missing ones;
`remove` drops one. The applied rule is named in the traffic record and audited.
`kill -HUP <pid>` reloads the file; an invalid file is rejected whole and the
previous rules stay active. The scope gate still runs first: a rule can narrow
what the proxy does, never widen the engagement.
Request bodies with `Content-Length` are forwarded as before. `Transfer-Encoding:
chunked` is read chunk by chunk — hex size, CRLF framing, extensions and
trailers — validated against a 1 MiB payload cap and relayed unchanged, so the
origin still receives chunked encoding. Over the cap answers `413`, a malformed
size or framing answers `400`, and both are decided before the origin socket is
opened. The raw capture keeps the chunk framing, so `traffic_read` shows what was
actually sent.
---
## Checks that end in a finding
## Findings, assets, traffic, reports
Three web checks exist because the header audit alone leaves money on the table:
A finding starts `open`. `finding_update` moves it to `confirmed`,
`false-positive` or `fixed`, changes severity, confidence, remediation or tags,
and records why. Updates are written beside the old file and renamed, so a reader
sees one version or the other and never half of either. `finding_add` is
idempotent for the same target and title (case-insensitive, whitespace collapsed)
and returns `duplicate: true` with the existing id.
- `cors_check` sends a GET with a marker `Origin` and grades the answer. A server
that reflects any origin and sets `Access-Control-Allow-Credentials: true` lets
any site read authenticated responses — `high`, not "a header note".
- `cookie_audit` walks every `Set-Cookie` and reports which of Secure, HttpOnly
and SameSite is missing, including the `SameSite=None` without Secure case that
browsers reject.
- `http_options` reads `Allow`/`Public` and flags TRACE, PUT and DELETE.
An asset is one record per target: a second observation merges into it, unions
the port list and replaces the service text with the latest reading.
`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.
A capture is a proof, not a memory: `tNNNN.http` holds the request bytes and the
raw response, `tNNNN.json` the metadata.
`report_markdown` renders everything into one file:
- **Markdown** — severity and lifecycle tables, one section per finding;
- **CSV** — stable columns, quoted fields;
- **JSON** — filters, counts by severity and status, the records themselves, and
the inventory when `include_assets` is set.
Filters: exact `target`, `min_severity`, `status`. Reports are opened `O_EXCL`:
a report is never overwritten. `save: false` renders without writing.
---
## 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, CSV or JSON, 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 — 11 techniques across recon, enum, web, creds, AD, wifi and report,
plus a note per tool on what people get wrong with it.
## Transport
```sh
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, tools, rewrite rules, webhook, child limit, exit
APEX_WEBHOOK=https://hooks.example/apex \
APEX_WEBHOOK_MIN_SEVERITY=high \
apex-twin
```
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. The HTTP face
bounds itself: at most `APEX_HTTP_MAX_CHILDREN` (default 64) connections are
served at once (503 `http busy` beyond), and a request head must arrive within
`APEX_HTTP_HEAD_TIMEOUT_MS` (default 20000) or the connection is answered with
408 and closed.
`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).
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, it is
called with argv (no shell), and a failing webhook never fails the finding.
`--check` answers the operational questions without starting a server:
`rewrite_rules`, `webhook_configured` (a boolean; the URL is never printed),
`proxy_max_children`, `audit_max_bytes`, `http_max_children`,
`http_head_timeout_ms`, `evidence_max_bytes` and the loaded scope, alongside the version and tool count.
`capabilities` returns the same fields to the model.
---
## The radio
## State directory
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.
Everything lives under `$APEX_HOME` (default `~/.local/state/apex-twin`), created
0700; files are 0600:
Scans always end with `stopscan`, so the next command meets a clean device.
```
scope.json the rules of engagement
audit.log one JSON line per decision, append-only
audit.log.1 previous audit file after size rotation
findings/f0001.json one finding per file
evidence/<ts>-<label>.bin raw proof
reports/report-<ts>.md Markdown / .csv / .json, 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
rewrite.json proxy rules (optional, reloaded on SIGHUP)
```
The audit line is written **before** the action, so a process that dies mid-scan
still left its intent on disk. When `audit.log` reaches
`APEX_AUDIT_MAX_BYTES` it is rotated to `audit.log.1` under `flock`, one previous
file kept. Audit lines are one `write()` each, so parallel proxy children cannot
interleave them.
Back up `audit.log`, `audit.log.1` and `evidence/` before deleting a state
directory; they may contain credentials, tokens or personal data from an
engagement.
---
## Security model
- **Loopback only.** The HTTP face and the proxy bind `127.0.0.1` and have no
authentication. Any local user who can reach the port can use the server
within the loaded scope. Run it as a dedicated user on a host you control.
- **The scope file is trusted input.** Writing it is equivalent to being the
operator.
- **Audit before action.** A missing audit line for a tool that touched the
network is a bug worth reporting.
- **Target content is data.** Responses are stored as bytes; the program does
not execute target content.
- **No TLS interception.** `CONNECT` is a blind tunnel, by design.
- **Memory safety is tested.** Scope, rewrite, HTTP and proxy parsers run under
ASan/UBSan in the suite and in three fuzzers; a sanitizer report is a test
failure.
The full threat model, trust boundaries and a hardening checklist are in
[SECURITY.md](SECURITY.md).
---
## Limits
| Limit | Value |
|---|---|
| HTTP MCP request body | 8 MiB (`413` over) |
| Proxy chunked request payload | 1 MiB (`413` over, malformed `400`) |
| Proxy response per capture | 1 MiB (marked truncated) |
| Concurrent proxy children | `APEX_PROXY_MAX_CHILDREN`, default 64, `503` beyond |
| Concurrent HTTP MCP connections | `APEX_HTTP_MAX_CHILDREN`, default 64 |
| HTTP request deadline (head + body) | `APEX_HTTP_HEAD_TIMEOUT_MS`, default 20000 |
| Evidence blob | `APEX_EVIDENCE_MAX_BYTES`, default 16 MiB |
| Audit file | `APEX_AUDIT_MAX_BYTES`, default 10 MiB, rotates to `.1` |
| Findings per report | 1024 |
| Tool timeout | default 60 s, hard cap 900 s |
| Radio scan | 3–300 s, always ends with `stopscan` |
---
## Build, test, release
Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
`-D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE`.
```sh
APEX_SERIAL=/dev/ttyACM0 APEX_BAUD=115200
make # apex-twin
make test # version check + gate audit + 397 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
make test-asan # the whole suite against the sanitizer binary
make analyze # gcc -fanalyzer over every translation unit
make coverage # -O0 --coverage build, suite, per-file gcov report
make fuzz # 240 mutated scope/rewrite/MCP inputs against the ASan binary
make fuzz-proxy # 60 mutated raw requests against the ASan proxy
make fuzz-http # 40 mutated raw requests against the ASan MCP HTTP face
make dist # apex-twin-<version>.tar.gz: source, tests, docs, units
make distcheck # build the tarball, unpack it, build and test it there
make release-check # the whole gate, fail-fast (several minutes)
make install # binary, docs, man page and both systemd units
```
The fuzzers have red proofs: `make fuzz-red`, `make fuzz-proxy-red` and
`make fuzz-http-red` build deliberately broken binaries and fail if the harness
reports them green. `make fuzz-selftest` compiles a real out-of-bounds program
and requires the detector to flag it.
`make release-check` runs: version check → gate audit → suite → ASan/UBSan suite
→ `-fanalyzer` → all three fuzzers → `distcheck`. It takes several minutes and
needs the network for the `example.com` checks; `make test` is the fast loop.
Every guarantee in this repository was seen failing before it was trusted:
a report without its closing brace, a disabled status filter, a disabled asset
merge, the old `status_code()` (which read the `1` of `HTTP/1.1`), a bypassed
proxy gate, forced CORS/cookie flags, a disabled notification floor, a disabled
rewrite matcher, a serial proxy, a missing connection cap, a missing HTTP
deadline, a disabled evidence cap, a disabled audit rotation and a stale man
page. `README` claims without a red test are treated as unfinished work.
---
## Install
```sh
make install # /usr/local
make install DESTDIR=/tmp/pkg PREFIX=/usr
```
Installs:
```
$PREFIX/bin/apex-twin
$PREFIX/share/doc/apex-twin/{README,CHANGELOG,SECURITY,LICENSE,operations,artex-port}.md
$PREFIX/share/man/man1/apex-twin.1
$PREFIX/lib/systemd/system/apex-twin.service
$PREFIX/lib/systemd/system/apex-twin-proxy.service
```
The units hardcode `User=lotherk` and a state path under
`/home/lotherk/stack/data/apex-twin`; edit them for another account. Secrets
belong in `~/.config/apex-twin/env` (the units read it when present), not in the
unit file. The proxy unit is separate: an engagement box may want the MCP server
without an open listener. Neither unit gets `CAP_NET_RAW`; connect scans need no
privilege.
---
## Environment
| Variable | Default | Meaning |
|---|---|---|
| `APEX_HOME` | `~/.local/state/apex-twin` | state dir (0700) |
| `APEX_SCOPE` | `$APEX_HOME/scope.json` | scope file |
| `APEX_HOME` | `~/.local/state/apex-twin` | state directory |
| `APEX_SCOPE` | `$APEX_HOME/scope.json` | rules of engagement |
| `APEX_REWRITE` | `$APEX_HOME/rewrite.json` | proxy rewrite rules |
| `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_DRY_RUN` | unset | `1` prints commands instead of running them |
| `APEX_DEFAULT_TIMEOUT_MS` | `60000` | per-tool timeout |
| `APEX_MAX_TIMEOUT_MS` | `900000` | hard timeout 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) |
| `APEX_WEBHOOK_MIN_SEVERITY` | `critical` | webhook floor |
| `APEX_PROXY_MAX_CHILDREN` | `64` | concurrent proxy connections before 503 |
| `APEX_AUDIT_MAX_BYTES` | `10485760` | rotate `audit.log` to `.1`; `0` disables |
| `APEX_HTTP_MAX_CHILDREN` | `64` | concurrent MCP HTTP connections before 503 |
| `APEX_HTTP_HEAD_TIMEOUT_MS` | `20000` | request head/body deadline; `0` disables |
| `APEX_EVIDENCE_MAX_BYTES` | `16777216` | `evidence_save` cap; `0` unlimited |
| `APEX_HTTP_HEAD_TIMEOUT_MS` | `20000` | HTTP head/body deadline; 0 disables |
| `APEX_AUDIT_MAX_BYTES` | `10485760` | rotate `audit.log` to `.1`; 0 disables |
| `APEX_EVIDENCE_MAX_BYTES` | `16777216` | `evidence_save` cap; 0 unlimited |
## Files it writes
---
## Source layout
```
$APEX_HOME/
scope.json the rules of engagement
audit.log one JSON line per decision, append-only
audit.log.1 previous audit file after size rotation
findings/f0001.json one finding per file
evidence/<ts>-<label>.bin raw proof, 0600
reports/report-<ts>.md rendered findings, 0600, never overwritten
reports/report-<ts>.json machine-readable variant (same counts and records)
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
src/apex.h types, version, prototypes
src/config.c $APEX_HOME, paths, environment defaults
src/scope.c the gate: parse, match, expiry, DNS rule, JSON view
src/proc.c fork/exec, timeout via process-group kill, output cap
src/store.c audit log, findings, assets, evidence, traffic, rotation
src/guard.c command guard: tokeniser, deny rules, target extraction
src/proxy.c loopback forward proxy, CONNECT tunnel, chunked bodies
src/rewrite.c rewrite rule file and matching
src/notify.c webhook via curl (argv, no shell)
src/tools_recon.c gated(), gated_cmd(), TCP helpers, recon + findings tools
src/tools_web.c HTTP in-process, header audit, probes, capture
src/tools_radio.c Marauder serial: guard, allowlist, scan-then-stop
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_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)
tests/ run.py, gate_audit.py, version_check.py, fuzzers, coverage
docs/ operations.md, artex-port.md, apex-twin.1 (man page)
systemd/ apex-twin.service, apex-twin-proxy.service
examples/ scope.json
```
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
## Documentation
```sh
make test
```
- [docs/operations.md](docs/operations.md) — run book: install, state and backup,
scope lifecycle, systemd, proxy and rewrite rules, webhook, upgrade,
troubleshooting, limits.
- [docs/artex-port.md](docs/artex-port.md) — what was ported from ARTEX and what
was deliberately left out.
- [SECURITY.md](SECURITY.md) — threat model, trust boundaries, hardening
checklist.
- [CHANGELOG.md](CHANGELOG.md) — every release with the commit that introduced it.
- `man apex-twin` (source: `docs/apex-twin.1`) — modes, environment, scope rules,
files and limits in one page.
373 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.
A rare empty-stdout flake in the suite was a bug in the test harness, not the
server: the PTY Marauder simulator closed its fd numbers while its reader thread
could still be inside `select()`, the next `mkstemp()` reused one, and the thread
consumed the subprocess's stdin — the child then saw EOF, exited 0 and answered
nothing. `MarauderSim.close()` now joins its threads before closing, and
`tests/run.py` repeats the close-then-spawn sequence twelve times as a
regression check (12/12 threads alive and 6/12 lost spawns were seen before the
fix). The retry that used to mask it is gone: empty stdout is a failure.
The suite is also run against `apex-twin-asan` (`make test-asan`), built with
`-fsanitize=address,undefined`. All 373 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.
`make fuzz` runs `tests/fuzz.py`: 240 deterministically mutated inputs (80 each
for `scope.json`, `rewrite.json` and JSON-RPC lines) against the sanitizer
binary. A case fails on any sanitizer report, a signal or a timeout; a malformed
scope is allowed to close the gate, that is a correct answer. `make
fuzz-selftest` compiles a real out-of-bounds program and requires the harness to
flag it. `make fuzz-red` builds `apex-twin-asan-bug` (one deliberate heap overflow
under `APEX_FUZZ_BUG`) and fails if the fuzzer reports it green — the harness has
been seen catching that bug.
`make fuzz-proxy` is the socket-side counterpart (`tests/fuzz_proxy.py`): it
starts the sanitizer proxy against a local origin and sends 60 mutated raw
requests — absolute URIs with broken authorities, CONNECT variants, 100 kB
request lines, CRLF injection, invalid UTF-8, truncated heads. A case fails if
the proxy dies, prints a sanitizer report or leaves the connection hanging; a
400/403/501/502 or a reset after the proxy rejected unread bytes is success. The
run reports how many valid requests still got a 200, so a proxy that rejects
everything cannot pass. `make fuzz-proxy-red` builds the same proxy with a
deliberate parser overflow (`APEX_FUZZ_BUG_PROXY`) and requires the fuzzer to
reject it; it does (3/3 failure lines, "caught the deliberate bug").
`make fuzz-http` (`tests/fuzz_http.py`) points the same idea at the MCP HTTP
face: broken request lines, negative/huge/duplicate Content-Length, chunked
bodies, 100 kB and 8.5 MB bodies, invalid UTF-8, a head split across two writes,
wrong paths and methods, plus mutated raw requests. The HTTP face forks a child
per connection, so process liveness is not the judge — the child inherits stderr
and any ASan/UBSan report fails the run. A case also fails on a hang; 200/202/
400/404/405/413 are all legitimate answers. 40 cases, 18 valid 200s.
`make fuzz-http-red` (`APEX_FUZZ_BUG_HTTP`, a heap overflow after a complete
head) is rejected 2/2 with the exact `apex-twin.c` UBSan line.
`make version-check` compares `APEX_VERSION` in `src/apex.h` with the man page
`.TH`, the README status line, the top `CHANGELOG.md` heading, the
`SECURITY.md` supported line and the Makefile tarball name. It runs first in
`tests/run.sh` and at the top of `make release-check`. It exists because
`SECURITY.md` said 0.23.x while the tree was at 0.30.0 for seven releases; leaving
the man page at the old version was seen failing the check with
`docs/apex-twin.1 .TH says 1.0.0, header says 1.0.1`.
`make gate-audit` is a static check of the one invariant: it parses every
`TOOLS_*[]` table and handler body (comments and strings stripped), and rejects
any tool whose schema names a `target` without calling
`gated()`/`gated_cmd()`/`apex_scope_check()`, and any handler that opens a socket
or spawns a process without one of those calls. The only exceptions are the four
record filters that read local state (`asset_list`, `finding_list`,
`report_markdown`, `traffic_list`), named in the script. It also pins the tool
count, so adding a tool forces a review. Renaming the gate call in `portscan`
and `finding_add` produced three violations; the audit is part of `make test`.
`make distcheck` builds the tarball, unpacks it into a temporary directory,
runs `make` and `make test` there, and removes the directory. That is the check
that the thing you ship builds without the working tree.
`make release-check` is the full gate, fail-fast: gate audit, suite, ASan/UBSan
suite, `gcc -fanalyzer`, `fuzz`, `fuzz-proxy`, `fuzz-http`, then `distcheck`. It
takes roughly 5–10 minutes on one core and needs the network for the
example.com checks; `make test` is the fast loop.
`make coverage` builds `apex-twin-cov` with `-O0 --coverage`, runs the suite and
prints per-file line coverage (`tests/coverage.py`, gcov only, no extra tools).
The first measured pass was 55.9%, and the gap passes brought it to **78.7%**.
A second pass added the guard rule table (16 rules plus the three notes), the
process paths (`proc.c` timeout kill at 66.9% → 73.9%: a fake `nmap` that
sleeps past its deadline, a 1.2 MB output that must truncate, a failed exec
reported as 127), `http_paths` base and limit handling, and proxy rewrite edges
(header replacement, wildcard host, invalid file rejected whole). `guard.c`
went 72.5% → 83.0%, `tools_guard.c` 85.4% → 95.1%. A PTY-based Marauder
simulator earlier raised
`tools_radio.c` from 31.7% to 76.2% without hardware: firmware `info`/`help`,
`list`, a `scanall` that ends in `stopscan`, a login-prompt refusal and a
`serial_tx=true` transmit are all tested. The lowest files now are `proc.c`
(fork/exec error paths) and `tools_recon.c` (external binaries). The
`-O0` build also proved a truncation warning in `guard.c` that `-O2` had not:
the copied scope reason is now bounded with a precision, not left to snprintf.
---
## Status
1.0.3. Built and run: 45 tools, 373 checks, 340 fuzz cases and 78.7% line
1.0.4. Built and run: 45 tools, 397 checks, 340 fuzz cases and 79.4% 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
graded lead, `report_markdown` turns findings and inventory into one Markdown,
CSV or JSON file, and `evidence_read`/`traffic_read` get the proof back. `--proxy` puts
the same gate in front of curl and a browser, serves connections in parallel,
forwards chunked and Content-Length bodies, and takes rewrite rules that can set or remove a header
or block a path; `APEX_WEBHOOK` wakes someone when the severity floor is
crossed. The radio is tested against a PTY Marauder (firmware info, scans that
end in `stopscan`, a login prompt that is refused, `serial_tx` gating).
`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, `make analyze` is clean, all three fuzzers reject a deliberately
broken build, and `make coverage` keeps the gaps visible. Not yet wired into a
fleet router.
CSV or JSON file, and `evidence_read`/`traffic_read` get the proof back.
`--proxy` puts the same gate in front of curl and a browser, serves connections
in parallel, forwards chunked and Content-Length bodies, and takes rewrite rules
that can set or remove a header or block a path; `APEX_WEBHOOK` wakes someone
when the severity floor is crossed. The radio is tested against a PTY Marauder
(firmware info, scans that end in `stopscan`, a login prompt that is refused,
`serial_tx` gating). `make install` ships the binary, this README, the docs, the
man page and both units; `--check` reports the operational state without
starting a server. The whole suite also runs under ASan/UBSan, `make analyze` is
clean, all three fuzzers reject a deliberately broken build, and `make coverage`
keeps the gaps visible.
Licence: AGPL-3.0, same as ARTEX.
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.
Not yet wired into a fleet router, and there is no TLS interception.
---
## License
**CNCL 1.1 — Could Not Care Less License.**
No rights reserved. No obligations imposed. Use it, copy it, modify it, break it,
fix it, sell it, give it away, keep your changes private, publish them, feed it
to an AI, relicense it. No attribution, no royalties, no source disclosure, no
conditions. The software is provided as is, without warranty.
The full text is in [LICENSE](LICENSE). If you change that text, it is no longer
CNCL.
ARTEX inspired the design; this C implementation is original work and is offered
under CNCL. The vendored `libmcp` transport is part of this tree.
+1 -1
View File
@@ -111,4 +111,4 @@ reader, a TLS interceptor, a multi-user service, or an agent loop. A feature
that adds a shell, reads target data it was not asked to prove, or widens the
scope without an operator edit is out of scope by design.
Licence: AGPL-3.0, same as ARTEX.
Licence: CNCL 1.1 - Could Not Care Less License; see LICENSE.
+2 -2
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.3" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.0.4" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -201,4 +201,4 @@ and
.I CHANGELOG.md
in the installed documentation directory.
.SH LICENSE
AGPL\-3.0, same as ARTEX.
CNCL 1.1 \- Could Not Care Less License; see LICENSE.
+1 -1
View File
@@ -31,7 +31,7 @@ make install DESTDIR=/tmp/pkg PREFIX=/usr
```
$PREFIX/bin/apex-twin
$PREFIX/share/doc/apex-twin/{README,CHANGELOG,SECURITY,operations,artex-port}.md
$PREFIX/share/doc/apex-twin/{README,CHANGELOG,SECURITY,LICENSE,operations,artex-port}.md
$PREFIX/share/man/man1/apex-twin.1
$PREFIX/lib/systemd/system/apex-twin.service
$PREFIX/lib/systemd/system/apex-twin-proxy.service
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.0.3"
#define APEX_VERSION "1.0.4"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+63
View File
@@ -383,6 +383,69 @@ check("private address allowed when allow_private is true", not err(res[0]),
text(res[0]))
shutil.rmtree(priv_home, ignore_errors=True)
print("\n== scope edges ==")
edge_home = tempfile.mkdtemp(prefix="apex-edge-")
write_scope(edge_home, {
"label": "edges", "expires": "2099-12-31T23:59:59Z",
"allow_private": True,
"allow_ip": ["10.10.0.0/24", "10.10.1.128/25", "2001:db8::/32"],
"deny_ip": ["10.10.0.66"],
"allow_domain": ["example.com", "*.wild.invalid"],
"allow_port": ["80", "8000-8010"],
})
edge_cases = [
("10.10.0.5", 80, True),
("10.10.0.66", 80, False), # deny_ip beats allow_ip
("10.10.0.5", 8000, True), # range lo
("10.10.0.5", 8010, True), # range hi
("10.10.0.5", 7999, False), # one below
("10.10.0.5", 8011, False), # one above
("10.10.1.200", 80, True), # inside the /25
("10.10.1.100", 80, False), # just outside the /25
("2001:db8::1", 80, True), # IPv6 CIDR
("2001:db9::1", 80, False), # outside the IPv6 CIDR
("example.com", 80, True), # allow_domain apex
("api.example.com", 80, True), # plain entry also matches subdomains
("foo.wild.invalid", 80, True), # *.name matches a subdomain
("wild.invalid", 80, False), # *.name does not match the apex
("10.10.0.5:9999", 0, False), # port gleaned from the target
("10.10.0.5.", 80, True), # FQDN trailing dot
]
res, _ = run([call(i + 1, "scope_check", target=t, port=pt)
for i, (t, pt, _ok) in enumerate(edge_cases)], home=edge_home)
by_id = {r.get("id"): r for r in res}
for i, (t, pt, want) in enumerate(edge_cases):
got = json.loads(text(by_id[i + 1]))
check("scope edge %s:%d is %s" % (t, pt, "allowed" if want else "denied"),
got["allowed"] is want, got)
checks = {"deny_ip": "10.10.0.66", "allow_ip": "10.10.1.", "port": ":9999"}
if t == "10.10.0.66":
check("deny wins and says so", "deny_ip" in got["reason"], got["reason"])
if t == "10.10.0.5" and pt in (7999, 8011):
check("port boundary names allow_port",
"allow_port" in got["reason"], got["reason"])
if t in ("10.10.1.100", "2001:db9::1"):
check("an address outside the CIDR says so",
"outside allow_ip" in got["reason"], got["reason"])
if t == "wild.invalid":
check("a wildcard apex is not silently allowed",
"does not resolve" in got["reason"], got["reason"])
bad_scope = os.path.join(edge_home, "broken.json")
with open(bad_scope, "w") as f:
f.write("{not json")
res, _ = run([
call(1, "scope_reload", path=bad_scope),
call(2, "scope_check", target="10.10.0.5", port=80),
], home=edge_home)
by_id = {r.get("id"): r for r in res}
check("an invalid scope file cannot be reloaded", err(by_id[1]),
text(by_id[1]))
after = json.loads(text(by_id[2]))
check("a failed reload closes the gate instead of keeping the old scope",
after["allowed"] is False and "no scope loaded" in after["reason"], after)
shutil.rmtree(edge_home, ignore_errors=True)
# ------------------------------------------------------------------- tools
print("\n== recon that really runs ==")
res, _ = run([