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