1use binrw::{BinRead, BinWrite, binrw};
29use std::io::Cursor;
30
31use crate::proto::error::{ProtoError, ProtoResult};
32
33pub const SMB2_MAGIC: [u8; 4] = [0xFE, b'S', b'M', b'B'];
35
36pub const SMB2_HEADER_STRUCTURE_SIZE: u16 = 64;
38
39pub const SMB2_HEADER_LEN: usize = 64;
41
42pub const SMB2_FLAGS_SERVER_TO_REDIR: u32 = 0x0000_0001;
48pub const SMB2_FLAGS_ASYNC_COMMAND: u32 = 0x0000_0002;
50pub const SMB2_FLAGS_RELATED_OPERATIONS: u32 = 0x0000_0004;
52pub const SMB2_FLAGS_SIGNED: u32 = 0x0000_0008;
54pub const SMB2_FLAGS_PRIORITY_MASK: u32 = 0x0000_0070;
56pub const SMB2_FLAGS_DFS_OPERATIONS: u32 = 0x1000_0000;
58pub const SMB2_FLAGS_REPLAY_OPERATION: u32 = 0x2000_0000;
60
61#[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 pub const fn as_u16(self) -> u16 {
94 self as u16
95 }
96}
97
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub enum HeaderTail {
110 Sync { reserved: u32, tree_id: u32 },
113 Async { async_id: u64 },
115}
116
117impl HeaderTail {
118 pub const fn sync(tree_id: u32) -> Self {
120 HeaderTail::Sync {
121 reserved: 0,
122 tree_id,
123 }
124 }
125
126 pub const fn async_(async_id: u64) -> Self {
128 HeaderTail::Async { async_id }
129 }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub struct Smb2Header {
152 pub credit_charge: u16,
153 pub channel_sequence_status: u32,
158 pub command: Command,
159 pub credit_request_response: u16,
161 pub flags: u32,
162 pub next_command: u32,
164 pub message_id: u64,
165 pub tail: HeaderTail,
168 pub session_id: u64,
169 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 pub fn is_async(&self) -> bool {
193 self.flags & SMB2_FLAGS_ASYNC_COMMAND != 0
194 }
195
196 pub fn is_response(&self) -> bool {
198 self.flags & SMB2_FLAGS_SERVER_TO_REDIR != 0
199 }
200
201 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 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 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 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#[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 assert_eq!(&buf[..4], &SMB2_MAGIC);
375 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; 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 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 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}