车联网安全之渗透实战 —— CAN 总线及协议:能读懂车内语言
本文仅用于安全研究与防御加固目的。演示内容全部基于虚拟 CAN 总线与实验数据,帮助理解 CAN/ISO-TP/诊断通信与固件安全审计思路;不提供面向真实车辆的操控复现与攻击指令
前言
声明:本文仅用于安全研究与防御加固目的。演示内容全部基于虚拟 CAN 总线与实验数据,帮助理解 CAN/ISO-TP/诊断通信与固件安全审计思路;不提供面向真实车辆的操控复现与攻击指令
我的上一篇车联网文章已经讲到:拿到车机 ADB / 提权 root 后,控制面一下子大了。这次我们继续沿着“真实项目里会发生的下一步”往下走:
已经在系统里了(拿到一台 Linux/Android 车机或台架网关的 shell/root),你要做两件事:
1)把 CAN 流量抓出来并看懂
2)把 固件更新链路与诊断链路 的风险点梳理出来
为了让读者能跟着做,我用 vcan 搭实验环境,但流程和工具链跟现场是一致的
can基本知识
如果你是第一次接触 CAN,可以把这篇文章当成入门基本知识;
如果你有基础,可以快速扫一遍,用来对齐后文的分析视角。
CAN(Controller Area Network)不是 IP 网络,也不是主从结构,而是一个多主、广播式、基于仲裁的总线系统。
和以太网 / TCP-IP 的关键区别
对比项 | CAN | 以太网 / IP |
通信模式 | 广播(Broadcast) | 点对点 |
地址 | 无 MAC / IP | 有 |
认证 | 无 | 有(TLS/Session) |
加密 | 无 | 可选 |
冲突处理 | 硬件仲裁 | 碰撞/重传 |
实时性 | 强实时 | 尽力而为 |
这也是为什么 CAN 在功能安全上很强,但在安全防护上很差劲
CAN 帧结构:
在 candump 里看到的这一行:
vcan0 19B [8] 00 00 0E 00 00 00 00 00其实就是一个 标准 CAN 帧(11-bit ID) 的可视化。
标准 CAN 帧(Classic CAN)(CAN FD 支持更大 payload,但本文仅讨论 Classic CAN)
+---------+--------+-----+---------+------+
| CAN ID | DLC | RTR | DATA | CRC |
+---------+--------+-----+---------+------+
11 bit 0~8 B <= 8 B在 can-utils 里通常简化显示为:
<ID>#<DATA>例如:
19B#00000E000000含义是:
- ID = 0x19B
- DATA = 8 字节
- 没有“源地址 / 目的地址”的概念
CAN ID:不是地址,是“优先级 + 语义”
- CAN ID 不是“谁发给谁”
- CAN ID 表示:这条消息是什么以及有多重要
仲裁规则:ID 数值越小,优先级越高
这也是为什么刹车、转向相关 ID 通常很小,娱乐系统、状态上报 ID 通常较大
为什么攻击/分析时都“从 ID 入手”,因为:
- ID 决定 这条消息是否能抢占总线
- ID 决定 哪些 ECU 会监听它
- ID 是你做 差分分析、周期分析、信号定位 的第一入口
这也是上一篇文章为什么一直在做:
sort | uniq | diffDATA 最多 8 字节,但并不是“随便放”。
常见 DATA 编码模式
类型 | 特征 | 示例 |
开关量 | 单 bit / 少量 bit | 门锁、转向灯 |
计数器 | 每帧 +1 / 循环 | rolling counter |
物理量 | 连续变化 | 速度、转速 |
校验 | 高频变化、无规律 | checksum |
认证 | 随 payload 变化 | MAC/HMAC |
这是后面写“找变化字节、剥离 counter”的理论基础
在真实车辆中,CAN 报文几乎都属于这两类:
1.周期报文(Periodic)
- 固定周期发送(10ms / 20ms / 100ms)
- 描述“当前状态”
- 最常见
示例:
- 当前车速
- 当前档位
- 当前转向角
这也是统计 frames/sec 的原因
2.事件报文(Event-based)
- 只在事件发生时发送
- 常见于:
- 门锁
- 按键
- 故障码
环境准备
安装工具:can-utils / python-can
Linux 下 can-utils 是 SocketCAN 用户态工具集,包含 candump/cansend/canplayer/cansniffer 等。
candump使用:
candump -tz vcan0:看实时
candump -l vcan0:落盘(自动命名)
candump -f normal.log vcan0:落盘(自定义命名)
candump -L vcan0 > out.log:stdout 输出log格式(方便重定向/管道)- Ubuntu/Debian(推荐):
sudo apt update
sudo apt install -y can-utils python3-pip
pip3 install python-canpython-can 的 SocketCAN 接口文档:(python-can.readthedocs.io)
创建虚拟 CAN 网卡(vcan0)
sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set up vcan0
ip -details link show vcan0这就是一个“假的车内 CAN 总线”,所有工具都能对它抓包、发包、回放。
如果模块/lib/modules/linux-headers-$(uname -r)下没有vcan.ko,则无法创建vcan模块,需安装linux-headers-$(uname -r):
sudo apt install linux-headers-$(uname -r) linux-source找有用信号
先制造一点车内噪声
用 cangen 生成随机流量,模拟车上多个 ECU 在广播状态报文:
# 每 10ms 发一帧,ID 自动递增,DLC=8,数据随机
cangen vcan0 -g 10 -L 8 -vcandump 抓包
开另一个终端抓包:
candump -tz vcan0-t z会打印时间戳,方便做周期分析- 会看到类似:
(1700.123456) vcan0 123#112233...
实战经验:第一步不是“猜含义”,而是把流量变成“结构化数据”——ID、周期、变化字节。
例题:Routine Control
This challenge is within the Harborbay vehicle simulator on VSEC. From the home page, enter HarborBay. Select the Mach-E User Space Diagnostics Challenge Simulation, then launch the terminal.
这项挑战在 VSEC 上的 Harborbay 车辆模拟器中进行。从主页进入 HarborBay。选择 Mach-E 用户空间诊断挑战模拟,然后启动终端。
I hear routine control has a lot of fun features.
我听说常规控制有很多有趣的功能。使用 Routine Control 服务来执行已定义的步骤序列并获取任何相关结果,服务 ID 是 0x31
子功能也比较简单,开始(01)、停止(02)、获取结果(03)
那先试试开始执行吧,简单试了试都是否定响应,估计也得爆破
import can
import time
import binascii
bus = can.Bus(interface='socketcan', channel='vcan0')
for i in range(0,0xFF):
for j in range(0,0xFF):
message = can.Message(arbitration_id=0x7E0, is_extended_id=False, dlc=8, data=[0x04, 0x31, 0x01, i, j, 0x00, 0x00, 0x00])
bus.send(message, timeout=0.2)
msg = bus.recv()
result = binascii.hexlify(msg.data).decode('utf-8')
if result == "037f3131":
pass
else:
print("i: ",hex(i)," j: ",hex(j))
bus.shutdown()跑了一段时间发现 1337 是响应的,因此先执行 1337 然后再获取结果
cansend vcan0 7E0#0431011337000000 && cansend vcan0 7E0#0431031337000000 && cansend vcan0 7E0#3000000000000000得到flag为bh{c0ntroll1ng_th3_r0ut1nes}
找周期报文,找变化字段
用 cansniffer 分析
cansniffer vcan0cansniffer 会突出显示变化的字节,非常适合做“信号定位”。(GitHub)
例题:ASRG CTF CAP2 — Hard CAP2
这是一个包含 CAN 嗅探器数据 的 pcap 文件,目标是从中找出被篡改的交通信号灯信号。
初步分析
- 分析 pcap 文件发现其格式与 CAN1 挑战相似
- 使用 Wireshark 或类似工具打开
cap2.pcap文件 - 关注 CAN 总线数据帧,特别是 ID 和 Data 字段
- 在时间戳
0.000000和9.999999处发现了重复信号 - 这些重复信号具有相同的 ID,但最后一位(bit)不同
- 这表明可能存在隐蔽的数据传输
定位可疑 ID
- 经过筛选,发现 ID 157 的数据帧最为可疑
- 该 ID 的数据帧在特定时间点出现成对出现,且仅最后一位不同
提取修改的比特位
cansniffer vcan0- 从 ID 157 的数据帧中提取数据字段
- 重点关注每个数据帧的最后一位(bit)
- 过滤掉时间戳为
0.000000的重复帧(这些是虚假的时间戳)
成功提取出隐藏在 CAN 信号中的flag:
flag_05B2873A2FA21D297D3442FF我们主动发一个“看起来像计数器”的帧:
# 在一个终端循环发送(模拟 ECU 心跳)
while true; do
for i in $(seq 0 255); do
printf -v b "%02X" $i
cansend vcan0 123#${b}00000000000000
sleep 0.05
done
done然后在 cansniffer 里你会看到:
- ID
0x123的第 1 字节持续递增 - 典型“rolling counter/心跳计数”特征
总结:
车上很多报文都有 counter(防重放/同步/诊断相关),你定位信号时要把“计数器/校验”先剥离,不然会误判。
记录与回放
记录 log(用于复现 bug / 还原现场)
candump -l vcan0会生成 candump-*.log
或者
$ candump vcan0 -f normal_log会生成 normal_log
回放 log
canplayer -I candump-2026-01-20_*.logcanplayer 会按原始时间间隔回放(做分析、做 IDS、做回归测试都离不开它)
cansend也能(举例:)
$ cat normal_log | awk '{print $3}' | cut -d'#' -f1 | sort | uniq > normal_ids.txt
$ cat door_unlock_log | awk '{print $3}' | cut -d'#' -f1 | sort | uniq > unlock_ids.txt
$ diff normal_ids.txt unlock_ids.txt
16a17
> 19B
#从这个结果可以看出,ID:19B 仅在门未解锁时出现
$ cat door_unlock_log | awk '{print $3}' | grep 19B# | uniq
19B#00000E000000
#可以确认,此消息是车门解锁时发送的 CAN 消息
$ cansend vcan0 19B#00000E000000
#如果能在模拟器中确认门可以解锁,那么就知道是由特定的消息控制门的解锁自动化代码
代码1:(CAN 日志初筛分析器)
下面这段脚本做三件事:
1)读取 candump -l 生成的 log
2)按 ID 统计频率(找周期报文)
3)找每个 ID 的“变化字节位置”(定位信号)
文件名:
analyze_candump.py
import re
from collections import defaultdict, Counter
# candump -l 格式常见形态:
# (1700000000.123456) vcan0 123#1122334455667788
PAT = re.compile(r"\((?P<ts>[\d\.]+)\)\s+(?P<if>\S+)\s+(?P<id>[0-9A-Fa-f]+)#(?P<data>[0-9A-Fa-f]*)")
def parse_log(path: str):
frames = []
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
m = PAT.search(line)
if not m:
continue
ts = float(m.group("ts"))
can_id = int(m.group("id"), 16)
data_hex = m.group("data")
data = bytes.fromhex(data_hex) if data_hex else b""
frames.append((ts, can_id, data))
return frames
def id_frequency(frames):
# 粗略统计:每个 ID 每秒帧数(基于首末时间)
by_id = defaultdict(list)
for ts, can_id, data in frames:
by_id[can_id].append(ts)
freq = {}
for can_id, tss in by_id.items():
if len(tss) < 2:
freq[can_id] = 0.0
continue
duration = max(tss) - min(tss)
freq[can_id] = (len(tss) - 1) / duration if duration > 0 else 0.0
return freq
def changing_bytes(frames, target_id):
# 找某个 ID 的哪些字节发生变化
payloads = [data for _, can_id, data in frames if can_id == target_id]
if len(payloads) < 2:
return []
max_len = max(len(p) for p in payloads)
changed = [False] * max_len
prev = payloads[0].ljust(max_len, b"\x00")
for p in payloads[1:]:
cur = p.ljust(max_len, b"\x00")
for i in range(max_len):
if cur[i] != prev[i]:
changed[i] = True
prev = cur
return [i for i, c in enumerate(changed) if c]
def main():
path = "candump.log" # 改成你的文件名
frames = parse_log(path)
print(f"[+] Loaded frames: {len(frames)}")
freq = id_frequency(frames)
top = sorted(freq.items(), key=lambda x: x[1], reverse=True)[:10]
print("\n[+] Top 10 IDs by approx frequency (frames/sec):")
for can_id, f in top:
print(f" ID 0x{can_id:03X} ~ {f:.2f} fps")
# 对 Top3 做变化字节扫描
print("\n[+] Changing byte positions for Top3:")
for can_id, _ in top[:3]:
ch = changing_bytes(frames, can_id)
print(f" ID 0x{can_id:03X} changed bytes: {ch}")
if __name__ == "__main__":
main()怎么用:
1)先抓包:
candump -l vcan0
# 得到 candump-xxxx.log,把它拷贝成 candump.log 或改脚本变量2)跑分析:
python analyze_candump.py真实车辆里诊断(UDS)经常跑在 ISO-TP 上(ISO 15765-2)。Linux 里 ISO-TP 有内核支持与工具链(can-utils 也带 isotpsend/isotprecv 等)。
用 ISO-TP 发一个大于 8 字节的消息
开接收端:
isotprecv -s 7e1 -d 7e9 -c vcan0再开一个终端发送:
echo -n "Hello-ISO-TP-Over-CAN" | isotpsend -s 7e1 -d 7e9 -c vcan0你会看到接收端输出整段字符串(底层其实拆成了多帧再重组)。
代码二(candump 日志 → 自动推测周期 + 自动聚类变化字段 + 输出信号表)
输入:candump -tz -L vcan0 > candump.log 这样的日志(推荐格式)
输出:
id_summary.csv(按 ID 汇总:帧数、fps、周期估计、payload 长度等)signal_table.csv(疑似信号表:byte/bit、变化率、熵、疑似类型、簇ID)
使用方法:
python can_signal_miner.py -i candump.log --top 30#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
can_signal_miner.py
- Parse candump logs
- Estimate period per CAN ID (robust median of inter-arrival)
- Identify changing bytes/bits
- Cluster fields by co-change patterns
- Export:
- id_summary.csv
- signal_table.csv
"""
import re
import csv
import math
import argparse
from collections import defaultdict, Counter
from statistics import median
# Supports common candump variants:
# (1700000000.123456) vcan0 123#112233...
# (1700000000.123456) vcan0 123 [8] 11 22 33 ...
# or with -L: (ts) if 123#...
PAT_HEX = re.compile(
r"""
^\((?P<ts>[\d\.]+)\)\s+
(?P<iface>\S+)\s+
(?P<id>[0-9A-Fa-f]+)
(?:
\#(?P<data1>[0-9A-Fa-f]*)
|
\s+\[(?P<dlc>\d+)\]\s+(?P<data2>(?:[0-9A-Fa-f]{2}\s*)*)
)
""",
re.VERBOSE,
)
def parse_candump(path: str):
"""Return list of frames: (ts, can_id_int, data_bytes, dlc_int, iface)"""
frames = []
with open(path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
line = line.strip()
m = PAT_HEX.match(line)
if not m:
continue
ts = float(m.group("ts"))
iface = m.group("iface")
can_id = int(m.group("id"), 16)
if m.group("data1") is not None:
data_hex = m.group("data1") or ""
data = bytes.fromhex(data_hex) if data_hex else b""
dlc = len(data)
else:
dlc = int(m.group("dlc"))
data2 = (m.group("data2") or "").strip().replace(" ", "")
data = bytes.fromhex(data2) if data2 else b""
# Some logs might not include full dlc bytes; pad if needed
if len(data) < dlc:
data = data + b"\x00" * (dlc - len(data))
else:
data = data[:dlc]
frames.append((ts, can_id, data, dlc, iface))
return frames
def robust_period_ms(timestamps):
"""
Estimate period in ms using robust median of inter-arrival deltas.
Return None if insufficient data or unstable.
"""
if len(timestamps) < 5:
return None
dts = [timestamps[i] - timestamps[i-1] for i in range(1, len(timestamps))]
# Filter out zero/negative (shouldn't happen but)
dts = [x for x in dts if x > 0]
if len(dts) < 4:
return None
med = median(dts)
# Basic stability check using MAD-like threshold
abs_dev = [abs(x - med) for x in dts]
mad = median(abs_dev)
if med <= 0:
return None
# If too jittery, report None
if mad > med * 0.5:
return None
return med * 1000.0
def byte_entropy(values):
"""Shannon entropy for a byte-position values list."""
if not values:
return 0.0
cnt = Counter(values)
total = len(values)
ent = 0.0
for c in cnt.values():
p = c / total
ent -= p * math.log2(p)
return ent # 0..8
def change_rate(values):
"""Fraction of adjacent samples that differ."""
if len(values) < 2:
return 0.0
diffs = sum(1 for i in range(1, len(values)) if values[i] != values[i-1])
return diffs / (len(values) - 1)
def counter_score(values):
"""
Heuristic: how much this byte behaves like a rolling counter.
Score in [0,1], higher => more likely incrementing modulo 256.
"""
if len(values) < 6:
return 0.0
ok = 0
total = 0
for i in range(1, len(values)):
prev = values[i-1]
cur = values[i]
# Accept +1 modulo 256 as counter-like
if (prev + 1) & 0xFF == cur:
ok += 1
total += 1
return ok / total if total else 0.0
def bit_flip_rates(byte_values):
"""Return list[8] each is flip rate for that bit."""
if len(byte_values) < 2:
return [0.0] * 8
flips = [0] * 8
total = len(byte_values) - 1
for i in range(1, len(byte_values)):
x = byte_values[i-1] ^ byte_values[i]
for b in range(8):
flips[b] += (x >> b) & 1
return [f / total for f in flips]
def cochange_vector(frames_by_id, can_id, max_len):
"""
For clustering: build per-byte co-change signature as bitmask over time chunks.
We compress timeline into N windows and mark if byte changed in each window.
"""
payloads = [data.ljust(max_len, b"\x00") for (_, data, _, _) in frames_by_id[can_id]]
if len(payloads) < 10:
return None
# Choose number of windows
N = 32
step = max(1, len(payloads) // N)
vecs = []
prev = payloads[0]
changes = [[0]*N for _ in range(max_len)]
idx = 0
w = 0
for i in range(1, len(payloads)):
cur = payloads[i]
if i % step == 0 and w < N - 1:
w += 1
for bi in range(max_len):
if cur[bi] != prev[bi]:
changes[bi][w] = 1
prev = cur
idx += 1
return changes # [byte][window] 0/1
def simple_cluster(change_vectors):
"""
Very lightweight clustering without external deps:
Cluster bytes by identical change window patterns.
Returns dict byte_index -> cluster_id
"""
pattern_to_cluster = {}
byte_cluster = {}
next_id = 1
for bi, pattern in change_vectors.items():
key = tuple(pattern)
if key not in pattern_to_cluster:
pattern_to_cluster[key] = next_id
next_id += 1
byte_cluster[bi] = pattern_to_cluster[key]
return byte_cluster
def classify_field(ent, cr, cs, bit_rate_max):
"""
Simple heuristic labeling:
- counter: strong counter_score
- checksum-like: high entropy + high change rate + not counter
- switch/flag: low entropy but some bit flips
- analog-like: medium entropy + steady changes
"""
if cs >= 0.6 and cr >= 0.2:
return "rolling_counter?"
if ent >= 6.5 and cr >= 0.4 and cs < 0.2:
return "checksum_or_auth?"
if ent <= 2.0 and bit_rate_max >= 0.05:
return "switch_or_flags?"
if 2.0 < ent < 6.5 and cr >= 0.1:
return "analog_or_state?"
if cr < 0.05:
return "static_or_constant?"
return "unknown"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True, help="candump log file (e.g., candump.log)")
ap.add_argument("--top", type=int, default=50, help="analyze top N IDs by frame count")
args = ap.parse_args()
frames = parse_candump(args.input)
if not frames:
print("[!] No frames parsed. Make sure you used: candump -tz -L vcan0 > candump.log")
return
# Group by ID
by_id = defaultdict(list) # id -> list of (ts, data, dlc, iface)
for ts, cid, data, dlc, iface in frames:
by_id[cid].append((ts, data, dlc, iface))
# Sort each ID timeline
for cid in by_id:
by_id[cid].sort(key=lambda x: x[0])
# Summaries
id_stats = []
for cid, items in by_id.items():
ts_list = [x[0] for x in items]
duration = ts_list[-1] - ts_list[0] if len(ts_list) > 1 else 0.0
fps = (len(items)-1)/duration if duration > 0 else 0.0
p_ms = robust_period_ms(ts_list)
dlc_mode = Counter([x[2] for x in items]).most_common(1)[0][0]
id_stats.append((cid, len(items), fps, p_ms, dlc_mode))
# pick top IDs
id_stats.sort(key=lambda x: x[1], reverse=True)
pick = id_stats[: args.top]
# Export id_summary.csv
with open("id_summary.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["can_id_hex", "frames", "fps_est", "period_ms_est", "dlc_mode"])
for cid, n, fps, p_ms, dlc in pick:
w.writerow([f"0x{cid:X}", n, f"{fps:.3f}", f"{p_ms:.2f}" if p_ms else "", dlc])
# Build signal table
rows = []
for cid, n, fps, p_ms, dlc_mode in pick:
items = by_id[cid]
max_len = max(len(x[1]) for x in items) if items else 0
if max_len == 0:
continue
# Collect per-byte value series
series = [[] for _ in range(max_len)]
for _, data, _, _ in items:
data = data.ljust(max_len, b"\x00")
for bi in range(max_len):
series[bi].append(data[bi])
# Change window patterns for clustering
change_windows = cochange_vector(by_id, cid, max_len)
byte_cluster = {}
if change_windows is not None:
# map bi->pattern
cv = {bi: change_windows[bi] for bi in range(max_len)}
byte_cluster = simple_cluster(cv)
# For each byte, compute metrics; then drill down bits where useful
for bi in range(max_len):
vals = series[bi]
cr = change_rate(vals)
ent = byte_entropy(vals)
cs = counter_score(vals)
bit_rates = bit_flip_rates(vals)
bit_max = max(bit_rates) if bit_rates else 0.0
field_type = classify_field(ent, cr, cs, bit_max)
cluster_id = byte_cluster.get(bi, "")
# Byte-level row
rows.append([
f"0x{cid:X}", dlc_mode, f"{p_ms:.2f}" if p_ms else "",
bi, "", # bit empty
f"{cr:.3f}", f"{ent:.3f}", f"{cs:.3f}", f"{bit_max:.3f}",
field_type, cluster_id
])
# If it looks like switch/flags, output bit-level suspects too
if field_type in ("switch_or_flags?",) and cr > 0.02:
for bit in range(8):
if bit_rates[bit] >= 0.03: # threshold: adjust if needed
rows.append([
f"0x{cid:X}", dlc_mode, f"{p_ms:.2f}" if p_ms else "",
bi, bit,
f"{bit_rates[bit]:.3f}", "", "", "",
"bit_flag_candidate", cluster_id
])
with open("signal_table.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow([
"can_id_hex", "dlc_mode", "period_ms_est",
"byte_index", "bit_index",
"change_rate", "entropy_bits", "counter_score", "max_bit_flip_rate",
"label", "cluster_id"
])
w.writerows(rows)
print("[+] Done.")
print(" - id_summary.csv")
print(" - signal_table.csv")
print("\nTip: 用 Excel/Sheets 按 can_id_hex 过滤,再按 change_rate/label 排序,很快就能定位“像信号”的字段。")
if __name__ == "__main__":
main()
代码3(实时提示哪个 ID 的哪个 byte/bit 在变)
用途:在 ICSim 操作(转向灯/门锁)时,脚本会实时打印“变化字段”,并把变化记录写到 live_changes.csv,非常“实战叙事”。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
live_can_diff.py
- Listen on SocketCAN
- Track last payload per ID
- Print byte/bit changes in real time
- Export changes to CSV for later write-up
"""
import time
import csv
import argparse
import can
def bytes_to_hex(b: bytes) -> str:
return b.hex().upper()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--channel", default="vcan0", help="SocketCAN channel, e.g. vcan0/can0")
ap.add_argument("--csv", default="live_changes.csv", help="output csv file")
ap.add_argument("--only-id", default=None, help="filter by CAN ID hex, e.g. 19B or 0x19B")
ap.add_argument("--maxlen", type=int, default=8, help="track up to N bytes (classic CAN=8)")
args = ap.parse_args()
only_id = None
if args.only_id:
s = args.only_id.lower().replace("0x", "")
only_id = int(s, 16)
bus = can.Bus(interface="socketcan", channel=args.channel)
last = {} # can_id -> last_bytes (padded)
print(f"[+] Listening on {args.channel}. Ctrl+C to stop.")
print("[+] Tip: 这时候去操作 ICSim/controls,观察哪些字段变化。\n")
with open(args.csv, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["ts", "can_id_hex", "byte_index", "bit_index", "old", "new", "delta_type"])
try:
while True:
msg = bus.recv(timeout=1.0)
if msg is None:
continue
cid = msg.arbitration_id
if only_id is not None and cid != only_id:
continue
data = bytes(msg.data[:args.maxlen]).ljust(args.maxlen, b"\x00")
ts = time.time()
if cid not in last:
last[cid] = data
continue
prev = last[cid]
if prev == data:
continue
# Byte diff
for i in range(args.maxlen):
if prev[i] != data[i]:
print(f"[{ts:.3f}] ID 0x{cid:X} byte[{i}] {prev[i]:02X} -> {data[i]:02X}")
w.writerow([f"{ts:.6f}", f"0x{cid:X}", i, "", f"{prev[i]:02X}", f"{data[i]:02X}", "byte"])
# Bit diff for this byte
x = prev[i] ^ data[i]
for bit in range(8):
if (x >> bit) & 1:
oldb = (prev[i] >> bit) & 1
newb = (data[i] >> bit) & 1
print(f" └─ bit[{bit}] {oldb} -> {newb}")
w.writerow([f"{ts:.6f}", f"0x{cid:X}", i, bit, oldb, newb, "bit"])
last[cid] = data
except KeyboardInterrupt:
print("\n[+] Stopped.")
print(f"[+] CSV saved: {args.csv}")
finally:
bus.shutdown()
if __name__ == "__main__":
main()用法:
终端 A:ICSim 状态界面
./icsim vcan0终端 B:控制面板
./controls vcan0终端 C:实时变化侦测
python live_can_diff.py -c vcan0 --csv live_changes.csv然后你按键盘做一次“左转向灯/解锁”,终端 C 会刷出类似:
[... ] ID 0x19B byte[2] 00 -> 0E
└─ bit[1] 0 -> 1
└─ bit[2] 0 -> 1参考资料及致谢
1.https://github.com/linux-can/can-utils
2.https://www.kernel.org/doc/html/latest/networking/can.html
3.https://python-can.readthedocs.io/en/stable/
4.https://medium.com/@yogeshojha/car-hacking-101-practical-guide-to-exploiting-can-bus-using-instrument-cluster-simulator-part-i-cd88d3eb4a53
5.https://github.com/zombieCraig/ICSim
基于vcan实验环境,详解CAN/ISO-TP协议分析、周期报文识别、信号定位及UDS诊断链路风险挖掘方法。
由 AI 根据全文自动生成,仅供参考,以原文为准
