apex-twin 1.18.0: RPC and NTP probes, sshd_config and PAM audits

Red:
- rpc_probe: one ONC RPC CALL to the portmapper (program 100000, version 2,
  procedure DUMP) with a hand-built XDR message; decodes program/version/
  protocol/port mappings and names common services. No export is mounted.
- ntp_probe: one NTPv4 client packet (mode 3); parses version, mode, leap,
  stratum, reference id (trailing NUL trimmed), root delay/dispersion in ms and
  the transmit time. No monlist.

Blue:
- ssh_config_audit: scores sshd_config for root login, password auth, empty
  passwords, X11, GatewayPorts, PermitTunnel, MaxAuthTries and legacy
  Ciphers/MACs/KexAlgorithms; optional root prefix.
- pam_audit: scans /etc/pam.d for pam_permit, pam_unix nullok, pam_exec and
  reports when neither pam_faillock nor pam_tally2 provides lockout.

Tests: UDP portmapper agent, UDP NTP agent, sshd_config tree and pam.d tree.
674 checks, ASan suite green, analyze clean, release-check green including
distcheck 1.18.0.
This commit is contained in:
lotherk committed 2026-11-21 15:57:13 +00:00
1 parent 816fd0fb57
commit d966fa9600
9 files changed
+829 -20

No files matched your search

+19 -1
View File
@@ -8,7 +8,25 @@ fields, and state from an older version is read by a newer one.
There are no git tags. The hash next to a version is the commit that introduced
it; the current entry is the commit that adds this section.
## 1.17.0 — 2026-11-21 — this change
## 1.18.0 — 2026-11-21 — this change
- **RPC** (`rpc_probe`): one ONC RPC CALL to the portmapper (program 100000,
version 2, procedure DUMP) with a hand-built XDR message; decodes the
mapping list (program, version, protocol, port) and names common services
(portmapper, nfs, mountd, nlockmgr, ypserv). No export is mounted.
- **NTP** (`ntp_probe`): one NTPv4 client packet (mode 3); parses version,
mode, leap indicator, stratum, reference id (trailing NUL trimmed), root
delay/dispersion in milliseconds and the transmit time. No monlist.
- **SSH config** (`ssh_config_audit`): scores sshd_config for root login,
password auth, empty passwords, X11 forwarding, GatewayPorts, PermitTunnel,
MaxAuthTries and legacy Ciphers/MACs/KexAlgorithms; optional root prefix.
- **PAM** (`pam_audit`): scans /etc/pam.d for pam_permit, pam_unix nullok,
pam_exec and reports when neither pam_faillock nor pam_tally2 provides
lockout; optional root prefix.
- Tests with a UDP portmapper agent, a UDP NTP agent, an sshd_config tree and a
pam.d tree. 674 checks. Coverage 79.7%.
## 1.17.0 — 2026-11-21 — 816fd0f
- **CSRF** (`csrf_audit`): fetch one page, list its forms (action, method,
input count) and flag forms without an input whose name contains csrf,
+15 -7
View File
@@ -5,11 +5,11 @@ no Python in the serving path. It gives an agent real reconnaissance and real we
testing behind a scope gate that refuses everything until a rules-of-engagement
file says otherwise.
**116 tools · 663 end-to-end checks · 340 fuzz cases · 79.7% line coverage · ~519 KiB**
**120 tools · 674 end-to-end checks · 340 fuzz cases · 79.7% line coverage · ~531 KiB**
```
$ ./apex-twin --check
{"version":"1.17.0","tools":116,...,"scope":{"loaded":true,...}}
{"version":"1.18.0","tools":120,...,"scope":{"loaded":true,...}}
```
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
@@ -149,7 +149,7 @@ closes a request whose head or body does not arrive within
---
## Tools (116)
## Tools (120)
### Scope and bookkeeping
@@ -274,6 +274,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `ldap_search` | Anonymous subtree search (size limit 20) from namingContexts; DNs plus cn/uid/mail |
| `openapi_discovery` | Six usual spec paths: OpenAPI/Swagger version, title and path count, evidence |
| `csrf_audit` | Forms on one page: action, method, input count and missing CSRF token fields |
| `rpc_probe` | ONC RPC portmapper DUMP: program/version/protocol/port mappings with service names |
| `ntp_probe` | NTPv4 client packet: version, mode, leap, stratum, refid, root delay/dispersion, time |
| `imap_probe` | Banner, CAPABILITY list, STARTTLS and LOGINDISABLED; no LOGIN |
| `pop3_probe` | Banner, CAPA list, STLS flag; no USER/PASS |
| `sip_probe` | One UDP OPTIONS: status line, Server header, Allow methods |
@@ -315,6 +317,8 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `kernel_hardening` | Sysctl hardening set (ASLR, kptr, dmesg, perf, BPF, ptrace, symlinks, core_pattern) with score |
| `sudoers_audit` | NOPASSWD, !authenticate, broad ALL, direct user rules, world-writable sudoers |
| `auditd_audit` | auditd type counts, AVC denials, failed auth, top exe paths and keys |
| `ssh_config_audit` | sshd_config scoring: root login, passwords, tunnels, forwardings, legacy ciphers/MACs/kex |
| `pam_audit` | pam.d: pam_permit, pam_unix nullok, pam_exec and missing faillock/tally lockout |
### ESP32
@@ -530,6 +534,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| Kernel hardening | 12 sysctls; root prefix for mounted images |
| Sudoers audit | 200 files, 100 findings; read-only |
| auditd | 5000 lines; path limited to /var/log or the state dir |
| RPC/NTP | one UDP query, two attempts, 2 s wait |
| sshd/PAM | read config files only; optional root prefix |
---
@@ -540,7 +546,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 663 end-to-end checks
make test # version check + gate audit + 674 end-to-end checks
make version-check # the five places that carry a version must agree
make gate-audit # static: every target-taking tool calls the gate
make asan # apex-twin-asan with ASan + UBSan
@@ -649,7 +655,8 @@ src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery,
mqtt_probe, graphql_probe, docker_api_probe,
elasticsearch_probe, imap_probe, pop3_probe, sip_probe,
telnet_probe, http_methods, websocket_probe, ike_probe,
snmp_walk, ldap_search, openapi_discovery, csrf_audit
snmp_walk, ldap_search, openapi_discovery, csrf_audit,
rpc_probe, ntp_probe
src/tools_blue.c hardening_audit, log_audit, ioc_scan, web_log_audit,
detect_rules, integrity_baseline, mitre_map,
process_snapshot, persistence_audit, net_baseline,
@@ -691,7 +698,7 @@ examples/ scope.json
## Status
1.17.0. Built and run: 116 tools, 663 checks, 340 fuzz cases and 79.7% line
1.18.0. Built and run: 120 tools, 674 checks, 340 fuzz cases and 79.7% line
coverage. The loop closes: a probe captures the exchange as a pair, a finding
points at it, `finding_update` gives it a state, an asset records the host it
came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
@@ -726,7 +733,8 @@ integrity verification; 1.14 added offline ESP32 flash analysis and a mount
audit; 1.15 added HTTP method, WebSocket and IKEv2 checks plus a firewall audit; 1.16
added SNMP walk, LDAP search and OpenAPI discovery plus a systemd audit; 1.17
added CSRF, kernel, sudoers and auditd checks and fixed evidence ordering for
same-second files, again without changing an existing file format.
same-second files; 1.18 added RPC and NTP probes plus sshd_config and PAM
audits, again without changing an existing file format.
Not yet wired into a fleet router, and there is no TLS interception.
+4 -1
View File
@@ -9,7 +9,7 @@ problem.
The supported line is the one printed by `apex-twin --version` for the tree you
built; this document ships with that same tree. At the time of writing the line
is **1.17.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.18.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
line. The 1.0 line promises that the on-disk JSON formats for findings, assets
and traffic only gain fields, so state stays readable; older builds are still
rebuilt rather than patched in place.
@@ -66,6 +66,9 @@ only narrow what the proxy does (the scope gate still runs first).
- **Firmware writing needs an explicit confirmation.** `esp_flash` refuses
without `confirm=true`, validates an absolute image path and audits the
attempt; it exists to provision the operator's own board.
- **RPC and NTP are single queries.** `rpc_probe` sends one portmapper DUMP and
`ntp_probe` one client packet; neither mounts an export, changes a clock or
requests a monlist. `ssh_config_audit` and `pam_audit` read config files.
- **Form and local audits are reads.** `csrf_audit` fetches one page and parses
its forms; `kernel_hardening`, `sudoers_audit` and `auditd_audit` read local
files, with the audit log restricted to /var/log and the state directory.
+8 -7
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.17.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.18.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -43,12 +43,13 @@ memcached_probe, param_fuzz, open_redirect, host_header_injection, ssti_probe,
xxe_probe, ldap_probe, rdp_probe, smb_probe, vnc_probe, mqtt_probe,
graphql_probe, docker_api_probe, elasticsearch_probe, imap_probe, pop3_probe,
sip_probe, telnet_probe, http_methods, websocket_probe, ike_probe, snmp_walk,
ldap_search, openapi_discovery, csrf_audit), defensive audits (hardening_audit,
log_audit, ioc_scan, web_log_audit, detect_rules, integrity_baseline,
mitre_map, process_snapshot, persistence_audit, net_baseline, ssh_key_audit,
suid_baseline, cap_baseline, module_audit, package_integrity, mount_audit,
firewall_audit, systemd_audit, kernel_hardening, sudoers_audit,
auditd_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash,
ldap_search, openapi_discovery, csrf_audit, rpc_probe, ntp_probe), defensive
audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules,
integrity_baseline, mitre_map, process_snapshot, persistence_audit,
net_baseline, ssh_key_audit, suid_baseline, cap_baseline, module_audit,
package_integrity, mount_audit, firewall_audit, systemd_audit,
kernel_hardening, sudoers_audit, auditd_audit, ssh_config_audit,
pam_audit) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash, esp_flash,
esp_partition_table, esp_nvs_parse, firmware_scan).
.SH MODES
.TP
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.17.0"
#define APEX_VERSION "1.18.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+282
View File
@@ -4321,6 +4321,273 @@ static void t_auditd_audit(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
}
/* ----------------------------------------------------------- ssh_config_audit */
static void ssh_finding(mcp_buf *b, int *first, const char *id,
const char *severity, const char *value,
const char *detail)
{
if (!*first)
mcp_buf_puts(b, ",");
*first = 0;
mcp_buf_puts(b, "{\"id\":");
apex_json_str(b, id);
mcp_buf_puts(b, ",\"severity\":");
apex_json_str(b, severity);
mcp_buf_puts(b, ",\"value\":");
apex_json_str(b, value);
mcp_buf_puts(b, ",\"detail\":");
apex_json_str(b, detail);
mcp_buf_puts(b, "}");
}
static void t_ssh_config_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
static char config[65536];
char path[1024];
char value[256];
mcp_buf b;
int first = 1;
int count = 0;
int score = 100;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) > 400) {
mcp_reply_error(c, "root path too long");
return;
}
snprintf(path, sizeof(path), "%s/etc/ssh/sshd_config", root);
if (read_text(path, config, sizeof(config)) <= 0) {
mcp_reply_error(c, "cannot read sshd_config");
return;
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"path\":");
apex_json_str(&b, path);
mcp_buf_puts(&b, ",\"findings\":[");
if (sshd_value(config, "PermitRootLogin", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "root-login", "high", value,
"root may log in directly over SSH");
score -= 12;
count++;
}
if (sshd_value(config, "PasswordAuthentication", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "password-auth", "medium", value,
"password authentication is enabled");
score -= 6;
count++;
}
if (sshd_value(config, "PermitEmptyPasswords", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "empty-passwords", "high", value,
"empty passwords are accepted");
score -= 12;
count++;
}
if (sshd_value(config, "X11Forwarding", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "x11-forwarding", "low", value,
"X11 forwarding is enabled");
score -= 2;
count++;
}
if (sshd_value(config, "GatewayPorts", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "gateway-ports", "high", value,
"remote forwards may bind non-loopback addresses");
score -= 10;
count++;
}
if (sshd_value(config, "PermitTunnel", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "permit-tunnel", "medium", value,
"tun/tap tunnelling is allowed");
score -= 6;
count++;
}
if (sshd_value(config, "MaxAuthTries", value, sizeof(value)) &&
atoi(value) > 4) {
ssh_finding(&b, &first, "max-auth-tries", "medium", value,
"more than four authentication tries per connection");
score -= 4;
count++;
}
if (sshd_value(config, "Ciphers", value, sizeof(value)) &&
(strstr(value, "3des") != NULL || strstr(value, "arcfour") != NULL ||
strstr(value, "blowfish") != NULL || strstr(value, "cbc") != NULL)) {
ssh_finding(&b, &first, "weak-ciphers", "medium", value,
"cipher list contains legacy ciphers");
score -= 6;
count++;
}
if (sshd_value(config, "MACs", value, sizeof(value)) &&
(strstr(value, "md5") != NULL || strstr(value, "sha1-96") != NULL)) {
ssh_finding(&b, &first, "weak-macs", "medium", value,
"MAC list contains md5 or truncated sha1");
score -= 6;
count++;
}
if (sshd_value(config, "KexAlgorithms", value, sizeof(value)) &&
(strstr(value, "group1") != NULL ||
strstr(value, "group14-sha1") != NULL)) {
ssh_finding(&b, &first, "weak-kex", "medium", value,
"key exchange offers group1 or group14-sha1");
score -= 6;
count++;
}
if (sshd_value(config, "AllowTcpForwarding", value, sizeof(value)) &&
strcasecmp(value, "yes") == 0) {
ssh_finding(&b, &first, "tcp-forwarding", "low", value,
"TCP forwarding is allowed");
score -= 2;
count++;
}
if (score < 0)
score = 0;
mcp_buf_printf(&b, "],\"score\":%d,\"findings_count\":%d}", score,
count);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ----------------------------------------------------------------- pam_audit */
typedef struct {
mcp_buf *b;
int first;
int count;
int files;
int rules;
int faillock;
} pam_ctx;
static void pam_finding(pam_ctx *ctx, const char *path, int line,
const char *kind, const char *severity,
const char *detail)
{
if (ctx->count >= 100)
return;
if (!ctx->first)
mcp_buf_puts(ctx->b, ",");
ctx->first = 0;
ctx->count++;
mcp_buf_puts(ctx->b, "{\"path\":");
apex_json_str(ctx->b, path);
mcp_buf_printf(ctx->b, ",\"line\":%d,\"kind\":", line);
apex_json_str(ctx->b, kind);
mcp_buf_puts(ctx->b, ",\"severity\":");
apex_json_str(ctx->b, severity);
mcp_buf_puts(ctx->b, ",\"detail\":");
apex_json_str(ctx->b, detail);
mcp_buf_puts(ctx->b, "}");
}
static void pam_scan_file(pam_ctx *ctx, const char *path)
{
FILE *f;
char *line = NULL;
size_t cap = 0;
int lineno = 0;
if (ctx->files >= 100)
return;
f = fopen(path, "rb");
if (f == NULL)
return;
ctx->files++;
while (getline(&line, &cap, f) >= 0) {
char *t = line;
lineno++;
while (*t == ' ' || *t == '\t')
t++;
if (*t == '\0' || *t == '#')
continue;
ctx->rules++;
if (strstr(t, "pam_permit.so") != NULL)
pam_finding(ctx, path, lineno, "pam-permit", "high",
"pam_permit always succeeds");
if (strstr(t, "pam_unix.so") != NULL &&
strstr(t, "nullok") != NULL)
pam_finding(ctx, path, lineno, "pam-nullok", "high",
"pam_unix accepts empty passwords (nullok)");
if (strstr(t, "pam_exec.so") != NULL)
pam_finding(ctx, path, lineno, "pam-exec", "medium",
"pam_exec runs an external program during auth");
if (strstr(t, "pam_faillock.so") != NULL ||
strstr(t, "pam_tally2.so") != NULL)
ctx->faillock = 1;
}
free(line);
fclose(f);
}
static void t_pam_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
char path[1024];
mcp_buf b;
mcp_buf findings;
pam_ctx ctx;
DIR *d;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) > 400) {
mcp_reply_error(c, "root path too long");
return;
}
snprintf(path, sizeof(path), "%s/etc/pam.d", root);
d = opendir(path);
if (d == NULL) {
mcp_reply_error(c, "cannot read /etc/pam.d");
return;
}
mcp_buf_init(&findings);
memset(&ctx, 0, sizeof(ctx));
ctx.b = &findings;
ctx.first = 1;
{
struct dirent *ent;
while ((ent = readdir(d)) != NULL) {
char full[1024];
struct stat st;
if (ent->d_name[0] == '.')
continue;
snprintf(full, sizeof(full), "%.800s/%.160s", path,
ent->d_name);
if (stat(full, &st) != 0 || !S_ISREG(st.st_mode))
continue;
pam_scan_file(&ctx, full);
}
closedir(d);
}
if (ctx.files > 0 && !ctx.faillock)
pam_finding(&ctx, path, 0, "no-faillock", "medium",
"no pam_faillock/pam_tally2 lockout configured");
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, root);
mcp_buf_printf(&b, ",\"files\":%d,\"rules\":%d,\"faillock\":%s,"
"\"findings_count\":%d,\"findings\":[",
ctx.files, ctx.rules, ctx.faillock ? "true" : "false",
ctx.count);
if (findings.p != NULL)
mcp_buf_add(&b, findings.p, findings.len);
mcp_buf_puts(&b, "]}");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
mcp_buf_free(&findings);
}
const mcp_tool TOOLS_BLUE[] = {
{ "hardening_audit",
"Read-only posture audit of the local host: sshd_config (root login, "
@@ -4577,6 +4844,21 @@ const mcp_tool TOOLS_BLUE[] = {
"\"limit\":{\"type\":\"integer\",\"description\":\"lines, default "
"5000\"}}}",
t_auditd_audit },
{ "ssh_config_audit",
"Score an sshd_config (optional root prefix): PermitRootLogin, "
"PasswordAuthentication, PermitEmptyPasswords, X11Forwarding, "
"GatewayPorts, PermitTunnel, MaxAuthTries and legacy Ciphers/MACs/"
"KexAlgorithms, with a finding per weak value. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_ssh_config_audit },
{ "pam_audit",
"Scan /etc/pam.d (optional root prefix) for pam_permit, pam_unix nullok "
"and pam_exec, and report whether pam_faillock or pam_tally2 provides "
"lockout. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"}}}",
t_pam_audit },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+348
View File
@@ -3939,6 +3939,334 @@ static void t_ldap_search(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
}
/* ---------------------------------------------------------------- rpc_probe */
static const char *rpc_program_name(unsigned long prog)
{
switch (prog) {
case 100000:
return "portmapper";
case 100003:
return "nfs";
case 100004:
return "ypserv";
case 100005:
return "mountd";
case 100007:
return "ypbind";
case 100011:
return "rquotad";
case 100021:
return "nlockmgr";
case 100024:
return "status";
case 100068:
return "metad";
case 100083:
return "ttdbserver";
case 100227:
return "nfs_acl";
default:
return "unknown";
}
}
static int rpc_udp(const char *target, int port, unsigned char *resp,
size_t resp_cap, size_t *rlen)
{
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *use = NULL;
struct addrinfo *rp;
char service[16];
unsigned char msg[40];
int fd = -1;
int attempt;
unsigned long xid = (unsigned long)getpid() ^ (unsigned long)time(NULL);
memset(msg, 0, sizeof(msg));
msg[0] = (unsigned char)(xid >> 24);
msg[1] = (unsigned char)(xid >> 16);
msg[2] = (unsigned char)(xid >> 8);
msg[3] = (unsigned char)xid;
msg[7] = 0; /* CALL */
msg[11] = 2; /* RPC version */
msg[15] = 0; /* program 100000: 0x000186a0 */
msg[14] = 0x01;
msg[13] = 0x86;
msg[12] = 0xa0;
msg[19] = 2; /* version 2 */
msg[23] = 4; /* procedure DUMP */
snprintf(service, sizeof(service), "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if (getaddrinfo(target, service, &hints, &res) != 0)
return -1;
for (rp = res; rp != NULL; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd >= 0) {
use = rp;
break;
}
}
if (use == NULL) {
freeaddrinfo(res);
return -1;
}
for (attempt = 0; attempt < 2; attempt++) {
struct pollfd pfd;
ssize_t r;
if (sendto(fd, msg, sizeof(msg), 0, use->ai_addr,
use->ai_addrlen) < 0)
break;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
if (poll(&pfd, 1, 2000) <= 0)
continue;
r = recv(fd, resp, resp_cap, 0);
if (r > 0) {
*rlen = (size_t)r;
close(fd);
freeaddrinfo(res);
return 0;
}
}
close(fd);
freeaddrinfo(res);
return -1;
}
static void t_rpc_probe(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
int port = mcp_arg_int(args, "port", 111);
unsigned char resp[2048];
size_t rlen = 0;
mcp_buf b;
int first = 1;
int count = 0;
size_t off;
unsigned long reply_stat;
unsigned long accept_stat;
(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 (!gated(c, "rpc_probe", target, port))
return;
if (rpc_udp(target, port, resp, sizeof(resp), &rlen) != 0) {
mcp_reply_error(c, "no RPC response");
return;
}
if (rlen < 24) {
mcp_reply_error(c, "RPC response too short");
return;
}
reply_stat = be32(resp + 8);
if (reply_stat != 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "RPC call rejected (reply_stat %lu)",
reply_stat);
mcp_reply_error(c, b.p);
mcp_buf_free(&b);
return;
}
accept_stat = be32(resp + 20);
if (accept_stat != 0) {
mcp_buf_init(&b);
mcp_buf_printf(&b, "RPC call not accepted (accept_stat %lu)",
accept_stat);
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_printf(&b, ",\"port\":%d,\"rpc\":true,\"mappings\":[", port);
off = 24;
while (off + 4 <= rlen) {
unsigned long follow = be32(resp + off);
off += 4;
if (follow == 0)
break;
if (off + 16 > rlen)
break;
{
unsigned long prog = be32(resp + off);
unsigned long vers = be32(resp + off + 4);
unsigned long prot = be32(resp + off + 8);
unsigned long mport = be32(resp + off + 12);
off += 16;
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
count++;
mcp_buf_puts(&b, "{\"program\":");
mcp_buf_printf(&b, "%lu,\"version\":%lu,\"protocol\":\"%s\","
"\"port\":%lu,\"name\":", prog, vers,
prot == 6 ? "tcp" : (prot == 17 ? "udp" : "other"),
mport);
apex_json_str(&b, rpc_program_name(prog));
mcp_buf_puts(&b, "}");
}
if (count >= 64)
break;
}
mcp_buf_printf(&b, "],\"count\":%d}", count);
apex_audit("rpc_probe", target, port, 0, "portmapper dump", "RPC DUMP");
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ---------------------------------------------------------------- ntp_probe */
static void t_ntp_probe(mcp_conn *c, const mcp_json *args, void *user)
{
const char *target = mcp_arg_string(args, "target");
int port = mcp_arg_int(args, "port", 123);
unsigned char msg[48];
unsigned char resp[512];
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *use = NULL;
struct addrinfo *rp;
char service[16];
int fd = -1;
int attempt;
ssize_t r = 0;
int got = 0;
int leap;
int version;
int mode;
int stratum;
char refid[16];
char when[64];
mcp_buf b;
(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 (!gated(c, "ntp_probe", target, port))
return;
memset(msg, 0, sizeof(msg));
msg[0] = 0x23; /* LI 0, version 4, client */
snprintf(service, sizeof(service), "%d", port);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if (getaddrinfo(target, service, &hints, &res) != 0) {
mcp_reply_error(c, "cannot resolve the target");
return;
}
for (rp = res; rp != NULL; rp = rp->ai_next) {
fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (fd >= 0) {
use = rp;
break;
}
}
if (use == NULL) {
freeaddrinfo(res);
mcp_reply_error(c, "cannot open a UDP socket");
return;
}
for (attempt = 0; attempt < 2 && !got; attempt++) {
struct pollfd pfd;
if (sendto(fd, msg, sizeof(msg), 0, use->ai_addr,
use->ai_addrlen) < 0)
break;
pfd.fd = fd;
pfd.events = POLLIN;
pfd.revents = 0;
if (poll(&pfd, 1, 2000) <= 0)
continue;
r = recv(fd, resp, sizeof(resp), 0);
if (r >= 48)
got = 1;
}
close(fd);
freeaddrinfo(res);
if (!got) {
mcp_reply_error(c, "no NTP response");
return;
}
leap = (resp[0] >> 6) & 0x03;
version = (resp[0] >> 3) & 0x07;
mode = resp[0] & 0x07;
stratum = resp[1];
refid[0] = '\0';
{
int printable = 1;
int len = 4;
int i;
while (len > 0 && resp[12 + len - 1] == 0)
len--;
if (len == 0)
printable = 0;
for (i = 0; i < len; i++)
if (resp[12 + i] < 0x20 || resp[12 + i] > 0x7e)
printable = 0;
if (printable)
snprintf(refid, sizeof(refid), "%.*s", len,
(const char *)resp + 12);
else
snprintf(refid, sizeof(refid), "%02x%02x%02x%02x",
resp[12], resp[13], resp[14], resp[15]);
}
when[0] = '\0';
{
unsigned long secs = be32(resp + 40);
if (secs > 2208988800UL) {
time_t t = (time_t)(secs - 2208988800UL);
struct tm tmv = *gmtime(&t);
strftime(when, sizeof(when), "%Y-%m-%dT%H:%M:%SZ", &tmv);
}
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"ntp\":true,\"version\":%d,"
"\"mode\":%d,\"leap\":%d,\"stratum\":%d,"
"\"root_delay_ms\":%lu,\"root_dispersion_ms\":%lu,"
"\"refid\":", port, version, mode, leap, stratum,
(unsigned long)(be32(resp + 4) / 65536UL * 1000UL +
(be32(resp + 4) % 65536UL) * 1000UL /
65536UL),
(unsigned long)(be32(resp + 8) / 65536UL * 1000UL +
(be32(resp + 8) % 65536UL) * 1000UL /
65536UL));
apex_json_str(&b, refid);
mcp_buf_puts(&b, ",\"server_time\":");
apex_json_str(&b, when);
mcp_buf_puts(&b, "}");
apex_audit("ntp_probe", target, port, 1, "NTP server answered",
when[0] != '\0' ? when : refid);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_PROTO[] = {
{ "ftp_probe",
"One-connection FTP check: read the 220 banner, ask FEAT, then try the "
@@ -4156,6 +4484,26 @@ const mcp_tool TOOLS_PROTO[] = {
"default from namingContexts\"}},"
"\"required\":[\"target\"]}",
t_ldap_search },
{ "rpc_probe",
"Call the ONC RPC portmapper (program 100000, version 2, procedure DUMP) "
"over UDP and decode the mapping list: program, version, protocol and "
"port, with common services named (portmapper, nfs, mountd, nlockmgr, "
"ypserv). No NFS call is made. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 111\"}},"
"\"required\":[\"target\"]}",
t_rpc_probe },
{ "ntp_probe",
"Send one NTPv4 client packet (mode 3) over UDP and parse the server "
"answer: version, mode, leap indicator, stratum, reference id, root "
"delay/dispersion in milliseconds and the transmit time. No monlist and "
"no configuration. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 123\"}},"
"\"required\":[\"target\"]}",
t_ntp_probe },
};
const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]);
+1 -1
View File
@@ -21,7 +21,7 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 116
EXPECTED_TOOLS = 120
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
+151 -2
View File
@@ -134,7 +134,7 @@ res, _ = run([
], home=empty)
check("tools/list answers", any(r.get("id") == 1 for r in res))
tools = [r for r in res if r.get("id") == 1][0]["result"]["tools"]
check("116 tools registered", len(tools) == 116, len(tools))
check("120 tools registered", len(tools) == 120, len(tools))
names = {t["name"] for t in tools}
for need in ("portscan", "nmap", "http_request", "marauder_scan",
"method_playbook", "finding_add", "finding_update", "scope_check",
@@ -1560,7 +1560,7 @@ try:
check("http initialize", init["result"]["serverInfo"]["name"] == "apex-twin",
init)
listing = post({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
check("http tools/list", len(listing["result"]["tools"]) == 116)
check("http tools/list", len(listing["result"]["tools"]) == 120)
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
@@ -5312,6 +5312,155 @@ shutil.rmtree(kh_root, ignore_errors=True)
shutil.rmtree(sudo_root, ignore_errors=True)
shutil.rmtree(sec_home2, ignore_errors=True)
print("\n== RPC, NTP, sshd_config and PAM ==")
def rpc_agent():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 0))
sock.settimeout(0.2)
port = sock.getsockname()[1]
stop = threading.Event()
def loop():
while not stop.is_set():
try:
data, addr = sock.recvfrom(2048)
except socket.timeout:
continue
except OSError:
return
if len(data) < 40:
continue
resp = data[:4]
resp += struct.pack(">I", 1)
resp += struct.pack(">I", 0)
resp += struct.pack(">II", 0, 0)
resp += struct.pack(">I", 0)
resp += struct.pack(">I", 1) + struct.pack(">IIII", 100003, 3, 6,
2049)
resp += struct.pack(">I", 1) + struct.pack(">IIII", 100005, 3, 17,
20048)
resp += struct.pack(">I", 0)
sock.sendto(resp, addr)
threading.Thread(target=loop, daemon=True).start()
return sock, port, stop
def ntp_agent():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 0))
sock.settimeout(0.2)
port = sock.getsockname()[1]
stop = threading.Event()
def loop():
while not stop.is_set():
try:
_data, addr = sock.recvfrom(512)
except socket.timeout:
continue
except OSError:
return
resp = bytearray(48)
resp[0] = (0 << 6) | (4 << 3) | 4
resp[1] = 2
resp[2] = 6
resp[3] = 0xec
struct.pack_into(">I", resp, 4, 0x00010000)
struct.pack_into(">I", resp, 8, 0x00008000)
resp[12:16] = b"GPS\x00"
secs = int(time.time()) + 2208988800
struct.pack_into(">I", resp, 40, secs & 0xffffffff)
sock.sendto(bytes(resp), addr)
threading.Thread(target=loop, daemon=True).start()
return sock, port, stop
rpc_sock, rpc_port, rpc_stop = rpc_agent()
ntp_sock, ntp_port, ntp_stop = ntp_agent()
net_home2 = tempfile.mkdtemp(prefix="apex-net2-")
sshd_root = tempfile.mkdtemp(prefix="apex-sshd-")
os.makedirs(os.path.join(sshd_root, "etc", "ssh"))
with open(os.path.join(sshd_root, "etc", "ssh", "sshd_config"), "w") as f:
f.write("PermitRootLogin yes\n")
f.write("PasswordAuthentication yes\n")
f.write("PermitEmptyPasswords yes\n")
f.write("X11Forwarding yes\n")
f.write("GatewayPorts yes\n")
f.write("PermitTunnel yes\n")
f.write("MaxAuthTries 10\n")
f.write("Ciphers aes128-cbc,3des-cbc\n")
f.write("MACs hmac-md5\n")
f.write("KexAlgorithms diffie-hellman-group14-sha1\n")
pam_root = tempfile.mkdtemp(prefix="apex-pam-")
os.makedirs(os.path.join(pam_root, "etc", "pam.d"))
with open(os.path.join(pam_root, "etc", "pam.d", "common-auth"), "w") as f:
f.write("auth required pam_unix.so nullok\n")
f.write("auth sufficient pam_permit.so\n")
f.write("auth optional pam_exec.so /usr/local/bin/hook\n")
with open(os.path.join(pam_root, "etc", "pam.d", "other"), "w") as f:
f.write("password requisite pam_unix.so sha512\n")
write_scope(net_home2, {"label": "net2", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(rpc_port), str(ntp_port)]})
res, _ = run([
call(1, "rpc_probe", target="127.0.0.1", port=rpc_port),
call(2, "ntp_probe", target="127.0.0.1", port=ntp_port),
call(3, "ssh_config_audit", root=sshd_root),
call(4, "pam_audit", root=pam_root),
call(5, "rpc_probe", target="198.51.100.9", port=111),
call(6, "ssh_config_audit", root="/nonexistent-sshd"),
call(7, "pam_audit", root="/nonexistent-pam"),
], home=net_home2)
by_id = {r.get("id"): r for r in res}
rpc = json.loads(text(by_id[1]))
maps = {m["name"]: m for m in rpc["mappings"]}
check("rpc_probe decodes the portmapper dump",
rpc["count"] == 2 and maps["nfs"]["port"] == 2049 and
maps["nfs"]["protocol"] == "tcp", rpc)
check("rpc_probe names mountd and its UDP port",
maps["mountd"]["port"] == 20048 and
maps["mountd"]["protocol"] == "udp", rpc)
ntp = json.loads(text(by_id[2]))
check("ntp_probe reads the server answer",
ntp["version"] == 4 and ntp["mode"] == 4 and ntp["stratum"] == 2 and
ntp["refid"] == "GPS", ntp)
check("ntp_probe converts delay and dispersion",
ntp["root_delay_ms"] == 1000 and ntp["root_dispersion_ms"] == 500 and
ntp["server_time"] != "", ntp)
ssh = json.loads(text(by_id[3]))
ssh_ids = {f["id"] for f in ssh["findings"]}
check("ssh_config_audit finds every weak directive",
{"root-login", "password-auth", "empty-passwords", "x11-forwarding",
"gateway-ports", "permit-tunnel", "max-auth-tries", "weak-ciphers",
"weak-macs", "weak-kex"} == ssh_ids, ssh)
check("ssh_config_audit scores the result", ssh["score"] == 30, ssh)
pam = json.loads(text(by_id[4]))
pkinds = [f["kind"] for f in pam["findings"]]
check("pam_audit reads both files and the rules",
pam["files"] == 2 and pam["rules"] == 4 and pam["faillock"] is False,
pam)
check("pam_audit flags permit, nullok and exec",
{"pam-permit", "pam-nullok", "pam-exec", "no-faillock"} <= set(pkinds),
pkinds)
check("rpc_probe refuses an out-of-scope target", err(by_id[5]),
text(by_id[5]))
check("ssh_config_audit reports a missing config", err(by_id[6]),
text(by_id[6]))
check("pam_audit reports a missing pam.d", err(by_id[7]), text(by_id[7]))
rpc_stop.set()
rpc_sock.close()
ntp_stop.set()
ntp_sock.close()
shutil.rmtree(sshd_root, ignore_errors=True)
shutil.rmtree(pam_root, ignore_errors=True)
shutil.rmtree(net_home2, ignore_errors=True)
print("\n== esp32 tools ==")
esp_home = tempfile.mkdtemp(prefix="apex-esp-")
write_scope(esp_home, {"label": "esp", "expires": "2099-12-31T23:59:59Z"})