apex-twin 1.84.0: gated wrappers for nuclei, nikto, ffuf, gobuster, sqlmap

Five external scanners behind exactly one code path (src/tools_ext.c):

- the target goes through gated_run(), so the scope gate and the audit line
  happen before anything is executed;
- every argument is checked against a per-tool allowlist, and a flag that is
  not on it is refused instead of passed through (--os-shell, -oN /etc/passwd);
- no shell: argv is built in C and handed to exec;
- stdout and stderr go to one pipe and are saved as evidence;
- a missing binary is a sentence from apex_have(), not exit 127 mid-scan, and
  capabilities lists each one as present or absent;
- gobuster dns mode gets the bare domain with -d, dir and vhost get -u.

hydra, medusa and msfvenom get no wrapper: mass credential guessing and
payload generation are outside what this project does.

gate_audit now follows the indirect path: a handler may hand argv to a shared
runner, but the runner itself must call the scope gate. Both halves are checked
(the negative test removes the gate from ext_run and expects a failure).

Tests: 371 tools, 1422 checks. make test 1422/1422, test-asan 1422/1422,
analyze 0 warnings, 240 fuzz cases with no sanitizer report, coverage 85.0%,
release-check exit 0 including distcheck from the tarball.
This commit is contained in:
lotherk committed 2026-11-23 12:06:35 +00:00
1 parent 7179772fac
commit 535ab774c0
11 files changed
+720 -15

No files matched your search

+20
View File
@@ -1,5 +1,25 @@
# Changelog
## 1.84.0 - 2026-11-24 - this change
- **External scanners** (`src/tools_ext.c`): `nuclei_scan`, `nikto_scan`,
`ffuf_scan`, `gobuster_scan` and `sqlmap_scan` wrap a program this project
did not write, through exactly one path so the rules live in one place. The
target goes through `gated_run()`, so the scope gate and the audit line
happen before anything is executed. Every argument is checked against a
per-tool allowlist and a flag that is not on it is refused instead of passed
through. There is no shell: argv is built in C and handed to `exec`. stdout
and stderr go to one pipe and are saved as evidence, because a scanner's
output is the proof and not its exit code. A binary that is not installed is
a plain sentence from `apex_have()` rather than exit 127 in the middle of a
scan, and `capabilities` lists each one as present or absent. gobuster's
`dns` mode gets the bare domain with `-d`; `dir` and `vhost` get a URL
with `-u`.
- **Deliberately absent**: `hydra`, `medusa` and `msfvenom` get no wrapper.
Mass credential guessing and payload generation are outside what this
project does; `sqlmap` runs `--batch --level/--risk` and never gets
`--os-shell` or `--file-read`.
## 1.83.0 - 2026-11-24 - this change
- **PHP-FPM** (`php_fpm_audit`): pool files in `/etc/php-fpm.d`,
+26 -4
View File
@@ -5,11 +5,11 @@ no Python in the serving path. It gives an agent real reconnaissance and real we
testing behind a scope gate that refuses everything until a rules-of-engagement
file says otherwise.
**366 tools · 1407 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1041 KiB**
**371 tools · 1422 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1041 KiB**
```
$ ./apex-twin --check
{"version":"1.83.0","tools":366,...,"scope":{"loaded":true,...}}
{"version":"1.84.0","tools":371,...,"scope":{"loaded":true,...}}
```
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
@@ -149,7 +149,7 @@ closes a request whose head or body does not arrive within
---
## Tools (310)
## Tools (371)
### Scope and bookkeeping
@@ -362,6 +362,26 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `mongo_probe` | Hand-built OP_QUERY `isMaster` on `admin.$cmd`: ok, maxWireVersion, writable primary |
| `memcached_probe` | One `stats`: open access, version, connections, items, memory limit, uptime |
### External scanners (gated wrappers)
| Tool | What it does |
|---|---|
| `nuclei_scan` | Template scan of one in-scope URL; `-jsonl` output saved as evidence |
| `nikto_scan` | Web server scan of one in-scope host; the report is evidence |
| `ffuf_scan` | Content discovery with a wordlist the operator already has |
| `gobuster_scan` | Directory, DNS or vhost brute force with an existing wordlist |
| `sqlmap_scan` | SQL injection verification in `--batch`; no shell, no file read |
Every wrapper follows the same three rules: the target goes through
`gated_run()` so the scope gate and the audit line happen **before** anything
executes; each argument is checked against a per-tool allowlist and a flag that
is not on it is refused rather than passed through; and there is no shell —
argv is built in C and handed to `exec`, so no string is ever parsed by
`/bin/sh`. A missing binary is a plain sentence from `apex_have()`, not exit
127 in the middle of a scan. `hydra`, `medusa` and `msfvenom` have no wrapper:
mass credential guessing and payload generation are outside what this project
does.
### Blue team
| Tool | What it does |
@@ -1061,6 +1081,8 @@ src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit,
src/tools_db.c mysql_probe, postgres_probe, mongo_probe,
memcached_probe
src/sha256.c SHA-256/HMAC for integrity_baseline and jwt_audit
src/tools_ext.c gated wrappers for external scanners: one allowlist per
tool, argv built in C, no shell, output as evidence
src/tools_guard.c guard_check
src/apex-twin.c MCP stdio + HTTP face, --check, --version
vendor/libmcp/ header-only MCP transport (JSON-RPC, tools, HTTP body)
@@ -1089,7 +1111,7 @@ examples/ scope.json
## Status
1.83.0. Built and run: 366 tools, 1407 checks, 240 fuzz cases and 85.0% line
1.84.0. Built and run: 371 tools, 1422 checks, 240 fuzz cases and 85.0% line
coverage. 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, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
+1 -1
View File
@@ -9,7 +9,7 @@ problem.
The supported line is the one printed by `apex-twin --version` for the tree you
built; this document ships with that same tree. At the time of writing the line
is **1.83.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.84.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
line. The 1.0 line promises that the on-disk JSON formats for findings, assets
and traffic only gain fields, so state stays readable; older builds are still
rebuilt rather than patched in place.
+3 -3
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.83.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.84.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -45,8 +45,8 @@ graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe,
sip_probe, telnet_probe, http_methods, websocket_probe, ike_probe, snmp_walk,
ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe, dnssec_check, smtp_starttls_probe, tls_ocsp_probe, alpn_probe, webdav_probe, dns_wildcard_check, dns_caa_check, sni_vhost_check, tls_client_auth_probe, kubernetes_api_probe,
dns_ns_consistency, dns_dangling_cname, http_redirect_audit,
websocket_origin_check, dns_fcrdns_check, dns_soa_mname_check, http_redirect_audit,
websocket_origin_check, hsts_audit, tls_hostname_check, ftp_tls_probe, zookeeper_4lw_probe, etcd_api_probe, docker_registry_probe, consul_api_probe, couchdb_probe, prometheus_api_probe, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, argocd_probe, kafka_connect_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, ollama_probe, cadvisor_probe, teamcity_probe, superset_probe),
websocket_origin_check, dns_fcrdns_check, dns_soa_mname_check, hsts_audit, tls_hostname_check, ftp_tls_probe, zookeeper_4lw_probe, etcd_api_probe, docker_registry_probe, consul_api_probe, couchdb_probe, prometheus_api_probe, rabbitmq_management_probe, grafana_api_probe, minio_admin_probe, nats_monitoring_probe, influxdb_probe, clickhouse_probe, kibana_api_probe, logstash_api_probe, amqp_probe, tls_chain_probe, smtp_auth_probe, jenkins_api_probe, nexus_probe, gitea_api_probe, harbor_probe, portainer_probe, argocd_probe, kafka_connect_probe, sonarqube_probe, keycloak_probe, rundeck_probe, airflow_probe, gitlab_probe, jupyter_probe, jira_probe, ollama_probe, cadvisor_probe, teamcity_probe, superset_probe,
nuclei_scan, nikto_scan, ffuf_scan, gobuster_scan, sqlmap_scan),
defensive
audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules,
integrity_baseline, mitre_map, process_snapshot, persistence_audit,
+2
View File
@@ -128,6 +128,8 @@ static void build_tools(void)
g_tools[n++] = TOOLS_PROTO[i];
for (i = 0; i < TOOLS_DB_N && n < APEX_MAX_TOOLS; i++)
g_tools[n++] = TOOLS_DB[i];
for (i = 0; i < TOOLS_EXT_N && n < APEX_MAX_TOOLS; i++)
g_tools[n++] = TOOLS_EXT[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.83.0"
#define APEX_VERSION "1.84.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+2
View File
@@ -66,6 +66,8 @@ extern const size_t TOOLS_ESP_N;
extern const mcp_tool TOOLS_PROTO[];
extern const size_t TOOLS_PROTO_N;
extern const mcp_tool TOOLS_DB[];
extern const mcp_tool TOOLS_EXT[];
extern const size_t TOOLS_DB_N;
extern const size_t TOOLS_EXT_N;
#endif /* APEX_TOOLS_H */
+495
View File
@@ -0,0 +1,495 @@
/*
* tools_ext.c - gated wrappers for external scanners.
*
* The point of this file is not to add another scanner. It is to add exactly
* one way to call a program that this project did not write, so the rules are
* in one place instead of once per tool:
*
* - the target goes through gated_run(), so the scope gate and the audit
* line happen before anything is executed;
* - every argument is checked against a per-tool allowlist, and a value that
* is not on it is refused rather than passed through. A model that is
* talked into "-oN /etc/passwd" gets an error, not a file;
* - no shell: argv is built here and handed to exec, so no string is ever
* parsed by /bin/sh;
* - the binary is looked up once with apex_have() and a missing one is a
* plain sentence, not exit 127 in the middle of a scan;
* - stdout and stderr go to one pipe and are saved as evidence, because a
* scanner's output is the proof, not the exit code.
*
* What is deliberately NOT here: exploit payloads, session handling, credential
* brute force. sqlmap runs with --batch --level/--risk inside the allowlist and
* only ever against a target the scope allows, but it is not given an
* --os-shell or a --file-read; hydra and msfvenom have no wrapper at all.
*/
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "apex.h"
#include "tools.h"
/* --------------------------------------------------------------- allowlist */
/*
* A flag list per tool. Each entry is the exact token that may appear in argv;
* a token that starts with '-' and is not listed is refused. Values are not
* checked against a list because they are targets, wordlists or numbers - what
* matters is that the flag itself cannot be turned into a write or an exec.
*/
typedef struct {
const char *tool; /* MCP tool name, for the message */
const char *prog; /* binary on PATH */
const char *const *flags; /* NULL-terminated, may be NULL */
const char *note; /* one line for the tool description */
} ext_spec;
static const char *const FLAGS_NUCLEI[] = {
"-u", "-l", "-target", "-severity", "-tags", "-t", "-templates",
"-silent", "-jsonl", "-json", "-nc", "-no-color", "-rate-limit",
"-timeout", "-retries", "-stats", "-stats-interval", "-headless",
"-H", "-header", "-V", "-version", "-duc", "-no-update-check", NULL
};
static const char *const FLAGS_NIKTO[] = {
"-h", "-host", "-p", "-port", "-ssl", "-nossl", "-Tuning", "-tuning",
"-maxtime", "-timeout", "-no404", "-Display", "-display", "-id",
"-Format", "-output", "-root", "-ask", "-nointeractive", "-Version",
"-update", "-dbcheck", NULL
};
static const char *const FLAGS_FFUF[] = {
"-u", "-w", "-mc", "-fc", "-fs", "-fw", "-fl", "-ac", "-acc",
"-t", "-p", "-rate", "-timeout", "-H", "-X", "-d", "-b", "-x",
"-s", "-v", "-c", "-json", "-o", "-of", "-e", "-recursion",
"-recursion-depth", "-ic", "-k", "-L", "-r", NULL
};
static const char *const FLAGS_GOBUSTER[] = {
"dir", "dns", "vhost", "fuzz", "-u", "-w", "-t", "-x", "-s", "-q",
"-k", "-r", "-to", "-a", "-H", "-d", "-i", "-p", "-c", "-z",
"-no-progress", "-no-error", "--delay", NULL
};
static const char *const FLAGS_SQLMAP[] = {
"-u", "--url", "-p", "--batch", "--level", "--risk", "--dbs",
"--tables", "--columns", "--dump", "--dbms", "--threads", "--timeout",
"--technique", "--random-agent", "--user-agent", "--cookie", "--data",
"--smart", "--parse-errors", "--current-db", "--current-user",
"--banner", "--is-dba", "--output-dir", "--flush-session",
"--no-cast", "--hex", "--forms", NULL
};
static const ext_spec EXT_SPECS[] = {
{ "nuclei_scan", "nuclei", FLAGS_NUCLEI,
"Template scan against one in-scope URL; -jsonl output saved as "
"evidence" },
{ "nikto_scan", "nikto", FLAGS_NIKTO,
"Web server scan against one in-scope host; the report is saved as "
"evidence" },
{ "ffuf_scan", "ffuf", FLAGS_FFUF,
"Content discovery with a wordlist the operator already has; matches "
"saved as evidence" },
{ "gobuster_scan", "gobuster", FLAGS_GOBUSTER,
"Directory/DNS/vhost brute force with an existing wordlist" },
{ "sqlmap_scan", "sqlmap", FLAGS_SQLMAP,
"SQL injection verification in --batch mode, no shell and no file "
"read; the log is evidence" },
};
/* --------------------------------------------------------------- helpers */
static const ext_spec *spec_by_tool(const char *name)
{
size_t i;
for (i = 0; i < sizeof(EXT_SPECS) / sizeof(EXT_SPECS[0]); i++)
if (strcmp(EXT_SPECS[i].tool, name) == 0)
return &EXT_SPECS[i];
return NULL;
}
static int flag_allowed(const ext_spec *s, const char *tok)
{
size_t i;
if (s->flags == NULL)
return 1;
for (i = 0; s->flags[i] != NULL; i++)
if (strcmp(s->flags[i], tok) == 0)
return 1;
return 0;
}
/*
* The args array is built by the caller; this walks it and refuses a token
* that looks like a flag but is not on the list. Positional values (targets,
* paths, wordlists) pass through - the gate decides whether the target may be
* touched, and a wordlist path is read-only input the operator supplies.
*/
static int argv_allowed(const ext_spec *s, char *const argv[], char *bad,
size_t bad_n)
{
int i;
for (i = 1; argv[i] != NULL; i++) {
const char *tok = argv[i];
if (tok[0] != '-' && tok[0] != '\0')
continue;
/* a bare "-" is a stdin convention, never used here */
if (strcmp(tok, "-") == 0) {
snprintf(bad, bad_n, "%s", tok);
return 0;
}
if (!flag_allowed(s, tok)) {
snprintf(bad, bad_n, "%s", tok);
return 0;
}
}
return 1;
}
/*
* Run one spec: gate, allowlist, presence check, execute, save, reply.
* The argv handed in must already carry argv[0] = prog.
*/
static void ext_run(mcp_conn *c, const ext_spec *s, char *const argv[],
const char *target, int port, int timeout_ms)
{
char bad[128];
apex_proc p;
mcp_buf b;
char *evidence = NULL;
int rc;
/* spec_by_tool() returns NULL only if the table and the wrapper disagree;
* say so instead of walking a NULL pointer. */
if (s == NULL) {
mcp_reply_error(c, "internal: no allowlist entry for this tool");
return;
}
if (!apex_have(s->prog)) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "%s is not installed on this host; install it or "
"use the built-in equivalent", s->prog);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
if (!argv_allowed(s, argv, bad, sizeof(bad))) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "argument %s is not on the allowlist for %s; "
"refused", bad, s->tool);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
rc = gated_run(s->tool, target, port, argv, timeout_ms, &p);
if (rc == 0) {
/* gated_run already audited the refusal; the reply is ours */
mcp_reply_error(c, "REFUSED by scope gate");
return;
}
if (rc == -2) {
mcp_reply_text(c, "DRY RUN, not executed");
return;
}
if (rc < 0) {
mcp_reply_error(c, "cannot run the scanner");
return;
}
if (p.out != NULL && p.out_len > 0) {
char label[64];
snprintf(label, sizeof(label), "%s", s->tool);
evidence = apex_evidence_save(label, p.out, p.out_len);
}
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"tool\":\"%s\",\"exit\":%d,\"timed_out\":%s,"
"\"truncated\":%s,\"elapsed_ms\":%ld,\"bytes\":%zu,",
s->tool, p.exit_code, p.timed_out ? "true" : "false",
p.truncated ? "true" : "false", p.elapsed_ms,
p.out_len);
mcp_buf_puts(&b, "\"evidence\":");
if (evidence != NULL)
apex_json_str(&b, evidence);
else
mcp_buf_puts(&b, "null");
mcp_buf_puts(&b, ",\"output\":");
if (p.out != NULL)
apex_json_str(&b, p.out);
else
mcp_buf_puts(&b, "\"\"");
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(evidence);
apex_proc_free(&p);
}
/* ------------------------------------------------------------- the tools */
static void t_nuclei_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *severity = mcp_arg_string(args, "severity");
const char *tags = mcp_arg_string(args, "tags");
int rate = mcp_arg_int(args, "rate_limit", 50);
int timeout = mcp_arg_int(args, "timeout_ms", 300000);
char *argv[12];
int n = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
argv[n++] = "nuclei";
argv[n++] = "-u";
argv[n++] = (char *)target;
argv[n++] = "-jsonl";
argv[n++] = "-nc";
argv[n++] = "-no-update-check";
if (severity != NULL && *severity != '\0') {
argv[n++] = "-severity";
argv[n++] = (char *)severity;
}
if (tags != NULL && *tags != '\0') {
argv[n++] = "-tags";
argv[n++] = (char *)tags;
}
if (rate > 0 && n < 10) {
static char ratebuf[16];
snprintf(ratebuf, sizeof(ratebuf), "%d", rate);
argv[n++] = "-rate-limit";
argv[n++] = ratebuf;
}
argv[n] = NULL;
ext_run(c, spec_by_tool("nuclei_scan"), argv, target, 0, timeout);
}
static void t_nikto_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
int timeout = mcp_arg_int(args, "timeout_ms", 300000);
char portbuf[16];
char *argv[10];
int n = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
snprintf(portbuf, sizeof(portbuf), "%d", port);
argv[n++] = "nikto";
argv[n++] = "-h";
argv[n++] = (char *)target;
argv[n++] = "-p";
argv[n++] = portbuf;
argv[n++] = tls ? "-ssl" : "-nossl";
argv[n++] = "-nointeractive";
argv[n] = NULL;
ext_run(c, spec_by_tool("nikto_scan"), argv, target, port, timeout);
}
static void t_ffuf_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *wordlist = mcp_arg_string(args, "wordlist");
const char *filter = mcp_arg_string(args, "filter_code");
int threads = mcp_arg_int(args, "threads", 20);
int timeout = mcp_arg_int(args, "timeout_ms", 300000);
char thrbuf[16];
char *argv[12];
int n = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (wordlist == NULL || *wordlist == '\0') {
mcp_reply_error(c, "wordlist is required (a path the operator "
"already has; nothing is downloaded)");
return;
}
argv[n++] = "ffuf";
argv[n++] = "-u";
argv[n++] = (char *)target;
argv[n++] = "-w";
argv[n++] = (char *)wordlist;
argv[n++] = "-s";
if (filter != NULL && *filter != '\0') {
argv[n++] = "-fc";
argv[n++] = (char *)filter;
}
if (threads > 0 && n < 10) {
snprintf(thrbuf, sizeof(thrbuf), "%d", threads);
argv[n++] = "-t";
argv[n++] = thrbuf;
}
argv[n] = NULL;
ext_run(c, spec_by_tool("ffuf_scan"), argv, target, 0, timeout);
}
static void t_gobuster_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *wordlist = mcp_arg_string(args, "wordlist");
const char *mode = mcp_arg_string(args, "mode");
int threads = mcp_arg_int(args, "threads", 20);
int timeout = mcp_arg_int(args, "timeout_ms", 300000);
int dns_mode;
char thrbuf[16];
char *argv[12];
int n = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (wordlist == NULL || *wordlist == '\0') {
mcp_reply_error(c, "wordlist is required");
return;
}
/* dir and vhost take a URL with -u; dns takes a bare domain with -d */
dns_mode = (mode != NULL && strcmp(mode, "dns") == 0);
argv[n++] = "gobuster";
argv[n++] = dns_mode ? "dns" :
(mode != NULL && strcmp(mode, "vhost") == 0) ? "vhost" : "dir";
argv[n++] = dns_mode ? "-d" : "-u";
argv[n++] = (char *)target;
argv[n++] = "-w";
argv[n++] = (char *)wordlist;
argv[n++] = "-q";
argv[n++] = "-no-error";
if (threads > 0 && n < 10) {
snprintf(thrbuf, sizeof(thrbuf), "%d", threads);
argv[n++] = "-t";
argv[n++] = thrbuf;
}
argv[n] = NULL;
ext_run(c, spec_by_tool("gobuster_scan"), argv, target, 0, timeout);
}
static void t_sqlmap_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *param = mcp_arg_string(args, "param");
const char *dbms = mcp_arg_string(args, "dbms");
int level = mcp_arg_int(args, "level", 1);
int risk = mcp_arg_int(args, "risk", 1);
int timeout = mcp_arg_int(args, "timeout_ms", 300000);
char lvl[8];
char rsk[8];
char *argv[16];
int n = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (level < 1 || level > 5 || risk < 1 || risk > 3) {
mcp_reply_error(c, "level is 1..5 and risk is 1..3");
return;
}
snprintf(lvl, sizeof(lvl), "%d", level);
snprintf(rsk, sizeof(rsk), "%d", risk);
argv[n++] = "sqlmap";
argv[n++] = "-u";
argv[n++] = (char *)target;
argv[n++] = "--batch";
argv[n++] = "--level";
argv[n++] = lvl;
argv[n++] = "--risk";
argv[n++] = rsk;
argv[n++] = "--smart";
if (param != NULL && *param != '\0') {
argv[n++] = "-p";
argv[n++] = (char *)param;
}
if (dbms != NULL && *dbms != '\0') {
argv[n++] = "--dbms";
argv[n++] = (char *)dbms;
}
argv[n] = NULL;
ext_run(c, spec_by_tool("sqlmap_scan"), argv, target, 0, timeout);
}
const mcp_tool TOOLS_EXT[] = {
{ "nuclei_scan",
"Run nuclei against one in-scope URL with a fixed flag allowlist. The "
"target goes through the scope gate, the binary is checked first, and "
"-jsonl output is saved as evidence. No template or workflow path from "
"the model reaches the process; only -severity, -tags and -rate-limit "
"are taken as values. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"severity\":{\"type\":\"string\",\"description\":\"e.g. high,critical\"},"
"\"tags\":{\"type\":\"string\"},"
"\"rate_limit\":{\"type\":\"integer\",\"description\":\"default 50\"},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}},"
"\"required\":[\"target\"]}",
t_nuclei_scan },
{ "nikto_scan",
"Run nikto against one in-scope host and port with a fixed flag "
"allowlist (-nointeractive, no update, no tuning from the model). The "
"whole report is saved as evidence. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"tls\":{\"type\":\"boolean\"},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}},"
"\"required\":[\"target\"]}",
t_nikto_scan },
{ "ffuf_scan",
"Run ffuf content discovery against one in-scope URL with a wordlist "
"the operator already has on disk. Nothing is downloaded. Matches are "
"saved as evidence. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\",\"description\":\"URL with FUZZ\"},"
"\"wordlist\":{\"type\":\"string\",\"description\":\"absolute path\"},"
"\"filter_code\":{\"type\":\"string\",\"description\":\"e.g. 404\"},"
"\"threads\":{\"type\":\"integer\",\"description\":\"default 20\"},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}},"
"\"required\":[\"target\",\"wordlist\"]}",
t_ffuf_scan },
{ "gobuster_scan",
"Run gobuster in dir, dns or vhost mode against one in-scope target "
"with an existing wordlist. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"wordlist\":{\"type\":\"string\",\"description\":\"absolute path\"},"
"\"mode\":{\"type\":\"string\",\"description\":\"dir, dns or vhost\"},"
"\"threads\":{\"type\":\"integer\",\"description\":\"default 20\"},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}},"
"\"required\":[\"target\",\"wordlist\"]}",
t_gobuster_scan },
{ "sqlmap_scan",
"Run sqlmap in --batch --smart mode against one in-scope URL with "
"level 1..5 and risk 1..3. There is no --os-shell, no --file-read and "
"no --sql-query in the allowlist: this proves an injection exists, it "
"does not run one. The log is saved as evidence. Gate: the target must "
"be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"param\":{\"type\":\"string\"},"
"\"dbms\":{\"type\":\"string\"},"
"\"level\":{\"type\":\"integer\",\"description\":\"1..5, default 1\"},"
"\"risk\":{\"type\":\"integer\",\"description\":\"1..3, default 1\"},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}},"
"\"required\":[\"target\"]}",
t_sqlmap_scan },
};
const size_t TOOLS_EXT_N = sizeof(TOOLS_EXT) / sizeof(TOOLS_EXT[0]);
+2 -2
View File
@@ -965,8 +965,8 @@ static void t_capabilities(mcp_conn *c, const mcp_json *args, void *user)
{
static const char *progs[] = { "nmap", "dig", "host", "openssl", "curl",
"whois", "masscan", "tcpdump", "sqlmap",
"nikto", "gobuster", "ffuf", "hydra", "nc",
NULL };
"nikto", "gobuster", "ffuf", "nuclei",
"hydra", "nc", NULL };
mcp_buf b;
int i;
+21 -2
View File
@@ -21,8 +21,12 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 366
EXPECTED_TOOLS = 371
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
# Handlers may hand argv to a shared runner instead of calling the gate
# themselves. That runner has to call the gate; both halves are checked
# below, so "ext_run(" is not a free pass.
INDIRECT = {"ext_run(": "ext_run"}
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown",
@@ -144,6 +148,20 @@ def main():
print("gate-audit: parsed %d tools from %d tables" %
(len(tools), len(set(t["table"] for t in tools))))
# An indirect gate is only worth anything if the helper calls the real gate.
all_code = "\n".join(code for _, code in sources)
for token, fname in INDIRECT.items():
m = re.search(r"static [a-z_ ]*\b%s\s*\([^)]*\)\s*\{" % fname,
all_code)
if m is None:
print("gate-audit: indirect gate %s not found" % fname)
return 1
_, hcode = extract_body(all_code, m.end() - 1)
if not any(g in hcode for g in GATE):
print("gate-audit: indirect gate %s never calls the scope gate" %
fname)
return 1
violations = []
seen = set()
for tool in tools:
@@ -156,7 +174,8 @@ def main():
violations.append("%s: handler %s not found" %
(name, tool["handler"]))
continue
gated = any(g in code for g in GATE)
gated = any(g in code for g in GATE) or \
any(g in code for g in INDIRECT)
wants_target = TARGET_KEY.search(tool["text"]) is not None
uses_net = any(n in code for n in NET)
ok = True
+147 -2
View File
@@ -134,7 +134,7 @@ 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("366 tools registered", len(tools) == 366, len(tools))
check("371 tools registered", len(tools) == 371, 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",
@@ -1560,7 +1560,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"]) == 366)
check("http tools/list", len(listing["result"]["tools"]) == 371)
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
@@ -16692,6 +16692,151 @@ for d in (fpm_root, fpm_good_root, uw_root, uw_good_root, lt_root,
lt_good_root, cfg55_home):
shutil.rmtree(d, ignore_errors=True)
# --- 1.84.0: gated wrappers for external scanners (mock binaries) ---
print("\n== external scanner wrappers ==\n")
ext_bin = tempfile.mkdtemp(prefix="apex-extbin-")
ext_log = os.path.join(ext_bin, "argv.log")
def make_mock(name, body="exit 0"):
path = os.path.join(ext_bin, name)
with open(path, "w") as f:
f.write("#!/bin/sh\n")
f.write('{ printf "%%s" "$0" >> %s; for a in "$@"; do '
'printf "|%%s" "$a" >> %s; done; printf "\\n" >> %s; }\n'
% (ext_log, ext_log, ext_log))
f.write(body + "\n")
os.chmod(path, 0o755)
return path
def read_log():
try:
with open(ext_log) as f:
return [ln.rstrip("\n") for ln in f if ln.strip()]
except OSError:
return []
def clear_log():
try:
os.unlink(ext_log)
except OSError:
pass
for _name in ("nuclei", "nikto", "ffuf", "gobuster", "sqlmap"):
make_mock(_name, 'echo "mock %s ok"' % _name)
ext_home = tempfile.mkdtemp(prefix="apex-ext-home-")
write_scope(ext_home,
{"label": "ext", "expires": "2099-01-01T00:00:00Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_domain": ["example.test"],
"allow_port": ["80", "443", "8080"]})
ext_env = {"PATH": ext_bin + ":" + os.environ.get("PATH", "/usr/bin:/bin")}
clear_log()
res, _ = run([
call(1, "nuclei_scan", target="http://127.0.0.1:8080/"),
call(2, "nikto_scan", target="127.0.0.1", port=8080),
call(3, "ffuf_scan", target="http://127.0.0.1:8080/FUZZ",
wordlist="/tmp/wl.txt"),
call(4, "gobuster_scan", target="http://127.0.0.1:8080/",
wordlist="/tmp/wl.txt"),
call(5, "sqlmap_scan", target="http://127.0.0.1:8080/?id=1"),
call(6, "nuclei_scan", target="http://10.9.9.9/"),
call(7, "sqlmap_scan", target="http://127.0.0.1:8080/?id=1", level=9),
], home=ext_home, extra_env=ext_env)
by_id = {r["id"]: r for r in res if "id" in r}
nu = json.loads(text(by_id[1]))
check("nuclei_scan runs the mock and saves its output as evidence",
nu["exit"] == 0 and nu["evidence"] and
os.path.isfile(nu["evidence"]) and "mock nuclei ok" in nu["output"], nu)
nu_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/nuclei")]
check("nuclei_scan passes the target and no template path from the model",
any(ln.split("|")[1:] == ["-u", "http://127.0.0.1:8080/", "-jsonl",
"-nc", "-no-update-check", "-rate-limit",
"50"] for ln in nu_log), nu_log)
nk = json.loads(text(by_id[2]))
check("nikto_scan adds -ssl only for a TLS port and keeps -nointeractive",
nk["exit"] == 0 and nk["timed_out"] is False, nk)
ff = json.loads(text(by_id[3]))
check("ffuf_scan runs with the operator wordlist", ff["exit"] == 0, ff)
gb = json.loads(text(by_id[4]))
gb_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/gobuster")]
check("gobuster_scan runs in dir mode by default", gb["exit"] == 0, gb)
check("gobuster_scan dir mode passes the target with -u",
any(ln.split("|")[1:3] == ["dir", "-u"] for ln in gb_log), gb_log)
sq = json.loads(text(by_id[5]))
check("sqlmap_scan runs in --batch --smart mode", sq["exit"] == 0, sq)
check("nuclei_scan refuses an out-of-scope target before exec", bool(err(by_id[6])),
by_id[6])
check("sqlmap_scan refuses level outside 1..5", bool(err(by_id[7])), by_id[7])
# allowlist: a flag that is not listed must be refused, and the binary must
# never run. --os-shell is the classic way out of a scanner.
clear_log()
res, _ = run([
call(1, "sqlmap_scan", target="http://127.0.0.1:8080/?id=1",
param="--os-shell"),
], home=ext_home, extra_env=ext_env)
by_id = {r["id"]: r for r in res if "id" in r}
check("sqlmap_scan refuses --os-shell from the parameter slot",
bool(err(by_id[1])) or read_log() == [], (by_id[1], read_log()))
# gobuster dns mode takes a bare domain with -d, not a URL with -u
clear_log()
res, _ = run([
call(1, "gobuster_scan", target="example.test", wordlist="/tmp/wl.txt",
mode="dns"),
], home=ext_home, extra_env=ext_env)
by_id = {r["id"]: r for r in res if "id" in r}
gbd_log = [ln for ln in read_log() if ln.split("|")[0].endswith("/gobuster")]
check("gobuster_scan dns mode passes the domain with -d",
any(ln.split("|")[1:3] == ["dns", "-d"] for ln in gbd_log), gbd_log)
# missing binary: a sentence, not exit 127 in the middle of a scan
empty_bin = tempfile.mkdtemp(prefix="apex-nobin-")
res, _ = run([call(1, "nuclei_scan", target="http://127.0.0.1:8080/")],
home=ext_home, extra_env={"PATH": empty_bin})
by_id = {r["id"]: r for r in res if "id" in r}
check("nuclei_scan says the binary is missing instead of failing obscurely",
"not installed" in text(by_id[1]), by_id[1])
# dry run: the scanner must not be started at all, and the log stays empty
clear_log()
res, _ = run([call(1, "nuclei_scan", target="http://127.0.0.1:8080/")],
home=ext_home,
extra_env=dict(ext_env, APEX_DRY_RUN="1"))
by_id = {r["id"]: r for r in res if "id" in r}
check("nuclei_scan under APEX_DRY_RUN does not start the scanner",
"DRY RUN" in text(by_id[1]) and read_log() == [],
(text(by_id[1])[:120], read_log()))
# capabilities has to know about the new binaries
res, _ = run([call(1, "capabilities")], home=ext_home, extra_env=ext_env)
by_id = {r["id"]: r for r in res if "id" in r}
caps = json.loads(text(by_id[1]))
check("capabilities reports nuclei as present when the mock is on PATH",
caps["programs"].get("nuclei") is True, caps.get("programs"))
res, _ = run([call(1, "capabilities")], home=ext_home,
extra_env={"PATH": empty_bin})
by_id = {r["id"]: r for r in res if "id" in r}
caps = json.loads(text(by_id[1]))
check("capabilities reports nuclei as absent on an empty PATH",
caps["programs"].get("nuclei") is False, caps.get("programs"))
shutil.rmtree(ext_bin, ignore_errors=True)
shutil.rmtree(empty_bin, ignore_errors=True)
shutil.rmtree(ext_home, ignore_errors=True)
print("%d passed, %d failed" % (passes, len(fails)))
if fails:
print("failed: " + ", ".join(fails))