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 entry
234 .get(data_offset..data_offset + data_length)
235 .ok_or(ProtoError::Malformed("create context data out of range"))?
236 .to_vec()
237 };
238 out.push(CreateContext { name, data });
239
240 if next == 0 {
241 break;
242 }
243 cursor_off = cursor_off
244 .checked_add(next)
245 .ok_or(ProtoError::Malformed("create context next overflow"))?;
246 }
247 Ok(out)
248 }
249
250 pub fn encode_chain(list: &[CreateContext], out: &mut Vec<u8>) -> ProtoResult<()> {
253 if list.is_empty() {
254 return Ok(());
255 }
256 let mut scratch: Vec<u8> = Vec::new();
261 let mut entry_starts: Vec<usize> = Vec::with_capacity(list.len());
262
263 for (i, ctx) in list.iter().enumerate() {
264 while !scratch.len().is_multiple_of(8) {
267 scratch.push(0);
268 }
269 entry_starts.push(scratch.len());
270
271 let header_pos = scratch.len();
274 scratch.extend_from_slice(&[0u8; 16]);
275
276 let name_offset_rel = (scratch.len() - header_pos) as u16;
278 scratch.extend_from_slice(&ctx.name);
279 while !(scratch.len() - header_pos).is_multiple_of(8) {
281 scratch.push(0);
282 }
283 let data_offset_rel = (scratch.len() - header_pos) as u16;
284 scratch.extend_from_slice(&ctx.data);
285
286 let hdr = &mut scratch[header_pos..header_pos + 16];
288 hdr[0..4].copy_from_slice(&0u32.to_le_bytes()); hdr[4..6].copy_from_slice(&name_offset_rel.to_le_bytes());
290 hdr[6..8].copy_from_slice(&(ctx.name.len() as u16).to_le_bytes());
291 hdr[8..10].copy_from_slice(&0u16.to_le_bytes()); hdr[10..12].copy_from_slice(&data_offset_rel.to_le_bytes());
293 hdr[12..16].copy_from_slice(&(ctx.data.len() as u32).to_le_bytes());
294
295 if i + 1 < list.len() {
298 while !scratch.len().is_multiple_of(8) {
299 scratch.push(0);
300 }
301 }
302 }
303
304 for i in 0..(entry_starts.len() - 1) {
306 let this = entry_starts[i];
307 let next = entry_starts[i + 1];
308 let delta = (next - this) as u32;
309 scratch[this..this + 4].copy_from_slice(&delta.to_le_bytes());
310 }
311 out.extend_from_slice(&scratch);
314 Ok(())
315 }
316}
317
318#[derive(Debug, Clone, Copy, PartialEq, Eq)]
324#[repr(u8)]
325pub enum OplockLevel {
326 None = 0x00,
327 Ii = 0x01,
328 Exclusive = 0x08,
329 Batch = 0x09,
330 Lease = 0xFF,
331}
332
333impl OplockLevel {
334 pub fn from_u8(v: u8) -> Option<Self> {
335 Some(match v {
336 0x00 => Self::None,
337 0x01 => Self::Ii,
338 0x08 => Self::Exclusive,
339 0x09 => Self::Batch,
340 0xFF => Self::Lease,
341 _ => return None,
342 })
343 }
344}
345
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348#[repr(u32)]
349pub enum ImpersonationLevel {
350 Anonymous = 0x0000_0000,
351 Identification = 0x0000_0001,
352 Impersonation = 0x0000_0002,
353 Delegate = 0x0000_0003,
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 fn utf16le(s: &str) -> Vec<u8> {
361 s.encode_utf16().flat_map(u16::to_le_bytes).collect()
362 }
363
364 #[test]
365 fn request_round_trips() {
366 let name = utf16le("dir\\file.txt");
367 let r = CreateRequest {
368 structure_size: 57,
369 security_flags: 0,
370 requested_oplock_level: 0,
371 impersonation_level: ImpersonationLevel::Impersonation as u32,
372 smb_create_flags: 0,
373 reserved: 0,
374 desired_access: 0x0012_0089,
375 file_attributes: 0,
376 share_access: 0x0000_0007,
377 create_disposition: 1,
378 create_options: 0x0000_0040,
379 name_offset: 0x78,
380 name_length: name.len() as u16,
381 create_contexts_offset: 0,
382 create_contexts_length: 0,
383 name,
384 create_contexts: vec![],
385 };
386 let mut buf = Vec::new();
387 r.write_to(&mut buf).unwrap();
388 let decoded = CreateRequest::parse(&buf).unwrap();
389 assert_eq!(decoded, r);
390 assert_eq!(decoded.name_str().unwrap(), "dir\\file.txt");
391 }
392
393 fn body_with_buffers(
396 name: &[u8],
397 name_offset: u16,
398 contexts: &[u8],
399 contexts_offset: u32,
400 ) -> Vec<u8> {
401 let fixed = CreateRequest {
402 structure_size: 57,
403 security_flags: 0,
404 requested_oplock_level: 0,
405 impersonation_level: ImpersonationLevel::Impersonation as u32,
406 smb_create_flags: 0,
407 reserved: 0,
408 desired_access: 0x0012_0089,
409 file_attributes: 0,
410 share_access: 0x0000_0007,
411 create_disposition: 1,
412 create_options: 0,
413 name_offset,
414 name_length: name.len() as u16,
415 create_contexts_offset: contexts_offset,
416 create_contexts_length: contexts.len() as u32,
417 name: vec![],
418 create_contexts: vec![],
419 };
420 let mut body = Vec::new();
421 fixed.write_to(&mut body).unwrap();
422 for (data, offset) in [(name, u32::from(name_offset)), (contexts, contexts_offset)] {
423 if data.is_empty() {
424 continue;
425 }
426 let start = offset as usize - 64;
427 if body.len() < start + data.len() {
428 body.resize(start + data.len(), 0);
429 }
430 body[start..start + data.len()].copy_from_slice(data);
431 }
432 body
433 }
434
435 #[test]
436 fn request_reads_name_and_contexts_at_their_offsets() {
437 let name = utf16le("dir\\file.txt");
438 let ctxs = vec![CreateContext {
439 name: CreateContext::NAME_MXAC.to_vec(),
440 data: vec![],
441 }];
442 let mut chain = Vec::new();
443 CreateContext::encode_chain(&ctxs, &mut chain).unwrap();
444 let name_offset = 0x80;
446 let contexts_offset = (u32::from(name_offset) + name.len() as u32).next_multiple_of(8);
447 let body = body_with_buffers(&name, name_offset, &chain, contexts_offset);
448
449 let req = CreateRequest::parse(&body).unwrap();
450 assert_eq!(req.name_str().unwrap(), "dir\\file.txt");
451 assert_eq!(
452 CreateContext::parse_chain(&req.create_contexts).unwrap(),
453 ctxs
454 );
455 }
456
457 #[test]
458 fn request_rejects_buffers_outside_the_request() {
459 const NAME_OFFSET_FIELD: usize = 44;
461 let name = utf16le("a.txt");
462 for name_offset in [0x70, 0x200] {
464 let mut body = body_with_buffers(&name, 0x78, &[], 0x78);
465 body[NAME_OFFSET_FIELD..NAME_OFFSET_FIELD + 2]
466 .copy_from_slice(&u16::to_le_bytes(name_offset));
467 assert!(
468 CreateRequest::parse(&body).is_err(),
469 "name offset {name_offset:#x}"
470 );
471 }
472 let mut body = body_with_buffers(&name, 0x78, &[0; 16], 0x88);
474 body.truncate(body.len() - 1);
475 assert!(CreateRequest::parse(&body).is_err());
476 }
477
478 #[test]
479 fn request_accepts_empty_buffers_at_any_offset() {
480 let body = body_with_buffers(&[], 0, &[], 0);
481 let req = CreateRequest::parse(&body).unwrap();
482 assert_eq!(req.name_str().unwrap(), "");
483 assert!(req.create_contexts.is_empty());
484 }
485
486 #[test]
487 fn response_round_trips() {
488 let r = CreateResponse {
489 structure_size: 89,
490 oplock_level: 0,
491 flags: 0,
492 create_action: 1,
493 creation_time: 0x01D9_0000_0000_0000,
494 last_access_time: 0x01D9_0000_0000_0000,
495 last_write_time: 0x01D9_0000_0000_0000,
496 change_time: 0x01D9_0000_0000_0000,
497 allocation_size: 0x1000,
498 end_of_file: 0x800,
499 file_attributes: 0x0020,
500 reserved2: 0,
501 file_id: FileId::new(0x1234, 0x5678),
502 create_contexts_offset: 0,
503 create_contexts_length: 0,
504 create_contexts: vec![],
505 };
506 let mut buf = Vec::new();
507 r.write_to(&mut buf).unwrap();
508 let decoded = CreateResponse::parse(&buf).unwrap();
509 assert_eq!(decoded, r);
510 }
511
512 #[test]
513 fn create_context_chain_round_trips_single() {
514 let ctxs = vec![CreateContext {
515 name: b"MxAc".to_vec(),
516 data: vec![],
517 }];
518 let mut buf = Vec::new();
519 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
520 let decoded = CreateContext::parse_chain(&buf).unwrap();
521 assert_eq!(decoded, ctxs);
522 }
523
524 #[test]
525 fn create_context_chain_round_trips_multi() {
526 let ctxs = vec![
527 CreateContext {
528 name: b"DHnQ".to_vec(),
529 data: vec![0u8; 16],
530 },
531 CreateContext {
532 name: b"MxAc".to_vec(),
533 data: vec![],
534 },
535 CreateContext {
536 name: b"QFid".to_vec(),
537 data: vec![0xAA; 32],
538 },
539 ];
540 let mut buf = Vec::new();
541 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
542 let decoded = CreateContext::parse_chain(&buf).unwrap();
543 assert_eq!(decoded, ctxs);
544 }
545
546 #[test]
547 fn create_context_chain_rejects_malformed_entries() {
548 let short_name = vec![CreateContext {
549 name: b"MxA".to_vec(),
550 data: vec![],
551 }];
552 let mut buf = Vec::new();
553 CreateContext::encode_chain(&short_name, &mut buf).unwrap();
554 assert!(CreateContext::parse_chain(&buf).is_err());
555
556 let pair = vec![
557 CreateContext {
558 name: b"QFid".to_vec(),
559 data: vec![],
560 },
561 CreateContext {
562 name: b"MxAc".to_vec(),
563 data: vec![0; 8],
564 },
565 ];
566 let mut chain = Vec::new();
567 CreateContext::encode_chain(&pair, &mut chain).unwrap();
568 let next = u32::from_le_bytes(chain[0..4].try_into().unwrap());
569 let mut bad = chain.clone();
571 bad[10..12].copy_from_slice(&16u16.to_le_bytes());
572 bad[12..16].copy_from_slice(&next.to_le_bytes());
573 assert!(CreateContext::parse_chain(&bad).is_err());
574 for next in [8u32, chain.len() as u32 + 8] {
576 let mut bad = chain.clone();
577 bad[0..4].copy_from_slice(&next.to_le_bytes());
578 assert!(CreateContext::parse_chain(&bad).is_err(), "next {next}");
579 }
580 }
581
582 #[test]
583 fn empty_chain_round_trips() {
584 let ctxs: Vec<CreateContext> = vec![];
585 let mut buf = Vec::new();
586 CreateContext::encode_chain(&ctxs, &mut buf).unwrap();
587 assert!(buf.is_empty());
588 let decoded = CreateContext::parse_chain(&buf).unwrap();
589 assert!(decoded.is_empty());
590 }
591}