1use binrw::{BinRead, BinWrite, binrw};
9use std::io::Cursor;
10
11use crate::proto::error::{ProtoError, ProtoResult};
12
13#[binrw]
17#[brw(little)]
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
19pub struct FileId {
20 pub persistent: u64,
21 pub volatile: u64,
22}
23
24impl FileId {
25 pub const fn new(persistent: u64, volatile: u64) -> Self {
26 Self {
27 persistent,
28 volatile,
29 }
30 }
31
32 pub const fn any() -> Self {
34 Self {
35 persistent: u64::MAX,
36 volatile: u64::MAX,
37 }
38 }
39}
40
41const CREATE_BUFFER_OFFSET: u64 = 0x78;
44
45#[binrw]
55#[brw(little)]
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct CreateRequest {
58 pub structure_size: u16,
59 pub security_flags: u8,
60 pub requested_oplock_level: u8,
61 pub impersonation_level: u32,
62 pub smb_create_flags: u64,
63 pub reserved: u64,
64 pub desired_access: u32,
65 pub file_attributes: u32,
66 pub share_access: u32,
67 pub create_disposition: u32,
68 pub create_options: u32,
69 pub name_offset: u16,
70 pub name_length: u16,
71 pub create_contexts_offset: u32,
72 pub create_contexts_length: u32,
73 #[br(parse_with = super::read_buf_at, args(
75 name_offset.into(),
76 name_length.into(),
77 CREATE_BUFFER_OFFSET,
78 ))]
79 pub name: Vec<u8>,
80 #[br(parse_with = super::read_buf_at, args(
83 create_contexts_offset.into(),
84 create_contexts_length as usize,
85 CREATE_BUFFER_OFFSET,
86 ))]
87 pub create_contexts: Vec<u8>,
88}
89
90impl CreateRequest {
91 pub fn name_str(&self) -> Option<String> {
93 if !self.name.len().is_multiple_of(2) {
94 return None;
95 }
96 let units: Vec<u16> = self
97 .name
98 .chunks_exact(2)
99 .map(|c| u16::from_le_bytes([c[0], c[1]]))
100 .collect();
101 Some(String::from_utf16_lossy(&units))
102 }
103
104 pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
105 Ok(Self::read(&mut Cursor::new(buf))?)
106 }
107 pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
108 let mut c = Cursor::new(Vec::new());
109 BinWrite::write(self, &mut c)?;
110 out.extend_from_slice(&c.into_inner());
111 Ok(())
112 }
113}
114
115#[binrw]
117#[brw(little)]
118#[derive(Debug, Clone, PartialEq, Eq)]
119pub struct CreateResponse {
120 pub structure_size: u16,
121 pub oplock_level: u8,
122 pub flags: u8,
123 pub create_action: u32,
124 pub creation_time: u64,
125 pub last_access_time: u64,
126 pub last_write_time: u64,
127 pub change_time: u64,
128 pub allocation_size: u64,
129 pub end_of_file: u64,
130 pub file_attributes: u32,
131 pub reserved2: u32,
132 pub file_id: FileId,
133 pub create_contexts_offset: u32,
134 pub create_contexts_length: u32,
135 #[br(parse_with = super::read_buf, args(create_contexts_length as usize))]
136 pub create_contexts: Vec<u8>,
137}
138
139impl CreateResponse {
140 pub fn parse(buf: &[u8]) -> ProtoResult<Self> {
141 Ok(Self::read(&mut Cursor::new(buf))?)
142 }
143 pub fn write_to(&self, out: &mut Vec<u8>) -> ProtoResult<()> {
144 let mut c = Cursor::new(Vec::new());
145 BinWrite::write(self, &mut c)?;
146 out.extend_from_slice(&c.into_inner());
147 Ok(())
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Default)]
169pub struct CreateContext {
170 pub name: Vec<u8>,
171 pub data: Vec<u8>,
172}
173
174impl CreateContext {
175 pub const NAME_EXTA: &'static [u8; 4] = b"ExtA"; pub const NAME_SECD: &'static [u8; 4] = b"SecD"; pub const NAME_DHNQ: &'static [u8; 4] = b"DHnQ"; pub const NAME_DHNC: &'static [u8; 4] = b"DHnC"; pub const NAME_ALSI: &'static [u8; 4] = b"AlSi"; pub const NAME_MXAC: &'static [u8; 4] = b"MxAc"; pub const NAME_TWRP: &'static [u8; 4] = b"TWrp"; pub const NAME_QFID: &'static [u8; 4] = b"QFid"; pub const NAME_RQLS: &'static [u8; 4] = b"RqLs"; pub const NAME_DH2Q: &'static [u8; 4] = b"DH2Q"; pub const NAME_DH2C: &'static [u8; 4] = b"DH2C"; pub fn parse_chain(chain: &[u8]) -> ProtoResult<Vec<CreateContext>> {
196 let mut out = Vec::new();
197 if chain.is_empty() {
198 return Ok(out);
199 }
200 let mut cursor_off = 0usize;
201 loop {
202 let rest = chain
203 .get(cursor_off..)
204 .ok_or(ProtoError::Malformed("create context out of range"))?;
205 if rest.len() < 16 {
206 return Err(ProtoError::Malformed("create context too short"));
207 }
208 let next = u32::from_le_bytes([rest[0], rest[1], rest[2], rest[3]]) as usize;
209 let entry = match next {
210 0 => rest,
211 16.. => rest
212 .get(..next)
213 .ok_or(ProtoError::Malformed("create context next out of range"))?,
214 _ => return Err(ProtoError::Malformed("create context too short")),
215 };
216 let name_offset = u16::from_le_bytes([entry[4], entry[5]]) as usize;
217 let name_length = u16::from_le_bytes([entry[6], entry[7]]) as usize;
218 let data_offset = u16::from_le_bytes([entry[10], entry[11]]) as usize;
220 let data_length =
221 u32::from_le_bytes([entry[12], entry[13], entry[14], entry[15]]) as usize;
222 if name_length < 4 {
223 return Err(ProtoError::Malformed("create context name too short"));
224 }
225
226 let name = entry
227 .get(name_offset..name_offset + name_length)
228 .ok_or(ProtoError::Malformed("create context name out of range"))?
229 .to_vec();
230 let data = if data_length == 0 {
231 Vec::new()
232 } else {
233 data_offset
234 .checked_add(data_length)
235 .and_then(|end| entry.get(data_offset..end))
236 .ok_or(ProtoError::Malformed("create context data out of range"))?
237 .to_vec()
238 };
239 out.push(CreateContext { name, data });
240
241 if next == 0 {
242 break;
243 }
244 cursor_off = cursor_off
245 .checked_add(next)
246 .ok_or(ProtoError::Malformed("create context next overflow"))?;
247 }
248 Ok(out)
249 }
250
251 pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
254 if list.is_empty() {
255 return Ok(());
256 }
257 let mut scratch: Vec<u8> = Vec::new();
262 let mut entry_starts: Vec<usize> = Vec::with_capacity(list.len());
263
264 for (i, ctx) in list.iter().enumerate() {
265 while !scratch.len().is_multiple_of(8) {
268 scratch.push(0);
269 }
270 entry_starts.push(scratch.len());
271
272 let header_pos = scratch.len();
275 scratch.extend_from_slice(&[0u8; 16]);
276
277 let name_offset_rel = (scratch.len() - header_pos) as u16;
279 scratch.extend_from_slice(&ctx.name);
280 while !(scratch.len() - header_pos).is_multiple_of(8) {
282 scratch.push(0);
283 }
284 let data_offset_rel = (scratch.len() - header_pos) as u16;
285 scratch.extend_from_slice(&ctx.data);
286
287 let hdr = &mut scratch[header_pos..header_pos + 16];
289 hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); hdr[4..6].copy_from_slice(&name_offset_rel.to_le_bytes());
291 hdr[6..8].copy_from_slice(&(ctx.name.len() as u16).to_le_bytes());
292 hdr[8..10].copy_from_slice(&0u16.to_le_bytes()); hdr[10..12].copy_from_slice(&data_offset_rel.to_le_bytes());
294 hdr[12..16].copy_from_slice(&(ctx.data.len() as u32).to_le_bytes());
295
296 if i + 1 < list.len() {
299 while !scratch.len().is_multiple_of(8) {
300 scratch.push(0);
301 }
302 }
303 }
304
305 for i in 0..(entry_starts.len() - 1) {
307 let this = entry_starts[i];
308 let next = entry_starts[i + 1];
309 let delta = (next - this) as u32;
310 scratch[this..this + 4].copy_from_slice(&delta.to_le_bytes());
311 }
312 out.extend_from_slice(&scratch);
315 Ok(())
316 }
317}
318
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325#[repr(u8)]
326pub enum OplockLevel {
327 None = 0x00,
328 Ii = 0x01,
329 Exclusive = 0x08,
330 Batch = 0x09,
331 Lease = 0xFF,
332}
333
334impl OplockLevel {
335 pub fn from_u8(v: u8) -> Option<Self> {
336 Some(match v {
337 0x00 => Self::None,
338 0x01 => Self::Ii,
339 0x08 => Self::Exclusive,
340 0x09 => Self::Batch,
341 0xFF => Self::Lease,
342 _ => return None,
343 })
344 }
345}
346
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349#[repr(u32)]
350pub enum ImpersonationLevel {
351 Anonymous = 0x0000_0000,
352 Identification = 0x0000_0001,
353 Impersonation = 0x0000_0002,
354 Delegate = 0x0000_0003,
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360
361 fn utf16le(s: &str) -> Vec<u8> {
362 s.encode_utf16().flat_map(u16::to_le_bytes).collect()
363 }
364
365 #[test]
366 fn request_round_trips() {
367 let name = utf16le("dir\\file.txt");
368 let r = CreateRequest {
369 structure_size: 57,
370 security_flags: 0,
371 requested_oplock_level: 0,
372 impersonation_level: ImpersonationLevel::Impersonation as u32,
373 smb_create_flags: 0,
374 reserved: 0,
375 desired_access: 0x0012_0089,
376 file_attributes: 0,
377 share_access: 0x0000_0007,
378 create_disposition: 1,
379 create_options: 0x0000_0040,
380 name_offset: 0x78,
381 name_length: name.len() as u16,
382 create_contexts_offset: 0,
383 create_contexts_length: 0,
384 name,
385 create_contexts: vec![],
386 };
387 let mut buf = Vec::new();
388 r.write_to(&mut buf).unwrap();
389 let decoded = CreateRequest::parse(&buf).unwrap();
390 assert_eq!(decoded, r);
391 assert_eq!(decoded.name_str().unwrap(), "dir\\file.txt");
392 }
393
394 fn body_with_buffers(
397 name: &[u8],
398 name_offset: u16,
399 contexts: &[u8],
400 contexts_offset: u32,
401 ) -> Vec<u8> {
402 let fixed = CreateRequest {
403 structure_size: 57,
404 security_flags: 0,
405 requested_oplock_level: 0,
406 impersonation_level: ImpersonationLevel::Impersonation as u32,
407 smb_create_flags: 0,
408 reserved: 0,
409 desired_access: 0x0012_0089,
410 file_attributes: 0,
411 share_access: 0x0000_0007,
412 create_disposition: 1,
413 create_options: 0,
414 name_offset,
415 name_length: name.len() as u16,
416 create_contexts_offset: contexts_offset,
417 create_contexts_length: contexts.len() as u32,
418 name: vec![],
419 create_contexts: vec![],
420 };
421 let mut body = Vec::new();
422 fixed.write_to(&mut body).unwrap();
423 for (data, offset) in [(name, u32::from(name_offset)), (contexts, contexts_offset)] {
424 if data.is_empty() {
425 continue;
426 }
427 let start = offset as usize - 64;
428 if body.len() < start + data.len() {
429 body.resize(start + data.len(), 0);
430 }
431 body[start..start + data.len()].copy_from_slice(data);
432 }
433 body
434 }
435
436 #[test]
437 fn request_reads_name_and_contexts_at_their_offsets() {
438 let name = utf16le("dir\\file.txt");
439 let ctxs = vec![CreateContext {
440 name: CreateContext::NAME_MXAC.to_vec(),
441 data: vec![],
442 }];
443 let mut chain = Vec::new();
444 CreateContext::encode_chain(&ctxs, &mut chain).unwrap();
445 let name_offset = 0x80;
447 let contexts_offset = (u32::from(name_offset) + name.len() as u32).next_multiple_of(8);
448 let body = body_with_buffers(&name, name_offset, &chain, contexts_offset);
449
450 let req = CreateRequest::parse(&body).unwrap();
451 assert_eq!(req.name_str().unwrap(), "dir\\file.txt");
452 assert_eq!(
453 CreateContext::parse_chain(&req.create_contexts).unwrap(),
454 ctxs
455 );
456 }
457
458 #[test]
459 fn request_rejects_buffers_outside_the_request() {
460 const NAME_OFFSET_FIELD: usize = 44;
462 let name = utf16le("a.txt");
463 for name_offset in [0x70, 0x200] {
465 let mut body = body_with_buffers(&name, 0x78, &[], 0x78);
466 body[NAME_OFFSET_FIELD..NAME_OFFSET_FIELD + 2]
467 .copy_from_slice(&u16::to_le_bytes(name_offset));
468 assert!(
469 CreateRequest::parse(&body).is_err(),
470 "name offset {name_offset:#x}"
471 );
472 }
473 let mut body = body_with_buffers(&name, 0x78, &[0; 16], 0x88);
475 body.truncate(body.len() - 1);
476 assert!(CreateRequest::parse(&body).is_err());
477 }
478
479 #[test]
480 fn request_accepts_empty_buffers_at_any_offset() {
481 let body = body_with_buffers(&[], 0, &[], 0);
482 let req = CreateRequest::parse(&body).unwrap();
483 assert_eq!(req.name_str().unwrap(), "");
484 assert!(req.create_contexts.is_empty());
485 }
486
487 #[test]
488 fn response_round_trips() {
489 let r = CreateResponse {
490 structure_size: 89,
491 oplock_level: 0,
492 flags: 0,
493 create_action: 1,
494 creation_time: 0x01D9_0000_0000_0000,
495 last_access_time: 0x01D9_0000_0000_0000,
496 last_write_time: 0x01D9_0000_0000_0000,
497 change_time: 0x01D9_0000_0000_0000,
498 allocation_size: 0x1000,
499 end_of_file: 0x800,
500 file_attributes: 0x0020,
501 reserved2: 0,
502 file_id: FileId::new(0x1234, 0x5678),
503 create_contexts_offset: 0,
504 create_contexts_length: 0,
505 create_contexts: vec![],
506 };
507 let mut buf = Vec::new();
508 r.write_to(&mut buf).unwrap();
509 let decoded = CreateResponse::parse(&buf).unwrap();
510 assert_eq!(decoded, r);
511 }
512
513 #[test]
514 fn create_context_chain_round_trips_single() {
515 let ctxs = vec![CreateContext {
516 name: b"MxAc".to_vec(),
517 data: vec![],
518 }];
519 let mut buf = Vec::new();
520 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
521 let decoded = CreateContext::parse_chain(&buf).unwrap();
522 assert_eq!(decoded, ctxs);
523 }
524
525 #[test]
526 fn create_context_chain_round_trips_multi() {
527 let ctxs = vec![
528 CreateContext {
529 name: b"DHnQ".to_vec(),
530 data: vec![0u8; 16],
531 },
532 CreateContext {
533 name: b"MxAc".to_vec(),
534 data: vec![],
535 },
536 CreateContext {
537 name: b"QFid".to_vec(),
538 data: vec![0xAA; 32],
539 },
540 ];
541 let mut buf = Vec::new();
542 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
543 let decoded = CreateContext::parse_chain(&buf).unwrap();
544 assert_eq!(decoded, ctxs);
545 }
546
547 #[test]
548 fn create_context_chain_rejects_malformed_entries() {
549 let short_name = vec![CreateContext {
550 name: b"MxA".to_vec(),
551 data: vec![],
552 }];
553 let mut buf = Vec::new();
554 CreateContext::encode_chain(&short_name, &mut buf).unwrap();
555 assert!(CreateContext::parse_chain(&buf).is_err());
556
557 let pair = vec![
558 CreateContext {
559 name: b"QFid".to_vec(),
560 data: vec![],
561 },
562 CreateContext {
563 name: b"MxAc".to_vec(),
564 data: vec![0; 8],
565 },
566 ];
567 let mut chain = Vec::new();
568 CreateContext::encode_chain(&pair, &mut chain).unwrap();
569 let next = u32::from_le_bytes(chain[0..4].try_into().unwrap());
570 let mut bad = chain.clone();
572 bad[10..12].copy_from_slice(&16u16.to_le_bytes());
573 bad[12..16].copy_from_slice(&next.to_le_bytes());
574 assert!(CreateContext::parse_chain(&bad).is_err());
575 for next in [8u32, chain.len() as u32 + 8] {
577 let mut bad = chain.clone();
578 bad[0..4].copy_from_slice(&next.to_le_bytes());
579 assert!(CreateContext::parse_chain(&bad).is_err(), "next {next}");
580 }
581 }
582
583 #[test]
584 fn empty_chain_round_trips() {
585 let ctxs: Vec<CreateContext> = vec![];
586 let mut buf = Vec::new();
587 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
588 assert!(buf.is_empty());
589 let decoded = CreateContext::parse_chain(&buf).unwrap();
590 assert!(decoded.is_empty());
591 }
592}