Skip to main content

smb_server/proto/
header.rs

1//! SMB2 fixed 64-byte packet header (sync + async forms).
2//!
3//! References:
4//! * MS-SMB2 §2.2.1   — Common header preamble.
5//! * MS-SMB2 §2.2.1.1 — Async form (`Flags & SMB2_FLAGS_ASYNC_COMMAND`).
6//! * MS-SMB2 §2.2.1.2 — Sync form.
7//!
8//! ## Encoding choice
9//!
10//! The two forms differ only in the 12-byte block at offset 0x18..0x24:
11//!
12//! * **Sync**:  `ChannelSequence` (u16) + `Reserved` (u16) + `Reserved2` (u32) + `TreeId` (u32)
13//!   wait — actually the sync form is: `Reserved` (u32) + `TreeId` (u32) (bytes 0x20..0x28).
14//! * **Async**: `AsyncId` (u64) at bytes 0x20..0x28.
15//!
16//! In *both* forms, bytes 0x10..0x14 are `Status` (or `ChannelSequence + Reserved` on
17//! 3.x channel-sequence-aware requests; we treat them as a single u32 named
18//! `channel_sequence_status`). Bytes 0x14..0x18 are `Command + CreditReqResp`,
19//! 0x18..0x1C are `Flags`, 0x1C..0x20 are `NextCommand`, 0x20..0x28 are `MessageId`.
20//! The discriminated 8-byte block lives at 0x28..0x30, followed by the 16-byte
21//! `Signature` at 0x30..0x40 — totalling 64 bytes.
22//!
23//! We model this as a single `Smb2Header` struct with a `tail: HeaderTail` enum
24//! that is `Sync { reserved: u32, tree_id: u32 }` or `Async { async_id: u64 }`,
25//! discriminated by `Flags & SMB2_FLAGS_ASYNC_COMMAND`. This is the cleanest
26//! mapping to the spec — every other field is shared.
27
28use binrw::{BinRead, BinWrite, binrw};
29use std::io::Cursor;
30
31use crate::proto::error::{ProtoError, ProtoResult};
32
33/// SMB2 protocol identifier ("\xfeSMB").
34pub const SMB2_MAGIC: [u8; 4] = [0xFE, b'S', b'M', b'B'];
35
36/// Fixed `StructureSize` of the SMB2 header (MS-SMB2 §2.2.1.1/§2.2.1.2).
37pub const SMB2_HEADER_STRUCTURE_SIZE: u16 = 64;
38
39/// Total wire size of the SMB2 header.
40pub const SMB2_HEADER_LEN: usize = 64;
41
42// ---------------------------------------------------------------------------
43// Flags (MS-SMB2 §2.2.1.2 Flags field)
44// ---------------------------------------------------------------------------
45
46/// `SMB2_FLAGS_SERVER_TO_REDIR` — set on responses.
47pub const SMB2_FLAGS_SERVER_TO_REDIR: u32 = 0x0000_0001;
48/// `SMB2_FLAGS_ASYNC_COMMAND` — selects the async header form.
49pub const SMB2_FLAGS_ASYNC_COMMAND: u32 = 0x0000_0002;
50/// `SMB2_FLAGS_RELATED_OPERATIONS` — compound chain marker.
51pub const SMB2_FLAGS_RELATED_OPERATIONS: u32 = 0x0000_0004;
52/// `SMB2_FLAGS_SIGNED` — message is signed.
53pub const SMB2_FLAGS_SIGNED: u32 = 0x0000_0008;
54/// `SMB2_FLAGS_PRIORITY_MASK` — bits 4..6 hold priority (3.1.1+).
55pub const SMB2_FLAGS_PRIORITY_MASK: u32 = 0x0000_0070;
56/// `SMB2_FLAGS_DFS_OPERATIONS`.
57pub const SMB2_FLAGS_DFS_OPERATIONS: u32 = 0x1000_0000;
58/// `SMB2_FLAGS_REPLAY_OPERATION`.
59pub const SMB2_FLAGS_REPLAY_OPERATION: u32 = 0x2000_0000;
60
61// ---------------------------------------------------------------------------
62// Command opcodes (MS-SMB2 §2.2.1.2 Command field)
63// ---------------------------------------------------------------------------
64
65/// SMB2 command opcodes (the 19 commands in v1).
66#[binrw]
67#[brw(little, repr = u16)]
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
69pub enum Command {
70    Negotiate = 0x0000,
71    SessionSetup = 0x0001,
72    Logoff = 0x0002,
73    TreeConnect = 0x0003,
74    TreeDisconnect = 0x0004,
75    Create = 0x0005,
76    Close = 0x0006,
77    Flush = 0x0007,
78    Read = 0x0008,
79    Write = 0x0009,
80    Lock = 0x000A,
81    Ioctl = 0x000B,
82    Cancel = 0x000C,
83    Echo = 0x000D,
84    QueryDirectory = 0x000E,
85    ChangeNotify = 0x000F,
86    QueryInfo = 0x0010,
87    SetInfo = 0x0011,
88    OplockBreak = 0x0012,
89}
90
91impl Command {
92    /// Raw opcode for diagnostics.
93    pub const fn as_u16(self) -> u16 {
94        self as u16
95    }
96}
97
98// ---------------------------------------------------------------------------
99// Header struct
100// ---------------------------------------------------------------------------
101
102/// The 12-byte tail of the header that differs between sync and async forms.
103///
104/// The discriminant is `flags & SMB2_FLAGS_ASYNC_COMMAND`. We can't easily use
105/// binrw's args+if without making the parent struct generic over the runtime
106/// flag value, so the parent reads/writes this manually via `parse` / `write`
107/// helpers and we expose a regular Rust enum here.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum HeaderTail {
110    /// Sync form: `Reserved (u32)` + `TreeId (u32)` at bytes 0x24..0x2C.
111    /// (See note in module docs about offsets.)
112    Sync { reserved: u32, tree_id: u32 },
113    /// Async form: `AsyncId (u64)` at bytes 0x24..0x2C.
114    Async { async_id: u64 },
115}
116
117impl HeaderTail {
118    /// Default sync tail with `TreeId = 0`.
119    pub const fn sync(tree_id: u32) -> Self {
120        HeaderTail::Sync {
121            reserved: 0,
122            tree_id,
123        }
124    }
125
126    /// Default async tail.
127    pub const fn async_(async_id: u64) -> Self {
128        HeaderTail::Async { async_id }
129    }
130}
131
132/// SMB2 fixed 64-byte header.
133///
134/// On the wire the layout is (offsets in decimal — total 64 bytes):
135///
136/// | Offset | Size | Field |
137/// |-------:|-----:|-------|
138/// |   0    |   4  | ProtocolId (`0xFE 'S' 'M' 'B'`) |
139/// |   4    |   2  | StructureSize (always 64) |
140/// |   6    |   2  | CreditCharge |
141/// |   8    |   4  | (Channel)Status |
142/// |  12    |   2  | Command |
143/// |  14    |   2  | CreditRequest/CreditResponse |
144/// |  16    |   4  | Flags |
145/// |  20    |   4  | NextCommand |
146/// |  24    |   8  | MessageId |
147/// |  32    |   8  | Reserved/TreeId (sync) **or** AsyncId (async) |
148/// |  40    |   8  | SessionId |
149/// |  48    |  16  | Signature |
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub struct Smb2Header {
152    pub credit_charge: u16,
153    /// Bytes 8..12: in client→server requests on 3.x this can split into
154    /// `ChannelSequence(u16)` + `Reserved(u16)`; in server→client responses
155    /// it carries `Status` (NTSTATUS). We expose the raw u32 — handlers/
156    /// signing code interpret it.
157    pub channel_sequence_status: u32,
158    pub command: Command,
159    /// On requests this is `CreditRequest`; on responses, `CreditResponse`.
160    pub credit_request_response: u16,
161    pub flags: u32,
162    /// Offset to the next header in a compound chain, or 0 for the last.
163    pub next_command: u32,
164    pub message_id: u64,
165    /// Sync: `(reserved, tree_id)`. Async: `async_id`. Discriminated by
166    /// `flags & SMB2_FLAGS_ASYNC_COMMAND`.
167    pub tail: HeaderTail,
168    pub session_id: u64,
169    /// 16-byte signature; zeroed on unsigned messages.
170    pub signature: [u8; 16],
171}
172
173impl Default for Smb2Header {
174    fn default() -> Self {
175        Self {
176            credit_charge: 0,
177            channel_sequence_status: 0,
178            command: Command::Negotiate,
179            credit_request_response: 0,
180            flags: 0,
181            next_command: 0,
182            message_id: 0,
183            tail: HeaderTail::sync(0),
184            session_id: 0,
185            signature: [0u8; 16],
186        }
187    }
188}
189
190impl Smb2Header {
191    /// Convenience: is this an async-form header?
192    pub fn is_async(&self) -> bool {
193        self.flags & SMB2_FLAGS_ASYNC_COMMAND != 0
194    }
195
196    /// Convenience: is this a server→client response?
197    pub fn is_response(&self) -> bool {
198        self.flags & SMB2_FLAGS_SERVER_TO_REDIR != 0
199    }
200
201    /// Convenience: tree_id from a sync header (panics if async).
202    pub fn tree_id(&self) -> Option<u32> {
203        match self.tail {
204            HeaderTail::Sync { tree_id, .. } => Some(tree_id),
205            HeaderTail::Async { .. } => None,
206        }
207    }
208
209    /// Convenience: async_id from an async header.
210    pub fn async_id(&self) -> Option<u64> {
211        match self.tail {
212            HeaderTail::Async { async_id } => Some(async_id),
213            HeaderTail::Sync { .. } => None,
214        }
215    }
216
217    /// Parse from a byte slice. Returns the header and the remaining bytes.
218    pub fn parse(buf: &[u8]) -> ProtoResult<(Self, &[u8])> {
219        if buf.len() < SMB2_HEADER_LEN {
220            return Err(ProtoError::Malformed("short SMB2 header"));
221        }
222        let mut cursor = Cursor::new(&buf[..SMB2_HEADER_LEN]);
223        let raw = RawHeader::read(&mut cursor)?;
224        if raw.protocol_id != SMB2_MAGIC {
225            return Err(ProtoError::Malformed("bad SMB2 magic"));
226        }
227        if raw.structure_size != SMB2_HEADER_STRUCTURE_SIZE {
228            return Err(ProtoError::Malformed("SMB2 header structure_size != 64"));
229        }
230        let command = match Command::read_le(&mut Cursor::new(raw.command_raw.to_le_bytes())) {
231            Ok(c) => c,
232            Err(_) => {
233                return Err(ProtoError::Malformed("unknown SMB2 command opcode"));
234            }
235        };
236        let tail = if raw.flags & SMB2_FLAGS_ASYNC_COMMAND != 0 {
237            HeaderTail::Async {
238                async_id: u64::from_le_bytes(raw.tail_bytes),
239            }
240        } else {
241            let reserved = u32::from_le_bytes([
242                raw.tail_bytes[0],
243                raw.tail_bytes[1],
244                raw.tail_bytes[2],
245                raw.tail_bytes[3],
246            ]);
247            let tree_id = u32::from_le_bytes([
248                raw.tail_bytes[4],
249                raw.tail_bytes[5],
250                raw.tail_bytes[6],
251                raw.tail_bytes[7],
252            ]);
253            HeaderTail::Sync { reserved, tree_id }
254        };
255        Ok((
256            Smb2Header {
257                credit_charge: raw.credit_charge,
258                channel_sequence_status: raw.channel_sequence_status,
259                command,
260                credit_request_response: raw.credit_request_response,
261                flags: raw.flags,
262                next_command: raw.next_command,
263                message_id: raw.message_id,
264                tail,
265                session_id: raw.session_id,
266                signature: raw.signature,
267            },
268            &buf[SMB2_HEADER_LEN..],
269        ))
270    }
271
272    /// Serialize the 64-byte header into `out`.
273    pub fn write(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
274        let tail_bytes = match self.tail {
275            HeaderTail::Sync { reserved, tree_id } => {
276                let mut b = [0u8; 8];
277                b[..4].copy_from_slice(&reserved.to_le_bytes());
278                b[4..].copy_from_slice(&tree_id.to_le_bytes());
279                b
280            }
281            HeaderTail::Async { async_id } => async_id.to_le_bytes(),
282        };
283        let raw = RawHeader {
284            protocol_id: SMB2_MAGIC,
285            structure_size: SMB2_HEADER_STRUCTURE_SIZE,
286            credit_charge: self.credit_charge,
287            channel_sequence_status: self.channel_sequence_status,
288            command_raw: self.command.as_u16(),
289            credit_request_response: self.credit_request_response,
290            flags: self.flags,
291            next_command: self.next_command,
292            message_id: self.message_id,
293            tail_bytes,
294            session_id: self.session_id,
295            signature: self.signature,
296        };
297        let start = out.len();
298        let mut cursor = Cursor::new(Vec::with_capacity(SMB2_HEADER_LEN));
299        raw.write(&mut cursor)?;
300        out.extend_from_slice(&cursor.into_inner());
301        debug_assert_eq!(out.len() - start, SMB2_HEADER_LEN);
302        Ok(())
303    }
304}
305
306// ---------------------------------------------------------------------------
307// Internal raw header for binrw plumbing.
308// ---------------------------------------------------------------------------
309
310#[binrw]
311#[brw(little)]
312#[derive(Debug, Clone, Copy)]
313struct RawHeader {
314    protocol_id: [u8; 4],
315    structure_size: u16,
316    credit_charge: u16,
317    channel_sequence_status: u32,
318    command_raw: u16,
319    credit_request_response: u16,
320    flags: u32,
321    next_command: u32,
322    message_id: u64,
323    tail_bytes: [u8; 8],
324    session_id: u64,
325    signature: [u8; 16],
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    fn sample_sync() -> Smb2Header {
333        Smb2Header {
334            credit_charge: 1,
335            channel_sequence_status: 0,
336            command: Command::Negotiate,
337            credit_request_response: 1,
338            flags: 0,
339            next_command: 0,
340            message_id: 0,
341            tail: HeaderTail::Sync {
342                reserved: 0,
343                tree_id: 0,
344            },
345            session_id: 0,
346            signature: [0u8; 16],
347        }
348    }
349
350    fn sample_async() -> Smb2Header {
351        Smb2Header {
352            credit_charge: 4,
353            channel_sequence_status: 0,
354            command: Command::Read,
355            credit_request_response: 1,
356            flags: SMB2_FLAGS_ASYNC_COMMAND | SMB2_FLAGS_SERVER_TO_REDIR,
357            next_command: 0,
358            message_id: 42,
359            tail: HeaderTail::Async {
360                async_id: 0xDEAD_BEEF_CAFE_F00D,
361            },
362            session_id: 0x1122_3344_5566_7788,
363            signature: [0xAA; 16],
364        }
365    }
366
367    #[test]
368    fn sync_round_trips() {
369        let hdr = sample_sync();
370        let mut buf = Vec::new();
371        hdr.write(&mut buf).unwrap();
372        assert_eq!(buf.len(), SMB2_HEADER_LEN);
373        // First 4 bytes must be the magic.
374        assert_eq!(&buf[..4], &SMB2_MAGIC);
375        // StructureSize at offset 4 == 64
376        assert_eq!(u16::from_le_bytes([buf[4], buf[5]]), 64);
377
378        let (decoded, rest) = Smb2Header::parse(&buf).unwrap();
379        assert!(rest.is_empty());
380        assert_eq!(decoded, hdr);
381    }
382
383    #[test]
384    fn async_round_trips() {
385        let hdr = sample_async();
386        let mut buf = Vec::new();
387        hdr.write(&mut buf).unwrap();
388        assert_eq!(buf.len(), SMB2_HEADER_LEN);
389
390        let (decoded, _rest) = Smb2Header::parse(&buf).unwrap();
391        assert_eq!(decoded, hdr);
392        assert!(decoded.is_async());
393        assert!(decoded.is_response());
394        assert_eq!(decoded.async_id(), Some(0xDEAD_BEEF_CAFE_F00D));
395        assert_eq!(decoded.tree_id(), None);
396    }
397
398    #[test]
399    fn rejects_bad_magic() {
400        let hdr = sample_sync();
401        let mut buf = Vec::new();
402        hdr.write(&mut buf).unwrap();
403        buf[0] = 0xFF;
404        let err = Smb2Header::parse(&buf).unwrap_err();
405        assert!(matches!(err, ProtoError::Malformed(_)));
406    }
407
408    #[test]
409    fn rejects_bad_structure_size() {
410        let hdr = sample_sync();
411        let mut buf = Vec::new();
412        hdr.write(&mut buf).unwrap();
413        buf[4] = 0; // wreck the structure_size LE bytes
414        buf[5] = 0;
415        let err = Smb2Header::parse(&buf).unwrap_err();
416        assert!(matches!(err, ProtoError::Malformed(_)));
417    }
418
419    #[test]
420    fn rejects_short_buffer() {
421        let err = Smb2Header::parse(&[0u8; 32]).unwrap_err();
422        assert!(matches!(err, ProtoError::Malformed(_)));
423    }
424
425    #[test]
426    fn handcrafted_sync_negotiate_request() {
427        // Hand-built Sync NEGOTIATE request header: magic, size=64, no flags,
428        // command=0, mid=0, tree_id=0, sid=0, no signature.
429        let mut buf = vec![0u8; 64];
430        buf[..4].copy_from_slice(&SMB2_MAGIC);
431        buf[4..6].copy_from_slice(&64u16.to_le_bytes());
432        // command at offset 12 = 0 (NEGOTIATE), already zero
433        // everything else zero
434        let (hdr, _) = Smb2Header::parse(&buf).unwrap();
435        assert_eq!(hdr.command, Command::Negotiate);
436        assert!(!hdr.is_async());
437        assert_eq!(hdr.tree_id(), Some(0));
438    }
439
440    #[test]
441    fn command_round_trips_via_binrw() {
442        for cmd in [
443            Command::Negotiate,
444            Command::SessionSetup,
445            Command::Logoff,
446            Command::TreeConnect,
447            Command::TreeDisconnect,
448            Command::Create,
449            Command::Close,
450            Command::Flush,
451            Command::Read,
452            Command::Write,
453            Command::Lock,
454            Command::Ioctl,
455            Command::Cancel,
456            Command::Echo,
457            Command::QueryDirectory,
458            Command::ChangeNotify,
459            Command::QueryInfo,
460            Command::SetInfo,
461            Command::OplockBreak,
462        ] {
463            let mut hdr = sample_sync();
464            hdr.command = cmd;
465            let mut buf = Vec::new();
466            hdr.write(&mut buf).unwrap();
467            let (decoded, _) = Smb2Header::parse(&buf).unwrap();
468            assert_eq!(decoded.command, cmd);
469        }
470    }
471}