pklg.py (6443B)
1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: GPL-2.0-only 3 """Minimal decoder for Apple PacketLogger logs (.pklg): HCI, LE, L2CAP, ATT. 4 5 Usage: pklg.py file.pklg [--handle 0x0040] [--att] [--notes] [--conn] 6 """ 7 import argparse 8 import datetime as dt 9 import struct 10 import sys 11 12 TYPES = {0x00: "CMD", 0x01: "EVT", 0x02: "ACL>", 0x03: "ACL<", 0x08: "SCO>", 0x09: "SCO<"} 13 14 ATT_OPS = { 15 0x01: "ERR", 0x02: "MTU_REQ", 0x03: "MTU_RSP", 0x04: "FIND_INFO_REQ", 0x05: "FIND_INFO_RSP", 16 0x06: "FIND_BY_TYPE_REQ", 0x07: "FIND_BY_TYPE_RSP", 0x08: "READ_BY_TYPE_REQ", 0x09: "READ_BY_TYPE_RSP", 17 0x0A: "READ_REQ", 0x0B: "READ_RSP", 0x0C: "READ_BLOB_REQ", 0x0D: "READ_BLOB_RSP", 18 0x10: "READ_BY_GROUP_REQ", 0x11: "READ_BY_GROUP_RSP", 0x12: "WRITE_REQ", 0x13: "WRITE_RSP", 19 0x1B: "NOTIFY", 0x1D: "INDICATE", 0x1E: "CONFIRM", 0x52: "WRITE_CMD", 0xD2: "SIGNED_WRITE", 20 } 21 22 23 def records(path): 24 data = open(path, "rb").read() 25 # Detect the byte order: the length of the first record must be plausible. 26 be = struct.unpack(">I", data[:4])[0] 27 le = struct.unpack("<I", data[:4])[0] 28 endian = ">" if 9 <= be < 0x10000 else "<" 29 if not (9 <= (be if endian == ">" else le) < 0x10000): 30 sys.exit("unrecognized pklg format") 31 off = 0 32 while off + 13 <= len(data): 33 (length,) = struct.unpack(endian + "I", data[off:off + 4]) 34 if endian == ">": 35 secs, usecs = struct.unpack(">II", data[off + 4:off + 12]) 36 else: 37 usecs, secs = struct.unpack("<II", data[off + 4:off + 12]) 38 typ = data[off + 12] 39 payload = data[off + 13:off + 4 + length] 40 off += 4 + length 41 yield secs + usecs / 1e6, typ, payload 42 43 44 def ts(t): 45 return dt.datetime.fromtimestamp(t).strftime("%H:%M:%S.%f")[:-3] 46 47 48 def uuid_str(b): 49 if len(b) == 2: 50 return "%04X" % struct.unpack("<H", b)[0] 51 h = b[::-1].hex().upper() 52 return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:]}" 53 54 55 def att_decode(p): 56 op = p[0] 57 name = ATT_OPS.get(op, "OP_%02X" % op) 58 rest = p[1:] 59 if op in (0x12, 0x52, 0x1B, 0x1D, 0x0A) and len(rest) >= 2: 60 (h,) = struct.unpack("<H", rest[:2]) 61 return f"{name} h=0x{h:04X} {rest[2:].hex(' ')}" 62 if op == 0x01 and len(rest) >= 4: 63 req, h, code = struct.unpack("<BHB", rest[:4]) 64 return f"ERR req={ATT_OPS.get(req, req)} h=0x{h:04X} code=0x{code:02X}" 65 if op == 0x09 and rest: 66 n = rest[0] 67 items = [] 68 for i in range(1, len(rest) - n + 1, n): 69 e = rest[i:i + n] 70 h = struct.unpack("<H", e[:2])[0] 71 v = e[2:] 72 if len(v) in (5, 19): # characteristic declaration 73 props, vh = v[0], struct.unpack("<H", v[1:3])[0] 74 items.append(f"[decl 0x{h:04X} props=0x{props:02X} val=0x{vh:04X} uuid={uuid_str(v[3:])}]") 75 else: 76 items.append(f"[0x{h:04X} {v.hex(' ')}]") 77 return f"{name} " + " ".join(items) 78 if op == 0x11 and rest: 79 n = rest[0] 80 items = [] 81 for i in range(1, len(rest) - n + 1, n): 82 e = rest[i:i + n] 83 s, en = struct.unpack("<HH", e[:4]) 84 items.append(f"[svc 0x{s:04X}-0x{en:04X} {uuid_str(e[4:])}]") 85 return f"{name} " + " ".join(items) 86 if op == 0x05 and rest: 87 fmt = rest[0] 88 n = 4 if fmt == 1 else 18 89 items = [] 90 for i in range(1, len(rest) - n + 1, n): 91 e = rest[i:i + n] 92 items.append(f"[0x{struct.unpack('<H', e[:2])[0]:04X} {uuid_str(e[2:])}]") 93 return f"{name} " + " ".join(items) 94 return f"{name} {rest.hex(' ')}" 95 96 97 def main(): 98 ap = argparse.ArgumentParser() 99 ap.add_argument("file") 100 ap.add_argument("--handle", type=lambda x: int(x, 0), help="keep a single HCI connection") 101 ap.add_argument("--att", action="store_true", help="show ATT") 102 ap.add_argument("--notes", action="store_true", help="show the text notes of bluetoothd") 103 ap.add_argument("--conn", action="store_true", help="LE connections and advertised names") 104 ap.add_argument("--grep", help="filter the notes") 105 a = ap.parse_args() 106 107 frag = {} 108 for t, typ, p in records(a.file): 109 if typ in (0x02, 0x03) and a.att and len(p) >= 4: 110 hf, ln = struct.unpack("<HH", p[:4]) 111 handle, pb = hf & 0x0FFF, (hf >> 12) & 0x3 112 if a.handle is not None and handle != a.handle: 113 continue 114 body = p[4:4 + ln] 115 if pb in (0, 2): # start 116 frag[(handle, typ)] = body 117 else: 118 frag[(handle, typ)] = frag.get((handle, typ), b"") + body 119 buf = frag[(handle, typ)] 120 if len(buf) < 4: 121 continue 122 l2len, cid = struct.unpack("<HH", buf[:4]) 123 if len(buf) < 4 + l2len: 124 continue 125 frag.pop((handle, typ)) 126 if cid == 4: 127 d = "→" if typ == 0x02 else "←" 128 print(f"{ts(t)} {d} 0x{handle:03X} {att_decode(buf[4:4 + l2len])}") 129 elif cid == 6: 130 print(f"{ts(t)} {'→' if typ == 0x02 else '←'} 0x{handle:03X} SMP {buf[4:4 + l2len].hex(' ')}") 131 elif typ == 0x01 and a.conn and len(p) >= 3 and p[0] == 0x3E: 132 sub = p[2] 133 if sub in (0x01, 0x0A): 134 status, h = p[3], struct.unpack("<H", p[4:6])[0] 135 addr = p[8:14][::-1].hex(":") 136 print(f"{ts(t)} LE_CONN status={status} handle=0x{h:03X} peer={addr} type={p[7]}") 137 elif sub in (0x02, 0x0D): 138 # advertising reports: look for the names (AD type 0x08/0x09) 139 raw = p[3:] 140 i = 0 141 while i < len(raw) - 1: 142 if raw[i] in (0x08, 0x09) and 0 < raw[i - 1] < 32 if i else False: 143 pass 144 i += 1 145 elif typ == 0x01 and a.conn and len(p) >= 2 and p[0] == 0x05: 146 status, h, reason = p[2], struct.unpack("<H", p[3:5])[0], p[5] 147 print(f"{ts(t)} DISCONNECT handle=0x{h:03X} reason=0x{reason:02X}") 148 elif typ not in TYPES and a.notes: 149 try: 150 s = p.decode("utf-8", "replace").strip("\x00").strip() 151 except Exception: 152 continue 153 if a.grep and a.grep.lower() not in s.lower(): 154 continue 155 print(f"{ts(t)} [{typ:02X}] {s}") 156 157 158 if __name__ == "__main__": 159 main()