apex-twin 0.1.0: C99/POSIX offensive-security MCP server

Scope gate is the product: deny-by-default, deny beats allow, DNS answers
must stay inside allow_ip, port and radio-transmission are separate switches.
27 tools over libmcp: recon (in-process portscan, nmap, dns, tls, banner),
web (http_request, header audit, path discovery, sqli/xss leads), ESP32
Marauder serial bridge, findings with evidence, and 12 method playbooks.

56 end-to-end checks, seen red with the no-scope branch disabled.
Not yet wired into systemd or a fleet router.
This commit is contained in:
lotherk committed 2026-11-20 21:59:09 +00:00
commit d7bc372208
20 files changed
+6353

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
apex-twin
*.o
+27
View File
@@ -0,0 +1,27 @@
CC ?= cc
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Wpedantic -Werror \
-D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE
LIBDIR ?= vendor/libmcp
PREFIX ?= /usr/local
SRC := $(wildcard src/*.c)
OBJ := $(SRC:.c=.o)
all: apex-twin
apex-twin: $(OBJ)
$(CC) $(CFLAGS) -o $@ $(OBJ)
src/%.o: src/%.c src/apex.h $(LIBDIR)/mcp.h
$(CC) $(CFLAGS) -I$(LIBDIR) -Isrc -c -o $@ $<
test: apex-twin
./tests/run.sh
install: apex-twin
mkdir -p $(DESTDIR)$(PREFIX)/bin
cp apex-twin $(DESTDIR)$(PREFIX)/bin/
clean:
rm -f apex-twin $(OBJ)
.PHONY: all test install clean
+173
View File
@@ -0,0 +1,173 @@
# APEX TWIN
An offensive-security MCP server in C99 + POSIX. One static binary, libc only,
no Python in the serving path. It gives an agent real reconnaissance and real web
testing behind a scope gate that refuses everything until a rules-of-engagement
file says otherwise.
Derived from [ARTEX](https://github.com/Autumn-27/artex)'s ideas (scope gates,
findings with evidence, budgets) but written from nothing in C, with the fleet's
`libmcp` transport and the ESP32 Marauder serial CLI folded in.
**What it is not:** an exploit framework. There is no payload that reads a
database, no shell, no post-exploitation. Every tool either observes (scan, fetch,
capture) or proves (headers, certificate, reflected payload). Transmission is a
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 install # /usr/local/bin/apex-twin
```
Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
`-D_POSIX_C_SOURCE=200809L -D_DEFAULT_SOURCE`.
## The gate is the product
Every tool that can touch something calls `apex_scope_check()` before it opens a
socket or spawns a process, and appends the decision to `audit.log` before the
action. The rules, in the order they are applied:
| # | Rule | Result |
|---|---|---|
| 1 | no scope file | deny everything |
| 2 | scope expired | deny everything |
| 3 | target in `deny_ip` | deny (deny beats allow) |
| 4 | port not in `allow_port` | deny (empty list = all ports) |
| 5 | target in neither `allow_ip` nor `allow_domain` | deny |
| 6 | private/loopback/link-local and `allow_private` is false | deny |
| 7 | a name that resolves partly outside `allow_ip` | deny |
Rule 7 exists because of DNS rebinding: an allow-listed name that resolves to an
internal address would otherwise be a way in. Every address a name returns must
be inside the scope, and an unresolvable name is refused rather than waved through.
Radio transmission is gated a second time: `serial_tx` must be true *and* the
command must be on the allowlist. A receiver is a scanner; a transmitter is an
attack.
## Scope file
`$APEX_HOME/scope.json`, default `~/.local/state/apex-twin/scope.json`:
```json
{
"label": "acme-q1",
"expires": "2026-03-31T23:59:59Z",
"allow_private": false,
"serial_tx": false,
"allow_ip": ["203.0.113.0/24", "198.51.100.7"],
"deny_ip": ["203.0.113.66"],
"allow_domain": ["app.acme.example", "*.acme.example"],
"allow_port": ["80", "443", "8000-8100"]
}
```
`"*.acme.example"` matches subdomains only; `"acme.example"` matches the apex and
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)
**Scope and bookkeeping** — `scope_show`, `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),
`banner`, `http_head`
**Web** — `http_request` (any method, body, headers), `http_headers` (HSTS/CSP/
frame/nosniff/referrer/permissions audit), `http_paths` (built-in wordlist:
`.git`, `.env`, actuator, swagger, backups), `sqli_probe` (quote + boolean pair,
reports differing answers as a lead), `xss_probe` (marked payload, returns the
reflection context), `curl`
**Radio** — `marauder_info`, `marauder_commands`, `marauder_cmd`, `marauder_scan`
**Method** — `method_techniques`, `method_playbook`, `method_tool`
**Findings** — `finding_add`, `finding_list`, `finding_read`
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
an engagement — 12 techniques across recon, enum, web, creds, AD, wifi and report,
plus a note per tool on what people get wrong with it.
## Transport
```sh
apex-twin # MCP over stdin/stdout (one JSON-RPC line each way)
apex-twin --http 8797 # MCP over HTTP on 127.0.0.1:8797, POST /mcp
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.
## The radio
The Marauder bridge speaks the firmware CLI at 115200 baud, and it refuses to talk
to something that is not a radio. Before the first command it sends a bare CRLF:
a console answers that with its login prompt, a Marauder either stays quiet or
prints a prompt of its own. On this machine `/dev/ttyACM0` is an Espressif USB
JTAG unit running a Mikronix console, and typing `scanall` into it produced
`login: scanall: no such user` and then `3 incorrect attempts, giving up`. The
guard now refuses it by name instead.
Scans always end with `stopscan`, so the next command meets a clean device.
```sh
APEX_SERIAL=/dev/ttyACM0 APEX_BAUD=115200
```
## Environment
| Variable | Default | Meaning |
|---|---|---|
| `APEX_HOME` | `~/.local/state/apex-twin` | state dir (0700) |
| `APEX_SCOPE` | `$APEX_HOME/scope.json` | scope file |
| `APEX_SERIAL` | `/dev/ttyACM0` | Marauder tty |
| `APEX_BAUD` | `115200` | serial baud |
| `APEX_DRY_RUN` | unset | `1` prints commands, runs none |
| `APEX_DEFAULT_TIMEOUT_MS` | `60000` | per-tool default |
| `APEX_MAX_TIMEOUT_MS` | `900000` | hard cap |
## Files it writes
```
$APEX_HOME/
scope.json the rules of engagement
audit.log one JSON line per decision, append-only
findings/f0001.json one finding per file
evidence/<ts>-<label>.bin raw proof, 0600
```
The audit line is written *before* the action, so a process that dies mid-scan
still left its intent on disk.
## Tests
```sh
make test
```
56 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.
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
`{"serverInfo":{"name":"koder"}}` while the suite was green.
## Status
0.1.0. Built and run. Not yet wired into a systemd unit or a fleet router.
Licence: AGPL-3.0, same as ARTEX.
+10
View File
@@ -0,0 +1,10 @@
{
"label": "replace-with-your-engagement",
"expires": "2026-12-31T23:59:59Z",
"allow_private": false,
"serial_tx": false,
"allow_ip": ["203.0.113.0/24"],
"deny_ip": ["203.0.113.1", "203.0.113.254"],
"allow_domain": ["*.acme.example"],
"allow_port": ["80", "443", "8000-8100"]
}
+338
View File
@@ -0,0 +1,338 @@
/*
* apex-twin.c - MCP entry point.
*
* stdout is the transport, so nothing else may write to it. Every diagnostic
* goes to stderr, which is what a client sees in its log.
*
* apex-twin MCP over stdin/stdout, one JSON-RPC line each way
* apex-twin --http 8797 Streamable HTTP on 127.0.0.1:8797
* apex-twin --check print the scope, the tool count and the host, exit
* apex-twin --version print the version
*
* The scope is loaded at start and on every scope_reload call. A scope that
* cannot be read is not a warning: the gate refuses everything, which is the
* only safe default for a program whose tools can touch a network.
*/
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
#define MAX_BODY (8u << 20)
static mcp_server g_srv;
static mcp_tool g_tools[64];
static void build_tools(void)
{
size_t n = 0;
size_t i;
for (i = 0; i < TOOLS_RECON_N && n < 64; i++)
g_tools[n++] = TOOLS_RECON[i];
for (i = 0; i < TOOLS_WEB_N && n < 64; i++)
g_tools[n++] = TOOLS_WEB[i];
for (i = 0; i < TOOLS_RADIO_N && n < 64; i++)
g_tools[n++] = TOOLS_RADIO[i];
for (i = 0; i < TOOLS_KB_N && n < 64; i++)
g_tools[n++] = TOOLS_KB[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
g_srv.tools = g_tools;
g_srv.ntools = n;
g_srv.user = NULL;
}
/* ------------------------------------------------------------ http face */
static char *ci_strstr(const char *hay, const char *needle)
{
size_t nl = strlen(needle);
const char *p;
if (nl == 0)
return (char *)hay;
for (p = hay; *p != '\0'; p++) {
size_t i;
for (i = 0; i < nl; i++) {
if (p[i] == '\0')
return NULL;
if (p[i] >= 'A' && p[i] <= 'Z')
if (p[i] - 'A' + 'a' != needle[i])
break;
if (p[i] != needle[i] && !(p[i] >= 'A' && p[i] <= 'Z'))
break;
}
if (i == nl)
return (char *)p;
}
return NULL;
}
static void http_send(int fd, int code, const char *ctype, const char *body,
size_t len, const char *session)
{
mcp_buf out;
size_t sent = 0;
const char *reason = "OK";
if (code == 202)
reason = "Accepted";
else if (code == 400)
reason = "Bad Request";
else if (code == 404)
reason = "Not Found";
else if (code == 405)
reason = "Method Not Allowed";
else if (code == 413)
reason = "Payload Too Large";
mcp_buf_init(&out);
mcp_buf_printf(&out, "HTTP/1.1 %d %s\r\n", code, reason);
if (ctype != NULL)
mcp_buf_printf(&out, "Content-Type: %s\r\n", ctype);
if (session != NULL)
mcp_buf_printf(&out, "Mcp-Session-Id: %s\r\n", session);
mcp_buf_printf(&out, "Content-Length: %lu\r\n", (unsigned long)len);
mcp_buf_puts(&out, "Connection: close\r\n\r\n");
if (len > 0)
mcp_buf_add(&out, body, len);
while (sent < out.len) {
ssize_t w = write(fd, out.p + sent, out.len - sent);
if (w <= 0)
break;
sent += (size_t)w;
}
mcp_buf_free(&out);
}
static void serve_one(int fd, const char *session)
{
char buf[8192];
mcp_buf head;
int done = 0;
long clen = 0;
char *body = NULL;
char *reply;
mcp_buf_init(&head);
while (!done) {
ssize_t r = read(fd, buf, sizeof(buf));
char *sep;
if (r <= 0)
break;
mcp_buf_add(&head, buf, (size_t)r);
sep = strstr(head.p, "\r\n\r\n");
if (sep == NULL) {
if (head.len > MAX_BODY) {
http_send(fd, 413, "text/plain", "headers too large\n", 17, NULL);
mcp_buf_free(&head);
close(fd);
return;
}
continue;
}
{
char *cl = ci_strstr(head.p, "content-length:");
size_t hlen = (size_t)(sep + 4 - head.p);
size_t have = head.len > hlen ? head.len - hlen : 0;
if (cl != NULL)
clen = strtol(cl + 15, NULL, 10);
if (clen < 0 || clen > (long)MAX_BODY) {
http_send(fd, 413, "text/plain", "body too large\n", 15, NULL);
mcp_buf_free(&head);
close(fd);
return;
}
body = calloc((size_t)clen + 1, 1);
if (body == NULL) {
mcp_buf_free(&head);
close(fd);
return;
}
if (have > (size_t)clen)
have = (size_t)clen;
memcpy(body, head.p + hlen, have);
while (have < (size_t)clen) {
ssize_t r2 = read(fd, body + have, (size_t)clen - have);
if (r2 <= 0)
break;
have += (size_t)r2;
}
body[have] = '\0';
done = 1;
}
}
if (!done) {
http_send(fd, 400, "text/plain", "incomplete request\n", 20, NULL);
free(body);
mcp_buf_free(&head);
close(fd);
return;
}
if (strncmp(head.p, "GET ", 4) == 0 || strncmp(head.p, "DELETE ", 7) == 0) {
/* no SSE stream: this server answers per request */
http_send(fd, 202, NULL, "", 0, session);
free(body);
mcp_buf_free(&head);
close(fd);
return;
}
if (strncmp(head.p, "POST ", 5) != 0) {
http_send(fd, 405, "text/plain", "only POST /mcp\n", 15, NULL);
free(body);
mcp_buf_free(&head);
close(fd);
return;
}
if (strstr(head.p, "/mcp") == NULL) {
http_send(fd, 404, "text/plain", "want /mcp\n", 9, NULL);
free(body);
mcp_buf_free(&head);
close(fd);
return;
}
reply = mcp_handle(&g_srv, body != NULL ? body : "{}");
free(body);
if (reply == NULL)
http_send(fd, 202, NULL, "", 0, session);
else {
http_send(fd, 200, "application/json", reply, strlen(reply), session);
free(reply);
}
mcp_buf_free(&head);
close(fd);
}
static int serve_http(int port)
{
int ls;
struct sockaddr_in addr;
int one = 1;
char session[40];
snprintf(session, sizeof(session), "%08x-%08x", (unsigned)time(NULL),
(unsigned)getpid());
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls < 0) {
perror("socket");
return 1;
}
setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
/* loopback only: this service can scan and must not be on the LAN by
* accident. A tunnel is the way in, not a public bind. */
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons((unsigned short)port);
if (bind(ls, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
perror("bind");
close(ls);
return 1;
}
if (listen(ls, 32) != 0) {
perror("listen");
close(ls);
return 1;
}
signal(SIGCHLD, SIG_IGN);
fprintf(stderr, "apex-twin: http mcp on 127.0.0.1:%d (session %s)\n", port,
session);
for (;;) {
int fd = accept(ls, NULL, NULL);
pid_t pid;
if (fd < 0)
continue;
pid = fork();
if (pid == 0) {
close(ls);
serve_one(fd, session);
_exit(0);
}
if (pid > 0)
close(fd);
else
serve_one(fd, session);
}
}
int main(int argc, char **argv)
{
int i;
apex_config_init();
build_tools();
if (apex_scope_load() != 0)
fprintf(stderr, "apex-twin: no scope at %s - every target is refused "
"until one is written\n", g_cfg.scope_file);
else
fprintf(stderr, "apex-twin: scope '%s' loaded from %s (%d cidr, "
"%d domains, %d port ranges, serial_tx=%s)\n",
g_scope.label, g_scope.source, g_scope.n_allow_ip,
g_scope.n_allow_domain, g_scope.n_allow_port,
g_scope.serial_tx ? "on" : "off");
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "--version") == 0) {
printf("apex-twin %s\n", APEX_VERSION);
return 0;
}
if (strcmp(argv[i], "--check") == 0) {
mcp_buf b;
mcp_buf_init(&b);
apex_scope_json(&b);
printf("{\"version\":\"%s\",\"tools\":%lu,\"home\":\"%s\","
"\"scope\":%s}\n", APEX_VERSION,
(unsigned long)g_srv.ntools, g_cfg.home, b.p);
mcp_buf_free(&b);
return 0;
}
if (strcmp(argv[i], "--http") == 0) {
const char *port = (i + 1 < argc) ? argv[i + 1] : "8797";
const char *colon = strrchr(port, ':');
if (colon != NULL)
port = colon + 1;
return serve_http(atoi(port));
}
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
printf("apex-twin %s - offensive-security MCP server (C99/POSIX)\n\n"
" apex-twin MCP over stdin/stdout\n"
" apex-twin --http PORT MCP over HTTP on 127.0.0.1\n"
" apex-twin --check print scope and tool count\n"
" apex-twin --version print the version\n\n"
"Environment:\n"
" APEX_HOME state dir (default "
"~/.local/state/apex-twin)\n"
" APEX_SCOPE scope file (default $APEX_HOME/scope.json)\n"
" APEX_SERIAL Marauder tty (default /dev/ttyACM0)\n"
" APEX_BAUD serial baud (default 115200)\n"
" APEX_DRY_RUN=1 show commands, run none\n",
APEX_VERSION);
return 0;
}
}
fprintf(stderr, "apex-twin: %lu tools on stdio\n",
(unsigned long)g_srv.ntools);
return mcp_serve_stdio(&g_srv);
}
+127
View File
@@ -0,0 +1,127 @@
/*
* APEX TWIN - C99/POSIX offensive-security MCP server.
*
* One process, one dispatch table, one scope gate in front of every action.
* The gate is the product: a tool that cannot name a target inside the loaded
* scope does not run, and every decision is appended to the audit log before
* the command is spawned.
*/
#ifndef APEX_H
#define APEX_H
#include <stddef.h>
#include <sys/types.h>
#include <time.h>
#include "mcp.h"
#define APEX_VERSION "0.1.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
#define APEX_MAX_CIDR 64
#define APEX_MAX_DOMAIN 64
#define APEX_MAX_PORTS 32
/* ------------------------------------------------------------------ scope */
typedef struct {
int family; /* AF_INET or AF_INET6 */
unsigned char addr[16];
int bits;
} apex_cidr;
typedef struct {
char suffix[256]; /* "example.com", stored lower case, no dot prefix */
int sub_only; /* "*.example.com": the apex itself is not matched */
} apex_domain;
typedef struct {
int lo;
int hi;
} apex_portrange;
typedef struct {
int loaded;
int allow_private; /* RFC1918 / loopback / link-local permitted */
int serial_tx; /* transmitting radio commands armed */
time_t expires; /* 0 = no expiry */
char source[APEX_PATH_MAX];
char label[128];
apex_cidr allow_ip[APEX_MAX_CIDR];
int n_allow_ip;
apex_cidr deny_ip[APEX_MAX_CIDR];
int n_deny_ip;
apex_domain allow_domain[APEX_MAX_DOMAIN];
int n_allow_domain;
apex_portrange allow_port[APEX_MAX_PORTS];
int n_allow_port;
} apex_scope;
typedef struct {
char home[APEX_PATH_MAX];
char scope_file[APEX_PATH_MAX];
char audit_file[APEX_PATH_MAX];
char finding_dir[APEX_PATH_MAX];
char evidence_dir[APEX_PATH_MAX];
char serial[128];
int baud;
int default_timeout_ms;
int max_timeout_ms;
size_t max_output;
int dry_run;
} apex_cfg;
extern apex_cfg g_cfg;
extern apex_scope g_scope;
int apex_mkdir_p(const char *path, mode_t mode);
/* dir + "/" + name into dst. -1 when it does not fit, never truncated. */
int apex_path_join(char *dst, size_t n, const char *dir, const char *name);
int apex_write_file(const char *path, const char *data, size_t len, mode_t mode);
void apex_config_init(void);
int apex_scope_load(void);
/* 1 = allowed, 0 = denied. reason is always filled. */
int apex_scope_check(const char *target, int port, char *reason, size_t n);
void apex_scope_json(mcp_buf *b);
/* --------------------------------------------------------------- process */
typedef struct {
int exit_code; /* -1 spawn failed, -2 killed by signal */
int signal_num;
int timed_out;
int truncated;
long elapsed_ms;
char *out;
size_t out_len;
} apex_proc;
int apex_run(char *const argv[], int timeout_ms, size_t max_out, apex_proc *p);
void apex_proc_free(apex_proc *p);
int apex_have(const char *prog);
char *apex_join_argv(char *const argv[]);
char *apex_strdup(const char *s);
/* ----------------------------------------------------------------- store */
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_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);
int apex_audit_tail(mcp_buf *b, int limit);
/* ------------------------------------------------------------------ util */
char *apex_now_iso(void);
void apex_json_str(mcp_buf *b, const char *s);
int apex_port_in_scope(int port);
int apex_scope_expired(void);
const char *apex_home(void);
#endif /* APEX_H */
+176
View File
@@ -0,0 +1,176 @@
/*
* config.c - state directory, defaults, small file helpers.
*
* Everything APEX TWIN writes lives under $APEX_HOME (default
* ~/.local/state/apex-twin). Nothing else on the machine is touched.
*/
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include "apex.h"
apex_cfg g_cfg;
apex_scope g_scope;
static void copy_str(char *dst, size_t n, const char *src)
{
if (n == 0)
return;
if (src == NULL) {
dst[0] = '\0';
return;
}
snprintf(dst, n, "%s", src);
}
int apex_mkdir_p(const char *path, mode_t mode)
{
char tmp[APEX_PATH_MAX];
size_t len;
size_t i;
if (path == NULL)
return -1;
len = strlen(path);
if (len == 0 || len >= sizeof(tmp))
return -1;
memcpy(tmp, path, len + 1);
for (i = 1; i < len; i++) {
if (tmp[i] != '/')
continue;
tmp[i] = '\0';
if (mkdir(tmp, mode) != 0 && errno != EEXIST)
return -1;
tmp[i] = '/';
}
if (mkdir(tmp, mode) != 0 && errno != EEXIST)
return -1;
return 0;
}
int apex_path_join(char *dst, size_t n, const char *dir, const char *name)
{
size_t dl;
size_t nl;
size_t sep;
if (dst == NULL || dir == NULL || name == NULL || n == 0)
return -1;
dl = strlen(dir);
nl = strlen(name);
sep = (dl > 0 && dir[dl - 1] != '/') ? 1u : 0u;
if (dl + sep + nl + 1 > n)
return -1;
memcpy(dst, dir, dl);
if (sep == 1)
dst[dl] = '/';
memcpy(dst + dl + sep, name, nl + 1);
return 0;
}
int apex_write_file(const char *path, const char *data, size_t len, mode_t mode)
{
int fd;
size_t off = 0;
fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, mode);
if (fd < 0)
return -1;
while (off < len) {
ssize_t w = write(fd, data + off, len - off);
if (w <= 0) {
close(fd);
return -1;
}
off += (size_t)w;
}
close(fd);
return 0;
}
const char *apex_home(void)
{
return g_cfg.home;
}
static void path_join(char *dst, size_t n, const char *a, const char *b)
{
size_t al = strlen(a);
if (al > 0 && a[al - 1] == '/')
snprintf(dst, n, "%s%s", a, b);
else
snprintf(dst, n, "%s/%s", a, b);
}
static void env_int(const char *name, int *dst)
{
const char *v = getenv(name);
if (v != NULL && *v != '\0')
*dst = atoi(v);
}
void apex_config_init(void)
{
const char *home = getenv("APEX_HOME");
const char *scope = getenv("APEX_SCOPE");
const char *serial = getenv("APEX_SERIAL");
const char *dry = getenv("APEX_DRY_RUN");
memset(&g_cfg, 0, sizeof(g_cfg));
if (home != NULL && *home != '\0') {
copy_str(g_cfg.home, sizeof(g_cfg.home), home);
} else {
const char *xdg = getenv("XDG_STATE_HOME");
const char *uhome = getenv("HOME");
if (xdg != NULL && *xdg != '\0') {
path_join(g_cfg.home, sizeof(g_cfg.home), xdg, "apex-twin");
} else if (uhome != NULL && *uhome != '\0') {
char tmp[APEX_PATH_MAX];
path_join(tmp, sizeof(tmp), uhome, ".local/state");
path_join(g_cfg.home, sizeof(g_cfg.home), tmp, "apex-twin");
} else {
copy_str(g_cfg.home, sizeof(g_cfg.home), "/tmp/apex-twin");
}
}
path_join(g_cfg.scope_file, sizeof(g_cfg.scope_file), g_cfg.home, "scope.json");
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");
if (scope != NULL && *scope != '\0')
copy_str(g_cfg.scope_file, sizeof(g_cfg.scope_file), scope);
/* An ESP32 on this host shows up as an Espressif USB JTAG unit. */
if (serial != NULL && *serial != '\0')
copy_str(g_cfg.serial, sizeof(g_cfg.serial), serial);
else
copy_str(g_cfg.serial, sizeof(g_cfg.serial), "/dev/ttyACM0");
g_cfg.baud = 115200;
g_cfg.default_timeout_ms = 60000;
g_cfg.max_timeout_ms = 900000;
g_cfg.max_output = APEX_MAX_OUT;
g_cfg.dry_run = 0;
env_int("APEX_DEFAULT_TIMEOUT_MS", &g_cfg.default_timeout_ms);
env_int("APEX_MAX_TIMEOUT_MS", &g_cfg.max_timeout_ms);
env_int("APEX_BAUD", &g_cfg.baud);
if (dry != NULL && (*dry == '1' || *dry == 'y' || *dry == 't'))
g_cfg.dry_run = 1;
apex_mkdir_p(g_cfg.home, 0700);
apex_mkdir_p(g_cfg.finding_dir, 0700);
apex_mkdir_p(g_cfg.evidence_dir, 0700);
}
+9
View File
@@ -0,0 +1,9 @@
/*
* mcp_impl.c - the one translation unit that compiles libmcp.
*
* mcp.h is header-only: the implementation lives behind MCP_IMPLEMENTATION and
* must be instantiated exactly once, or every other object file gets its own
* copy of the parser and the linker complains about duplicates.
*/
#define MCP_IMPLEMENTATION
#include "mcp.h"
+242
View File
@@ -0,0 +1,242 @@
/*
* proc.c - run one program, capture its output, honour a timeout.
*
* fork + exec + pipe, no shell: the argv array is built by the caller from
* arguments that already passed the scope gate, so no string from a model ever
* reaches /bin/sh. stdin is /dev/null, stdout and stderr share one pipe, and a
* timer kills the child group when the deadline passes.
*/
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include "apex.h"
static long now_ms(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (long)tv.tv_sec * 1000L + (long)tv.tv_usec / 1000L;
}
char *apex_strdup(const char *s)
{
size_t n;
char *p;
if (s == NULL)
return NULL;
n = strlen(s) + 1;
p = malloc(n);
if (p != NULL)
memcpy(p, s, n);
return p;
}
char *apex_join_argv(char *const argv[])
{
mcp_buf b;
int i;
mcp_buf_init(&b);
for (i = 0; argv[i] != NULL; i++) {
int quote = 0;
const char *p;
if (i > 0)
mcp_buf_puts(&b, " ");
for (p = argv[i]; *p; p++)
if (*p == ' ' || *p == '\t' || *p == '"' || *p == '\'' ||
*p == '$' || *p == '`')
quote = 1;
if (!quote) {
mcp_buf_puts(&b, argv[i]);
continue;
}
mcp_buf_puts(&b, "'");
for (p = argv[i]; *p; p++) {
if (*p == '\'')
mcp_buf_puts(&b, "'\\''");
else
mcp_buf_add(&b, p, 1);
}
mcp_buf_puts(&b, "'");
}
if (b.p == NULL)
mcp_buf_puts(&b, "");
return b.p;
}
/* Walk PATH once. No shelling out to `command -v`: that needs a shell. */
int apex_have(const char *prog)
{
const char *path;
char buf[APEX_PATH_MAX];
if (prog == NULL || *prog == '\0')
return 0;
if (strchr(prog, '/') != NULL)
return access(prog, X_OK) == 0;
path = getenv("PATH");
if (path == NULL || *path == '\0')
path = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
while (*path) {
const char *end = strchr(path, ':');
size_t len = end != NULL ? (size_t)(end - path) : strlen(path);
if (len > 0 && len + 1 + strlen(prog) + 1 <= sizeof(buf)) {
size_t n = strlen(prog);
memcpy(buf, path, len);
buf[len] = '/';
memcpy(buf + len + 1, prog, n + 1);
if (access(buf, X_OK) == 0)
return 1;
}
if (end == NULL)
break;
path = end + 1;
}
return 0;
}
void apex_proc_free(apex_proc *p)
{
if (p == NULL)
return;
free(p->out);
p->out = NULL;
p->out_len = 0;
}
int apex_run(char *const argv[], int timeout_ms, size_t max_out, apex_proc *p)
{
int fds[2];
pid_t pid;
long start;
time_t deadline;
if (p == NULL || argv == NULL || argv[0] == NULL)
return -1;
memset(p, 0, sizeof(*p));
if (max_out == 0 || max_out > g_cfg.max_output)
max_out = g_cfg.max_output;
if (timeout_ms <= 0)
timeout_ms = g_cfg.default_timeout_ms;
if (timeout_ms > g_cfg.max_timeout_ms)
timeout_ms = g_cfg.max_timeout_ms;
if (pipe(fds) != 0) {
p->exit_code = -1;
return -1;
}
start = now_ms();
deadline = time(NULL) + timeout_ms / 1000 + 1;
pid = fork();
if (pid < 0) {
close(fds[0]);
close(fds[1]);
p->exit_code = -1;
return -1;
}
if (pid == 0) {
int devnull;
/* own process group: the timeout kills grandchildren too */
setpgid(0, 0);
devnull = open("/dev/null", O_RDONLY);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
close(devnull);
}
dup2(fds[1], STDOUT_FILENO);
dup2(fds[1], STDERR_FILENO);
close(fds[0]);
close(fds[1]);
/* never let a child inherit the MCP transport */
execvp(argv[0], argv);
fprintf(stderr, "apex-twin: cannot exec %s: %s\n", argv[0],
strerror(errno));
_exit(127);
}
setpgid(pid, pid);
close(fds[1]);
p->out = malloc(max_out + 1);
if (p->out == NULL) {
kill(-pid, SIGKILL);
close(fds[0]);
waitpid(pid, NULL, 0);
p->exit_code = -1;
return -1;
}
{
int flags = fcntl(fds[0], F_GETFL, 0);
if (flags >= 0)
fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);
}
for (;;) {
char buf[8192];
ssize_t r = read(fds[0], buf, sizeof(buf));
if (r > 0) {
size_t room = max_out - p->out_len;
if ((size_t)r > room) {
memcpy(p->out + p->out_len, buf, room);
p->out_len += room;
p->truncated = 1;
} else {
memcpy(p->out + p->out_len, buf, (size_t)r);
p->out_len += (size_t)r;
}
continue;
}
if (r == 0)
break;
if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)
break;
if (time(NULL) > deadline) {
p->timed_out = 1;
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
break;
}
{
struct timespec ts = { 0, 20 * 1000 * 1000 };
nanosleep(&ts, NULL);
}
}
close(fds[0]);
p->out[p->out_len] = '\0';
{
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
;
if (WIFEXITED(status))
p->exit_code = WEXITSTATUS(status);
else if (WIFSIGNALED(status)) {
p->exit_code = -2;
p->signal_num = WTERMSIG(status);
} else {
p->exit_code = -1;
}
}
p->elapsed_ms = now_ms() - start;
return 0;
}
+723
View File
@@ -0,0 +1,723 @@
/*
* scope.c - the gate in front of every offensive action.
*
* A tool never decides for itself whether a target is fair game. It hands the
* target to apex_scope_check(), gets 1 or 0 plus a reason, and writes both into
* the audit log before it spawns anything. That is the whole design: one
* function, one answer, one log line.
*
* Rules, in the order they are applied:
*
* 1. no scope file loaded -> deny everything
* 2. scope expired -> deny everything
* 3. target inside deny_ip -> deny (deny always beats allow)
* 4. port not in allow_port -> deny (an empty list means all ports)
* 5. target not in allow_ip and not in allow_domain -> deny
* 6. private/loopback/link-local address without allow_private -> deny
*
* Deny-before-allow is deliberate: a mistake in the allow list must not
* outvote an explicit exclusion.
*/
#include <arpa/inet.h>
#include <ctype.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "apex.h"
/* day number from a civil date, no timegm: that one is GNU, not POSIX. */
static long days_from_civil(long y, unsigned m, unsigned d)
{
long era;
unsigned yoe;
unsigned doy;
unsigned doe;
y -= m <= 2;
era = (y >= 0 ? y : y - 399) / 400;
yoe = (unsigned)(y - era * 400);
doy = (153u * (m + (m > 2 ? -3 : 9)) + 2u) / 5u + d - 1u;
doe = yoe * 365u + yoe / 4u - yoe / 100u + doy;
return era * 146097L + (long)doe - 719468L;
}
/* Accepts "2026-12-31", "2026-12-31T23:59:59Z", "2026-12-31 23:59". */
static time_t parse_iso(const char *s)
{
int y = 0;
int mo = 0;
int d = 0;
int h = 0;
int mi = 0;
int se = 0;
int n;
if (s == NULL)
return 0;
n = sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2d", &y, &mo, &d, &h, &mi, &se);
if (n < 3)
n = sscanf(s, "%4d-%2d-%2d %2d:%2d:%2d", &y, &mo, &d, &h, &mi, &se);
if (n < 3)
return 0;
if (mo < 1 || mo > 12 || d < 1 || d > 31)
return 0;
return days_from_civil(y, (unsigned)mo, (unsigned)d) * 86400L +
h * 3600L + mi * 60L + se;
}
/* --------------------------------------------------------------- parsing */
static int parse_cidr(const char *text, apex_cidr *out)
{
char buf[128];
char *slash;
int bits = -1;
int fam;
unsigned char raw[16];
size_t len;
if (text == NULL)
return -1;
len = strlen(text);
if (len == 0 || len >= sizeof(buf))
return -1;
memcpy(buf, text, len + 1);
slash = strchr(buf, '/');
if (slash != NULL) {
*slash = '\0';
bits = atoi(slash + 1);
}
if (inet_pton(AF_INET, buf, raw) == 1) {
fam = AF_INET;
if (bits < 0)
bits = 32;
if (bits > 32)
return -1;
memset(out->addr, 0, sizeof(out->addr));
memcpy(out->addr, raw, 4);
} else if (inet_pton(AF_INET6, buf, raw) == 1) {
fam = AF_INET6;
if (bits < 0)
bits = 128;
if (bits > 128)
return -1;
memcpy(out->addr, raw, 16);
} else {
return -1;
}
out->family = fam;
out->bits = bits;
return 0;
}
static int cidr_match(const apex_cidr *c, const unsigned char *addr, int fam)
{
const unsigned char *a = c->addr;
int whole;
int rest;
if (c->family != fam)
return 0;
whole = c->bits / 8;
rest = c->bits % 8;
if (whole > 0 && memcmp(a, addr, (size_t)whole) != 0)
return 0;
if (rest != 0) {
unsigned char mask = (unsigned char)(0xff << (8 - rest));
if ((a[whole] & mask) != (addr[whole] & mask))
return 0;
}
return 1;
}
static void lower(char *s)
{
for (; *s; s++)
*s = (char)tolower((unsigned char)*s);
}
static void add_domain(apex_scope *sc, const char *text)
{
char buf[256];
int sub = 0;
size_t len;
if (sc->n_allow_domain >= APEX_MAX_DOMAIN)
return;
if (text == NULL)
return;
len = strlen(text);
if (len == 0 || len >= sizeof(buf))
return;
memcpy(buf, text, len + 1);
if (buf[0] == '*') {
sub = 1;
if (buf[1] == '.')
memmove(buf, buf + 2, strlen(buf + 2) + 1);
else
memmove(buf, buf + 1, strlen(buf + 1) + 1);
}
/* tolerate a leading dot: ".example.com" means the same suffix */
if (buf[0] == '.')
memmove(buf, buf + 1, strlen(buf + 1) + 1);
if (buf[0] == '\0')
return;
lower(buf);
snprintf(sc->allow_domain[sc->n_allow_domain].suffix,
sizeof(sc->allow_domain[0].suffix), "%s", buf);
sc->allow_domain[sc->n_allow_domain].sub_only = sub;
sc->n_allow_domain++;
}
static void add_portrange(apex_scope *sc, const char *text)
{
int lo = 0;
int hi = 0;
if (sc->n_allow_port >= APEX_MAX_PORTS || text == NULL)
return;
if (strchr(text, '-') != NULL) {
if (sscanf(text, "%d-%d", &lo, &hi) != 2)
return;
} else {
lo = hi = atoi(text);
}
if (lo < 1 || hi > 65535 || lo > hi)
return;
sc->allow_port[sc->n_allow_port].lo = lo;
sc->allow_port[sc->n_allow_port].hi = hi;
sc->n_allow_port++;
}
static void add_ip_list(apex_cidr *arr, int *count, int max, const char *text)
{
if (*count >= max)
return;
if (parse_cidr(text, &arr[*count]) == 0)
(*count)++;
}
/* --------------------------------------------------------------- loading */
static void scope_read_strings(const mcp_json *root, const char *key,
void (*apply)(apex_scope *, const char *))
{
const mcp_json *arr = mcp_arg(root, key);
size_t i;
for (i = 0; i < mcp_array_len(arr); i++) {
const char *s = mcp_json_string(mcp_array_at(arr, i));
if (s != NULL)
apply(&g_scope, s);
}
}
static void apply_ip(const mcp_json *root, const char *key, apex_cidr *arr,
int *count, int max)
{
const mcp_json *list = mcp_arg(root, key);
size_t i;
for (i = 0; i < mcp_array_len(list); i++) {
const char *s = mcp_json_string(mcp_array_at(list, i));
if (s != NULL)
add_ip_list(arr, count, max, s);
}
}
int apex_scope_load(void)
{
char *text;
long size;
FILE *f;
mcp_json *root;
const char *label;
const char *expires;
memset(&g_scope, 0, sizeof(g_scope));
snprintf(g_scope.source, sizeof(g_scope.source), "%s", g_cfg.scope_file);
f = fopen(g_cfg.scope_file, "rb");
if (f == NULL) {
g_scope.loaded = 0;
return -1;
}
if (fseek(f, 0, SEEK_END) != 0) {
fclose(f);
g_scope.loaded = 0;
return -1;
}
size = ftell(f);
if (size <= 0 || size > (1L << 20)) {
fclose(f);
g_scope.loaded = 0;
return -1;
}
rewind(f);
text = malloc((size_t)size + 1);
if (text == NULL) {
fclose(f);
g_scope.loaded = 0;
return -1;
}
if (fread(text, 1, (size_t)size, f) != (size_t)size) {
free(text);
fclose(f);
g_scope.loaded = 0;
return -1;
}
text[size] = '\0';
fclose(f);
root = mcp_parse(text);
free(text);
if (root == NULL) {
g_scope.loaded = 0;
return -1;
}
label = mcp_arg_string(root, "label");
if (label != NULL)
snprintf(g_scope.label, sizeof(g_scope.label), "%s", label);
expires = mcp_arg_string(root, "expires");
if (expires != NULL)
g_scope.expires = parse_iso(expires);
g_scope.allow_private = mcp_arg_bool(root, "allow_private", 0);
g_scope.serial_tx = mcp_arg_bool(root, "serial_tx", 0);
apply_ip(root, "allow_ip", g_scope.allow_ip, &g_scope.n_allow_ip, APEX_MAX_CIDR);
apply_ip(root, "deny_ip", g_scope.deny_ip, &g_scope.n_deny_ip, APEX_MAX_CIDR);
scope_read_strings(root, "allow_domain", add_domain);
scope_read_strings(root, "allow_port", add_portrange);
mcp_json_free(root);
g_scope.loaded = 1;
return 0;
}
int apex_scope_expired(void)
{
time_t now;
if (g_scope.expires == 0)
return 0;
now = time(NULL);
return now > g_scope.expires;
}
/* --------------------------------------------------------------- matching */
static int is_private(const unsigned char *a, int fam)
{
if (fam == AF_INET) {
if (a[0] == 10)
return 1;
if (a[0] == 172 && a[1] >= 16 && a[1] <= 31)
return 1;
if (a[0] == 192 && a[1] == 168)
return 1;
if (a[0] == 127)
return 1;
if (a[0] == 169 && a[1] == 254)
return 1;
if (a[0] == 0)
return 1;
return 0;
}
if (fam == AF_INET6) {
static const unsigned char loop[16] = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1 };
if (memcmp(a, loop, 16) == 0)
return 1;
if ((a[0] & 0xfe) == 0xfc) /* fc00::/7 unique local */
return 1;
if (a[0] == 0xfe && (a[1] & 0xc0) == 0x80) /* fe80::/10 */
return 1;
return 0;
}
return 1;
}
static int domain_matches(const apex_domain *d, const char *host)
{
size_t hl = strlen(host);
size_t sl = strlen(d->suffix);
if (sl == 0)
return 0;
if (hl == sl)
return !d->sub_only && strcmp(host, d->suffix) == 0;
if (hl < sl + 2)
return 0;
if (strcmp(host + hl - sl, d->suffix) != 0)
return 0;
return host[hl - sl - 1] == '.';
}
static int looks_like_ip(const char *t)
{
unsigned char raw[16];
if (inet_pton(AF_INET, t, raw) == 1)
return AF_INET;
if (inet_pton(AF_INET6, t, raw) == 1)
return AF_INET6;
return 0;
}
static int any_ip_denied(const char *target)
{
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p;
int hit = 0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(target, NULL, &hints, &res) != 0)
return 0;
for (p = res; p != NULL; p = p->ai_next) {
int fam = p->ai_family;
const unsigned char *raw;
int i;
if (fam == AF_INET)
raw = (const unsigned char *)&((struct sockaddr_in *)p->ai_addr)->sin_addr;
else if (fam == AF_INET6)
raw = (const unsigned char *)&((struct sockaddr_in6 *)p->ai_addr)->sin6_addr;
else
continue;
for (i = 0; i < g_scope.n_deny_ip; i++) {
if (cidr_match(&g_scope.deny_ip[i], raw, fam)) {
hit = 1;
break;
}
}
if (hit)
break;
}
freeaddrinfo(res);
return hit;
}
/* Every address the name resolves to must be inside allow_ip; one that is not
* is a redirect to somewhere else, and the gate says no. An unresolvable name
* cannot be checked, so it is refused rather than waved through. */
static int all_addrs_allowed(const char *target, char *reason, size_t n)
{
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p;
int seen = 0;
int ok = 1;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(target, NULL, &hints, &res) != 0) {
snprintf(reason, n, "%s does not resolve, cannot verify address", target);
return 0;
}
for (p = res; p != NULL; p = p->ai_addr ? p->ai_next : p->ai_next) {
int fam = p->ai_family;
const unsigned char *raw;
int i;
int hit = 0;
if (fam != AF_INET && fam != AF_INET6)
continue;
if (fam == AF_INET)
raw = (const unsigned char *)&((struct sockaddr_in *)p->ai_addr)->sin_addr;
else
raw = (const unsigned char *)&((struct sockaddr_in6 *)p->ai_addr)->sin6_addr;
seen++;
for (i = 0; i < g_scope.n_allow_ip; i++) {
if (cidr_match(&g_scope.allow_ip[i], raw, fam)) {
hit = 1;
break;
}
}
if (!hit) {
char text[64];
if (fam == AF_INET)
inet_ntop(AF_INET, raw, text, sizeof(text));
else
inet_ntop(AF_INET6, raw, text, sizeof(text));
snprintf(reason, n, "%s resolves to %s which is outside allow_ip",
target, text);
ok = 0;
break;
}
if (!g_scope.allow_private && is_private(raw, fam)) {
snprintf(reason, n, "%s is a private/loopback address and "
"allow_private is false", target);
ok = 0;
break;
}
}
freeaddrinfo(res);
if (ok && seen == 0) {
snprintf(reason, n, "%s has no usable address", target);
return 0;
}
return ok;
}
int apex_scope_check(const char *target, int port, char *reason, size_t n)
{
char host[256];
int fam;
int i;
size_t len;
int domain_ok = 0;
if (reason != NULL && n > 0)
reason[0] = '\0';
if (!g_scope.loaded) {
snprintf(reason, n, "no scope loaded from %s - every target is refused",
g_cfg.scope_file);
return 0;
}
if (apex_scope_expired()) {
snprintf(reason, n, "scope '%s' expired", g_scope.label);
return 0;
}
if (target == NULL || *target == '\0') {
snprintf(reason, n, "empty target");
return 0;
}
len = strlen(target);
if (len >= sizeof(host)) {
snprintf(reason, n, "target too long");
return 0;
}
memcpy(host, target, len + 1);
lower(host);
/* strip a scheme and a path so "https://host/x" is still checkable */
{
char *sep = strstr(host, "://");
if (sep != NULL)
memmove(host, sep + 3, strlen(sep + 3) + 1);
}
{
char *slash = strchr(host, '/');
if (slash != NULL)
*slash = '\0';
}
{
char *at = strrchr(host, '@');
if (at != NULL)
memmove(host, at + 1, strlen(at + 1) + 1);
}
if (host[0] == '[') { /* [::1]:8080 */
char *close = strchr(host, ']');
if (close != NULL) {
*close = '\0';
memmove(host, host + 1, strlen(host + 1) + 1);
}
} else {
char *colon = strchr(host, ':');
/* one colon and nothing but digits after it: it is a port, not IPv6 */
if (colon != NULL && strchr(colon + 1, ':') == NULL) {
int all_digit = 1;
char *q;
for (q = colon + 1; *q; q++)
if (!isdigit((unsigned char)*q))
all_digit = 0;
if (all_digit) {
if (port <= 0)
port = atoi(colon + 1);
*colon = '\0';
}
}
}
/* trailing dot of an FQDN: same name */
if (len > 0 && host[strlen(host) - 1] == '.')
host[strlen(host) - 1] = '\0';
if (host[0] == '\0') {
snprintf(reason, n, "empty host after normalising the target");
return 0;
}
/* 3. explicit denial wins */
if (any_ip_denied(host)) {
snprintf(reason, n, "%s is inside deny_ip", host);
return 0;
}
/* 4. port must be allowed when a list exists. port <= 0 means the caller
* enumerates ports itself and filters each one with apex_port_in_scope();
* it is not a wildcard for a single-port action. */
if (port > 0 && g_scope.n_allow_port > 0) {
int ok = 0;
for (i = 0; i < g_scope.n_allow_port; i++) {
if (port >= g_scope.allow_port[i].lo && port <= g_scope.allow_port[i].hi) {
ok = 1;
break;
}
}
if (!ok) {
snprintf(reason, n, "port %d is not in allow_port", port);
return 0;
}
}
/* 5. either the name is listed, or every address it has is listed */
for (i = 0; i < g_scope.n_allow_domain; i++) {
if (domain_matches(&g_scope.allow_domain[i], host)) {
domain_ok = 1;
break;
}
}
if (!domain_ok)
return all_addrs_allowed(host, reason, n);
/* a listed domain still must not resolve into a private net when that is
* switched off - otherwise the allow list is a DNS-rebinding gift */
if (!g_scope.allow_private) {
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, NULL, &hints, &res) == 0) {
for (p = res; p != NULL; p = p->ai_next) {
int f = p->ai_family;
const unsigned char *raw;
if (f == AF_INET)
raw = (const unsigned char *)&((struct sockaddr_in *)p->ai_addr)->sin_addr;
else if (f == AF_INET6)
raw = (const unsigned char *)&((struct sockaddr_in6 *)p->ai_addr)->sin6_addr;
else
continue;
if (is_private(raw, f)) {
snprintf(reason, n, "%s resolves into a private net and "
"allow_private is false", host);
freeaddrinfo(res);
return 0;
}
}
freeaddrinfo(res);
}
}
fam = looks_like_ip(host);
if (port > 0)
snprintf(reason, n, "allowed: %s port %d", host, port);
else
snprintf(reason, n, "allowed: %s (port range checked per probe)", host);
(void)fam;
return 1;
}
int apex_port_in_scope(int port)
{
int i;
if (g_scope.n_allow_port == 0)
return 1;
for (i = 0; i < g_scope.n_allow_port; i++)
if (port >= g_scope.allow_port[i].lo && port <= g_scope.allow_port[i].hi)
return 1;
return 0;
}
void apex_scope_json(mcp_buf *b)
{
int i;
char ts[64];
struct tm tmv;
mcp_buf_puts(b, "{\"loaded\":");
mcp_buf_puts(b, g_scope.loaded ? "true" : "false");
mcp_buf_puts(b, ",\"label\":");
apex_json_str(b, g_scope.label);
mcp_buf_puts(b, ",\"source\":");
apex_json_str(b, g_scope.source);
mcp_buf_puts(b, ",\"expired\":");
mcp_buf_puts(b, apex_scope_expired() ? "true" : "false");
mcp_buf_puts(b, ",\"expires\":");
if (g_scope.expires == 0) {
mcp_buf_puts(b, "null");
} else {
tmv = *gmtime(&g_scope.expires);
strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%SZ", &tmv);
apex_json_str(b, ts);
}
mcp_buf_printf(b, ",\"allow_private\":%s,\"serial_tx\":%s",
g_scope.allow_private ? "true" : "false",
g_scope.serial_tx ? "true" : "false");
mcp_buf_puts(b, ",\"allow_ip\":[");
for (i = 0; i < g_scope.n_allow_ip; i++) {
char text[64];
if (i > 0)
mcp_buf_puts(b, ",");
if (g_scope.allow_ip[i].family == AF_INET)
inet_ntop(AF_INET, g_scope.allow_ip[i].addr, text, sizeof(text));
else
inet_ntop(AF_INET6, g_scope.allow_ip[i].addr, text, sizeof(text));
mcp_buf_printf(b, "\"%s/%d\"", text, g_scope.allow_ip[i].bits);
}
mcp_buf_puts(b, "],\"deny_ip\":[");
for (i = 0; i < g_scope.n_deny_ip; i++) {
char text[64];
if (i > 0)
mcp_buf_puts(b, ",");
if (g_scope.deny_ip[i].family == AF_INET)
inet_ntop(AF_INET, g_scope.deny_ip[i].addr, text, sizeof(text));
else
inet_ntop(AF_INET6, g_scope.deny_ip[i].addr, text, sizeof(text));
mcp_buf_printf(b, "\"%s/%d\"", text, g_scope.deny_ip[i].bits);
}
mcp_buf_puts(b, "],\"allow_domain\":[");
for (i = 0; i < g_scope.n_allow_domain; i++) {
if (i > 0)
mcp_buf_puts(b, ",");
if (g_scope.allow_domain[i].sub_only)
mcp_buf_puts(b, "\"*.");
else
mcp_buf_puts(b, "\"");
mcp_buf_puts(b, g_scope.allow_domain[i].suffix);
mcp_buf_puts(b, "\"");
}
mcp_buf_puts(b, "],\"allow_port\":[");
for (i = 0; i < g_scope.n_allow_port; i++) {
if (i > 0)
mcp_buf_puts(b, ",");
if (g_scope.allow_port[i].lo == g_scope.allow_port[i].hi)
mcp_buf_printf(b, "\"%d\"", g_scope.allow_port[i].lo);
else
mcp_buf_printf(b, "\"%d-%d\"", g_scope.allow_port[i].lo,
g_scope.allow_port[i].hi);
}
mcp_buf_puts(b, "]}");
}
+412
View File
@@ -0,0 +1,412 @@
/*
* store.c - audit log, findings, evidence.
*
* Three files, no database:
*
* $APEX_HOME/audit.log one JSON line per gate decision and per run
* $APEX_HOME/findings/fNNNN.json one finding per file, append-only by id
* $APEX_HOME/evidence/<name> raw bytes that prove a finding
*
* The audit log is append-only and written *before* a command is spawned: if
* the process dies mid-run, the intent is still on disk. A finding points at an
* evidence file, and every proof line carries where it came from, so a report
* is a directory listing, not a memory of what happened.
*/
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "apex.h"
char *apex_now_iso(void)
{
time_t now = time(NULL);
struct tm tmv;
char buf[64];
tmv = *gmtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tmv);
return apex_strdup(buf);
}
void apex_json_str(mcp_buf *b, const char *s)
{
mcp_buf_puts(b, "\"");
mcp_json_escape(b, s != NULL ? s : "");
mcp_buf_puts(b, "\"");
}
static void append_line(const char *path, const char *line, size_t len)
{
int fd;
fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0)
return;
(void)write(fd, line, len);
(void)write(fd, "\n", 1);
close(fd);
}
/*
* One line per decision. The format is fixed enough to grep and read with a
* shell, and JSON so a later reader does not need this program to parse it.
*/
void apex_audit(const char *tool, const char *target, int port, int allowed,
const char *reason, const char *cmd)
{
mcp_buf b;
char *ts;
if (tool == NULL)
tool = "?";
ts = apex_now_iso();
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"ts\":\"%s\",\"tool\":", ts != NULL ? ts : "?");
apex_json_str(&b, tool);
mcp_buf_puts(&b, ",\"target\":");
apex_json_str(&b, target != NULL ? target : "");
mcp_buf_printf(&b, ",\"port\":%d,\"decision\":\"%s\",\"reason\":",
port, allowed ? "allow" : "deny");
apex_json_str(&b, reason != NULL ? reason : "");
mcp_buf_puts(&b, ",\"cmd\":");
apex_json_str(&b, cmd != NULL ? cmd : "");
mcp_buf_puts(&b, "}");
append_line(g_cfg.audit_file, b.p, b.len);
mcp_buf_free(&b);
free(ts);
}
static int next_finding_id(void)
{
int i;
char path[APEX_PATH_FULL];
for (i = 1; i < 1000000; i++) {
char name[32];
snprintf(name, sizeof(name), "f%04d.json", i);
if (apex_path_join(path, sizeof(path), g_cfg.finding_dir, name) != 0)
return -1;
if (access(path, F_OK) != 0)
return i;
}
return -1;
}
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 id = next_finding_id();
char path[APEX_PATH_FULL];
char fid[16];
char *ts;
mcp_buf b;
if (id < 0)
return NULL;
snprintf(fid, sizeof(fid), "f%04d", id);
{
char fname[32];
snprintf(fname, sizeof(fname), "%s.json", fid);
if (apex_path_join(path, sizeof(path), g_cfg.finding_dir, fname) != 0)
return NULL;
}
ts = apex_now_iso();
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"id\":\"%s\",\"ts\":\"%s\",\"target\":", fid,
ts != NULL ? ts : "?");
apex_json_str(&b, target);
mcp_buf_puts(&b, ",\"title\":");
apex_json_str(&b, title);
mcp_buf_puts(&b, ",\"severity\":");
apex_json_str(&b, severity != NULL ? severity : "info");
mcp_buf_puts(&b, ",\"confidence\":");
apex_json_str(&b, confidence != NULL ? confidence : "firm");
mcp_buf_puts(&b, ",\"tool\":");
apex_json_str(&b, tool);
mcp_buf_puts(&b, ",\"cwe\":");
apex_json_str(&b, cwe);
mcp_buf_puts(&b, ",\"remediation\":");
apex_json_str(&b, remediation);
mcp_buf_puts(&b, ",\"tags\":");
apex_json_str(&b, tags);
mcp_buf_puts(&b, ",\"evidence\":");
apex_json_str(&b, evidence);
mcp_buf_puts(&b, "}\n");
if (apex_write_file(path, b.p, b.len, 0600) != 0) {
mcp_buf_free(&b);
free(ts);
return NULL;
}
mcp_buf_free(&b);
free(ts);
apex_audit("finding_add", target, 0, 1, fid, NULL);
return apex_strdup(fid);
}
char *apex_evidence_save(const char *label, const char *data, size_t len)
{
char path[APEX_PATH_FULL];
char name[256];
char stamp[32];
time_t now = time(NULL);
struct tm tmv;
size_t i;
int fd;
size_t off = 0;
tmv = *gmtime(&now);
strftime(stamp, sizeof(stamp), "%Y%m%dT%H%M%S", &tmv);
snprintf(name, sizeof(name), "%s", label != NULL && *label != '\0' ? label : "raw");
for (i = 0; name[i] != '\0'; i++) {
unsigned char c = (unsigned char)name[i];
if (c == '/' || c == '\\' || c == ' ' || c == ':' || c < 0x20)
name[i] = '_';
if (i > 120)
name[i] = '\0';
}
{
char fname[320];
snprintf(fname, sizeof(fname), "%s-%s.bin", stamp, name);
if (apex_path_join(path, sizeof(path), g_cfg.evidence_dir, fname) != 0)
return NULL;
}
fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0) {
/* same second, same label: fall back to a suffixed name */
char fname[340];
snprintf(fname, sizeof(fname), "%s-%s-%d.bin", stamp, name,
(int)getpid());
if (apex_path_join(path, sizeof(path), g_cfg.evidence_dir, fname) != 0)
return NULL;
fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0)
return NULL;
}
while (off < len) {
ssize_t w = write(fd, data + off, len - off);
if (w <= 0)
break;
off += (size_t)w;
}
close(fd);
return apex_strdup(path);
}
static char *simple_field(const char *json, const char *key, char *out, size_t n)
{
char pattern[64];
const char *p;
const char *start;
size_t i = 0;
snprintf(pattern, sizeof(pattern), "\"%s\":\"", key);
p = strstr(json, pattern);
if (p == NULL) {
out[0] = '\0';
return NULL;
}
start = p + strlen(pattern);
while (*start != '\0' && *start != '"' && i + 1 < n) {
if (*start == '\\' && start[1] != '\0') {
start++;
switch (*start) {
case 'n': out[i++] = '\n'; break;
case 't': out[i++] = '\t'; break;
case 'r': out[i++] = '\r'; break;
default: out[i++] = *start; break;
}
start++;
continue;
}
out[i++] = *start++;
}
out[i] = '\0';
return out;
}
int apex_finding_list(mcp_buf *b, const char *target_filter, int limit)
{
DIR *d;
struct dirent *ent;
int shown = 0;
int total = 0;
if (limit <= 0)
limit = 100;
mcp_buf_puts(b, "[");
d = opendir(g_cfg.finding_dir);
if (d != NULL) {
while ((ent = readdir(d)) != NULL) {
char path[APEX_PATH_FULL];
FILE *f;
char *text;
long size;
char target[256];
char id[32];
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);
simple_field(text, "target", target, sizeof(target));
if (target_filter != NULL && *target_filter != '\0' &&
strcmp(target_filter, target) != 0) {
free(text);
continue;
}
total++;
if (shown < limit) {
if (shown > 0)
mcp_buf_puts(b, ",");
mcp_buf_add(b, text, strlen(text) > 0 ? strlen(text) - 1 : 0);
(void)id;
shown++;
}
free(text);
}
closedir(d);
}
mcp_buf_puts(b, "]");
return total;
}
int apex_finding_read(const char *id, mcp_buf *b)
{
char path[APEX_PATH_FULL];
char *text;
long size;
FILE *f;
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;
{
char fname[64];
snprintf(fname, sizeof(fname), "%s.json", id);
if (apex_path_join(path, sizeof(path), g_cfg.finding_dir, fname) != 0)
return -1;
}
f = fopen(path, "rb");
if (f == NULL)
return -1;
if (fseek(f, 0, SEEK_END) != 0) {
fclose(f);
return -1;
}
size = ftell(f);
if (size <= 0 || size > 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);
mcp_buf_puts(b, text);
free(text);
return 0;
}
int apex_audit_tail(mcp_buf *b, int limit)
{
FILE *f;
char line[8192];
char **ring = NULL;
int count = 0;
int start;
int i;
if (limit <= 0)
limit = 50;
ring = calloc((size_t)limit, sizeof(*ring));
if (ring == NULL)
return -1;
f = fopen(g_cfg.audit_file, "rb");
if (f != NULL) {
while (fgets(line, sizeof(line), f) != NULL) {
size_t len = strlen(line);
while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
line[--len] = '\0';
if (len == 0)
continue;
free(ring[count % limit]);
ring[count % limit] = apex_strdup(line);
count++;
}
fclose(f);
}
start = count > limit ? count - limit : 0;
mcp_buf_puts(b, "[");
for (i = start; i < count; i++) {
const char *entry = ring[i % limit];
if (entry == NULL)
continue;
if (i > start)
mcp_buf_puts(b, ",");
mcp_buf_puts(b, entry);
}
mcp_buf_puts(b, "]");
for (i = 0; i < limit; i++)
free(ring[i]);
free(ring);
return count - start;
}
+28
View File
@@ -0,0 +1,28 @@
/*
* tools.h - shared between the tool modules.
*
* gated() and gated_cmd() are the only two ways a tool may reach the outside
* world. Both consult the scope gate and write the audit line; nothing else
* touches a socket or spawns a process.
*/
#ifndef APEX_TOOLS_H
#define APEX_TOOLS_H
#include "apex.h"
int gated(mcp_conn *c, const char *tool, const char *target, int port);
int gated_cmd(mcp_conn *c, const char *tool, const char *target, int port,
char *const argv[], int timeout_ms, int *exit_code);
int tcp_probe(const char *host, int port, int timeout_ms);
int tcp_connect_host(const char *host, int port, int timeout_ms);
extern const mcp_tool TOOLS_RECON[];
extern const size_t TOOLS_RECON_N;
extern const mcp_tool TOOLS_WEB[];
extern const size_t TOOLS_WEB_N;
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;
#endif /* APEX_TOOLS_H */
+443
View File
@@ -0,0 +1,443 @@
/*
* tools_kb.c - the part that makes an agent useful instead of loud.
*
* An LLM that has a port scanner and no method runs nmap, reads a wall of text
* and writes a report that says "open ports found". This module carries the
* method: for a named technique it returns the ordered steps, the exact command
* shape, the checks that confirm the result, and the mistake that wastes the
* engagement. Kali's tool list is the vocabulary; the procedure is what is
* written here.
*
* The knowledge is data, not code: one table of techniques, one table of tool
* notes. Adding a technique is adding a row.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "apex.h"
#include "tools.h"
typedef struct {
const char *id;
const char *phase; /* recon | enum | web | creds | ad | wifi | report */
const char *title;
const char *tools;
const char *when; /* the trigger: when to pick this one */
const char *steps; /* ordered, with reasons */
const char *confirm; /* evidence that makes it a finding */
const char *pitfall;
} technique;
static const technique TECHNIQUES[] = {
{
"host-discovery", "recon", "Live host discovery",
"nmap -sn, ping, arp-scan",
"Use before any port scan on a subnet: scanning 4096 ports against dead "
"hosts spends the time budget and tells you nothing.",
"1. ping the broadcast and the default gateway to learn the L2 segment.\n"
"2. nmap -sn -PE -PS22,80,443 <cidr> for ICMP plus TCP ping.\n"
"3. Cross-check with arp-scan -l on the local segment: a host that drops "
"ICMP still answers ARP.\n"
"4. Write each live host into the finding list with the method that found "
"it; a host found only by ARP is a different fact than one that answers "
"ICMP.",
"Any host that answers one method but not the other - that difference is "
"what tells you a firewall is present.",
"A subnet sweep from a VPS does not find the internal hosts: ARP does not "
"cross a router. Sweep from inside the segment." },
{
"port-scan", "recon", "Port scan with a purpose",
"nmap -sS/-sT, masscan, apex twin portscan",
"Use after host discovery, on the hosts that answered. Choose the profile "
"from what you already know, not from habit.",
"1. Fast pass: nmap -Pn -F or the built-in portscan on top 1024.\n"
"2. Service pass on the open ports only: nmap -sV -p<open> -Pn.\n"
"3. Script pass on the services that have scripts: nmap --script "
"http-title,http-headers,ssl-enum-ciphers -p<open>.\n"
"4. Write the evidence: the nmap output is the proof, so save the raw "
"text before summarising it.",
"A version banner plus an OS guess is a finding only when it is outdated "
"or default. 'Port 80 open' alone is inventory, not a finding.",
"-sS needs root. As a normal user nmap silently falls back to -sT; if the "
"output says 'not shown because not root', the scan was connect(), which "
"is slower and noisier." },
{
"service-enum", "enum", "Service enumeration",
"nmap -sV --script, banner grab, netcat",
"Use on every open port before calling it done: an open port is a claim, "
"the banner is the fact.",
"1. banner: connect and read the first bytes (SSH, SMTP, FTP, MySQL).\n"
"2. version: nmap -sV -p<port> gives product and version.\n"
"3. protocol-specific: smtp-user-enum for SMTP, snmpwalk for 161, "
"ldapsearch anonymous for 389, redis-cli ping for 6379.\n"
"4. default credentials on that product, one attempt, from the vendor "
"documentation - not a brute force.",
"The banner string with product and version. That is what makes a CVE "
"match possible; without it you are guessing.",
"A banner can be rewritten by the admin (httpd.conf ServerTokens). Match "
"the version against the actual behaviour before writing a CVE." },
{
"http-headers", "web", "HTTP surface: headers and defaults",
"curl -I, nmap http-headers, apex twin http_headers",
"Use as the first web check. It is cheap, it needs no exploitation, and "
"it produces real findings.",
"1. curl -sSI http://host/ and https://host/ - note every header.\n"
"2. Look for: missing HSTS/CSP/X-Frame-Options, Server and X-Powered-By "
"version disclosure, permissive CORS (Access-Control-Allow-Origin: * with "
"credentials).\n"
"3. Check the default page for the exact product and version.\n"
"4. Check robots.txt and sitemap.xml: they name what the admin did not "
"want indexed.",
"The raw response with the missing header. Write the header name and why "
"it matters, not 'headers are insecure'.",
"A missing CSP on a site with no injection point is low value; a missing "
"HSTS on a site with a login is a downgrade path. Rank by what it enables." },
{
"path-discovery", "web", "Path and endpoint discovery",
"feroxbuster, gobuster, ffuf, apex twin http_paths",
"Use when the visible site is a small part of the app: an admin panel, an "
"API, a backup or a .git directory is almost never linked.",
"1. Built-in shortlist first (.git, .env, admin, api, actuator, backup).\n"
"2. Then a wordlist: gobuster dir -w /usr/share/wordlists/dirb/common.txt "
"-x php,html,txt -t 20.\n"
"3. Filter noise: 200 and 301 are interesting, a custom 404 that answers "
"200 for everything is not. Compare lengths.\n"
"4. A .git/HEAD that answers 200 is a source disclosure: fetch "
".git/config and note the remote URL.",
"The status line and content length for a path that is not the catch-all "
"page. Fetch the body and keep it as evidence.",
"Without a baseline request to a random path you cannot tell a hit from a "
"soft 404. Always request /this-path-does-not-exist-<random> first." },
{
"sqli", "web", "SQL injection: confirm, then prove",
"sqlmap, manual quotes, apex twin sqli_probe",
"Use on parameters that reach the database: id=, cat=, user=, search=. "
"Not on parameters that are echoed only.",
"1. Baseline: request the page with a valid and an invalid value, note "
"status and length.\n"
"2. Single quote: an error page or a length jump is a lead.\n"
"3. Boolean pair: ' AND '1'='1 vs ' AND '1'='2 - if the answers differ, "
"the input reaches the query.\n"
"4. sqlmap -u '<url>' -p <param> --batch --level 2 --risk 1 to confirm the "
"technique. Never --dump against production: reading rows is data theft, "
"not a test.\n"
"5. Write the finding with the payload and the differing responses.",
"Two responses that differ only because of your boolean. That is proof the "
"parameter is in the query; the database version string from sqlmap is "
"the severity.",
"Time-based payloads (SLEEP) on a production database stall the app. Use "
"the boolean pair first; only escalate to time-based on a staging target." },
{
"xss", "web", "Cross-site scripting",
"manual markers, dalfox, apex twin xss_probe",
"Use on reflected parameters and on stored fields a second user reads. "
"Reflection alone is not a finding.",
"1. Send a unique marker, find it in the response.\n"
"2. Look at the context: inside <title>, inside an attribute, inside a "
"script block. Each one needs a different payload.\n"
"3. Test the encoding: < becomes &lt; means the sink is safe; < survives "
"means it is not.\n"
"4. For stored XSS, note who reads the page and what the payload can do "
"with their session - that is the impact.",
"The response where the angle brackets survive unencoded, with the "
"surrounding context in the evidence.",
"alert(1) in a page that also has a strict CSP does not execute. Report "
"the CSP state with the payload or the finding is wrong." },
{
"creds", "creds", "Credential testing without a lockout",
"hydra, medusa, netexec, curl",
"Use only when the engagement allows it and you know the lockout policy. "
"An account lockout on production is an outage you caused.",
"1. Find the policy first: a single deliberately wrong login tells you the "
"failure message; five fast ones tell you whether it locks.\n"
"2. Default credentials from the vendor docs, one attempt each.\n"
"3. If brute force is allowed: hydra -l <user> -P <list> <service>://<host> "
"with -t 4 and -W 3, never the default 16 threads.\n"
"4. On success, prove access with one harmless command and record where "
"the credential works.",
"A successful authentication and the privilege it grants. The credential "
"alone is not the finding; the access is.",
"Testing a password list against an account you do not own locks out a "
"real user. Check the policy, or test against a hash you already have." },
{
"ad", "ad", "Active Directory: the first three checks",
"netexec, ldapsearch, bloodhound-python, kerbrute",
"Use on any host with LDAP 389, Kerberos 88 or SMB 445. AD is usually the "
"real target behind a web app.",
"1. Anonymous LDAP: ldapsearch -x -H ldap://<dc> -s base "
"namingContexts. An answer means the directory talks to strangers.\n"
"2. SMB signing and version: netexec smb <cidr> --gen-relay-list. 'signing: "
"False' is the relay precondition.\n"
"3. User enumeration: kerbrute userenum with a small list; a valid user "
"answers differently from an invalid one.\n"
"4. With one credential: netexec smb <cidr> -u <user> -p <pass> "
"--shares, then bloodhound-python -c All for the paths.",
"Signing disabled plus a relayable host, or a valid user list - both are "
"concrete and both lead somewhere.",
"Lockout policy applies to Kerberos too. kerbrute with a large list "
"against a 3-attempt policy locks the whole department." },
{
"wifi", "wifi", "Wireless assessment with the Marauder",
"ESP32 Marauder, airodump-ng, hcxdumptool",
"Use when the engagement includes the radio: rogue APs, weak encryption, "
"captive portals. It is the only phase where a transmitter is involved.",
"1. marauder_info: firmware and board, and which commands this build has.\n"
"2. marauder_scan scanall 30: access points with BSSID, channel, RSSI, "
"encryption.\n"
"3. From the list: open networks (encryption OPN) and WEP are findings on "
"sight; WPA2-PSK is only a finding if the passphrase is guessable.\n"
"4. sniffpmkid for handshake material - capture is receive-only and "
"allowed; cracking it offline needs a wordlist and time you must budget.\n"
"5. Deauth, beacon spam and evil portal need \\\"serial_tx\\\": true in the "
"scope. They are denial-of-service against everyone in range, including "
"people who are not the client.",
"An open network, a WEP network, or a handshake plus a recovered "
"passphrase. RSSI plus BSSID is what makes it attributable.",
"Deauth is a radio jammer: it hits every device on the channel, not just "
"the target. That is why it needs an explicit flag and a written "
"authorisation, not a tool parameter." },
{
"report", "report", "Writing the finding that survives review",
"-",
"Use continuously, not at the end: a finding written an hour after the "
"test is a memory, not evidence.",
"1. Title: what is wrong, in the target's terms "
"('Git directory exposed on www.example.com').\n"
"2. Evidence: the raw request and the raw response, saved as a file.\n"
"3. Impact: what an attacker does next with it - not 'security risk'.\n"
"4. Reproduction: the exact command that shows it again.\n"
"5. Remediation: the concrete change, with the header or config line.\n"
"6. Confidence: certain (you did it), firm (the response proves it), "
"tentative (a lead). Never write certain for a lead.",
"The evidence file path. A finding with no path is deleted in review.",
"'Potential' findings train the client to ignore the report. If you could "
"not confirm it, say tentative and name the missing check." },
};
/* Tool notes: what a tool is for and the one thing people get wrong. */
typedef struct {
const char *name;
const char *use;
const char *mistake;
} toolnote;
static const toolnote TOOLS_KB_TABLE[] = {
{ "nmap", "port and service discovery; the -sV banner is what makes a CVE "
"match possible",
"running -p- with -sV against a whole subnet: it takes days. Scan open "
"ports first, then -sV only on those." },
{ "masscan", "internet-scale port sweep at line rate",
"its default rate (100 pps) is slower than nmap; and it does not do "
"service detection at all." },
{ "feroxbuster", "recursive content discovery with a good default wordlist",
"running it without a baseline 404 length: every soft-404 becomes a 'hit'." },
{ "ffuf", "fast fuzzing of paths, parameters and vhosts (-fs to filter size)",
"forgetting -fs/-fc: the output is 4000 identical catch-all pages." },
{ "gobuster", "vhost and directory brute force with extensions",
"no -t tuning: the default thread count gets you rate-limited or blocked." },
{ "sqlmap", "confirm and classify an injection after a manual lead",
"--dump/--os-shell on anything you do not own is data theft, not a test." },
{ "nikto", "quick CGI and server misconfiguration sweep",
"treating its output as findings: most lines are version notes. Confirm "
"each one." },
{ "hydra", "credential testing against a known service",
"the default 16 threads trip lockouts and IDS. Use -t 4 and check the "
"policy first." },
{ "netexec", "SMB/LDAP/WinRM spray, shares, signing, relay lists",
"spraying one password across all users without checking lockout: that is "
"an outage." },
{ "bloodhound-python", "collect AD relationships for attack paths",
"collecting without a second credential: the graph of an unauthenticated "
"run is nearly empty." },
{ "ldapsearch", "anonymous and authenticated directory queries",
"assuming anonymous is off - test it, it often is not." },
{ "curl", "exact bytes for a request: methods, headers, redirects, TLS",
"-k hides the certificate problem you were supposed to find." },
{ "openssl s_client", "certificate chain, SANs, protocol and cipher support",
"without -servername you get the default vhost certificate, not the one "
"the site serves." },
{ "tcpdump", "packet-level proof of what actually crossed the wire",
"no -s 0 means truncated packets; no -w means the evidence is gone when "
"the shell closes." },
{ "marauder", "ESP32 Wi-Fi/BLE scanning, capture and (gated) transmission",
"leaving a sniffer running: the next command gets an empty answer and the "
"device looks broken." },
{ "apex twin portscan", "in-process TCP connect scan, no external program",
"it is a connect scan: it appears in the target's application log, unlike "
"a SYN scan." },
};
/* ------------------------------------------------------------------ tools */
static void t_kb_technique(mcp_conn *c, const mcp_json *args, void *user)
{
const char *id = mcp_arg_string(args, "id");
const char *phase = mcp_arg_string(args, "phase");
size_t i;
mcp_buf b;
int shown = 0;
(void)user;
mcp_buf_init(&b);
if (id != NULL && *id != '\0') {
for (i = 0; i < sizeof(TECHNIQUES) / sizeof(TECHNIQUES[0]); i++) {
if (strcmp(TECHNIQUES[i].id, id) != 0)
continue;
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, TECHNIQUES[i].id);
mcp_buf_puts(&b, ",\"phase\":");
apex_json_str(&b, TECHNIQUES[i].phase);
mcp_buf_puts(&b, ",\"title\":");
apex_json_str(&b, TECHNIQUES[i].title);
mcp_buf_puts(&b, ",\"tools\":");
apex_json_str(&b, TECHNIQUES[i].tools);
mcp_buf_puts(&b, ",\"when\":");
apex_json_str(&b, TECHNIQUES[i].when);
mcp_buf_puts(&b, ",\"steps\":");
apex_json_str(&b, TECHNIQUES[i].steps);
mcp_buf_puts(&b, ",\"confirm\":");
apex_json_str(&b, TECHNIQUES[i].confirm);
mcp_buf_puts(&b, ",\"pitfall\":");
apex_json_str(&b, TECHNIQUES[i].pitfall);
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_reply_error(c, "no such technique");
mcp_buf_free(&b);
return;
}
mcp_buf_puts(&b, "[");
for (i = 0; i < sizeof(TECHNIQUES) / sizeof(TECHNIQUES[0]); i++) {
if (phase != NULL && *phase != '\0' &&
strcmp(TECHNIQUES[i].phase, phase) != 0)
continue;
if (shown > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, TECHNIQUES[i].id);
mcp_buf_puts(&b, ",\"phase\":");
apex_json_str(&b, TECHNIQUES[i].phase);
mcp_buf_puts(&b, ",\"title\":");
apex_json_str(&b, TECHNIQUES[i].title);
mcp_buf_puts(&b, ",\"tools\":");
apex_json_str(&b, TECHNIQUES[i].tools);
mcp_buf_puts(&b, ",\"when\":");
apex_json_str(&b, TECHNIQUES[i].when);
mcp_buf_puts(&b, "}");
shown++;
}
mcp_buf_puts(&b, "]");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_kb_tool(mcp_conn *c, const mcp_json *args, void *user)
{
const char *name = mcp_arg_string(args, "name");
size_t i;
mcp_buf b;
(void)user;
mcp_buf_init(&b);
if (name == NULL || *name == '\0') {
mcp_buf_puts(&b, "[");
for (i = 0; i < sizeof(TOOLS_KB_TABLE) / sizeof(TOOLS_KB_TABLE[0]); i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"name\":");
apex_json_str(&b, TOOLS_KB_TABLE[i].name);
mcp_buf_puts(&b, ",\"use\":");
apex_json_str(&b, TOOLS_KB_TABLE[i].use);
mcp_buf_puts(&b, "}");
}
mcp_buf_puts(&b, "]");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
return;
}
for (i = 0; i < sizeof(TOOLS_KB_TABLE) / sizeof(TOOLS_KB_TABLE[0]); i++) {
if (strstr(TOOLS_KB_TABLE[i].name, name) == NULL)
continue;
mcp_buf_puts(&b, "{\"name\":");
apex_json_str(&b, TOOLS_KB_TABLE[i].name);
mcp_buf_puts(&b, ",\"use\":");
apex_json_str(&b, TOOLS_KB_TABLE[i].use);
mcp_buf_puts(&b, ",\"mistake\":");
apex_json_str(&b, TOOLS_KB_TABLE[i].mistake);
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_reply_error(c, "no note for that tool");
mcp_buf_free(&b);
}
static void t_kb_plan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *phase = mcp_arg_string(args, "phase");
size_t i;
mcp_buf b;
int shown = 0;
(void)user;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"phase\":");
apex_json_str(&b, phase != NULL ? phase : "all");
mcp_buf_puts(&b, ",\"order\":[");
for (i = 0; i < sizeof(TECHNIQUES) / sizeof(TECHNIQUES[0]); i++) {
if (phase != NULL && *phase != '\0' &&
strcmp(TECHNIQUES[i].phase, phase) != 0)
continue;
if (shown > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, TECHNIQUES[i].id);
mcp_buf_puts(&b, ",\"phase\":");
apex_json_str(&b, TECHNIQUES[i].phase);
mcp_buf_puts(&b, ",\"title\":");
apex_json_str(&b, TECHNIQUES[i].title);
mcp_buf_puts(&b, ",\"first_move\":");
apex_json_str(&b, TECHNIQUES[i].when);
mcp_buf_puts(&b, "}");
shown++;
}
mcp_buf_printf(&b, "],\"count\":%d,\"note\":\"run these in order; each one "
"names the check that turns a lead into a finding\"}", shown);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_KB[] = {
{ "method_techniques",
"List the engagement techniques with the phase they belong to and the "
"trigger that says when to pick them. Call it before planning an "
"engagement so the plan follows a method instead of a habit.",
"{\"type\":\"object\",\"properties\":{"
"\"id\":{\"type\":\"string\",\"description\":\"omit to list all; e.g. "
"\\\"sqli\\\", \\\"wifi\\\", \\\"ad\\\"\"},"
"\"phase\":{\"type\":\"string\",\"description\":\"recon|enum|web|creds|ad|wifi|report\"}}}",
t_kb_technique },
{ "method_playbook",
"Return the ordered steps for one technique, plus the confirmation check "
"and the pitfall that wastes time on it. Use it right before you run a "
"phase you have not done in this engagement.",
"{\"type\":\"object\",\"properties\":{"
"\"phase\":{\"type\":\"string\",\"description\":\"filter by phase; omit for "
"the whole order\"}}}",
t_kb_plan },
{ "method_tool",
"Explain what a tool is for and the one mistake people make with it. Use "
"it when you are about to reach for a tool and are not sure which "
"parameters matter.",
"{\"type\":\"object\",\"properties\":{"
"\"name\":{\"type\":\"string\",\"description\":\"e.g. nmap, sqlmap, marauder; "
"omit for the index\"}}}",
t_kb_tool },
};
const size_t TOOLS_KB_N = sizeof(TOOLS_KB) / sizeof(TOOLS_KB[0]);
+606
View File
@@ -0,0 +1,606 @@
/*
* tools_radio.c - ESP32 Marauder over serial.
*
* Marauder speaks a plain line CLI at 115200 baud on its USB serial port
* (/dev/ttyACM0 when it is an Espressif USB JTAG unit, /dev/ttyUSB0 on the
* older CP210x boards). This module does three things:
*
* marauder_info ask `info` and `help`, so a model learns what this exact
* firmware build can do before it tries anything
* marauder_cmd send one command from an allowlist and return its output
* marauder_scan run a scanning command for a bounded time, then stop it
*
* Two rules, both learned from the device:
*
* 1. A scan is started, waited on, and *stopped*. Leaving a sniffer running
* is how the next command gets an empty answer and nobody knows why.
* 2. Anything that transmits (deauth, beacon spam, evil portal, BLE spam) is
* gated twice: on the scope's serial_tx flag and on the command allowlist.
* A receiver is a scanner; a transmitter is an attack.
*/
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <termios.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
static char *find_ci_local(const char *hay, const char *needle)
{
size_t nl = strlen(needle);
const char *p;
if (nl == 0)
return (char *)hay;
for (p = hay; *p != '\0'; p++) {
size_t i;
for (i = 0; i < nl; i++) {
char c = p[i];
if (c >= 'A' && c <= 'Z')
c = (char)(c - 'A' + 'a');
if (p[i] == '\0' || c != needle[i])
break;
}
if (i == nl)
return (char *)p;
}
return NULL;
}
static int baud_constant(int baud)
{
switch (baud) {
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
default: return B115200;
}
}
static int serial_open(const char *path, int baud)
{
int fd = open(path, O_RDWR | O_NOCTTY | O_NONBLOCK);
struct termios tio;
if (fd < 0)
return -1;
if (tcgetattr(fd, &tio) != 0) {
close(fd);
return -1;
}
cfmakeraw(&tio);
cfsetispeed(&tio, baud_constant(baud));
cfsetospeed(&tio, baud_constant(baud));
tio.c_cflag |= (CLOCAL | CREAD);
tio.c_cflag &= ~CRTSCTS;
tio.c_cc[VMIN] = 0;
tio.c_cc[VTIME] = 0;
if (tcsetattr(fd, TCSANOW, &tio) != 0) {
close(fd);
return -1;
}
tcflush(fd, TCIOFLUSH);
/* back to blocking reads with a timeout for the actual conversation */
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags >= 0)
fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
}
return fd;
}
static size_t serial_talk(int fd, const char *cmd, char *out, size_t cap,
int quiet_ms, int max_ms);
/*
* Listen before talking. The port may be something else entirely - on this host
* /dev/ttyACM0 is an Espressif USB JTAG unit running a Mikronix console, and a
* Marauder command typed into a login prompt is noise at best and a lockout at
* worst ("3 incorrect attempts, giving up").
*
* A device that greets us with a login prompt is not a radio. A silent device
* may be a Marauder: its CLI prints nothing until a command arrives.
* Returns 1 when it is safe to write, 0 when it is not; why[] says which.
*/
static int serial_guard(int fd, char *why, size_t n)
{
static const char *deny[] = { "login:", "password:", "console (",
"mikronix", "netbsd", "busybox", "root@",
"giving up", "incorrect attempts" };
char banner[4096];
size_t got;
size_t i;
/*
* A console stays silent until something is typed, so listening alone
* proves nothing: on this host the bare CRLF below is what makes
* /dev/ttyACM0 answer with its Mikronix login prompt. A Marauder answers a
* blank line with nothing or with a fresh prompt - neither matches deny[].
*/
memset(banner, 0, sizeof(banner));
got = serial_talk(fd, "", banner, sizeof(banner), 300, 1500);
for (i = 0; i < sizeof(deny) / sizeof(deny[0]); i++) {
char *hit = find_ci_local(banner, deny[i]);
if (hit != NULL) {
char context[120];
size_t k = 0;
while (hit[k] != '\0' && hit[k] != '\n' && hit[k] != '\r' &&
k + 1 < sizeof(context)) {
unsigned char ch = (unsigned char)hit[k];
context[k] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : ' ';
k++;
}
context[k] = '\0';
snprintf(why, n, "%s is not a Marauder: it answered a blank line "
"with \"%s\". Refusing to send radio commands to a shell "
"login. Set APEX_SERIAL to the Marauder's port.",
g_cfg.serial, context);
return 0;
}
}
if (got == 0)
snprintf(why, n, "%s stayed silent; assuming a Marauder CLI", g_cfg.serial);
else
snprintf(why, n, "%s answered a blank line with no shell prompt; "
"assuming a Marauder CLI", g_cfg.serial);
return 1;
}
/* Send a line, then collect whatever arrives until `quiet_ms` passes with no
* new byte or `max_ms` is up. Marauder has no framing, so quiet is the signal. */
static size_t serial_talk(int fd, const char *cmd, char *out, size_t cap,
int quiet_ms, int max_ms)
{
size_t used = 0;
struct timeval t0;
if (cmd != NULL) {
char line[256];
snprintf(line, sizeof(line), "%s\r\n", cmd);
if (write(fd, line, strlen(line)) < 0)
return 0;
tcdrain(fd);
}
gettimeofday(&t0, NULL);
for (;;) {
struct pollfd pfd;
struct timeval now;
long spent;
gettimeofday(&now, NULL);
spent = (now.tv_sec - t0.tv_sec) * 1000L +
(now.tv_usec - t0.tv_usec) / 1000L;
if (spent >= max_ms)
break;
pfd.fd = fd;
pfd.events = POLLIN;
if (poll(&pfd, 1, quiet_ms) <= 0) {
if (used > 0)
break; /* silence after data: answer is complete */
continue; /* silence before data: keep waiting */
}
{
char buf[512];
ssize_t n = read(fd, buf, sizeof(buf));
if (n <= 0)
break;
if (used + (size_t)n + 1 > cap)
n = (ssize_t)(cap - used - 1);
if (n > 0) {
memcpy(out + used, buf, (size_t)n);
used += (size_t)n;
}
}
}
if (cap > 0) {
/* strip trailing NULs and control noise the device sends at open */
while (used > 0 && (out[used - 1] == '\0' || out[used - 1] == '\r'))
used--;
out[used] = '\0';
}
return used;
}
/* ------------------------------------------------------------ allowlists */
typedef struct {
const char *name;
int transmits;
const char *why;
} radio_cmd;
/*
* Only what a firmware answers to. Everyone of these was taken from the
* Marauder CLI index (help, info, scanall, sniffbeacon, sniffdeauth,
* sniffpmkid, sniffsae, channel, foxhunt, mactrack, pingscan, recon,
* wardrive, gpsdata, remoteid, csimotion, stopscan, list, select, clearlist,
* join, evilportal, sniffbt, blespam, settings, led, save, load, reboot).
* A command not in this table is refused - a model does not get to type raw
* text into a radio.
*/
static const radio_cmd RADIO_CMDS[] = {
{ "info", 0, "firmware version and board identity" },
{ "help", 0, "the command set this build actually has" },
{ "scanall", 0, "scan APs and stations" },
{ "sniffbeacon", 0, "capture beacon frames" },
{ "sniffdeauth", 0, "capture deauthentication frames" },
{ "sniffpmkid", 0, "capture PMKID handshake material" },
{ "sniffsae", 0, "capture SAE authentication frames" },
{ "sniffbt", 0, "scan Bluetooth devices" },
{ "stopscan", 0, "stop the running scan" },
{ "list", 0, "show the current target list" },
{ "clearlist", 0, "clear the target list" },
{ "channel", 0, "channel analysis" },
{ "foxhunt", 0, "signal strength hunt" },
{ "mactrack", 0, "track a MAC address" },
{ "pingscan", 0, "ping sweep" },
{ "recon", 0, "combined recon" },
{ "wardrive", 0, "recon with GPS logging" },
{ "gpsdata", 0, "GPS position" },
{ "remoteid", 0, "drone Remote ID scan" },
{ "csimotion", 0, "CSI motion monitor" },
{ "settings", 0, "read device settings" },
{ "led", 0, "set the LED" },
{ "save", 0, "save to SD" },
{ "load", 0, "load from SD" },
/* transmitters: gated on scope.serial_tx */
{ "attack", 1, "deauthentication and beacon flood" },
{ "evilportal", 1, "captive portal" },
{ "blespam", 1, "BLE advertisement spam" },
{ "spoofat", 1, "AirTag spoofing" },
{ "join", 1, "join a network" },
{ "reboot", 1, "restart the device" },
{ "update", 1, "firmware update" },
};
static const radio_cmd *radio_lookup(const char *name)
{
size_t i;
if (name == NULL)
return NULL;
for (i = 0; i < sizeof(RADIO_CMDS) / sizeof(RADIO_CMDS[0]); i++)
if (strcmp(RADIO_CMDS[i].name, name) == 0)
return &RADIO_CMDS[i];
return NULL;
}
/* A free-text argument after the command: letters, digits, a few separators. */
static int safe_arg(const char *s)
{
size_t i;
if (s == NULL)
return 1;
if (strlen(s) > 96)
return 0;
for (i = 0; s[i] != '\0'; i++) {
unsigned char c = (unsigned char)s[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9'))
continue;
if (c == ' ' || c == '-' || c == '_' || c == '.' || c == ':' ||
c == '/' || c == ',')
continue;
return 0;
}
if (strstr(s, "\r") != NULL || strstr(s, "\n") != NULL)
return 0;
return 1;
}
/* --------------------------------------------------------------- handlers */
static void t_radio_info(mcp_conn *c, const mcp_json *args, void *user)
{
char *out;
size_t n;
int fd;
mcp_buf b;
(void)args;
(void)user;
fd = serial_open(g_cfg.serial, g_cfg.baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s (is the Marauder plugged in? "
"set APEX_SERIAL)", g_cfg.serial, strerror(errno));
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
out = calloc(1, 16384);
if (out == NULL) {
close(fd);
mcp_reply_error(c, "out of memory");
return;
}
{
char why[512];
if (!serial_guard(fd, why, sizeof(why))) {
apex_audit("marauder_info", g_cfg.serial, 0, 0, why, NULL);
mcp_reply_error(c, why);
close(fd);
free(out);
return;
}
}
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"port\":");
apex_json_str(&b, g_cfg.serial);
mcp_buf_printf(&b, ",\"baud\":%d,\"scope_serial_tx\":%s,",
g_cfg.baud, g_scope.serial_tx ? "true" : "false");
n = serial_talk(fd, "info", out, 16384, 400, 4000);
mcp_buf_puts(&b, "\"info\":");
apex_json_str(&b, out);
n = serial_talk(fd, "help", out, 16384, 400, 6000);
mcp_buf_puts(&b, ",\"help\":");
apex_json_str(&b, out);
mcp_buf_puts(&b, "}");
close(fd);
free(out);
(void)n;
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_radio_cmd(mcp_conn *c, const mcp_json *args, void *user)
{
const char *name = mcp_arg_string(args, "command");
const char *arg = mcp_arg_string(args, "arg");
const radio_cmd *rc;
char line[256];
char *out;
int fd;
mcp_buf b;
(void)user;
rc = radio_lookup(name);
if (rc == NULL) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "command not in the allowlist: %s",
name != NULL ? name : "(none)");
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
if (!safe_arg(arg)) {
mcp_reply_error(c, "argument contains characters a radio does not need");
return;
}
if (rc->transmits && !g_scope.serial_tx) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "'%s' transmits (%s) but the scope has "
"serial_tx=false. Add \\\"serial_tx\\\": true to the scope "
"file and reload it, after the engagement allows it.",
rc->name, rc->why);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
apex_audit("marauder_cmd", rc->name, 0, 0, "serial_tx disabled", name);
return;
}
if (arg != NULL && *arg != '\0')
snprintf(line, sizeof(line), "%s %s", rc->name, arg);
else
snprintf(line, sizeof(line), "%s", rc->name);
apex_audit("marauder_cmd", line, 0, 1,
rc->transmits ? "transmit allowed" : "receive only", name);
if (g_cfg.dry_run) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "DRY RUN, not sent: %s on %s", line, g_cfg.serial);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
return;
}
fd = serial_open(g_cfg.serial, g_cfg.baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s", g_cfg.serial, strerror(errno));
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
out = calloc(1, 16384);
if (out == NULL) {
close(fd);
mcp_reply_error(c, "out of memory");
return;
}
{
char why[512];
if (!serial_guard(fd, why, sizeof(why))) {
apex_audit("marauder_cmd", line, 0, 0, why, NULL);
mcp_reply_error(c, why);
close(fd);
free(out);
return;
}
}
(void)serial_talk(fd, line, out, 16384, 400, 6000);
mcp_buf_init(&b);
mcp_buf_printf(&b, "$ %s\n%s", line, out[0] != '\0' ? out : "(no output)");
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
close(fd);
free(out);
}
static void t_radio_scan(mcp_conn *c, const mcp_json *args, void *user)
{
const char *name = mcp_arg_string(args, "command");
int seconds = mcp_arg_int(args, "seconds", 20);
char *out;
int fd;
mcp_buf b;
const radio_cmd *rc;
(void)user;
rc = radio_lookup(name != NULL ? name : "scanall");
if (rc == NULL || rc->transmits) {
mcp_reply_error(c, "use a receive-only scan command: scanall, sniffbeacon, "
"sniffdeauth, sniffpmkid, sniffbt, recon, wardrive");
return;
}
if (seconds < 3)
seconds = 3;
if (seconds > 300)
seconds = 300;
apex_audit("marauder_scan", name, 0, 1, "receive-only scan", name);
if (g_cfg.dry_run) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "DRY RUN, not started: %s for %d s", name, seconds);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
return;
}
fd = serial_open(g_cfg.serial, g_cfg.baud);
if (fd < 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "cannot open %s: %s", g_cfg.serial, strerror(errno));
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
out = calloc(1, 65536);
if (out == NULL) {
close(fd);
mcp_reply_error(c, "out of memory");
return;
}
{
char why[512];
if (!serial_guard(fd, why, sizeof(why))) {
apex_audit("marauder_scan", name, 0, 0, why, NULL);
mcp_reply_error(c, why);
close(fd);
free(out);
return;
}
}
(void)serial_talk(fd, name, out, 65536, 500, 2000);
{
int waited = 0;
while (waited < seconds * 1000) {
size_t used = strlen(out);
char more[8192];
memset(more, 0, sizeof(more));
if (serial_talk(fd, NULL, more, sizeof(more), 500, 2000) == 0)
break;
if (used + strlen(more) + 1 < 65536)
memcpy(out + used, more, strlen(more));
waited += 2000;
}
}
/* always stop the scan: a running sniffer answers nothing afterwards */
{
char stop[2048];
memset(stop, 0, sizeof(stop));
(void)serial_talk(fd, "stopscan", stop, sizeof(stop), 400, 3000);
}
close(fd);
mcp_buf_init(&b);
mcp_buf_printf(&b, "$ %s (%d s, then stopscan)\n", name, seconds);
mcp_buf_add(&b, out, strlen(out));
if (strlen(out) == 0)
mcp_buf_puts(&b, "(no output - is the antenna attached?)");
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
free(out);
}
static void t_radio_commands(mcp_conn *c, const mcp_json *args, void *user)
{
mcp_buf b;
size_t i;
(void)args;
(void)user;
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"port\":");
apex_json_str(&b, g_cfg.serial);
mcp_buf_printf(&b, ",\"baud\":%d,\"serial_tx\":%s,\"commands\":[",
g_cfg.baud, g_scope.serial_tx ? "true" : "false");
for (i = 0; i < sizeof(RADIO_CMDS) / sizeof(RADIO_CMDS[0]); i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"command\":");
apex_json_str(&b, RADIO_CMDS[i].name);
mcp_buf_printf(&b, ",\"transmits\":%s,\"why\":",
RADIO_CMDS[i].transmits ? "true" : "false");
apex_json_str(&b, RADIO_CMDS[i].why);
mcp_buf_puts(&b, "}");
}
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_RADIO[] = {
{ "marauder_info",
"Open the ESP32 Marauder serial port and return the firmware's own `info` "
"and `help` output. Call this first: it tells you which commands this exact "
"build has and which board it is.",
"{\"type\":\"object\",\"properties\":{}}",
t_radio_info },
{ "marauder_commands",
"List the radio commands APEX TWIN will forward and mark which ones "
"transmit. Use it to see whether the attached device is usable at all "
"without sending anything.",
"{\"type\":\"object\",\"properties\":{}}",
t_radio_commands },
{ "marauder_cmd",
"Send one allowlisted command to the Marauder and return its output. "
"Transmitting commands (attack, evilportal, blespam, spoofat, join, reboot, "
"update) need \\\"serial_tx\\\": true in the scope: a receiver is a scanner, "
"a transmitter is an attack.",
"{\"type\":\"object\",\"properties\":{"
"\"command\":{\"type\":\"string\",\"description\":\"e.g. info, list, "
"channel, gpsdata, settings\"},"
"\"arg\":{\"type\":\"string\",\"description\":\"optional argument after the "
"command\"}},"
"\"required\":[\"command\"]}",
t_radio_cmd },
{ "marauder_scan",
"Run a receive-only radio scan for a bounded number of seconds and then "
"stop it, returning everything the device printed. Use it for Wi-Fi access "
"points, beacon frames, handshake material or Bluetooth devices. The scan "
"is always stopped before the tool returns, so the next command gets a "
"clean device.",
"{\"type\":\"object\",\"properties\":{"
"\"command\":{\"type\":\"string\",\"enum\":[\"scanall\",\"sniffbeacon\","
"\"sniffdeauth\",\"sniffpmkid\",\"sniffsae\",\"sniffbt\",\"recon\","
"\"wardrive\",\"remoteid\",\"csimotion\"]},"
"\"seconds\":{\"type\":\"integer\",\"description\":\"3-300, default 20\"}},"
"\"required\":[\"command\"]}",
t_radio_scan },
};
const size_t TOOLS_RADIO_N = sizeof(TOOLS_RADIO) / sizeof(TOOLS_RADIO[0]);
+935
View File
@@ -0,0 +1,935 @@
/*
* tools_recon.c - network reconnaissance, each one behind the gate.
*
* Two shapes of tool live here:
*
* apex_run() nmap, dig, host, whois, openssl - real binaries, real
* protocols, output captured and returned verbatim.
* pure C the TCP connect probes, the certificate fetch and the HTTP
* request use no external program at all, so APEX TWIN still
* works on a box where only libc is installed.
*
* Every handler calls gated() first. gated() is the only place that decides,
* and it writes the audit line before returning.
*/
#include <arpa/inet.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
/* --------------------------------------------------------------- helpers */
/*
* The one gate call every tool makes. Returns 1 when the target may be touched,
* 0 otherwise; on 0 the caller must reply with an error and return.
*/
int gated(mcp_conn *c, const char *tool, const char *target, int port)
{
char reason[512];
int ok = apex_scope_check(target, port, reason, sizeof(reason));
apex_audit(tool, target, port, ok, reason, NULL);
if (!ok) {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return 0;
}
return 1;
}
int gated_cmd(mcp_conn *c, const char *tool, const char *target, int port,
char *const argv[], int timeout_ms, int *exit_code)
{
char reason[512];
int ok = apex_scope_check(target, port, reason, sizeof(reason));
char *cmd = apex_join_argv(argv);
apex_proc p;
mcp_buf b;
int rc;
apex_audit(tool, target, port, ok, reason, cmd);
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
free(cmd);
return 0;
}
if (g_cfg.dry_run) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "DRY RUN, not executed: %s", cmd != NULL ? cmd : "");
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
free(cmd);
return 0;
}
rc = apex_run(argv, timeout_ms, g_cfg.max_output, &p);
if (rc != 0) {
mcp_reply_error(c, "cannot run the command");
free(cmd);
return 0;
}
mcp_buf_init(&b);
mcp_buf_printf(&b, "$ %s\nexit=%d time=%ldms%s%s\n",
cmd != NULL ? cmd : "", p.exit_code, p.elapsed_ms,
p.truncated ? " TRUNCATED" : "",
p.timed_out ? " TIMEOUT" : "");
if (p.exit_code == 127) {
mcp_buf_printf(&b, "the program is not installed on this host\n");
}
if (p.out != NULL && p.out_len > 0)
mcp_buf_add(&b, p.out, p.out_len);
else
mcp_buf_puts(&b, "(no output)");
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
if (exit_code != NULL)
*exit_code = p.exit_code;
apex_proc_free(&p);
free(cmd);
return 1;
}
/* A plain TCP connect with a millisecond budget. Returns 0 open, -1 closed. */
int tcp_probe(const char *host, int port, int timeout_ms)
{
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p;
char service[16];
int fd;
int rc = -1;
int flags;
snprintf(service, sizeof(service), "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, service, &hints, &res) != 0)
return -1;
for (p = res; p != NULL; p = p->ai_next) {
struct pollfd pfd;
int err = 0;
socklen_t elen = sizeof(err);
fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (fd < 0)
continue;
flags = fcntl(fd, F_GETFL, 0);
if (flags >= 0)
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
rc = connect(fd, p->ai_addr, p->ai_addrlen);
if (rc == 0) {
close(fd);
res ? freeaddrinfo(res) : (void)0;
return 0;
}
if (errno != EINPROGRESS) {
close(fd);
continue;
}
pfd.fd = fd;
pfd.events = POLLOUT;
rc = poll(&pfd, 1, timeout_ms);
if (rc <= 0) {
close(fd);
rc = -1;
continue;
}
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &elen) != 0 || err != 0) {
close(fd);
rc = -1;
continue;
}
close(fd);
freeaddrinfo(res);
return 0;
}
if (res != NULL)
freeaddrinfo(res);
return -1;
}
/* Same connect, but hands back the fd for a request. */
int tcp_connect_host(const char *host, int port, int timeout_ms)
{
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *p;
char service[16];
int fd = -1;
snprintf(service, sizeof(service), "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host, service, &hints, &res) != 0)
return -1;
for (p = res; p != NULL; p = p->ai_next) {
struct timeval tv;
int flags;
struct pollfd pfd;
int err = 0;
socklen_t elen = sizeof(err);
fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (fd < 0)
continue;
flags = fcntl(fd, F_GETFL, 0);
if (flags >= 0)
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
if (connect(fd, p->ai_addr, p->ai_addrlen) != 0) {
if (errno != EINPROGRESS) {
close(fd);
fd = -1;
continue;
}
pfd.fd = fd;
pfd.events = POLLOUT;
if (poll(&pfd, 1, timeout_ms) <= 0) {
close(fd);
fd = -1;
continue;
}
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &elen) != 0 ||
err != 0) {
close(fd);
fd = -1;
continue;
}
}
/* back to blocking with a timeout: the caller reads a reply */
if (flags >= 0)
fcntl(fd, F_SETFL, flags);
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
break;
}
if (res != NULL)
freeaddrinfo(res);
return fd;
}
/* ------------------------------------------------------------------ tools */
static void t_scope(mcp_conn *c, const mcp_json *args, void *user)
{
mcp_buf b;
(void)args;
(void)user;
mcp_buf_init(&b);
apex_scope_json(&b);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_scope_reload(mcp_conn *c, const mcp_json *args, void *user)
{
mcp_buf b;
const char *path;
(void)user;
path = mcp_arg_string(args, "path");
if (path != NULL && *path != '\0') {
snprintf(g_cfg.scope_file, sizeof(g_cfg.scope_file), "%s", path);
}
mcp_buf_init(&b);
if (apex_scope_load() != 0) {
mcp_buf_printf(&b, "cannot load scope from %s", g_cfg.scope_file);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
apex_audit("scope_reload", g_cfg.scope_file, 0, 0, "load failed", NULL);
return;
}
apex_audit("scope_reload", g_cfg.scope_file, 0, 1, "loaded", NULL);
apex_scope_json(&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");
const char *ports = mcp_arg_string(args, "ports");
int timeout = mcp_arg_int(args, "timeout_ms", 2000);
mcp_buf b;
int checked = 0;
int open_count = 0;
int lo;
int hi;
int port;
(void)user;
(void)ports;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (timeout < 100)
timeout = 100;
if (timeout > 30000)
timeout = 30000;
/* the gate runs once per port range check; the audit line names the range */
if (!gated(c, "portscan", target, 0))
return;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_puts(&b, ",\"open\":[");
lo = 1;
hi = 1024;
if (ports != NULL && sscanf(ports, "%d-%d", &lo, &hi) != 2) {
if (sscanf(ports, "%d", &lo) == 1)
hi = lo;
}
if (lo < 1)
lo = 1;
if (hi > 65535)
hi = 65535;
if (lo > hi)
lo = hi;
for (port = lo; port <= hi && checked < 4096; port++) {
if (!apex_port_in_scope(port))
continue;
checked++;
if (tcp_probe(target, port, timeout) == 0) {
if (open_count > 0)
mcp_buf_puts(&b, ",");
mcp_buf_printf(&b, "%d", port);
open_count++;
}
}
mcp_buf_printf(&b, "],\"checked\":%d,\"open_count\":%d,", checked, open_count);
mcp_buf_printf(&b, "\"timeout_ms\":%d}", timeout);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_nmap(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *profile = mcp_arg_string(args, "profile");
int timeout = mcp_arg_int(args, "timeout_ms", 300000);
char *argv[24];
int i = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (!apex_have("nmap")) {
mcp_reply_error(c, "nmap is not installed on this host");
return;
}
argv[i++] = "nmap";
if (profile == NULL || strcmp(profile, "default") == 0) {
argv[i++] = "-sV";
argv[i++] = "-Pn";
argv[i++] = "--top-ports";
argv[i++] = "100";
} else if (strcmp(profile, "quick") == 0) {
argv[i++] = "-Pn";
argv[i++] = "-F";
} else if (strcmp(profile, "full") == 0) {
argv[i++] = "-sV";
argv[i++] = "-Pn";
argv[i++] = "-p-";
} else if (strcmp(profile, "udp") == 0) {
argv[i++] = "-sU";
argv[i++] = "--top-ports";
argv[i++] = "50";
} else if (strcmp(profile, "vuln") == 0) {
argv[i++] = "-sV";
argv[i++] = "--script";
argv[i++] = "vuln";
argv[i++] = "-Pn";
} else if (strcmp(profile, "http") == 0) {
argv[i++] = "-Pn";
argv[i++] = "-p";
argv[i++] = "80,443,8000,8080,8443";
argv[i++] = "-sV";
} else {
mcp_reply_error(c, "unknown profile: quick|default|full|udp|vuln|http");
return;
}
/* --: a target starting with '-' must not become an option */
argv[i++] = "--";
argv[i++] = (char *)target;
argv[i] = NULL;
gated_cmd(c, "nmap", target, 0, argv, timeout, NULL);
}
static void t_dns(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *type = mcp_arg_string(args, "type");
char *argv[8];
int i = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (!apex_have("dig")) {
mcp_reply_error(c, "dig is not installed on this host");
return;
}
argv[i++] = "dig";
argv[i++] = "+short";
argv[i++] = "+time=5";
argv[i++] = "+tries=1";
if (type != NULL && *type != '\0') {
static const char *ok_types[] = { "A", "AAAA", "MX", "TXT", "NS", "SOA",
"CNAME", "SRV", "CAA", "PTR" };
size_t k;
for (k = 0; k < sizeof(ok_types) / sizeof(ok_types[0]); k++) {
if (strcmp(type, ok_types[k]) == 0)
break;
}
if (k == sizeof(ok_types) / sizeof(ok_types[0])) {
mcp_reply_error(c, "unsupported record type");
return;
}
{
char *upper = apex_strdup(type);
if (upper == NULL) {
mcp_reply_error(c, "out of memory");
return;
}
for (k = 0; upper[k] != '\0'; k++)
upper[k] = (char)toupper((unsigned char)upper[k]);
/* the argv array outlives this block only until apex_run */
argv[i++] = upper;
argv[i++] = (char *)target;
argv[i] = NULL;
gated_cmd(c, "dns", target, 0, argv, 20000, NULL);
free(upper);
return;
}
}
argv[i++] = (char *)target;
argv[i] = NULL;
gated_cmd(c, "dns", target, 0, argv, 20000, NULL);
}
static void t_tls_cert(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
int port = mcp_arg_int(args, "port", 443);
char portstr[16];
char *argv[10];
int i = 0;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (port <= 0 || port > 65535) {
mcp_reply_error(c, "port out of range");
return;
}
if (!apex_have("openssl")) {
mcp_reply_error(c, "openssl is not installed on this host");
return;
}
snprintf(portstr, sizeof(portstr), "%d", port);
argv[i++] = "openssl";
argv[i++] = "s_client";
argv[i++] = "-connect";
argv[i++] = portstr;
argv[i++] = "-servername";
argv[i++] = (char *)target;
argv[i++] = "-showcerts";
argv[i++] = "-verify_return_error";
argv[i] = NULL;
/* openssl waits on stdin; apex_run gives it /dev/null, which closes it */
gated_cmd(c, "tls_cert", target, port, argv, 30000, NULL);
}
static void t_http_head(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
int port = mcp_arg_int(args, "port", 443);
int use_tls = mcp_arg_bool(args, "tls", port == 443);
mcp_buf b;
int fd;
char request[1024];
char response[8192];
ssize_t n;
char reason[512];
char *cmd;
int ok;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (path[0] != '/') {
mcp_reply_error(c, "path must start with /");
return;
}
ok = apex_scope_check(target, port, reason, sizeof(reason));
mcp_buf_init(&b);
mcp_buf_printf(&b, "HEAD %s%s:%d%s HTTP/1.1", use_tls ? "https://" : "http://",
target, port, path);
cmd = b.p;
apex_audit("http_head", target, port, ok, reason, cmd);
mcp_buf_free(&b);
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
/* Plain HTTP is done in-process. HTTPS would need a TLS stack; this binary
* has no OpenSSL link, so it hands that one case to the installed client. */
if (use_tls) {
char *argv[10];
int i = 0;
char url[600];
char *header = NULL;
char *payload = NULL;
if (!apex_have("curl")) {
mcp_reply_error(c, "curl is not installed, cannot speak TLS");
return;
}
snprintf(url, sizeof(url), "https://%s:%d%s", target, port, path);
if (g_cfg.dry_run) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "DRY RUN, not executed: curl -sSI %s", url);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
return;
}
{
char *env = getenv("APEX_CURL_HEADERS");
if (env != NULL && *env != '\0')
header = apex_strdup(env);
}
payload = apex_strdup("APEX");
argv[i++] = "curl";
argv[i++] = "-sS";
argv[i++] = "-I";
argv[i++] = "--max-time";
argv[i++] = "20";
if (header != NULL) {
argv[i++] = "-H";
argv[i++] = header;
}
(void)payload;
argv[i++] = url;
argv[i] = NULL;
gated_cmd(c, "http_head", target, port, argv, 30000, NULL);
free(header);
free(payload);
return;
}
fd = tcp_connect_host(target, port, 8000);
if (fd < 0) {
mcp_reply_error(c, "cannot connect");
return;
}
snprintf(request, sizeof(request),
"HEAD %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: apex-twin/%s\r\n"
"Accept: */*\r\nConnection: close\r\n\r\n",
path, target, APEX_VERSION);
if (write(fd, request, strlen(request)) < 0) {
close(fd);
mcp_reply_error(c, "cannot send the request");
return;
}
n = read(fd, response, sizeof(response) - 1);
close(fd);
if (n <= 0) {
mcp_reply_error(c, "no response");
return;
}
response[n] = '\0';
mcp_buf_init(&b);
mcp_buf_printf(&b, "HEAD %s:%d%s\n", target, port, path);
mcp_buf_add(&b, response, (size_t)n);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
}
static void t_banner(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 wait = mcp_arg_int(args, "wait_ms", 1500);
mcp_buf b;
int fd;
char buf[2048];
ssize_t n;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (!gated(c, "banner", target, port))
return;
fd = tcp_connect_host(target, port, 5000);
if (fd < 0) {
mcp_reply_error(c, "cannot connect");
return;
}
mcp_buf_init(&b);
if (port == 80 || port == 8080 || port == 8000) {
char req[256];
snprintf(req, sizeof(req), "HEAD / HTTP/1.0\r\nHost: %s\r\n\r\n", target);
(void)write(fd, req, strlen(req));
}
if (wait < 100)
wait = 100;
if (wait > 10000)
wait = 10000;
{
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLIN;
if (poll(&pfd, 1, wait) <= 0) {
close(fd);
mcp_reply_text(c, "no banner within the wait window");
mcp_buf_free(&b);
return;
}
}
n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) {
mcp_reply_text(c, "connected, but no bytes came back");
mcp_buf_free(&b);
return;
}
buf[n] = '\0';
mcp_buf_printf(&b, "%s:%d banner (%zd bytes):\n", target, port, n);
mcp_buf_add(&b, buf, (size_t)n);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
}
static void t_audit_log(mcp_conn *c, const mcp_json *args, void *user)
{
int limit = mcp_arg_int(args, "limit", 50);
mcp_buf b;
(void)user;
mcp_buf_init(&b);
apex_audit_tail(&b, limit);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_evidence(mcp_conn *c, const mcp_json *args, void *user)
{
const char *label = mcp_arg_string(args, "label");
const char *data = mcp_arg_string(args, "data");
char *path;
mcp_buf b;
(void)user;
if (data == NULL) {
mcp_reply_error(c, "data is required");
return;
}
path = apex_evidence_save(label, data, strlen(data));
if (path == NULL) {
mcp_reply_error(c, "cannot write the evidence file");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"evidence\":");
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"bytes\":%lu}", (unsigned long)strlen(data));
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(path);
}
static void t_finding_add(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *title = mcp_arg_string(args, "title");
const char *severity = mcp_arg_string(args, "severity");
const char *confidence = mcp_arg_string(args, "confidence");
const char *evidence = mcp_arg_string(args, "evidence");
const char *tool = mcp_arg_string(args, "tool");
const char *cwe = mcp_arg_string(args, "cwe");
const char *remediation = mcp_arg_string(args, "remediation");
const char *tags = mcp_arg_string(args, "tags");
char *id;
mcp_buf b;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (title == NULL || *title == '\0') {
mcp_reply_error(c, "title is required");
return;
}
/* a finding about a target is a statement about a target: same gate */
if (!gated(c, "finding_add", target, 0))
return;
id = apex_finding_add(target, title, severity, confidence, tool, evidence,
cwe, remediation, tags);
if (id == NULL) {
mcp_reply_error(c, "cannot write the finding");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"id\":");
apex_json_str(&b, id);
mcp_buf_puts(&b, ",\"target\":");
apex_json_str(&b, target);
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(id);
}
static void t_finding_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;
int total;
(void)user;
mcp_buf_init(&b);
total = apex_finding_list(&b, target, limit);
(void)total;
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_finding_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_finding_read(id, &b) != 0) {
mcp_buf_free(&b);
mcp_reply_error(c, "no such finding");
return;
}
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
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 };
mcp_buf b;
int i;
(void)args;
(void)user;
mcp_buf_init(&b);
mcp_buf_printf(&b, "{\"version\":\"%s\",\"home\":", APEX_VERSION);
apex_json_str(&b, g_cfg.home);
mcp_buf_puts(&b, ",\"serial\":");
apex_json_str(&b, g_cfg.serial);
mcp_buf_printf(&b, ",\"dry_run\":%s,\"programs\":{",
g_cfg.dry_run ? "true" : "false");
for (i = 0; progs[i] != NULL; i++) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "\"");
mcp_buf_puts(&b, progs[i]);
mcp_buf_printf(&b, "\":%s", apex_have(progs[i]) ? "true" : "false");
}
mcp_buf_puts(&b, "},\"scope_loaded\":");
mcp_buf_puts(&b, g_scope.loaded ? "true" : "false");
mcp_buf_puts(&b, "}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_RECON[] = {
{ "scope_show",
"Show the loaded rules of engagement: allowed IP ranges, domains, ports, "
"expiry and whether private addresses and radio transmission are armed. "
"Call this first before any engagement - an empty scope refuses everything.",
"{\"type\":\"object\",\"properties\":{}}",
t_scope },
{ "scope_reload",
"Reload the scope file from disk, optionally from another path. Use it when "
"the engagement rules were edited while the server is running.",
"{\"type\":\"object\",\"properties\":{"
"\"path\":{\"type\":\"string\",\"description\":\"absolute path to a scope JSON; "
"omit to reload the current one\"}}}",
t_scope_reload },
{ "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 "
"detection. Ports outside the scope's allow_port list are skipped silently.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\",\"description\":\"host or IP inside the scope\"},"
"\"ports\":{\"type\":\"string\",\"description\":\"\\\"80\\\", \\\"1-1024\\\"; "
"default 1-1024\"},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"per-port connect timeout, "
"default 2000\"}},"
"\"required\":[\"target\"]}",
t_portscan },
{ "nmap",
"Run nmap against an in-scope target with a fixed profile. Use it when you "
"need service and version detection. Profiles: quick, default "
"(top-100 + -sV), full (-p-), udp, vuln (--script vuln), http. The tool "
"refuses targets outside the scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"profile\":{\"type\":\"string\",\"enum\":[\"quick\",\"default\",\"full\","
"\"udp\",\"vuln\",\"http\"]},"
"\"timeout_ms\":{\"type\":\"integer\",\"description\":\"default 300000\"}},"
"\"required\":[\"target\"]}",
t_nmap },
{ "dns",
"Resolve a name with dig: A, AAAA, MX, TXT, NS, SOA, CNAME, SRV, CAA or PTR. "
"Use it to map the target's DNS surface and to catch a name that points "
"somewhere the scope does not allow.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"type\":{\"type\":\"string\",\"description\":\"record type, default A\"}},"
"\"required\":[\"target\"]}",
t_dns },
{ "tls_cert",
"Fetch and show the X.509 certificate a TLS service presents (issuer, "
"subject, SANs, validity, chain). Use it for certificate hygiene findings "
"and to learn which host names the service believes it owns.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 443\"}},"
"\"required\":[\"target\"]}",
t_tls_cert },
{ "http_head",
"Send a HEAD request and return the raw response. Plain HTTP is done "
"in-process; https is handed to curl. Use it to check which server is "
"answering and what headers it leaks.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 443\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"tls\":{\"type\":\"boolean\",\"description\":\"default: true for port 443\"}},"
"\"required\":[\"target\"]}",
t_http_head },
{ "banner",
"Connect to a port and return whatever the service says first. Use it for "
"a quick service identity (SSH, SMTP, FTP, MySQL) before a full nmap run.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\"},"
"\"wait_ms\":{\"type\":\"integer\",\"description\":\"default 1500\"}},"
"\"required\":[\"target\",\"port\"]}",
t_banner },
{ "finding_add",
"Record a finding with severity, confidence and a pointer to the evidence. "
"Use it the moment something is worth reporting - the audit trail is the "
"product, a finding without evidence is a guess. Example: tool=\\\"nmap\\\", "
"evidence=\\\"evidence/...\\\".",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"title\":{\"type\":\"string\"},"
"\"severity\":{\"type\":\"string\",\"description\":\"info|low|medium|high|critical\"},"
"\"confidence\":{\"type\":\"string\",\"description\":\"certain|firm|tentative\"},"
"\"evidence\":{\"type\":\"string\",\"description\":\"path or command output that proves it\"},"
"\"tool\":{\"type\":\"string\"},"
"\"cwe\":{\"type\":\"string\"},"
"\"remediation\":{\"type\":\"string\"},"
"\"tags\":{\"type\":\"string\"}},"
"\"required\":[\"target\",\"title\"]}",
t_finding_add },
{ "finding_list",
"List recorded findings, optionally only those for one target. Use it to "
"see what is already known before testing again.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"default 100\"}}}",
t_finding_list },
{ "finding_read",
"Read one finding by id (f0001, f0002, ...).",
"{\"type\":\"object\",\"properties\":{"
"\"id\":{\"type\":\"string\"}},"
"\"required\":[\"id\"]}",
t_finding_read },
{ "evidence_save",
"Store raw bytes as evidence and get the path back. Use it for a full HTTP "
"response, a certificate dump or a scan output too long to paste into a "
"finding. Reference the returned path in finding_add.",
"{\"type\":\"object\",\"properties\":{"
"\"label\":{\"type\":\"string\"},"
"\"data\":{\"type\":\"string\"}},"
"\"required\":[\"data\"]}",
t_evidence },
{ "audit_log",
"Show the last gate decisions as JSON lines: what was asked, what was "
"allowed or refused and why. Use it to prove that nothing outside the "
"scope was touched.",
"{\"type\":\"object\",\"properties\":{"
"\"limit\":{\"type\":\"integer\",\"description\":\"default 50\"}}}",
t_audit_log },
{ "capabilities",
"Report which external programs this host has, where the state lives and "
"whether the run is a dry run. Use it once at the start of an engagement.",
"{\"type\":\"object\",\"properties\":{}}",
t_capabilities },
};
const size_t TOOLS_RECON_N = sizeof(TOOLS_RECON) / sizeof(TOOLS_RECON[0]);
+865
View File
@@ -0,0 +1,865 @@
/*
* tools_web.c - HTTP attack surface.
*
* Everything here talks HTTP the way a browser does: a real request, a real
* response, the bytes kept. That is the difference between a finding and a
* guess - the raw response is what gets attached to the evidence file.
*
* Plain HTTP is spoken in-process. TLS is handed to curl when it is installed,
* because this binary deliberately links no TLS stack: a 300 kB static server
* that must run on a field box should not drag in libssl.
*/
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include "apex.h"
#include "tools.h"
/* Read until the peer closes, the buffer fills or the deadline passes. */
static ssize_t read_all(int fd, char *buf, size_t cap, int timeout_ms)
{
size_t used = 0;
struct timeval t0;
long budget = timeout_ms > 0 ? timeout_ms : 1000;
gettimeofday(&t0, NULL);
while (used + 1 < cap) {
struct pollfd pfd;
struct timeval now;
long spent;
ssize_t n;
gettimeofday(&now, NULL);
spent = (now.tv_sec - t0.tv_sec) * 1000L +
(now.tv_usec - t0.tv_usec) / 1000L;
if (spent >= budget)
break;
pfd.fd = fd;
pfd.events = POLLIN;
if (poll(&pfd, 1, (int)(budget - spent)) <= 0)
break;
n = read(fd, buf + used, cap - used - 1);
if (n <= 0)
break;
used += (size_t)n;
}
buf[used] = '\0';
return (ssize_t)used;
}
/*
* One HTTP/1.1 request, one response. Returns 0 on success. The caller owns
* *out. method and path are validated by the caller; headers is a raw block of
* extra request lines ("X-Foo: bar\r\n") or NULL.
*/
static int http_once(const char *host, int port, int tls, const char *method,
const char *path, const char *body, const char *headers,
int timeout_ms, char **out, size_t *out_len,
char *status_line, size_t status_n)
{
int fd;
mcp_buf req;
char *resp;
size_t cap = g_cfg.max_output;
ssize_t n;
const char *first_line;
if (tls) {
/* curl speaks TLS for us; -i keeps the status line in the output */
char *argv[16];
int i = 0;
char url[700];
apex_proc p;
if (!apex_have("curl"))
return -1;
snprintf(url, sizeof(url), "https://%s:%d%s", host, port, path);
argv[i++] = "curl";
argv[i++] = "-sS";
argv[i++] = "-i";
argv[i++] = "--max-time";
argv[i++] = "25";
argv[i++] = "-X";
argv[i++] = (char *)method;
if (body != NULL && *body != '\0') {
argv[i++] = "--data-binary";
argv[i++] = (char *)body;
}
argv[i++] = url;
argv[i] = NULL;
if (apex_run(argv, timeout_ms, cap, &p) != 0)
return -1;
*out = p.out;
*out_len = p.out_len;
p.out = NULL;
apex_proc_free(&p);
if (status_line != NULL && status_n > 0 && *out != NULL) {
size_t k = 0;
while ((*out)[k] != '\0' && (*out)[k] != '\r' && k + 1 < status_n) {
status_line[k] = (*out)[k];
k++;
}
status_line[k] = '\0';
}
return *out != NULL ? 0 : -1;
}
fd = tcp_connect_host(host, port, 8000);
if (fd < 0)
return -1;
mcp_buf_init(&req);
mcp_buf_printf(&req, "%s %s HTTP/1.1\r\nHost: %s\r\n", method, path, host);
mcp_buf_printf(&req, "User-Agent: apex-twin/%s\r\n", APEX_VERSION);
mcp_buf_puts(&req, "Accept: */*\r\nConnection: close\r\n");
if (headers != NULL && *headers != '\0')
mcp_buf_puts(&req, headers);
if (body != NULL) {
mcp_buf_printf(&req, "Content-Length: %lu\r\n", (unsigned long)strlen(body));
mcp_buf_puts(&req, "Content-Type: application/x-www-form-urlencoded\r\n");
}
mcp_buf_puts(&req, "\r\n");
if (body != NULL && *body != '\0')
mcp_buf_puts(&req, body);
if (write(fd, req.p, req.len) != (ssize_t)req.len) {
mcp_buf_free(&req);
close(fd);
return -1;
}
mcp_buf_free(&req);
resp = malloc(cap + 1);
if (resp == NULL) {
close(fd);
return -1;
}
n = read_all(fd, resp, cap + 1, timeout_ms);
close(fd);
if (n <= 0) {
free(resp);
return -1;
}
*out = resp;
*out_len = (size_t)n;
first_line = resp;
if (status_line != NULL && status_n > 0) {
size_t k = 0;
while (first_line[k] != '\0' && first_line[k] != '\r' && k + 1 < status_n) {
status_line[k] = first_line[k];
k++;
}
status_line[k] = '\0';
}
return 0;
}
/* Case-insensitive substring search. strcasestr is GNU, so it is not used. */
static char *find_ci(const char *hay, const char *needle)
{
size_t nl = strlen(needle);
const char *p;
if (nl == 0)
return (char *)hay;
for (p = hay; *p != '\0'; p++) {
size_t i;
for (i = 0; i < nl; i++) {
if (p[i] == '\0')
return NULL;
if (tolower((unsigned char)p[i]) !=
tolower((unsigned char)needle[i]))
break;
}
if (i == nl)
return (char *)p;
}
return NULL;
}
static int status_code(const char *status_line)
{
const char *p = status_line;
while (*p != '\0' && !isdigit((unsigned char)*p))
p++;
return atoi(p);
}
static int looks_tls(int port)
{
return port == 443 || port == 8443 || port == 9443 || port == 4443;
}
/* Cheap sanity check: no CRLF injection into the request line. */
static int safe_token(const char *s, size_t max)
{
size_t i;
if (s == NULL || *s == '\0')
return 0;
for (i = 0; s[i] != '\0'; i++) {
if (i >= max)
return 0;
if ((unsigned char)s[i] < 0x20 || s[i] == 0x7f)
return 0;
}
return 1;
}
/* ------------------------------------------------------------------ tools */
static void t_http_request(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
const char *method = mcp_arg_string(args, "method");
const char *body = mcp_arg_string(args, "body");
const char *headers = mcp_arg_string(args, "headers");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", looks_tls(port));
char *resp = NULL;
size_t len = 0;
char status[256];
char reason[512];
mcp_buf b;
int ok;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (path[0] != '/') {
mcp_reply_error(c, "path must start with /");
return;
}
if (!safe_token(path, 512)) {
mcp_reply_error(c, "path contains control characters");
return;
}
if (method == NULL || *method == '\0')
method = body != NULL ? "POST" : "GET";
{
static const char *ok_methods[] = { "GET", "POST", "PUT", "DELETE",
"PATCH", "OPTIONS", "HEAD", "TRACE" };
size_t k;
for (k = 0; k < sizeof(ok_methods) / sizeof(ok_methods[0]); k++)
if (strcmp(method, ok_methods[k]) == 0)
break;
if (k == sizeof(ok_methods) / sizeof(ok_methods[0])) {
mcp_reply_error(c, "unsupported method");
return;
}
}
if (headers != NULL && strstr(headers, "\r\n\r\n") != NULL) {
mcp_reply_error(c, "headers must not contain a blank line");
return;
}
ok = apex_scope_check(target, port, reason, sizeof(reason));
mcp_buf_init(&b);
mcp_buf_printf(&b, "%s %s://%s:%d%s", method, tls ? "https" : "http",
target, port, path);
apex_audit("http_request", target, port, ok, reason, b.p);
mcp_buf_free(&b);
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
if (g_cfg.dry_run) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "DRY RUN, not executed: %s %s://%s:%d%s", method,
tls ? "https" : "http", target, port, path);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
return;
}
status[0] = '\0';
if (http_once(target, port, tls, method, path, body, headers, 25000, &resp,
&len, status, sizeof(status)) != 0) {
mcp_reply_error(c, "no response (connect or TLS failed)");
return;
}
mcp_buf_init(&b);
mcp_buf_printf(&b, "%s %s://%s:%d%s\n%s\n%lu bytes\n\n", method,
tls ? "https" : "http", target, port, path, status,
(unsigned long)len);
/* long answers go to evidence, the model gets the head of the response */
if (len > 64000) {
char *ev = apex_evidence_save("http-response", resp, len);
mcp_buf_printf(&b, "(truncated to 64 kB; full body: %s)\n",
ev != NULL ? ev : "not saved");
mcp_buf_add(&b, resp, 64000);
free(ev);
} else {
mcp_buf_add(&b, resp, len);
}
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
free(resp);
}
static void t_http_headers(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", looks_tls(port));
static const struct {
const char *name;
const char *why;
const char *severity;
} checks[] = {
{ "strict-transport-security", "no HSTS: TLS downgrade stays possible", "medium" },
{ "content-security-policy", "no CSP: any injection runs unfiltered", "medium" },
{ "x-frame-options", "no X-Frame-Options: clickjacking possible", "low" },
{ "x-content-type-options", "no nosniff: MIME confusion possible", "low" },
{ "referrer-policy", "no Referrer-Policy: URLs leak cross-origin", "info" },
{ "permissions-policy", "no Permissions-Policy", "info" },
};
size_t i;
char *resp = NULL;
size_t len = 0;
char status[256];
char reason[512];
mcp_buf b;
int ok;
int missing = 0;
char *header_end;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (path == NULL || *path == '\0')
path = "/";
ok = apex_scope_check(target, port, reason, sizeof(reason));
apex_audit("http_headers", target, port, ok, reason, "header audit");
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
status[0] = '\0';
if (http_once(target, port, tls, "GET", path, NULL, NULL, 20000, &resp, &len,
status, sizeof(status)) != 0) {
mcp_reply_error(c, "no response");
return;
}
header_end = strstr(resp, "\r\n\r\n");
if (header_end != NULL)
*header_end = '\0';
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"status\":", port);
apex_json_str(&b, status);
mcp_buf_puts(&b, ",\"missing\":[");
for (i = 0; i < sizeof(checks) / sizeof(checks[0]); i++) {
if (find_ci(resp, checks[i].name) == NULL) {
if (missing > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"header\":");
apex_json_str(&b, checks[i].name);
mcp_buf_puts(&b, ",\"why\":");
apex_json_str(&b, checks[i].why);
mcp_buf_puts(&b, ",\"severity\":");
apex_json_str(&b, checks[i].severity);
mcp_buf_puts(&b, "}");
missing++;
}
}
mcp_buf_printf(&b, "],\"missing_count\":%d}", missing);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(resp);
}
static void t_http_paths(mcp_conn *c, const mcp_json *args, void *user)
{
static const char *wordlist[] = {
"admin", "administrator", "login", "wp-admin", "wp-login.php",
"phpmyadmin", "server-status", "server-info", ".git/config",
".git/HEAD", ".env", ".svn/entries", "backup.zip", "backup.sql",
"db.sql", "config.php", "config.json", "robots.txt", "sitemap.xml",
"api", "api/v1", "api/v2", "swagger.json", "openapi.json", "graphql",
"health", "healthz", "metrics", "debug", "console", "actuator",
"actuator/env", "cgi-bin/", "uploads/", "static/", "assets/",
"test", "dev", "staging", "old", "tmp", "backup", "console/",
"jenkins", "gitlab", "grafana", "kibana", "prometheus", "traefik",
"phpinfo.php", "info.php", "shell.php", "upload.php", "index.php~",
"web.config", "crossdomain.xml", "clientaccesspolicy.xml",
".well-known/security.txt", "favicon.ico", NULL
};
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "base");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", looks_tls(port));
int max = mcp_arg_int(args, "limit", 40);
char reason[512];
mcp_buf b;
int i;
int hits = 0;
int tested = 0;
int ok;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
ok = apex_scope_check(target, port, reason, sizeof(reason));
apex_audit("http_paths", target, port, ok, reason, "path discovery");
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
if (max <= 0 || max > 200)
max = 40;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"hits\":[", port);
for (i = 0; wordlist[i] != NULL && tested < max; i++) {
char req_path[600];
char *resp = NULL;
size_t len = 0;
char status[256];
int code;
if (path != NULL && *path != '\0' && strcmp(path, "/") != 0)
snprintf(req_path, sizeof(req_path), "%s/%s", path, wordlist[i]);
else
snprintf(req_path, sizeof(req_path), "/%s", wordlist[i]);
tested++;
status[0] = '\0';
if (http_once(target, port, tls, "GET", req_path, NULL, NULL, 8000,
&resp, &len, status, sizeof(status)) != 0)
continue;
code = status_code(status);
if (code == 200 || code == 201 || code == 301 || code == 302 ||
code == 401 || code == 403) {
if (hits > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, req_path);
mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu}", code,
(unsigned long)len);
hits++;
}
free(resp);
}
mcp_buf_printf(&b, "],\"tested\":%d,\"hits_count\":%d}", tested, hits);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/*
* An injection probe that does not pretend to be sqlmap: it sends one payload
* with a quote and one boolean pair, and reports whether the answers differ.
* A difference is a lead, not a finding - the model decides what to keep.
*/
static void t_sqli_probe(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
const char *param = mcp_arg_string(args, "param");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", looks_tls(port));
int method = mcp_arg_bool(args, "post", 0);
const char *payloads[] = { "'", "\"", "')", "' OR '1'='1", "' AND '1'='2" };
size_t i;
char reason[512];
mcp_buf b;
int ok;
long base_len = -1;
int base_code = 0;
(void)user;
if (target == NULL || *target == '\0' || param == NULL || *param == '\0') {
mcp_reply_error(c, "target and param are required");
return;
}
if (!safe_token(param, 64)) {
mcp_reply_error(c, "param must be a plain parameter name");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (path[0] != '/') {
mcp_reply_error(c, "path must start with /");
return;
}
ok = apex_scope_check(target, port, reason, sizeof(reason));
mcp_buf_init(&b);
mcp_buf_printf(&b, "%s probe %s param=%s", method ? "POST" : "GET", path, param);
apex_audit("sqli_probe", target, port, ok, reason, b.p);
mcp_buf_free(&b);
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_puts(&b, ",\"param\":");
apex_json_str(&b, param);
mcp_buf_puts(&b, ",\"probes\":[");
for (i = 0; i < sizeof(payloads) / sizeof(payloads[0]); i++) {
char url[1024];
char body[1024];
char *resp = NULL;
size_t len = 0;
char status[256];
int code;
const char *how;
int abnormal = 0;
if (method) {
char encoded[512];
size_t k;
size_t w = 0;
for (k = 0; payloads[i][k] != '\0' && w + 4 < sizeof(encoded); k++) {
unsigned char ch = (unsigned char)payloads[i][k];
if (isalnum(ch) || ch == '-' || ch == '_' || ch == '.')
encoded[w++] = (char)ch;
else
w += (size_t)snprintf(encoded + w, sizeof(encoded) - w,
"%%%02X", ch);
}
encoded[w] = '\0';
snprintf(body, sizeof(body), "%s=%s&submit=1", param, encoded);
snprintf(url, sizeof(url), "%s", path);
} else {
char encoded[512];
size_t k;
size_t w = 0;
for (k = 0; payloads[i][k] != '\0' && w + 4 < sizeof(encoded); k++) {
unsigned char ch = (unsigned char)payloads[i][k];
if (isalnum(ch) || ch == '-' || ch == '_' || ch == '.')
encoded[w++] = (char)ch;
else
w += (size_t)snprintf(encoded + w, sizeof(encoded) - w,
"%%%02X", ch);
}
encoded[w] = '\0';
snprintf(url, sizeof(url), "%s%s%s=%s", path,
strchr(path, '?') != NULL ? "&" : "?", param, encoded);
body[0] = '\0';
}
how = method ? "POST" : "GET";
status[0] = '\0';
if (http_once(target, port, tls, how, url,
method ? body : NULL, NULL, 15000, &resp, &len, status,
sizeof(status)) != 0) {
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"payload\":");
apex_json_str(&b, payloads[i]);
mcp_buf_puts(&b, ",\"result\":\"no response\"}");
continue;
}
code = status_code(status);
if (i == 0) {
base_len = (long)len;
base_code = code;
} else if ((long)len != base_len || code != base_code) {
abnormal = 1;
}
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"payload\":");
apex_json_str(&b, payloads[i]);
mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu,\"differs\":%s}", code,
(unsigned long)len, abnormal ? "true" : "false");
free(resp);
}
mcp_buf_puts(&b, "],\"note\":\"a differing answer is a lead, not proof; "
"confirm by hand before writing a finding\"}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
static void t_xss_probe(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *path = mcp_arg_string(args, "path");
const char *param = mcp_arg_string(args, "param");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", looks_tls(port));
const char *marker = "apex7x1";
char payload[256];
char url[1024];
char *resp = NULL;
size_t len = 0;
char status[256];
char reason[512];
mcp_buf b;
int ok;
int reflected;
(void)user;
if (target == NULL || *target == '\0' || param == NULL || *param == '\0') {
mcp_reply_error(c, "target and param are required");
return;
}
if (!safe_token(param, 64)) {
mcp_reply_error(c, "param must be a plain parameter name");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (path[0] != '/') {
mcp_reply_error(c, "path must start with /");
return;
}
snprintf(payload, sizeof(payload), "%s<script>alert(1)</script>", marker);
ok = apex_scope_check(target, port, reason, sizeof(reason));
apex_audit("xss_probe", target, port, ok, reason, "reflection probe");
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
{
char encoded[512];
size_t k;
size_t w = 0;
for (k = 0; payload[k] != '\0' && w + 4 < sizeof(encoded); k++) {
unsigned char ch = (unsigned char)payload[k];
if (isalnum(ch) || ch == '-' || ch == '_' || ch == '.')
encoded[w++] = (char)ch;
else
w += (size_t)snprintf(encoded + w, sizeof(encoded) - w, "%%%02X",
ch);
}
encoded[w] = '\0';
snprintf(url, sizeof(url), "%s%s%s=%s", path,
strchr(path, '?') != NULL ? "&" : "?", param, encoded);
}
status[0] = '\0';
if (http_once(target, port, tls, "GET", url, NULL, NULL, 15000, &resp, &len,
status, sizeof(status)) != 0) {
mcp_reply_error(c, "no response");
return;
}
reflected = strstr(resp, marker) != NULL;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_puts(&b, ",\"param\":");
apex_json_str(&b, param);
mcp_buf_puts(&b, ",\"payload\":");
apex_json_str(&b, payload);
mcp_buf_printf(&b, ",\"status\":%d,\"reflected\":%s", status_code(status),
reflected ? "true" : "false");
if (reflected) {
char *pos = strstr(resp, marker);
char window[512];
size_t k = 0;
while (pos[k] != '\0' && k + 1 < sizeof(window) && k < 400) {
unsigned char ch = (unsigned char)pos[k];
window[k] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : '.';
k++;
}
window[k] = '\0';
mcp_buf_puts(&b, ",\"context\":");
apex_json_str(&b, window);
}
mcp_buf_puts(&b, ",\"note\":\"reflection is a lead; it is only a finding "
"if the context shows the angle brackets survive unencoded\"}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
free(resp);
}
static void t_curl(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
const char *url_path = mcp_arg_string(args, "url");
int port = mcp_arg_int(args, "port", 0);
char reason[512];
char raw[1024];
int ok;
apex_proc p;
mcp_buf b;
int rc;
(void)user;
if (target == NULL || *target == '\0') {
mcp_reply_error(c, "target is required");
return;
}
if (url_path == NULL || strncmp(url_path, "/", 1) != 0) {
/* curl gets a path, never a full URL: the host must stay gated */
mcp_reply_error(c, "url must be a path beginning with /");
return;
}
ok = apex_scope_check(target, port, reason, sizeof(reason));
snprintf(raw, sizeof(raw), "curl path=%s", url_path);
apex_audit("curl", target, port, ok, reason, raw);
if (!ok) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "REFUSED by scope gate: %s", reason);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
if (!apex_have("curl")) {
mcp_reply_error(c, "curl is not installed on this host");
return;
}
{
char url[1200];
char *argv[20];
int i = 0;
if (port > 0)
snprintf(url, sizeof(url), "http://%s:%d%s", target, port, url_path);
else
snprintf(url, sizeof(url), "http://%s%s", target, url_path);
argv[i++] = "curl";
argv[i++] = "-sS";
argv[i++] = "-i";
argv[i++] = "--max-time";
argv[i++] = "20";
argv[i++] = url;
argv[i] = NULL;
rc = apex_run(argv, 25000, g_cfg.max_output, &p);
if (rc != 0) {
mcp_reply_error(c, "curl failed to start");
return;
}
mcp_buf_init(&b);
mcp_buf_printf(&b, "$ %s\nexit=%d\n", url, p.exit_code);
if (p.out != NULL)
mcp_buf_add(&b, p.out, p.out_len);
mcp_reply_text(c, b.p);
mcp_buf_free(&b);
apex_proc_free(&p);
}
}
const mcp_tool TOOLS_WEB[] = {
{ "http_request",
"Send one HTTP request and return status line plus the whole response. Use "
"it for anything that needs a real method, body or header: login forms, "
"API endpoints, method checks. The response is kept verbatim.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80, 443 for tls\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"method\":{\"type\":\"string\"},"
"\"body\":{\"type\":\"string\"},"
"\"headers\":{\"type\":\"string\",\"description\":\"raw lines, CRLF separated\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\",\"path\"]}",
t_http_request },
{ "http_headers",
"Audit the security response headers (HSTS, CSP, frame, nosniff, referrer, "
"permissions) and list what is missing with the reason it matters. Use it "
"for a first pass over any web target - it is cheap and it yields findings.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\"},"
"\"path\":{\"type\":\"string\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_http_headers },
{ "http_paths",
"Probe a built-in wordlist of common paths and endpoints (.git, .env, "
"admin, actuator, swagger, backups) and report which answer with 200, 30x, "
"401 or 403. Use it right after the header audit of a web target.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\"},"
"\"base\":{\"type\":\"string\",\"description\":\"path prefix, default /\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"default 40\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_http_paths },
{ "sqli_probe",
"Send a fixed set of quote and boolean payloads to one parameter and report "
"whether the answers differ in status or length. Use it to locate a "
"candidate, then confirm by hand - this is a lead generator, not an "
"exploit. It never returns data from the database.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"path\":{\"type\":\"string\"},"
"\"param\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\"},"
"\"post\":{\"type\":\"boolean\",\"description\":\"send as a form POST\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\",\"path\",\"param\"]}",
t_sqli_probe },
{ "xss_probe",
"Send a marked script payload to one parameter and report whether it comes "
"back in the response, with the surrounding context. Use it to find "
"reflecting parameters; the context tells you whether it is exploitable.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"path\":{\"type\":\"string\"},"
"\"param\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\",\"path\",\"param\"]}",
t_xss_probe },
{ "curl",
"Run curl against a path on an in-scope host. Use it when a tool needs the "
"exact bytes curl produces (redirects, auth challenges, odd encodings) or "
"when only curl can reach the service. The URL is built from the gated "
"target; you cannot hand curl a foreign host.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"url\":{\"type\":\"string\",\"description\":\"path beginning with /\"},"
"\"port\":{\"type\":\"integer\"}},"
"\"required\":[\"target\",\"url\"]}",
t_curl },
};
const size_t TOOLS_WEB_N = sizeof(TOOLS_WEB) / sizeof(TOOLS_WEB[0]);
+31
View File
@@ -0,0 +1,31 @@
[Unit]
Description=APEX TWIN offensive-security MCP server
Documentation=file:/usr/local/share/doc/apex-twin/README.md
After=network-online.target
[Service]
Type=simple
User=lotherk
# /dev/ttyACM0 is root:dialout - without this group the radio tools fail with
# EACCES while everything else looks healthy.
SupplementaryGroups=dialout
Environment=APEX_HOME=/home/lotherk/stack/data/apex-twin
Environment=APEX_SERIAL=/dev/ttyACM0
EnvironmentFile=-/home/lotherk/.config/apex-twin/env
ExecStart=/usr/local/bin/apex-twin --http 127.0.0.1:8797
Restart=on-failure
RestartSec=3
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=read-only
PrivateTmp=yes
ReadWritePaths=/home/lotherk/stack/data/apex-twin
# DeviceAllow only takes effect with a closed DevicePolicy, and a scanner needs
# no device node except the tty, which the dialout group already grants.
# no capability is needed: every tool is a connect() or a child process. The one
# exception is nmap -sS, which wants CAP_NET_RAW and is therefore unavailable
# here - that is intended, connect scans need no privilege.
CapabilityBoundingSet=~CAP_SYS_ADMIN CAP_SYS_PTRACE CAP_NET_ADMIN
[Install]
WantedBy=default.target
Executable
+306
View File
@@ -0,0 +1,306 @@
#!/usr/bin/env python3
"""APEX TWIN end-to-end: gate, tools, store, transport.
No mocks. A temp state directory, the real binary, real DNS for the one name
that is in scope, and assertions on the files the server actually wrote. The
point of the suite is the gate: everything else is a tool, the gate is the
product.
"""
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BIN = os.path.join(HERE, "apex-twin")
ROOT = tempfile.mkdtemp(prefix="apex-twin-test-")
fails = []
passes = 0
def check(name, cond, detail=""):
global passes
if cond:
passes += 1
print("PASS " + name)
else:
print("FAIL " + name + (" " + str(detail) if detail else ""))
fails.append(name)
def run(msgs, home=None, extra_env=None):
env = dict(os.environ)
env["APEX_HOME"] = home or ROOT
if extra_env:
env.update(extra_env)
proc = subprocess.run([BIN], input="\n".join(json.dumps(m) for m in msgs) + "\n",
capture_output=True, text=True, env=env, timeout=180)
out = []
for line in proc.stdout.splitlines():
if line.strip():
out.append(json.loads(line))
return out, proc
def call(i, _tool, **args):
return {"jsonrpc": "2.0", "id": i, "method": "tools/call",
"params": {"name": _tool, "arguments": args}}
def text(r):
try:
return r["result"]["content"][0]["text"]
except Exception:
return ""
def err(r):
try:
return bool(r["result"].get("isError"))
except Exception:
return False
def write_scope(home, obj):
os.makedirs(home, exist_ok=True)
with open(os.path.join(home, "scope.json"), "w") as f:
json.dump(obj, f)
SCOPE = {
"label": "suite",
"expires": "2099-12-31T23:59:59Z",
"allow_private": False,
"allow_ip": ["192.0.2.0/24", "198.51.100.7"],
"deny_ip": ["192.0.2.66"],
"allow_domain": ["example.com"],
"allow_port": ["80", "8080"],
}
print("== binary ==")
check("binary exists", os.path.isfile(BIN), BIN)
# ---------------------------------------------------------------- no scope
print("\n== no scope: everything refused ==")
empty = tempfile.mkdtemp(prefix="apex-noscope-")
res, _ = run([
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
call(2, "portscan", target="example.com", ports="80"),
call(3, "nmap", target="example.com"),
call(4, "http_request", target="example.com", path="/"),
call(5, "scope_show"),
], 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))
names = {t["name"] for t in tools}
for need in ("portscan", "nmap", "http_request", "marauder_scan",
"method_playbook", "finding_add"):
check("tool present: " + need, need in names)
for r in res:
if r.get("id") in (2, 3, 4):
check("refused without scope (id %s)" % r["id"], err(r), text(r))
# the *reason* is the contract: a refusal that falls through to another
# deny branch (empty allow_ip) looks identical from isError alone
check("refusal names the missing scope (id %s)" % r["id"],
"no scope loaded" in text(r), text(r))
check("scope_show reports loaded=false",
'"loaded":false' in text([r for r in res if r.get("id") == 5][0]))
shutil.rmtree(empty, ignore_errors=True)
# --------------------------------------------------------------- with scope
print("\n== with scope ==")
write_scope(ROOT, SCOPE)
res, _ = run([
call(1, "scope_show"),
call(2, "portscan", target="198.51.100.5", ports="80"), # outside
call(3, "portscan", target="192.0.2.66", ports="80"), # denied ip
call(4, "nmap", target="203.0.113.9"), # outside
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
])
by_id = {r.get("id"): r for r in res}
check("scope loaded", '"loaded":true' in text(by_id[1]), text(by_id[1]))
check("out-of-scope ip refused", err(by_id[2]), text(by_id[2]))
check("refusal says outside allow_ip", "outside allow_ip" in text(by_id[2]),
text(by_id[2]))
check("denied ip refused over allow range", err(by_id[3]), text(by_id[3]))
check("deny reason names deny_ip", "deny_ip" in text(by_id[3]), text(by_id[3]))
check("out-of-scope nmap refused", err(by_id[4]), text(by_id[4]))
check("refusal says outside allow_ip (nmap)", "outside allow_ip" in text(by_id[4]),
text(by_id[4]))
check("transmitting radio command refused without serial_tx", err(by_id[5]),
text(by_id[5]))
check("refusal names serial_tx", "serial_tx" in text(by_id[5]), text(by_id[5]))
check("non-allowlisted radio command refused", err(by_id[6]), text(by_id[6]))
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]))
print("\n== scope expiry ==")
expired_home = tempfile.mkdtemp(prefix="apex-expired-")
write_scope(expired_home, dict(SCOPE, expires="2000-01-01T00:00:00Z"))
res, _ = run([call(1, "portscan", target="example.com", ports="80")],
home=expired_home)
check("expired scope refuses", err(res[0]), text(res[0]))
check("refusal says expired", "expired" in text(res[0]), text(res[0]))
shutil.rmtree(expired_home, ignore_errors=True)
print("\n== allow_private off ==")
priv_home = tempfile.mkdtemp(prefix="apex-priv-")
write_scope(priv_home, {"label": "priv", "allow_private": False,
"allow_domain": ["localhost"], "allow_port": ["80"]})
res, _ = run([call(1, "portscan", target="localhost", ports="80")],
home=priv_home)
check("private address refused when allow_private is false", err(res[0]),
text(res[0]))
check("refusal names allow_private", "allow_private" in text(res[0]), text(res[0]))
write_scope(priv_home, {"label": "priv", "allow_private": True,
"allow_domain": ["localhost"], "allow_port": ["80"]})
res, _ = run([call(1, "portscan", target="localhost", ports="80",
timeout_ms=500)], home=priv_home)
check("private address allowed when allow_private is true", not err(res[0]),
text(res[0]))
shutil.rmtree(priv_home, ignore_errors=True)
# ------------------------------------------------------------------- tools
print("\n== recon that really runs ==")
res, _ = run([
call(1, "capabilities"),
call(2, "portscan", target="example.com", ports="80", timeout_ms=4000),
call(3, "http_headers", target="example.com", port=80, path="/"),
call(4, "audit_log", limit=5),
])
by_id = {r.get("id"): r for r in res}
caps = json.loads(text(by_id[1]))
check("capabilities names the state dir", caps["home"] == ROOT, caps["home"])
check("capabilities reports scope_loaded", caps["scope_loaded"] is True)
check("capabilities probes programs", isinstance(caps["programs"], dict),
caps.get("programs"))
scan = json.loads(text(by_id[2]))
check("portscan reached example.com:80", 80 in scan["open"], text(by_id[2]))
check("portscan only probed allowed ports", scan["checked"] <= 2, scan)
hdrs = json.loads(text(by_id[3]))
check("http_headers got a status line", hdrs["status"].startswith("HTTP/1.1"),
hdrs.get("status"))
check("http_headers found missing headers", hdrs["missing_count"] > 0, hdrs)
audit = json.loads(text(by_id[4]))
check("audit_log returns entries", len(audit) > 0, audit)
check("audit entries carry a decision",
all("decision" in a for a in audit), audit[:1])
# ------------------------------------------------------------------- store
print("\n== findings and evidence ==")
res, _ = run([
call(1, "evidence_save", label="suite", data="HTTP/1.1 200 OK\nServer: x"),
call(2, "finding_add", target="example.com", title="Missing CSP",
severity="medium", confidence="certain", tool="http_headers",
evidence="see evidence", cwe="CWE-693", remediation="add CSP"),
call(3, "finding_list"),
call(4, "finding_read", id="f0001"),
call(5, "finding_add", target="198.51.100.5", title="out of scope"),
])
by_id = {r.get("id"): r for r in res}
ev = json.loads(text(by_id[1]))
check("evidence file written", os.path.isfile(ev["evidence"]), ev)
check("evidence bytes recorded", ev["bytes"] == len("HTTP/1.1 200 OK\nServer: x"), ev)
fid = json.loads(text(by_id[2]))["id"]
check("finding got an id", fid.startswith("f"), fid)
listed = json.loads(text(by_id[3]))
check("finding appears in the list", any(f["id"] == fid for f in listed), listed)
read = json.loads(text(by_id[4]))
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]))
# --------------------------------------------------------------- transport
print("\n== http transport ==")
def free_port():
"""Never assume a port: 18797 on this host is an SSH forward to koder and
answered a foreign serverInfo while the suite was green."""
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
port = free_port()
env = dict(os.environ)
env["APEX_HOME"] = ROOT
srv = subprocess.Popen([BIN, "--http", str(port)], env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
deadline = time.time() + 10
up = False
while time.time() < deadline:
probe = socket.socket()
try:
probe.connect(("127.0.0.1", port))
up = True
probe.close()
break
except OSError:
probe.close()
time.sleep(0.1)
check("http listener came up on a free port", up, port)
try:
def post(obj):
data = json.dumps(obj).encode()
req = urllib.request.Request("http://127.0.0.1:%d/mcp" % port, data=data,
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=20) as r:
return json.loads(r.read().decode())
init = post({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
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)
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
nested = post({"jsonrpc": "2.0", "method": "tools/call",
"params": {"name": "finding_read", "arguments": {"id": "f0001"}},
"id": "string-id"})
check("http echoes a string id", nested.get("id") == "string-id", nested)
try:
urllib.request.urlopen("http://127.0.0.1:%d/nope" % port, data=b"{}",
timeout=5)
check("wrong path rejected", False, "200 for /nope")
except urllib.error.HTTPError as e:
check("wrong path rejected", e.code == 404, e.code)
finally:
srv.terminate()
try:
srv.wait(timeout=5)
except subprocess.TimeoutExpired:
srv.kill()
# ------------------------------------------------------------- serial guard
print("\n== serial guard ==")
fake = os.path.join(ROOT, "notamodem")
with open(fake, "w") as f:
f.write("")
res, _ = run([call(1, "marauder_info")], extra_env={"APEX_SERIAL": fake})
check("a non-tty serial port fails loudly", err(res[0]), text(res[0]))
print("\n== summary ==")
print("%d passed, %d failed" % (passes, len(fails)))
if fails:
print("failed: " + ", ".join(fails))
shutil.rmtree(ROOT, ignore_errors=True)
sys.exit(1)
shutil.rmtree(ROOT, ignore_errors=True)
sys.exit(0)
Executable
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec python3 "$(dirname "$0")/run.py"
+898
View File
@@ -0,0 +1,898 @@
/*
* libmcp - a minimal Model Context Protocol server in C99 + POSIX.
*
* Single file on purpose: copy mcp.h into a project, add one .c that does
*
* #define MCP_IMPLEMENTATION
* #include "mcp.h"
*
* and the whole server is there. No dependencies beyond libc.
*
* What it implements: newline-delimited JSON-RPC 2.0 on stdin/stdout,
* `initialize`, `tools/list`, `tools/call`, `ping`, and the rule that a
* message without an `id` is a notification and gets no answer.
*
* You supply a table of tools; each tool gets its arguments as a read-only
* JSON view and calls exactly one reply function.
*
* static void tool_echo(mcp_conn *c, const mcp_json *args, void *user)
* {
* const char *s = mcp_arg_string(args, "text");
* mcp_reply_text(c, s ? s : "");
* }
*
* static const mcp_tool tools[] = {
* { "echo", "Echo text back.", MCP_SCHEMA_ECHO, tool_echo },
* };
*
* int main(void)
* {
* mcp_server srv = { "echo-server", "1.0.0", tools, 1, NULL };
* return mcp_serve_stdio(&srv);
* }
*
* A tool that does not reply gets an error reply from the library, so a
* forgotten branch cannot make a client hang.
*/
#ifndef MCP_H
#define MCP_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ---------------------------------------------------------------- json view */
enum mcp_jtype { MCP_NULL, MCP_BOOL, MCP_NUM, MCP_STR, MCP_ARR, MCP_OBJ };
typedef struct mcp_json mcp_json;
struct mcp_json {
enum mcp_jtype t;
int b;
double n;
char *s;
mcp_json **items;
char **keys;
size_t count;
};
/* ---------------------------------------------------------------- server */
typedef struct mcp_conn mcp_conn;
typedef void (*mcp_handler)(mcp_conn *c, const mcp_json *args, void *user);
typedef struct {
const char *name;
const char *description;
const char *schema; /* JSON object text for inputSchema */
mcp_handler handler;
} mcp_tool;
typedef struct {
const char *name;
const char *version;
const mcp_tool *tools;
size_t ntools;
void *user;
} mcp_server;
/* Serve on stdin/stdout until EOF. Returns 0. */
int mcp_serve_stdio(mcp_server *srv);
/* ---------------------------------------------------------------- replies */
/* Reply with a single text content block (the usual tool answer). */
void mcp_reply_text(mcp_conn *c, const char *text);
/* Reply with text that happens to be JSON (pretty for the model, still text). */
void mcp_reply_json(mcp_conn *c, const char *json);
/* Reply with a raw result object, exactly as given. */
void mcp_reply_raw(mcp_conn *c, const char *json);
/* Reply with a tool error: {"content":[...],"isError":true}. */
void mcp_reply_error(mcp_conn *c, const char *message);
/* JSON-RPC level error (bad params, unknown method). */
void mcp_reply_rpc_error(mcp_conn *c, int code, const char *message);
/* ---------------------------------------------------------------- arguments */
const mcp_json *mcp_arg(const mcp_json *args, const char *key);
const char *mcp_arg_string(const mcp_json *args, const char *key);
int mcp_arg_int(const mcp_json *args, const char *key, int dflt);
double mcp_arg_num(const mcp_json *args, const char *key, double dflt);
int mcp_arg_bool(const mcp_json *args, const char *key, int dflt);
const char *mcp_json_string(const mcp_json *v);
size_t mcp_array_len(const mcp_json *v);
const mcp_json *mcp_array_at(const mcp_json *v, size_t i);
/* Growable string. Use it to build a reply, then mcp_reply_text/json it. */
typedef struct {
char *p;
size_t len;
size_t cap;
} mcp_buf;
void mcp_buf_init(mcp_buf *b);
void mcp_buf_add(mcp_buf *b, const char *s, size_t n);
void mcp_buf_puts(mcp_buf *b, const char *s);
void mcp_buf_printf(mcp_buf *b, const char *fmt, ...);
void mcp_buf_free(mcp_buf *b);
/* Escape a string into a JSON string body (no surrounding quotes). */
void mcp_json_escape(mcp_buf *b, const char *s);
/* Parse a complete JSON document. Returns NULL on error. Free with
* mcp_json_free(). A backend that stores its own state as JSON needs this. */
mcp_json *mcp_parse(const char *text);
void mcp_json_free(mcp_json *v);
/* Handle one JSON-RPC line and return the reply as a malloc'd string, or NULL
* when the message was a notification. Free with free(). This is what a HTTP
* transport needs: same envelope, no stdin/stdout. */
char *mcp_handle(mcp_server *srv, const char *line);
#ifdef __cplusplus
}
#endif
#endif /* MCP_H */
/* ===========================================================================
* implementation
* =========================================================================== */
#ifdef MCP_IMPLEMENTATION
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MCP_MAX_TOOLS
#define MCP_MAX_TOOLS 128
#endif
struct mcp_conn {
FILE *out;
mcp_buf outbuf; /* when to_buf, replies accumulate here */
int to_buf;
char *id_json; /* the request id, already serialized */
int replied;
};
/* ------------------------------------------------------------------ buffer */
void mcp_buf_init(mcp_buf *b)
{
b->p = NULL;
b->len = 0;
b->cap = 0;
}
void mcp_buf_add(mcp_buf *b, const char *s, size_t n)
{
if (b->len + n + 1 > b->cap) {
size_t want = b->cap ? b->cap : 256;
while (want < b->len + n + 1)
want *= 2;
b->p = realloc(b->p, want);
if (b->p == NULL) {
fprintf(stderr, "libmcp: out of memory\n");
exit(1);
}
b->cap = want;
}
memcpy(b->p + b->len, s, n);
b->len += n;
b->p[b->len] = '\0';
}
void mcp_buf_puts(mcp_buf *b, const char *s)
{
mcp_buf_add(b, s, strlen(s));
}
void mcp_buf_printf(mcp_buf *b, const char *fmt, ...)
{
char tmp[512];
va_list ap;
int n;
va_start(ap, fmt);
n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
va_end(ap);
if (n < 0)
return;
if ((size_t)n < sizeof(tmp)) {
mcp_buf_add(b, tmp, (size_t)n);
return;
}
{
char *big = malloc((size_t)n + 1);
if (big == NULL)
return;
va_start(ap, fmt);
vsnprintf(big, (size_t)n + 1, fmt, ap);
va_end(ap);
mcp_buf_add(b, big, (size_t)n);
free(big);
}
}
void mcp_buf_free(mcp_buf *b)
{
free(b->p);
mcp_buf_init(b);
}
void mcp_json_escape(mcp_buf *b, const char *s)
{
if (s == NULL)
return;
for (; *s; s++) {
unsigned char c = (unsigned char)*s;
switch (c) {
case '"': mcp_buf_puts(b, "\\\""); break;
case '\\': mcp_buf_puts(b, "\\\\"); break;
case '\n': mcp_buf_puts(b, "\\n"); break;
case '\r': mcp_buf_puts(b, "\\r"); break;
case '\t': mcp_buf_puts(b, "\\t"); break;
default:
if (c < 0x20) {
char tmp[8];
snprintf(tmp, sizeof(tmp), "\\u%04x", c);
mcp_buf_puts(b, tmp);
} else {
mcp_buf_add(b, (const char *)&c, 1);
}
}
}
}
/* ------------------------------------------------------------------ parser */
static mcp_json *jnew(enum mcp_jtype t)
{
mcp_json *v = calloc(1, sizeof(*v));
if (v == NULL) {
fprintf(stderr, "libmcp: out of memory\n");
exit(1);
}
v->t = t;
return v;
}
static void jfree(mcp_json *v)
{
size_t i;
if (v == NULL)
return;
if (v->t == MCP_STR)
free(v->s);
for (i = 0; i < v->count; i++) {
if (v->keys != NULL)
free(v->keys[i]);
jfree(v->items[i]);
}
free(v->items);
free(v->keys);
free(v);
}
static const char *skip_ws(const char *p)
{
while (*p && isspace((unsigned char)*p))
p++;
return p;
}
static const char *jparse(const char *p, mcp_json **out);
static char *parse_string(const char **pp)
{
const char *p = *pp;
mcp_buf b;
if (*p != '"')
return NULL;
p++;
mcp_buf_init(&b);
while (*p && *p != '"') {
if (*p == '\\') {
p++;
switch (*p) {
case '"': mcp_buf_add(&b, "\"", 1); break;
case '\\': mcp_buf_add(&b, "\\", 1); break;
case '/': mcp_buf_add(&b, "/", 1); break;
case 'b': mcp_buf_add(&b, "\b", 1); break;
case 'f': mcp_buf_add(&b, "\f", 1); break;
case 'n': mcp_buf_add(&b, "\n", 1); break;
case 'r': mcp_buf_add(&b, "\r", 1); break;
case 't': mcp_buf_add(&b, "\t", 1); break;
case 'u':
if (p[1] && p[2] && p[3] && p[4]) {
char hex[5];
unsigned long cp;
char utf8[4];
size_t len = 0;
memcpy(hex, p + 1, 4);
hex[4] = '\0';
cp = strtoul(hex, NULL, 16);
if (cp < 0x80) {
utf8[len++] = (char)cp;
} else if (cp < 0x800) {
utf8[len++] = (char)(0xc0 | (cp >> 6));
utf8[len++] = (char)(0x80 | (cp & 0x3f));
} else {
utf8[len++] = (char)(0xe0 | (cp >> 12));
utf8[len++] = (char)(0x80 | ((cp >> 6) & 0x3f));
utf8[len++] = (char)(0x80 | (cp & 0x3f));
}
mcp_buf_add(&b, utf8, len);
p += 4;
}
break;
default: mcp_buf_add(&b, p, 1); break;
}
p++;
continue;
}
mcp_buf_add(&b, p, 1);
p++;
}
if (*p == '"')
p++;
*pp = p;
if (b.p == NULL)
mcp_buf_add(&b, "", 0);
return b.p;
}
static const char *jparse_array(const char *p, mcp_json **out)
{
mcp_json *v = jnew(MCP_ARR);
p = skip_ws(p + 1);
if (*p == ']') {
*out = v;
return p + 1;
}
for (;;) {
mcp_json *item = NULL;
p = jparse(p, &item);
if (p == NULL) {
jfree(v);
return NULL;
}
v->items = realloc(v->items, (v->count + 1) * sizeof(*v->items));
if (v->items == NULL) {
jfree(v);
return NULL;
}
v->items[v->count++] = item;
p = skip_ws(p);
if (*p == ',') {
p = skip_ws(p + 1);
continue;
}
if (*p == ']') {
*out = v;
return p + 1;
}
jfree(v);
return NULL;
}
}
static const char *jparse_object(const char *p, mcp_json **out)
{
mcp_json *v = jnew(MCP_OBJ);
p = skip_ws(p + 1);
if (*p == '}') {
*out = v;
return p + 1;
}
for (;;) {
char *key = NULL;
mcp_json *val = NULL;
p = skip_ws(p);
key = parse_string(&p);
if (key == NULL) {
jfree(v);
return NULL;
}
p = skip_ws(p);
if (*p != ':') {
free(key);
jfree(v);
return NULL;
}
p = jparse(skip_ws(p + 1), &val);
if (p == NULL) {
free(key);
jfree(v);
return NULL;
}
v->items = realloc(v->items, (v->count + 1) * sizeof(*v->items));
v->keys = realloc(v->keys, (v->count + 1) * sizeof(*v->keys));
if (v->items == NULL || v->keys == NULL) {
free(key);
jfree(val);
jfree(v);
return NULL;
}
v->keys[v->count] = key;
v->items[v->count] = val;
v->count++;
p = skip_ws(p);
if (*p == ',') {
p++;
continue;
}
if (*p == '}') {
*out = v;
return p + 1;
}
jfree(v);
return NULL;
}
}
static const char *jparse(const char *p, mcp_json **out)
{
p = skip_ws(p);
switch (*p) {
case '{':
return jparse_object(p, out);
case '[':
return jparse_array(p, out);
case '"': {
mcp_json *v = jnew(MCP_STR);
v->s = parse_string(&p);
if (v->s == NULL) {
jfree(v);
return NULL;
}
*out = v;
return p;
}
case 't':
if (strncmp(p, "true", 4) == 0) {
mcp_json *v = jnew(MCP_BOOL);
v->b = 1;
*out = v;
return p + 4;
}
return NULL;
case 'f':
if (strncmp(p, "false", 5) == 0) {
mcp_json *v = jnew(MCP_BOOL);
v->b = 0;
*out = v;
return p + 5;
}
return NULL;
case 'n':
if (strncmp(p, "null", 4) == 0) {
*out = jnew(MCP_NULL);
return p + 4;
}
return NULL;
default: {
char *end = NULL;
double d = strtod(p, &end);
mcp_json *v;
if (end == p)
return NULL;
v = jnew(MCP_NUM);
v->n = d;
*out = v;
return end;
}
}
}
/* ------------------------------------------------------------------ reading */
const mcp_json *mcp_arg(const mcp_json *args, const char *key)
{
size_t i;
if (args == NULL || args->t != MCP_OBJ || key == NULL)
return NULL;
for (i = 0; i < args->count; i++)
if (strcmp(args->keys[i], key) == 0)
return args->items[i];
return NULL;
}
const char *mcp_json_string(const mcp_json *v)
{
return (v != NULL && v->t == MCP_STR) ? v->s : NULL;
}
const char *mcp_arg_string(const mcp_json *args, const char *key)
{
return mcp_json_string(mcp_arg(args, key));
}
int mcp_arg_int(const mcp_json *args, const char *key, int dflt)
{
const mcp_json *v = mcp_arg(args, key);
return (v != NULL && v->t == MCP_NUM) ? (int)v->n : dflt;
}
double mcp_arg_num(const mcp_json *args, const char *key, double dflt)
{
const mcp_json *v = mcp_arg(args, key);
return (v != NULL && v->t == MCP_NUM) ? v->n : dflt;
}
int mcp_arg_bool(const mcp_json *args, const char *key, int dflt)
{
const mcp_json *v = mcp_arg(args, key);
return (v != NULL && v->t == MCP_BOOL) ? v->b : dflt;
}
size_t mcp_array_len(const mcp_json *v)
{
return (v != NULL && v->t == MCP_ARR) ? v->count : 0;
}
const mcp_json *mcp_array_at(const mcp_json *v, size_t i)
{
if (v == NULL || v->t != MCP_ARR || i >= v->count)
return NULL;
return v->items[i];
}
/* ------------------------------------------------------------------ writing */
static void send_line(mcp_conn *c, const char *body, size_t len)
{
if (c->to_buf) {
mcp_buf_add(&c->outbuf, body, len);
return;
}
fwrite(body, 1, len, c->out);
fputc('\n', c->out);
fflush(c->out);
}
static void emit_result(mcp_conn *c, const char *result_json)
{
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
mcp_buf_puts(&b, c->id_json ? c->id_json : "null");
mcp_buf_puts(&b, ",\"result\":");
mcp_buf_puts(&b, result_json);
mcp_buf_puts(&b, "}");
send_line(c, b.p, b.len);
mcp_buf_free(&b);
c->replied = 1;
}
void mcp_reply_rpc_error(mcp_conn *c, int code, const char *message)
{
mcp_buf b;
if (c->replied)
return;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
mcp_buf_puts(&b, c->id_json ? c->id_json : "null");
mcp_buf_printf(&b, ",\"error\":{\"code\":%d,\"message\":\"", code);
mcp_json_escape(&b, message);
mcp_buf_puts(&b, "\"}}");
send_line(c, b.p, b.len);
mcp_buf_free(&b);
c->replied = 1;
}
void mcp_reply_raw(mcp_conn *c, const char *json)
{
if (c->replied)
return;
emit_result(c, json ? json : "{}");
}
static void emit_content(mcp_conn *c, const char *text, int is_error)
{
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":\"");
mcp_json_escape(&b, text ? text : "");
mcp_buf_puts(&b, "\"}]");
if (is_error)
mcp_buf_puts(&b, ",\"isError\":true");
mcp_buf_puts(&b, "}");
emit_result(c, b.p);
mcp_buf_free(&b);
}
void mcp_reply_text(mcp_conn *c, const char *text)
{
if (c->replied)
return;
emit_content(c, text, 0);
}
void mcp_reply_json(mcp_conn *c, const char *json)
{
if (c->replied)
return;
emit_content(c, json, 0);
}
void mcp_reply_error(mcp_conn *c, const char *message)
{
if (c->replied)
return;
emit_content(c, message, 1);
}
/* ------------------------------------------------------------------ parse api */
mcp_json *mcp_parse(const char *text)
{
mcp_json *v = NULL;
if (text == NULL)
return NULL;
if (jparse(text, &v) == NULL) {
jfree(v);
return NULL;
}
return v;
}
void mcp_json_free(mcp_json *v)
{
jfree(v);
}
/* ------------------------------------------------------------------ server */
static void tools_list(mcp_conn *c, const mcp_server *srv)
{
mcp_buf b;
size_t i;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"tools\":[");
for (i = 0; i < srv->ntools; i++) {
const mcp_tool *t = &srv->tools[i];
if (i > 0)
mcp_buf_puts(&b, ",");
mcp_buf_puts(&b, "{\"name\":\"");
mcp_json_escape(&b, t->name);
mcp_buf_puts(&b, "\",\"description\":\"");
mcp_json_escape(&b, t->description ? t->description : "");
mcp_buf_puts(&b, "\",\"inputSchema\":");
mcp_buf_puts(&b, (t->schema && *t->schema) ? t->schema
: "{\"type\":\"object\",\"properties\":{}}");
mcp_buf_puts(&b, "}");
}
mcp_buf_puts(&b, "]}");
emit_result(c, b.p);
mcp_buf_free(&b);
}
static void tools_call(mcp_conn *c, const mcp_server *srv, const mcp_json *params)
{
const char *name = mcp_arg_string(params, "name");
const mcp_json *args = mcp_arg(params, "arguments");
size_t i;
if (name == NULL) {
mcp_reply_rpc_error(c, -32602, "missing tool name");
return;
}
for (i = 0; i < srv->ntools; i++) {
if (strcmp(srv->tools[i].name, name) != 0)
continue;
c->replied = 0;
if (srv->tools[i].handler != NULL)
srv->tools[i].handler(c, args, srv->user);
if (!c->replied) {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "tool '%s' produced no reply", name);
emit_content(c, b.p, 1);
mcp_buf_free(&b);
}
return;
}
{
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "unknown tool: %s", name);
mcp_reply_rpc_error(c, -32601, b.p);
mcp_buf_free(&b);
}
}
static char *id_to_json(const mcp_json *id)
{
mcp_buf b;
if (id == NULL)
return NULL;
mcp_buf_init(&b);
if (id->t == MCP_STR) {
mcp_buf_puts(&b, "\"");
mcp_json_escape(&b, id->s);
mcp_buf_puts(&b, "\"");
} else if (id->t == MCP_NUM) {
mcp_buf_printf(&b, "%.0f", id->n);
} else if (id->t == MCP_BOOL) {
mcp_buf_puts(&b, id->b ? "true" : "false");
} else {
mcp_buf_puts(&b, "null");
}
return b.p;
}
static void handle_line(mcp_server *srv, const char *line, mcp_conn *c)
{
mcp_json *msg = NULL;
mcp_json *id;
const char *method;
if (jparse(line, &msg) == NULL || msg == NULL || msg->t != MCP_OBJ) {
jfree(msg);
c->id_json = NULL;
c->replied = 0;
mcp_reply_rpc_error(c, -32700, "parse error");
return;
}
id = NULL;
{
size_t i;
for (i = 0; i < msg->count; i++)
if (strcmp(msg->keys[i], "id") == 0)
id = msg->items[i];
}
method = mcp_arg_string(msg, "method");
c->replied = 0;
free(c->id_json);
c->id_json = id_to_json(id);
/* no id -> notification -> no answer, whatever the method is */
if (id == NULL) {
if (method != NULL && strcmp(method, "tools/call") == 0) {
const mcp_json *args = mcp_arg(mcp_arg(msg, "params"), "arguments");
(void)args;
}
jfree(msg);
return;
}
if (method == NULL) {
mcp_reply_rpc_error(c, -32600, "invalid request: no method");
jfree(msg);
return;
}
if (strcmp(method, "initialize") == 0) {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}}");
mcp_buf_puts(&b, ",\"serverInfo\":{\"name\":\"");
mcp_json_escape(&b, srv->name ? srv->name : "libmcp");
mcp_buf_puts(&b, "\",\"version\":\"");
mcp_json_escape(&b, srv->version ? srv->version : "1.0.0");
mcp_buf_puts(&b, "\"}}");
emit_result(c, b.p);
mcp_buf_free(&b);
} else if (strcmp(method, "tools/list") == 0) {
tools_list(c, srv);
} else if (strcmp(method, "tools/call") == 0) {
tools_call(c, srv, mcp_arg(msg, "params"));
} else if (strcmp(method, "ping") == 0) {
emit_result(c, "{}");
} else {
mcp_buf b;
mcp_buf_init(&b);
mcp_buf_printf(&b, "unknown method: %s", method);
mcp_reply_rpc_error(c, -32601, b.p);
mcp_buf_free(&b);
}
jfree(msg);
}
/* Plain C99 line reader: no getline, no ssize_t, so this header compiles on
* every libc without a feature-test macro. */
static int read_line(FILE *f, mcp_buf *b)
{
int ch;
b->len = 0;
if (b->p != NULL)
b->p[0] = '\0';
while ((ch = fgetc(f)) != EOF && ch != '\n') {
char c = (char)ch;
mcp_buf_add(b, &c, 1);
}
if (ch == EOF && b->len == 0)
return 0;
while (b->len > 0 && b->p[b->len - 1] == '\r')
b->p[--b->len] = '\0';
return 1;
}
char *mcp_handle(mcp_server *srv, const char *line)
{
mcp_conn c;
char *out = NULL;
if (srv == NULL || line == NULL)
return NULL;
memset(&c, 0, sizeof(c));
c.out = stdout;
c.to_buf = 1;
mcp_buf_init(&c.outbuf);
handle_line(srv, line, &c);
if (c.outbuf.len > 0) {
out = malloc(c.outbuf.len + 1);
if (out != NULL)
memcpy(out, c.outbuf.p, c.outbuf.len + 1);
}
mcp_buf_free(&c.outbuf);
free(c.id_json);
return out;
}
int mcp_serve_stdio(mcp_server *srv)
{
mcp_conn c;
mcp_buf line;
memset(&c, 0, sizeof(c));
c.out = stdout;
mcp_buf_init(&line);
while (read_line(stdin, &line)) {
if (line.len == 0)
continue;
handle_line(srv, line.p, &c);
}
mcp_buf_free(&line);
free(c.id_json);
return 0;
}
#endif /* MCP_IMPLEMENTATION */