#!/usr/bin/env python3
"""wifi24_capture.py - capture 802.11 traffic you are actually able to read.

The rule this tool enforces: a frame is written to the output only if it is
unencrypted, or if it is encrypted and the keys you supplied decrypted it.
Everything else - someone else's protected traffic, which you have the keys to
neither read nor lawfully collect - is dropped before it ever reaches a file.

That is a deliberate design choice, not a technical limit. A monitor-mode card
hears every frame in the air, and the usual capture tools write all of it to
disk. Keeping ciphertext you cannot read buys you nothing analytically and
leaves you holding other people's traffic, so this tool throws it away.

How the gate works
------------------
Two filter expressions do the work, both evaluated by tshark with your keys
loaded:

  permit  wlan.fc.protected == 0 || (wlan.fc.protected == 1 && llc)
  forbid  wlan.fc.protected == 1 && !llc

The Protected Frame bit in the 802.11 frame control field says whether the
payload is encrypted. An LLC header is only visible above an encrypted frame
when decryption succeeded, so `protected && llc` means "encrypted, and we read
it". The forbidden expression is the exact complement, and it is re-run against
the finished file as a post-condition: if it matches even one frame, the output
is deleted rather than handed back. Fail closed.

The intermediate raw capture - which does contain everything the card heard -
lives in a 0700 directory and is shredded before the tool exits.

Scope
-----
Capturing traffic on networks you do not run, or do not have permission to
test, is unlawful in most places regardless of what you can decrypt. This tool
reduces what you collect; it does not grant you authority to collect it.
"""

import argparse
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile

PERMIT = "wlan.fc.protected == 0 || (wlan.fc.protected == 1 && llc)"
FORBID = "wlan.fc.protected == 1 && !llc"

KEY_TYPES = ("wpa-pwd", "wpa-psk", "wep")


def parse_args(argv=None):
    p = argparse.ArgumentParser(
        description="Capture 802.11 traffic, keeping only frames that are unencrypted "
                    "or that your keys decrypt.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""examples:
  # open / unencrypted traffic and management frames only, no keys at all
  wifi24_capture.py -i mon0 -c 6 -d 30 -w cafe.pcapng

  # a WPA2 network whose passphrase you know
  wifi24_capture.py -i mon0 -c 1 -d 60 -w lab.pcapng \\
      --key wpa-pwd:'correct horse battery staple:PSU-IoT'

  # same thing with the precomputed PSK instead of the passphrase
  wifi24_capture.py -i mon0 -c 1 -d 60 -w lab.pcapng --key wpa-psk:0123...  # 64 hex

key formats:
  wpa-pwd:<passphrase>[:<ssid>]   passphrase, optionally bound to one SSID
  wpa-psk:<64 hex digits>         precomputed pairwise master key
  wep:<hex digits>                WEP key

Decrypting WPA/WPA2 unicast traffic also needs the 4-way handshake for each
station in the capture, so start the capture before the client associates (or
wait out a rekey). Without the handshake the frames stay encrypted, and this
tool will correctly refuse to keep them.""")
    p.add_argument("-i", "--interface", required=True, help="monitor-capable interface (e.g. wlan1, mon0)")
    p.add_argument("-w", "--write", required=True, help="output pcapng file")
    p.add_argument("-c", "--channel", type=int, help="2.4 GHz channel 1-14 to sit on")
    p.add_argument("-d", "--duration", type=int, default=30, help="seconds to capture (default 30)")
    p.add_argument("--key", action="append", default=[], metavar="TYPE:VALUE",
                   help="decryption key; repeatable. See key formats below.")
    p.add_argument("--keep-raw", metavar="PATH",
                   help="also save the unfiltered capture here. This is everything the "
                        "card heard, encrypted frames included, and defeats the point of "
                        "this tool. For debugging the tool itself.")
    p.add_argument("--dry-run", action="store_true", help="show what would run, capture nothing")
    return p.parse_args(argv)


def check_key(spec):
    """Validate one --key argument; return it, or raise ValueError."""
    kind, _, value = spec.partition(":")
    if kind not in KEY_TYPES:
        raise ValueError(f"unknown key type {kind!r} (expected one of {', '.join(KEY_TYPES)})")
    if not value:
        raise ValueError(f"key {kind!r} has no value")
    if kind == "wpa-psk" and not re.fullmatch(r"[0-9a-fA-F]{64}", value):
        raise ValueError("wpa-psk takes exactly 64 hex digits")
    if kind == "wep" and not re.fullmatch(r"[0-9a-fA-F]+", value.replace(":", "")):
        raise ValueError("wep takes hex digits")
    return kind, value


def key_options(keys):
    """Turn validated keys into tshark -o arguments."""
    opts = []
    if keys:
        opts += ["-o", "wlan.enable_decryption:TRUE"]
    for kind, value in keys:
        opts += ["-o", f'uat:80211_keys:"{kind}","{value}"']
    return opts


def iface_is_monitor(iface):
    try:
        out = subprocess.run(["iw", "dev", iface, "info"], capture_output=True, text=True, timeout=10)
    except (OSError, subprocess.SubprocessError):
        return None
    if out.returncode != 0:
        return None
    m = re.search(r"^\s*type\s+(\S+)", out.stdout, re.M)
    return m.group(1) if m else None


def set_channel(iface, channel):
    """Best effort. Returns True, or False with advice printed."""
    r = subprocess.run(["iw", "dev", iface, "set", "channel", str(channel)],
                       capture_output=True, text=True)
    if r.returncode == 0:
        return True
    print(f"wifi24_capture: could not set channel {channel} on {iface}: "
          f"{r.stderr.strip() or 'failed'}", file=sys.stderr)
    print(f"  run this first, then re-run without -c:\n"
          f"    sudo iw dev {iface} set channel {channel}", file=sys.stderr)
    return False


def count_matching(path, filt, keys):
    """How many frames in path match filt, with keys loaded."""
    cmd = ["tshark", "-r", path, *key_options(keys), "-Y", filt, "-T", "fields", "-e", "frame.number"]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode != 0:
        raise RuntimeError(f"tshark failed on {path}: {r.stderr.strip().splitlines()[-1:] or ['?']}")
    return sum(1 for line in r.stdout.splitlines() if line.strip())


def shred(path):
    """Remove a file, overwriting it first when shred is available."""
    if not os.path.exists(path):
        return
    if shutil.which("shred"):
        subprocess.run(["shred", "-u", path], capture_output=True)
    if os.path.exists(path):
        try:
            with open(path, "r+b") as f:
                f.write(b"\0" * os.path.getsize(path))
                f.flush()
                os.fsync(f.fileno())
        except OSError:
            pass
        os.unlink(path)


def main(argv=None):
    args = parse_args(argv)

    for tool in ("dumpcap", "tshark"):
        if shutil.which(tool) is None:
            print(f"wifi24_capture: {tool} not found (install wireshark-cli)", file=sys.stderr)
            return 1

    try:
        keys = [check_key(k) for k in args.key]
    except ValueError as e:
        print(f"wifi24_capture: {e}", file=sys.stderr)
        return 2

    if args.channel is not None and not 1 <= args.channel <= 14:
        print("wifi24_capture: channel must be 1-14", file=sys.stderr)
        return 2

    iftype = iface_is_monitor(args.interface)
    if iftype is None:
        print(f"wifi24_capture: {args.interface} not found, or iw is unavailable", file=sys.stderr)
        return 1

    # dumpcap -I puts a managed interface into monitor mode. An interface that is
    # already in monitor mode is captured as-is; asking for -I on one of those can
    # fail outright.
    monitor_flag = [] if iftype == "monitor" else ["-I"]

    if not keys:
        print("wifi24_capture: no keys given - only unencrypted frames "
              "(management, control, open networks) will be kept.")

    if args.channel is not None and not args.dry_run:
        set_channel(args.interface, args.channel)

    workdir = tempfile.mkdtemp(prefix="wifi24-")
    os.chmod(workdir, 0o700)
    raw = os.path.join(workdir, "raw.pcapng")

    dumpcap_cmd = ["dumpcap", *monitor_flag, "-i", args.interface,
                   "-a", f"duration:{args.duration}", "-w", raw]
    tshark_cmd = ["tshark", "-r", raw, *key_options(keys), "-Y", PERMIT, "-w", args.write]

    if args.dry_run:
        print("would run:")
        print("  " + shlex.join(dumpcap_cmd))
        print("  " + shlex.join(tshark_cmd))
        print(f"  then assert 0 frames match: {FORBID}")
        os.rmdir(workdir)
        return 0

    try:
        print(f"capturing {args.duration}s on {args.interface}"
              f"{f' channel {args.channel}' if args.channel else ''}...")
        r = subprocess.run(dumpcap_cmd, capture_output=True, text=True)
        if r.returncode != 0 or not os.path.exists(raw):
            tail = (r.stderr or r.stdout).strip().splitlines()[-3:]
            print("wifi24_capture: capture failed:", file=sys.stderr)
            for line in tail:
                print(f"  {line}", file=sys.stderr)
            print("  unprivileged capture needs cap_net_raw+cap_net_admin on dumpcap "
                  "and membership in the wireshark group.", file=sys.stderr)
            return 1

        total = count_matching(raw, "frame", keys)

        # Apply the gate. tshark's -Y filters what -w writes, so the encrypted
        # frames we cannot read are never copied into the output file.
        r = subprocess.run(tshark_cmd, capture_output=True, text=True)
        if r.returncode != 0:
            print(f"wifi24_capture: filtering failed: {r.stderr.strip()}", file=sys.stderr)
            return 1

        kept = count_matching(args.write, "frame", keys)

        # Fail closed: prove the output holds nothing we could not read.
        leaked = count_matching(args.write, FORBID, keys)
        if leaked:
            shred(args.write)
            print(f"wifi24_capture: {leaked} undecryptable frame(s) reached the output; "
                  f"deleted {args.write} rather than keep them.", file=sys.stderr)
            return 1

        if args.keep_raw:
            shutil.copy2(raw, args.keep_raw)
            print(f"  raw capture kept at {args.keep_raw} - it contains encrypted "
                  f"frames you cannot read.")

        dropped = total - kept
        print(f"heard   {total:>6} frames")
        print(f"kept    {kept:>6} unencrypted or successfully decrypted -> {args.write}")
        print(f"dropped {dropped:>6} encrypted and unreadable, discarded")
        if not total:
            # A dead RX path looks exactly like a quiet channel in the numbers
            # above, so say so rather than let 0/0/0 pass for a good capture.
            print(f"\nwifi24_capture: {args.interface} handed up no frames at all.",
                  file=sys.stderr)
            print("  That is almost never a quiet channel - an interface in monitor "
                  "mode on a live\n  channel always hears beacons. Check it with:",
                  file=sys.stderr)
            print(f"    iw dev {args.interface} info", file=sys.stderr)
            print(f"    dumpcap -i {args.interface} -a duration:5 -w /dev/null",
                  file=sys.stderr)
            print("  If the interface looks correct and still hears nothing, its RX "
                  "path has probably\n  died - retuning across bands while in monitor "
                  "mode can do this. Bounce it:", file=sys.stderr)
            print(f"    sudo ip link set {args.interface} down && "
                  f"sudo ip link set {args.interface} up", file=sys.stderr)
            print("  then re-apply type, monitor flags and channel.", file=sys.stderr)
            return 1

        if not kept:
            print("nothing kept. Either the air was silent, or everything in it was "
                  "encrypted with keys you did not supply.")
        return 0
    finally:
        shred(raw)
        try:
            os.rmdir(workdir)
        except OSError:
            pass


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