apex-twin 1.9.0: SSTI, XXE, LDAP probes and SSH key audit

Red:
- ssti_probe: five template payloads ({{1337*7}}, ${1337*7}, #{1337*7},
  <%= 1337*7 %>, {{1337*'7'}}) with expected outputs, after a baseline request
  clears pages that already contain the numbers. Reports evaluation with the
  likely engine, reflection or template errors; GET query or POST form;
  evaluations saved as evidence.
- xxe_probe: XML with a DOCTYPE external entity pointing at a loopback listener
  this process opens, in element and attribute form (optionally wrapped in a
  form field). A callback proves the parser resolved it; parser error
  signatures are reported too.
- ldap_probe: LDAPv3 anonymous simple bind, then a rootDSE search (baseObject
  '', scope base, present(objectClass)); reports namingContexts, vendorName,
  supportedLDAPVersion and the other attributes; an accepted anonymous bind is
  audited.

Blue:
- ssh_key_audit: authorized_keys under /etc/ssh, /root/.ssh, /home/*/.ssh and
  the state dir, plus private keys (id_* and /etc/ssh/ssh_host_*_key). Flags
  unrestricted entries, ssh-rsa/ssh-dss, duplicate keys and private keys
  readable beyond their owner; optional root prefix for a mounted image.

Tests: a template engine that evaluates Jinja and EL payloads, an XML endpoint
that fetches the external entity, LDAP servers that accept and reject the
anonymous bind with a rootDSE, and an SSH key tree with restricted,
unrestricted, duplicate and weak keys plus three private-key modes. 569 checks,
ASan suite green, analyze clean, release-check green including distcheck 1.9.0.

The LDAP bind parser had to be structural: the result code is an enum TLV
(0a 01 code), not three raw bytes after the protocol-op tag.
This commit is contained in:
lotherk committed 2026-11-21 13:13:14 +00:00
1 parent dfcc5340e0
commit 60075eb30f
10 files changed
+1305 -21

No files matched your search

+27 -1
View File
@@ -8,7 +8,33 @@ 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.8.0 — 2026-11-21 — this change
## 1.9.0 — 2026-11-21 — this change
- **SSTI** (`ssti_probe`): five payloads (`{{1337*7}}`, `${1337*7}`,
`#{1337*7}`, `<%= 1337*7 %>`, `{{1337*'7'}}`) with expected outputs; a
baseline request first rejects pages that already contain the numbers.
Reports evaluation (with the likely engine), reflection or template errors,
GET query or POST form, evaluations saved as evidence.
- **XXE** (`xxe_probe`): POSTs XML with a DOCTYPE external entity that points
at a loopback listener this process opens, in element and attribute form
(optionally wrapped in a form field). A callback proves the parser resolved
the entity; parser error signatures are reported too.
- **LDAP** (`ldap_probe`): LDAPv3 anonymous simple bind, then a rootDSE search
(baseObject "", scope base, present(objectClass)); reports namingContexts,
vendorName, supportedLDAPVersion and the other attributes. An accepted
anonymous bind is audited.
- **Blue** (`ssh_key_audit`): authorized_keys under /etc/ssh, /root/.ssh,
/home/*/.ssh and the state dir, plus private keys (id_* and
/etc/ssh/ssh_host_*_key). Flags unrestricted entries, ssh-rsa/ssh-dss,
duplicate keys and private keys accessible beyond their owner; optional root
prefix audits a mounted image.
- Tests with local fixtures: a template engine that evaluates Jinja and EL
payloads, an XML endpoint that fetches the external entity, LDAP servers that
accept and reject the anonymous bind with a rootDSE, and an SSH key tree with
restricted/unrestricted/duplicate/weak keys and three private-key modes.
569 checks. Coverage 80.1%.
## 1.8.0 — 2026-11-21 — dfcc534
- **Red, web input** (`tools_red.c`): `param_fuzz` sends three benign probes per
parameter (unique marker, single quote, `{{1337*7}}`) through GET query or
+18 -9
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.
**81 tools · 553 end-to-end checks · 340 fuzz cases · 79.9% line coverage · ~391 KiB**
**85 tools · 569 end-to-end checks · 340 fuzz cases · 80.1% line coverage · ~408 KiB**
```
$ ./apex-twin --check
{"version":"1.8.0","tools":81,...,"scope":{"loaded":true,...}}
{"version":"1.9.0","tools":85,...,"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 (81)
## Tools (85)
### Scope and bookkeeping
@@ -257,6 +257,9 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `param_fuzz` | Marker, quote and `{{1337*7}}` per parameter; reports reflection, SQL/stack/template errors and template evaluation |
| `open_redirect` | Sends an external marker URL and a protocol-relative variant; reports Location/meta-refresh redirects with evidence |
| `host_header_injection` | Canary as Host and X-Forwarded-Host; reports reflection in body or Location, with baseline size |
| `ssti_probe` | Five template payloads with expected results; reports evaluation, reflection or template errors and the likely engine |
| `xxe_probe` | XML with an external entity pointing at its own loopback listener; callback proves the parser resolved it |
| `ldap_probe` | LDAPv3 anonymous bind plus rootDSE read (namingContexts, vendorName, supportedLDAPVersion) |
| `ftp_probe` | One FTP connection: banner, FEAT list, and whether the literal anonymous pair is accepted (audited) |
| `smtp_probe` | One SMTP connection: banner, EHLO extensions, VRFY of up to 8 users classified exists/unknown/cannot-verify |
| `ssh_audit` | Banner plus KEXINIT lists (kex, host key, ciphers, MACs) and deprecated algorithms flagged |
@@ -283,6 +286,7 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `process_snapshot` | Read `/proc`: exe/fd count per process, flags /tmp or deleted executables, reverse-shell command lines, >256 fds |
| `persistence_audit` | Cron, systemd units/timers and at jobs: flags /tmp paths, curl/wget piped to a shell, base64-to-shell, nc -e/socat, bash -i, setuid chmod |
| `net_baseline` | Listening TCP ports with owning process names (`create`/`verify`); reports new, gone and process-changed ports |
| `ssh_key_audit` | authorized_keys and private keys: unrestricted entries, ssh-rsa/ssh-dss, duplicates, loose permissions |
### ESP32
@@ -474,6 +478,8 @@ The full threat model, trust boundaries and a hardening checklist are in
| Database probes | one or two connections each; no password attempts |
| Param fuzz | 10 parameters × 3 probes per call, 100 ms apart |
| Net baseline | 500 ports; process lookup capped by /proc walk |
| SSTI | 5 payloads per call, 100 ms apart |
| SSRF/XXE callbacks | one loopback listener, 1.2 s wait per probe |
---
@@ -484,7 +490,7 @@ Flags are fixed: `-std=c99 -Wall -Wextra -Wpedantic -Werror` plus
```sh
make # apex-twin
make test # version check + gate audit + 553 end-to-end checks
make test # version check + gate audit + 569 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
@@ -588,10 +594,12 @@ src/tools_report.c report renderers (Markdown, CSV, JSON)
src/tools_traffic.c traffic_list / traffic_read
src/tools_red.c vuln_check, subdomain_enum, cred_test, vhost_discovery,
http_brute, ssrf_probe, jwt_audit, hash_id, param_fuzz,
open_redirect, host_header_injection
open_redirect, host_header_injection, ssti_probe,
xxe_probe, ldap_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
process_snapshot, persistence_audit, net_baseline,
ssh_key_audit
src/tools_esp.c esp_info, esp_monitor, esp_read_flash, esp_flash
src/tools_proto.c ftp_probe, smtp_probe, ssh_audit, tls_audit,
redis_probe, snmp_probe, dns_zone_transfer
@@ -626,7 +634,7 @@ examples/ scope.json
## Status
1.8.0. Built and run: 81 tools, 553 checks, 340 fuzz cases and 79.9% line
1.9.0. Built and run: 85 tools, 569 checks, 340 fuzz cases and 80.1% 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
@@ -652,8 +660,9 @@ verification, detection-rule export, integrity baselines and firmware writing
/proc snapshot; 1.5 added FTP/SMTP/SSH service probes and a persistence audit;
1.6 added TLS, Redis, SNMP and DNS zone-transfer checks; 1.7 added MySQL,
PostgreSQL, MongoDB and Memcached probes; 1.8 added parameter fuzzing, open
redirect and Host-header checks plus a network baseline, again without changing
an existing tool or file format.
redirect and Host-header checks plus a network baseline; 1.9 added SSTI, XXE
and LDAP probes plus an SSH key audit, again without changing an existing tool
or file format.
Not yet wired into a fleet router, and there is no TLS interception.
+6 -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.8.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.9.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,11 @@ 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.
- **SSTI and XXE probes prove evaluation, then stop.** `ssti_probe` sends
arithmetic expressions and only looks for their result; `xxe_probe` points
the external entity at its own loopback listener and never at a file or a
third party. `ldap_probe` sends an anonymous bind and a rootDSE read, not
credentials. `ssh_key_audit` only reads key files the operator can read.
- **Web input probes send markers, not exploits.** `param_fuzz` injects a
unique marker, a single quote and `{{1337*7}}`, then looks for reflection and
error signatures; `open_redirect` sends a URL on example.com; `host_header_-
+6 -6
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.8.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-21" "apex-twin 1.9.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -39,11 +39,11 @@ testing it carries offensive verification (vuln_check, subdomain_enum,
cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id,
ftp_probe, smtp_probe, ssh_audit, tls_audit, redis_probe, snmp_probe,
dns_zone_transfer, mysql_probe, postgres_probe, mongo_probe,
memcached_probe, param_fuzz, open_redirect, host_header_injection), defensive
audits (hardening_audit, log_audit, ioc_scan, web_log_audit, detect_rules,
integrity_baseline, mitre_map, process_snapshot, persistence_audit,
net_baseline) and ESP32 board tools (esp_info, esp_monitor, esp_read_flash,
esp_flash).
memcached_probe, param_fuzz, open_redirect, host_header_injection, ssti_probe,
xxe_probe, ldap_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) and ESP32 board tools
(esp_info, esp_monitor, esp_read_flash, esp_flash).
.SH MODES
.TP
.B apex-twin
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.8.0"
#define APEX_VERSION "1.9.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+295
View File
@@ -2274,6 +2274,289 @@ static void t_net_baseline(mcp_conn *c, const mcp_json *args, void *user)
mcp_buf_free(&b);
}
/* ------------------------------------------------------------ ssh_key_audit */
typedef struct {
mcp_buf *b;
int first;
int count;
int files;
int keys;
int max_files;
char blobs[64][256];
char where[64][256];
int nblobs;
} key_ctx;
static void key_finding(key_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 int ssh_key_type(const char *token)
{
return strncmp(token, "ssh-", 4) == 0 ||
strncmp(token, "ecdsa-", 6) == 0 ||
strncmp(token, "sk-ssh-", 7) == 0 ||
strncmp(token, "sk-ecdsa-", 9) == 0;
}
static void key_scan_file(key_ctx *ctx, const char *path)
{
FILE *f;
char *line = NULL;
size_t cap = 0;
int lineno = 0;
if (ctx->files >= ctx->max_files)
return;
f = fopen(path, "rb");
if (f == NULL)
return;
ctx->files++;
while (getline(&line, &cap, f) >= 0) {
char *tokens[16];
int ntok = 0;
char *save = NULL;
char *tok;
char *copy;
int kidx = -1;
int i;
char options[512];
size_t olen = 0;
int restricted;
lineno++;
while (line[0] == ' ' || line[0] == '\t')
memmove(line, line + 1, strlen(line));
trim_eol(line);
if (line[0] == '\0' || line[0] == '#')
continue;
copy = strdup(line);
if (copy == NULL)
continue;
tok = strtok_r(copy, " \t", &save);
while (tok != NULL && ntok < 16) {
tokens[ntok++] = tok;
tok = strtok_r(NULL, " \t", &save);
}
for (i = 0; i < ntok; i++)
if (ssh_key_type(tokens[i])) {
kidx = i;
break;
}
if (kidx < 0) {
free(copy);
continue;
}
ctx->keys++;
options[0] = '\0';
for (i = 0; i < kidx; i++) {
size_t tl = strlen(tokens[i]);
if (olen + tl + 2 < sizeof(options)) {
if (olen > 0)
options[olen++] = ' ';
memcpy(options + olen, tokens[i], tl);
olen += tl;
options[olen] = '\0';
}
}
restricted = strstr(options, "from=") != NULL ||
strstr(options, "command=") != NULL ||
strstr(options, "restrict") != NULL ||
strstr(options, "no-pty") != NULL ||
strstr(options, "no-port-forwarding") != NULL ||
strstr(options, "no-agent-forwarding") != NULL;
if (!restricted)
key_finding(ctx, path, lineno, "unrestricted", "medium",
"key has no from= or command= restriction");
if (strcmp(tokens[kidx], "ssh-rsa") == 0)
key_finding(ctx, path, lineno, "weak-key-type", "low",
"ssh-rsa uses SHA-1 signatures");
if (strcmp(tokens[kidx], "ssh-dss") == 0)
key_finding(ctx, path, lineno, "weak-key-type", "medium",
"ssh-dss is deprecated");
if (kidx + 1 < ntok) {
const char *blob = tokens[kidx + 1];
int j;
int dup = 0;
for (j = 0; j < ctx->nblobs; j++)
if (strcmp(ctx->blobs[j], blob) == 0)
dup = 1;
if (dup) {
char detail[320];
snprintf(detail, sizeof(detail),
"the same key is authorized more than once");
key_finding(ctx, path, lineno, "duplicate-key", "low",
detail);
} else if (ctx->nblobs < 64) {
snprintf(ctx->blobs[ctx->nblobs],
sizeof(ctx->blobs[0]), "%.240s", blob);
snprintf(ctx->where[ctx->nblobs],
sizeof(ctx->where[0]), "%.200s:%d", path,
lineno);
ctx->nblobs++;
}
}
free(copy);
}
free(line);
fclose(f);
}
static void key_private_check(key_ctx *ctx, const char *path)
{
struct stat st;
char detail[192];
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode))
return;
if ((st.st_mode & 0077) == 0)
return;
snprintf(detail, sizeof(detail),
"private key is accessible beyond its owner (mode %04o)",
(unsigned)(st.st_mode & 07777));
key_finding(ctx, path, 0, "private-key-permissions", "high", detail);
}
static void key_scan_ssh_dir(key_ctx *ctx, const char *dir)
{
DIR *d = opendir(dir);
struct dirent *ent;
if (d == NULL)
return;
while ((ent = readdir(d)) != NULL && ctx->files < ctx->max_files) {
char path[1024];
size_t dl = strlen(dir);
size_t nl = strlen(ent->d_name);
if (ent->d_name[0] == '.')
continue;
if (dl + nl + 2 > sizeof(path))
continue;
memcpy(path, dir, dl);
path[dl] = '/';
memcpy(path + dl + 1, ent->d_name, nl + 1);
if (strcmp(ent->d_name, "authorized_keys") == 0)
key_scan_file(ctx, path);
else if (strncmp(ent->d_name, "id_", 3) == 0 &&
strstr(ent->d_name, ".pub") == NULL)
key_private_check(ctx, path);
}
closedir(d);
}
static void key_scan_homes(key_ctx *ctx, const char *home_root)
{
DIR *d = opendir(home_root);
struct dirent *ent;
if (d == NULL)
return;
while ((ent = readdir(d)) != NULL && ctx->files < ctx->max_files) {
char sshdir[1024];
if (ent->d_name[0] == '.')
continue;
snprintf(sshdir, sizeof(sshdir), "%.800s/%.160s/.ssh", home_root,
ent->d_name);
key_scan_ssh_dir(ctx, sshdir);
}
closedir(d);
}
static void t_ssh_key_audit(mcp_conn *c, const mcp_json *args, void *user)
{
const char *root = mcp_arg_string(args, "root");
int limit = mcp_arg_int(args, "limit", 200);
char base[512];
size_t bl;
char path[1024];
mcp_buf b;
mcp_buf findings;
key_ctx ctx;
DIR *d;
(void)user;
if (root == NULL)
root = "";
if (strlen(root) >= sizeof(base) - 2) {
mcp_reply_error(c, "root path too long");
return;
}
snprintf(base, sizeof(base), "%s", root);
bl = strlen(base);
while (bl > 0 && base[bl - 1] == '/')
base[--bl] = '\0';
if (limit <= 0 || limit > 2000)
limit = 200;
mcp_buf_init(&findings);
memset(&ctx, 0, sizeof(ctx));
ctx.b = &findings;
ctx.first = 1;
ctx.max_files = limit;
snprintf(path, sizeof(path), "%s/etc/ssh/authorized_keys", base);
key_scan_file(&ctx, path);
snprintf(path, sizeof(path), "%s/root/.ssh", base);
key_scan_ssh_dir(&ctx, path);
snprintf(path, sizeof(path), "%s/home", base);
key_scan_homes(&ctx, path);
snprintf(path, sizeof(path), "%.450s%.450s/.ssh", base, g_cfg.home);
key_scan_ssh_dir(&ctx, path);
/* host keys in /etc/ssh */
snprintf(path, sizeof(path), "%s/etc/ssh", base);
d = opendir(path);
if (d != NULL) {
struct dirent *ent;
while ((ent = readdir(d)) != NULL) {
char full[1024];
if (strncmp(ent->d_name, "ssh_host_", 9) != 0)
continue;
if (strstr(ent->d_name, "_key") == NULL)
continue;
snprintf(full, sizeof(full), "%.800s/%.160s", path,
ent->d_name);
key_private_check(&ctx, full);
}
closedir(d);
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"root\":");
apex_json_str(&b, base);
mcp_buf_printf(&b, ",\"files_scanned\":%d,\"keys\":%d,"
"\"findings_count\":%d,\"findings\":[",
ctx.files, ctx.keys, 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, "
@@ -2390,6 +2673,18 @@ const mcp_tool TOOLS_BLUE[] = {
"\"limit\":{\"type\":\"integer\",\"description\":\"max ports, default "
"500\"}}}",
t_net_baseline },
{ "ssh_key_audit",
"Audit SSH key material on the local host (optional root prefix for a "
"mounted image): authorized_keys under /etc/ssh, /root/.ssh, "
"/home/*/.ssh and the state dir, plus private keys (id_* and "
"/etc/ssh/ssh_host_*_key). Flags unrestricted keys (no from=/command=/"
"restrict), ssh-rsa and ssh-dss key types, duplicate keys and private "
"keys readable beyond their owner. Read-only.",
"{\"type\":\"object\",\"properties\":{"
"\"root\":{\"type\":\"string\",\"description\":\"prefix, default empty\"},"
"\"limit\":{\"type\":\"integer\",\"description\":\"key files to read, "
"default 200\"}}}",
t_ssh_key_audit },
};
const size_t TOOLS_BLUE_N = sizeof(TOOLS_BLUE) / sizeof(TOOLS_BLUE[0]);
+335
View File
@@ -1673,6 +1673,330 @@ static void t_dns_zone_transfer(mcp_conn *c, const mcp_json *args, void *user)
apex_proc_free(&p);
}
/* ---------------------------------------------------------------- ldap_probe */
typedef struct {
char name[64];
char value[256];
} ldap_attr;
/* Read one BER TLV; returns the tag, stores the content, -1 on error. */
static int ber_read(int fd, unsigned char *buf, size_t cap, size_t *len)
{
unsigned char head[2];
size_t l;
size_t k;
size_t off;
if (apex_net_exact(fd, head, 2) != 0)
return -1;
if ((head[1] & 0x80) != 0) {
unsigned char lb[4];
k = head[1] & 0x7f;
if (k == 0 || k > 3)
return -1;
if (apex_net_exact(fd, lb, k) != 0)
return -1;
l = 0;
for (off = 0; off < k; off++)
l = (l << 8) | lb[off];
} else {
l = head[1];
}
if (l > cap)
return -1;
if (apex_net_exact(fd, buf, l) != 0)
return -1;
*len = l;
return head[0];
}
/* One tag/length/value out of a buffer. */
static int ber_next(const unsigned char *buf, size_t n, size_t *off,
unsigned char *tag, const unsigned char **val,
size_t *vlen)
{
size_t o = *off;
size_t l;
if (o + 2 > n)
return -1;
*tag = buf[o++];
if ((buf[o] & 0x80) != 0) {
size_t k = buf[o++] & 0x7f;
size_t m;
if (k == 0 || k > 3 || o + k > n)
return -1;
l = 0;
for (m = 0; m < k; m++)
l = (l << 8) | buf[o++];
} else {
l = buf[o++];
}
if (o + l > n)
return -1;
*val = buf + o;
*vlen = l;
*off = o + l;
return 0;
}
static int ldap_result_code(const unsigned char *buf, size_t n, int *code)
{
size_t off = 0;
unsigned char tag;
const unsigned char *val;
size_t vlen;
size_t o2 = 0;
*code = -1;
if (ber_next(buf, n, &off, &tag, &val, &vlen) != 0)
return 0; /* messageID */
if (ber_next(buf, n, &off, &tag, &val, &vlen) != 0)
return 0; /* protocol op */
if (tag != 0x61 && tag != 0x65)
return 0;
if (ber_next(val, vlen, &o2, &tag, &val, &vlen) != 0 ||
tag != 0x0a || vlen < 1)
return 0;
*code = val[0];
return 1;
}
static void ldap_attr_add(ldap_attr *attrs, int *n, const char *name,
const unsigned char *val, size_t vlen)
{
int i;
size_t w = 0;
for (i = 0; i < *n; i++)
if (strcmp(attrs[i].name, name) == 0)
return;
if (*n >= 16)
return;
snprintf(attrs[*n].name, sizeof(attrs[*n].name), "%.48s", name);
while (w < vlen && w + 1 < sizeof(attrs[*n].value)) {
unsigned char ch = val[w];
attrs[*n].value[w] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : ' ';
w++;
}
attrs[*n].value[w] = '\0';
(*n)++;
}
static void ldap_parse_entry(const unsigned char *buf, size_t n,
ldap_attr *attrs, int *nattrs)
{
size_t off = 0;
unsigned char tag;
const unsigned char *val;
size_t vlen;
const unsigned char *list;
size_t list_len;
size_t aoff = 0;
if (ber_next(buf, n, &off, &tag, &val, &vlen) != 0 || tag != 0x04)
return; /* objectName */
if (ber_next(buf, n, &off, &tag, &val, &vlen) != 0 || tag != 0x30)
return;
list = val;
list_len = vlen;
while (aoff < list_len) {
const unsigned char *attr;
size_t attr_len;
size_t ioff = 0;
unsigned char itag;
const unsigned char *name;
size_t name_len;
const unsigned char *set;
size_t set_len;
char cname[64];
if (ber_next(list, list_len, &aoff, &itag, &attr, &attr_len) != 0 ||
itag != 0x30)
break;
if (ber_next(attr, attr_len, &ioff, &itag, &name, &name_len) != 0 ||
itag != 0x04)
continue;
if (ber_next(attr, attr_len, &ioff, &itag, &set, &set_len) != 0 ||
itag != 0x31)
continue;
snprintf(cname, sizeof(cname), "%.*s",
(int)(name_len < 48 ? name_len : 48),
(const char *)name);
{
size_t voff = 0;
unsigned char vtag;
const unsigned char *vval;
size_t vvlen;
if (ber_next(set, set_len, &voff, &vtag, &vval, &vvlen) == 0 &&
vtag == 0x04)
ldap_attr_add(attrs, nattrs, cname, vval, vvlen);
}
}
}
static void t_ldap_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", 389);
unsigned char bind_req[16];
unsigned char search_req[128];
unsigned char resp[8192];
size_t rlen;
int fd;
int tag;
int bind_code = -1;
int anonymous = 0;
int root_dse = 0;
ldap_attr attrs[16];
int nattrs = 0;
int rounds;
mcp_buf b;
int i;
int first;
(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, "ldap_probe", target, port))
return;
fd = tcp_connect_host(target, port, 6000);
if (fd < 0) {
mcp_reply_error(c, "cannot connect to the LDAP service");
return;
}
/* anonymous simple bind, LDAPv3 */
{
static const unsigned char bind[] = {
0x30, 0x07, 0x02, 0x01, 0x03, 0x04, 0x00, 0x80, 0x00
};
memcpy(bind_req, bind, sizeof(bind));
}
if (write(fd, bind_req, 9) != 9) {
close(fd);
mcp_reply_error(c, "cannot send the bind request");
return;
}
tag = ber_read(fd, resp, sizeof(resp), &rlen);
if (tag != 0x30 || !ldap_result_code(resp, rlen, &bind_code)) {
close(fd);
mcp_reply_error(c, "no LDAP bind response");
return;
}
anonymous = bind_code == 0;
/* rootDSE search: baseObject "", scope base, present(objectClass) */
if (anonymous) {
unsigned char inner[96];
size_t n = 0;
unsigned char sr[128];
size_t srl;
unsigned char msg[160];
size_t ml;
inner[n++] = 0x04;
inner[n++] = 0x00;
inner[n++] = 0x02;
inner[n++] = 0x01;
inner[n++] = 0x00;
inner[n++] = 0x02;
inner[n++] = 0x01;
inner[n++] = 0x00;
inner[n++] = 0x02;
inner[n++] = 0x01;
inner[n++] = 0x00;
inner[n++] = 0x02;
inner[n++] = 0x01;
inner[n++] = 0x00;
inner[n++] = 0x02;
inner[n++] = 0x01;
inner[n++] = 0x01;
inner[n++] = 0x87;
inner[n++] = 0x0b;
memcpy(inner + n, "objectClass", 11);
n += 11;
inner[n++] = 0x30;
inner[n++] = 0x00;
srl = ber_tlv(sr, 0x60, inner, n);
{
unsigned char mc[128];
size_t m = 0;
mc[m++] = 0x02;
mc[m++] = 0x01;
mc[m++] = 0x02;
memcpy(mc + m, sr, srl);
m += srl;
ml = ber_tlv(msg, 0x30, mc, m);
}
memcpy(search_req, msg, ml);
if (write(fd, search_req, ml) == (ssize_t)ml) {
for (rounds = 0; rounds < 8; rounds++) {
tag = ber_read(fd, resp, sizeof(resp), &rlen);
if (tag < 0)
break;
if (tag == 0x30 && rlen > 2) {
size_t off = 0;
unsigned char t2;
const unsigned char *v2;
size_t l2;
/* skip messageID, then look at the protocol op */
if (ber_next(resp, rlen, &off, &t2, &v2, &l2) == 0 &&
ber_next(resp, rlen, &off, &t2, &v2, &l2) == 0) {
if (t2 == 0x64) {
root_dse = 1;
ldap_parse_entry(v2, l2, attrs,
&nattrs);
} else if (t2 == 0x65) {
break;
}
}
}
}
}
}
close(fd);
if (anonymous)
apex_audit("ldap_probe", target, port, 0,
"anonymous bind accepted", "LDAPv3 simple bind");
else
apex_audit("ldap_probe", target, port, 1,
"anonymous bind rejected", "LDAPv3 simple bind");
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"ldap\":true,\"bind_result\":%d,"
"\"anonymous\":%s,\"root_dse\":%s,\"attributes\":[",
port, bind_code, anonymous ? "true" : "false",
root_dse ? "true" : "false");
first = 1;
for (i = 0; i < nattrs; i++) {
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"name\":");
apex_json_str(&b, attrs[i].name);
mcp_buf_puts(&b, ",\"value\":");
apex_json_str(&b, attrs[i].value);
mcp_buf_puts(&b, "}");
}
mcp_buf_puts(&b, "]}");
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 "
@@ -1758,6 +2082,17 @@ const mcp_tool TOOLS_PROTO[] = {
"return, default 500\"}},"
"\"required\":[\"server\",\"zone\"]}",
t_dns_zone_transfer },
{ "ldap_probe",
"Send an LDAPv3 anonymous simple bind, then (if accepted) a rootDSE "
"search for baseObject \"\" with the present(objectClass) filter and "
"report namingContexts, vendorName, supportedLDAPVersion and the other "
"attributes the server returns. An accepted anonymous bind is audited. "
"No credentials and no writes. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 389\"}},"
"\"required\":[\"target\"]}",
t_ldap_probe },
};
const size_t TOOLS_PROTO_N = sizeof(TOOLS_PROTO) / sizeof(TOOLS_PROTO[0]);
+381
View File
@@ -2048,6 +2048,352 @@ static void t_host_header_injection(mcp_conn *c, const mcp_json *args,
mcp_buf_free(&b);
}
/* ---------------------------------------------------------------- ssti_probe */
typedef struct {
const char *kind;
const char *payload;
const char *expected;
const char *engine;
} ssti_payload;
static const ssti_payload SSTI_PAYLOADS[] = {
{ "jinja-twig", "{{1337*7}}", "9359", "Jinja2/Twig/Nunjucks" },
{ "el-freemarker", "${1337*7}", "9359", "FreeMarker/JSP EL/Thymeleaf" },
{ "jsf-ruby", "#{1337*7}", "9359", "JSF/Ruby" },
{ "erb-ejs", "<%= 1337*7 %>", "9359", "ERB/EJS" },
{ "jinja-string", "{{1337*'7'}}", "1337133713371337", "Jinja2 string repeat" },
};
static void t_ssti_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");
const char *method = mcp_arg_string(args, "method");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
int delay = mcp_arg_int(args, "delay_ms", 100);
int is_post;
char marker[48];
int baseline_contaminated = 0;
mcp_buf b;
int first = 1;
int tested = 0;
int evaluated = 0;
int saved = 0;
int i;
(void)user;
if (target == NULL || *target == '\0' || param == NULL || *param == '\0') {
mcp_reply_error(c, "target and param are required");
return;
}
if (path == NULL || *path == '\0')
path = "/";
if (path[0] != '/') {
mcp_reply_error(c, "path must start with /");
return;
}
if (delay < 0 || delay > 1000)
delay = 100;
is_post = method != NULL && strcasecmp(method, "POST") == 0;
if (!gated(c, "ssti_probe", target, port))
return;
snprintf(marker, sizeof(marker), "apexSSTI%ld", (long)getpid());
/* baseline: does the page already contain the expected numbers? */
{
char req[1200];
char status[256];
char *resp = NULL;
size_t len = 0;
mcp_buf enc;
mcp_buf_init(&enc);
url_enc(&enc, marker);
if (is_post)
snprintf(req, sizeof(req), "%s", path);
else {
const char *sep = strchr(path, '?') != NULL ? "&" : "?";
snprintf(req, sizeof(req), "%s%s%s=%s", path, sep, param,
enc.p != NULL ? enc.p : "");
}
status[0] = '\0';
if (apex_http_once(target, port, tls, is_post ? "POST" : "GET", req,
is_post ? enc.p : NULL,
is_post ? "Content-Type: application/"
"x-www-form-urlencoded\r\n" : NULL,
8000, &resp, &len, status, sizeof(status)) == 0) {
if (find_bytes(resp, len, "9359") ||
find_bytes(resp, len, "133713371337"))
baseline_contaminated = 1;
free(resp);
}
mcp_buf_free(&enc);
}
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port);
apex_json_str(&b, path);
mcp_buf_puts(&b, ",\"param\":");
apex_json_str(&b, param);
mcp_buf_printf(&b, ",\"method\":\"%s\",\"baseline_contaminated\":%s,"
"\"results\":[", is_post ? "POST" : "GET",
baseline_contaminated ? "true" : "false");
for (i = 0; i < (int)(sizeof(SSTI_PAYLOADS) / sizeof(SSTI_PAYLOADS[0]));
i++) {
char req[1600];
char status[256];
char *resp = NULL;
size_t len = 0;
int code;
int ev;
int reflected;
int err;
int flags = 0;
int first_sig = 1;
mcp_buf enc;
mcp_buf body;
mcp_buf signals;
char *evidence = NULL;
mcp_buf_init(&enc);
url_enc(&enc, SSTI_PAYLOADS[i].payload);
mcp_buf_init(&body);
if (is_post) {
mcp_buf_printf(&body, "%s=%s", param,
enc.p != NULL ? enc.p : "");
snprintf(req, sizeof(req), "%s", path);
} else {
const char *sep = strchr(path, '?') != NULL ? "&" : "?";
snprintf(req, sizeof(req), "%s%s%s=%s", path, sep, param,
enc.p != NULL ? enc.p : "");
}
status[0] = '\0';
if (apex_http_once(target, port, tls, is_post ? "POST" : "GET", req,
is_post ? body.p : NULL,
is_post ? "Content-Type: application/"
"x-www-form-urlencoded\r\n" : NULL,
8000, &resp, &len, status, sizeof(status)) != 0) {
mcp_buf_free(&enc);
mcp_buf_free(&body);
continue;
}
tested++;
code = apex_status_code(status);
ev = find_bytes(resp, len, SSTI_PAYLOADS[i].expected) &&
!baseline_contaminated;
reflected = find_bytes(resp, len, SSTI_PAYLOADS[i].payload);
err = any_sig(resp, len, TPL_SIGS);
mcp_buf_init(&signals);
if (ev) {
apex_json_str(&signals, "evaluated");
flags++;
}
if (reflected) {
if (flags > 0)
mcp_buf_puts(&signals, ",");
apex_json_str(&signals, "reflected");
flags++;
}
if (err) {
if (flags > 0)
mcp_buf_puts(&signals, ",");
apex_json_str(&signals, "template-error");
flags++;
}
(void)first_sig;
if (ev) {
evaluated++;
if (saved < 3) {
char label[64];
snprintf(label, sizeof(label), "ssti-%.16s",
SSTI_PAYLOADS[i].kind);
evidence = apex_evidence_save(label, resp, len);
saved++;
}
}
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"payload\":");
apex_json_str(&b, SSTI_PAYLOADS[i].kind);
mcp_buf_printf(&b, ",\"status\":%d,\"bytes\":%lu,\"evaluated\":%s,"
"\"reflected\":%s,\"engine\":",
code, (unsigned long)len, ev ? "true" : "false",
reflected ? "true" : "false");
apex_json_str(&b, ev ? SSTI_PAYLOADS[i].engine : "");
mcp_buf_puts(&b, ",\"signals\":[");
if (signals.p != NULL)
mcp_buf_add(&b, signals.p, signals.len);
mcp_buf_puts(&b, "],\"evidence\":");
if (evidence != NULL)
apex_json_str(&b, evidence);
else
mcp_buf_puts(&b, "null");
mcp_buf_puts(&b, "}");
free(evidence);
mcp_buf_free(&signals);
mcp_buf_free(&enc);
mcp_buf_free(&body);
free(resp);
if (delay > 0 && i + 1 < (int)(sizeof(SSTI_PAYLOADS) /
sizeof(SSTI_PAYLOADS[0])))
sleep_ms(delay);
}
mcp_buf_printf(&b, "],\"tested\":%d,\"evaluated_count\":%d}",
tested, evaluated);
apex_audit("ssti_probe", target, port, evaluated == 0,
evaluated == 0 ? "no template evaluation"
: "template payload evaluated", path);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
/* ------------------------------------------------------------------ xxe_probe */
static const char *XXE_SIGS[] = {
"DOCTYPE is disallowed", "External entity", "entity reference",
"XML parse error", "parser error", "SAXParseException",
"Invalid URI", "DTD is prohibited", NULL
};
static void t_xxe_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 *field = mcp_arg_string(args, "post_field");
int port = mcp_arg_int(args, "port", 80);
int tls = mcp_arg_bool(args, "tls", apex_looks_tls(port));
int wait_ms = mcp_arg_int(args, "wait_ms", 1200);
int cbport = 0;
int ls;
char token[64];
mcp_buf b;
int first = 1;
int confirmed = 0;
int probe;
(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 (wait_ms < 200 || wait_ms > 5000)
wait_ms = 1200;
if (!gated(c, "xxe_probe", target, port))
return;
ls = cb_open(&cbport);
if (ls < 0) {
mcp_reply_error(c, "cannot open the callback listener");
return;
}
snprintf(token, sizeof(token), "apex%ld", (long)getpid());
mcp_buf_init(&b);
mcp_buf_puts(&b, "{\"target\":");
apex_json_str(&b, target);
mcp_buf_printf(&b, ",\"port\":%d,\"path\":", port);
apex_json_str(&b, path);
mcp_buf_printf(&b, ",\"callback_port\":%d,\"probes\":[", cbport);
for (probe = 0; probe < 2; probe++) {
char url[300];
char xml[1024];
char inj[4096];
char status[256];
char *resp = NULL;
size_t len = 0;
int code = 0;
int evaluated = 0;
int error_sig = 0;
int reflected = 0;
char *evidence = NULL;
mcp_buf enc;
snprintf(url, sizeof(url), "http://127.0.0.1:%d/%s-%d", cbport,
token, probe);
if (probe == 0) {
snprintf(xml, sizeof(xml),
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE foo [<!ENTITY xxe SYSTEM \"%s\">]>\n"
"<foo>&xxe;</foo>\n", url);
} else {
snprintf(xml, sizeof(xml),
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE foo [<!ENTITY xxe SYSTEM \"%s\">]>\n"
"<foo bar=\"&xxe;\"/>\n", url);
}
if (field != NULL && *field != '\0') {
mcp_buf_init(&enc);
url_enc(&enc, xml);
snprintf(inj, sizeof(inj), "%s=%s", field,
enc.p != NULL ? enc.p : "");
mcp_buf_free(&enc);
} else {
snprintf(inj, sizeof(inj), "%s", xml);
}
status[0] = '\0';
if (apex_http_once(target, port, tls, "POST", path, inj,
(field != NULL && *field != '\0')
? "Content-Type: application/x-www-form-"
"urlencoded\r\n"
: "Content-Type: application/xml\r\n",
10000, &resp, &len, status,
sizeof(status)) == 0) {
char req[1024];
code = apex_status_code(status);
error_sig = any_sig(resp, len, XXE_SIGS);
reflected = find_bytes(resp, len, "&xxe;");
if (cb_wait(ls, wait_ms, req, sizeof(req))) {
char want[96];
snprintf(want, sizeof(want), "%s-%d", token, probe);
if (strstr(req, want) != NULL) {
evaluated = 1;
confirmed = 1;
evidence = apex_evidence_save("xxe-callback", req,
strlen(req));
}
}
free(resp);
}
if (!first)
mcp_buf_puts(&b, ",");
first = 0;
mcp_buf_puts(&b, "{\"kind\":");
apex_json_str(&b, probe == 0 ? "element" : "attribute");
mcp_buf_printf(&b, ",\"status\":%d,\"evaluated\":%s,"
"\"error_signature\":%s,\"reflected\":%s,"
"\"evidence\":", code,
evaluated ? "true" : "false",
error_sig ? "true" : "false",
reflected ? "true" : "false");
if (evidence != NULL)
apex_json_str(&b, evidence);
else
mcp_buf_puts(&b, "null");
mcp_buf_puts(&b, "}");
free(evidence);
}
close(ls);
mcp_buf_printf(&b, "],\"confirmed\":%s}", confirmed ? "true" : "false");
apex_audit("xxe_probe", target, port, confirmed,
confirmed ? "external entity was fetched"
: "no external entity callback", path);
mcp_reply_json(c, b.p);
mcp_buf_free(&b);
}
const mcp_tool TOOLS_RED[] = {
{ "vuln_check",
"Non-destructive verification of exposed artifacts on one web target: "
@@ -2229,6 +2575,41 @@ const mcp_tool TOOLS_RED[] = {
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_host_header_injection },
{ "ssti_probe",
"Send five template payloads ({{1337*7}}, ${1337*7}, #{1337*7}, "
"<%= 1337*7 %>, {{1337*'7'}}) through one parameter and check for the "
"evaluated result (9359 or a repeated 1337), a reflected payload or a "
"template error. A baseline request first clears pages that already "
"contain the numbers. GET query or POST form, evaluations saved as "
"evidence. Gate: the target must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"param\":{\"type\":\"string\"},"
"\"method\":{\"type\":\"string\",\"enum\":[\"GET\",\"POST\"],"
"\"description\":\"default GET\"},"
"\"delay_ms\":{\"type\":\"integer\",\"description\":\"default 100\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\",\"param\"]}",
t_ssti_probe },
{ "xxe_probe",
"POST an XML body with a DOCTYPE external entity that points at a "
"loopback listener this process opens, in element and attribute form. A "
"callback proves the parser resolved the entity; the request line is "
"saved as evidence. Optionally wrap the XML in a form field. Also "
"reports parser error signatures and entity reflection. Gate: the target "
"must be in scope.",
"{\"type\":\"object\",\"properties\":{"
"\"target\":{\"type\":\"string\"},"
"\"port\":{\"type\":\"integer\",\"description\":\"default 80\"},"
"\"path\":{\"type\":\"string\",\"description\":\"default /\"},"
"\"post_field\":{\"type\":\"string\",\"description\":\"form field "
"that carries the XML; default raw body\"},"
"\"wait_ms\":{\"type\":\"integer\",\"description\":\"default 1200\"},"
"\"tls\":{\"type\":\"boolean\"}},"
"\"required\":[\"target\"]}",
t_xxe_probe },
};
const size_t TOOLS_RED_N = sizeof(TOOLS_RED) / sizeof(TOOLS_RED[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 = 81
EXPECTED_TOOLS = 85
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.
+235 -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("81 tools registered", len(tools) == 81, len(tools))
check("85 tools registered", len(tools) == 85, 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"]) == 81)
check("http tools/list", len(listing["result"]["tools"]) == 85)
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
@@ -3849,6 +3849,239 @@ adv_srv.shutdown()
adv_srv.server_close()
shutil.rmtree(adv_home, ignore_errors=True)
print("\n== template, XXE, LDAP and SSH key checks ==")
class _SstiHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parts = urllib.parse.urlsplit(self.path)
value = urllib.parse.parse_qs(parts.query).get("t", [""])[0]
if parts.path == "/jinja":
body = ("out:9359" if "{{1337*7}}" in value
else "echo:" + value).encode()
elif parts.path == "/el":
body = ("out:9359" if "${1337*7}" in value
else "echo:" + value).encode()
else:
body = b"static page"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class _XxeHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
need = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(need)
parts = urllib.parse.urlsplit(self.path)
if parts.path == "/xml" and b"<!ENTITY" in body:
m = re.search(rb'SYSTEM "(http://[^"]+)"', body)
if m:
try:
urllib.request.urlopen(m.group(1).decode(),
timeout=3).read()
except Exception:
pass
answer = b"parsed"
self.send_response(200)
self.send_header("Content-Length", str(len(answer)))
self.end_headers()
self.wfile.write(answer)
def log_message(self, *args):
pass
def ber_len(n):
if n < 128:
return bytes([n])
if n < 256:
return bytes([0x81, n])
return bytes([0x82, (n >> 8) & 0xff, n & 0xff])
def ber_tlv(tag, content):
return bytes([tag]) + ber_len(len(content)) + content
def ldap_attribute(name, value):
return ber_tlv(0x30, ber_tlv(0x04, name.encode()) +
ber_tlv(0x31, ber_tlv(0x04, value.encode())))
def ldap_read_message(conn):
head = conn.recv(2)
if len(head) < 2:
return None
length = head[1]
if length & 0x80:
k = length & 0x7f
raw = b""
while len(raw) < k:
chunk = conn.recv(k - len(raw))
if not chunk:
return None
raw += chunk
length = int.from_bytes(raw, "big")
body = b""
while len(body) < length:
chunk = conn.recv(length - len(body))
if not chunk:
return None
body += chunk
return body
def ldap_handler(reject):
def handle(conn):
ldap_read_message(conn)
code = 49 if reject else 0
bind_body = b"\x0a\x01" + bytes([code]) + b"\x04\x00" + b"\x04\x00"
conn.sendall(ber_tlv(0x30, b"\x02\x01\x01" +
ber_tlv(0x61, bind_body)))
if reject:
return
ldap_read_message(conn)
entry_body = (b"\x04\x00" +
ber_tlv(0x30,
ldap_attribute("namingContexts",
"dc=example,dc=test") +
ldap_attribute("vendorName", "TestLDAP") +
ldap_attribute("supportedLDAPVersion", "3")))
entry = ber_tlv(0x30, b"\x02\x01\x02" + ber_tlv(0x64, entry_body))
done = ber_tlv(0x30, b"\x02\x01\x02" +
ber_tlv(0x65, b"\x0a\x01\x00\x04\x00\x04\x00"))
conn.sendall(entry + done)
return handle
ssti_srv = http.server.HTTPServer(("127.0.0.1", 0), _SstiHandler)
ssti_port = ssti_srv.server_address[1]
threading.Thread(target=ssti_srv.serve_forever, daemon=True).start()
xxe_srv = http.server.HTTPServer(("127.0.0.1", 0), _XxeHandler)
xxe_port = xxe_srv.server_address[1]
threading.Thread(target=xxe_srv.serve_forever, daemon=True).start()
ldap_srv, ldap_port = start_line_server(ldap_handler(False))
ldap_reject_srv, ldap_reject_port = start_line_server(ldap_handler(True))
key_root = tempfile.mkdtemp(prefix="apex-keys-")
ssh_alice = os.path.join(key_root, "home", "alice", ".ssh")
ssh_etc = os.path.join(key_root, "etc", "ssh")
os.makedirs(ssh_alice)
os.makedirs(ssh_etc)
alice_keys = os.path.join(ssh_alice, "authorized_keys")
with open(alice_keys, "w") as f:
f.write("ssh-ed25519 AAAAB3NzaC1lZDI1NTE5AAAAIAliceKey alice@host\n")
f.write('from="10.0.0.0/8" ssh-ed25519 '
"AAAAB3NzaC1lZDI1NTE5AAAAIBobKey bob@host\n")
f.write("ssh-ed25519 AAAAB3NzaC1lZDI1NTE5AAAAIAliceKey dup@host\n")
f.write("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAAliceRsa old@host\n")
with open(os.path.join(ssh_etc, "authorized_keys"), "w") as f:
f.write('command="/usr/bin/backup" ssh-ed25519 '
"AAAAB3NzaC1lZDI1NTE5AAAAIBackupKey backup\n")
id_rsa = os.path.join(ssh_alice, "id_rsa")
with open(id_rsa, "w") as f:
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nzzz\n")
os.chmod(id_rsa, 0o644)
id_ed = os.path.join(ssh_alice, "id_ed25519")
with open(id_ed, "w") as f:
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nyyy\n")
os.chmod(id_ed, 0o600)
host_key = os.path.join(ssh_etc, "ssh_host_rsa_key")
with open(host_key, "w") as f:
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nxxx\n")
os.chmod(host_key, 0o640)
sec_home = tempfile.mkdtemp(prefix="apex-sec-")
write_scope(sec_home, {"label": "sec", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(ssti_port), str(xxe_port),
str(ldap_port),
str(ldap_reject_port)]})
res, _ = run([
call(1, "ssti_probe", target="127.0.0.1", port=ssti_port, path="/jinja",
param="t", delay_ms=0, tls=False),
call(2, "ssti_probe", target="127.0.0.1", port=ssti_port, path="/el",
param="t", delay_ms=0, tls=False),
call(3, "ssti_probe", target="127.0.0.1", port=ssti_port, path="/plain",
param="t", delay_ms=0, tls=False),
call(4, "xxe_probe", target="127.0.0.1", port=xxe_port, path="/xml",
wait_ms=600, tls=False),
call(5, "xxe_probe", target="127.0.0.1", port=xxe_port, path="/safe-xml",
wait_ms=300, tls=False),
call(6, "ldap_probe", target="127.0.0.1", port=ldap_port),
call(7, "ldap_probe", target="127.0.0.1", port=ldap_reject_port),
call(8, "ssti_probe", target="198.51.100.9", port=80, param="t"),
call(9, "ssh_key_audit", root=key_root),
], home=sec_home)
by_id = {r.get("id"): r for r in res}
jinja = json.loads(text(by_id[1]))
jinja_hit = [r for r in jinja["results"] if r["evaluated"]]
check("ssti_probe evaluates the Jinja payload",
jinja["evaluated_count"] == 1 and jinja_hit and
jinja_hit[0]["payload"] == "jinja-twig" and
"Jinja2" in jinja_hit[0]["engine"], jinja)
check("ssti_probe keeps the evaluation as evidence",
jinja_hit[0]["evidence"] and os.path.isfile(jinja_hit[0]["evidence"]),
jinja_hit[0])
el = json.loads(text(by_id[2]))
el_hit = [r for r in el["results"] if r["evaluated"]]
check("ssti_probe evaluates the EL payload",
el["evaluated_count"] == 1 and el_hit and
el_hit[0]["payload"] == "el-freemarker", el)
plain_ssti = json.loads(text(by_id[3]))
check("ssti_probe finds nothing on a static page",
plain_ssti["evaluated_count"] == 0 and plain_ssti["tested"] == 5,
plain_ssti)
xxe = json.loads(text(by_id[4]))
check("xxe_probe resolves the external entity",
xxe["confirmed"] is True and
any(p["evaluated"] for p in xxe["probes"]), xxe)
check("xxe_probe keeps the callback as evidence",
any(p["evidence"] and os.path.isfile(p["evidence"])
for p in xxe["probes"]), xxe["probes"])
safe_xxe = json.loads(text(by_id[5]))
check("xxe_probe finds nothing on a safe endpoint",
safe_xxe["confirmed"] is False, safe_xxe)
ldap = json.loads(text(by_id[6]))
ldap_attrs = {a["name"]: a["value"] for a in ldap["attributes"]}
check("ldap_probe accepts the anonymous bind",
ldap["anonymous"] is True and ldap["bind_result"] == 0, ldap)
check("ldap_probe reads the rootDSE attributes",
ldap["root_dse"] is True and
ldap_attrs.get("namingContexts") == "dc=example,dc=test" and
ldap_attrs.get("vendorName") == "TestLDAP", ldap)
ldap_no = json.loads(text(by_id[7]))
check("ldap_probe reports a rejected anonymous bind",
ldap_no["anonymous"] is False and ldap_no["bind_result"] == 49 and
ldap_no["root_dse"] is False, ldap_no)
check("ssti_probe refuses an out-of-scope target", err(by_id[8]),
text(by_id[8]))
keys = json.loads(text(by_id[9]))
kinds = [f["kind"] for f in keys["findings"]]
check("ssh_key_audit reads both authorized_keys files",
keys["files_scanned"] == 2 and keys["keys"] == 5, keys)
check("ssh_key_audit flags unrestricted keys", kinds.count("unrestricted") == 3,
kinds)
check("ssh_key_audit flags the ssh-rsa key", "weak-key-type" in kinds, kinds)
check("ssh_key_audit flags the duplicate key", "duplicate-key" in kinds, kinds)
private = [f for f in keys["findings"]
if f["kind"] == "private-key-permissions"]
check("ssh_key_audit flags loose private-key permissions",
len(private) == 2 and
all(f["path"] != id_ed for f in private), private)
for srv in (ssti_srv, xxe_srv):
srv.shutdown()
srv.server_close()
ldap_srv.close()
ldap_reject_srv.close()
shutil.rmtree(key_root, ignore_errors=True)
shutil.rmtree(sec_home, 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"})