apex-twin 1.100.0: auth_test over six protocols, SIGPIPE fix

Authentication testing in src/tools_auth.c (new file, 16th table): auth_test
speaks http Basic, ftp, smtp AUTH LOGIN, imap, pop3 and mysql
(mysql_native_password) against one in-scope service. The operator supplies
the wordlists (inline or file) and every limit - delay_ms, max_attempts,
stop_on_hit, lockout_limit, timeout_ms; the program adds none of its own.
auth_plan counts a run without connecting, auth_protocols lists the
protocols, auth_hits returns the credential findings with evidence paths.
A hit is the protocol's own accept answer; each accepted pair becomes a
critical finding with the pair and the answer in evidence, while the audit
log keeps the account and service and never the password.

Two real bugs found by the tests they came with:

- An HTTP answer below 400 counted as a hit, so a 404 or a 500 would have
  been reported as valid credentials. Only 2xx/3xx prove authentication
  now; two checks pin it and fail against the old logic.
- SIGPIPE killed the whole server when a target hung up mid-write: one
  dead target, one dead MCP server. Ignored once at startup, so the write
  returns EPIPE and the tool reports a failed connection. Five checks, one
  per protocol.

SHA1 for the MySQL scramble is written out in the file and checked against
the published vectors for "", "abc", "password" and a 1000-byte multi-block
input. The MySQL seed is read by counting handshake fields; a fixed offset
picked up the capability flags and made every login fail against a healthy
server, which the suite proves by neutralising the offset.

427 tools, 1637 end-to-end checks, 84.7% line coverage.
release-check exit 0, distcheck 1.100.0 passes 1637/1637 from the tarball.
This commit is contained in:
lotherk committed 2026-11-24 06:45:02 +00:00
1 parent 759d9f8351
commit 59b71ab3a1
11 files changed
+2730 -16

No files matched your search

+37
View File
@@ -1,3 +1,40 @@
## 1.100.0 - 2026-11-24 - this change
- **Authentication testing** (`auth_test`): real login attempts against one
in-scope service over http (Basic), ftp, smtp (AUTH LOGIN), imap, pop3 and
mysql (`mysql_native_password`). Wordlists inline or from a file, and the
operator sets `delay_ms`, `max_attempts`, `stop_on_hit`, `lockout_limit` and
`timeout_ms`; the program adds no limit of its own. A hit is the protocol's
accept answer (235, +OK, 230, a1 OK, a MySQL OK packet, an HTTP 2xx/3xx),
never an inference; a 404 or a 500 is a miss, and a dead connection is an
error, not a refused password. Each accepted pair is a critical finding whose evidence
file holds the pair and the answer, while the audit log keeps the account and
the service and never the password.
- **`auth_plan`** counts a run (users, passwords, pairs, delay total, first
users) without connecting. **`auth_protocols`** lists the protocols and
default ports. **`auth_hits`** returns the credential findings with their
evidence paths.
- **SHA1** in `src/tools_auth.c`, needed for the MySQL native-password
scramble. Checked against the published vectors for "", "abc", "password"
and a 1000-byte multi-block input.
- The MySQL seed is read by counting the handshake fields explicitly. Reading
it from a fixed offset picked up the capability flags and made every login
fail against a healthy server; the test suite now proves that specific
regression by neutralising the offset.
- **`SECURITY.md`** no longer describes `cred_test`'s old 20-attempt, 200 ms
limit as if it bounded authentication testing. `auth_test` takes its limits
from the operator, and the document now says so instead of implying a
program-side ceiling that does not exist.
- `SIGPIPE` is ignored at startup. A target that closes the connection
mid-write used to end the whole server with signal 13 - one dead target,
one dead MCP server. Now the write returns `EPIPE` and the tool reports a
failed connection. Five checks pin it, one per protocol.
- An HTTP answer below 400 was accepted as a hit in the first cut of
`auth_test`, so a 404 or a 500 would have been reported as valid
credentials. Only 2xx/3xx prove authentication now, and two checks pin it.
- Four tools in `src/tools_auth.c` (new file, 16th table): 427 tools,
1637 end-to-end checks.
# Changelog
## 1.99.0 - 2026-11-24 - this change
+39 -4
View File
@@ -5,11 +5,11 @@ no Python in the serving path. It gives an agent real reconnaissance and real we
testing behind a scope gate that refuses everything until a rules-of-engagement
file says otherwise.
**423 tools · 1600 end-to-end checks · 240 fuzz cases · 84.8% line coverage · ~1402 KiB**
**427 tools · 1637 end-to-end checks · 240 fuzz cases · 84.7% line coverage · ~1402 KiB**
```
$ ./apex-twin --check
{"version":"1.99.0","tools":423,...,"scope":{"loaded":true,...}}
{"version":"1.100.0","tools":427,...,"scope":{"loaded":true,...}}
```
APEX TWIN was inspired by [ARTEX](https://github.com/Autumn-27/artex) (scope
@@ -156,7 +156,7 @@ closes a request whose head or body does not arrive within
---
## Tools (423)
## Tools (427)
### Scope and bookkeeping
@@ -307,6 +307,10 @@ command in the allowlist: a receiver is a scanner, a transmitter is an attack.
| `vuln_check` | Non-destructive verification of `/.git/HEAD`, `/.env` (keys only, values redacted), directory listing and `phpinfo`; raw response saved as evidence |
| `subdomain_enum` | Built-in wordlist (or your names) under one in-scope domain; every name is gate-checked before it is resolved |
| `cred_test` | HTTP Basic default credentials, max 20 attempts, 200 ms apart, stops on 429, refuses an endpoint that answers without auth |
| `auth_test` | Real login attempts against one in-scope service: http, ftp, smtp, imap, pop3, mysql. Your wordlists, your delay, your attempt ceiling, your stop conditions; a hit is the protocol's own accept code, saved as evidence and recorded as a finding |
| `auth_plan` | Count a credential run (pairs, delay total) without connecting |
| `auth_protocols` | The protocols `auth_test` speaks and their default ports |
| `auth_hits` | The credential findings so far, with the evidence file that holds the pair |
| `vhost_discovery` | Host-header fuzzing against one in-scope IP; reports names whose status, byte count or title differs from the baseline, with evidence |
| `http_brute` | Built-in, comma or file wordlist for hidden paths; 200/201/204/3xx/401/403 are hits, 100 ms apart, evidence for the first five 200s |
| `ssrf_probe` | Injects a URL parameter pointing at its own loopback listener (or your `callback_base`) and confirms a real fetch; never targets metadata endpoints |
@@ -400,6 +404,37 @@ Modules: `shellshock` (CVE-2014-6271), `log4shell` (CVE-2021-44228),
(CVE-2021-41773/42013), `jenkins_script`. The gate decides the target; the
operator decides everything else.
### Authentication testing
`auth_test` tries credentials against one in-scope service. Protocols: `http`
(Basic), `ftp`, `smtp` (AUTH LOGIN), `imap`, `pop3` and `mysql`
(`mysql_native_password`, scrambled the way the server expects).
You supply the users and passwords — inline as a comma list or as a file with
one entry per line — and every knob of the run:
| Parameter | Meaning |
|---|---|
| `users` / `userlist` | comma list, or a file with one user per line |
| `passwords` / `passlist` | the same for passwords |
| `delay_ms` | pause between attempts, default 0 |
| `max_attempts` | hard ceiling, default all pairs |
| `stop_on_hit` | stop at the first accepted pair |
| `lockout_limit` | consecutive rate-limit answers that end the run; 0 disables |
| `timeout_ms` | per connection, default 10000 |
A hit is the protocol saying so: 235, `+OK`, 230, `a1 OK`, a MySQL OK packet,
or an HTTP 2xx/3xx. Anything else is a miss — including a 404 or a 500, which
say nothing about credentials — and a connection that dies is counted as an
error rather than as a refused password.
An accepted pair becomes a `critical` finding whose evidence file holds the
pair and the answer it got; the audit log records the account and the service
but never the password, so the log can be shared and the evidence cannot.
`auth_plan` counts a run before it happens (pairs, delay total, first users)
without connecting. `auth_protocols` lists the protocols and default ports.
`auth_hits` shows the credential findings so far with their evidence paths.
### External scanners (gated wrappers)
| Tool | What it does |
@@ -1204,7 +1239,7 @@ examples/ scope.json
## Status
1.99.0. Built and run: 423 tools, 1600 checks, 240 fuzz cases and 84.8% line
1.100.0. Built and run: 427 tools, 1637 checks, 240 fuzz cases and 84.7% line
coverage. The loop closes: a probe captures the exchange as a pair, a finding
points at it, `finding_update` gives it a state, an asset records the host it
came from, `cors_check`/`cookie_audit`/`http_options` turn a web answer into a
+14 -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.99.x** (`src/apex.h`, `APEX_VERSION`). Security fixes land on the current
is **1.100.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.
@@ -56,10 +56,19 @@ only narrow what the proxy does (the scope gate still runs first).
mid-scan still leaves the intent on disk.
- **Accidental exposure.** Both listeners bind loopback only; the HTTP face and
the proxy do not authenticate.
- **Credential guessing.** `cred_test` makes authentication attempts, but only
against an in-scope HTTP Basic endpoint, at most 20 of them, with a 200 ms
pause, stopping on 429, and it refuses a path that needs no authentication
(nothing to test). Keep the scope and the rules of engagement explicit.
- **A target that hangs up.** `SIGPIPE` is ignored once at startup, so a peer
that closes the connection mid-write returns `EPIPE` to the tool that wrote
and is reported as a failed connection. Without it, one dead target would end
the whole server — the failure mode every network tool would share.
- **Credential guessing.** `cred_test` is the small built-in check: HTTP Basic
only, at most 20 attempts, 200 ms apart. `auth_test` is the real one and has
no built-in rate or attempt limit beyond what the operator passes: the
wordlists, `delay_ms`, `max_attempts`, `stop_on_hit` and `lockout_limit` are
the operator's settings, not the program's opinion. What the program does
guarantee is that every attempt is one gated connection to one in-scope
target, that a hit is the protocol's own accept answer rather than a guess,
and that the password never reaches the audit log. How hard to push, and what
a lockout on the target would cost, is the operator's call.
- **SSRF probing only calls your collector.** `ssrf_probe` injects URLs that
point at its own loopback listener (or `callback_base` you supply). It never
injects cloud metadata addresses and never reads what the target fetches.
+13 -3
View File
@@ -1,5 +1,5 @@
.\" apex-twin.1 - manual page for APEX TWIN
.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.99.0" "User Commands"
.TH APEX-TWIN 1 "2026-11-24" "apex-twin 1.100.0" "User Commands"
.SH NAME
apex-twin \- scope\-gated offensive\-security MCP server
.SH SYNOPSIS
@@ -42,9 +42,19 @@ handle or a config value. Eleven modules ship: shellshock, log4shell, Struts2
S2-045, Tomcat PUT, Redis CONFIG SET, command injection, Apache traversal,
the Jenkins script console, the WebLogic console bypass, CouchDB admin party
and Spring Boot Actuator. A write counts as confirmed only when it is read
back. A confirmed hit writes evidence, a finding and an audit line. Beside it there is offensive
back. A confirmed hit writes evidence, a finding and an audit line.
.PP
.B auth_test
tries credentials against one in-scope service over http (Basic), ftp,
smtp, imap, pop3 or mysql. The wordlists, the delay between attempts, the
attempt ceiling, the stop-on-first-hit and the lockout threshold are the
operator's settings; the program adds no limit of its own. A hit is the
protocol's own accept answer, never a guess: an HTTP 2xx or 3xx, a 235, a
\&+OK, a 230, an "a1 OK" or a MySQL OK packet. A 404 or a 500 is a miss. The
password goes into the evidence file and never into the audit log.
verification (vuln_check, subdomain_enum,
cred_test, vhost_discovery, http_brute, ssrf_probe, jwt_audit, hash_id,
cred_test, auth_test, auth_plan, auth_protocols, auth_hits,
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, ssti_probe,
+12
View File
@@ -132,6 +132,8 @@ static void build_tools(void)
g_tools[n++] = TOOLS_EXT[i];
for (i = 0; i < TOOLS_EXPLOIT_N && n < APEX_MAX_TOOLS; i++)
g_tools[n++] = TOOLS_EXPLOIT[i];
for (i = 0; i < TOOLS_AUTH_N && n < APEX_MAX_TOOLS; i++)
g_tools[n++] = TOOLS_AUTH[i];
g_srv.name = "apex-twin";
g_srv.version = APEX_VERSION;
@@ -482,6 +484,16 @@ int main(int argc, char **argv)
{
int i;
/*
* A peer that hangs up mid-write must not kill the server. Every tool
* that speaks to a socket writes to a peer it does not control, and
* write(2) raises SIGPIPE when that peer is gone; the default action
* ends the process, which would turn one dead target into a dead MCP
* server. Ignored here once, so each write returns EPIPE and the tool
* reports it as a failed connection.
*/
signal(SIGPIPE, SIG_IGN);
apex_config_init();
build_tools();
+1 -1
View File
@@ -15,7 +15,7 @@
#include "mcp.h"
#define APEX_VERSION "1.99.0"
#define APEX_VERSION "1.100.0"
#define APEX_MAX_OUT (1u << 20)
#define APEX_PATH_MAX 512
#define APEX_PATH_FULL 1024
+2
View File
@@ -79,5 +79,7 @@ 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;
extern const mcp_tool TOOLS_AUTH[];
extern const size_t TOOLS_AUTH_N;
#endif /* APEX_TOOLS_H */
+1420
View File
File diff suppressed because it is too large. Load diff
+594
View File
@@ -0,0 +1,594 @@
# ===========================================================================
# authentication testing: six protocols, wordlists, stop conditions
# ===========================================================================
print("\n== authentication testing ==")
import base64 as _b64
import glob
import hashlib as _hashlib
import socketserver as _ss
import threading as _threading
# --------------------------------------------------------------- fixtures
def _auth_scope():
"""A home whose scope allows the loopback ports the fixtures bind."""
home = tempfile.mkdtemp(prefix="apex-auth-")
write_scope(home, {
"label": "auth-suite",
"expires": "2099-12-31T23:59:59Z",
"allow_private": True,
"allow_ip": ["127.0.0.1/32"],
"deny_ip": [],
"allow_domain": [],
"allow_port": list(range(1, 65536)),
"allow_private_ports": list(range(1, 65536)),
})
return home
class _FtpHandler(_ss.StreamRequestHandler):
"""FTP: 331 for a known user, 230 only for the right password."""
users = {"alice": "secret", "bob": "hunter2"}
def handle(self):
self.wfile.write(b"220 fixture FTP ready\r\n")
user = None
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
verb, _, arg = cmd.partition(" ")
verb = verb.upper()
if verb == "USER":
user = arg
if arg in self.users:
self.wfile.write(b"331 need a password\r\n")
else:
self.wfile.write(b"530 no such user\r\n")
elif verb == "PASS":
if user in self.users and self.users[user] == arg:
self.wfile.write(b"230 logged in\r\n")
else:
self.wfile.write(b"530 login incorrect\r\n")
elif verb == "QUIT":
self.wfile.write(b"221 bye\r\n")
return
else:
self.wfile.write(b"500 what\r\n")
class _SmtpHandler(_ss.StreamRequestHandler):
"""SMTP: AUTH LOGIN, 235 for the right pair, 535 otherwise."""
users = {"alice": "secret"}
def handle(self):
self.wfile.write(b"220 fixture ESMTP\r\n")
authed_user = None
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
upper = cmd.upper()
if upper.startswith("EHLO"):
self.wfile.write(b"250-fixture\r\n250-AUTH LOGIN\r\n250 OK\r\n")
elif upper == "AUTH LOGIN":
self.wfile.write(b"334 VXNlcm5hbWU6\r\n")
raw = self.rfile.readline().decode("latin-1").strip()
try:
authed_user = _b64.b64decode(raw).decode("latin-1")
except Exception:
authed_user = None
self.wfile.write(b"334 UGFzc3dvcmQ6\r\n")
raw = self.rfile.readline().decode("latin-1").strip()
try:
pw = _b64.b64decode(raw).decode("latin-1")
except Exception:
pw = None
if self.users.get(authed_user) == pw:
self.wfile.write(b"235 2.7.0 accepted\r\n")
else:
self.wfile.write(b"535 5.7.8 rejected\r\n")
elif upper == "QUIT":
self.wfile.write(b"221 bye\r\n")
return
else:
self.wfile.write(b"250 OK\r\n")
class _ImapHandler(_ss.StreamRequestHandler):
"""IMAP: a1 OK only for the right pair, a1 NO otherwise."""
users = {"alice": "secret"}
def handle(self):
self.wfile.write(b"* OK fixture IMAP ready\r\n")
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
parts = cmd.split(" ")
if len(parts) >= 4 and parts[1].upper() == "LOGIN":
user, pw = parts[2], parts[3]
if self.users.get(user) == pw:
self.wfile.write(b"a1 OK LOGIN completed\r\n")
else:
self.wfile.write(b"a1 NO LOGIN failed\r\n")
elif "LOGOUT" in cmd.upper():
self.wfile.write(b"* BYE\r\n")
return
else:
self.wfile.write(b"a1 BAD unknown\r\n")
class _Pop3Handler(_ss.StreamRequestHandler):
"""POP3: +OK for the right pair, -ERR otherwise."""
users = {"alice": "secret"}
def handle(self):
self.wfile.write(b"+OK fixture POP3 ready\r\n")
user = None
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
verb, _, arg = cmd.partition(" ")
verb = verb.upper()
if verb == "USER":
user = arg
self.wfile.write(b"+OK user accepted\r\n")
elif verb == "PASS":
if self.users.get(user) == arg:
self.wfile.write(b"+OK maildrop locked\r\n")
else:
self.wfile.write(b"-ERR invalid password\r\n")
elif verb == "QUIT":
self.wfile.write(b"+OK bye\r\n")
return
else:
self.wfile.write(b"-ERR what\r\n")
class _MysqlHandler(_ss.StreamRequestHandler):
"""
MySQL: a v10 handshake, then the native-password scramble checked the way
the server does it. The seed is fixed so the test can compute the expected
token itself and prove the client got the algorithm right.
"""
users = {"alice": "secret"}
seed = b"12345678abcdefghijkl"
def handle(self):
payload = bytearray()
payload.append(10) # protocol v10
payload += b"5.7.0-fixture\x00"
payload += b"\x01\x00\x00\x00" # connection id
payload += self.seed[:8] + b"\x00" # part 1 + filler
payload += b"\xff\xf7" # capability, lower
payload += b"\x21" # charset
payload += b"\x02\x00" # status
payload += b"\xff\x81" # capability, upper
payload += b"\x15" # auth plugin data length
payload += b"\x00" * 10 # reserved
payload += self.seed[8:20] + b"\x00"
payload += b"mysql_native_password\x00"
head = bytes([len(payload) & 0xFF, (len(payload) >> 8) & 0xFF,
(len(payload) >> 16) & 0xFF, 0])
self.wfile.write(head + bytes(payload))
head = self.rfile.read(4)
if len(head) < 4:
return
plen = head[0] | (head[1] << 8) | (head[2] << 16)
body = self.rfile.read(plen)
if len(body) < plen:
return
# flags(4) maxpkt(4) charset(1) zeros(23) user NUL token(20)
rest = body[32:]
nul = rest.find(b"\x00")
user = rest[:nul].decode("latin-1")
token = rest[nul + 1:nul + 21]
want = self.users.get(user)
if want is None:
self._err(1045, "Access denied")
return
stage1 = _hashlib.sha1(want.encode()).digest()
stage2 = _hashlib.sha1(stage1).digest()
stage3 = _hashlib.sha1(self.seed + stage2).digest()
expect = bytes(a ^ b for a, b in zip(stage1, stage3))
if token == expect:
ok = b"\x00\x00\x00\x02\x00\x00\x00"
self.wfile.write(bytes([len(ok), 0, 0, 2]) + ok)
else:
self._err(1045, "Access denied")
def _err(self, code, msg):
payload = b"\xff" + bytes([code & 0xFF, (code >> 8) & 0xFF]) + b"#28000" + msg.encode()
self.wfile.write(bytes([len(payload) & 0xFF,
(len(payload) >> 8) & 0xFF,
(len(payload) >> 16) & 0xFF, 2]) + payload)
class _BasicAuthHandler(http.server.BaseHTTPRequestHandler):
"""HTTP Basic: 401 without the right header, 200 with it."""
users = {"alice": "secret"}
def do_GET(self):
hdr = self.headers.get("Authorization", "")
ok = False
if hdr.startswith("Basic "):
try:
raw = _b64.b64decode(hdr[6:]).decode("latin-1")
user, _, pw = raw.partition(":")
ok = self.users.get(user) == pw
except Exception:
ok = False
if ok:
body = b"welcome"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="fixture"')
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
class _RateLimitHandler(_ss.StreamRequestHandler):
"""POP3 that answers -ERR [LOCK] to everything: the lockout fixture."""
def handle(self):
self.wfile.write(b"+OK fixture POP3 ready\r\n")
while True:
line = self.rfile.readline()
if not line:
return
self.wfile.write(b"-ERR maildrop locked, too many attempts\r\n")
class _GoneHandler(http.server.BaseHTTPRequestHandler):
"""The path is gone: 404 for every request, credentials or not."""
def do_GET(self):
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
class _BrokenHandler(http.server.BaseHTTPRequestHandler):
"""The server is broken: 500 for every request."""
def do_GET(self):
self.send_response(500)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
def _serve(handler):
srv = _ss.ThreadingTCPServer(("127.0.0.1", 0), handler)
srv.daemon_threads = True
_threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
class _FtpNoPassHandler(_ss.StreamRequestHandler):
"""FTP that answers 230 to USER alone: some embedded servers do this."""
def handle(self):
self.wfile.write(b"220 no-pass FTP ready\r\n")
while True:
line = self.rfile.readline()
if not line:
return
verb = line.decode("latin-1").split(" ", 1)[0].upper()
if verb == "USER":
self.wfile.write(b"230 anonymous ok\r\n")
elif verb == "QUIT":
self.wfile.write(b"221 bye\r\n")
return
else:
self.wfile.write(b"530 no\r\n")
class _RateLimit429Handler(http.server.BaseHTTPRequestHandler):
"""HTTP that answers 429 to everything: rate limiting, not a login."""
def do_GET(self):
self.send_response(429)
self.send_header("Retry-After", "30")
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
class _HangupHandler(_ss.StreamRequestHandler):
"""Closes the connection the moment it is opened, on every protocol."""
def handle(self):
return
_auth_servers = []
_auth_ports = {}
for _name, _h in (("ftp", _FtpHandler), ("smtp", _SmtpHandler),
("imap", _ImapHandler), ("pop3", _Pop3Handler),
("mysql", _MysqlHandler), ("ratelimit", _RateLimitHandler),
("ftpnopass", _FtpNoPassHandler),
("rl429", _RateLimit429Handler)):
_s = _serve(_h)
_auth_servers.append(_s)
_auth_ports[_name] = _s.server_address[1]
_http_srv = http.server.HTTPServer(("127.0.0.1", 0), _BasicAuthHandler)
_auth_servers.append(_http_srv)
_threading.Thread(target=_http_srv.serve_forever, daemon=True).start()
_auth_ports["http"] = _http_srv.server_address[1]
for _name, _h in (("gone", _GoneHandler), ("broken", _BrokenHandler)):
_s = http.server.HTTPServer(("127.0.0.1", 0), _h)
_auth_servers.append(_s)
_threading.Thread(target=_s.serve_forever, daemon=True).start()
_auth_ports[_name] = _s.server_address[1]
auth_home = _auth_scope()
# wordlists on disk, the form a real run uses
auth_words = tempfile.mkdtemp(prefix="apex-auth-words-")
user_list = os.path.join(auth_words, "users.txt")
pass_list = os.path.join(auth_words, "passes.txt")
with open(user_list, "w") as f:
f.write("# users\nnobody\n\nalice\n")
with open(pass_list, "w") as f:
f.write("wrong\nsecret\n")
blank_list = os.path.join(auth_words, "blank.txt")
with open(blank_list, "w") as f:
f.write("# only a comment\n\n\n")
# ---------------------------------------------------------------- protocol list
res, _ = run([call(1, "auth_protocols")], home=auth_home)
ap = json.loads(text(res[0]))
check("auth_protocols lists the six protocols with their default ports",
[p["name"] for p in ap["protocols"]] ==
["http", "ftp", "smtp", "imap", "pop3", "mysql"] and
{p["name"]: p["default_port"] for p in ap["protocols"]}["mysql"] == 3306,
ap)
# --------------------------------------------------------------------- plan
res, _ = run([call(1, "auth_plan", users="a,b,c", passwords="1,2")],
home=auth_home)
pl = json.loads(text(res[0]))
check("auth_plan counts the pairs without connecting",
pl["users"] == 3 and pl["passwords"] == 2 and pl["pairs"] == 6, pl)
res, _ = run([call(1, "auth_plan", userlist=user_list, passlist=pass_list)],
home=auth_home)
pl = json.loads(text(res[0]))
check("auth_plan reads wordlists and skips blank lines and comments",
pl["users"] == 2 and pl["passwords"] == 2, pl)
res, _ = run([call(1, "auth_plan", userlist="/nonexistent/x")], home=auth_home)
check("auth_plan fails loudly on a wordlist it cannot read", err(res[0]), res[0])
# --------------------------------------------------------------- gate first
res, _ = run([call(1, "auth_test", target="10.1.2.3", protocol="ftp",
users="a", passwords="b")], home=auth_home)
check("auth_test refuses a target outside the scope",
err(res[0]) and "scope" in text(res[0]).lower(), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="telnet",
users="a", passwords="b")], home=auth_home)
check("auth_test names the protocols it does not speak",
err(res[0]) and "ftp" in text(res[0]), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
users="a")], home=auth_home)
check("auth_test demands both a user and a password source", err(res[0]), res[0])
# ------------------------------------------------------- one hit per protocol
for _proto in ("ftp", "smtp", "imap", "pop3", "mysql"):
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol=_proto,
port=_auth_ports[_proto], users="nobody,alice",
passwords="wrong,secret")], home=auth_home)
r = json.loads(text(res[0]))
check("auth_test finds the %s password and only that one" % _proto,
r["hits"] == 1 and r["found"][0]["username"] == "alice" and
r["found"][0]["password"] == "secret" and r["attempts"] == 4, r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="http",
port=_auth_ports["http"], path="/",
users="nobody,alice", passwords="wrong,secret")],
home=auth_home)
r = json.loads(text(res[0]))
check("auth_test finds the HTTP Basic password",
r["hits"] == 1 and r["found"][0]["username"] == "alice", r)
# ------------------------------- an error page is not a valid credential
for _name, _want in (("gone", 404), ("broken", 500)):
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="http",
port=_auth_ports[_name], path="/",
users="alice", passwords="secret")], home=auth_home)
r = json.loads(text(res[0]))
check("HTTP %d is not reported as valid credentials" % _want,
r["hits"] == 0 and r["attempts"] == 1, r)
# ------------------------------------------------------- a miss is not a hit
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], users="alice",
passwords="nope,nada")], home=auth_home)
r = json.loads(text(res[0]))
check("a refused password is a miss, not a hit",
r["hits"] == 0 and r["attempts"] == 2 and r["errors"] == 0, r)
# --------------------------------------------------------- wordlists on disk
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], userlist=user_list,
passlist=pass_list)], home=auth_home)
r = json.loads(text(res[0]))
check("auth_test uses the wordlists from disk",
r["users"] == 2 and r["passwords"] == 2 and r["hits"] == 1, r)
# ------------------------------------------------------------ stop conditions
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], users="alice,bob",
passwords="wrong,secret,secret", stop_on_hit=True)],
home=auth_home)
r = json.loads(text(res[0]))
check("stop_on_hit ends the run at the first accepted pair",
r["hits"] == 1 and r["stopped"] is True and r["attempts"] == 2, r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], users="alice,bob",
passwords="a,b,c", max_attempts=3)], home=auth_home)
r = json.loads(text(res[0]))
check("max_attempts is a hard ceiling and says it was reached",
r["attempts"] == 3 and r["stopped"] is True and
"ceiling" in (r["reason"] or ""), r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="pop3",
port=_auth_ports["ratelimit"], users="alice",
passwords="a,b,c,d", lockout_limit=2)], home=auth_home)
r = json.loads(text(res[0]))
check("a streak of rate-limit answers stops the run and names the reason",
r["lockout"] is True and r["attempts"] == 2 and
"rate-limit" in (r["reason"] or ""), r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="pop3",
port=_auth_ports["ratelimit"], users="alice",
passwords="a,b,c", lockout_limit=0)], home=auth_home)
r = json.loads(text(res[0]))
check("lockout_limit 0 runs the whole list instead of stopping",
r["lockout"] is False and r["attempts"] == 3, r)
# ------------------------------------------- a dead port is an error, not a miss
_dead = None
_s = socket.socket()
_s.bind(("127.0.0.1", 0))
_dead = _s.getsockname()[1]
_s.close()
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_dead, users="alice", passwords="secret")],
home=auth_home)
r = json.loads(text(res[0]))
check("a dead port counts as an error, not as a refused password",
r["errors"] == 1 and r["attempts"] == 0 and r["hits"] == 0, r)
# --------------------------------------------------------- finding + evidence
res, _ = run([call(1, "auth_hits"), call(2, "finding_list")], home=auth_home)
hits = json.loads(text(res[0]))
fl = json.loads(text(res[1]))
check("every accepted pair became a credential finding",
len(hits["hits"]) >= 6 and
all(h["title"].startswith("Valid ") for h in hits["hits"]),
len(hits["hits"]))
check("the credential finding is critical and points at evidence",
any(f["severity"] == "critical" and f["tool"] == "auth_test" and
f["evidence"] for f in fl), fl[:2])
_auth_ev = [h["evidence"] for h in hits["hits"] if h["evidence"]]
check("the evidence file holds the pair and the answer it got",
_auth_ev and open(_auth_ev[0]).read().count("password:") == 1,
_auth_ev[:1])
# --------------------------------------------------- the log stays clean
_audit_txt = ""
for _p in glob.glob(os.path.join(auth_home, "**", "audit.log"),
recursive=True):
_audit_txt += open(_p, errors="replace").read()
check("the audit log records the account but never the password",
"auth_test" in _audit_txt and "alice" in _audit_txt and
"password: secret" not in _audit_txt and
'"secret"' not in _audit_txt, _audit_txt[-400:])
# --------------------------------------- the protocol's own odd answers
# FTP that accepts USER without a password: the hit is real, and the tool
# must not go on to send a PASS the server never asked for.
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_auth_ports["ftpnopass"], protocol="ftp",
users="alice", passwords="whatever", stop_on_hit=True)],
home=auth_home)
_fp = json.loads(text(res[0]))
check("FTP 230 after USER alone is a hit, not a miss",
_fp["found"] and _fp["found"][0]["username"] == "alice" and
_fp["hits"] == 1, _fp)
# A 429 is rate limiting: it must count toward the lockout, never as a hit.
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_auth_ports["rl429"], protocol="http",
users="alice,bob", passwords="a,b", lockout_limit=2)],
home=auth_home)
_rl = json.loads(text(res[0]))
check("HTTP 429 counts toward the lockout and is never a hit",
_rl["lockout"] is True and _rl["hits"] == 0 and _rl["attempts"] == 2, _rl)
# An empty wordlist is a usage error, not a silent no-op run.
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_auth_ports["ftp"], protocol="ftp",
userlist=blank_list)],
home=auth_home)
check("an empty wordlist fails loudly instead of running nothing",
err(res[0]), text(res[0]))
# ------------------------------------------------- argument validation
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=99999, users="a", passwords="b")], home=auth_home)
check("a port outside 1-65535 is refused",
err(res[0]) and "65535" in text(res[0]), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="http",
port=_auth_ports["http"], path="nope",
users="a", passwords="b")], home=auth_home)
check("an HTTP path without a leading slash is refused",
err(res[0]) and "start with /" in text(res[0]), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1",
users="a", passwords="b")], home=auth_home)
check("a missing protocol is refused with the list of supported ones",
err(res[0]) and "protocol is required" in text(res[0]), text(res[0]))
# ------------------------------------------- a server that hangs up early
_hang = _serve(_HangupHandler)
_auth_servers.append(_hang)
for _proto in ("ftp", "smtp", "imap", "pop3", "mysql"):
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_hang.server_address[1], protocol=_proto,
users="a", passwords="b")], home=auth_home)
_hg = json.loads(text(res[0]))
check("a %s server that hangs up counts as an error, not a hit" % _proto,
_hg["hits"] == 0 and _hg["errors"] == 1 and not _hg["found"], _hg)
# --------------------------------------------------------------- shutdown
for _s in _auth_servers:
try:
_s.shutdown()
_s.server_close()
except Exception:
pass
shutil.rmtree(auth_words, ignore_errors=True)
shutil.rmtree(auth_home, ignore_errors=True)
+2 -2
View File
@@ -21,7 +21,7 @@ import re
import sys
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EXPECTED_TOOLS = 423
EXPECTED_TOOLS = 427
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
@@ -31,7 +31,7 @@ INDIRECT = {"ext_run(": "ext_runx", "ext_runx(": "ext_runx",
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",
"traffic_list", "detect_rules", "mitre_map"}
"traffic_list", "detect_rules", "mitre_map", "auth_hits"}
# Tools that spawn a local program and take no target at all, so there is
# nothing for the gate to check. Each one still writes its audit line before it
# runs. msfvenom_build renders a payload on this host; the others talk to a
+596 -1
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("423 tools registered", len(tools) == 423, len(tools))
check("427 tools registered", len(tools) == 427, 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",
@@ -19907,6 +19907,601 @@ 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)
# ===========================================================================
# authentication testing: six protocols, wordlists, stop conditions
# ===========================================================================
print("\n== authentication testing ==")
import base64 as _b64
import glob
import hashlib as _hashlib
import socketserver as _ss
import threading as _threading
# --------------------------------------------------------------- fixtures
def _auth_scope():
"""A home whose scope allows the loopback ports the fixtures bind."""
home = tempfile.mkdtemp(prefix="apex-auth-")
write_scope(home, {
"label": "auth-suite",
"expires": "2099-12-31T23:59:59Z",
"allow_private": True,
"allow_ip": ["127.0.0.1/32"],
"deny_ip": [],
"allow_domain": [],
"allow_port": list(range(1, 65536)),
"allow_private_ports": list(range(1, 65536)),
})
return home
class _FtpHandler(_ss.StreamRequestHandler):
"""FTP: 331 for a known user, 230 only for the right password."""
users = {"alice": "secret", "bob": "hunter2"}
def handle(self):
self.wfile.write(b"220 fixture FTP ready\r\n")
user = None
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
verb, _, arg = cmd.partition(" ")
verb = verb.upper()
if verb == "USER":
user = arg
if arg in self.users:
self.wfile.write(b"331 need a password\r\n")
else:
self.wfile.write(b"530 no such user\r\n")
elif verb == "PASS":
if user in self.users and self.users[user] == arg:
self.wfile.write(b"230 logged in\r\n")
else:
self.wfile.write(b"530 login incorrect\r\n")
elif verb == "QUIT":
self.wfile.write(b"221 bye\r\n")
return
else:
self.wfile.write(b"500 what\r\n")
class _SmtpHandler(_ss.StreamRequestHandler):
"""SMTP: AUTH LOGIN, 235 for the right pair, 535 otherwise."""
users = {"alice": "secret"}
def handle(self):
self.wfile.write(b"220 fixture ESMTP\r\n")
authed_user = None
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
upper = cmd.upper()
if upper.startswith("EHLO"):
self.wfile.write(b"250-fixture\r\n250-AUTH LOGIN\r\n250 OK\r\n")
elif upper == "AUTH LOGIN":
self.wfile.write(b"334 VXNlcm5hbWU6\r\n")
raw = self.rfile.readline().decode("latin-1").strip()
try:
authed_user = _b64.b64decode(raw).decode("latin-1")
except Exception:
authed_user = None
self.wfile.write(b"334 UGFzc3dvcmQ6\r\n")
raw = self.rfile.readline().decode("latin-1").strip()
try:
pw = _b64.b64decode(raw).decode("latin-1")
except Exception:
pw = None
if self.users.get(authed_user) == pw:
self.wfile.write(b"235 2.7.0 accepted\r\n")
else:
self.wfile.write(b"535 5.7.8 rejected\r\n")
elif upper == "QUIT":
self.wfile.write(b"221 bye\r\n")
return
else:
self.wfile.write(b"250 OK\r\n")
class _ImapHandler(_ss.StreamRequestHandler):
"""IMAP: a1 OK only for the right pair, a1 NO otherwise."""
users = {"alice": "secret"}
def handle(self):
self.wfile.write(b"* OK fixture IMAP ready\r\n")
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
parts = cmd.split(" ")
if len(parts) >= 4 and parts[1].upper() == "LOGIN":
user, pw = parts[2], parts[3]
if self.users.get(user) == pw:
self.wfile.write(b"a1 OK LOGIN completed\r\n")
else:
self.wfile.write(b"a1 NO LOGIN failed\r\n")
elif "LOGOUT" in cmd.upper():
self.wfile.write(b"* BYE\r\n")
return
else:
self.wfile.write(b"a1 BAD unknown\r\n")
class _Pop3Handler(_ss.StreamRequestHandler):
"""POP3: +OK for the right pair, -ERR otherwise."""
users = {"alice": "secret"}
def handle(self):
self.wfile.write(b"+OK fixture POP3 ready\r\n")
user = None
while True:
line = self.rfile.readline()
if not line:
return
cmd = line.decode("latin-1").rstrip("\r\n")
verb, _, arg = cmd.partition(" ")
verb = verb.upper()
if verb == "USER":
user = arg
self.wfile.write(b"+OK user accepted\r\n")
elif verb == "PASS":
if self.users.get(user) == arg:
self.wfile.write(b"+OK maildrop locked\r\n")
else:
self.wfile.write(b"-ERR invalid password\r\n")
elif verb == "QUIT":
self.wfile.write(b"+OK bye\r\n")
return
else:
self.wfile.write(b"-ERR what\r\n")
class _MysqlHandler(_ss.StreamRequestHandler):
"""
MySQL: a v10 handshake, then the native-password scramble checked the way
the server does it. The seed is fixed so the test can compute the expected
token itself and prove the client got the algorithm right.
"""
users = {"alice": "secret"}
seed = b"12345678abcdefghijkl"
def handle(self):
payload = bytearray()
payload.append(10) # protocol v10
payload += b"5.7.0-fixture\x00"
payload += b"\x01\x00\x00\x00" # connection id
payload += self.seed[:8] + b"\x00" # part 1 + filler
payload += b"\xff\xf7" # capability, lower
payload += b"\x21" # charset
payload += b"\x02\x00" # status
payload += b"\xff\x81" # capability, upper
payload += b"\x15" # auth plugin data length
payload += b"\x00" * 10 # reserved
payload += self.seed[8:20] + b"\x00"
payload += b"mysql_native_password\x00"
head = bytes([len(payload) & 0xFF, (len(payload) >> 8) & 0xFF,
(len(payload) >> 16) & 0xFF, 0])
self.wfile.write(head + bytes(payload))
head = self.rfile.read(4)
if len(head) < 4:
return
plen = head[0] | (head[1] << 8) | (head[2] << 16)
body = self.rfile.read(plen)
if len(body) < plen:
return
# flags(4) maxpkt(4) charset(1) zeros(23) user NUL token(20)
rest = body[32:]
nul = rest.find(b"\x00")
user = rest[:nul].decode("latin-1")
token = rest[nul + 1:nul + 21]
want = self.users.get(user)
if want is None:
self._err(1045, "Access denied")
return
stage1 = _hashlib.sha1(want.encode()).digest()
stage2 = _hashlib.sha1(stage1).digest()
stage3 = _hashlib.sha1(self.seed + stage2).digest()
expect = bytes(a ^ b for a, b in zip(stage1, stage3))
if token == expect:
ok = b"\x00\x00\x00\x02\x00\x00\x00"
self.wfile.write(bytes([len(ok), 0, 0, 2]) + ok)
else:
self._err(1045, "Access denied")
def _err(self, code, msg):
payload = b"\xff" + bytes([code & 0xFF, (code >> 8) & 0xFF]) + b"#28000" + msg.encode()
self.wfile.write(bytes([len(payload) & 0xFF,
(len(payload) >> 8) & 0xFF,
(len(payload) >> 16) & 0xFF, 2]) + payload)
class _BasicAuthHandler(http.server.BaseHTTPRequestHandler):
"""HTTP Basic: 401 without the right header, 200 with it."""
users = {"alice": "secret"}
def do_GET(self):
hdr = self.headers.get("Authorization", "")
ok = False
if hdr.startswith("Basic "):
try:
raw = _b64.b64decode(hdr[6:]).decode("latin-1")
user, _, pw = raw.partition(":")
ok = self.users.get(user) == pw
except Exception:
ok = False
if ok:
body = b"welcome"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="fixture"')
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
class _RateLimitHandler(_ss.StreamRequestHandler):
"""POP3 that answers -ERR [LOCK] to everything: the lockout fixture."""
def handle(self):
self.wfile.write(b"+OK fixture POP3 ready\r\n")
while True:
line = self.rfile.readline()
if not line:
return
self.wfile.write(b"-ERR maildrop locked, too many attempts\r\n")
class _GoneHandler(http.server.BaseHTTPRequestHandler):
"""The path is gone: 404 for every request, credentials or not."""
def do_GET(self):
self.send_response(404)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
class _BrokenHandler(http.server.BaseHTTPRequestHandler):
"""The server is broken: 500 for every request."""
def do_GET(self):
self.send_response(500)
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
def _serve(handler):
srv = _ss.ThreadingTCPServer(("127.0.0.1", 0), handler)
srv.daemon_threads = True
_threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
class _FtpNoPassHandler(_ss.StreamRequestHandler):
"""FTP that answers 230 to USER alone: some embedded servers do this."""
def handle(self):
self.wfile.write(b"220 no-pass FTP ready\r\n")
while True:
line = self.rfile.readline()
if not line:
return
verb = line.decode("latin-1").split(" ", 1)[0].upper()
if verb == "USER":
self.wfile.write(b"230 anonymous ok\r\n")
elif verb == "QUIT":
self.wfile.write(b"221 bye\r\n")
return
else:
self.wfile.write(b"530 no\r\n")
class _RateLimit429Handler(http.server.BaseHTTPRequestHandler):
"""HTTP that answers 429 to everything: rate limiting, not a login."""
def do_GET(self):
self.send_response(429)
self.send_header("Retry-After", "30")
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *a):
pass
class _HangupHandler(_ss.StreamRequestHandler):
"""Closes the connection the moment it is opened, on every protocol."""
def handle(self):
return
_auth_servers = []
_auth_ports = {}
for _name, _h in (("ftp", _FtpHandler), ("smtp", _SmtpHandler),
("imap", _ImapHandler), ("pop3", _Pop3Handler),
("mysql", _MysqlHandler), ("ratelimit", _RateLimitHandler),
("ftpnopass", _FtpNoPassHandler),
("rl429", _RateLimit429Handler)):
_s = _serve(_h)
_auth_servers.append(_s)
_auth_ports[_name] = _s.server_address[1]
_http_srv = http.server.HTTPServer(("127.0.0.1", 0), _BasicAuthHandler)
_auth_servers.append(_http_srv)
_threading.Thread(target=_http_srv.serve_forever, daemon=True).start()
_auth_ports["http"] = _http_srv.server_address[1]
for _name, _h in (("gone", _GoneHandler), ("broken", _BrokenHandler)):
_s = http.server.HTTPServer(("127.0.0.1", 0), _h)
_auth_servers.append(_s)
_threading.Thread(target=_s.serve_forever, daemon=True).start()
_auth_ports[_name] = _s.server_address[1]
auth_home = _auth_scope()
# wordlists on disk, the form a real run uses
auth_words = tempfile.mkdtemp(prefix="apex-auth-words-")
user_list = os.path.join(auth_words, "users.txt")
pass_list = os.path.join(auth_words, "passes.txt")
with open(user_list, "w") as f:
f.write("# users\nnobody\n\nalice\n")
with open(pass_list, "w") as f:
f.write("wrong\nsecret\n")
blank_list = os.path.join(auth_words, "blank.txt")
with open(blank_list, "w") as f:
f.write("# only a comment\n\n\n")
# ---------------------------------------------------------------- protocol list
res, _ = run([call(1, "auth_protocols")], home=auth_home)
ap = json.loads(text(res[0]))
check("auth_protocols lists the six protocols with their default ports",
[p["name"] for p in ap["protocols"]] ==
["http", "ftp", "smtp", "imap", "pop3", "mysql"] and
{p["name"]: p["default_port"] for p in ap["protocols"]}["mysql"] == 3306,
ap)
# --------------------------------------------------------------------- plan
res, _ = run([call(1, "auth_plan", users="a,b,c", passwords="1,2")],
home=auth_home)
pl = json.loads(text(res[0]))
check("auth_plan counts the pairs without connecting",
pl["users"] == 3 and pl["passwords"] == 2 and pl["pairs"] == 6, pl)
res, _ = run([call(1, "auth_plan", userlist=user_list, passlist=pass_list)],
home=auth_home)
pl = json.loads(text(res[0]))
check("auth_plan reads wordlists and skips blank lines and comments",
pl["users"] == 2 and pl["passwords"] == 2, pl)
res, _ = run([call(1, "auth_plan", userlist="/nonexistent/x")], home=auth_home)
check("auth_plan fails loudly on a wordlist it cannot read", err(res[0]), res[0])
# --------------------------------------------------------------- gate first
res, _ = run([call(1, "auth_test", target="10.1.2.3", protocol="ftp",
users="a", passwords="b")], home=auth_home)
check("auth_test refuses a target outside the scope",
err(res[0]) and "scope" in text(res[0]).lower(), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="telnet",
users="a", passwords="b")], home=auth_home)
check("auth_test names the protocols it does not speak",
err(res[0]) and "ftp" in text(res[0]), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
users="a")], home=auth_home)
check("auth_test demands both a user and a password source", err(res[0]), res[0])
# ------------------------------------------------------- one hit per protocol
for _proto in ("ftp", "smtp", "imap", "pop3", "mysql"):
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol=_proto,
port=_auth_ports[_proto], users="nobody,alice",
passwords="wrong,secret")], home=auth_home)
r = json.loads(text(res[0]))
check("auth_test finds the %s password and only that one" % _proto,
r["hits"] == 1 and r["found"][0]["username"] == "alice" and
r["found"][0]["password"] == "secret" and r["attempts"] == 4, r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="http",
port=_auth_ports["http"], path="/",
users="nobody,alice", passwords="wrong,secret")],
home=auth_home)
r = json.loads(text(res[0]))
check("auth_test finds the HTTP Basic password",
r["hits"] == 1 and r["found"][0]["username"] == "alice", r)
# ------------------------------- an error page is not a valid credential
for _name, _want in (("gone", 404), ("broken", 500)):
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="http",
port=_auth_ports[_name], path="/",
users="alice", passwords="secret")], home=auth_home)
r = json.loads(text(res[0]))
check("HTTP %d is not reported as valid credentials" % _want,
r["hits"] == 0 and r["attempts"] == 1, r)
# ------------------------------------------------------- a miss is not a hit
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], users="alice",
passwords="nope,nada")], home=auth_home)
r = json.loads(text(res[0]))
check("a refused password is a miss, not a hit",
r["hits"] == 0 and r["attempts"] == 2 and r["errors"] == 0, r)
# --------------------------------------------------------- wordlists on disk
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], userlist=user_list,
passlist=pass_list)], home=auth_home)
r = json.loads(text(res[0]))
check("auth_test uses the wordlists from disk",
r["users"] == 2 and r["passwords"] == 2 and r["hits"] == 1, r)
# ------------------------------------------------------------ stop conditions
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], users="alice,bob",
passwords="wrong,secret,secret", stop_on_hit=True)],
home=auth_home)
r = json.loads(text(res[0]))
check("stop_on_hit ends the run at the first accepted pair",
r["hits"] == 1 and r["stopped"] is True and r["attempts"] == 2, r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_auth_ports["ftp"], users="alice,bob",
passwords="a,b,c", max_attempts=3)], home=auth_home)
r = json.loads(text(res[0]))
check("max_attempts is a hard ceiling and says it was reached",
r["attempts"] == 3 and r["stopped"] is True and
"ceiling" in (r["reason"] or ""), r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="pop3",
port=_auth_ports["ratelimit"], users="alice",
passwords="a,b,c,d", lockout_limit=2)], home=auth_home)
r = json.loads(text(res[0]))
check("a streak of rate-limit answers stops the run and names the reason",
r["lockout"] is True and r["attempts"] == 2 and
"rate-limit" in (r["reason"] or ""), r)
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="pop3",
port=_auth_ports["ratelimit"], users="alice",
passwords="a,b,c", lockout_limit=0)], home=auth_home)
r = json.loads(text(res[0]))
check("lockout_limit 0 runs the whole list instead of stopping",
r["lockout"] is False and r["attempts"] == 3, r)
# ------------------------------------------- a dead port is an error, not a miss
_dead = None
_s = socket.socket()
_s.bind(("127.0.0.1", 0))
_dead = _s.getsockname()[1]
_s.close()
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=_dead, users="alice", passwords="secret")],
home=auth_home)
r = json.loads(text(res[0]))
check("a dead port counts as an error, not as a refused password",
r["errors"] == 1 and r["attempts"] == 0 and r["hits"] == 0, r)
# --------------------------------------------------------- finding + evidence
res, _ = run([call(1, "auth_hits"), call(2, "finding_list")], home=auth_home)
hits = json.loads(text(res[0]))
fl = json.loads(text(res[1]))
check("every accepted pair became a credential finding",
len(hits["hits"]) >= 6 and
all(h["title"].startswith("Valid ") for h in hits["hits"]),
len(hits["hits"]))
check("the credential finding is critical and points at evidence",
any(f["severity"] == "critical" and f["tool"] == "auth_test" and
f["evidence"] for f in fl), fl[:2])
_auth_ev = [h["evidence"] for h in hits["hits"] if h["evidence"]]
check("the evidence file holds the pair and the answer it got",
_auth_ev and open(_auth_ev[0]).read().count("password:") == 1,
_auth_ev[:1])
# --------------------------------------------------- the log stays clean
_audit_txt = ""
for _p in glob.glob(os.path.join(auth_home, "**", "audit.log"),
recursive=True):
_audit_txt += open(_p, errors="replace").read()
check("the audit log records the account but never the password",
"auth_test" in _audit_txt and "alice" in _audit_txt and
"password: secret" not in _audit_txt and
'"secret"' not in _audit_txt, _audit_txt[-400:])
# --------------------------------------- the protocol's own odd answers
# FTP that accepts USER without a password: the hit is real, and the tool
# must not go on to send a PASS the server never asked for.
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_auth_ports["ftpnopass"], protocol="ftp",
users="alice", passwords="whatever", stop_on_hit=True)],
home=auth_home)
_fp = json.loads(text(res[0]))
check("FTP 230 after USER alone is a hit, not a miss",
_fp["found"] and _fp["found"][0]["username"] == "alice" and
_fp["hits"] == 1, _fp)
# A 429 is rate limiting: it must count toward the lockout, never as a hit.
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_auth_ports["rl429"], protocol="http",
users="alice,bob", passwords="a,b", lockout_limit=2)],
home=auth_home)
_rl = json.loads(text(res[0]))
check("HTTP 429 counts toward the lockout and is never a hit",
_rl["lockout"] is True and _rl["hits"] == 0 and _rl["attempts"] == 2, _rl)
# An empty wordlist is a usage error, not a silent no-op run.
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_auth_ports["ftp"], protocol="ftp",
userlist=blank_list)],
home=auth_home)
check("an empty wordlist fails loudly instead of running nothing",
err(res[0]), text(res[0]))
# ------------------------------------------------- argument validation
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="ftp",
port=99999, users="a", passwords="b")], home=auth_home)
check("a port outside 1-65535 is refused",
err(res[0]) and "65535" in text(res[0]), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1", protocol="http",
port=_auth_ports["http"], path="nope",
users="a", passwords="b")], home=auth_home)
check("an HTTP path without a leading slash is refused",
err(res[0]) and "start with /" in text(res[0]), text(res[0]))
res, _ = run([call(1, "auth_test", target="127.0.0.1",
users="a", passwords="b")], home=auth_home)
check("a missing protocol is refused with the list of supported ones",
err(res[0]) and "protocol is required" in text(res[0]), text(res[0]))
# ------------------------------------------- a server that hangs up early
_hang = _serve(_HangupHandler)
_auth_servers.append(_hang)
for _proto in ("ftp", "smtp", "imap", "pop3", "mysql"):
res, _ = run([call(1, "auth_test", target="127.0.0.1",
port=_hang.server_address[1], protocol=_proto,
users="a", passwords="b")], home=auth_home)
_hg = json.loads(text(res[0]))
check("a %s server that hangs up counts as an error, not a hit" % _proto,
_hg["hits"] == 0 and _hg["errors"] == 1 and not _hg["found"], _hg)
# --------------------------------------------------------------- shutdown
for _s in _auth_servers:
try:
_s.shutdown()
_s.server_close()
except Exception:
pass
shutil.rmtree(auth_words, ignore_errors=True)
shutil.rmtree(auth_home, ignore_errors=True)
for _s in exp_servers:
_s.shutdown()
_s.server_close()