apex-twin 0.6.0: traffic capture, request and raw response as one proof

http_capture is http_request that keeps the exchange: $APEX_HOME/traffic/
tNNNN.http holds the request bytes and the raw response, tNNNN.json holds
target, method, path, status and byte counts. TLS goes through curl, so the
request side is marked reconstructed in the file - the tool says what it did
not see. traffic_list and traffic_read find and replay the pair.

http_once now optionally returns the exact request it wrote, so a plain-HTTP
capture is byte-for-byte what went out. The store parses unquoted numbers and
booleans (simple_long); traffic_read rewinds before reading the pair.

The capture found a real pre-existing bug: status_code() took the first number
in 'HTTP/1.1 200 OK' - the 1 of the version - so http_paths, sqli_probe and
xss_probe had been comparing status 1 for every answer. It now skips the
protocol token; the suite asserts 200, and putting the old function back turns
two checks red.

40 tools, 185 checks. Two new files per capture are asserted on disk, the raw
pair is checked for the request line, the response marker and the status line,
and an out-of-scope capture is refused with the scope reason.
This commit is contained in:
lotherk committed 2026-11-21 06:55:43 +00:00
1 parent c1eff9e319
commit a99da9315c
10 files changed
+676 -24

No files matched your search

+30 -10
View File
@@ -17,8 +17,8 @@ separate, explicitly armed switch.
## Build
```sh
make # apex-twin, ~200 kB static-ish binary, zero warnings under -Werror
make test # 170 end-to-end checks, no mocks
make # apex-twin, ~210 kB static-ish binary, zero warnings under -Werror
make test # 185 end-to-end checks, no mocks
make install # /usr/local/bin/apex-twin
```
@@ -117,7 +117,21 @@ latest reading, so a scan that runs twice does not grow two rows.
`report_markdown` with `include_assets: true` appends the inventory table to the
same file as the findings.
## Tools (37)
## Captured traffic
`http_capture` is `http_request` that keeps the exchange: the request bytes (or
a reconstruction when TLS is handed to curl — the file says which) and the raw
response go to `$APEX_HOME/traffic/tNNNN.http`, with a `tNNNN.json` record
beside it holding target, method, path, status and byte counts. `traffic_list`
finds the pair, `traffic_read` shows it again as text, or base64 when the bytes
are not text.
The capture found an old bug the suite had never exercised: `status_code()`
took the first number in `HTTP/1.1 200 OK`, which is the `1` of the version, so
path discovery and both probes had been comparing status `1` for every answer.
The status is now parsed after the protocol token, and the test asserts `200`.
## Tools (40)
**Scope and bookkeeping** — `scope_show`, `scope_check` (ask the gate without
touching anything), `scope_reload`, `capabilities`, `audit_log`, `evidence_save`
@@ -128,6 +142,9 @@ 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), `tls_cert` (openssl),
`banner`, `http_head`
@@ -204,6 +221,8 @@ $APEX_HOME/
evidence/<ts>-<label>.bin raw proof, 0600
reports/report-<ts>.md rendered findings, 0600, never overwritten
assets/a0001.json one record per target, merged on the next look
traffic/t0001.json one capture: target, method, status, byte counts
traffic/t0001.http the request and the raw response, 0600
```
The audit line is written *before* the action, so a process that dies mid-scan
@@ -217,7 +236,7 @@ finding and the next report no longer mentions it.
make test
```
170 checks, real binary, real DNS, real files written; no mocks. The suite was
185 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
@@ -230,7 +249,8 @@ 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.
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.
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
@@ -238,10 +258,10 @@ this host is an SSH forward to another machine, and a foreign server answered
## Status
0.5.0. Built and run: 37 tools, 170 checks. The loop closes: a probe saves raw
evidence, a finding points at it, `finding_update` gives it a state, an asset
records the host it came from, `report_markdown` turns findings and inventory
into one Markdown or CSV file, and `evidence_read` gets the proof back. Not yet
wired into a fleet router.
0.6.0. Built and run: 40 tools, 185 checks. The loop closes: a probe captures
the exchange as a pair, a finding points at it, `finding_update` gives it a
state, an asset records the host it came from, `report_markdown` turns findings
and inventory into one Markdown or CSV file, and `evidence_read`/`traffic_read`
get the proof back. Not yet wired into a fleet router.
Licence: AGPL-3.0, same as ARTEX.
+5 -3
View File
@@ -20,6 +20,7 @@ module, deliberately left out, or still open.
| Finding lifecycle (`finding_workflow.go`, `finding_verification.go`) | `finding_update`, report status filter | open/confirmed/false-positive/fixed plus a note; no retest runner |
| Evidence (`evidence/store.go`) | `evidence/<ts>-<label>.bin` + `evidence_save`/`_list`/`_read` | 0600 blobs, base64 on read when not text |
| Asset inventory (`server/assets*.go`) | `src/store.c` assets + `asset_*` | One file per target, merged by target, gated on add |
| Traffic archive (`traffic/`) | `src/store.c` traffic + `http_capture`/`traffic_*` | Request/response pair on disk; a capture is a proof, not a proxy |
| Report export (`report/findings.go`) | `tools_report.c` `report_markdown` | Markdown and CSV, severity-sorted, severity and lifecycle tables, optional asset table |
| Budgets / timeouts (`agent/budget.go`) | `APEX_DEFAULT_TIMEOUT_MS`, `APEX_MAX_TIMEOUT_MS` | Per-tool timeout, process-group kill |
| Skills / methodology (`skills/`) | `src/tools_kb.c` | 12 techniques + per-tool pitfalls as data tables |
@@ -39,9 +40,10 @@ module, deliberately left out, or still open.
## Open
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.
1. **Intercepting proxy** (`traffic/`, `intercept/`): `http_capture` stores a
pair, but a forward proxy on loopback that stores every exchange a browser
or curl makes is still missing. The pieces (HTTP parser, traffic store,
audit, gate) are in place; the proxy loop and CONNECT tunnelling are not.
2. **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
+2
View File
@@ -50,6 +50,8 @@ static void build_tools(void)
g_tools[n++] = TOOLS_GUARD[i];
for (i = 0; i < TOOLS_ASSET_N && n < 64; i++)
g_tools[n++] = TOOLS_ASSET[i];
for (i = 0; i < TOOLS_TRAFFIC_N && n < 64; i++)
g_tools[n++] = TOOLS_TRAFFIC[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
+31 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.5.0"
#define APEX_VERSION "0.6.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
@@ -66,6 +66,7 @@ typedef struct {
char evidence_dir[APEX_PATH_MAX];
char report_dir[APEX_PATH_MAX];
char asset_dir[APEX_PATH_MAX];
char traffic_dir[APEX_PATH_MAX];
char serial[128];
int baud;
int default_timeout_ms;
@@ -174,6 +175,35 @@ int apex_asset_read(const char *id, mcp_buf *b);
int apex_asset_update(const char *id, const char *label, const char *ports,
const char *services, const char *tags, const char *note);
int apex_asset_scan(apex_asset *out, int max);
/* --------------------------------------------------------------- traffic */
/*
* One request/response pair as it happened, with the bytes on disk. This is the
* traffic store without the proxy: a capture is a proof, not a memory.
*/
typedef struct {
char id[16];
char ts[40];
char target[256];
int port;
int tls;
char method[16];
char path[512];
int status;
long request_bytes;
long response_bytes;
char raw[APEX_PATH_FULL];
char note[256];
} apex_traffic;
char *apex_traffic_add(const char *target, int port, int tls, const char *method,
const char *path, int status, const char *request,
size_t request_len, const char *response,
size_t response_len, const char *note);
int apex_traffic_list(mcp_buf *b, const char *target_filter, int limit);
/* metadata plus the raw pair, as text or base64 */
int apex_traffic_read(const char *id, mcp_buf *b);
char *apex_evidence_save(const char *label, const char *data, size_t len);
/* newest first; one {"name","bytes","mtime"} per evidence blob */
int apex_evidence_list(mcp_buf *b, int limit);
+2
View File
@@ -150,6 +150,7 @@ void apex_config_init(void)
path_join(g_cfg.evidence_dir, sizeof(g_cfg.evidence_dir), g_cfg.home, "evidence");
path_join(g_cfg.report_dir, sizeof(g_cfg.report_dir), g_cfg.home, "reports");
path_join(g_cfg.asset_dir, sizeof(g_cfg.asset_dir), g_cfg.home, "assets");
path_join(g_cfg.traffic_dir, sizeof(g_cfg.traffic_dir), g_cfg.home, "traffic");
if (scope != NULL && *scope != '\0')
copy_str(g_cfg.scope_file, sizeof(g_cfg.scope_file), scope);
@@ -177,4 +178,5 @@ void apex_config_init(void)
apex_mkdir_p(g_cfg.evidence_dir, 0700);
apex_mkdir_p(g_cfg.report_dir, 0700);
apex_mkdir_p(g_cfg.asset_dir, 0700);
apex_mkdir_p(g_cfg.traffic_dir, 0700);
}
+309
View File
@@ -1258,3 +1258,312 @@ int apex_asset_update(const char *id, const char *label, const char *ports,
apex_audit("asset_update", a.target, 0, 1, a.id, NULL);
return 0;
}
/* ---------------------------------------------------------------- traffic */
static int next_traffic_id(void)
{
int i;
char path[APEX_PATH_FULL];
for (i = 1; i < 1000000; i++) {
char name[32];
snprintf(name, sizeof(name), "t%04d.json", i);
if (apex_path_join(path, sizeof(path), g_cfg.traffic_dir, name) != 0)
return -1;
if (access(path, F_OK) != 0)
return i;
}
return -1;
}
static void traffic_json(mcp_buf *b, const apex_traffic *t)
{
mcp_buf_puts(b, "{\"id\":");
apex_json_str(b, t->id);
mcp_buf_puts(b, ",\"ts\":");
apex_json_str(b, t->ts[0] != '\0' ? t->ts : "?");
mcp_buf_puts(b, ",\"target\":");
apex_json_str(b, t->target);
mcp_buf_printf(b, ",\"port\":%d,\"tls\":%s,\"method\":", t->port,
t->tls ? "true" : "false");
apex_json_str(b, t->method);
mcp_buf_puts(b, ",\"path\":");
apex_json_str(b, t->path);
mcp_buf_printf(b, ",\"status\":%d,\"request_bytes\":%ld,"
"\"response_bytes\":%ld,\"raw\":",
t->status, t->request_bytes, t->response_bytes);
apex_json_str(b, t->raw);
mcp_buf_puts(b, ",\"note\":");
apex_json_str(b, t->note);
mcp_buf_puts(b, "}");
}
/* Numbers and booleans are written unquoted; simple_field only reads strings. */
static long simple_long(const char *json, const char *key, long dflt)
{
char pattern[64];
const char *p;
snprintf(pattern, sizeof(pattern), "\"%s\":", key);
p = strstr(json, pattern);
if (p == NULL)
return dflt;
p += strlen(pattern);
if (*p == '"')
p++;
if (*p == 't')
return 1;
if (*p == 'f')
return 0;
return atol(p);
}
static void parse_traffic(const char *text, apex_traffic *t)
{
memset(t, 0, sizeof(*t));
simple_field(text, "id", t->id, sizeof(t->id));
simple_field(text, "ts", t->ts, sizeof(t->ts));
simple_field(text, "target", t->target, sizeof(t->target));
simple_field(text, "method", t->method, sizeof(t->method));
simple_field(text, "path", t->path, sizeof(t->path));
simple_field(text, "raw", t->raw, sizeof(t->raw));
simple_field(text, "note", t->note, sizeof(t->note));
t->port = (int)simple_long(text, "port", 0);
t->status = (int)simple_long(text, "status", 0);
t->request_bytes = simple_long(text, "request_bytes", 0);
t->response_bytes = simple_long(text, "response_bytes", 0);
t->tls = simple_long(text, "tls", 0) == 1;
}
static int load_traffic_file(const char *path, apex_traffic *t)
{
FILE *f;
char *text;
long size;
f = fopen(path, "rb");
if (f == NULL)
return -1;
if (fseek(f, 0, SEEK_END) != 0) {
fclose(f);
return -1;
}
size = ftell(f);
if (size <= 0 || size > 65536) {
fclose(f);
return -1;
}
rewind(f);
text = malloc((size_t)size + 1);
if (text == NULL) {
fclose(f);
return -1;
}
if (fread(text, 1, (size_t)size, f) != (size_t)size) {
free(text);
fclose(f);
return -1;
}
text[size] = '\0';
fclose(f);
parse_traffic(text, t);
free(text);
return 0;
}
char *apex_traffic_add(const char *target, int port, int tls, const char *method,
const char *path, int status, const char *request,
size_t request_len, const char *response,
size_t response_len, const char *note)
{
int id = next_traffic_id();
apex_traffic t;
char json_path[APEX_PATH_FULL];
char raw_path[APEX_PATH_FULL];
char fname[32];
char rname[32];
char *now;
mcp_buf raw;
mcp_buf js;
if (id < 0 || target == NULL || *target == '\0')
return NULL;
snprintf(t.id, sizeof(t.id), "t%04d", id);
snprintf(fname, sizeof(fname), "%s.json", t.id);
snprintf(rname, sizeof(rname), "%s.http", t.id);
if (apex_path_join(json_path, sizeof(json_path), g_cfg.traffic_dir, fname) != 0 ||
apex_path_join(raw_path, sizeof(raw_path), g_cfg.traffic_dir, rname) != 0)
return NULL;
now = apex_now_iso();
field_copy(t.ts, sizeof(t.ts), now != NULL ? now : "?");
free(now);
field_copy(t.target, sizeof(t.target), target);
t.port = port;
t.tls = tls ? 1 : 0;
field_copy(t.method, sizeof(t.method), method != NULL ? method : "GET");
field_copy(t.path, sizeof(t.path), path);
t.status = status;
t.request_bytes = (long)request_len;
t.response_bytes = (long)response_len;
field_copy(t.raw, sizeof(t.raw), raw_path);
field_copy(t.note, sizeof(t.note), note);
mcp_buf_init(&raw);
if (request != NULL && request_len > 0)
mcp_buf_add(&raw, request, request_len);
if (raw.len > 0 && raw.p[raw.len - 1] != '\n')
mcp_buf_puts(&raw, "\n");
mcp_buf_puts(&raw, "=== RESPONSE (raw) ===\n");
if (response != NULL && response_len > 0)
mcp_buf_add(&raw, response, response_len);
if (apex_write_file(raw_path, raw.p, raw.len, 0600) != 0) {
mcp_buf_free(&raw);
return NULL;
}
mcp_buf_free(&raw);
mcp_buf_init(&js);
traffic_json(&js, &t);
mcp_buf_puts(&js, "\n");
if (apex_write_file(json_path, js.p, js.len, 0600) != 0) {
mcp_buf_free(&js);
unlink(raw_path);
return NULL;
}
mcp_buf_free(&js);
apex_audit("http_capture", target, port, 1, t.id, method);
return apex_strdup(t.id);
}
int apex_traffic_list(mcp_buf *b, const char *target_filter, int limit)
{
char (*names)[32];
int n;
int i;
int shown = 0;
if (limit <= 0)
limit = 100;
if (limit > 512)
limit = 512;
names = malloc((size_t)limit * 32);
if (names == NULL)
return -1;
n = 0;
{
DIR *d = opendir(g_cfg.traffic_dir);
struct dirent *ent;
if (d != NULL) {
while (n < limit && (ent = readdir(d)) != NULL) {
if (ent->d_name[0] == '.' ||
strstr(ent->d_name, ".json") == NULL)
continue;
field_copy(names[n], 32, ent->d_name);
n++;
}
closedir(d);
}
}
if (n > 1)
qsort(names, (size_t)n, 32, name_cmp);
mcp_buf_puts(b, "[");
for (i = 0; i < n && shown < limit; i++) {
char path[APEX_PATH_FULL];
apex_traffic t;
if (apex_path_join(path, sizeof(path), g_cfg.traffic_dir, names[i]) != 0)
continue;
if (load_traffic_file(path, &t) != 0)
continue;
if (target_filter != NULL && *target_filter != '\0' &&
strcmp(target_filter, t.target) != 0)
continue;
if (shown > 0)
mcp_buf_puts(b, ",");
traffic_json(b, &t);
shown++;
}
mcp_buf_puts(b, "]");
free(names);
return shown;
}
int apex_traffic_read(const char *id, mcp_buf *b)
{
char path[APEX_PATH_FULL];
char fname[64];
char rname[64];
apex_traffic t;
FILE *f;
unsigned char *data;
long size;
size_t i;
int textlike = 1;
size_t off;
if (id == NULL || *id == '\0')
return -1;
for (off = 0; id[off] != '\0'; off++)
if (!(id[off] >= '0' && id[off] <= '9') &&
!(id[off] >= 'a' && id[off] <= 'z') &&
!(id[off] >= 'A' && id[off] <= 'Z'))
return -1;
snprintf(fname, sizeof(fname), "%s.json", id);
if (apex_path_join(path, sizeof(path), g_cfg.traffic_dir, fname) != 0)
return -1;
if (load_traffic_file(path, &t) != 0)
return -1;
snprintf(rname, sizeof(rname), "%s.http", id);
if (apex_path_join(path, sizeof(path), g_cfg.traffic_dir, rname) != 0)
return -1;
f = fopen(path, "rb");
if (f == NULL)
return -1;
if (fseek(f, 0, SEEK_END) != 0) {
fclose(f);
return -1;
}
size = ftell(f);
if (size < 0 || size > (8L << 20)) {
fclose(f);
return -1;
}
rewind(f);
data = malloc((size_t)size + 1);
if (data == NULL) {
fclose(f);
return -1;
}
if (size > 0 && fread(data, 1, (size_t)size, f) != (size_t)size) {
free(data);
fclose(f);
return -1;
}
fclose(f);
data[size] = '\0';
for (i = 0; i < (size_t)size; i++) {
unsigned char c = data[i];
if (c != '\n' && c != '\r' && c != '\t' && (c < 0x20 || c > 0x7e)) {
textlike = 0;
break;
}
}
traffic_json(b, &t);
/* traffic_json ends with '}' — reopen it to add the pair */
if (b->len > 0 && b->p[b->len - 1] == '}')
b->p[--b->len] = '\0';
mcp_buf_printf(b, ",\"size\":%ld,\"encoding\":\"%s\",\"data\":\"", size,
textlike ? "text" : "base64");
if (textlike)
mcp_json_escape(b, (const char *)data);
else
base64_put(b, data, (size_t)size);
mcp_buf_puts(b, "\"}");
free(data);
return 0;
}
+2
View File
@@ -30,5 +30,7 @@ extern const mcp_tool TOOLS_GUARD[];
extern const size_t TOOLS_GUARD_N;
extern const mcp_tool TOOLS_ASSET[];
extern const size_t TOOLS_ASSET_N;
extern const mcp_tool TOOLS_TRAFFIC[];
extern const size_t TOOLS_TRAFFIC_N;
#endif /* APEX_TOOLS_H */
+70
View File
@@ -0,0 +1,70 @@
/*
* tools_traffic.c - the captured exchanges, read back.
*
* http_capture (tools_web.c) writes the pair; these two tools find it again.
* A traffic record is not a log line: tNNNN.http holds the request and the raw
* response, so a finding can point at what actually went over the wire.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apex.h"
#include "tools.h"
static void t_traffic_list(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
int limit = mcp_arg_int(args, "limit", 100);
mcp_buf b;
(void)user;
mcp_buf_init(&b);
if (apex_traffic_list(&b, target, limit) < 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "cannot read the traffic directory");
return;
}
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_traffic_read(mcp_conn *c, const mcp_json *args, void *user)
{
const char *id = mcp_arg_string(args, "id");
mcp_buf b;
(void)user;
if (id == NULL || *id == '\0') {
mcp_reply_error(c, "id is required");
return;
}
mcp_buf_init(&b);
if (apex_traffic_read(id, &b) != 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "no such traffic record");
return;
}
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_TRAFFIC[] = {
{ "traffic_list",
"List captured request/response pairs, newest id last, optionally only one "
"target. Each record has id, target, method, path, status, byte counts and "
"the path of the raw pair. Use it to find the exchange you need to show.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"default 100, max 512\"}}}",
t_traffic_list },
{ "traffic_read",
"Read one captured pair by id (t0001, t0002, ...): the metadata plus the raw "
"request and response, as text or base64 when the bytes are binary.",
"{\"type\":\"object\",\"properties\":{"
"\"id\":{\"type\":\"string\"}},"
"\"required\":[\"id\"]}",
t_traffic_read },
};
const size_t TOOLS_TRAFFIC_N = sizeof(TOOLS_TRAFFIC) / sizeof(TOOLS_TRAFFIC[0]);
+182 -7
View File
@@ -63,7 +63,8 @@ static ssize_t read_all(int fd, char *buf, size_t cap, int timeout_ms)
static int http_once(const char *host, int port, int tls, const char *method,
const char *path, const char *body, const char *headers,
int timeout_ms, char **out, size_t *out_len,
char *status_line, size_t status_n)
char *status_line, size_t status_n,
char **req_out, size_t *req_len)
{
int fd;
mcp_buf req;
@@ -72,6 +73,12 @@ static int http_once(const char *host, int port, int tls, const char *method,
ssize_t n;
const char *first_line;
if (req_out != NULL) {
*req_out = NULL;
if (req_len != NULL)
*req_len = 0;
}
if (tls) {
/* curl speaks TLS for us; -i keeps the status line in the output */
char *argv[16];
@@ -136,6 +143,15 @@ static int http_once(const char *host, int port, int tls, const char *method,
close(fd);
return -1;
}
if (req_out != NULL) {
*req_out = malloc(req.len + 1);
if (*req_out != NULL) {
memcpy(*req_out, req.p, req.len);
(*req_out)[req.len] = '\0';
if (req_len != NULL)
*req_len = req.len;
}
}
mcp_buf_free(&req);
resp = malloc(cap + 1);
@@ -192,6 +208,16 @@ static int status_code(const char *status_line)
{
const char *p = status_line;
if (p == NULL)
return 0;
/* "HTTP/1.1 200 OK": the version carries digits too, so skip the protocol
* token instead of taking the first number in the line */
if (strncmp(p, "HTTP/", 5) == 0) {
p = strchr(p, ' ');
if (p == NULL)
return 0;
return atoi(p + 1);
}
while (*p != '\0' && !isdigit((unsigned char)*p))
p++;
return atoi(p);
@@ -295,7 +321,7 @@ static void t_http_request(mcp_conn *c, const mcp_json *args, void *user)
status[0] = '\0';
if (http_once(target, port, tls, method, path, body, headers, 25000, &resp,
&len, status, sizeof(status)) != 0) {
&len, status, sizeof(status), NULL, NULL) != 0) {
mcp_reply_error(c, "no response (connect or TLS failed)");
return;
}
@@ -320,6 +346,137 @@ static void t_http_request(mcp_conn *c, const mcp_json *args, void *user)
free(resp);
}
static void t_http_capture(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
const char *method = mcp_arg_string(args, "method");
const char *body = mcp_arg_string(args, "body");
const char *headers = mcp_arg_string(args, "headers");
const char *note = mcp_arg_string(args, "note");
int port = mcp_arg_int(args, "port", 0);
int tls_arg = mcp_arg_bool(args, "tls", -1);
int tls;
char status[256];
char *resp = NULL;
size_t len = 0;
char *req = NULL;
size_t req_len = 0;
int req_rebuilt = 0;
mcp_buf rebuilt;
mcp_buf b;
char *id;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (!safe_token(target, 255)) {
mcp_reply_error(c, "target contains control characters");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (!safe_token(path, 512) || path[0] != '/') {
mcp_reply_error(c, "path must start with / and contain no control characters");
return;
}
if (method == NULL || *method == '\0')
method = body != NULL ? "POST" : "GET";
{
static const char *ok_methods[] = { "GET", "POST", "PUT", "DELETE",
"PATCH", "OPTIONS", "HEAD", "TRACE" };
size_t k;
for (k = 0; k < sizeof(ok_methods) / sizeof(ok_methods[0]); k++)
if (strcmp(method, ok_methods[k]) == 0)
break;
if (k == sizeof(ok_methods) / sizeof(ok_methods[0])) {
mcp_reply_error(c, "unsupported method");
return;
}
}
if (headers != NULL && strstr(headers, "\r\n\r\n") != NULL) {
mcp_reply_error(c, "headers must not contain a blank line");
return;
}
if (port <= 0)
port = tls_arg == 1 ? 443 : 80;
tls = tls_arg < 0 ? looks_tls(port) : tls_arg;
if (!gated(c, "http_capture", target, port))
return;
if (g_cfg.dry_run) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "DRY RUN, not captured: %s %s://%s:%d%s", method,
tls ? "https" : "http", target, port, path);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
return;
}
status[0] = '\0';
if (http_once(target, port, tls, method, path, body, headers, 25000, &resp,
&len, status, sizeof(status), &req, &req_len) != 0) {
mcp_reply_error(c, "no response (connect or TLS failed)");
return;
}
mcp_buf_init(&rebuilt);
if (req == NULL) {
/* TLS goes through curl, so this side is a description of the
* request, not the bytes on the wire. Say so in the file. */
mcp_buf_puts(&rebuilt, "# reconstructed: this tool does not speak TLS; "
"curl sent the request\n");
mcp_buf_printf(&rebuilt, "%s %s HTTP/1.1\r\nHost: %s:%d\r\n"
"User-Agent: apex-twin/%s\r\n\r\n", method, path, target,
port, APEX_VERSION);
req = rebuilt.p;
req_len = rebuilt.len;
req_rebuilt = 1;
}
id = apex_traffic_add(target, port, tls, method, path, status_code(status),
req, req_len, resp, len, note);
mcp_buf_free(&rebuilt);
if (id == NULL) {
free(resp);
free(req);
mcp_reply_error(c, "cannot write the traffic record");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, id);
mcp_buf_puts(&b, ",\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"tls\":%s,\"method\":\"%s\",\"path\":",
port, tls ? "true" : "false", method);
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"status\":%d,\"request_bytes\":%lu,"
"\"response_bytes\":%lu,\"raw\":",
status_code(status), (unsigned long)req_len,
(unsigned long)len);
{
char raw[APEX_PATH_FULL];
char fname[32];
snprintf(fname, sizeof(fname), "%s.http", id);
if (apex_path_join(raw, sizeof(raw), g_cfg.traffic_dir, fname) == 0)
apex_json_str(&b, raw);
else
mcp_buf_puts(&b, "null");
}
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(id);
free(resp);
if (req != NULL && !req_rebuilt)
free(req);
}
static void t_http_headers(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
@@ -365,8 +522,8 @@ static void t_http_headers(mcp_conn *c, const mcp_json *args, void *user)
return;
}
status[0] = '\0';
if (http_once(target, port, tls, "GET", path, NULL, NULL, 20000, &resp, &len,
status, sizeof(status)) != 0) {
if (http_once(target, port, tls, "GET", path, NULL, NULL, 20000, &resp,
&len, status, sizeof(status), NULL, NULL) != 0) {
mcp_reply_error(c, "no response");
return;
}
@@ -464,7 +621,7 @@ static void t_http_paths(mcp_conn *c, const mcp_json *args, void *user)
tested++;
status[0] = '\0';
if (http_once(target, port, tls, "GET", req_path, NULL, NULL, 8000,
&resp, &len, status, sizeof(status)) != 0)
&resp, &len, status, sizeof(status), NULL, NULL) != 0)
continue;
code = status_code(status);
if (code == 200 || code == 201 || code == 301 || code == 302 ||
@@ -590,7 +747,7 @@ static void t_sqli_probe(mcp_conn *c, const mcp_json *args, void *user)
status[0] = '\0';
if (http_once(target, port, tls, how, url,
method ? body : NULL, NULL, 15000, &resp, &len, status,
sizeof(status)) != 0) {
sizeof(status), NULL, NULL) != 0) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"payload\":");
@@ -682,7 +839,7 @@ static void t_xss_probe(mcp_conn *c, const mcp_json *args, void *user)
}
status[0] = '\0';
if (http_once(target, port, tls, "GET", url, NULL, NULL, 15000, &resp, &len,
status, sizeof(status)) != 0) {
status, sizeof(status), NULL, NULL) != 0) {
mcp_reply_error(c, "no response");
return;
}
@@ -800,6 +957,24 @@ const mcp_tool TOOLS_WEB[] = {
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\",\"path\"]}",
t_http_request },
{ "http_capture",
"Send one HTTP request and keep the exchange as evidence: the request (or a "
"reconstruction when TLS goes through curl) and the raw response go to "
"$APEX_HOME/traffic/tNNNN.http, with a tNNNN.json record beside it. Use it "
"when the traffic itself is the proof, and traffic_read to show it again. "
"Gated like every other request: an out-of-scope target is refused.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80, 443 when tls\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"method\":{\"type\":\"string\"},"
"\"body\":{\"type\":\"string\"},"
"\"headers\":{\"type\":\"string\",\"description\":\"raw lines, CRLF separated\"},"
"\"tls\":{\"type\":\"boolean\"},"
"\"note\":{\"type\":\"string\",\"description\":\"why this exchange "
"matters\"}},"
"\"required\":[\"target\"]}",
t_http_capture },
{ "http_headers",
"Audit the security response headers (HSTS, CSP, frame, nosniff, referrer, "
"permissions) and list what is missing with the reason it matters. Use it "
+43 -3
View File
@@ -99,13 +99,13 @@ res, _ = run([
], home=empty)
check("tools/list answers", any(r.get("id") == 1 for r in res))
tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"]
check("37 tools registered", len(tools) == 37, len(tools))
check("40 tools registered", len(tools) == 40, len(tools))
names = {t["name"] for t in tools}
for need in ("portscan", "nmap", "http_request", "marauder_scan",
"method_playbook", "finding_add", "finding_update", "scope_check",
"report_markdown", "evidence_list", "evidence_read",
"guard_check", "asset_add", "asset_list", "asset_read",
"asset_update"):
"asset_update", "http_capture", "traffic_list", "traffic_read"):
check("tool present: " + need, need in names)
for r in res:
if r.get("id") in (2, 3, 4):
@@ -581,6 +581,46 @@ check("asset writes are audited",
for e in audit3),
[e for e in audit3 if e["tool"] == "asset_add"][:3])
print("\n== traffic capture ==")
res, _ = run([
call(1, "http_capture", target="example.com", port=80, path="/",
note="suite capture"),
call(2, "traffic_list"),
call(3, "traffic_read", id="t0001"),
call(4, "http_capture", target="198.51.100.9", port=80, path="/"),
call(5, "audit_log", limit=200),
])
by_id = {r.get("id"): r for r in res}
cap = json.loads(text(by_id[1]))
check("http_capture returns an id and the real status",
cap["id"] == "t0001" and cap["status"] == 200, cap)
check("http_capture counts both directions",
cap["request_bytes"] > 0 and cap["response_bytes"] > 0, cap)
check("http_capture wrote the raw pair", os.path.isfile(cap["raw"]), cap)
with open(cap["raw"], "r") as f:
raw = f.read()
check("raw pair contains the request line", "GET / HTTP/1.1" in raw, raw[:80])
check("raw pair contains the response marker",
"=== RESPONSE (raw) ===" in raw, raw[:200])
check("raw pair contains the response status", "HTTP/1.1 200" in raw, raw[:200])
listed = json.loads(text(by_id[2]))
check("traffic_list lists the capture", len(listed) == 1 and
listed[0]["id"] == "t0001", listed)
check("traffic_list parses numeric fields",
listed[0]["status"] == 200 and listed[0]["tls"] is False, listed)
back = json.loads(text(by_id[3]))
check("traffic_read returns the pair as text",
back["encoding"] == "text" and back["size"] == os.path.getsize(cap["raw"]),
back)
check("traffic_read carries the request",
"Host: example.com" in back["data"], back["data"][:120])
check("http_capture refuses an out-of-scope target", err(by_id[4]),
text(by_id[4]))
check("http_capture is audited",
any(e["tool"] == "http_capture" and e["decision"] == "allow"
for e in json.loads(text(by_id[5]))),
[e for e in json.loads(text(by_id[5])) if e["tool"] == "http_capture"][:2])
# --------------------------------------------------------------- transport
print("\n== http transport ==")
@@ -625,7 +665,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"]) == 37)
check("http tools/list", len(listing["result"]["tools"]) == 40)
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