apex-twin 0.5.0: the asset inventory

A finding says what is wrong; an asset says what exists. asset_add puts a host,
domain or IP in $APEX_HOME/assets/aNNNN.json through the same gate as every
other target - an out-of-scope host is refused and the refusal is audited.

One target is one record: a second observation merges into the existing file,
unions the comma-separated port list and replaces the service text with the
latest reading, so a scan that runs twice does not grow two rows. asset_list /
asset_read / asset_update (atomic tmp+rename, audited) complete the set.
report_markdown include_assets=true appends the inventory table to the report.

While making the merge test red, the sabotage exposed a real bug: the create
path used an uninitialised apex_asset, so a fresh record built its port list on
stack garbage (invalid UTF-8 in the reply). memset fixed it.

37 tools, 170 checks. The merge tests were seen red: with the merge disabled,
seven checks failed and asset_list showed three rows for two targets.
This commit is contained in:
lotherk committed 2026-11-21 06:50:16 +00:00
1 parent 854642559b
commit c1eff9e319
10 files changed
+812 -43

No files matched your search

+29 -9
View File
@@ -17,8 +17,8 @@ separate, explicitly armed switch.
## Build
```sh
make # apex-twin, ~170 kB static-ish binary, zero warnings under -Werror
make test # 145 end-to-end checks, no mocks
make # apex-twin, ~200 kB static-ish binary, zero warnings under -Werror
make test # 170 end-to-end checks, no mocks
make install # /usr/local/bin/apex-twin
```
@@ -105,7 +105,19 @@ the update is audited like every other decision.
table, and filters by status — which is what turns "confirmed findings only"
from a promise into an artefact you can send.
## Tools (32)
## The inventory
A finding says what is wrong; an asset says what exists. `asset_add` puts a host,
domain or IP in `$APEX_HOME/assets/`, through the same gate as every other
target — an out-of-scope host cannot enter the inventory, and the refusal is
audited. One target is one record: a second observation merges into the
existing file, unions the port list and replaces the service text with the
latest reading, so a scan that runs twice does not grow two rows.
`report_markdown` with `include_assets: true` appends the inventory table to the
same file as the findings.
## Tools (37)
**Scope and bookkeeping** — `scope_show`, `scope_check` (ask the gate without
touching anything), `scope_reload`, `capabilities`, `audit_log`, `evidence_save`
@@ -113,6 +125,9 @@ touching anything), `scope_reload`, `capabilities`, `audit_log`, `evidence_save`
**Command guard** — `guard_check` (may this shell line run: deny rules first,
then the scope of every target in it)
**Inventory** — `asset_add` (gated; merges by target, unions ports), `asset_list`,
`asset_read`, `asset_update`
**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`
@@ -188,6 +203,7 @@ $APEX_HOME/
findings/f0001.json one finding per file
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
```
The audit line is written *before* the action, so a process that dies mid-scan
@@ -201,7 +217,7 @@ finding and the next report no longer mentions it.
make test
```
145 checks, real binary, real DNS, real files written; no mocks. The suite was
170 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
@@ -211,7 +227,10 @@ slash guard in `evidence_read` disabled `sub/../<blob>` was returned, and with
the `rm` rule disabled the guard fell through to the scope and reported the URL
instead of the delete — the precedence check went red. Disabling the report's
status filter turned five checks red: every filtered report contained the
unfiltered set.
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.
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
@@ -219,9 +238,10 @@ this host is an SSH forward to another machine, and a foreign server answered
## Status
0.4.0. Built and run: 33 tools, 145 checks. The loop closes: a probe saves raw
evidence, a finding points at it, `finding_update` gives it a state,
`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.
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.
Licence: AGPL-3.0, same as ARTEX.
+3 -4
View File
@@ -19,7 +19,8 @@ module, deliberately left out, or still open.
| Findings (`server/findings*.go`, `db`) | `src/store.c` findings + `finding_*` | One JSON file per finding, status lifecycle, atomic update |
| 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 |
| Report export (`report/findings.go`) | `tools_report.c` `report_markdown` | Markdown and CSV, severity-sorted, severity table |
| Asset inventory (`server/assets*.go`) | `src/store.c` assets + `asset_*` | One file per target, merged by target, gated on add |
| 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 |
| Wireless recon (`agent/tools*`, Marauder) | `src/tools_radio.c` | Serial CLI, console guard, allowlist, tx second gate |
@@ -41,9 +42,7 @@ module, deliberately left out, or still 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.
2. **Asset inventory** (`server/assets*.go`): one record per host with the
services seen; findings currently carry a target string only.
3. **Notifications** (`notify/`): webhook on a critical finding.
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
must call `gated()`/`apex_scope_check()` before it opens a socket or spawns a
+2
View File
@@ -48,6 +48,8 @@ static void build_tools(void)
g_tools[n++] = TOOLS_REPORT[i];
for (i = 0; i < TOOLS_GUARD_N && n < 64; i++)
g_tools[n++] = TOOLS_GUARD[i];
for (i = 0; i < TOOLS_ASSET_N && n < 64; i++)
g_tools[n++] = TOOLS_ASSET[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
+32 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "0.4.0"
#define APEX_VERSION "0.5.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
@@ -65,6 +65,7 @@ typedef struct {
char finding_dir[APEX_PATH_MAX];
char evidence_dir[APEX_PATH_MAX];
char report_dir[APEX_PATH_MAX];
char asset_dir[APEX_PATH_MAX];
char serial[128];
int baud;
int default_timeout_ms;
@@ -143,6 +144,36 @@ int apex_finding_status_valid(const char *status);
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);
/* ---------------------------------------------------------------- assets */
/*
* One host, domain or IP as it was seen, with the services observed on it.
* Assets are created through the gate (the handler checks the target first) and
* merged by target: a second observation updates the record instead of making
* a second one.
*/
typedef struct {
char id[16];
char ts[40];
char updated[40];
char target[256];
char label[256];
char kind[16]; /* host | ip | domain */
char ports[512]; /* comma separated, unioned on merge */
char services[1024]; /* latest observation */
char tags[256];
char note[1024];
} apex_asset;
char *apex_asset_add(const char *target, const char *label, const char *kind,
const char *ports, const char *services, const char *tags,
const char *note);
int apex_asset_list(mcp_buf *b, const char *target_filter, int limit);
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);
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
@@ -149,6 +149,7 @@ void apex_config_init(void)
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");
path_join(g_cfg.asset_dir, sizeof(g_cfg.asset_dir), g_cfg.home, "assets");
if (scope != NULL && *scope != '\0')
copy_str(g_cfg.scope_file, sizeof(g_cfg.scope_file), scope);
@@ -175,4 +176,5 @@ void apex_config_init(void)
apex_mkdir_p(g_cfg.finding_dir, 0700);
apex_mkdir_p(g_cfg.evidence_dir, 0700);
apex_mkdir_p(g_cfg.report_dir, 0700);
apex_mkdir_p(g_cfg.asset_dir, 0700);
}
+426
View File
@@ -832,3 +832,429 @@ int apex_audit_tail(mcp_buf *b, int limit)
free(ring);
return count - start;
}
/* ------------------------------------------------------------------ assets */
/*
* Assets are one file per target, merged by target. The id is a counter like a
* finding's; the target is what identifies the record, because two scans that
* see the same host should update one row, not grow a second one.
*/
static int next_asset_id(void)
{
int i;
char path[APEX_PATH_FULL];
for (i = 1; i < 1000000; i++) {
char name[32];
snprintf(name, sizeof(name), "a%04d.json", i);
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, name) != 0)
return -1;
if (access(path, F_OK) != 0)
return i;
}
return -1;
}
static void asset_json(mcp_buf *b, const apex_asset *a)
{
mcp_buf_puts(b, "{\"id\":");
apex_json_str(b, a->id);
mcp_buf_puts(b, ",\"ts\":");
apex_json_str(b, a->ts[0] != '\0' ? a->ts : "?");
mcp_buf_puts(b, ",\"updated\":");
apex_json_str(b, a->updated);
mcp_buf_puts(b, ",\"target\":");
apex_json_str(b, a->target);
mcp_buf_puts(b, ",\"label\":");
apex_json_str(b, a->label);
mcp_buf_puts(b, ",\"kind\":");
apex_json_str(b, a->kind[0] != '\0' ? a->kind : "host");
mcp_buf_puts(b, ",\"ports\":");
apex_json_str(b, a->ports);
mcp_buf_puts(b, ",\"services\":");
apex_json_str(b, a->services);
mcp_buf_puts(b, ",\"tags\":");
apex_json_str(b, a->tags);
mcp_buf_puts(b, ",\"note\":");
apex_json_str(b, a->note);
mcp_buf_puts(b, "}");
}
static int asset_store(const apex_asset *a, const char *path)
{
mcp_buf b;
int rc;
mcp_buf_init(&b);
asset_json(&b, a);
mcp_buf_puts(&b, "\n");
rc = apex_write_file(path, b.p, b.len, 0600);
mcp_buf_free(&b);
return rc;
}
static void parse_asset(const char *text, apex_asset *a)
{
memset(a, 0, sizeof(*a));
simple_field(text, "id", a->id, sizeof(a->id));
simple_field(text, "ts", a->ts, sizeof(a->ts));
simple_field(text, "updated", a->updated, sizeof(a->updated));
simple_field(text, "target", a->target, sizeof(a->target));
simple_field(text, "label", a->label, sizeof(a->label));
simple_field(text, "kind", a->kind, sizeof(a->kind));
simple_field(text, "ports", a->ports, sizeof(a->ports));
simple_field(text, "services", a->services, sizeof(a->services));
simple_field(text, "tags", a->tags, sizeof(a->tags));
simple_field(text, "note", a->note, sizeof(a->note));
}
static int load_asset_file(const char *path, apex_asset *a)
{
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_asset(text, a);
free(text);
return 0;
}
/* Sorted file names, so list/scan do not depend on readdir order. */
static int name_cmp(const void *a, const void *b)
{
return strcmp((const char *)a, (const char *)b);
}
static int asset_names(char (*names)[32], int max)
{
DIR *d;
struct dirent *ent;
int count = 0;
d = opendir(g_cfg.asset_dir);
if (d == NULL)
return 0;
while (count < max && (ent = readdir(d)) != NULL) {
if (ent->d_name[0] == '.' || strstr(ent->d_name, ".json") == NULL)
continue;
field_copy(names[count], 32, ent->d_name);
count++;
}
closedir(d);
if (count > 1)
qsort(names, (size_t)count, 32, name_cmp);
return count;
}
int apex_asset_scan(apex_asset *out, int max)
{
char (*names)[32];
int n;
int i;
int count = 0;
if (out == NULL || max <= 0)
return 0;
names = malloc((size_t)max * 32);
if (names == NULL)
return 0;
n = asset_names(names, max);
for (i = 0; i < n && count < max; i++) {
char path[APEX_PATH_FULL];
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, names[i]) != 0)
continue;
if (load_asset_file(path, &out[count]) == 0 && out[count].id[0] != '\0')
count++;
}
free(names);
return count;
}
static int find_asset(const char *target, apex_asset *out)
{
char (*names)[32];
int n;
int i;
int found = -1;
names = malloc(1024 * 32);
if (names == NULL)
return -1;
n = asset_names(names, 1024);
for (i = 0; i < n; i++) {
char path[APEX_PATH_FULL];
apex_asset a;
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, names[i]) != 0)
continue;
if (load_asset_file(path, &a) != 0)
continue;
if (strcasecmp(a.target, target) == 0) {
*out = a;
found = 0;
break;
}
}
free(names);
return found;
}
/* Union of two comma-separated port lists, case-insensitively. */
static int merge_ports(char *dst, size_t n, const char *add)
{
char tmp[512];
char *tok;
char *save;
size_t used;
if (add == NULL || *add == '\0')
return 0;
field_copy(tmp, sizeof(tmp), add);
used = strlen(dst);
tok = strtok_r(tmp, ",", &save);
while (tok != NULL) {
size_t len;
int present = 0;
char hay[512];
char *h;
char *hs;
while (*tok == ' ' || *tok == '\t')
tok++;
len = strlen(tok);
while (len > 0 && (tok[len - 1] == ' ' || tok[len - 1] == '\t'))
tok[--len] = '\0';
if (len == 0) {
tok = strtok_r(NULL, ",", &save);
continue;
}
field_copy(hay, sizeof(hay), dst);
h = strtok_r(hay, ",", &hs);
while (h != NULL) {
while (*h == ' ' || *h == '\t')
h++;
{
size_t hl = strlen(h);
while (hl > 0 && (h[hl - 1] == ' ' || h[hl - 1] == '\t'))
h[--hl] = '\0';
}
if (strcasecmp(h, tok) == 0) {
present = 1;
break;
}
h = strtok_r(NULL, ",", &hs);
}
if (!present && used + len + 3 < n) {
if (used > 0) {
if (dst[used - 1] != ',')
dst[used++] = ',';
if (used < n - 1)
dst[used++] = ' ';
}
memcpy(dst + used, tok, len);
used += len;
dst[used] = '\0';
}
tok = strtok_r(NULL, ",", &save);
}
return 0;
}
char *apex_asset_add(const char *target, const char *label, const char *kind,
const char *ports, const char *services, const char *tags,
const char *note)
{
apex_asset a;
char path[APEX_PATH_FULL];
char fname[32];
char *now;
memset(&a, 0, sizeof(a));
if (target == NULL || *target == '\0')
return NULL;
now = apex_now_iso();
if (find_asset(target, &a) == 0) {
if (label != NULL && *label != '\0')
field_copy(a.label, sizeof(a.label), label);
if (kind != NULL && *kind != '\0')
field_copy(a.kind, sizeof(a.kind), kind);
merge_ports(a.ports, sizeof(a.ports), ports);
if (services != NULL && *services != '\0')
field_copy(a.services, sizeof(a.services), services);
if (tags != NULL && *tags != '\0')
field_copy(a.tags, sizeof(a.tags), tags);
if (note != NULL && *note != '\0')
field_copy(a.note, sizeof(a.note), note);
field_copy(a.updated, sizeof(a.updated), now != NULL ? now : "?");
snprintf(fname, sizeof(fname), "%s.json", a.id);
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, fname) != 0 ||
asset_store(&a, path) != 0) {
free(now);
return NULL;
}
apex_audit("asset_add", target, 0, 1, a.id, NULL);
free(now);
return apex_strdup(a.id);
}
{
int id = next_asset_id();
if (id < 0) {
free(now);
return NULL;
}
snprintf(a.id, sizeof(a.id), "a%04d", id);
}
field_copy(a.ts, sizeof(a.ts), now != NULL ? now : "?");
field_copy(a.updated, sizeof(a.updated), now != NULL ? now : "?");
field_copy(a.target, sizeof(a.target), target);
field_copy(a.label, sizeof(a.label), label);
field_copy(a.kind, sizeof(a.kind),
kind != NULL && *kind != '\0' ? kind : "host");
merge_ports(a.ports, sizeof(a.ports), ports);
field_copy(a.services, sizeof(a.services), services);
field_copy(a.tags, sizeof(a.tags), tags);
field_copy(a.note, sizeof(a.note), note);
free(now);
snprintf(fname, sizeof(fname), "%s.json", a.id);
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, fname) != 0 ||
asset_store(&a, path) != 0)
return NULL;
apex_audit("asset_add", target, 0, 1, a.id, NULL);
return apex_strdup(a.id);
}
int apex_asset_read(const char *id, mcp_buf *b)
{
char path[APEX_PATH_FULL];
char fname[64];
apex_asset a;
size_t i;
if (id == NULL || *id == '\0')
return -1;
for (i = 0; id[i] != '\0'; i++)
if (!(id[i] >= '0' && id[i] <= '9') && !(id[i] >= 'a' && id[i] <= 'z') &&
!(id[i] >= 'A' && id[i] <= 'Z'))
return -1;
snprintf(fname, sizeof(fname), "%s.json", id);
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, fname) != 0)
return -1;
if (load_asset_file(path, &a) != 0)
return -1;
asset_json(b, &a);
return 0;
}
int apex_asset_list(mcp_buf *b, const char *target_filter, int limit)
{
apex_asset *all;
int n;
int i;
int shown = 0;
if (limit <= 0)
limit = 100;
if (limit > 512)
limit = 512;
all = calloc(512, sizeof(*all));
if (all == NULL)
return -1;
n = apex_asset_scan(all, 512);
mcp_buf_puts(b, "[");
for (i = 0; i < n && shown < limit; i++) {
if (target_filter != NULL && *target_filter != '\0' &&
strcmp(target_filter, all[i].target) != 0)
continue;
if (shown > 0)
mcp_buf_puts(b, ",");
asset_json(b, &all[i]);
shown++;
}
mcp_buf_puts(b, "]");
free(all);
return shown;
}
int apex_asset_update(const char *id, const char *label, const char *ports,
const char *services, const char *tags, const char *note)
{
apex_asset a;
char path[APEX_PATH_FULL];
char tmp[APEX_PATH_FULL];
char fname[64];
char tname[128];
char *now;
{
mcp_buf b;
mcp_buf_init(&b);
if (apex_asset_read(id, &b) != 0) {
mcp_buf_free(&b);
return -1;
}
parse_asset(b.p, &a);
mcp_buf_free(&b);
}
if (label != NULL)
field_copy(a.label, sizeof(a.label), label);
merge_ports(a.ports, sizeof(a.ports), ports);
if (services != NULL && *services != '\0')
field_copy(a.services, sizeof(a.services), services);
if (tags != NULL)
field_copy(a.tags, sizeof(a.tags), tags);
if (note != NULL)
field_copy(a.note, sizeof(a.note), note);
now = apex_now_iso();
field_copy(a.updated, sizeof(a.updated), now != NULL ? now : "?");
free(now);
snprintf(fname, sizeof(fname), "%s.json", a.id);
snprintf(tname, sizeof(tname), "%s.tmp.%ld", fname, (long)getpid());
if (apex_path_join(path, sizeof(path), g_cfg.asset_dir, fname) != 0)
return -1;
if (apex_path_join(tmp, sizeof(tmp), g_cfg.asset_dir, tname) != 0)
return -1;
if (asset_store(&a, tmp) != 0)
return -1;
if (rename(tmp, path) != 0) {
unlink(tmp);
return -1;
}
apex_audit("asset_update", a.target, 0, 1, a.id, NULL);
return 0;
}
+2
View File
@@ -28,5 +28,7 @@ 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;
extern const mcp_tool TOOLS_ASSET[];
extern const size_t TOOLS_ASSET_N;
#endif /* APEX_TOOLS_H */
+187
View File
@@ -0,0 +1,187 @@
/*
* tools_asset.c - the inventory: hosts and what was seen on them.
*
* A finding says "this is wrong"; an asset says "this exists". Both are needed
* for a report that a client can read. asset_add goes through the same gate as
* every other tool that names a target: adding an out-of-scope host to the
* inventory is refused and audited, because an inventory entry is a statement
* that the host was in play.
*
* The store merges by target: a second observation of the same host updates one
* record instead of growing a second one. Ports are unioned, services are the
* latest observation.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apex.h"
#include "tools.h"
static int kind_valid(const char *kind)
{
return kind == NULL || *kind == '\0' || strcmp(kind, "host") == 0 ||
strcmp(kind, "ip") == 0 || strcmp(kind, "domain") == 0;
}
static void reply_asset(mcp_conn *c, const char *id)
{
mcp_buf b;
mcp_buf_init(&b);
if (apex_asset_read(id, &b) != 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "the asset was written but cannot be read back");
return;
}
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_asset_add(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *label = mcp_arg_string(args, "label");
const char *kind = mcp_arg_string(args, "kind");
const char *ports = mcp_arg_string(args, "ports");
const char *services = mcp_arg_string(args, "services");
const char *tags = mcp_arg_string(args, "tags");
const char *note = mcp_arg_string(args, "note");
char *id;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (!kind_valid(kind)) {
mcp_reply_error(c, "kind must be host, ip or domain");
return;
}
if (!gated(c, "asset_add", target, 0))
return;
id = apex_asset_add(target, label, kind, ports, services, tags, note);
if (id == NULL) {
mcp_reply_error(c, "cannot write the asset");
return;
}
reply_asset(c, id);
free(id);
}
static void t_asset_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_asset_list(&b, target, limit) < 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "cannot read the asset directory");
return;
}
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_asset_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_asset_read(id, &b) != 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "no such asset");
return;
}
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_asset_update(mcp_conn *c, const mcp_json *args, void *user)
{
const char *id = mcp_arg_string(args, "id");
const char *label = mcp_arg_string(args, "label");
const char *ports = mcp_arg_string(args, "ports");
const char *services = mcp_arg_string(args, "services");
const char *tags = mcp_arg_string(args, "tags");
const char *note = mcp_arg_string(args, "note");
int rc;
(void)user;
if (id == NULL || *id == '\0') {
mcp_reply_error(c, "id is required");
return;
}
if (label == NULL && (ports == NULL || *ports == '\0') &&
(services == NULL || *services == '\0') && tags == NULL &&
note == NULL) {
mcp_reply_error(c, "nothing to update: pass at least one field");
return;
}
rc = apex_asset_update(id, label, ports, services, tags, note);
if (rc != 0) {
mcp_reply_error(c, "no such asset");
return;
}
reply_asset(c, id);
}
const mcp_tool TOOLS_ASSET[] = {
{ "asset_add",
"Put a host in the engagement inventory, or refresh what is known about "
"it. Gated like every target: an out-of-scope host is refused and "
"audited. Adding the same target twice merges into one record - ports "
"are unioned and services are replaced by the latest observation, so a "
"second scan does not create a duplicate row.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"label\":{\"type\":\"string\",\"description\":\"human name, e.g. "
"'customer portal'\"},"
"\"kind\":{\"type\":\"string\",\"enum\":[\"host\",\"ip\",\"domain\"],"
"\"description\":\"default host\"},"
"\"ports\":{\"type\":\"string\",\"description\":\"e.g. "
"'22/tcp,80/tcp,443/tcp'\"},"
"\"services\":{\"type\":\"string\",\"description\":\"what is running; "
"the latest observation wins\"},"
"\"tags\":{\"type\":\"string\"},"
"\"note\":{\"type\":\"string\"}},"
"\"required\":[\"target\"]}",
t_asset_add },
{ "asset_list",
"List the inventory, optionally only one target. Newest id last, each "
"record with target, kind, ports, services and the last update.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"default 100, max 512\"}}}",
t_asset_list },
{ "asset_read",
"Read one inventory record by id (a0001, a0002, ...).",
"{\"type\":\"object\",\"properties\":{"
"\"id\":{\"type\":\"string\"}},"
"\"required\":[\"id\"]}",
t_asset_read },
{ "asset_update",
"Change an inventory record: label, ports, services, tags or note. Ports "
"are unioned, services replace the previous text when given. The file is "
"rewritten atomically and the change is audited.",
"{\"type\":\"object\",\"properties\":{"
"\"id\":{\"type\":\"string\"},"
"\"label\":{\"type\":\"string\"},"
"\"ports\":{\"type\":\"string\"},"
"\"services\":{\"type\":\"string\"},"
"\"tags\":{\"type\":\"string\"},"
"\"note\":{\"type\":\"string\"}},"
"\"required\":[\"id\"]}",
t_asset_update },
};
const size_t TOOLS_ASSET_N = sizeof(TOOLS_ASSET) / sizeof(TOOLS_ASSET[0]);
+56 -26
View File
@@ -113,7 +113,8 @@ static void md_field(mcp_buf *b, const char *label, const char *value)
static void render_markdown(mcp_buf *b, const apex_finding *rows, int n,
const char *target, const char *min_sev,
const char *status)
const char *status, const apex_asset *assets,
int n_assets)
{
static const char *order[] = { "critical", "high", "medium", "low", "info" };
static const char *states[] = { "open", "confirmed", "false-positive",
@@ -162,6 +163,8 @@ static void render_markdown(mcp_buf *b, const apex_finding *rows, int n,
mcp_buf_printf(b, "- **Minimum severity**: %s\n", min_sev);
if (status != NULL && *status != '\0')
mcp_buf_printf(b, "- **Status filter**: %s\n", status);
if (assets != NULL)
mcp_buf_printf(b, "- **Assets**: %d\n", n_assets);
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]);
@@ -173,31 +176,44 @@ static void render_markdown(mcp_buf *b, const apex_finding *rows, int n,
mcp_buf_puts(b, "\n");
if (n == 0) {
mcp_buf_puts(b, "_No findings match._\n");
free(now);
return;
mcp_buf_puts(b, "_No findings match._\n\n");
} else {
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, "Updated", f->updated);
md_field(b, "Status", status_of(f));
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);
md_field(b, "Note", f->note);
mcp_buf_puts(b, "\n");
}
}
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, "Updated", f->updated);
md_field(b, "Status", status_of(f));
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);
md_field(b, "Note", f->note);
mcp_buf_puts(b, "\n");
if (assets != NULL) {
mcp_buf_printf(b, "## Assets (%d)\n\n", n_assets);
if (n_assets == 0) {
mcp_buf_puts(b, "_No assets recorded._\n");
} else {
mcp_buf_puts(b, "| ID | Target | Kind | Ports | Updated |\n"
"| --- | --- | --- | --- | --- |\n");
for (i = 0; i < n_assets; i++)
mcp_buf_printf(b, "| %s | %s | %s | %s | %s |\n",
assets[i].id, assets[i].target,
assets[i].kind[0] != '\0' ? assets[i].kind : "host",
assets[i].ports, assets[i].updated);
}
}
free(now);
}
@@ -300,10 +316,13 @@ static void t_report_markdown(mcp_conn *c, const mcp_json *args, void *user)
const char *status = mcp_arg_string(args, "status");
const char *format = mcp_arg_string(args, "format");
int save = mcp_arg_bool(args, "save", 1);
int include_assets = mcp_arg_bool(args, "include_assets", 0);
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;
apex_asset *assets = NULL;
int n_assets = 0;
int n;
int kept = 0;
int i;
@@ -335,13 +354,21 @@ static void t_report_markdown(mcp_conn *c, const mcp_json *args, void *user)
}
qsort(rows, (size_t)kept, sizeof(*rows), cmp_finding);
if (include_assets) {
assets = calloc(512, sizeof(*assets));
if (assets != NULL)
n_assets = apex_asset_scan(assets, 512);
}
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, status);
render_markdown(&body, rows, kept, target, min_sev, status,
include_assets ? assets : NULL,
include_assets ? n_assets : 0);
}
path[0] = '\0';
@@ -389,6 +416,7 @@ static void t_report_markdown(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&body);
free(all);
free(rows);
free(assets);
}
static void t_evidence_list(mcp_conn *c, const mcp_json *args, void *user)
@@ -448,7 +476,9 @@ const mcp_tool TOOLS_REPORT[] = {
"\"format\":{\"type\":\"string\",\"enum\":[\"markdown\",\"csv\"],"
"\"description\":\"default markdown\"},"
"\"save\":{\"type\":\"boolean\",\"description\":\"write under "
"$APEX_HOME/reports, default true\"}}}",
"$APEX_HOME/reports, default true\"},"
"\"include_assets\":{\"type\":\"boolean\",\"description\":\"append the "
"inventory table too, default false\"}}}",
t_report_markdown },
{ "evidence_list",
"List the raw evidence blobs saved by evidence_save and by the probes: "
+73 -3
View File
@@ -99,12 +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("33 tools registered", len(tools) == 33, len(tools))
check("37 tools registered", len(tools) == 37, 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"):
"guard_check", "asset_add", "asset_list", "asset_read",
"asset_update"):
check("tool present: " + need, need in names)
for r in res:
if r.get("id") in (2, 3, 4):
@@ -511,6 +512,75 @@ fixed = json.loads(text(by_id[14]))
check("a status is accepted in any case and stored canonical",
fixed["status"] == "fixed", fixed)
print("\n== asset inventory ==")
res, _ = run([
call(1, "asset_add", target="192.0.2.5", label="web", kind="ip",
ports="80/tcp", services="httpd"),
call(2, "asset_add", target="192.0.2.5", ports="80/tcp, 443/tcp",
services="nginx 1.24", tags="prod"),
call(3, "asset_add", target="198.51.100.9"),
call(4, "asset_add", target="example.com", label="site", kind="domain"),
call(5, "asset_list"),
call(6, "asset_read", id="a0001"),
call(7, "asset_update", id="a0001", note="seen twice", ports="22/tcp"),
call(8, "asset_read", id="a0001"),
call(9, "asset_update", id="a9999", note="x"),
call(10, "asset_update", id="a0001"),
call(11, "asset_add", target="192.0.2.6", kind="switch"),
call(12, "report_markdown", include_assets=True, save=False),
call(13, "report_markdown", include_assets=True, format="csv", save=False),
call(14, "audit_log", limit=200),
])
by_id = {r.get("id"): r for r in res}
a1 = json.loads(text(by_id[1]))
check("asset_add creates a record with an id",
a1["id"] == "a0001" and a1["kind"] == "ip", a1)
a2 = json.loads(text(by_id[2]))
check("a second observation merges into the same asset",
a2["id"] == "a0001" and a2["target"] == "192.0.2.5", a2)
check("ports are unioned on merge", a2["ports"] == "80/tcp, 443/tcp", a2)
check("services are the latest observation", a2["services"] == "nginx 1.24",
a2)
check("tags survive the merge", a2["tags"] == "prod", a2)
check("asset_add refuses an out-of-scope target", err(by_id[3]),
text(by_id[3]))
check("asset_add names the scope reason", "outside allow_ip" in text(by_id[3]),
text(by_id[3]))
a2nd = json.loads(text(by_id[4]))
check("a second target gets a second id", a2nd["id"] == "a0002", a2nd)
listed = json.loads(text(by_id[5]))
check("asset_list returns one row per target", len(listed) == 2, listed)
check("asset_list is sorted by id", [a["id"] for a in listed] == ["a0001", "a0002"],
[a["id"] for a in listed])
check("asset_read returns the record",
json.loads(text(by_id[6]))["target"] == "192.0.2.5", text(by_id[6]))
updated = json.loads(text(by_id[7]))
check("asset_update unions ports", updated["ports"] ==
"80/tcp, 443/tcp, 22/tcp", updated)
check("asset_update stores the note", updated["note"] == "seen twice", updated)
check("asset_update refuses an unknown id", err(by_id[9]), text(by_id[9]))
check("asset_update with no field is refused", err(by_id[10]), text(by_id[10]))
check("asset_add validates kind", err(by_id[11]) and
"kind must be" in text(by_id[11]), text(by_id[11]))
check("asset files leave no temp file behind",
not [p for p in os.listdir(os.path.join(ROOT, "assets")) if ".tmp" in p],
os.listdir(os.path.join(ROOT, "assets")))
rep = json.loads(text(by_id[12]))
check("report includes the asset table", "## Assets (2)" in rep["report"],
rep["report"][-400:])
check("report lists an asset target and its ports",
"| a0001 | 192.0.2.5 | ip | 80/tcp, 443/tcp, 22/tcp |" in rep["report"],
rep["report"][-400:])
csvr = json.loads(text(by_id[13]))
check("csv reports do not grow an asset section",
"## Assets" not in csvr["report"], csvr["report"][:200])
audit3 = json.loads(text(by_id[14]))
check("asset writes are audited",
any(e["tool"] == "asset_add" and e["decision"] == "allow" for e in audit3)
and any(e["tool"] == "asset_add" and e["decision"] == "deny"
for e in audit3),
[e for e in audit3 if e["tool"] == "asset_add"][:3])
# --------------------------------------------------------------- transport
print("\n== http transport ==")
@@ -555,7 +625,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"]) == 33)
check("http tools/list", len(listing["result"]["tools"]) == 37)
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