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