# Can Bus Intrusion Detection

> Use when building or testing a CAN bus intrusion detection system for a vehicle you own or an authorized bench setup. Covers baseline traffic profiling, frequency and payload anomaly detection, ID allowlisting, masquerade and suspension attack detection, IDS alert triage, and safe evaluation with recorded traffic before any live deployment. Also use when a fleet or bench program needs CAN anomalies explained in terms of which ECU, which message ID, and what changed.

- Skill: `mizazhaider-ceh/can-bus-intrusion-detection` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/can-bus-intrusion-detection`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/can-bus-intrusion-detection/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/can-bus-intrusion-detection

---


A CAN bus intrusion detection system (IDS) watches traffic that was
never designed to be authenticated and flags what does not fit the
vehicle's normal behaviour. Legitimate CAN traffic is highly periodic,
so most attacks stand out as timing changes, new message IDs, payload
jumps, or an ECU that stops talking. This sub-skill covers the
defensive side of can-bus-security, building and tuning detection on
recorded traffic first, then on a bench rig, and only then in a
parked vehicle you own. Never deploy an IDS that blocks or injects
frames on a moving vehicle, and never test detection by attacking a
vehicle you do not own.

## Quick Workflow

1. Capture a clean baseline from the bench rig or your own parked
   vehicle, covering idle, driving cycles on the bench, and each
   controlled action you care about.
2. Profile the baseline per message ID, period, payload length,
   value ranges, and which IDs appear together.
3. Write detection rules in layers, starting with allowlisting of
   known IDs, then frequency checks, then payload plausibility.
4. Evaluate every rule offline against recorded traffic, including
   recordings that contain injected or replayed frames.
5. Tune thresholds until false positives on clean traffic are rare
   enough that an analyst will still read the alerts.
6. Deploy in monitor-only mode on the bench, triage every alert, and
   label it true positive, false positive, or inconclusive.
7. Only after bench validation, run monitor-only in the parked
   vehicle and repeat the triage loop.
8. Report detection coverage per attack class, with the false
   positive rate measured on clean traffic.

## 1. Baseline profiling with SocketCAN logs

Capture with candump, then profile each ID with a short script.
Periodicity is the strongest signal on CAN, so measure inter-arrival
time, not just message counts.

```bash
# Capture a clean baseline on the bench rig (10 minutes, idle plus actions)
sudo ip link set can0 up type can bitrate 500000
candump -l can0
# Rename the log so baselines stay identifiable
mv candump-*.log can_baseline_idle.log

# Capture a second baseline while exercising controls on the bench
candump -l can0
mv candump-*.log can_baseline_active.log
```

```python
# Profile period and payload range per CAN ID from a candump log
import re
from collections import defaultdict

frames = defaultdict(list)
pattern = re.compile(r"\((\d+\.\d+)\)\s+\S+\s+([0-9A-F]+)#([0-9A-F]*)")
for line in open("can_baseline_idle.log"):
    m = pattern.search(line)
    if m:
        frames[m.group(2)].append((float(m.group(1)), m.group(3)))

for can_id, samples in sorted(frames.items()):
    times = [t for t, _ in samples]
    gaps = [b - a for a, b in zip(times, times[1:])]
    avg_gap = sum(gaps) / len(gaps) if gaps else 0
    print(f"{can_id} - count {len(samples)} - mean period {avg_gap:.4f}s")
```

## 2. Frequency and allowlist detection rules

A frequency rule fires when a normally periodic ID arrives far too
fast (flooding or injection) or stops entirely (suspension). An
allowlist rule fires on any ID absent from the baseline. Keep the
two separate so triage can tell a new ID apart from a timing attack.

```python
# Frequency and allowlist checks over a live or recorded stream
# Thresholds come from the baseline profile, never from guesswork.
ALLOWED_IDS = {"123", "1A4", "2F0"}
EXPECTED_PERIOD = {"123": 0.010, "1A4": 0.100, "2F0": 0.020}
last_seen = {}

def check_frame(can_id, timestamp, payload):
    alerts = []
    if can_id not in ALLOWED_IDS:
        alerts.append(f"UNKNOWN_ID {can_id} payload {payload}")
    if can_id in last_seen and can_id in EXPECTED_PERIOD:
        gap = timestamp - last_seen[can_id]
        if gap < EXPECTED_PERIOD[can_id] * 0.5:
            alerts.append(f"FREQUENCY_HIGH {can_id} gap {gap:.4f}s")
    last_seen[can_id] = timestamp
    return alerts
```

```bash
# Evaluate a rule set offline against a recording with injected frames
# The recording must be labelled, so every alert can be scored.
python3 ids_evaluate.py --baseline can_baseline_idle.log \
  --test can_test_injection.log --rules rules.yaml
# Expected output shape: true positives, false positives, and the
# per-ID breakdown, so one noisy ID cannot hide behind a good total.
```

## 3. Payload plausibility and masquerade detection

Frequency alone misses a masquerade attack, where a compromised ECU
sends plausible frames at the right rate with wrong values. Payload
rules check value ranges, rates of change, and cross-signal
consistency, for example a speed signal that jumps while the wheel
speed signals stay still.

```python
# Plausibility check on a decoded signal, using baseline value ranges
# SPEED_MIN and SPEED_MAX come from the baseline profile for this ID.
def check_speed(value, previous_value, wheel_speeds):
    alerts = []
    if not 0 <= value <= 250:
        alerts.append(f"VALUE_OUT_OF_RANGE speed={value}")
    if previous_value is not None and abs(value - previous_value) > 30:
        alerts.append(f"VALUE_JUMP speed {previous_value} to {value}")
    if wheel_speeds and abs(value - sum(wheel_speeds) / len(wheel_speeds)) > 10:
        alerts.append("CROSS_SIGNAL_MISMATCH speed vs wheel speeds")
    return alerts
```

```bash
# Build a labelled test set: clean traffic plus each attack class
# Run each class as its own file so detection coverage is per class.
# Classes to cover: flooding, replay, masquerade, suspension, new ID.
ls can_test_*.log
# can_test_flooding.log, can_test_replay.log, can_test_masquerade.log
# can_test_suspension.log, can_test_new_id.log
```

## 4. Alert triage and tuning loop

An IDS that cries wolf gets ignored, so triage is part of the
system, not an afterthought. Every alert needs the ID, the rule that
fired, the baseline expectation, and the surrounding frames. Tune
the noisiest rule first, and re-run the whole labelled set after
each change so fixing one rule does not silently break another.

```bash
# Triage template: one line per alert, filled in during review
# alert_id, rule, can_id, observed, expected, verdict, action
# Example rows kept in ids_triage.csv for the tuning record.
head -5 ids_triage.csv
# After tuning, re-score the full labelled set before redeploying.
python3 ids_evaluate.py --baseline can_baseline_idle.log \
  --test can_test_*.log --rules rules.yaml
```

## Edge cases

- Gateway-forwarded IDs: an ID that is legitimate on one bus may be
  unexpected on another, so keep one allowlist per bus, not one
  global list, and record which gateway forwards what.
- Event-driven frames: door, button, and diagnostic frames are
  legitimately aperiodic, so frequency rules must not apply to them,
  and allowlisting plus payload checks carry the load instead.
- Diagnostic sessions: UDS traffic during servicing introduces new
  IDs and bursts that look like attacks, so log maintenance windows
  and exclude or separately label diagnostic sessions.
- Bus-off and error frames: a faulty transceiver can flood error
  frames that mimic a flooding attack, so check physical layer health
  before concluding an attack is under way.
- Multi-ECU signals: the same physical value may appear on several
  IDs from different ECUs, so a cross-signal mismatch needs the
  sender mapping confirmed, or it becomes a false positive factory.
- Retransmissions and arbitration: CAN arbitration delays frames
  under load, so tight period thresholds on a busy bus will fire on
  legitimate congestion, and thresholds need slack for bus load.

## Key references

- ISO 11898, the CAN protocol family, for frame format, arbitration,
  and error handling that shape every detection rule.
- ISO 21434, road vehicles cybersecurity engineering, for threat
  analysis and risk assessment that justifies which attack classes
  the IDS must cover.
- SAE J1939 and manufacturer CAN documentation for the specific
  network under test, used to confirm which IDs and periods are
  legitimate before any rule is written.
- SocketCAN documentation and the can-utils toolset, for capture,
  replay, and analysis tooling on Linux bench setups.
- The parent skill can-bus-security, for sniffing, message analysis,
  and gateway mapping that produce the baseline this sub-skill
  depends on.

