"""Extract and execute only the packet mutation method on in-memory Scapy packets."""
import ast
import hashlib
import json
from pathlib import Path
import random
import sys
import scapy.all as scapy
from scapy.layers.inet import IP, TCP, UDP


def replay(checkout):
    path = Path(checkout) / "netfilter.py"
    source = path.read_text()
    tree = ast.parse(source)
    cls = next(node for node in tree.body if isinstance(node, ast.ClassDef)
               and node.name == "PentestNetFilter")
    method = next(node for node in cls.body if isinstance(node, ast.FunctionDef)
                  and node.name == "modify_packet_for_evasion")
    scope = {"random": random.Random(2026), "scapy": scapy, "IP": IP, "TCP": TCP, "UDP": UDP}
    exec(compile(ast.Module(body=[method], type_ignores=[]), str(path), "exec"), scope)
    modify = scope[method.name]
    syn = IP(src="192.0.2.1", dst="192.0.2.2") / TCP(flags="S", seq=0xffffffff, window=1024)
    changed = modify(None, syn.copy())
    assert changed[TCP].window in [8192, 16384, 29200, 32768, 65535]
    assert 0 <= changed[TCP].seq <= 0xffffffff
    assert 1 <= (changed[TCP].seq - syn[TCP].seq) % (2**32) <= 100
    request = b"GET / HTTP/1.1\r\nHost: fixture.example\r\nUser-Agent: fixture\r\n\r\n"
    http = IP(src="192.0.2.1", dst="192.0.2.2") / TCP(flags="PA") / scapy.Raw(load=request)
    rewritten = modify(None, http.copy())
    assert b"Chrome/120.0.0.0" in rewritten[scapy.Raw].load
    assert b"Host: fixture.example\r\n" in rewritten[scapy.Raw].load
    lower = http.copy()
    lower[scapy.Raw].load = request.replace(b"User-Agent:", b"user-agent:")
    assert modify(None, lower.copy())[scapy.Raw].load == lower[scapy.Raw].load
    untouched = IP(src="192.0.2.1", dst="192.0.2.2") / UDP() / scapy.Raw(load=b"OWNED FIXTURE")
    assert bytes(modify(None, untouched.copy())) == bytes(untouched)
    serialized = IP(bytes(rewritten))
    assert serialized.len == len(bytes(serialized))
    return {"source_sha256": hashlib.sha256(source.encode()).hexdigest(),
            "scapy_version": scapy.conf.version, "assertions": 8,
            "syn_window": changed[TCP].window, "syn_sequence": changed[TCP].seq,
            "rewritten_payload_bytes": len(rewritten[scapy.Raw].load),
            "lowercase_header_unchanged": True,
            "scope": "Actual extracted method; no sniffing, sockets, firewall changes, packet send or IDS."}


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python3 netfilter_packet_replay.py /path/to/flea-flicker-netfilter")
    print(json.dumps(replay(sys.argv[1]), indent=2))
