# =========================================================================== # 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)