apex-twin 0.2.0: report export, evidence reader, scope dry-run
Close the loop between the three stores: - report_markdown renders findings/fNNNN.json into one Markdown or CSV file under $APEX_HOME/reports, critical-first, with a severity table, filterable by exact target and minimum severity. O_EXCL: a report is never overwritten. - evidence_list/evidence_read make the saved proof readable again; text stays text, anything else is base64. Names with a separator, a leading dot or a control character are refused so a blob cannot escape its directory. - scope_check answers 'may I touch this' with the real gate and the real reason, writes the audit line, and opens no socket. apex_finding_scan() gives the report one parsed struct per finding, so the renderer never re-parses JSON. 31 tools, 87 end-to-end checks; the report's closing brace and the evidence traversal guard were both seen failing on purpose before they were trusted.
This commit is contained in:
1 parent
d7bc372208
commit
4168a7d0f9
10 files changed
+903
-15
No files matched your search
@@ -17,8 +17,8 @@ separate, explicitly armed switch.
|
||||
## Build
|
||||
|
||||
```sh
|
||||
make # apex-twin, 136 kB static-ish binary, zero warnings under -Werror
|
||||
make test # 56 end-to-end checks, no mocks
|
||||
make # apex-twin, ~149 kB static-ish binary, zero warnings under -Werror
|
||||
make test # 87 end-to-end checks, no mocks
|
||||
make install # /usr/local/bin/apex-twin
|
||||
```
|
||||
|
||||
@@ -72,10 +72,10 @@ 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 (27)
|
||||
## Tools (31)
|
||||
|
||||
**Scope and bookkeeping** — `scope_show`, `scope_reload`, `capabilities`,
|
||||
`audit_log`, `evidence_save`
|
||||
**Scope and bookkeeping** — `scope_show`, `scope_check` (ask the gate without
|
||||
touching anything), `scope_reload`, `capabilities`, `audit_log`, `evidence_save`
|
||||
|
||||
**Network recon** — `portscan` (in-process TCP connect, no nmap needed), `nmap`
|
||||
(profiles quick/default/full/udp/vuln/http), `dns` (dig), `tls_cert` (openssl),
|
||||
@@ -91,7 +91,9 @@ reflection context), `curl`
|
||||
|
||||
**Method** — `method_techniques`, `method_playbook`, `method_tool`
|
||||
|
||||
**Findings** — `finding_add`, `finding_list`, `finding_read`
|
||||
**Findings** — `finding_add`, `finding_list`, `finding_read`, `report_markdown`
|
||||
(Markdown or CSV, severity-sorted, written to `$APEX_HOME/reports`),
|
||||
`evidence_list`, `evidence_read` (text, or base64 when the bytes are not text)
|
||||
|
||||
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
|
||||
@@ -107,7 +109,9 @@ apex-twin --check # scope, tool count and state dir as JSON, then exit
|
||||
```
|
||||
|
||||
HTTP binds **loopback only**. A service that can scan and transmit must not appear
|
||||
on a LAN by accident; reach it through a tunnel.
|
||||
on a LAN by accident; reach it through a tunnel. `systemd/apex-twin.service` runs
|
||||
exactly that: `--http 127.0.0.1:8797`, a 0700 state dir, `dialout` for the radio,
|
||||
and a capability bounding set without `CAP_NET_RAW` (connect scans need none).
|
||||
|
||||
## The radio
|
||||
|
||||
@@ -145,10 +149,13 @@ $APEX_HOME/
|
||||
audit.log one JSON line per decision, append-only
|
||||
findings/f0001.json one finding per file
|
||||
evidence/<ts>-<label>.bin raw proof, 0600
|
||||
reports/report-<ts>.md rendered findings, 0600, never overwritten
|
||||
```
|
||||
|
||||
The audit line is written *before* the action, so a process that dies mid-scan
|
||||
still left its intent on disk.
|
||||
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
|
||||
|
||||
@@ -156,11 +163,14 @@ still left its intent on disk.
|
||||
make test
|
||||
```
|
||||
|
||||
56 checks, real binary, real DNS, real files written; no mocks. The suite was
|
||||
87 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.
|
||||
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.
|
||||
|
||||
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
|
||||
@@ -168,6 +178,9 @@ this host is an SSH forward to another machine, and a foreign server answered
|
||||
|
||||
## Status
|
||||
|
||||
0.1.0. Built and run. Not yet wired into a systemd unit or a fleet router.
|
||||
0.2.0. Built and run: 31 tools, 87 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.
|
||||
|
||||
Licence: AGPL-3.0, same as ARTEX.
|
||||
@@ -0,0 +1,54 @@
|
||||
# ARTEX → APEX TWIN: what was ported and what was not
|
||||
|
||||
ARTEX (`~/src/ARTEX`) is a Go platform: an LLM-driven pentest engine with an
|
||||
agent loop, a Postgres store, a web UI, a traffic archive, an intercepting proxy
|
||||
and a command guard. APEX TWIN takes the ideas that hold up without a database
|
||||
and without a model in the serving path, and writes them in C99/POSIX with one
|
||||
binary and libc.
|
||||
|
||||
This page keeps the port honest: every ARTEX subsystem is either mapped to a C
|
||||
module, deliberately left out, or still open.
|
||||
|
||||
## Ported
|
||||
|
||||
| ARTEX | APEX TWIN | Notes |
|
||||
|---|---|---|
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| Wireless recon (`agent/tools*`, Marauder) | `src/tools_radio.c` | Serial CLI, console guard, allowlist, tx second gate |
|
||||
|
||||
## Deliberately not ported
|
||||
|
||||
| ARTEX | Why not |
|
||||
|---|---|
|
||||
| Agent engine, planner, intents, goals (`agent/`) | The MCP client is the agent; a second scheduler in C would duplicate its loop and need an LLM client |
|
||||
| Postgres store (`db/`) | Files under `$APEX_HOME` are the whole state; a report is a directory listing |
|
||||
| Web UI (`web/`) | No HTTP UI in the binary; the MCP client is the UI |
|
||||
| Multi-user auth, sessions, chat (`server/auth*.go`) | One operator, one process, loopback transport |
|
||||
| LLM pool and providers (`llmpool/`, `agent/provider*.go`) | No model in the serving path by design |
|
||||
| Traffic archive and intercepting proxy (`traffic/`, `intercept/`) | The largest open item; see below |
|
||||
| Intercept rules in the database | A scope file an operator can read is the C version of the same idea |
|
||||
|
||||
## 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
|
||||
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
|
||||
services seen; findings currently carry a target string only.
|
||||
4. **Finding lifecycle** (`finding_workflow.go`, `finding_verification.go`):
|
||||
status pending/confirmed/false-positive, retest pointers.
|
||||
5. **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
|
||||
process.
|
||||
@@ -44,6 +44,8 @@ static void build_tools(void)
|
||||
g_tools[n++] = TOOLS_RADIO[i];
|
||||
for (i = 0; i < TOOLS_KB_N && n < 64; i++)
|
||||
g_tools[n++] = TOOLS_KB[i];
|
||||
for (i = 0; i < TOOLS_REPORT_N && n < 64; i++)
|
||||
g_tools[n++] = TOOLS_REPORT[i];
|
||||
|
||||
g_srv.name = "apex-twin";
|
||||
g_srv.version = APEX_VERSION;
|
||||
|
||||
+23
-1
@@ -15,7 +15,7 @@
|
||||
|
||||
#include "mcp.h"
|
||||
|
||||
#define APEX_VERSION "0.1.0"
|
||||
#define APEX_VERSION "0.2.0"
|
||||
#define APEX_MAX_OUT (1u << 20)
|
||||
#define APEX_PATH_MAX 512
|
||||
#define APEX_PATH_FULL 1024
|
||||
@@ -64,6 +64,7 @@ typedef struct {
|
||||
char audit_file[APEX_PATH_MAX];
|
||||
char finding_dir[APEX_PATH_MAX];
|
||||
char evidence_dir[APEX_PATH_MAX];
|
||||
char report_dir[APEX_PATH_MAX];
|
||||
char serial[128];
|
||||
int baud;
|
||||
int default_timeout_ms;
|
||||
@@ -106,14 +107,35 @@ char *apex_strdup(const char *s);
|
||||
|
||||
/* ----------------------------------------------------------------- store */
|
||||
|
||||
/* One finding as it sits on disk. Long fields are truncated, never overflowed;
|
||||
* a report is rendered from these, not from parsing JSON a second time. */
|
||||
typedef struct {
|
||||
char id[16];
|
||||
char ts[40];
|
||||
char target[256];
|
||||
char title[512];
|
||||
char severity[16];
|
||||
char confidence[16];
|
||||
char tool[64];
|
||||
char cwe[32];
|
||||
char remediation[1024];
|
||||
char tags[256];
|
||||
char evidence[512];
|
||||
} apex_finding;
|
||||
|
||||
void apex_audit(const char *tool, const char *target, int port, int allowed,
|
||||
const char *reason, const char *cmd);
|
||||
char *apex_finding_add(const char *target, const char *title, const char *severity,
|
||||
const char *confidence, const char *tool, const char *evidence,
|
||||
const char *cwe, const char *remediation, const char *tags);
|
||||
int apex_finding_scan(apex_finding *out, int max);
|
||||
int apex_finding_list(mcp_buf *b, const char *target_filter, int limit);
|
||||
int apex_finding_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);
|
||||
/* read one blob back: {"name","bytes","encoding":"text"|"base64","data"} */
|
||||
int apex_evidence_read(const char *name, mcp_buf *b);
|
||||
int apex_audit_tail(mcp_buf *b, int limit);
|
||||
|
||||
/* ------------------------------------------------------------------ util */
|
||||
|
||||
@@ -148,6 +148,7 @@ void apex_config_init(void)
|
||||
path_join(g_cfg.audit_file, sizeof(g_cfg.audit_file), g_cfg.home, "audit.log");
|
||||
path_join(g_cfg.finding_dir, sizeof(g_cfg.finding_dir), g_cfg.home, "findings");
|
||||
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");
|
||||
|
||||
if (scope != NULL && *scope != '\0')
|
||||
copy_str(g_cfg.scope_file, sizeof(g_cfg.scope_file), scope);
|
||||
@@ -173,4 +174,5 @@ void apex_config_init(void)
|
||||
apex_mkdir_p(g_cfg.home, 0700);
|
||||
apex_mkdir_p(g_cfg.finding_dir, 0700);
|
||||
apex_mkdir_p(g_cfg.evidence_dir, 0700);
|
||||
apex_mkdir_p(g_cfg.report_dir, 0700);
|
||||
}
|
||||
+237
@@ -18,6 +18,7 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
@@ -208,6 +209,173 @@ char *apex_evidence_save(const char *label, const char *data, size_t len)
|
||||
return apex_strdup(path);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- evidence */
|
||||
|
||||
typedef struct {
|
||||
char name[256];
|
||||
long bytes;
|
||||
time_t mtime;
|
||||
} evidence_item;
|
||||
|
||||
static int evidence_cmp(const void *a, const void *b)
|
||||
{
|
||||
const evidence_item *x = a;
|
||||
const evidence_item *y = b;
|
||||
|
||||
/* names start with a UTC timestamp: descending is newest first */
|
||||
return strcmp(y->name, x->name);
|
||||
}
|
||||
|
||||
int apex_evidence_list(mcp_buf *b, int limit)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *ent;
|
||||
evidence_item *items;
|
||||
int count = 0;
|
||||
|
||||
if (limit <= 0)
|
||||
limit = 100;
|
||||
if (limit > 1000)
|
||||
limit = 1000;
|
||||
items = calloc((size_t)limit, sizeof(*items));
|
||||
if (items == NULL)
|
||||
return -1;
|
||||
d = opendir(g_cfg.evidence_dir);
|
||||
if (d != NULL) {
|
||||
while (count < limit && (ent = readdir(d)) != NULL) {
|
||||
char path[APEX_PATH_FULL];
|
||||
struct stat st;
|
||||
|
||||
if (ent->d_name[0] == '.')
|
||||
continue;
|
||||
if (apex_path_join(path, sizeof(path), g_cfg.evidence_dir,
|
||||
ent->d_name) != 0)
|
||||
continue;
|
||||
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
|
||||
continue;
|
||||
snprintf(items[count].name, sizeof(items[count].name), "%s",
|
||||
ent->d_name);
|
||||
items[count].bytes = (long)st.st_size;
|
||||
items[count].mtime = st.st_mtime;
|
||||
count++;
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
qsort(items, (size_t)count, sizeof(*items), evidence_cmp);
|
||||
mcp_buf_puts(b, "[");
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 0; i < count; i++) {
|
||||
char ts[64];
|
||||
struct tm tmv = *gmtime(&items[i].mtime);
|
||||
|
||||
strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%SZ", &tmv);
|
||||
if (i > 0)
|
||||
mcp_buf_puts(b, ",");
|
||||
mcp_buf_puts(b, "{\"name\":");
|
||||
apex_json_str(b, items[i].name);
|
||||
mcp_buf_printf(b, ",\"bytes\":%ld,\"mtime\":", items[i].bytes);
|
||||
apex_json_str(b, ts);
|
||||
mcp_buf_puts(b, "}");
|
||||
}
|
||||
}
|
||||
mcp_buf_puts(b, "]");
|
||||
free(items);
|
||||
return count;
|
||||
}
|
||||
|
||||
static void base64_put(mcp_buf *b, const unsigned char *p, size_t n)
|
||||
{
|
||||
static const char tab[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i + 2 < n; i += 3) {
|
||||
unsigned long v = ((unsigned long)p[i] << 16) |
|
||||
((unsigned long)p[i + 1] << 8) | p[i + 2];
|
||||
char out[4];
|
||||
|
||||
out[0] = tab[(v >> 18) & 63];
|
||||
out[1] = tab[(v >> 12) & 63];
|
||||
out[2] = tab[(v >> 6) & 63];
|
||||
out[3] = tab[v & 63];
|
||||
mcp_buf_add(b, out, 4);
|
||||
}
|
||||
if (i < n) {
|
||||
unsigned long v = (unsigned long)p[i] << 16;
|
||||
char out[4];
|
||||
|
||||
if (i + 1 < n)
|
||||
v |= (unsigned long)p[i + 1] << 8;
|
||||
out[0] = tab[(v >> 18) & 63];
|
||||
out[1] = tab[(v >> 12) & 63];
|
||||
out[2] = (i + 1 < n) ? tab[(v >> 6) & 63] : '=';
|
||||
out[3] = '=';
|
||||
mcp_buf_add(b, out, 4);
|
||||
}
|
||||
}
|
||||
|
||||
int apex_evidence_read(const char *name, mcp_buf *b)
|
||||
{
|
||||
char path[APEX_PATH_FULL];
|
||||
struct stat st;
|
||||
FILE *f;
|
||||
unsigned char *data;
|
||||
size_t i;
|
||||
int textlike = 1;
|
||||
|
||||
if (name == NULL || *name == '\0' || name[0] == '.')
|
||||
return -1;
|
||||
if (strlen(name) > 200)
|
||||
return -1;
|
||||
for (i = 0; name[i] != '\0'; i++)
|
||||
if (name[i] == '/' || name[i] == '\\' || name[i] < 0x20)
|
||||
return -1;
|
||||
if (apex_path_join(path, sizeof(path), g_cfg.evidence_dir, name) != 0)
|
||||
return -1;
|
||||
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
|
||||
return -1;
|
||||
if (st.st_size < 0 || st.st_size > (8L << 20))
|
||||
return -1;
|
||||
f = fopen(path, "rb");
|
||||
if (f == NULL)
|
||||
return -1;
|
||||
data = malloc((size_t)st.st_size + 1);
|
||||
if (data == NULL) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (st.st_size > 0 &&
|
||||
fread(data, 1, (size_t)st.st_size, f) != (size_t)st.st_size) {
|
||||
free(data);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
fclose(f);
|
||||
data[st.st_size] = '\0';
|
||||
for (i = 0; i < (size_t)st.st_size; i++) {
|
||||
unsigned char c = data[i];
|
||||
|
||||
if (c != '\n' && c != '\r' && c != '\t' && (c < 0x20 || c > 0x7e)) {
|
||||
textlike = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
mcp_buf_puts(b, "{\"name\":");
|
||||
apex_json_str(b, name);
|
||||
mcp_buf_printf(b, ",\"bytes\":%ld,\"encoding\":\"%s\",\"data\":\"",
|
||||
(long)st.st_size, textlike ? "text" : "base64");
|
||||
if (textlike)
|
||||
mcp_json_escape(b, (const char *)data);
|
||||
else
|
||||
base64_put(b, data, (size_t)st.st_size);
|
||||
mcp_buf_puts(b, "\"}");
|
||||
free(data);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static char *simple_field(const char *json, const char *key, char *out, size_t n)
|
||||
{
|
||||
char pattern[64];
|
||||
@@ -240,6 +408,75 @@ static char *simple_field(const char *json, const char *key, char *out, size_t n
|
||||
return out;
|
||||
}
|
||||
|
||||
int apex_finding_scan(apex_finding *out, int max)
|
||||
{
|
||||
DIR *d;
|
||||
struct dirent *ent;
|
||||
int count = 0;
|
||||
|
||||
if (out == NULL || max <= 0)
|
||||
return 0;
|
||||
d = opendir(g_cfg.finding_dir);
|
||||
if (d == NULL)
|
||||
return 0;
|
||||
while (count < max && (ent = readdir(d)) != NULL) {
|
||||
char path[APEX_PATH_FULL];
|
||||
FILE *f;
|
||||
char *text;
|
||||
long size;
|
||||
apex_finding *dst;
|
||||
|
||||
if (ent->d_name[0] == '.' || strstr(ent->d_name, ".json") == NULL)
|
||||
continue;
|
||||
if (apex_path_join(path, sizeof(path), g_cfg.finding_dir, ent->d_name) != 0)
|
||||
continue;
|
||||
f = fopen(path, "rb");
|
||||
if (f == NULL)
|
||||
continue;
|
||||
if (fseek(f, 0, SEEK_END) != 0) {
|
||||
fclose(f);
|
||||
continue;
|
||||
}
|
||||
size = ftell(f);
|
||||
if (size <= 0 || size > 65536) {
|
||||
fclose(f);
|
||||
continue;
|
||||
}
|
||||
rewind(f);
|
||||
text = malloc((size_t)size + 1);
|
||||
if (text == NULL) {
|
||||
fclose(f);
|
||||
continue;
|
||||
}
|
||||
if (fread(text, 1, (size_t)size, f) != (size_t)size) {
|
||||
free(text);
|
||||
fclose(f);
|
||||
continue;
|
||||
}
|
||||
text[size] = '\0';
|
||||
fclose(f);
|
||||
|
||||
dst = &out[count];
|
||||
memset(dst, 0, sizeof(*dst));
|
||||
simple_field(text, "id", dst->id, sizeof(dst->id));
|
||||
simple_field(text, "ts", dst->ts, sizeof(dst->ts));
|
||||
simple_field(text, "target", dst->target, sizeof(dst->target));
|
||||
simple_field(text, "title", dst->title, sizeof(dst->title));
|
||||
simple_field(text, "severity", dst->severity, sizeof(dst->severity));
|
||||
simple_field(text, "confidence", dst->confidence, sizeof(dst->confidence));
|
||||
simple_field(text, "tool", dst->tool, sizeof(dst->tool));
|
||||
simple_field(text, "cwe", dst->cwe, sizeof(dst->cwe));
|
||||
simple_field(text, "remediation", dst->remediation,
|
||||
sizeof(dst->remediation));
|
||||
simple_field(text, "tags", dst->tags, sizeof(dst->tags));
|
||||
simple_field(text, "evidence", dst->evidence, sizeof(dst->evidence));
|
||||
free(text);
|
||||
count++;
|
||||
}
|
||||
closedir(d);
|
||||
return count;
|
||||
}
|
||||
|
||||
int apex_finding_list(mcp_buf *b, const char *target_filter, int limit)
|
||||
{
|
||||
DIR *d;
|
||||
|
||||
@@ -24,5 +24,7 @@ extern const mcp_tool TOOLS_RADIO[];
|
||||
extern const size_t TOOLS_RADIO_N;
|
||||
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;
|
||||
|
||||
#endif /* APEX_TOOLS_H */
|
||||
@@ -270,6 +270,33 @@ static void t_scope_reload(mcp_conn *c, const mcp_json *args, void *user)
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void t_scope_check(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
int port = mcp_arg_int(args, "port", 0);
|
||||
char reason[512];
|
||||
int ok;
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
if (target == NULL || *target == '\0') {
|
||||
mcp_reply_error(c, "target is required");
|
||||
return;
|
||||
}
|
||||
ok = apex_scope_check(target, port, reason, sizeof(reason));
|
||||
/* a decision is a decision even when nothing was touched: log it */
|
||||
apex_audit("scope_check", target, port, ok, reason, NULL);
|
||||
mcp_buf_init(&b);
|
||||
mcp_buf_puts(&b, "{\"target\":");
|
||||
apex_json_str(&b, target);
|
||||
mcp_buf_printf(&b, ",\"port\":%d,\"allowed\":%s,\"reason\":", port,
|
||||
ok ? "true" : "false");
|
||||
apex_json_str(&b, reason);
|
||||
mcp_buf_puts(&b, "}");
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void t_portscan(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
@@ -817,6 +844,17 @@ const mcp_tool TOOLS_RECON[] = {
|
||||
"\"path\":{\"type\":\"string\",\"description\":\"absolute path to a scope JSON; "
|
||||
"omit to reload the current one\"}}}",
|
||||
t_scope_reload },
|
||||
{ "scope_check",
|
||||
"Ask the scope gate about one target without touching it. Returns allowed "
|
||||
"true/false plus the reason, and writes the decision to the audit log. Use "
|
||||
"it to plan an engagement, to test an edited scope, and to answer 'may I "
|
||||
"scan this' before spending a scan on the answer.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\",\"description\":\"host, domain or IP\"},"
|
||||
"\"port\":{\"type\":\"integer\",\"description\":\"optional; when set the "
|
||||
"allow_port list is enforced too\"}},"
|
||||
"\"required\":[\"target\"]}",
|
||||
t_scope_check },
|
||||
{ "portscan",
|
||||
"TCP connect scan of an in-scope target, implemented in-process (no nmap "
|
||||
"needed). Use it for a fast look at which ports answer; use nmap for service "
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
/*
|
||||
* tools_report.c - close the loop: findings become a report, evidence becomes
|
||||
* readable again.
|
||||
*
|
||||
* A finding that cannot leave the store is a note to self. This module renders
|
||||
* everything under findings/ into one Markdown or CSV file, sorted by severity,
|
||||
* and writes it to $APEX_HOME/reports. The evidence saved by the probes is
|
||||
* listed and read back here as well, so a report can point at proof that the
|
||||
* reader can still open.
|
||||
*
|
||||
* Neither renderer touches the network and neither consults the gate: they read
|
||||
* what the gate already allowed, and both are pure functions of the state dir.
|
||||
*/
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "apex.h"
|
||||
#include "tools.h"
|
||||
|
||||
#define REPORT_MAX_FINDINGS 1024
|
||||
|
||||
static int sev_rank(const char *s)
|
||||
{
|
||||
if (s == NULL)
|
||||
return 0;
|
||||
if (strcasecmp(s, "critical") == 0)
|
||||
return 4;
|
||||
if (strcasecmp(s, "high") == 0)
|
||||
return 3;
|
||||
if (strcasecmp(s, "medium") == 0)
|
||||
return 2;
|
||||
if (strcasecmp(s, "low") == 0)
|
||||
return 1;
|
||||
return 0; /* info and anything unrecognised */
|
||||
}
|
||||
|
||||
static const char *sev_canonical(const char *s, int *rank)
|
||||
{
|
||||
if (s != NULL) {
|
||||
if (strcasecmp(s, "critical") == 0) {
|
||||
*rank = 4;
|
||||
return "critical";
|
||||
}
|
||||
if (strcasecmp(s, "high") == 0) {
|
||||
*rank = 3;
|
||||
return "high";
|
||||
}
|
||||
if (strcasecmp(s, "medium") == 0) {
|
||||
*rank = 2;
|
||||
return "medium";
|
||||
}
|
||||
if (strcasecmp(s, "low") == 0) {
|
||||
*rank = 1;
|
||||
return "low";
|
||||
}
|
||||
if (strcasecmp(s, "info") == 0) {
|
||||
*rank = 0;
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
*rank = 0;
|
||||
return "other";
|
||||
}
|
||||
|
||||
static int cmp_finding(const void *a, const void *b)
|
||||
{
|
||||
const apex_finding *x = a;
|
||||
const apex_finding *y = b;
|
||||
int rx = sev_rank(x->severity);
|
||||
int ry = sev_rank(y->severity);
|
||||
int c;
|
||||
|
||||
if (rx != ry)
|
||||
return ry - rx; /* critical first */
|
||||
c = strcmp(y->id, x->id); /* newer id first */
|
||||
return c;
|
||||
}
|
||||
|
||||
static void csv_field(mcp_buf *b, const char *s)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
mcp_buf_puts(b, "\"");
|
||||
if (s != NULL) {
|
||||
for (i = 0; s[i] != '\0'; i++) {
|
||||
char c = s[i];
|
||||
|
||||
if (c == '"')
|
||||
mcp_buf_puts(b, "\"\"");
|
||||
else
|
||||
mcp_buf_add(b, &c, 1);
|
||||
}
|
||||
}
|
||||
mcp_buf_puts(b, "\"");
|
||||
}
|
||||
|
||||
static void md_field(mcp_buf *b, const char *label, const char *value)
|
||||
{
|
||||
if (value == NULL || *value == '\0')
|
||||
return;
|
||||
mcp_buf_printf(b, "- **%s**: %s\n", label, value);
|
||||
}
|
||||
|
||||
static void render_markdown(mcp_buf *b, const apex_finding *rows, int n,
|
||||
const char *target, const char *min_sev)
|
||||
{
|
||||
static const char *order[] = { "critical", "high", "medium", "low", "info" };
|
||||
int counts[5] = { 0, 0, 0, 0, 0 };
|
||||
int other = 0;
|
||||
char *now = apex_now_iso();
|
||||
int i;
|
||||
|
||||
for (i = 0; i < n; i++) {
|
||||
int r;
|
||||
const char *c = sev_canonical(rows[i].severity, &r);
|
||||
|
||||
if (strcmp(c, "critical") == 0)
|
||||
counts[0]++;
|
||||
else if (strcmp(c, "high") == 0)
|
||||
counts[1]++;
|
||||
else if (strcmp(c, "medium") == 0)
|
||||
counts[2]++;
|
||||
else if (strcmp(c, "low") == 0)
|
||||
counts[3]++;
|
||||
else if (strcmp(c, "info") == 0)
|
||||
counts[4]++;
|
||||
else
|
||||
other++;
|
||||
}
|
||||
|
||||
mcp_buf_puts(b, "# APEX TWIN findings report\n\n");
|
||||
mcp_buf_printf(b, "- **Scope label**: %s\n",
|
||||
g_scope.label[0] != '\0' ? g_scope.label : "(none)");
|
||||
mcp_buf_printf(b, "- **Generated**: %s\n", now != NULL ? now : "?");
|
||||
mcp_buf_printf(b, "- **Findings**: %d\n", n);
|
||||
if (target != NULL && *target != '\0')
|
||||
mcp_buf_printf(b, "- **Target filter**: %s\n", target);
|
||||
if (min_sev != NULL && *min_sev != '\0')
|
||||
mcp_buf_printf(b, "- **Minimum severity**: %s\n", min_sev);
|
||||
mcp_buf_puts(b, "\n## Summary\n\n| Severity | Count |\n| --- | --- |\n");
|
||||
for (i = 0; i < 5; i++)
|
||||
mcp_buf_printf(b, "| %s | %d |\n", order[i], counts[i]);
|
||||
if (other > 0)
|
||||
mcp_buf_printf(b, "| other | %d |\n", other);
|
||||
mcp_buf_puts(b, "\n");
|
||||
|
||||
if (n == 0) {
|
||||
mcp_buf_puts(b, "_No findings match._\n");
|
||||
free(now);
|
||||
return;
|
||||
}
|
||||
|
||||
mcp_buf_puts(b, "## Findings\n\n");
|
||||
for (i = 0; i < n; i++) {
|
||||
const apex_finding *f = &rows[i];
|
||||
|
||||
mcp_buf_printf(b, "### %d. [%s] %s\n\n", i + 1,
|
||||
f->severity[0] != '\0' ? f->severity : "info",
|
||||
f->title[0] != '\0' ? f->title : "(untitled)");
|
||||
md_field(b, "ID", f->id);
|
||||
md_field(b, "Target", f->target);
|
||||
md_field(b, "Found", f->ts);
|
||||
md_field(b, "Confidence", f->confidence);
|
||||
md_field(b, "Tool", f->tool);
|
||||
md_field(b, "CWE", f->cwe);
|
||||
md_field(b, "Evidence", f->evidence);
|
||||
md_field(b, "Remediation", f->remediation);
|
||||
md_field(b, "Tags", f->tags);
|
||||
mcp_buf_puts(b, "\n");
|
||||
}
|
||||
free(now);
|
||||
}
|
||||
|
||||
static void render_csv(mcp_buf *b, const apex_finding *rows, int n)
|
||||
{
|
||||
int i;
|
||||
|
||||
mcp_buf_puts(b, "id,target,title,severity,confidence,tool,cwe,evidence,"
|
||||
"remediation,tags,ts\n");
|
||||
for (i = 0; i < n; i++) {
|
||||
const apex_finding *f = &rows[i];
|
||||
|
||||
csv_field(b, f->id);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->target);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->title);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->severity);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->confidence);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->tool);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->cwe);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->evidence);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->remediation);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->tags);
|
||||
mcp_buf_puts(b, ",");
|
||||
csv_field(b, f->ts);
|
||||
mcp_buf_puts(b, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
static int write_new_file(const char *path, const char *body, size_t len)
|
||||
{
|
||||
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
|
||||
size_t off = 0;
|
||||
|
||||
if (fd < 0)
|
||||
return -1;
|
||||
while (off < len) {
|
||||
ssize_t w = write(fd, body + off, len - off);
|
||||
|
||||
if (w <= 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
off += (size_t)w;
|
||||
}
|
||||
return close(fd) == 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
static int save_report(const char *suffix, const char *body, size_t len,
|
||||
char *out, size_t outn)
|
||||
{
|
||||
time_t now = time(NULL);
|
||||
struct tm tmv = *gmtime(&now);
|
||||
char stamp[32];
|
||||
int attempt;
|
||||
|
||||
strftime(stamp, sizeof(stamp), "%Y%m%dT%H%M%SZ", &tmv);
|
||||
for (attempt = 0; attempt < 100; attempt++) {
|
||||
char name[96];
|
||||
char path[APEX_PATH_FULL];
|
||||
|
||||
if (attempt == 0)
|
||||
snprintf(name, sizeof(name), "report-%s.%s", stamp, suffix);
|
||||
else
|
||||
snprintf(name, sizeof(name), "report-%s-%d.%s", stamp, attempt,
|
||||
suffix);
|
||||
if (apex_path_join(path, sizeof(path), g_cfg.report_dir, name) != 0)
|
||||
return -1;
|
||||
/* a report is never overwritten: a second one in the same second
|
||||
* gets a suffix instead of eating the first */
|
||||
if (write_new_file(path, body, len) == 0) {
|
||||
snprintf(out, outn, "%s", path);
|
||||
return 0;
|
||||
}
|
||||
if (errno != EEXIST)
|
||||
return -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- handlers */
|
||||
|
||||
static void t_report_markdown(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *target = mcp_arg_string(args, "target");
|
||||
const char *min_sev = mcp_arg_string(args, "min_severity");
|
||||
const char *format = mcp_arg_string(args, "format");
|
||||
int save = mcp_arg_bool(args, "save", 1);
|
||||
int is_csv = format != NULL && strcasecmp(format, "csv") == 0;
|
||||
int min_rank = min_sev != NULL && *min_sev != '\0' ? sev_rank(min_sev) : 0;
|
||||
apex_finding *all;
|
||||
apex_finding *rows;
|
||||
int n;
|
||||
int kept = 0;
|
||||
int i;
|
||||
mcp_buf body;
|
||||
mcp_buf out;
|
||||
char path[APEX_PATH_FULL];
|
||||
int saved = 0;
|
||||
|
||||
(void)user;
|
||||
all = calloc(REPORT_MAX_FINDINGS, sizeof(*all));
|
||||
rows = calloc(REPORT_MAX_FINDINGS, sizeof(*rows));
|
||||
if (all == NULL || rows == NULL) {
|
||||
free(all);
|
||||
free(rows);
|
||||
mcp_reply_error(c, "out of memory");
|
||||
return;
|
||||
}
|
||||
n = apex_finding_scan(all, REPORT_MAX_FINDINGS);
|
||||
for (i = 0; i < n; i++) {
|
||||
if (target != NULL && *target != '\0' &&
|
||||
strcmp(target, all[i].target) != 0)
|
||||
continue;
|
||||
if (sev_rank(all[i].severity) < min_rank)
|
||||
continue;
|
||||
rows[kept++] = all[i];
|
||||
}
|
||||
qsort(rows, (size_t)kept, sizeof(*rows), cmp_finding);
|
||||
|
||||
mcp_buf_init(&body);
|
||||
{
|
||||
/* one renderer writes into the same buffer, so the format decides */
|
||||
if (is_csv)
|
||||
render_csv(&body, rows, kept);
|
||||
else
|
||||
render_markdown(&body, rows, kept, target, min_sev);
|
||||
}
|
||||
|
||||
path[0] = '\0';
|
||||
if (save)
|
||||
saved = save_report(is_csv ? "csv" : "md", body.p, body.len, path,
|
||||
sizeof(path)) == 0;
|
||||
|
||||
mcp_buf_init(&out);
|
||||
mcp_buf_puts(&out, "{\"format\":\"");
|
||||
mcp_buf_puts(&out, is_csv ? "csv" : "markdown");
|
||||
mcp_buf_printf(&out, "\",\"findings\":%d,\"bytes\":%lu,\"saved\":%s,"
|
||||
"\"path\":", kept, (unsigned long)body.len,
|
||||
saved ? "true" : "false");
|
||||
if (saved)
|
||||
apex_json_str(&out, path);
|
||||
else
|
||||
mcp_buf_puts(&out, "null");
|
||||
mcp_buf_puts(&out, ",\"by_severity\":{");
|
||||
{
|
||||
static const char *keys[] = { "critical", "high", "medium", "low",
|
||||
"info" };
|
||||
int k;
|
||||
|
||||
for (k = 0; k < 5; k++) {
|
||||
int count = 0;
|
||||
|
||||
for (i = 0; i < kept; i++) {
|
||||
int r;
|
||||
const char *cv = sev_canonical(rows[i].severity, &r);
|
||||
|
||||
if (strcmp(cv, keys[k]) == 0)
|
||||
count++;
|
||||
}
|
||||
if (k > 0)
|
||||
mcp_buf_puts(&out, ",");
|
||||
mcp_buf_printf(&out, "\"%s\":%d", keys[k], count);
|
||||
}
|
||||
}
|
||||
mcp_buf_puts(&out, "},\"report\":");
|
||||
apex_json_str(&out, body.p != NULL ? body.p : "");
|
||||
mcp_buf_puts(&out, "}");
|
||||
|
||||
mcp_reply_json(c, out.p);
|
||||
mcp_buf_free(&out);
|
||||
mcp_buf_free(&body);
|
||||
free(all);
|
||||
free(rows);
|
||||
}
|
||||
|
||||
static void t_evidence_list(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
int limit = mcp_arg_int(args, "limit", 100);
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
mcp_buf_init(&b);
|
||||
if (apex_evidence_list(&b, limit) < 0) {
|
||||
mcp_buf_free(&b);
|
||||
mcp_reply_error(c, "cannot read the evidence directory");
|
||||
return;
|
||||
}
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
static void t_evidence_read(mcp_conn *c, const mcp_json *args, void *user)
|
||||
{
|
||||
const char *name = mcp_arg_string(args, "name");
|
||||
mcp_buf b;
|
||||
|
||||
(void)user;
|
||||
if (name == NULL || *name == '\0') {
|
||||
mcp_reply_error(c, "name is required (one entry from evidence_list)");
|
||||
return;
|
||||
}
|
||||
mcp_buf_init(&b);
|
||||
if (apex_evidence_read(name, &b) != 0) {
|
||||
mcp_buf_free(&b);
|
||||
mcp_reply_error(c, "no such evidence file, or it is too large");
|
||||
return;
|
||||
}
|
||||
mcp_reply_json(c, b.p);
|
||||
mcp_buf_free(&b);
|
||||
}
|
||||
|
||||
const mcp_tool TOOLS_REPORT[] = {
|
||||
{ "report_markdown",
|
||||
"Render every recorded finding into one report that a human can send: "
|
||||
"Markdown (default) or CSV, sorted critical-first, with a severity table. "
|
||||
"Use it at the end of an engagement, and after a batch of findings, to "
|
||||
"produce the artefact. The file is written to $APEX_HOME/reports and its "
|
||||
"path is returned together with the rendered text.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"target\":{\"type\":\"string\",\"description\":\"only findings for this "
|
||||
"exact target\"},"
|
||||
"\"min_severity\":{\"type\":\"string\",\"enum\":[\"info\",\"low\",\"medium\","
|
||||
"\"high\",\"critical\"],\"description\":\"drop anything below this; "
|
||||
"default info\"},"
|
||||
"\"format\":{\"type\":\"string\",\"enum\":[\"markdown\",\"csv\"],"
|
||||
"\"description\":\"default markdown\"},"
|
||||
"\"save\":{\"type\":\"boolean\",\"description\":\"write under "
|
||||
"$APEX_HOME/reports, default true\"}}}",
|
||||
t_report_markdown },
|
||||
{ "evidence_list",
|
||||
"List the raw evidence blobs saved by evidence_save and by the probes: "
|
||||
"name, size and UTC timestamp, newest first. Use it before writing a "
|
||||
"report so the report points at files that still exist.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"limit\":{\"type\":\"integer\",\"description\":\"default 100, max 1000\"}}}",
|
||||
t_evidence_list },
|
||||
{ "evidence_read",
|
||||
"Read one evidence blob back by the name evidence_list returned. Text "
|
||||
"comes back as text, anything else as base64, so bytes that a terminal "
|
||||
"cannot show still survive the round trip. Paths outside the evidence "
|
||||
"directory are refused.",
|
||||
"{\"type\":\"object\",\"properties\":{"
|
||||
"\"name\":{\"type\":\"string\",\"description\":\"exact name from "
|
||||
"evidence_list\"}},"
|
||||
"\"required\":[\"name\"]}",
|
||||
t_evidence_read },
|
||||
};
|
||||
|
||||
const size_t TOOLS_REPORT_N = sizeof(TOOLS_REPORT) / sizeof(TOOLS_REPORT[0]);
|
||||
+88
-3
@@ -97,10 +97,11 @@ 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("27 tools registered", len(tools) == 27, len(tools))
|
||||
check("31 tools registered", len(tools) == 31, len(tools))
|
||||
names = {t["name"] for t in tools}
|
||||
for need in ("portscan", "nmap", "http_request", "marauder_scan",
|
||||
"method_playbook", "finding_add"):
|
||||
"method_playbook", "finding_add", "scope_check",
|
||||
"report_markdown", "evidence_list", "evidence_read"):
|
||||
check("tool present: " + need, need in names)
|
||||
for r in res:
|
||||
if r.get("id") in (2, 3, 4):
|
||||
@@ -124,6 +125,10 @@ res, _ = run([
|
||||
call(5, "marauder_cmd", command="attack"), # transmit, tx off
|
||||
call(6, "marauder_cmd", command="rm -rf /"), # not allowlisted
|
||||
call(7, "http_request", target="example.com", port=22, path="/"), # port
|
||||
call(8, "scope_check", target="192.0.2.5", port=80), # in scope
|
||||
call(9, "scope_check", target="192.0.2.66", port=80), # denied ip
|
||||
call(10, "scope_check", target="example.com", port=22), # port
|
||||
call(11, "scope_check", target="203.0.113.9", port=80), # outside
|
||||
])
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
check("scope loaded", '"loaded":true' in text(by_id[1]), text(by_id[1]))
|
||||
@@ -143,6 +148,22 @@ check("refusal names the allowlist", "allowlist" in text(by_id[6]),
|
||||
text(by_id[6]))
|
||||
check("port outside allow_port refused", err(by_id[7]), text(by_id[7]))
|
||||
check("refusal names allow_port", "allow_port" in text(by_id[7]), text(by_id[7]))
|
||||
dry_ok = json.loads(text(by_id[8]))
|
||||
check("scope_check allows an in-scope target", dry_ok["allowed"] is True, dry_ok)
|
||||
check("scope_check allows without touching the target",
|
||||
"audit" not in text(by_id[8]), dry_ok)
|
||||
dry_deny = json.loads(text(by_id[9]))
|
||||
check("scope_check refuses a deny_ip target", dry_deny["allowed"] is False,
|
||||
dry_deny)
|
||||
check("scope_check names deny_ip", "deny_ip" in dry_deny["reason"], dry_deny)
|
||||
dry_port = json.loads(text(by_id[10]))
|
||||
check("scope_check enforces allow_port", dry_port["allowed"] is False, dry_port)
|
||||
check("scope_check names allow_port", "allow_port" in dry_port["reason"],
|
||||
dry_port)
|
||||
dry_out = json.loads(text(by_id[11]))
|
||||
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== scope expiry ==")
|
||||
expired_home = tempfile.mkdtemp(prefix="apex-expired-")
|
||||
@@ -209,6 +230,7 @@ res, _ = run([
|
||||
call(3, "finding_list"),
|
||||
call(4, "finding_read", id="f0001"),
|
||||
call(5, "finding_add", target="198.51.100.5", title="out of scope"),
|
||||
call(6, "evidence_save", label="binary", data="caf\u00e9tail"),
|
||||
])
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
ev = json.loads(text(by_id[1]))
|
||||
@@ -223,6 +245,69 @@ check("finding_read returns the finding", read["id"] == "f0001", read)
|
||||
check("finding for an out-of-scope target is refused", err(by_id[5]),
|
||||
text(by_id[5]))
|
||||
|
||||
print("\n== evidence round trip and report ==")
|
||||
ev_name = os.path.basename(ev["evidence"])
|
||||
binary_name = os.path.basename(json.loads(text(by_id[6]))["evidence"])
|
||||
os.makedirs(os.path.join(ROOT, "evidence", "sub"), exist_ok=True)
|
||||
res, _ = run([
|
||||
call(1, "evidence_list"),
|
||||
call(2, "evidence_read", name=ev_name),
|
||||
call(3, "evidence_read", name=binary_name),
|
||||
call(4, "evidence_read", name="../scope.json"),
|
||||
call(5, "evidence_read", name="sub/../" + ev_name),
|
||||
call(6, "report_markdown"),
|
||||
call(7, "report_markdown", format="csv", target="example.com"),
|
||||
call(8, "report_markdown", target="no.example"),
|
||||
call(9, "report_markdown", min_severity="high", save=False),
|
||||
])
|
||||
by_id = {r.get("id"): r for r in res}
|
||||
listed_ev = json.loads(text(by_id[1]))
|
||||
check("evidence_list sees both blobs", len(listed_ev) == 2, listed_ev)
|
||||
check("evidence_list names the newest first",
|
||||
listed_ev[0]["mtime"] >= listed_ev[-1]["mtime"], listed_ev)
|
||||
back = json.loads(text(by_id[2]))
|
||||
check("evidence_read returns the saved bytes",
|
||||
back["data"] == "HTTP/1.1 200 OK\nServer: x" and back["encoding"] == "text",
|
||||
back)
|
||||
bin_back = json.loads(text(by_id[3]))
|
||||
check("binary evidence comes back as base64",
|
||||
bin_back["encoding"] == "base64" and bin_back["data"] == "Y2Fmw6l0YWls",
|
||||
bin_back)
|
||||
check("evidence_read refuses a path outside the directory", err(by_id[4]),
|
||||
text(by_id[4]))
|
||||
check("evidence_read refuses a parent-directory component", err(by_id[5]),
|
||||
text(by_id[5]))
|
||||
|
||||
report = json.loads(text(by_id[6]))
|
||||
check("report names one finding", report["findings"] == 1, report)
|
||||
check("report counts the severity", report["by_severity"]["medium"] == 1, report)
|
||||
check("report was written to disk", report["saved"] is True and
|
||||
os.path.isfile(report["path"]), report)
|
||||
with open(report["path"], "r") as f:
|
||||
md = f.read()
|
||||
check("report contains the finding title", "Missing CSP" in md, md[:200])
|
||||
check("report contains the severity table", "| medium | 1 |" in md, md[:400])
|
||||
check("report returns the rendered text", "# APEX TWIN findings report" in
|
||||
report["report"], report["report"][:80])
|
||||
|
||||
csv = json.loads(text(by_id[7]))
|
||||
check("csv report uses the requested format", csv["format"] == "csv", csv)
|
||||
with open(csv["path"], "r") as f:
|
||||
rows = f.read().splitlines()
|
||||
check("csv header is stable", rows[0].startswith("id,target,title,severity"), rows[:1])
|
||||
check("csv quotes every field", rows[1].startswith('"f0001","example.com"'), rows[1])
|
||||
check("csv keeps the title intact", '"Missing CSP"' in rows[1], rows[1])
|
||||
|
||||
empty = json.loads(text(by_id[8]))
|
||||
check("report filter can select nothing", empty["findings"] == 0, empty)
|
||||
check("empty report still renders", "_No findings match._" in empty["report"],
|
||||
empty["report"])
|
||||
|
||||
unsaved = json.loads(text(by_id[9]))
|
||||
check("min_severity drops a lower finding", unsaved["findings"] == 0, unsaved)
|
||||
check("save=false writes no file", unsaved["saved"] is False and
|
||||
unsaved["path"] is None, unsaved)
|
||||
|
||||
# --------------------------------------------------------------- transport
|
||||
print("\n== http transport ==")
|
||||
|
||||
@@ -267,7 +352,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"]) == 27)
|
||||
check("http tools/list", len(listing["result"]["tools"]) == 31)
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user