| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
import pyshark |
| 4 |
import struct |
| 5 |
import sys |
| 6 |
import binascii |
| 7 |
|
| 8 |
device = "1.255" |
| 9 |
device_in = "{}.2".format(device) |
| 10 |
device_out = "{}.1".format(device) |
| 11 |
|
| 12 |
def hexDump(s: bytes, prefix:str="", addr:int=0, compact:bool=False) -> str: |
| 13 |
""" Utility function to hex-dump binary data. """ |
| 14 |
N = len(s) |
| 15 |
Nb = N//16 |
| 16 |
if (N%16): Nb += 1 |
| 17 |
res = "" |
| 18 |
last_line = None |
| 19 |
compressing = False |
| 20 |
for j in range(Nb): |
| 21 |
a,b = j*16, min((j+1)*16,N) |
| 22 |
line = s[a:b] |
| 23 |
if (not compact) or (last_line != line): |
| 24 |
h = " ".join(map("{:02x}".format, line)) |
| 25 |
h += " "*(16-(b-a)) |
| 26 |
t = "" |
| 27 |
for i in range(a,b): |
| 28 |
c = s[i] |
| 29 |
if c>=0x20 and c<0x7f: |
| 30 |
t += chr(c) |
| 31 |
else: |
| 32 |
t += "." |
| 33 |
res += (prefix + "{:08X} ".format(addr+16*j) + h + " | " + t + "\n") |
| 34 |
last_line = line |
| 35 |
compressing = False |
| 36 |
elif not compressing: |
| 37 |
res += (prefix + "*\n") |
| 38 |
compressing = True |
| 39 |
return res[:-1] |
| 40 |
|
| 41 |
def isDataPacket(p): |
| 42 |
return ("USB.CAPDATA" in p) |
| 43 |
|
| 44 |
def isFromHost(p): |
| 45 |
return (("host" == p.usb.src) and (device_in == p.usb.dst)) |
| 46 |
|
| 47 |
def isFromDevice(p): |
| 48 |
return (("host" == p.usb.dst) and (device_out == p.usb.src)) |
| 49 |
|
| 50 |
def getData(p): |
| 51 |
if not isDataPacket(p): |
| 52 |
return None |
| 53 |
return binascii.a2b_hex(p["USB.CAPDATA_RAW"].value) |
| 54 |
|
| 55 |
|
| 56 |
class Packet: |
| 57 |
def __init__(self, data:bytes): |
| 58 |
self._flag, self._cmd, self._sub, self._pcrc, size = struct.unpack("<xBBBHH", data[:8]) |
| 59 |
self._payload = bytes() |
| 60 |
if size: self._payload = data[8:(8+size)] |
| 61 |
self._crc = 0xffff |
| 62 |
for i in range(len(data)//2): |
| 63 |
v = struct.unpack("<H", data[(2*i):(2*(i+1))])[0] |
| 64 |
if v > self._crc: self._crc += 0xffff; |
| 65 |
self._crc -= v |
| 66 |
if len(data)%2: |
| 67 |
v = struct.unpack("B", data[-1:])[0] |
| 68 |
if v > self._crc: self._crc +=0xffff; |
| 69 |
self._crc -= v; |
| 70 |
|
| 71 |
|
| 72 |
def __repr__(self): |
| 73 |
if 0 == len(self._payload): |
| 74 |
return "Packet flag={:02x}, cmd={:02x}, sub={:02x}, crc={:04x}.".format(self._flag, self._cmd, self._sub, self._crc) |
| 75 |
return "Packet flag={:02x}, cmd={:02x}, sub={:02x}, crc={:04x}\n{}".format(self._flag, self._cmd, self._sub, self._crc, hexDump(self._payload, " ")) |
| 76 |
|
| 77 |
cap = pyshark.FileCapture(sys.argv[1], include_raw=True, use_json=True) |
| 78 |
nextaddr = 0 |
| 79 |
for p in cap: |
| 80 |
if isDataPacket(p): |
| 81 |
print(Packet(getData(p))) |