1use binrw::{BinRead, BinWrite, binrw};
24use std::io::Cursor;
25
26use crate::proto::error::{ProtoError, ProtoResult};
27
28pub const SMB2_MAGIC: [u8; 4] = [0xFE, b'S', b'M', b'B'];
30
31pub const SMB2_HEADER_STRUCTURE_SIZE: u16 = 64;
33
34pub const SMB2_HEADER_LEN: usize = 64;
36
37pub const SMB2_FLAGS_SERVER_TO_REDIR: u32 = 0x0000_0001;
43pub const SMB2_FLAGS_ASYNC_COMMAND: u32 = 0x0000_0002;
45pub const SMB2_FLAGS_RELATED_OPERATIONS: u32 = 0x0000_0004;
47pub const SMB2_FLAGS_SIGNED: u32 = 0x0000_0008;
49pub const SMB2_FLAGS_PRIORITY_MASK: u32 = 0x0000_0070;
51pub const SMB2_FLAGS_DFS_OPERATIONS: u32 = 0x1000_0000;
53pub const SMB2_FLAGS_REPLAY_OPERATION: u32 = 0x2000_0000;
55
56#[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 pub const fn as_u16(self) -> u16 {
89 self as u16
90 }
91}
92
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum HeaderTail {
104 Sync { reserved: u32, tree_id: u32 },
106 Async { async_id: u64 },
108}
109
110impl HeaderTail {
111 pub const fn sync(tree_id: u32) -> Self {
113 HeaderTail::Sync {
114 reserved: 0,
115 tree_id,
116 }
117 }
118
119 pub const fn async_(async_id: u64) -> Self {
121 HeaderTail::Async { async_id }
122 }
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub struct Smb2Header {
145 pub credit_charge: u16,
146 pub channel_sequence_status: u32,
150 pub command: Command,
151 pub credit_request_response: u16,
153 pub flags: u32,
154 pub next_command: u32,
156 pub message_id: u64,
157 pub tail: HeaderTail,
160 pub session_id: u64,
161 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 pub fn is_async(&self) -> bool {
185 self.flags & SMB2_FLAGS_ASYNC_COMMAND != 0
186 }
187
188 pub fn is_response(&self) -> bool {
190 self.flags & SMB2_FLAGS_SERVER_TO_REDIR != 0
191 }
192
193 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 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 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 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#[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 assert_eq!(&buf[..4], &SMB2_MAGIC);
367 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; 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 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 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}