From 32ece44c58066173ab90068ddee72d6d3d6cb738 Mon Sep 17 00:00:00 2001 From: lotherk Date: Sat, 21 Nov 2026 10:42:27 +0000 Subject: [PATCH] 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. --- CHANGELOG.md | 17 +- LICENSE | 83 +++++ Makefile | 4 +- README.md | 908 ++++++++++++++++++++++++--------------------- SECURITY.md | 2 +- docs/apex-twin.1 | 4 +- docs/operations.md | 2 +- src/apex.h | 2 +- tests/run.py | 63 ++++ 9 files changed, 649 insertions(+), 436 deletions(-) create mode 100644 LICENSE diff --git a/CHANGELOG.md b/CHANGELOG.md index 59c1722..14c0e10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c0aced3 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/Makefile b/Makefile index 88a7e55..393c995 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/README.md b/README.md index 769fd42..8d43f19 100644 --- a/README.md +++ b/README.md @@ -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-.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 / ` is refused for the +delete, not for the URL. -The order is the contract and the suite proves it: `rm -rf / ` -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 ` 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/-