repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
ksmbd-attack-surface-and-fuzzing-syzkaller.mdMarkdown332 lines19.2 KiBsource raw download

title: "ksmbd Attack Surface & SMB2/SMB3 Protocol Fuzzing (syzkaller)" section: "Network Services" sectionSlug: "network-services-pentesting" sourcePath: "src/network-services-pentesting/pentesting-smb/ksmbd-attack-surface-and-fuzzing-syzkaller.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/network-services-pentesting/pentesting-smb/ksmbd-attack-surface-and-fuzzing-syzkaller.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

ksmbd Attack Surface & SMB2/SMB3 Protocol Fuzzing (syzkaller)#

Overview#

This page summarizes practical techniques for exercising and fuzzing the Linux in-kernel SMB server (ksmbd) with syzkaller. It focuses on expanding the protocol attack surface through configuration, building a stateful harness capable of chaining SMB2 operations, generating grammar-valid PDUs, biasing mutations toward weakly covered code paths, and using syzkaller features such as focus_areas and ANYBLOB. The cited research enumerates specific CVEs; this page emphasizes the reusable methodology and concrete snippets that can be adapted to a lab.[1][2]

Target scope: SMB2/SMB3 over TCP. Kerberos and RDMA are intentionally out-of-scope to keep the harness simple.


Expand ksmbd Attack Surface via Configuration#

By default, a minimal ksmbd setup leaves large parts of the server untested. Enable the following features to drive the server through additional parsers/handlers and reach deeper code paths:[1]

Enabling these increases execution in modules such as:

Notes

Minimal lab configuration (adjust to the options your kernel/userspace build actually exposes):

[global]
    map to guest = bad user
    guest account = nobody
    max connections = 65536
    smb2 max credits = 8192
    smb2 leases = yes
    server multi channel support = yes
    durable handles = yes

[fuzz]
    path = /srv/ksmbd/fuzz
    guest ok = yes
    oplocks = yes
    vfs objects = acl_xattr streams_xattr

Why these toggles matter


Authentication and Rate-Limiting Adjustments for Fuzzing#

SMB3 needs a valid session. Implementing Kerberos in harnesses adds complexity, so prefer NTLM/guest for fuzzing:

Caution: These relaxations are to facilitate fuzzing only. Do not deploy with these settings in production.


Stateful Harness: Extract Resources and Chain Requests#

SMB is stateful: many requests depend on identifiers returned by prior responses (SessionId, TreeID, FileID pairs). Your harness must parse responses and reuse IDs within the same program to reach deep handlers (e.g., smb2_create → smb2_ioctl → smb2_close).[1]

Example snippet to process a response buffer after stripping the four-byte SMB-over-TCP framing header and cache IDs:

// process response. does not contain +4B PDU length
void process_buffer(int msg_no, const char *buffer, size_t received) {
  uint16_t cmd_rsp = u16((const uint8_t *)(buffer + CMD_OFFSET));
  switch (cmd_rsp) {
    case SMB2_TREE_CONNECT:
      if (received >= TREE_ID_OFFSET + sizeof(uint32_t))
        tree_id = u32((const uint8_t *)(buffer + TREE_ID_OFFSET));
      break;
    case SMB2_SESS_SETUP:
      // The harness expects its first successful session-setup response here.
      if (msg_no == 0x01 && received >= SESSION_ID_OFFSET + sizeof(uint64_t))
        session_id = u64((const uint8_t *)(buffer + SESSION_ID_OFFSET));
      break;
    case SMB2_CREATE:
      if (received >= CREATE_VFID_OFFSET + sizeof(uint64_t)) {
        persistent_file_id = u64((const uint8_t *)(buffer + CREATE_PFID_OFFSET));
        volatile_file_id   = u64((const uint8_t *)(buffer + CREATE_VFID_OFFSET));
      }
      break;
    default:
      break;
  }
}

Tips

Recover Coverage From ksmbd Worker Threads#

Recent ksmbd fuzzing work added KCOV remote coverage support via a per-connection handle because SMB requests are received on the connection thread and then executed asynchronously by handle_ksmbd_work() kworkers. Without that plumbing, valid network traffic can still reach the target but syzkaller loses visibility into the worker-side execution, which makes deeper ksmbd paths look artificially cold.[15]

Practical implications

Prefer a Hybrid Harness Over One Giant Pseudo-Syscall#

If you keep extending the setup, use the custom pseudo-syscall mainly for the bootstrap steps that are annoying to express declaratively (negotiate/session-setup/tree-connect), then export the returned identifiers as syzkaller resources for follow-up operations. syzkaller explicitly discourages overusing pseudo-syscalls, and a hybrid model makes minimization/crossover noticeably less painful.[1][14]

Example sketch:

resource ksmbd_sess[int64]
resource ksmbd_tree[int32]
resource ksmbd_fid[int64]

syz_ksmbd_bootstrap(..., sess ptr[out, ksmbd_sess], tree ptr[out, ksmbd_tree])
syz_ksmbd_create(..., sess ksmbd_sess, tree ksmbd_tree, fid ptr[out, ksmbd_fid])
syz_ksmbd_setinfo_acl(..., sess ksmbd_sess, tree ksmbd_tree, fid ksmbd_fid, ...)
syz_ksmbd_close(..., sess ksmbd_sess, tree ksmbd_tree, fid ksmbd_fid)

This keeps ordering information visible to the fuzzer instead of hiding the whole protocol behind one blob-oriented helper.


Grammar-Driven SMB2 Generation (Valid PDUs)#

Translate the Microsoft Open Specifications SMB2 structures into a fuzzer grammar so your generator produces structurally valid PDUs, which systematically reach dispatchers and IOCTL handlers.[11]

Example (SMB2 IOCTL request):

smb2_ioctl_req {
  Header_Prefix           SMB2Header_Prefix
  Command                 const[0xb, int16]
  Header_Suffix           SMB2Header_Suffix
  StructureSize           const[57, int16]
  Reserved                const[0, int16]
  CtlCode                 union_control_codes
  PersistentFileId        const[0x4, int64]
  VolatileFileId          const[0x0, int64]
  InputOffset             offsetof[Input, int32]
  InputCount              bytesize[Input, int32]
  MaxInputResponse        const[65536, int32]
  OutputOffset            offsetof[Output, int32]
  OutputCount             len[Output, int32]
  MaxOutputResponse       const[65536, int32]
  Flags                   int32[0:1]
  Reserved2               const[0, int32]
  Input                   array[int8]
  Output                  array[int8]
} [packed]

This style forces correct structure sizes/offsets and dramatically improves coverage versus blind mutation.[3]

Prioritise CREATE Contexts, ACLs, and Named Streams#

Recent upstream fixes landed in parser families that are easy to miss if the corpus only contains generic open/read/close traffic. Give these paths dedicated grammar entries and seed packets:

That bias is worthwhile because recent bug fixes landed in create-lease parsing, durable-handle context parsing, DACL/ACE validation, and compound QUERY_INFO response builders. If those objects stay opaque, syzkaller tends to spend mutations on packet noise instead of the fields that actually gate parser depth.[1]

For an exploitation-oriented example reached through streams_xattr, check the dedicated named-stream OOB write page.


Add Compound and Reconnect Scenarios to the Corpus#

Recent fixes showed that request parsing is only half of the attack surface: ksmbd also breaks in response builders and cross-connection lifetime handling.[1]

High-yield scenarios to model explicitly:

Useful mutation knobs in those scenarios:

These patterns map directly to recent bug families: response-buffer misaccounting in compound QUERY_INFO handlers, multichannel session UAFs in ksmbd_sessions_deregister(), and durable/lease create-context parser bugs that only show up when reconnect semantics are preserved.


Directed Fuzzing With focus_areas#

Use syzkaller’s experimental focus_areas to overweight specific functions/files that currently have weak coverage.[4] Example JSON:

{
  "focus_areas": [
    {"filter": {"functions": ["smb_check_perm_dacl"]}, "weight": 20.0},
    {"filter": {"files": ["^fs/smb/server/"]}, "weight": 2.0},
    {"weight": 1.0}
  ]
}

This helps construct valid ACLs that hit arithmetic/overflow paths in smbacl.c. For instance, a malicious Security Descriptor with an oversized dacloffset reproduces an integer-overflow.[1]

Reproducer builder (minimal Python):

def build_sd():
  import struct
  sd = bytearray(0x14)
  sd[0x00] = 0x00; sd[0x01] = 0x00
  struct.pack_into('<H', sd, 0x02, 0x0001)
  struct.pack_into('<I', sd, 0x04, 0x78)
  struct.pack_into('<I', sd, 0x08, 0x00)
  struct.pack_into('<I', sd, 0x0C, 0x10000)
  struct.pack_into('<I', sd, 0x10, 0xFFFFFFFF)  # dacloffset
  while len(sd) < 0x78:
    sd += b'A'
  sd += b"\x01\x01\x00\x00\x00\x00\x00\x00"  # minimal DACL
  sd += b"\xCC" * 64
  return bytes(sd)

Breaking Coverage Plateaus With ANYBLOB#

syzkaller’s anyTypes (ANYBLOB/ANYRES) allow collapsing complex structures into blobs that mutate generically.[5] Seed a new corpus from public SMB pcaps and convert payloads into syzkaller programs calling your pseudo-syscall (e.g., syz_ksmbd_send_req):[12]

# Extract SMB payloads to JSON
# tshark -r smb2_dac_sample.pcap -Y "smb || smb2" -T json -e tcp.payload > packets.json
import json, os
os.makedirs("corpus", exist_ok=True)

with open("packets.json") as f:
  data = json.load(f)
# adjust indexing to your tshark JSON structure
packets = [e["_source"]["layers"]["tcp.payload"] for e in data]

for i, pkt in enumerate(packets):
  pdu = pkt[0]
  pdu_size = len(pdu) // 2  # hex string length → bytes
  with open(f"corpus/packet_{i:03d}.txt", "w") as f:
    f.write(
      f"syz_ksmbd_send_req(&(&(0x7f0000000340))=ANY=[@ANYBLOB=\"{pdu}\"], {hex(pdu_size)}, 0x0, 0x0)"
    )

This jump-starts exploration and can immediately trigger UAFs (e.g., in ksmbd_sessions_deregister) while lifting coverage a few percent.[1]

Higher-value captures to seed on purpose


Sanitizers: Beyond KASAN#

id = le32_to_cpu(psid->sub_auth[psid->num_subauth - 1]);
struct smb_sid {
  __u8 revision; __u8 num_subauth; __u8 authority[NUM_AUTHS];
  __le32 sub_auth[SID_MAX_SUB_AUTHORITIES]; /* sub_auth[num_subauth] */
} __attribute__((packed));

Setting num_subauth = 0 triggers an in-struct OOB read of sub_auth[-1], caught by UBSAN’s declared-bounds checks.


Throughput and Parallelism Notes#


Practical Checklist#


References#