#!/usr/bin/python3 """ Independently verify SMB2 signatures straight off the wire. Reads a classic pcap (tcpdump -w), reassembles the server->client TCP streams, walks the NBSS/SMB2 framing, and recomputes AES-128-CMAC over each PDU with the Signature field zeroed -- exactly what smb3_calc_signature() does. wire signature VALID + kernel rc=-13 -> the kernel hashed something other than what arrived; the destination page-cache folios diverged wire signature INVALID -> the bytes were already wrong before cifs saw them With --kernel, the signing key and the set of MessageIds to examine are both taken from the sigcheck.bt log (its SIGNKEY line and every rc != 0 response). tcpdump -i lo -s0 -w /var/tmp/445.pcap 'tcp port 445' ./smb2sigcheck.py --kernel /var/tmp/sig.out /var/tmp/445.pcap ./smb2sigcheck.py -k <32-hex-digits> --cmd 8 --bad /var/tmp/445.pcap """ import argparse import re import struct import sys from cryptography.hazmat.primitives.ciphers import algorithms from cryptography.hazmat.primitives.cmac import CMAC SMB2_READ = 0x08 SMB2_FLAGS_SERVER_TO_REDIR = 0x01 SMB2_FLAGS_SIGNED = 0x08 PAGE_SIZE = 4096 CMDS = {0: "NEGOTIATE", 1: "SESSION_SETUP", 2: "LOGOFF", 3: "TREE_CONNECT", 4: "TREE_DISCONNECT", 5: "CREATE", 6: "CLOSE", 7: "FLUSH", 8: "READ", 9: "WRITE", 10: "LOCK", 11: "IOCTL", 12: "CANCEL", 13: "ECHO", 14: "QUERY_DIRECTORY", 15: "CHANGE_NOTIFY", 16: "QUERY_INFO", 17: "SET_INFO", 18: "OPLOCK_BREAK"} def read_pcap(path): """Yield raw link-layer frames from a classic pcap file.""" with open(path, "rb") as f: hdr = f.read(24) if len(hdr) < 24: sys.exit("%s: too short to be a pcap" % path) magic = struct.unpack("> 4) * 4 payload = seg[doff:] if payload: yield (src, sport, dst, dport), seq, payload def reassemble(path, port): """Return {flowkey: bytes} for streams originating at `port`.""" chunks = {} base = {} for key, seq, payload in tcp_segments(path): if key[1] != port: continue if key not in base: base[key] = seq chunks[key] = {} off = (seq - base[key]) & 0xffffffff if off > 0x80000000: # pre-base retransmit continue prev = chunks[key].get(off) if prev is None or len(payload) > len(prev): chunks[key][off] = payload streams = {} for key, parts in chunks.items(): buf = bytearray() for off in sorted(parts): if off > len(buf): break # hole: stop here buf[off:off + len(parts[off])] = parts[off] streams[key] = bytes(buf) return streams def pdus(stream): """Yield each SMB2 PDU's signed byte range out of an NBSS stream.""" pos = 0 n = len(stream) while pos + 4 <= n: if stream[pos] != 0: return # not an NBSS session msg rlen = int.from_bytes(stream[pos + 1:pos + 4], "big") if pos + 4 + rlen > n: return rec = stream[pos + 4:pos + 4 + rlen] pos += 4 + rlen off = 0 while off + 64 <= len(rec): if rec[off:off + 4] != b"\xfeSMB": break nxt = struct.unpack(" len(rec) or end <= off: break yield rec[off:end] if not nxt: break off = end def unhex(s): """bpftrace %rh is space-separated hex; also tolerate \\xNN and colons.""" return bytes.fromhex(re.sub(r"\\x|[:\s]", "", s)) def load_kernel(path): """Parse sigcheck.bt output. Returns (signing_key, {mid: {"stream": bytes, "calc": bytes, "rc": int}}). Either element may be None/empty if the run was cut short. """ key = None per_mid = {} with open(path) as f: for line in f: fields = line.split() if not fields: continue if fields[0] == "SIGNKEY": if key is None: key = unhex(line.partition("key=")[2]) continue if fields[0] not in ("C", "R") or len(fields) < 4: continue kv = dict(x.split("=", 1) for x in fields[1:] if "=" in x) if "mid" not in kv: continue mid = int(kv["mid"]) ent = per_mid.setdefault(mid, {"chunks": {}, "calc": None, "rc": None}) if fields[0] == "C": n, ln = int(kv["n"]), int(kv["len"]) blob = unhex(" ".join(fields[4:])) if len(blob) != ln: print("warning: mid=%d chunk %d truncated (%d of %d bytes) " "-- raise BPFTRACE_MAX_STRLEN" % (mid, n, len(blob), ln), file=sys.stderr) ent["chunks"][n] = blob else: ent["calc"] = unhex(line.partition("calc=")[2]) ent["rc"] = int(kv["rc"]) out = {} for mid, ent in per_mid.items(): out[mid] = {"stream": b"".join(ent["chunks"][n] for n in sorted(ent["chunks"])), "calc": ent["calc"], "rc": ent["rc"]} return key, out def diff(wire, kern, gap=64): """Report where the kernel's CMAC input diverged from the wire PDU.""" if len(wire) != len(kern): print("LENGTH MISMATCH: wire=%d kernel=%d" % (len(wire), len(kern))) n = min(len(wire), len(kern)) bad = [i for i in range(n) if wire[i] != kern[i]] if not bad: print("kernel CMAC input is byte-identical to the wire PDU") return print("%d of %d bytes differ, first at offset %d (%s)" % ( len(bad), n, bad[0], "sync header" if bad[0] < 64 else "read_rsp body" if bad[0] < 80 else "file data +%d" % (bad[0] - 80))) # Coalesce into regions, tolerating short stretches of coincidental # agreement, then see whether each region's bytes are simply the wire's # bytes from somewhere else -- the signature of an aliased destination. regions = [] start = prev = bad[0] for i in bad[1:] + [None]: if i is not None and i - prev <= gap: prev = i continue regions.append((start, prev + 1)) if i is None: break start = prev = i for a, b in regions: print(" region: data +%d .. +%d (%d bytes)" % (a - 80, b - 80, b - a)) hits = [] at = wire.find(kern[a:b]) while at != -1 and len(hits) < 8: if at != a: hits.append(at - a) at = wire.find(kern[a:b], at + 1) for s in hits: print(" == wire data +%d (shift %+d%s)" % ( a - 80 + s, s, ", one PAGE_SIZE" if abs(s) == PAGE_SIZE else "")) if hits == [PAGE_SIZE]: print(" -> aliased sink: netfs_read_gaps() dirty_offset=%d " "dirty_len=%d" % (a - 80, PAGE_SIZE + b - a)) elif not hits: print(" (content not found elsewhere in the PDU)") lo = max(0, (bad[0] & ~0xf) - 16) for off in range(lo, min(n, lo + 64), 16): w, k = wire[off:off + 16], kern[off:off + 16] print(" %06x wire %s\n %06x kern %s%s" % ( off, w.hex(" "), off, k.hex(" "), "" if w == k else " <<<")) def check(pdu, key): """Return (ok, wire_sig, calc_sig).""" wire = pdu[48:64] c = CMAC(algorithms.AES(key)) c.update(pdu[:48] + b"\x00" * 16 + pdu[64:]) calc = c.finalize()[:16] return wire == calc, wire, calc def main(): ap = argparse.ArgumentParser() ap.add_argument("pcap") ap.add_argument("-k", "--key", help="32 hex digits; default: the SIGNKEY line of --kernel") ap.add_argument("-p", "--port", type=int, default=445) ap.add_argument("--mid", type=int, action="append", help="only this MessageId (repeatable); default with " "--kernel: every mid the kernel failed to verify") ap.add_argument("--cmd", type=int, help="only this SMB2 command (8 = READ)") ap.add_argument("--bad", action="store_true", help="only signature failures") ap.add_argument("--dump", metavar="FILE", help="write each selected READ payload here (. is " "appended when more than one is selected)") ap.add_argument("--kernel", metavar="FILE", help="sigcheck.bt output; diff its CMAC input against the " "wire PDU") args = ap.parse_args() kern_key, kern = (None, {}) if args.kernel: kern_key, kern = load_kernel(args.kernel) key = unhex(args.key) if args.key else kern_key if key is None: sys.exit("no signing key: pass -k, or --kernel with a SIGNKEY line") if len(key) != 16: sys.exit("signing key must be 16 bytes (32 hex digits)") mids = set(args.mid) if args.mid else None if mids is None and kern: mids = {m for m, e in kern.items() if e["rc"]} if not mids: sys.exit("%s logged no verification failures; pass --mid to pick " "specific MessageIds" % args.kernel) print("kernel failed to verify %d response(s): %s\n" % ( len(mids), " ".join(str(m) for m in sorted(mids))), file=sys.stderr) total = bad = 0 for stream in reassemble(args.pcap, args.port).values(): for pdu in pdus(stream): cmd = struct.unpack("= 80: doff = pdu[66] dlen = struct.unpack(" 1: path += ".%d" % mid with open(path, "wb") as f: f.write(data) extra += " -> %s" % path print("mid=%-8d %-16s pdu=%-7d %s wire=%s calc=%s%s" % ( mid, CMDS.get(cmd, "0x%x" % cmd), len(pdu), "OK " if ok else "BAD ", wire.hex(), calc.hex(), extra)) ent = kern.get(mid) if ent and ent["stream"]: c = CMAC(algorithms.AES(key)) c.update(ent["stream"]) ksig = c.finalize()[:16] print("\nkernel: rc=%s hashed=%d bytes, cmac=%s" % ( ent["rc"], len(ent["stream"]), ksig.hex())) if ent["calc"] and ksig != ent["calc"]: print(" (does not match the kernel's own calc=%s -- the " "chunk log is incomplete)" % ent["calc"].hex()) diff(pdu[:48] + b"\x00" * 16 + pdu[64:], ent["stream"]) print() elif ent: print("\nkernel: rc=%s but no chunks logged (dlen above the " "sigcheck.bt dump gate?)\n" % ent["rc"]) print("\n%d signed PDUs checked, %d bad" % (total, bad), file=sys.stderr) if __name__ == "__main__": main()