diff --git a/CHANGELOG.md b/CHANGELOG.md index fff0f75..41e6cc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 4c04658..b906bc3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/SECURITY.md b/SECURITY.md index 915c0cf..423eafd 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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. diff --git a/docs/apex-twin.1 b/docs/apex-twin.1 index b11b10c..9a303d8 100644 --- a/docs/apex-twin.1 +++ b/docs/apex-twin.1 @@ -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, diff --git a/src/apex-twin.c b/src/apex-twin.c index 4b5a7be..77ce75c 100644 --- a/src/apex-twin.c +++ b/src/apex-twin.c @@ -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(); diff --git a/src/apex.h b/src/apex.h index 77d4f19..e770e3c 100644 --- a/src/apex.h +++ b/src/apex.h @@ -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 diff --git a/src/tools.h b/src/tools.h index 5595ac1..34796ac 100644 --- a/src/tools.h +++ b/src/tools.h @@ -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 */ diff --git a/src/tools_auth.c b/src/tools_auth.c new file mode 100644 index 0000000..4bcbf9b --- /dev/null +++ b/src/tools_auth.c @@ -0,0 +1,1420 @@ +/* + * tools_auth.c - authentication testing against one in-scope service. + * + * This is the part that actually tries credentials. Every attempt is one + * connection to one target the scope gate has already approved. Nothing here + * decides how many attempts are reasonable, what a lockout means, or whether + * a service should be tested at all: the operator sets the wordlists, the + * delay, the attempt ceiling and the stop conditions, and the answer reports + * exactly what was tried. + * + * What is deliberately not invented: + * + * - A hit is a protocol answer, not a guess. SMTP says 235, IMAP says OK, + * POP3 says +OK, FTP says 230, MySQL says OK, HTTP stops answering + * 401/403. Anything else is a miss, and a dead connection is neither. + * - A lockout is detected, not assumed. Consecutive 429/421/454-style + * answers stop the run and say so, because the operator asked for that + * stop condition by name. + * - The password does not go into the audit log. The audit line names the + * account and the service; the evidence file holds the pair, because that + * is what proves the finding. + * + * No shell anywhere: argv never exists, bytes go straight to the socket. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "apex.h" +#include "tools.h" + +#define AUTH_MAX_WORDS 512 +#define AUTH_MAX_LINE 1024 +#define AUTH_CRED_MAX 256 +#define AUTH_MAX_PAIRS 4096 + +/* One credential pair as the operator wrote it. */ +typedef struct { + char user[AUTH_CRED_MAX]; + char pass[AUTH_CRED_MAX]; +} auth_pair; + +/* + * The operator's run: where, with what, how fast, and when to stop. The loop + * reads all of it from here, so it has no opinion of its own. + */ +typedef struct { + const char *target; + int port; + int tls; + int delay_ms; /* pause between attempts */ + int max_attempts; /* ceiling for the whole run */ + int stop_on_hit; /* stop at the first accepted pair */ + int lockout_limit; /* consecutive rate-limit answers that end the run */ + int timeout_ms; /* per connection */ + const char *path; /* http only: the path that answers 401/403 */ +} auth_run; + +typedef struct { + int attempts; /* connections that produced a protocol answer */ + int errors; /* connections that produced none */ + int hits; + int lockout; /* run ended on the rate-limit condition */ + int stopped; /* run ended early for another reason */ + int streak; /* consecutive rate-limit answers */ + char reason[640]; /* why the run ended when it did */ +} auth_stats; + +/* Result of one attempt. */ +#define AUTH_HIT 1 +#define AUTH_MISS 0 +#define AUTH_RATE 2 /* refused in a way that means "slow down" */ +#define AUTH_NOANSWER (-1) + + +/* + * A bounded copy. snprintf("%s") makes the compiler prove the sizes match, + * which it cannot here because the source lengths are only known at run time; + * this says the same thing without the format string. + */ +static void auth_copy(char *dst, size_t n, const char *src) +{ + size_t len; + + if (n == 0) + return; + if (src == NULL) { + dst[0] = '\0'; + return; + } + len = strlen(src); + if (len >= n) + len = n - 1; + memcpy(dst, src, len); + dst[len] = '\0'; +} + +/* ------------------------------------------------------------------ words */ + + +/* + * One word per line from a file the operator named. Blank lines and lines + * starting with # are skipped, a trailing CR from a DOS file is stripped. + * Returns the number of words, or -1 when the file cannot be read. + */ +static int read_wordlist(const char *path, char words[][AUTH_CRED_MAX], int max) +{ + FILE *f; + int n = 0; + char line[AUTH_CRED_MAX + 8]; + + f = fopen(path, "r"); + if (f == NULL) + return -1; + while (n < max && fgets(line, sizeof(line), f) != NULL) { + size_t len = strlen(line); + + while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r')) + line[--len] = '\0'; + if (len == 0 || line[0] == '#') + continue; + auth_copy(words[n], AUTH_CRED_MAX, line); + n++; + } + fclose(f); + return n; +} + +/* Split a comma list, the form cred_test has always taken. */ +static int split_words(const char *text, char words[][AUTH_CRED_MAX], int max) +{ + char copy[AUTH_CRED_MAX * 2]; + char *save = NULL; + char *tok; + int n = 0; + + if (text == NULL || *text == '\0') + return 0; + auth_copy(copy, sizeof(copy), text); + tok = strtok_r(copy, ",", &save); + while (tok != NULL && n < max) { + while (*tok == ' ' || *tok == '\t') + tok++; + if (*tok != '\0') + auth_copy(words[n++], AUTH_CRED_MAX, tok); + tok = strtok_r(NULL, ",", &save); + } + return n; +} + +/* + * The wordlist for one side of the pair. A file wins over an inline list when + * both are given, because the operator who wrote a file meant the file. + */ +static int words_for(const char *file, const char *inline_list, + char words[][AUTH_CRED_MAX], int max, char *err, size_t n) +{ + int got; + + if (file != NULL && *file != '\0') { + got = read_wordlist(file, words, max); + if (got < 0) { + snprintf(err, n, "cannot read wordlist %s", file); + return -1; + } + if (got == 0) { + snprintf(err, n, "wordlist %s has no usable words", file); + return -1; + } + return got; + } + return split_words(inline_list, words, max); +} + +/* -------------------------------------------------------------- transport */ + +/* + * One connection with a deadline. tcp_connect_host() covers the connect; the + * socket timeouts are what stop a server that accepts and then says nothing + * from holding the run open. + */ +static int auth_open(const auth_run *r, char *err, size_t n) +{ + int fd = tcp_connect_host(r->target, r->port, r->timeout_ms); + struct timeval tv; + + if (fd < 0) { + snprintf(err, n, "cannot connect to %s:%d", r->target, r->port); + return -1; + } + tv.tv_sec = r->timeout_ms / 1000; + tv.tv_usec = (r->timeout_ms % 1000) * 1000; + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + return fd; +} + +/* + * apex_net_line() already strips CR and LF, so this is a thin wrapper that + * exists to keep the protocol code readable: one reply, one call. + */ +static int auth_line(int fd, char *buf, size_t n) +{ + int got = apex_net_line(fd, buf, n); + + if (got < 0) + return -1; + return 0; +} + +/* + * One protocol line. The line and the CRLF go out as two writes rather than + * one snprintf, so a long password is sent whole instead of being cut off at + * an arbitrary buffer size. + */ +static int auth_send(int fd, const char *line) +{ + if (apex_net_write(fd, line) != 0) + return -1; + return apex_net_write(fd, "\r\n"); +} + +/* The three-digit reply code of an FTP/SMTP line, 0 when there is none. */ +static int auth_code(const char *line) +{ + int code = 0; + int i; + + for (i = 0; i < 3 && line[i] >= '0' && line[i] <= '9'; i++) + code = code * 10 + (line[i] - '0'); + return i == 3 ? code : 0; +} + +/* -------------------------------------------------------------------- sha1 */ + +/* + * SHA1, needed for the MySQL native-password scramble and nothing else. It is + * checked against the published vectors in the test suite, so a mistake here + * fails loudly instead of producing a login that never works. + */ +typedef struct { + uint32_t h[5]; + uint64_t len; + unsigned char buf[64]; + size_t used; +} sha1_ctx; + +static uint32_t rol32(uint32_t v, int n) +{ + return (v << n) | (v >> (32 - n)); +} + +static void sha1_block(sha1_ctx *c, const unsigned char *p) +{ + uint32_t w[80]; + uint32_t a, b, d, e, f, k, t; + int i; + + for (i = 0; i < 16; i++) + w[i] = ((uint32_t)p[i * 4] << 24) | ((uint32_t)p[i * 4 + 1] << 16) | + ((uint32_t)p[i * 4 + 2] << 8) | (uint32_t)p[i * 4 + 3]; + for (i = 16; i < 80; i++) + w[i] = rol32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); + a = c->h[0]; + b = c->h[1]; + d = c->h[2]; + e = c->h[3]; + f = c->h[4]; + for (i = 0; i < 80; i++) { + if (i < 20) { + k = 0x5A827999u; + t = (b & d) | (~b & e); + } else if (i < 40) { + k = 0x6ED9EBA1u; + t = b ^ d ^ e; + } else if (i < 60) { + k = 0x8F1BBCDCu; + t = (b & d) | (b & e) | (d & e); + } else { + k = 0xCA62C1D6u; + t = b ^ d ^ e; + } + t += rol32(a, 5) + f + k + w[i]; + f = e; + e = d; + d = rol32(b, 30); + b = a; + a = t; + } + c->h[0] += a; + c->h[1] += b; + c->h[2] += d; + c->h[3] += e; + c->h[4] += f; +} + +static void sha1_init(sha1_ctx *c) +{ + c->h[0] = 0x67452301u; + c->h[1] = 0xEFCDAB89u; + c->h[2] = 0x98BADCFEu; + c->h[3] = 0x10325476u; + c->h[4] = 0xC3D2E1F0u; + c->len = 0; + c->used = 0; +} + +static void sha1_update(sha1_ctx *c, const void *data, size_t len) +{ + const unsigned char *p = data; + + c->len += len; + while (len > 0) { + size_t take = 64 - c->used; + + if (take > len) + take = len; + memcpy(c->buf + c->used, p, take); + c->used += take; + p += take; + len -= take; + if (c->used == 64) { + sha1_block(c, c->buf); + c->used = 0; + } + } +} + +static void sha1_final(sha1_ctx *c, unsigned char out[20]) +{ + uint64_t bits = c->len * 8; + unsigned char pad = 0x80; + unsigned char zero = 0; + unsigned char lenbuf[8]; + int i; + + sha1_update(c, &pad, 1); + while (c->used != 56) + sha1_update(c, &zero, 1); + for (i = 0; i < 8; i++) + lenbuf[i] = (unsigned char)(bits >> (56 - i * 8)); + sha1_update(c, lenbuf, 8); + for (i = 0; i < 5; i++) { + out[i * 4] = (unsigned char)(c->h[i] >> 24); + out[i * 4 + 1] = (unsigned char)(c->h[i] >> 16); + out[i * 4 + 2] = (unsigned char)(c->h[i] >> 8); + out[i * 4 + 3] = (unsigned char)c->h[i]; + } +} + +static void auth_sha1(const void *data, size_t len, unsigned char out[20]) +{ + sha1_ctx c; + + sha1_init(&c); + sha1_update(&c, data, len); + sha1_final(&c, out); +} + +/* --------------------------------------------------------------- protocols */ + +/* + * HTTP Basic. The caller already knows the path answers 401/403; a pair is + * accepted when the same request stops answering 401/403. + */ +static int try_http_basic(const auth_run *r, const auth_pair *p, char *why, + size_t whyn) +{ + char pair[AUTH_CRED_MAX * 2 + 4]; + char header[AUTH_CRED_MAX * 4 + 96]; + char status[256]; + char *resp = NULL; + size_t len = 0; + char *b64; + int code; + int rc; + + snprintf(pair, sizeof(pair), "%s:%s", p->user, p->pass); + b64 = apex_base64_alloc(pair, strlen(pair)); + if (b64 == NULL) { + snprintf(why, whyn, "base64 allocation failed"); + return AUTH_NOANSWER; + } + snprintf(header, sizeof(header), "Authorization: Basic %s\r\n", b64); + free(b64); + status[0] = '\0'; + rc = apex_http_once(r->target, r->port, r->tls, "GET", + r->path != NULL ? r->path : "/", NULL, + header, r->timeout_ms, &resp, &len, status, + sizeof(status)); + if (rc != 0) { + snprintf(why, whyn, "no HTTP answer"); + return AUTH_NOANSWER; + } + code = apex_status_code(status); + free(resp); + if (code == 401 || code == 403) { + snprintf(why, whyn, "HTTP %d", code); + return AUTH_MISS; + } + if (code == 429) { + snprintf(why, whyn, "HTTP 429 rate limited"); + return AUTH_RATE; + } + /* + * Only a 2xx or 3xx proves the credentials: the server let the request + * through. A 5xx is the server breaking, and a 404 means the path is + * gone - neither says anything about the pair, and calling either a hit + * would invent a credential finding out of an error page. + */ + if (code >= 200 && code < 400) { + snprintf(why, whyn, "HTTP %d after Basic auth", code); + return AUTH_HIT; + } + snprintf(why, whyn, "HTTP %d after Basic auth, not an accept", code); + return AUTH_MISS; +} + +/* + * FTP: USER then PASS. 230 is a login, 331 after USER is the password prompt, + * 530 a refusal. 421 is the server closing the control connection, which is + * the FTP way of saying "too many" and is reported as such. + */ +static int try_ftp(const auth_run *r, const auth_pair *p, char *why, size_t whyn) +{ + char line[AUTH_MAX_LINE]; + char cmd[AUTH_MAX_LINE]; + char err[256]; + int fd; + int code; + int result = AUTH_NOANSWER; + + fd = auth_open(r, err, sizeof(err)); + if (fd < 0) { + snprintf(why, whyn, "%s", err); + return AUTH_NOANSWER; + } + if (auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no FTP banner"); + close(fd); + return AUTH_NOANSWER; + } + snprintf(cmd, sizeof(cmd), "USER %s", p->user); + if (auth_send(fd, cmd) != 0 || auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to USER"); + close(fd); + return AUTH_NOANSWER; + } + code = auth_code(line); + if (code == 230) { + snprintf(why, whyn, "FTP 230 after USER, no password needed"); + result = AUTH_HIT; + goto done; + } + if (code == 421 || code == 450 || code == 530) { + /* 421 is the close, 450 a temporary refusal; 530 is a plain + * rejection, so only 421/450 count as "slow down" */ + if (code == 530) { + snprintf(why, whyn, "FTP 530 user refused"); + result = AUTH_MISS; + } else { + snprintf(why, whyn, "FTP %d temporary refusal", code); + result = AUTH_RATE; + } + goto done; + } + if (code != 331 && code != 332) { + snprintf(why, whyn, "FTP %d for USER", code); + result = AUTH_MISS; + goto done; + } + snprintf(cmd, sizeof(cmd), "PASS %s", p->pass); + if (auth_send(fd, cmd) != 0 || auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to PASS"); + result = AUTH_NOANSWER; + goto done; + } + code = auth_code(line); + if (code == 230 || code == 202) { + snprintf(why, whyn, "FTP %d login accepted", code); + result = AUTH_HIT; + } else if (code == 421 || code == 450) { + snprintf(why, whyn, "FTP %d temporary refusal", code); + result = AUTH_RATE; + } else { + snprintf(why, whyn, "FTP %d login refused", code); + result = AUTH_MISS; + } +done: + apex_net_write(fd, "QUIT\r\n"); + close(fd); + return result; +} + +/* + * SMTP: EHLO, then AUTH LOGIN with the base64 user and password. 235 is the + * accept, 535 a refusal, 421/454 a temporary or rate-limit answer. + */ +static int try_smtp(const auth_run *r, const auth_pair *p, char *why, size_t whyn) +{ + char line[AUTH_MAX_LINE]; + char *b64; + char err[256]; + int fd; + int code; + int result = AUTH_NOANSWER; + + fd = auth_open(r, err, sizeof(err)); + if (fd < 0) { + snprintf(why, whyn, "%s", err); + return AUTH_NOANSWER; + } + if (auth_line(fd, line, sizeof(line)) != 0 || auth_code(line) != 220) { + snprintf(why, whyn, "no SMTP banner"); + close(fd); + return AUTH_NOANSWER; + } + if (auth_send(fd, "EHLO apex-twin") != 0) { + snprintf(why, whyn, "cannot send EHLO"); + close(fd); + return AUTH_NOANSWER; + } + /* the EHLO answer is multi-line: a line whose fourth byte is '-' continues */ + for (;;) { + if (auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to EHLO"); + close(fd); + return AUTH_NOANSWER; + } + if (strlen(line) < 4 || line[3] != '-') + break; + } + if (auth_send(fd, "AUTH LOGIN") != 0 || + auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to AUTH LOGIN"); + close(fd); + return AUTH_NOANSWER; + } + if (auth_code(line) != 334) { + snprintf(why, whyn, "SMTP %d for AUTH LOGIN, not offered", + auth_code(line)); + close(fd); + return AUTH_MISS; + } + b64 = apex_base64_alloc(p->user, strlen(p->user)); + if (b64 == NULL) { + close(fd); + snprintf(why, whyn, "base64 allocation failed"); + return AUTH_NOANSWER; + } + auth_send(fd, b64); + free(b64); + if (auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to the user line"); + close(fd); + return AUTH_NOANSWER; + } + if (auth_code(line) != 334) { + snprintf(why, whyn, "SMTP %d for the user", auth_code(line)); + close(fd); + return AUTH_MISS; + } + b64 = apex_base64_alloc(p->pass, strlen(p->pass)); + if (b64 == NULL) { + close(fd); + snprintf(why, whyn, "base64 allocation failed"); + return AUTH_NOANSWER; + } + auth_send(fd, b64); + free(b64); + if (auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to the password line"); + close(fd); + return AUTH_NOANSWER; + } + code = auth_code(line); + if (code == 235) { + snprintf(why, whyn, "SMTP 235 authentication accepted"); + result = AUTH_HIT; + } else if (code == 421 || code == 454 || code == 451) { + snprintf(why, whyn, "SMTP %d temporary failure", code); + result = AUTH_RATE; + } else { + snprintf(why, whyn, "SMTP %d authentication refused", code); + result = AUTH_MISS; + } + apex_net_write(fd, "QUIT\r\n"); + close(fd); + return result; +} + +/* + * IMAP: the greeting, then "a1 LOGIN user pass". OK is the accept, NO the + * refusal, BYE the server hanging up. + */ +static int try_imap(const auth_run *r, const auth_pair *p, char *why, size_t whyn) +{ + char line[AUTH_MAX_LINE]; + char cmd[AUTH_MAX_LINE * 2]; + char err[256]; + int fd; + int result = AUTH_NOANSWER; + + fd = auth_open(r, err, sizeof(err)); + if (fd < 0) { + snprintf(why, whyn, "%s", err); + return AUTH_NOANSWER; + } + if (auth_line(fd, line, sizeof(line)) != 0 || + strncasecmp(line, "* OK", 4) != 0) { + snprintf(why, whyn, "no IMAP greeting"); + close(fd); + return AUTH_NOANSWER; + } + /* + * A password with a quote or a backslash cannot go in the command line: + * IMAP would parse it as syntax. Send it as a literal instead, so the + * server receives exactly the bytes the operator wrote. + */ + if (strpbrk(p->pass, "\"\\") != NULL || strpbrk(p->user, "\"\\") != NULL) { + char ulit[32]; + char plit[32]; + + snprintf(ulit, sizeof(ulit), "{%zu}", strlen(p->user)); + snprintf(plit, sizeof(plit), "{%zu}", strlen(p->pass)); + snprintf(cmd, sizeof(cmd), "a1 LOGIN %s", ulit); + if (auth_send(fd, cmd) != 0 || + auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to the user literal"); + close(fd); + return AUTH_NOANSWER; + } + auth_send(fd, p->user); + if (auth_send(fd, plit) != 0 || + auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to the password literal"); + close(fd); + return AUTH_NOANSWER; + } + auth_send(fd, p->pass); + } else { + snprintf(cmd, sizeof(cmd), "a1 LOGIN %s %s", p->user, p->pass); + if (auth_send(fd, cmd) != 0) { + snprintf(why, whyn, "cannot send LOGIN"); + close(fd); + return AUTH_NOANSWER; + } + } + if (auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to LOGIN"); + close(fd); + return AUTH_NOANSWER; + } + if (strncasecmp(line, "a1 OK", 5) == 0) { + snprintf(why, whyn, "IMAP OK login accepted"); + result = AUTH_HIT; + } else if (strncasecmp(line, "* BYE", 5) == 0) { + snprintf(why, whyn, "IMAP %.120s", line); + result = AUTH_RATE; + } else if (strncasecmp(line, "a1 NO", 5) == 0) { + snprintf(why, whyn, "IMAP NO login refused"); + result = AUTH_MISS; + } else { + snprintf(why, whyn, "IMAP %.120s", line); + result = AUTH_MISS; + } + apex_net_write(fd, "a2 LOGOUT\r\n"); + close(fd); + return result; +} + +/* + * POP3: the +OK greeting, USER, PASS. +OK after PASS is the accept, -ERR the + * refusal. + */ +static int try_pop3(const auth_run *r, const auth_pair *p, char *why, size_t whyn) +{ + char line[AUTH_MAX_LINE]; + char cmd[AUTH_MAX_LINE]; + char err[256]; + int fd; + int result = AUTH_NOANSWER; + + fd = auth_open(r, err, sizeof(err)); + if (fd < 0) { + snprintf(why, whyn, "%s", err); + return AUTH_NOANSWER; + } + if (auth_line(fd, line, sizeof(line)) != 0 || + strncasecmp(line, "+OK", 3) != 0) { + snprintf(why, whyn, "no POP3 greeting"); + close(fd); + return AUTH_NOANSWER; + } + snprintf(cmd, sizeof(cmd), "USER %s", p->user); + if (auth_send(fd, cmd) != 0 || auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to USER"); + close(fd); + return AUTH_NOANSWER; + } + if (strncasecmp(line, "+OK", 3) != 0) { + if (strstr(line, "lock") != NULL || strstr(line, "busy") != NULL) { + snprintf(why, whyn, "POP3 %.120s", line); + result = AUTH_RATE; + } else { + snprintf(why, whyn, "POP3 %.120s for USER", line); + result = AUTH_MISS; + } + goto done; + } + snprintf(cmd, sizeof(cmd), "PASS %s", p->pass); + if (auth_send(fd, cmd) != 0 || auth_line(fd, line, sizeof(line)) != 0) { + snprintf(why, whyn, "no answer to PASS"); + result = AUTH_NOANSWER; + goto done; + } + if (strncasecmp(line, "+OK", 3) == 0) { + snprintf(why, whyn, "POP3 +OK login accepted"); + result = AUTH_HIT; + } else if (strstr(line, "lock") != NULL || strstr(line, "busy") != NULL) { + snprintf(why, whyn, "POP3 %.120s", line); + result = AUTH_RATE; + } else { + snprintf(why, whyn, "POP3 %.120s login refused", line); + result = AUTH_MISS; + } +done: + apex_net_write(fd, "QUIT\r\n"); + close(fd); + return result; +} + +/* + * MySQL: read the server greeting, then send a native-password response. + * Only mysql_native_password is spoken; a server that asks for another plugin + * answers 0xFE and this reports that instead of blaming the pair. + * + * Packet: 3-byte little-endian length, 1-byte sequence, payload. The reply is + * a 1-byte header, 0x00 for OK and 0xFF for ERR. + */ +static int try_mysql(const auth_run *r, const auth_pair *p, char *why, + size_t whyn) +{ + unsigned char greet[512]; + unsigned char pkt[128]; + unsigned char reply[256]; + unsigned char seed[20]; + unsigned char stage1[20]; + unsigned char stage2[20]; + unsigned char stage3[20]; + unsigned char token[20]; + char err[256]; + char user[64]; + size_t glen; + size_t seedlen; + size_t plen; + size_t i; + int fd; + int got; + int result = AUTH_NOANSWER; + + fd = auth_open(r, err, sizeof(err)); + if (fd < 0) { + snprintf(why, whyn, "%s", err); + return AUTH_NOANSWER; + } + got = apex_net_exact(fd, greet, 4); + if (got != 0) { + snprintf(why, whyn, "no MySQL greeting header"); + close(fd); + return AUTH_NOANSWER; + } + glen = (size_t)greet[0] | ((size_t)greet[1] << 8) | ((size_t)greet[2] << 16); + if (glen < 5 || glen > 500) { + snprintf(why, whyn, "MySQL greeting length %zu is not a handshake", + glen); + close(fd); + return AUTH_NOANSWER; + } + if (apex_net_exact(fd, greet, glen) != 0) { + snprintf(why, whyn, "short MySQL greeting"); + close(fd); + return AUTH_NOANSWER; + } + if (greet[0] == 0xFF) { + snprintf(why, whyn, "MySQL sent ERR instead of a handshake"); + close(fd); + return AUTH_NOANSWER; + } + if (greet[0] != 10) { + snprintf(why, whyn, "MySQL protocol %d is not v10", greet[0]); + close(fd); + return AUTH_NOANSWER; + } + /* version string, then the 4-byte connection id, then the 8-byte seed */ + i = 1; + while (i < glen && greet[i] != '\0') + i++; + i++; /* past the NUL */ + i += 4; /* connection id */ + if (i + 8 > glen) { + snprintf(why, whyn, "MySQL greeting is too short for a seed"); + close(fd); + return AUTH_NOANSWER; + } + memcpy(seed, greet + i, 8); + seedlen = 8; + /* + * The second half of the seed sits after the filler, the capability + * flags, the charset, the status, the upper capability word, the plugin + * data length and ten reserved bytes. Counting them explicitly is the + * whole point: reading from i+11 takes the capability flags as seed + * bytes, and every login then fails against a server that is fine. + */ + if (i + 8 + 1 + 2 + 1 + 2 + 2 + 1 + 10 <= glen) { + size_t p2 = i + 8 + 1 + 2 + 1 + 2 + 2 + 1 + 10; + size_t avail = glen > p2 ? glen - p2 : 0; + + if (avail > 12) + avail = 12; + /* the trailing NUL of part 2 is not part of the seed */ + while (avail > 0 && greet[p2 + avail - 1] == '\0') + avail--; + if (avail > 0) { + memcpy(seed + 8, greet + p2, avail); + seedlen = 8 + avail; + } + } + /* native password: SHA1(pass) XOR SHA1(seed + SHA1(SHA1(pass))) */ + auth_sha1(p->pass, strlen(p->pass), stage1); + auth_sha1(stage1, 20, stage2); + { + unsigned char concat[64]; + + memcpy(concat, seed, seedlen); + memcpy(concat + seedlen, stage2, 20); + auth_sha1(concat, seedlen + 20, stage3); + } + for (i = 0; i < 20; i++) + token[i] = stage1[i] ^ stage3[i]; + + /* capability flags: 4 bytes of client flags, then the 4-byte max packet, + * then the charset, then 23 bytes of zero, then the user, NUL, the token */ + auth_copy(user, sizeof(user), p->user); + plen = 4 + 4 + 1 + 23 + strlen(user) + 1 + 20; + if (plen > sizeof(pkt)) { + snprintf(why, whyn, "MySQL login packet too long"); + close(fd); + return AUTH_NOANSWER; + } + memset(pkt, 0, sizeof(pkt)); + /* CLIENT_LONG_PASSWORD | CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION + * | CLIENT_PLUGIN_AUTH, little endian */ + pkt[0] = 0x85; + pkt[1] = 0xA2; + pkt[2] = 0x0A; + pkt[3] = 0x00; + pkt[4] = 0xFF; + pkt[5] = 0xFF; + pkt[6] = 0xFF; + pkt[7] = 0x00; + pkt[8] = 33; /* utf8_general_ci */ + memcpy(pkt + 4 + 4 + 1 + 23, user, strlen(user)); + memcpy(pkt + 4 + 4 + 1 + 23 + strlen(user) + 1, token, 20); + + { + unsigned char head[4]; + + head[0] = (unsigned char)(plen & 0xFF); + head[1] = (unsigned char)((plen >> 8) & 0xFF); + head[2] = (unsigned char)((plen >> 16) & 0xFF); + head[3] = 1; /* sequence */ + if (write(fd, head, 4) != 4) { + snprintf(why, whyn, "cannot send the MySQL login packet"); + close(fd); + return AUTH_NOANSWER; + } + } + { + size_t off = 0; + + while (off < plen) { + ssize_t w = write(fd, pkt + off, plen - off); + + if (w <= 0) { + snprintf(why, whyn, "cannot send the MySQL login"); + close(fd); + return AUTH_NOANSWER; + } + off += (size_t)w; + } + } + if (apex_net_exact(fd, reply, 4) != 0) { + snprintf(why, whyn, "no answer to the MySQL login"); + close(fd); + return AUTH_NOANSWER; + } + { + size_t rlen = (size_t)reply[0] | ((size_t)reply[1] << 8) | + ((size_t)reply[2] << 16); + + if (rlen < 1 || rlen > sizeof(reply) || + apex_net_exact(fd, reply, rlen) != 0) { + snprintf(why, whyn, "truncated MySQL answer"); + close(fd); + return AUTH_NOANSWER; + } + if (reply[0] == 0x00) { + snprintf(why, whyn, "MySQL OK packet, login accepted"); + result = AUTH_HIT; + } else if (reply[0] == 0xFF) { + /* error code 1040 = too many connections, 1203 = max user + * connections; both are the server saying "not now" */ + int code = rlen >= 3 ? (reply[1] | (reply[2] << 8)) : 0; + + if (code == 1040 || code == 1203 || code == 1129) { + snprintf(why, whyn, + "MySQL error %d, too many connections", code); + result = AUTH_RATE; + } else { + snprintf(why, whyn, "MySQL error %d, login refused", + code); + result = AUTH_MISS; + } + } else if (reply[0] == 0xFE) { + snprintf(why, whyn, + "MySQL asks for another auth plugin; only " + "mysql_native_password is spoken"); + result = AUTH_NOANSWER; + } else { + snprintf(why, whyn, "MySQL answer 0x%02x", reply[0]); + result = AUTH_MISS; + } + } + close(fd); + return result; +} + +/* ------------------------------------------------------------------- loop */ + +/* + * The dispatch the run loop calls. Kept as a function pointer so a protocol + * added later is one table entry, not another branch in the loop. + */ +typedef int (*auth_try)(const auth_run *r, const auth_pair *p, char *why, + size_t whyn); + +/* The protocols, with the default port each one listens on. */ +static const struct { + const char *name; + int port; + auth_try fn; +} AUTH_PROTOS[] = { + { "http", 80, try_http_basic }, + { "ftp", 21, try_ftp }, + { "smtp", 25, try_smtp }, + { "imap", 143, try_imap }, + { "pop3", 110, try_pop3 }, + { "mysql", 3306, try_mysql }, +}; + +static size_t AUTH_PROTO_N = sizeof(AUTH_PROTOS) / sizeof(AUTH_PROTOS[0]); + +/* -------------------------------------------------------------- reporting */ + +/* + * One accepted pair becomes a finding with the pair in the evidence file. The + * password is in that file on purpose: a credential finding without the + * credential is not something the operator can act on. The audit log stays + * clean of it, so the log can be shared and the evidence cannot. + */ +static void auth_record(const auth_run *r, const char *proto, + const auth_pair *p, const char *why) +{ + mcp_buf ev; + char title[256]; + char *path; + char tags[128]; + + mcp_buf_init(&ev); + mcp_buf_printf(&ev, "service: %s\nhost: %s\nport: %d\nusername: %s\n" + "password: %s\nanswer: %s\n", + proto, r->target, r->port, p->user, p->pass, why); + path = apex_evidence_save("auth-hit", ev.p, ev.len); + mcp_buf_free(&ev); + snprintf(title, sizeof(title), "Valid %s credentials: %.120s", proto, + p->user); + snprintf(tags, sizeof(tags), "%s,credentials,login", proto); + free(apex_finding_add(r->target, title, "critical", "certain", + "auth_test", path != NULL ? path : "", + "CWE-521", "Rotate the password, then find out how " + "the account was reachable from here.", tags)); + /* the account name is safe for the log; the password is not */ + apex_audit("auth_test", r->target, r->port, 1, proto, p->user); + free(path); +} + +/* + * The run loop. It walks users outer and passwords inner, which is the order + * an operator reading a wordlist expects, and stops on the conditions the + * operator set: the hit, the attempt ceiling, or the rate-limit streak. + */ +static void auth_loop(const auth_run *r, const char *proto, auth_try fn, + char users[][AUTH_CRED_MAX], int nusers, + char passes[][AUTH_CRED_MAX], int npasses, + mcp_buf *hits, auth_stats *st) +{ + int u; + int p; + + memset(st, 0, sizeof(*st)); + mcp_buf_puts(hits, "["); + for (u = 0; u < nusers; u++) { + for (p = 0; p < npasses; p++) { + auth_pair pair; + char why[256]; + int rc; + + if (st->attempts + st->errors >= r->max_attempts) { + st->stopped = 1; + snprintf(st->reason, sizeof(st->reason), + "attempt ceiling %d reached", r->max_attempts); + return; + } + auth_copy(pair.user, sizeof(pair.user), users[u]); + auth_copy(pair.pass, sizeof(pair.pass), passes[p]); + why[0] = '\0'; + rc = fn(r, &pair, why, sizeof(why)); + if (rc == AUTH_NOANSWER) { + st->errors++; + st->streak = 0; + } else { + st->attempts++; + if (rc == AUTH_RATE) { + st->streak++; + } else { + st->streak = 0; + } + if (rc == AUTH_HIT) { + st->hits++; + if (st->hits > 1) + mcp_buf_puts(hits, ","); + mcp_buf_puts(hits, "{\"username\":"); + apex_json_str(hits, pair.user); + mcp_buf_puts(hits, ",\"password\":"); + apex_json_str(hits, pair.pass); + mcp_buf_puts(hits, ",\"answer\":"); + apex_json_str(hits, why); + mcp_buf_puts(hits, "}"); + auth_record(r, proto, &pair, why); + if (r->stop_on_hit) { + st->stopped = 1; + snprintf(st->reason, sizeof(st->reason), + "stopped at the first accepted pair"); + return; + } + } + } + /* + * A streak of rate-limit answers is the service asking for a + * pause. The operator named the threshold; past it the run + * ends and says which answer caused it. + */ + if (r->lockout_limit > 0 && st->streak >= r->lockout_limit) { + st->lockout = 1; + st->stopped = 1; + snprintf(st->reason, sizeof(st->reason), + "%d consecutive rate-limit answers: %.256s", + st->streak, why); + return; + } + if (r->delay_ms > 0) { + struct timespec ts; + + ts.tv_sec = r->delay_ms / 1000; + ts.tv_nsec = (long)(r->delay_ms % 1000) * 1000000L; + nanosleep(&ts, NULL); + } + } + } +} + +/* ------------------------------------------------------------------- tools */ + +/* The protocol table entry for a name, NULL when the operator mistyped it. */ +static size_t proto_index(const char *name) +{ + size_t i; + + for (i = 0; i < AUTH_PROTO_N; i++) { + if (strcmp(AUTH_PROTOS[i].name, name) == 0) + return i; + } + return AUTH_PROTO_N; +} + +static void t_auth_test(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + const char *proto = mcp_arg_string(args, "protocol"); + const char *path = mcp_arg_string(args, "path"); + const char *users_file = mcp_arg_string(args, "userlist"); + const char *pass_file = mcp_arg_string(args, "passlist"); + const char *users_in = mcp_arg_string(args, "users"); + const char *pass_in = mcp_arg_string(args, "passwords"); + int port = mcp_arg_int(args, "port", 0); + int tls = mcp_arg_bool(args, "tls", 0); + auth_run run; + auth_stats st; + char users[AUTH_MAX_WORDS][AUTH_CRED_MAX]; + char passes[AUTH_MAX_WORDS][AUTH_CRED_MAX]; + int nusers; + int npasses; + size_t idx; + char err[256]; + mcp_buf hits; + mcp_buf b; + + (void)user; + if (target == NULL || *target == '\0') { + mcp_reply_error(c, "target is required"); + return; + } + if (proto == NULL || *proto == '\0') { + mcp_reply_error(c, "protocol is required: http, ftp, smtp, imap, " + "pop3 or mysql"); + return; + } + idx = proto_index(proto); + if (idx == AUTH_PROTO_N) { + mcp_buf_init(&b); + mcp_buf_puts(&b, "unknown protocol; the supported ones are "); + for (idx = 0; idx < AUTH_PROTO_N; idx++) { + if (idx > 0) + mcp_buf_puts(&b, ", "); + mcp_buf_puts(&b, AUTH_PROTOS[idx].name); + } + mcp_reply_error(c, b.p); + mcp_buf_free(&b); + return; + } + if (port == 0) + port = AUTH_PROTOS[idx].port; + if (port <= 0 || port > 65535) { + mcp_reply_error(c, "port must be between 1 and 65535"); + return; + } + if (path != NULL && *path != '\0' && path[0] != '/') { + mcp_reply_error(c, "path must start with /"); + return; + } + /* the gate first: nothing is read from disk for a target it refuses */ + if (!gated(c, "auth_test", target, port)) + return; + + err[0] = '\0'; + nusers = words_for(users_file, users_in, users, AUTH_MAX_WORDS, err, + sizeof(err)); + if (nusers < 0) { + mcp_reply_error(c, err); + return; + } + npasses = words_for(pass_file, pass_in, passes, AUTH_MAX_WORDS, err, + sizeof(err)); + if (npasses < 0) { + mcp_reply_error(c, err); + return; + } + if (nusers == 0 || npasses == 0) { + mcp_reply_error(c, "at least one username and one password are " + "required: give users/passwords or userlist/passlist"); + return; + } + + memset(&run, 0, sizeof(run)); + run.target = target; + run.port = port; + run.tls = tls != 0 ? 1 : (strcmp(proto, "http") == 0 ? + apex_looks_tls(port) : 0); + run.delay_ms = mcp_arg_int(args, "delay_ms", 0); + run.max_attempts = mcp_arg_int(args, "max_attempts", 0); + run.stop_on_hit = mcp_arg_bool(args, "stop_on_hit", 0); + run.lockout_limit = mcp_arg_int(args, "lockout_limit", 0); + run.timeout_ms = mcp_arg_int(args, "timeout_ms", 10000); + run.path = path; + if (run.delay_ms < 0) + run.delay_ms = 0; + if (run.timeout_ms <= 0) + run.timeout_ms = 10000; + /* + * No ceiling means the operator wants every pair in the lists. The + * product is the ceiling; it is reported so nobody has to guess how + * long the run will take. + */ + if (run.max_attempts <= 0) + run.max_attempts = nusers * npasses; + if (run.max_attempts > AUTH_MAX_PAIRS) + run.max_attempts = AUTH_MAX_PAIRS; + + mcp_buf_init(&hits); + auth_loop(&run, proto, AUTH_PROTOS[idx].fn, users, nusers, passes, + npasses, &hits, &st); + mcp_buf_puts(&hits, "]"); + + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"protocol\":"); + apex_json_str(&b, proto); + mcp_buf_printf(&b, ",\"target\":\"%s\",\"port\":%d,\"tls\":%s", + target, port, run.tls ? "true" : "false"); + mcp_buf_printf(&b, ",\"users\":%d,\"passwords\":%d", nusers, npasses); + mcp_buf_printf(&b, ",\"attempts\":%d,\"errors\":%d,\"hits\":%d", + st.attempts, st.errors, st.hits); + mcp_buf_printf(&b, ",\"stopped\":%s,\"lockout\":%s", + st.stopped ? "true" : "false", + st.lockout ? "true" : "false"); + mcp_buf_puts(&b, ",\"reason\":"); + if (st.reason[0] != '\0') + apex_json_str(&b, st.reason); + else + mcp_buf_puts(&b, "null"); + mcp_buf_puts(&b, ",\"found\":"); + mcp_buf_puts(&b, hits.p != NULL ? hits.p : "[]"); + mcp_buf_puts(&b, "}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); + mcp_buf_free(&hits); +} + +/* + * A dry run: what the lists contain and how many attempts they add up to, + * without touching the target. Useful before a long run, and the only tool + * here that does not need the gate because it never connects. + */ +static void t_auth_plan(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *users_file = mcp_arg_string(args, "userlist"); + const char *pass_file = mcp_arg_string(args, "passlist"); + const char *users_in = mcp_arg_string(args, "users"); + const char *pass_in = mcp_arg_string(args, "passwords"); + int delay_ms = mcp_arg_int(args, "delay_ms", 0); + char users[AUTH_MAX_WORDS][AUTH_CRED_MAX]; + char passes[AUTH_MAX_WORDS][AUTH_CRED_MAX]; + int nusers; + int npasses; + long long ms; + char err[256]; + mcp_buf b; + + (void)user; + err[0] = '\0'; + nusers = words_for(users_file, users_in, users, AUTH_MAX_WORDS, err, + sizeof(err)); + if (nusers < 0) { + mcp_reply_error(c, err); + return; + } + npasses = words_for(pass_file, pass_in, passes, AUTH_MAX_WORDS, err, + sizeof(err)); + if (npasses < 0) { + mcp_reply_error(c, err); + return; + } + ms = (long long)nusers * npasses * (delay_ms > 0 ? delay_ms : 0); + mcp_buf_init(&b); + mcp_buf_printf(&b, "{\"users\":%d,\"passwords\":%d,\"pairs\":%lld", + nusers, npasses, (long long)nusers * npasses); + mcp_buf_printf(&b, ",\"delay_ms\":%d,\"delay_total_ms\":%lld", + delay_ms > 0 ? delay_ms : 0, ms); + mcp_buf_puts(&b, ",\"first_users\":["); + { + int i; + + for (i = 0; i < nusers && i < 5; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + apex_json_str(&b, users[i]); + } + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* + * The protocols and their default ports, so a client can pick without + * guessing. Static data, no gate. + */ +static void t_auth_protocols(mcp_conn *c, const mcp_json *args, void *user) +{ + mcp_buf b; + size_t i; + + (void)args; + (void)user; + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"protocols\":["); + for (i = 0; i < AUTH_PROTO_N; i++) { + if (i > 0) + mcp_buf_puts(&b, ","); + mcp_buf_puts(&b, "{\"name\":"); + apex_json_str(&b, AUTH_PROTOS[i].name); + mcp_buf_printf(&b, ",\"default_port\":%d}", AUTH_PROTOS[i].port); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +/* + * The hit list of the running session, newest first, without the passwords: + * this is the view an operator checks from a client while a long run is going. + */ +static void t_auth_hits(mcp_conn *c, const mcp_json *args, void *user) +{ + const char *target = mcp_arg_string(args, "target"); + apex_finding list[200]; + int n; + int i; + int first = 1; + mcp_buf b; + + (void)user; + n = apex_finding_scan(list, 200); + mcp_buf_init(&b); + mcp_buf_puts(&b, "{\"hits\":["); + for (i = 0; i < n; i++) { + if (strcmp(list[i].tool, "auth_test") != 0) + continue; + if (target != NULL && *target != '\0' && + strcmp(list[i].target, target) != 0) + continue; + if (!first) + mcp_buf_puts(&b, ","); + first = 0; + mcp_buf_puts(&b, "{\"id\":"); + apex_json_str(&b, list[i].id); + mcp_buf_puts(&b, ",\"target\":"); + apex_json_str(&b, list[i].target); + mcp_buf_puts(&b, ",\"title\":"); + apex_json_str(&b, list[i].title); + mcp_buf_puts(&b, ",\"evidence\":"); + apex_json_str(&b, list[i].evidence); + mcp_buf_puts(&b, "}"); + } + mcp_buf_puts(&b, "]}"); + mcp_reply_json(c, b.p); + mcp_buf_free(&b); +} + +const mcp_tool TOOLS_AUTH[] = { + { "auth_test", + "Try credentials against one in-scope service. Protocols: http (Basic), " + "ftp, smtp (AUTH LOGIN), imap, pop3, mysql (native password). The " + "operator supplies the users and passwords inline or as files, the " + "delay between attempts, the attempt ceiling and the stop conditions. " + "An accepted pair is a protocol answer (235, +OK, 230, OK), saved as " + "evidence and recorded as a finding; a dead connection is counted as an " + "error, not as a miss. Nothing is decided about whether a service " + "should be tested. Gate: the target must be in scope.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}," + "\"protocol\":{\"type\":\"string\",\"description\":\"http, ftp, smtp, " + "imap, pop3 or mysql\"}," + "\"port\":{\"type\":\"integer\",\"description\":\"default per protocol\"}," + "\"tls\":{\"type\":\"boolean\"}," + "\"path\":{\"type\":\"string\",\"description\":\"http only, default /\"}," + "\"users\":{\"type\":\"string\",\"description\":\"comma list\"}," + "\"passwords\":{\"type\":\"string\",\"description\":\"comma list\"}," + "\"userlist\":{\"type\":\"string\",\"description\":\"absolute path, one " + "user per line\"}," + "\"passlist\":{\"type\":\"string\",\"description\":\"absolute path, one " + "password per line\"}," + "\"delay_ms\":{\"type\":\"integer\",\"description\":\"pause between " + "attempts, default 0\"}," + "\"max_attempts\":{\"type\":\"integer\",\"description\":\"ceiling for " + "the run, default all pairs\"}," + "\"stop_on_hit\":{\"type\":\"boolean\",\"description\":\"stop at the " + "first accepted pair\"}," + "\"lockout_limit\":{\"type\":\"integer\",\"description\":\"consecutive " + "rate-limit answers that end the run, 0 disables\"}," + "\"timeout_ms\":{\"type\":\"integer\",\"description\":\"per connection, " + "default 10000\"}}," + "\"required\":[\"target\",\"protocol\"]}", + t_auth_test }, + { "auth_plan", + "Count what a credential run would do without touching the target: how " + "many users and passwords the lists hold, how many pairs that makes and " + "how much delay they add up to. Local only, no connection, no gate.", + "{\"type\":\"object\",\"properties\":{" + "\"users\":{\"type\":\"string\"}," + "\"passwords\":{\"type\":\"string\"}," + "\"userlist\":{\"type\":\"string\"}," + "\"passlist\":{\"type\":\"string\"}," + "\"delay_ms\":{\"type\":\"integer\"}}," + "\"required\":[]}", + t_auth_plan }, + { "auth_protocols", + "List the protocols auth_test speaks and the default port of each.", + "{\"type\":\"object\",\"properties\":{},\"required\":[]}", + t_auth_protocols }, + { "auth_hits", + "The credential findings recorded so far, newest first, with the path to " + "the evidence file that holds the pair. Optionally for one target.", + "{\"type\":\"object\",\"properties\":{" + "\"target\":{\"type\":\"string\"}}," + "\"required\":[]}", + t_auth_hits }, +}; + +const size_t TOOLS_AUTH_N = sizeof(TOOLS_AUTH) / sizeof(TOOLS_AUTH[0]); diff --git a/tests/auth_section.py b/tests/auth_section.py new file mode 100644 index 0000000..ee98914 --- /dev/null +++ b/tests/auth_section.py @@ -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) diff --git a/tests/gate_audit.py b/tests/gate_audit.py index f46f36f..e671a28 100755 --- a/tests/gate_audit.py +++ b/tests/gate_audit.py @@ -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 diff --git a/tests/run.py b/tests/run.py index ee78bb2..10cfb1d 100755 --- a/tests/run.py +++ b/tests/run.py @@ -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()