#!/usr/bin/env python3
"""
wificap.py — host-side driver for the wificap capture appliance.

The board is self-contained: it surveys, parks, captures and writes pcap to
its own SD card without a host attached. This tool is for the half of the
workflow that is easier on a laptop -- picking a target out of a survey,
watching counters while a capture runs, and pulling the finished pcap off the
card over the same USB cable that is already plugged in.

It speaks the board's line protocol: one command per line, replies tagged
OK / ERR / STAT / AP / HS / FILE / GET / B64 / END.

Usage:
    wificap.py survey [--seconds 20]       sweep and print what is on the air
    wificap.py watch [--target BSSID]      park and show live counters
    wificap.py pull [FILE] [-o DIR]        copy captures off the card
    wificap.py ls                          list captures on the card
    wificap.py cmd "park 11"               send one raw command

SPDX-License-Identifier: MIT
"""

from __future__ import annotations

import argparse
import base64
import binascii
import os
import sys
import time

try:
    import serial
except ImportError:
    sys.exit("pyserial is required: pip install pyserial")

DEFAULT_PORT = "/dev/ttyACM0"
BAUD = 115200


class Board:
    """A line-oriented conversation with the board."""

    def __init__(self, port: str, baud: int = BAUD, quiet: bool = True):
        self.s = serial.Serial(port, baud, timeout=0.2)
        self.quiet = quiet
        # The board may be mid-sweep and chatty; start from a clean slate.
        time.sleep(0.2)
        self.s.reset_input_buffer()

    def close(self) -> None:
        self.s.close()

    def send(self, cmd: str) -> None:
        self.s.write((cmd + "\n").encode())
        self.s.flush()

    def read_until(self, stop, timeout: float = 5.0) -> list[str]:
        """Collect lines until stop(line) is true or the timeout expires.

        The board echoes commands and interleaves ESP_LOG output with replies,
        so callers filter by tag rather than assuming the next line is theirs.
        """
        out: list[str] = []
        buf = b""
        end = time.time() + timeout
        while time.time() < end:
            buf += self.s.read(4096)
            while b"\n" in buf:
                raw, buf = buf.split(b"\n", 1)
                line = raw.decode("utf-8", "replace").strip("\r\n ")
                if not line:
                    continue
                out.append(line)
                if stop(line):
                    return out
        return out

    def command(self, cmd: str, timeout: float = 5.0) -> list[str]:
        self.send(cmd)
        return self.read_until(
            lambda l: l.startswith(("OK", "ERR", "STAT", "END")), timeout
        )


def parse_stat(lines: list[str]) -> dict[str, str]:
    for line in lines:
        if line.startswith("STAT "):
            out = {}
            for field in line[5:].split():
                if "=" in field:
                    k, v = field.split("=", 1)
                    out[k] = v
            return out
    return {}


# ---------------------------------------------------------------- commands


def cmd_survey(b: Board, args) -> int:
    b.command("survey")
    print(f"sweeping for {args.seconds}s ...", file=sys.stderr)

    deadline = time.time() + args.seconds
    while time.time() < deadline:
        time.sleep(1.0)
        b.s.reset_input_buffer()

    lines = b.command("aps", timeout=8.0)
    aps = []
    for line in lines:
        if not line.startswith("AP "):
            continue
        rec = {}
        parts = line[3:].split(None, 1)
        rec["bssid"] = parts[0]
        for field in (parts[1] if len(parts) > 1 else "").split(" ", 3):
            if "=" in field:
                k, v = field.split("=", 1)
                rec[k] = v
        # ssid= is last and may contain spaces, so recover it from the raw line
        if "ssid=" in line:
            rec["ssid"] = line.split("ssid=", 1)[1]
        aps.append(rec)

    if not aps:
        print("no access points seen; is the board surveying?", file=sys.stderr)
        return 1

    aps.sort(key=lambda a: (int(a.get("ch", 0)), -int(a.get("rssi", -100))))
    print(f"{'BSSID':<18} {'CH':>4} {'RSSI':>5} {'BCN':>5}  SSID")
    for a in aps:
        print(
            f"{a['bssid']:<18} {a.get('ch','?'):>4} {a.get('rssi','?'):>5} "
            f"{a.get('beacons','?'):>5}  {a.get('ssid','')}"
        )
    print(f"\n{len(aps)} access point(s).", file=sys.stderr)
    print(
        "pick one and run:  wificap.py watch --target <BSSID>",
        file=sys.stderr,
    )
    return 0


def cmd_watch(b: Board, args) -> int:
    if args.target:
        for line in b.command(f"target {args.target}"):
            if line.startswith(("OK", "ERR")):
                print(line, file=sys.stderr)
    if args.channel:
        for line in b.command(f"park {args.channel}"):
            if line.startswith(("OK", "ERR")):
                print(line, file=sys.stderr)

    if args.record:
        for line in b.command(f"rec {args.record}"):
            if line.startswith(("OK", "ERR")):
                print(line, file=sys.stderr)

    print("watching; Ctrl-C to stop\n", file=sys.stderr)
    hdr = f"{'ch':>4} {'f/s':>5} {'frames':>8} {'eapol':>6} {'pairs':>6} {'written':>8} {'bytes':>9}  state"
    print(hdr)

    try:
        while True:
            st = parse_stat(b.command("stat", timeout=3.0))
            if st:
                state = "CRACKABLE" if st.get("crackable") == "1" else st.get("mode", "?")
                if st.get("drop", "0") != "0":
                    state += f" drop={st['drop']}"
                print(
                    f"{st.get('ch','?'):>4} {st.get('fps','?'):>5} "
                    f"{st.get('frames','?'):>8} {st.get('eapol','?'):>6} "
                    f"{st.get('hs','?'):>6} {st.get('written','?'):>8} "
                    f"{st.get('bytes','?'):>9}  {state}"
                )
            time.sleep(args.interval)
    except KeyboardInterrupt:
        print("\nstopping capture", file=sys.stderr)
        if args.record:
            for line in b.command("rec off"):
                if line.startswith(("OK", "ERR")):
                    print(line, file=sys.stderr)
        for line in b.command("hs", timeout=4.0):
            if line.startswith("HS "):
                print(line, file=sys.stderr)
    return 0


def list_files(b: Board) -> list[tuple[str, int]]:
    files = []
    for line in b.command("ls", timeout=8.0):
        if line.startswith("FILE "):
            parts = line.split()
            if len(parts) >= 3:
                files.append((parts[1], int(parts[2])))
    return files


def cmd_ls(b: Board, args) -> int:
    files = list_files(b)
    if not files:
        print("no files on the card", file=sys.stderr)
        return 1
    for name, size in files:
        print(f"{size:>10}  {name}")
    return 0


def cmd_pull(b: Board, args) -> int:
    targets = [args.file] if args.file else [n for n, _ in list_files(b)]
    if not targets:
        print("nothing to pull", file=sys.stderr)
        return 1

    os.makedirs(args.outdir, exist_ok=True)
    rc = 0

    for name in targets:
        print(f"pulling {name} ...", file=sys.stderr)
        b.send(f"get {name}")

        data = bytearray()
        expect_size = -1
        want_crc = None
        buf = b""
        end = time.time() + args.timeout

        while time.time() < end:
            buf += b.s.read(4096)
            while b"\n" in buf:
                raw, buf = buf.split(b"\n", 1)
                line = raw.decode("utf-8", "replace").strip("\r\n ")
                if line.startswith("GET "):
                    parts = line.split()
                    if len(parts) >= 3:
                        expect_size = int(parts[2])
                elif line.startswith("B64 "):
                    try:
                        data += base64.b64decode(line[4:], validate=True)
                    except binascii.Error:
                        print(f"  bad base64 line, aborting", file=sys.stderr)
                        rc = 1
                        buf = b""
                        end = 0
                        break
                elif line.startswith("END"):
                    if "crc32=" in line:
                        want_crc = int(line.split("crc32=", 1)[1], 16)
                    end = 0
                    break
                elif line.startswith("ERR"):
                    print(f"  {line}", file=sys.stderr)
                    rc = 1
                    end = 0
                    break

        if want_crc is None:
            print(f"  transfer did not complete", file=sys.stderr)
            rc = 1
            continue

        got_crc = binascii.crc32(bytes(data)) & 0xFFFFFFFF
        if got_crc != want_crc:
            # A silently truncated pcap still opens, so this matters.
            print(
                f"  CRC mismatch: board {want_crc:08x}, received {got_crc:08x}",
                file=sys.stderr,
            )
            rc = 1
            continue
        if expect_size >= 0 and len(data) != expect_size:
            print(
                f"  size mismatch: expected {expect_size}, got {len(data)}",
                file=sys.stderr,
            )
            rc = 1
            continue

        out = os.path.join(args.outdir, os.path.basename(name))
        with open(out, "wb") as fh:
            fh.write(data)
        print(f"  {len(data)} bytes -> {out}  (crc32 {got_crc:08x} ok)", file=sys.stderr)

    return rc


def cmd_pmkid(b: Board, args) -> int:
    """Optional ACTIVE mode: associate to one AP to collect its PMKID.

    Everything else this tool does is passive. This is not: the board
    transmits an authentication and association request to the target, which
    is what makes the AP volunteer the PMKID in EAPOL message 1. Point it at
    an access point you administer.
    """
    if not args.yes:
        print(
            "This mode TRANSMITS to the target access point.\n"
            "Use it only on an AP you administer.\n"
            "Re-run with --yes to proceed.",
            file=sys.stderr,
        )
        return 2

    if args.survey:
        print("surveying first so the channel and SSID are known ...", file=sys.stderr)
        b.command("survey")
        time.sleep(args.survey)

    lines = b.command(f"attack {args.target} {args.seconds}", timeout=args.seconds + 20)
    for line in lines:
        if line.startswith(("OK", "ERR")):
            print(line, file=sys.stderr)

    # Print whatever PMKIDs the board now holds, in hashcat 22000 form.
    out = []
    for line in b.command("pmkid", timeout=6.0):
        if line.startswith("PMKID "):
            out.append(line[6:])

    if not out:
        print("no PMKID recovered", file=sys.stderr)
        return 1

    for h in out:
        print(h)

    if args.outfile:
        with open(args.outfile, "a") as fh:
            for h in out:
                fh.write(h + "\n")
        print(f"\nappended {len(out)} line(s) to {args.outfile}", file=sys.stderr)
        print(f"crack with:  hashcat -m 22000 {args.outfile} wordlist", file=sys.stderr)

    return 0


def cmd_raw(b: Board, args) -> int:
    for line in b.command(args.text, timeout=args.timeout):
        print(line)
    return 0


# ---------------------------------------------------------------- main


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__.split("\n")[1])
    p.add_argument("-p", "--port", default=DEFAULT_PORT, help="serial port")
    sub = p.add_subparsers(dest="cmd", required=True)

    s = sub.add_parser("survey", help="sweep and list access points")
    s.add_argument("--seconds", type=int, default=20)
    s.set_defaults(fn=cmd_survey)

    w = sub.add_parser("watch", help="park, capture, and show live counters")
    w.add_argument("--target", help="BSSID to filter on and park against")
    w.add_argument("--channel", type=int, help="park on this channel instead")
    w.add_argument(
        "--record",
        nargs="?",
        const="hs",
        choices=["hs", "all"],
        help="also write pcap to the card (default: hs)",
    )
    w.add_argument("--interval", type=float, default=1.0)
    w.set_defaults(fn=cmd_watch)

    l = sub.add_parser("ls", help="list captures on the card")
    l.set_defaults(fn=cmd_ls)

    g = sub.add_parser("pull", help="copy captures off the card")
    g.add_argument("file", nargs="?", help="filename (default: all)")
    g.add_argument("-o", "--outdir", default=".")
    g.add_argument("--timeout", type=float, default=120.0)
    g.set_defaults(fn=cmd_pull)

    # Optional ACTIVE mode. Deliberately not reachable from survey or watch:
    # it is the one thing here that transmits, so it takes its own subcommand
    # and its own confirmation flag.
    k = sub.add_parser(
        "pmkid",
        help="ACTIVE: associate to one AP to collect its PMKID (transmits)",
    )
    k.add_argument("--target", required=True, help="BSSID of an AP you administer")
    k.add_argument("--seconds", type=int, default=8, help="how long to wait for M1")
    k.add_argument(
        "--survey",
        type=int,
        nargs="?",
        const=20,
        help="survey first for N seconds to learn the channel and SSID",
    )
    k.add_argument("-o", "--outfile", help="append hashcat 22000 lines to this file")
    k.add_argument("--yes", action="store_true", help="confirm that you may transmit")
    k.set_defaults(fn=cmd_pmkid)

    c = sub.add_parser("cmd", help="send one raw command")
    c.add_argument("text")
    c.add_argument("--timeout", type=float, default=5.0)
    c.set_defaults(fn=cmd_raw)

    args = p.parse_args()

    try:
        board = Board(args.port)
    except serial.SerialException as e:
        print(f"cannot open {args.port}: {e}", file=sys.stderr)
        return 2

    try:
        return args.fn(board, args)
    finally:
        board.close()


if __name__ == "__main__":
    sys.exit(main())
